diff --git a/plugins/adblock/adblockdialog.cpp b/plugins/adblock/adblockdialog.cpp index 74e771137..206265f46 100644 --- a/plugins/adblock/adblockdialog.cpp +++ b/plugins/adblock/adblockdialog.cpp @@ -1,329 +1,329 @@ /* Copyright (c) 2008 Laurent Montel Copyright (C) 2006 Daniele Galdi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "adblockdialog.h" #include "adblock.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // ---------------------------------------------------------------------------- class ListViewItem : public QTreeWidgetItem { public: ListViewItem(QTreeWidget *listView, const QStringList &lst, const AdElement *element) : QTreeWidgetItem(listView, lst), m_element(element), m_blocked(false) {}; bool isBlocked() const { return (m_blocked); }; void setBlocked(bool blocked); void setBlockedBy(const QString &reason); void setNode(const DOM::Node &node); DOM::Node node()const { return (m_node); } const AdElement *element() const { return (m_element); } private: const AdElement *m_element; bool m_blocked; DOM::Node m_node; }; void ListViewItem::setBlocked(bool blocked) { m_blocked = blocked; - setData(0, Qt::TextColorRole, (blocked ? Qt::red : Qt::black)); + setData(0, Qt::ForegroundRole, (blocked ? Qt::red : Qt::black)); QFont itemFont = font(0); itemFont.setItalic(blocked); itemFont.setBold(blocked); setData(0, Qt::FontRole, itemFont); } void ListViewItem::setBlockedBy(const QString &reason) { setToolTip(0, reason); } void ListViewItem::setNode(const DOM::Node &node) { m_node = node; } // ---------------------------------------------------------------------------- AdBlockDlg::AdBlockDlg(QWidget *parent, const AdElementList *elements, KHTMLPart *part) : KDialog(parent), m_part(part) { setModal(true); setCaption(i18nc("@title:window", "Blockable items on this page")); setButtons(KDialog::User1 | KDialog::User2 | KDialog::Close); setDefaultButton(KDialog::User2); setButtonText(KDialog::User1, i18n("Configure Filters...")); setButtonIcon(KDialog::User1, KIcon("preferences-web-browser-adblock")); setButtonText(KDialog::User2, i18n("Add filter")); setButtonIcon(KDialog::User2, KStandardGuiItem::add().icon()); QWidget *page = new QWidget(this); setMainWidget(page); QVBoxLayout *layout = new QVBoxLayout(page); - layout->setMargin(0); + layout->setContentsMargins(0, 0, 0, 0); QLabel *l = new QLabel(i18n("Search:"), page); layout->addWidget(l); KTreeWidgetSearchLine *searchLine = new KTreeWidgetSearchLine(page); layout->addWidget(searchLine); l->setBuddy(searchLine); l = new QLabel(i18n("Blockable items:"), page); layout->addWidget(l); m_list = new QTreeWidget(page); m_list->setAllColumnsShowFocus(true); layout->addWidget(m_list); l->setBuddy(m_list); QStringList lstHeader; lstHeader << i18n("Source") << i18n("Category") << i18n("Tag"); m_list->setHeaderLabels(lstHeader); m_list->setColumnWidth(0, 600); m_list->setColumnWidth(1, 90); m_list->setColumnWidth(2, 65); m_list->setRootIsDecorated(false); AdElementList::const_iterator it; for (it = elements->constBegin(); it != elements->constEnd(); ++it) { const AdElement &element = (*it); QStringList lst; lst << element.url() << element.category() << element.type(); ListViewItem *item = new ListViewItem(m_list, lst, &element); item->setBlocked(element.isBlocked()); item->setBlockedBy(element.blockedBy()); item->setNode(element.node()); } searchLine->setTreeWidget(m_list); layout->addSpacing(KDialog::spacingHint()); l = new QLabel(i18n("New filter (can use *?[] wildcards, /RE/ for regular expression, prefix with @@ for white list):"), page); layout->addWidget(l); m_filter = new QLineEdit(page); layout->addWidget(m_filter); connect(m_filter, SIGNAL(textChanged(QString)), SLOT(filterTextChanged(QString))); l->setBuddy(m_filter); filterTextChanged(QString::null); connect(this, SIGNAL(user1Clicked()), this, SLOT(slotConfigureFilters())); connect(this, SIGNAL(user2Clicked()), this, SLOT(slotAddFilter())); // Use itemActivated() signal instead of itemDoubleClicked() to honour // the KDE single/double click setting, and allow keyboard navigation. // Activating a item just copies its URL to the "new filter" box and // sets focus to there, it doesn't add the filter immediately. //connect(m_list, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(updateFilter(QTreeWidgetItem*)) ); connect(m_list, SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(updateFilter(QTreeWidgetItem*))); m_menu = new KMenu(this); m_menu->addAction(i18n("Filter this item"), this, SLOT(filterItem())); m_menu->addAction(i18n("Filter all items at same path"), this, SLOT(filterPath())); m_menu->addAction(i18n("Filter all items from same host"), this, SLOT(filterHost())); m_menu->addAction(i18n("Filter all items from same domain"), this, SLOT(filterDomain())); m_menu->addSeparator(); m_menu->addAction(i18n("Add this item to white list"), this, SLOT(addWhiteList())); m_menu->addSeparator(); m_menu->addAction(i18n("Copy Link Address"), this, SLOT(copyLinkAddress())); //comment for the moment //m_menu->addAction( i18n( "Highlight Element" ), this, SLOT(highLightElement()) ); m_menu->addAction(i18n("View item"), this, SLOT(showElement())); m_list->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_list, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); resize(800, 400); } AdBlockDlg::~AdBlockDlg() { } void AdBlockDlg::filterTextChanged(const QString &text) { enableButton(KDialog::User2, !text.isEmpty()); } void AdBlockDlg::setFilterText(const QString &text) { m_filter->setText(text); m_filter->setFocus(Qt::OtherFocusReason); } void AdBlockDlg::updateFilter(QTreeWidgetItem *selected) { ListViewItem *item = static_cast(selected); if (item->isBlocked()) { m_filter->clear(); return; } setFilterText(item->text(0)); } void AdBlockDlg::slotAddFilter() { const QString text = m_filter->text().trimmed(); if (text.isEmpty()) { return; } kDebug() << "adding filter" << text; emit notEmptyFilter(text); for (QTreeWidgetItemIterator it(m_list); (*it) != 0; ++it) { ListViewItem *item = static_cast(*it); item->setBlocked(item->element()->isBlocked()); item->setBlockedBy(item->element()->blockedBy()); } enableButton(KDialog::User2, false); // now that filter has been added } // until it is changed again void AdBlockDlg::slotConfigureFilters() { emit configureFilters(); delayedDestruct(); } void AdBlockDlg::showContextMenu(const QPoint &pos) { QPoint newPos = m_list->viewport()->mapToGlobal(pos); int column = m_list->columnAt(pos.x()); if (column == -1) { return; } m_menu->popup(newPos); } void AdBlockDlg::filterItem() { QTreeWidgetItem *item = m_list->currentItem(); setFilterText(item->text(0)); } KUrl AdBlockDlg::getItem() { QTreeWidgetItem *item = m_list->currentItem(); KUrl u(item->text(0)); u.setQuery(QString()); u.setRef(QString()); return (u); } void AdBlockDlg::filterPath() { KUrl u(getItem()); u.setFileName("*"); setFilterText(u.url()); } void AdBlockDlg::filterHost() { KUrl u(getItem()); u.setPath("/*"); setFilterText(u.url()); } void AdBlockDlg::filterDomain() { KUrl u(getItem()); QString host = u.host(); if (host.isEmpty()) { return; } int idx = host.indexOf('.'); if (idx < 0) { return; } QString t = u.protocol() + "://*" + host.mid(idx) + "/*"; setFilterText(t); } void AdBlockDlg::addWhiteList() { QTreeWidgetItem *item = m_list->currentItem(); setFilterText("@@" + item->text(0)); } void AdBlockDlg::copyLinkAddress() { QApplication::clipboard()->setText(m_list->currentItem()->text(0)); } void AdBlockDlg::highLightElement() { ListViewItem *item = static_cast(m_list->currentItem()); if (item) { DOM::Node handle = item->node(); kDebug() << " m_part :" << m_part; if (!handle.isNull()) { m_part->setActiveNode(handle); } } } void AdBlockDlg::showElement() { new KRun(m_list->currentItem()->text(0), 0); } diff --git a/plugins/dirfilter/dirfilterplugin.cpp b/plugins/dirfilter/dirfilterplugin.cpp index daf247e4c..ca6dd66dc 100644 --- a/plugins/dirfilter/dirfilterplugin.cpp +++ b/plugins/dirfilter/dirfilterplugin.cpp @@ -1,550 +1,550 @@ /* Copyright (C) 2000-2011 Dawit Alemayehu This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "dirfilterplugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Q_GLOBAL_STATIC(SessionManager, globalSessionManager) static void generateKey(const QUrl &url, QString *key) { if (url.isValid()) { *key = url.scheme(); *key += QLatin1Char(':'); if (!url.host().isEmpty()) { *key += url.host(); *key += QLatin1Char(':'); } if (!url.path().isEmpty()) { *key += url.path(); } } } static void saveNameFilter(const QUrl &url, const QString &filter) { SessionManager::Filters f = globalSessionManager->restore(url); f.nameFilter = filter; globalSessionManager->save(url, f); } static void saveTypeFilters(const QUrl &url, const QStringList &filters) { SessionManager::Filters f = globalSessionManager->restore(url); f.typeFilters = filters; globalSessionManager->save(url, f); } SessionManager::SessionManager() { m_bSettingsLoaded = false; loadSettings(); } SessionManager::~SessionManager() { saveSettings(); } SessionManager::Filters SessionManager::restore(const QUrl &url) { QString key; generateKey(url, &key); return m_filters.value(key); } void SessionManager::save(const QUrl &url, const Filters &filters) { QString key; generateKey(url, &key); m_filters[key] = filters; } void SessionManager::saveSettings() { KConfig cfg(QStringLiteral("dirfilterrc"), KConfig::NoGlobals); KConfigGroup group = cfg.group("General"); group.writeEntry("ShowCount", showCount); group.writeEntry("UseMultipleFilters", useMultipleFilters); cfg.sync(); } void SessionManager::loadSettings() { if (m_bSettingsLoaded) { return; } KConfig cfg(QStringLiteral("dirfilterrc"), KConfig::NoGlobals); KConfigGroup group = cfg.group("General"); showCount = group.readEntry("ShowCount", false); useMultipleFilters = group.readEntry("UseMultipleFilters", true); m_bSettingsLoaded = true; } FilterBar::FilterBar(QWidget *parent) : QWidget(parent) { // Create close button QToolButton *closeButton = new QToolButton(this); closeButton->setAutoRaise(true); closeButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close"))); closeButton->setToolTip(i18nc("@info:tooltip", "Hide Filter Bar")); connect(closeButton, SIGNAL(clicked()), this, SIGNAL(closeRequest())); // Create label QLabel *filterLabel = new QLabel(i18nc("@label:textbox", "F&ilter:"), this); // Create filter editor m_filterInput = new KLineEdit(this); m_filterInput->setLayoutDirection(Qt::LeftToRight); m_filterInput->setClearButtonShown(true); connect(m_filterInput, SIGNAL(textChanged(QString)), this, SIGNAL(filterChanged(QString))); setFocusProxy(m_filterInput); m_typeFilterButton = new QPushButton(this); m_typeFilterButton->setIcon(QIcon::fromTheme(QStringLiteral("view-filter"))); m_typeFilterButton->setText(i18nc("@label:button", "Filter by t&ype")); m_typeFilterButton->setToolTip(i18nc("@info:tooltip", "Filter items by file type.")); // Apply layout QHBoxLayout *layout = new QHBoxLayout(this); - layout->setMargin(0); + layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(closeButton); layout->addWidget(filterLabel); layout->addWidget(m_filterInput); layout->addWidget(m_typeFilterButton); layout->addItem(new QSpacerItem(20, 20, QSizePolicy::MinimumExpanding, QSizePolicy::Minimum)); filterLabel->setBuddy(m_filterInput); } FilterBar::~FilterBar() { } void FilterBar::selectAll() { m_filterInput->selectAll(); } bool FilterBar::typeFilterMenuEnabled() const { return m_typeFilterButton->isEnabled(); } void FilterBar::setEnableTypeFilterMenu(bool state) { m_typeFilterButton->setEnabled(state); } void FilterBar::setTypeFilterMenu(QMenu *menu) { m_typeFilterButton->setMenu(menu); } QMenu *FilterBar::typeFilterMenu() { return m_typeFilterButton->menu(); } void FilterBar::setNameFilter(const QString &text) { m_filterInput->setText(text); } void FilterBar::clear() { m_filterInput->clear(); } void FilterBar::showEvent(QShowEvent *event) { if (!event->spontaneous()) { m_filterInput->setFocus(); } } void FilterBar::keyReleaseEvent(QKeyEvent *event) { QWidget::keyReleaseEvent(event); if (event->key() == Qt::Key_Escape) { if (m_filterInput->text().isEmpty()) { emit closeRequest(); } else { m_filterInput->clear(); } } } DirFilterPlugin::DirFilterPlugin(QObject *parent, const QVariantList &) : KParts::Plugin(parent) , m_filterBar(nullptr) , m_focusWidget(nullptr) { m_part = qobject_cast(parent); if (m_part) { connect(m_part, SIGNAL(aboutToOpenURL()), this, SLOT(slotOpenURL())); //connect(m_part, SIGNAL(completed()), this, SLOT(slotOpenURLCompleted())); connect(m_part, SIGNAL(completed(bool)), this, SLOT(slotOpenURLCompleted())); } KParts::ListingNotificationExtension *notifyExt = KParts::ListingNotificationExtension::childObject(m_part); if (notifyExt && notifyExt->supportedNotificationEventTypes() != KParts::ListingNotificationExtension::None) { m_listingExt = KParts::ListingFilterExtension::childObject(m_part); connect(notifyExt, SIGNAL(listingEvent(KParts::ListingNotificationExtension::NotificationEventType,KFileItemList)), this, SLOT(slotListingEvent(KParts::ListingNotificationExtension::NotificationEventType,KFileItemList))); QAction *action = actionCollection()->addAction(QStringLiteral("filterdir"), this, SLOT(slotShowFilterBar())); action->setText(i18nc("@action:inmenu Tools", "Show Filter Bar")); action->setIcon(QIcon::fromTheme(QStringLiteral("view-filter"))); actionCollection()->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I)); } } DirFilterPlugin::~DirFilterPlugin() { } void DirFilterPlugin::slotOpenURL() { if (m_part && !m_part->arguments().reload()) { m_pMimeInfo.clear(); if (m_filterBar && m_filterBar->isVisible()) { m_filterBar->clear(); m_filterBar->setEnableTypeFilterMenu(false); // Will be enabled once loading has completed } } } void DirFilterPlugin::slotOpenURLCompleted() { if (m_listingExt && m_part && m_filterBar && m_filterBar->isVisible()) { setFilterBar(); } } void DirFilterPlugin::slotShowPopup() { QMenu *filterMenu = (m_filterBar ? m_filterBar->typeFilterMenu() : nullptr); if (!filterMenu) { return; } filterMenu->clear(); QString label; QStringList inodes; quint64 enableReset = 0; QMapIterator it(m_pMimeInfo); while (it.hasNext()) { it.next(); if (it.key().startsWith(QLatin1String("inode"))) { inodes << it.key(); continue; } if (!globalSessionManager->showCount) { label = it.value().mimeComment; } else { label = it.value().mimeComment; label += QLatin1String(" ("); label += QString::number(it.value().filenames.size()); label += ')'; } QAction *action = filterMenu->addAction(QIcon::fromTheme(it.value().iconName), label); action->setCheckable(true); if (it.value().useAsFilter) { action->setChecked(true); enableReset++; } action->setData(it.key()); m_pMimeInfo[it.key()].action = action; } // Add all the items that have mime-type of "inode/*" here... if (!inodes.isEmpty()) { filterMenu->addSeparator(); Q_FOREACH (const QString &inode, inodes) { if (!globalSessionManager->showCount) { label = m_pMimeInfo[inode].mimeComment; } else { label = m_pMimeInfo[inode].mimeComment; label += QLatin1String(" ("); label += QString::number(m_pMimeInfo[inode].filenames.size()); label += ')'; } QAction *action = filterMenu->addAction(QIcon::fromTheme(m_pMimeInfo[inode].iconName), label); action->setCheckable(true); if (m_pMimeInfo[inode].useAsFilter) { action->setChecked(true); enableReset ++; } action->setData(inode); m_pMimeInfo[inode].action = action; } } filterMenu->addSeparator(); QAction *action = filterMenu->addAction(i18n("Use Multiple Filters"), this, SLOT(slotMultipleFilters())); action->setEnabled(enableReset <= 1); action->setCheckable(true); action->setChecked(globalSessionManager->useMultipleFilters); action = filterMenu->addAction(i18n("Show Count"), this, SLOT(slotShowCount())); action->setCheckable(true); action->setChecked(globalSessionManager->showCount); action = filterMenu->addAction(i18n("Reset"), this, SLOT(slotReset())); action->setEnabled(enableReset); } void DirFilterPlugin::slotItemSelected(QAction *action) { if (!m_listingExt || !action || !m_part) { return; } MimeInfoMap::iterator it = m_pMimeInfo.find(action->data().toString()); if (it != m_pMimeInfo.end()) { MimeInfo &mimeInfo = it.value(); QStringList filters; if (mimeInfo.useAsFilter) { mimeInfo.useAsFilter = false; filters = m_listingExt->filter(KParts::ListingFilterExtension::MimeType).toStringList(); if (filters.removeAll(it.key())) { m_listingExt->setFilter(KParts::ListingFilterExtension::MimeType, filters); } } else { m_pMimeInfo[it.key()].useAsFilter = true; if (globalSessionManager->useMultipleFilters) { filters = m_listingExt->filter(KParts::ListingFilterExtension::MimeType).toStringList(); filters << it.key(); } else { filters << it.key(); MimeInfoMap::iterator item = m_pMimeInfo.begin(); MimeInfoMap::iterator itemEnd = m_pMimeInfo.end(); while (item != itemEnd) { if (item != it) { item.value().useAsFilter = false; } item++; } } m_listingExt->setFilter(KParts::ListingFilterExtension::MimeType, filters); } saveTypeFilters(m_part->url(), filters); } } void DirFilterPlugin::slotNameFilterChanged(const QString &filter) { if (!m_listingExt || !m_part) { return; } m_listingExt->setFilter(KParts::ListingFilterExtension::SubString, filter); saveNameFilter(m_part->url(), filter); } void DirFilterPlugin::slotCloseRequest() { if (m_filterBar) { m_filterBar->clear(); m_filterBar->hide(); if (m_focusWidget) { m_focusWidget->setFocus(); m_focusWidget = nullptr; } } } void DirFilterPlugin::slotListingEvent(KParts::ListingNotificationExtension::NotificationEventType type, const KFileItemList &items) { if (!m_listingExt) { return; } switch (type) { case KParts::ListingNotificationExtension::ItemsAdded: { const QStringList filters = m_listingExt->filter(KParts::ListingFilterExtension::MimeType).toStringList(); Q_FOREACH (const KFileItem &item, items) { const QString mimeType(item.mimetype()); if (m_pMimeInfo.contains(mimeType)) { m_pMimeInfo[mimeType].filenames.insert(item.name()); } else { MimeInfo &mimeInfo = m_pMimeInfo[mimeType]; mimeInfo.useAsFilter = filters.contains(mimeType); mimeInfo.mimeComment = item.mimeComment(); mimeInfo.iconName = item.iconName(); mimeInfo.filenames.insert(item.name()); } } break; } case KParts::ListingNotificationExtension::ItemsDeleted: Q_FOREACH (const KFileItem &item, items) { const QString mimeType(item.mimetype()); MimeInfoMap::iterator it = m_pMimeInfo.find(mimeType); if (it != m_pMimeInfo.end()) { MimeInfo &info = it.value(); if (info.filenames.size() > 1) { info.filenames.remove(item.name()); } else { if (info.useAsFilter) { QStringList filters = m_listingExt->filter(KParts::ListingFilterExtension::MimeType).toStringList(); filters.removeAll(mimeType); m_listingExt->setFilter(KParts::ListingFilterExtension::MimeType, filters); saveTypeFilters(m_part->url(), filters); } m_pMimeInfo.erase(it); } } } break; default: return; } // Enable/disable mime based filtering depending on whether the number // document types in the current directory. if (m_filterBar) { m_filterBar->setEnableTypeFilterMenu(m_pMimeInfo.count() > 1); } } void DirFilterPlugin::slotReset() { if (!m_part || !m_listingExt) { return; } MimeInfoMap::iterator itEnd = m_pMimeInfo.end(); for (MimeInfoMap::iterator it = m_pMimeInfo.begin(); it != itEnd; ++it) { it.value().useAsFilter = false; } const QStringList filters; m_listingExt->setFilter(KParts::ListingFilterExtension::MimeType, filters); saveTypeFilters(m_part->url(), filters); } void DirFilterPlugin::slotShowCount() { globalSessionManager->showCount = !globalSessionManager->showCount; } void DirFilterPlugin::slotMultipleFilters() { globalSessionManager->useMultipleFilters = !globalSessionManager->useMultipleFilters; } void DirFilterPlugin::slotShowFilterBar() { QWidget *partWidget = (m_part ? m_part->widget() : nullptr); if (!m_filterBar && partWidget) { m_filterBar = new FilterBar(partWidget); m_filterBar->setTypeFilterMenu(new QMenu(m_filterBar)); connect(m_filterBar->typeFilterMenu(), SIGNAL(aboutToShow()), this, SLOT(slotShowPopup())); connect(m_filterBar->typeFilterMenu(), SIGNAL(triggered(QAction*)), this, SLOT(slotItemSelected(QAction*))); connect(m_filterBar, SIGNAL(filterChanged(QString)), this, SLOT(slotNameFilterChanged(QString))); connect(m_filterBar, SIGNAL(closeRequest()), this, SLOT(slotCloseRequest())); QBoxLayout *layout = qobject_cast(partWidget->layout()); if (layout) { layout->addWidget(m_filterBar); } } // Get the widget that currently has the focus so we can properly // restore it when the filter bar is closed. QWidget *window = (partWidget ? partWidget->window() : nullptr); m_focusWidget = (window ? window->focusWidget() : nullptr); if (m_filterBar) { setFilterBar(); m_filterBar->show(); } } void DirFilterPlugin::setFilterBar() { SessionManager::Filters savedFilters = globalSessionManager->restore(m_part->url()); if (m_listingExt) { m_listingExt->setFilter(KParts::ListingFilterExtension::MimeType, savedFilters.typeFilters); } if (m_filterBar) { m_filterBar->setNameFilter(savedFilters.nameFilter); m_filterBar->setEnableTypeFilterMenu(m_pMimeInfo.count() > 1); } Q_FOREACH (const QString &mimeType, savedFilters.typeFilters) { if (m_pMimeInfo.contains(mimeType)) { m_pMimeInfo[mimeType].useAsFilter = true; } } } K_PLUGIN_FACTORY(DirFilterFactory, registerPlugin();) #include "dirfilterplugin.moc" diff --git a/plugins/kimgalleryplugin/imgallerydialog.cpp b/plugins/kimgalleryplugin/imgallerydialog.cpp index 13282f07c..8b5611ee7 100644 --- a/plugins/kimgalleryplugin/imgallerydialog.cpp +++ b/plugins/kimgalleryplugin/imgallerydialog.cpp @@ -1,482 +1,482 @@ /* This file is part of the KDE project Copyright (C) 2001, 2003 Lukas Tinkl Andreas Schlapbach This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "imgallerydialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include KIGPDialog::KIGPDialog(QWidget *parent, const QString &path) : KPageDialog(parent) { setStandardButtons(QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Ok | QDialogButtonBox::Cancel); buttonBox()->button(QDialogButtonBox::Ok)->setDefault(true); setModal(true); setFaceType(List); m_path = path; setWindowTitle(i18nc("@title:window", "Create Image Gallery")); KGuiItem::assign(buttonBox()->button(QDialogButtonBox::Ok), KGuiItem(i18n("Create"), QStringLiteral("imagegallery"))); m_config = new KConfig(QStringLiteral("kimgallerypluginrc"), KConfig::NoGlobals); setupLookPage(path); setupDirectoryPage(path); setupThumbnailPage(path); connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), this, SLOT(slotDefault())); } void KIGPDialog::slotDefault() { m_title->setText(i18n("Image Gallery for %1", m_path)); m_imagesPerRow->setValue(4); m_imageName->setChecked(true); m_imageSize->setChecked(false); m_imageProperty->setChecked(false); m_fontName->setItemText(m_fontName->currentIndex(), QFontDatabase::systemFont(QFontDatabase::GeneralFont).family()); m_fontSize->setValue(14); m_foregroundColor->setColor(QColor(QStringLiteral("#d0ffd0"))); m_backgroundColor->setColor(QColor(QStringLiteral("#333333"))); m_imageNameReq->setUrl(QUrl::fromLocalFile(m_path + "images.html")); m_recurseSubDir->setChecked(false); m_recursionLevel->setEnabled(false); m_recursionLevel->setValue(0); m_copyOriginalFiles->setChecked(false); m_useCommentFile->setChecked(false); m_commentFileReq->setUrl(QUrl::fromLocalFile(m_path + "comments")); m_commentFileReq->setEnabled(false); m_imageFormat->setItemText(m_imageFormat->currentIndex(), QStringLiteral("JPEG")); m_thumbnailSize->setValue(140); m_colorDepthSet->setChecked(false); m_colorDepth->setItemText(m_colorDepth->currentIndex(), QStringLiteral("8")); } void KIGPDialog::setupLookPage(const QString &path) { QFrame *page = new QFrame(); KPageWidgetItem *pageItem = new KPageWidgetItem(page, i18n("Look")); pageItem->setHeader(i18n("Page Look")); pageItem->setIcon(QIcon::fromTheme("fill-color")); addPage(pageItem); KConfigGroup look = m_config->group("Look"); QVBoxLayout *vlay = new QVBoxLayout(page); - vlay->setMargin(0); + vlay->setContentsMargins(0, 0, 0, 0); QLabel *label = new QLabel(i18n("&Page title:"), page); vlay->addWidget(label); m_title = new QLineEdit(i18n("Image Gallery for %1", path), page); vlay->addWidget(m_title); label->setBuddy(m_title); m_imagesPerRow = new KIntNumInput(look.readEntry("ImagesPerRow", 4), page); m_imagesPerRow->setRange(1, 8, 1); m_imagesPerRow->setSliderEnabled(true); m_imagesPerRow->setLabel(i18n("I&mages per row:")); vlay->addWidget(m_imagesPerRow); QGridLayout *grid = new QGridLayout(); grid->setMargin(2); grid->setSpacing(2); vlay->addLayout(grid); m_imageName = new QCheckBox(i18n("Show image file &name"), page); m_imageName->setChecked(look.readEntry("ImageName", true)); grid->addWidget(m_imageName, 0, 0); m_imageSize = new QCheckBox(i18n("Show image file &size"), page); m_imageSize->setChecked(look.readEntry("ImageSize", false)); grid->addWidget(m_imageSize, 0, 1); m_imageProperty = new QCheckBox(i18n("Show image &dimensions"), page); m_imageProperty->setChecked(look.readEntry("ImageProperty", false)); grid->addWidget(m_imageProperty, 1, 0); QHBoxLayout *hlay11 = new QHBoxLayout(); vlay->addLayout(hlay11); m_fontName = new QComboBox(page); QStringList standardFonts; KFontChooser::getFontList(standardFonts, 0); m_fontName->addItems(standardFonts); m_fontName->setItemText(m_fontName->currentIndex(), look.readEntry("FontName", QFontDatabase::systemFont(QFontDatabase::GeneralFont).family())); label = new QLabel(i18n("Fon&t name:"), page); label->setBuddy(m_fontName); hlay11->addWidget(label); hlay11->addStretch(1); hlay11->addWidget(m_fontName); QHBoxLayout *hlay12 = new QHBoxLayout(); vlay->addLayout(hlay12); m_fontSize = new QSpinBox(page); m_fontSize->setMinimum(6); m_fontSize->setMaximum(15); m_fontSize->setSingleStep(1); m_fontSize->setValue(look.readEntry("FontSize", 14)); label = new QLabel(i18n("Font si&ze:"), page); label->setBuddy(m_fontSize); hlay12->addWidget(label); hlay12->addStretch(1); hlay12->addWidget(m_fontSize); QHBoxLayout *hlay1 = new QHBoxLayout(); vlay->addLayout(hlay1); m_foregroundColor = new KColorButton(page); m_foregroundColor->setColor(QColor(look.readEntry("ForegroundColor", "#d0ffd0"))); label = new QLabel(i18n("&Foreground color:"), page); label->setBuddy(m_foregroundColor); hlay1->addWidget(label); hlay1->addStretch(1); hlay1->addWidget(m_foregroundColor); QHBoxLayout *hlay2 = new QHBoxLayout(); vlay->addLayout(hlay2); m_backgroundColor = new KColorButton(page); m_backgroundColor->setColor(QColor(look.readEntry("BackgroundColor", "#333333"))); label = new QLabel(i18n("&Background color:"), page); hlay2->addWidget(label); label->setBuddy(m_backgroundColor); hlay2->addStretch(1); hlay2->addWidget(m_backgroundColor); vlay->addStretch(1); } void KIGPDialog::setupDirectoryPage(const QString &path) { QFrame *page = new QFrame(); KPageWidgetItem *pageItem = new KPageWidgetItem(page, i18n("Folders")); pageItem->setHeader(i18n("Folders")); pageItem->setIcon(QIcon::fromTheme("folder")); addPage(pageItem); KConfigGroup group = m_config->group("Directory"); QVBoxLayout *dvlay = new QVBoxLayout(page); - dvlay->setMargin(0); + dvlay->setContentsMargins(0, 0, 0, 0); QLabel *label; label = new QLabel(i18n("&Save to HTML file:"), page); dvlay->addWidget(label); QString whatsThis; whatsThis = i18n("

The name of the HTML file this gallery will be saved to.

"); label->setWhatsThis(whatsThis); m_imageNameReq = new KUrlRequester(QUrl::fromLocalFile(QString(path + "images.html")), page); label->setBuddy(m_imageNameReq); dvlay->addWidget(m_imageNameReq); connect(m_imageNameReq, SIGNAL(textChanged(QString)), this, SLOT(imageUrlChanged(QString))); m_imageNameReq->setWhatsThis(whatsThis); const bool recurseSubDir = group.readEntry("RecurseSubDirectories", false); m_recurseSubDir = new QCheckBox(i18n("&Recurse subfolders"), page); m_recurseSubDir->setChecked(recurseSubDir); whatsThis = i18n("

Whether subfolders should be included for the " "image gallery creation or not.

"); m_recurseSubDir->setWhatsThis(whatsThis); const int recursionLevel = group.readEntry("RecursionLevel", 0); m_recursionLevel = new KIntNumInput(recursionLevel, page); m_recursionLevel->setRange(0, 99, 1); m_recursionLevel->setSliderEnabled(true); m_recursionLevel->setLabel(i18n("Rec&ursion depth:")); if (recursionLevel == 0) { m_recursionLevel->setSpecialValueText(i18n("Endless")); } m_recursionLevel->setEnabled(recurseSubDir); whatsThis = i18n("

You can limit the number of folders the " "image gallery creator will traverse to by setting an " "upper bound for the recursion depth.

"); m_recursionLevel->setWhatsThis(whatsThis); connect(m_recurseSubDir, SIGNAL(toggled(bool)), m_recursionLevel, SLOT(setEnabled(bool))); dvlay->addWidget(m_recurseSubDir); dvlay->addWidget(m_recursionLevel); m_copyOriginalFiles = new QCheckBox(i18n("Copy or&iginal files"), page); m_copyOriginalFiles->setChecked(group.readEntry("CopyOriginalFiles", false)); dvlay->addWidget(m_copyOriginalFiles); whatsThis = i18n("

This makes a copy of all images and the gallery will refer " "to these copies instead of the original images.

"); m_copyOriginalFiles->setWhatsThis(whatsThis); const bool useCommentFile = group.readEntry("UseCommentFile", false); m_useCommentFile = new QCheckBox(i18n("Use &comment file"), page); m_useCommentFile->setChecked(useCommentFile); dvlay->addWidget(m_useCommentFile); whatsThis = i18n("

If you enable this option you can specify " "a comment file which will be used for generating " "subtitles for the images.

" "

For details about the file format please see " "the \"What's This?\" help below.

"); m_useCommentFile->setWhatsThis(whatsThis); label = new QLabel(i18n("Comments &file:"), page); label->setEnabled(useCommentFile); dvlay->addWidget(label); whatsThis = i18n("

You can specify the name of the comment file here. " "The comment file contains the subtitles for the images. " "The format of this file is:

" "

FILENAME1:" "
Description" "
" "
FILENAME2:" "
Description" "
" "
and so on

"); label->setWhatsThis(whatsThis); m_commentFileReq = new KUrlRequester(QUrl::fromLocalFile(QString(path + "comments")), page); m_commentFileReq->setEnabled(useCommentFile); label->setBuddy(m_commentFileReq); dvlay->addWidget(m_commentFileReq); m_commentFileReq->setWhatsThis(whatsThis); connect(m_useCommentFile, SIGNAL(toggled(bool)), label, SLOT(setEnabled(bool))); connect(m_useCommentFile, SIGNAL(toggled(bool)), m_commentFileReq, SLOT(setEnabled(bool))); dvlay->addStretch(1); } void KIGPDialog::setupThumbnailPage(const QString &path) { Q_UNUSED(path); QFrame *page = new QFrame(); KPageWidgetItem *pageItem = new KPageWidgetItem(page, i18n("Thumbnails")); pageItem->setHeader(i18n("Thumbnails")); pageItem->setIcon(QIcon::fromTheme("view-preview")); addPage(pageItem); KConfigGroup group = m_config->group("Thumbnails"); QLabel *label; QVBoxLayout *vlay = new QVBoxLayout(page); - vlay->setMargin(0); + vlay->setContentsMargins(0, 0, 0, 0); QHBoxLayout *hlay3 = new QHBoxLayout(); vlay->addLayout(hlay3); m_imageFormat = new QComboBox(page); QStringList lstImgageFormat; lstImgageFormat << QStringLiteral("JPEG") << QStringLiteral("PNG"); m_imageFormat->addItems(lstImgageFormat); m_imageFormat->setItemText(m_imageFormat->currentIndex(), group.readEntry("ImageFormat", "JPEG")); label = new QLabel(i18n("Image format f&or the thumbnails:"), page); hlay3->addWidget(label); label->setBuddy(m_imageFormat); hlay3->addStretch(1); hlay3->addWidget(m_imageFormat); m_thumbnailSize = new KIntNumInput(group.readEntry("ThumbnailSize", 140), page); m_thumbnailSize->setRange(10, 1000, 1); m_thumbnailSize->setLabel(i18n("Thumbnail size:")); m_thumbnailSize->setSliderEnabled(true); vlay->addWidget(m_thumbnailSize); QGridLayout *grid = new QGridLayout(); grid->setMargin(2); grid->setSpacing(2); vlay->addLayout(grid); QHBoxLayout *hlay4 = new QHBoxLayout(); vlay->addLayout(hlay4); const bool colorDepthSet = group.readEntry("ColorDepthSet", false); m_colorDepthSet = new QCheckBox(i18n("&Set different color depth:"), page); m_colorDepthSet->setChecked(colorDepthSet); hlay4->addWidget(m_colorDepthSet); m_colorDepth = new QComboBox(page); QStringList lst; lst << QStringLiteral("1") << QStringLiteral("8") << QStringLiteral("16") << QStringLiteral("32"); m_colorDepth->addItems(lst); m_colorDepth->setItemText(m_colorDepth->currentIndex(), group.readEntry("ColorDepth", "8")); m_colorDepth->setEnabled(colorDepthSet); hlay4->addWidget(m_colorDepth); connect(m_colorDepthSet, SIGNAL(toggled(bool)), m_colorDepth, SLOT(setEnabled(bool))); vlay->addStretch(1); } void KIGPDialog::writeConfig() { KConfigGroup group = m_config->group("Look"); group.writeEntry("ImagesPerRow", getImagesPerRow()); group.writeEntry("ImageName", printImageName()); group.writeEntry("ImageSize", printImageSize()); group.writeEntry("ImageProperty", printImageProperty()); group.writeEntry("FontName", getFontName()); group.writeEntry("FontSize", getFontSize()); group.writeEntry("ForegroundColor", getForegroundColor().name()); group.writeEntry("BackgroundColor", getBackgroundColor().name()); group = m_config->group("Directory"); group.writeEntry("RecurseSubDirectories", recurseSubDirectories()); group.writeEntry("RecursionLevel", recursionLevel()); group.writeEntry("CopyOriginalFiles", copyOriginalFiles()); group.writeEntry("UseCommentFile", useCommentFile()); group = m_config->group("Thumbnails"); group.writeEntry("ThumbnailSize", getThumbnailSize()); group.writeEntry("ColorDepth", getColorDepth()); group.writeEntry("ColorDepthSet", colorDepthSet()); group.writeEntry("ImageFormat", getImageFormat()); group.sync(); } KIGPDialog::~KIGPDialog() { delete m_config; } void KIGPDialog::imageUrlChanged(const QString &url) { buttonBox()->button(QDialogButtonBox::Ok)->setEnabled(!url.isEmpty()); } bool KIGPDialog::printImageName() const { return m_imageName->isChecked(); } bool KIGPDialog::printImageSize() const { return m_imageSize->isChecked(); } bool KIGPDialog::printImageProperty() const { return m_imageProperty->isChecked(); } bool KIGPDialog::recurseSubDirectories() const { return m_recurseSubDir->isChecked(); } int KIGPDialog::recursionLevel() const { return m_recursionLevel->value(); } bool KIGPDialog::copyOriginalFiles() const { return m_copyOriginalFiles->isChecked(); } bool KIGPDialog::useCommentFile() const { return m_useCommentFile->isChecked(); } int KIGPDialog::getImagesPerRow() const { return m_imagesPerRow->value(); } int KIGPDialog::getThumbnailSize() const { return m_thumbnailSize->value(); } int KIGPDialog::getColorDepth() const { return m_colorDepth->currentText().toInt(); } bool KIGPDialog::colorDepthSet() const { return m_colorDepthSet->isChecked(); } const QString KIGPDialog::getTitle() const { return m_title->text(); } const QUrl KIGPDialog::getImageUrl() const { return m_imageNameReq->url(); } const QString KIGPDialog::getCommentFile() const { return m_commentFileReq->url().toLocalFile(); } const QString KIGPDialog::getFontName() const { return m_fontName->currentText(); } const QString KIGPDialog::getFontSize() const { return m_fontSize->text(); } const QColor KIGPDialog::getBackgroundColor() const { return m_backgroundColor->color(); } const QColor KIGPDialog::getForegroundColor() const { return m_foregroundColor->color(); } const QString KIGPDialog::getImageFormat() const { return m_imageFormat->currentText(); } diff --git a/plugins/validators/clickiconlabel.cpp b/plugins/validators/clickiconlabel.cpp index 6cc672757..6b7d68a46 100644 --- a/plugins/validators/clickiconlabel.cpp +++ b/plugins/validators/clickiconlabel.cpp @@ -1,80 +1,80 @@ /* This file is part of Validators * * Copyright (C) 2008 by Pino Toscano * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ #include "clickiconlabel.h" #include #include #include ClickIconLabel::ClickIconLabel(QWidget *parent) : QWidget(parent) { QHBoxLayout *lay = new QHBoxLayout(this); - lay->setMargin(0); + lay->setContentsMargins(0, 0, 0, 0); lay->setSpacing(3); m_pixmap = new QLabel(this); lay->addWidget(m_pixmap); m_pixmap->show(); m_text = new QLabel(this); lay->addWidget(m_text); m_text->show(); } void ClickIconLabel::setText(const QString &text) { m_text->setText(text); } void ClickIconLabel::setPixmap(const QPixmap &pixmap) { m_pixmap->setPixmap(pixmap); } void ClickIconLabel::changeEvent(QEvent *event) { QWidget::changeEvent(event); #if QT_VERSION < 0x040500 switch (event->type()) { case QEvent::PaletteChange: m_text->setPalette(palette()); break; default: break; } #endif } void ClickIconLabel::mouseReleaseEvent(QMouseEvent *event) { switch (event->button()) { case Qt::LeftButton: emit leftClicked(); break; case Qt::MidButton: emit midClicked(); break; case Qt::RightButton: emit rightClicked(); break; default: break; } } diff --git a/plugins/validators/reportdialog.cpp b/plugins/validators/reportdialog.cpp index d53ef4ce0..4b91112ee 100644 --- a/plugins/validators/reportdialog.cpp +++ b/plugins/validators/reportdialog.cpp @@ -1,113 +1,113 @@ /* This file is part of Validators * * Copyright (C) 2008 by Pino Toscano * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ #include "reportdialog.h" #include "tidy_validator.h" #include #include #include static const int FrameNumberRole = Qt::UserRole + 1; static bool compare_report_items(QTreeWidgetItem *a, QTreeWidgetItem *b) { int val1 = a->data(0, FrameNumberRole).toInt(); int val2 = b->data(0, FrameNumberRole).toInt(); if (val1 != val2) { return val1 < val2; } val1 = a->text(2).toInt(); val2 = b->text(2).toInt(); if (val1 != val2) { return val1 < val2; } val1 = a->text(3).toInt(); val2 = b->text(3).toInt(); return val1 < val2; } QTreeWidgetItem *createItemFromReport(const TidyReport &report, const QIcon &icon, const QString &iconToolTip, const QString &frameName, int frameNumber) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setIcon(0, icon); item->setText(1, frameName); item->setText(2, QString::number(report.line)); item->setText(3, QString::number(report.col)); item->setText(4, report.msg); item->setToolTip(0, iconToolTip); item->setData(0, FrameNumberRole, frameNumber); return item; } ReportDialog::ReportDialog(const QList &results, QWidget *parent) : KDialog(parent) { setButtons(KDialog::Close); setCaption(i18nc("@title:window", "Validation Report")); m_ui.setupUi(mainWidget()); - mainWidget()->layout()->setMargin(0); + mainWidget()->layout()->setContentsMargins(0, 0, 0, 0); QHeaderView *header = m_ui.reportsView->header(); header->setResizeMode(0, QHeaderView::ResizeToContents); header->setResizeMode(1, QHeaderView::ResizeToContents); header->setResizeMode(2, QHeaderView::ResizeToContents); header->setResizeMode(3, QHeaderView::ResizeToContents); QList items; int i = 0; Q_FOREACH (ValidationResult *res, results) { const QIcon errorIcon = QIcon::fromTheme("dialog-error"); const QString errorStatus = i18nc("Validation status", "Error"); Q_FOREACH (const TidyReport &r, res->errors) { QTreeWidgetItem *item = createItemFromReport( r, errorIcon, errorStatus, res->frameName, i); items.append(item); } const QIcon warningIcon = QIcon::fromTheme("dialog-warning"); const QString warningStatus = i18nc("Validation status", "Warning"); Q_FOREACH (const TidyReport &r, res->warnings) { QTreeWidgetItem *item = createItemFromReport( r, warningIcon, warningStatus, res->frameName, i); items.append(item); } const QIcon a11yWarningIcon = QIcon::fromTheme("preferences-desktop-accessibility"); const QString a11yWarningStatus = i18nc("Validation status", "Accessibility warning"); Q_FOREACH (const TidyReport &r, res->accesswarns) { QTreeWidgetItem *item = createItemFromReport( r, a11yWarningIcon, a11yWarningStatus, res->frameName, i); items.append(item); } ++i; } qStableSort(items.begin(), items.end(), compare_report_items); m_ui.reportsView->addTopLevelItems(items); if (results.count() == 1) { header->setSectionHidden(1, true); } } QSize ReportDialog::sizeHint() const { return QSize(500, 400); } diff --git a/plugins/validators/validatorsdialog.cpp b/plugins/validators/validatorsdialog.cpp index 65a4431d6..b13ace245 100644 --- a/plugins/validators/validatorsdialog.cpp +++ b/plugins/validators/validatorsdialog.cpp @@ -1,139 +1,139 @@ /* This file is part of the KDE project Copyright (C) 2001 Andreas Schlapbach Copyright (C) 2008 Pino Toscano This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "validatorsdialog.h" #include "settings.h" #include #include ValidatorsDialog::ValidatorsDialog(QWidget *parent) : KPageDialog(parent) { setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); setModal(false); setWindowTitle(i18nc("@title:window", "Configure Validator Plugin")); setMinimumWidth(400); #ifdef HAVE_TIDY QWidget *internalConfiguration = new QWidget(); m_internalUi.setupUi(internalConfiguration); - internalConfiguration->layout()->setMargin(0); + internalConfiguration->layout()->setContentsMargins(0, 0, 0, 0); KPageWidgetItem *internalConfigurationItem = addPage(internalConfiguration, i18n("Internal Validation")); internalConfigurationItem->setIcon(QIcon::fromTheme("validators")); #endif QWidget *remoteConfiguration = new QWidget(); m_remoteUi.setupUi(remoteConfiguration); - remoteConfiguration->layout()->setMargin(0); + remoteConfiguration->layout()->setContentsMargins(0, 0, 0, 0); KPageWidgetItem *remoteConfigurationItem = addPage(remoteConfiguration, i18n("Remote Validation")); remoteConfigurationItem->setIcon(QIcon::fromTheme(QStringLiteral("validators"))); connect(this, SIGNAL(okClicked()), this, SLOT(slotOk())); connect(this, SIGNAL(cancelClicked()), this, SLOT(slotCancel())); load(); } ValidatorsDialog::~ValidatorsDialog() { } void ValidatorsDialog::load() { m_remoteUi.m_WWWValidatorCB->addItems(ValidatorsSettings::wWWValidatorUrl()); m_remoteUi.m_WWWValidatorCB->setCurrentIndex(ValidatorsSettings::wWWValidatorUrlIndex()); m_remoteUi.m_CSSValidatorCB->addItems(ValidatorsSettings::cSSValidatorUrl()); m_remoteUi.m_CSSValidatorCB->setCurrentIndex(ValidatorsSettings::cSSValidatorUrlIndex()); m_remoteUi.m_linkValidatorCB->addItems(ValidatorsSettings::linkValidatorUrl()); m_remoteUi.m_linkValidatorCB->setCurrentIndex(ValidatorsSettings::linkValidatorUrlIndex()); m_remoteUi.m_WWWValidatorUploadCB->addItems(ValidatorsSettings::wWWValidatorUploadUrl()); m_remoteUi.m_WWWValidatorUploadCB->setCurrentIndex(ValidatorsSettings::wWWValidatorUploadUrlIndex()); m_remoteUi.m_CSSValidatorUploadCB->addItems(ValidatorsSettings::cSSValidatorUploadUrl()); m_remoteUi.m_CSSValidatorUploadCB->setCurrentIndex(ValidatorsSettings::cSSValidatorUploadUrlIndex()); #ifdef HAVE_TIDY m_internalUi.accessibilityLevel->setCurrentIndex(ValidatorsSettings::accessibilityLevel()); m_internalUi.runAfterLoading->setChecked(ValidatorsSettings::runAfterLoading()); #endif } void ValidatorsDialog::save() { QStringList strList; for (int i = 0; i < m_remoteUi.m_WWWValidatorCB->count(); i++) { strList.append(m_remoteUi.m_WWWValidatorCB->itemText(i)); } ValidatorsSettings::setWWWValidatorUrl(strList); strList.clear(); for (int i = 0; i < m_remoteUi.m_CSSValidatorCB->count(); i++) { strList.append(m_remoteUi.m_CSSValidatorCB->itemText(i)); } ValidatorsSettings::setCSSValidatorUrl(strList); strList.clear(); for (int i = 0; i < m_remoteUi.m_linkValidatorCB->count(); i++) { strList.append(m_remoteUi.m_linkValidatorCB->itemText(i)); } ValidatorsSettings::setLinkValidatorUrl(strList); strList.clear(); for (int i = 0; i < m_remoteUi.m_WWWValidatorUploadCB->count(); i++) { strList.append(m_remoteUi.m_WWWValidatorUploadCB->itemText(i)); } ValidatorsSettings::setWWWValidatorUploadUrl(strList); strList.clear(); for (int i = 0; i < m_remoteUi.m_CSSValidatorUploadCB->count(); i++) { strList.append(m_remoteUi.m_CSSValidatorUploadCB->itemText(i)); } ValidatorsSettings::setCSSValidatorUploadUrl(strList); ValidatorsSettings::setWWWValidatorUrlIndex(m_remoteUi.m_WWWValidatorCB->currentIndex()); ValidatorsSettings::setCSSValidatorUrlIndex(m_remoteUi.m_CSSValidatorCB->currentIndex()); ValidatorsSettings::setLinkValidatorUrlIndex(m_remoteUi.m_linkValidatorCB->currentIndex()); ValidatorsSettings::setWWWValidatorUploadUrlIndex(m_remoteUi.m_WWWValidatorUploadCB->currentIndex()); ValidatorsSettings::setCSSValidatorUploadUrlIndex(m_remoteUi.m_CSSValidatorUploadCB->currentIndex()); #ifdef HAVE_TIDY ValidatorsSettings::setAccessibilityLevel(m_internalUi.accessibilityLevel->currentIndex()); ValidatorsSettings::setRunAfterLoading(m_internalUi.runAfterLoading->isChecked()); #endif ValidatorsSettings::self()->save(); emit configChanged(); } void ValidatorsDialog::slotOk() { save(); hide(); } void ValidatorsDialog::slotCancel() { load(); hide(); } diff --git a/settings/konq/kcustommenueditor.cpp b/settings/konq/kcustommenueditor.cpp index 7641ea22c..449ea64ea 100644 --- a/settings/konq/kcustommenueditor.cpp +++ b/settings/konq/kcustommenueditor.cpp @@ -1,252 +1,252 @@ /* This file is part of the KDE libraries Copyright (C) 2002 Waldo Bastian (bastian@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; version 2 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Own #include "kcustommenueditor.h" // Qt #include #include #include #include // KDE #include #include #include #include #include #include #include #include #include #include #include class KCustomMenuEditor::Item : public Q3ListViewItem { public: Item(Q3ListView *parent, KService::Ptr service) : Q3ListViewItem(parent), s(service) { init(); } Item(Q3ListViewItem *parent, KService::Ptr service) : Q3ListViewItem(parent), s(service) { init(); } void init() { QString serviceName = s->name(); // item names may contain ampersands. To avoid them being converted // to accelerators, replace them with two ampersands. serviceName.replace('&', "&&"); QPixmap normal = KIconLoader::global()->loadIcon(s->icon(), KIconLoader::Small, 0, KIconLoader::DefaultState, QStringList(), 0L, true); // make sure they are not larger than 16x16 if (normal.width() > 16 || normal.height() > 16) { QImage tmp = normal.toImage(); tmp = tmp.scaled(16, 16, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); normal = QPixmap::fromImage(tmp); } setText(0, serviceName); setPixmap(0, normal); } KService::Ptr s; }; class KCustomMenuEditor::KCustomMenuEditorPrivate { public: QPushButton *pbRemove; QPushButton *pbMoveUp; QPushButton *pbMoveDown; }; KCustomMenuEditor::KCustomMenuEditor(QWidget *parent) : KDialog(parent), m_listView(0), d(new KCustomMenuEditorPrivate) { setCaption(i18nc("@title:window", "Menu Editor")); setButtons(Ok | Cancel); setDefaultButton(Ok); QWidget *page = new QWidget(this); QHBoxLayout *pageHBoxLayout = new QHBoxLayout(page); - pageHBoxLayout->setMargin(0); + pageHBoxLayout->setContentsMargins(0, 0, 0, 0); setMainWidget(page); m_listView = new K3ListView(page); pageHBoxLayout->addWidget(m_listView); m_listView->addColumn(i18n("Menu")); m_listView->setFullWidth(true); m_listView->setSorting(-1); KDialogButtonBox *buttonBox = new KDialogButtonBox(page, Qt::Vertical); buttonBox->addButton(i18n("New..."), QDialogButtonBox::ActionRole, this, SLOT(slotNewItem())); d->pbRemove = buttonBox->addButton(i18n("Remove"), QDialogButtonBox::DestructiveRole, this, SLOT(slotRemoveItem())); d->pbMoveUp = buttonBox->addButton(i18n("Move Up"), QDialogButtonBox::ActionRole, this, SLOT(slotMoveUp())); d->pbMoveDown = buttonBox->addButton(i18n("Move Down"), QDialogButtonBox::ActionRole, this, SLOT(slotMoveDown())); buttonBox->layout(); connect(m_listView, SIGNAL(selectionChanged()), this, SLOT(refreshButton())); refreshButton(); } KCustomMenuEditor::~KCustomMenuEditor() { delete d; } void KCustomMenuEditor::refreshButton() { Q3ListViewItem *item = m_listView->currentItem(); d->pbRemove->setEnabled(item); d->pbMoveUp->setEnabled(item && item->itemAbove()); d->pbMoveDown->setEnabled(item && item->itemBelow()); } void KCustomMenuEditor::load(KConfig *cfg) { KConfigGroup cg(cfg, QString()); int count = cg.readEntry("NrOfItems", 0); Q3ListViewItem *last = 0; for (int i = 0; i < count; i++) { QString entry = cg.readPathEntry(QString("Item%1").arg(i + 1), QString()); if (entry.isEmpty()) { continue; } // Try KSycoca first. KService::Ptr menuItem = KService::serviceByDesktopPath(entry); if (!menuItem) { menuItem = KService::serviceByDesktopName(entry); } if (!menuItem) { menuItem = new KService(entry); } if (!menuItem->isValid()) { continue; } Q3ListViewItem *item = new Item(m_listView, menuItem); item->moveItem(last); last = item; } } void KCustomMenuEditor::save(KConfig *cfg) { // First clear the whole config file. const QStringList groups = cfg->groupList(); for (QStringList::ConstIterator it = groups.begin(); it != groups.end(); ++it) { cfg->deleteGroup(*it); } KConfigGroup cg(cfg, QString()); Item *item = (Item *) m_listView->firstChild(); int i = 0; while (item) { i++; QString path = item->s->entryPath(); if (QDir::isRelativePath(path) || QDir::isRelativePath(KGlobal::dirs()->relativeLocation("xdgdata-apps", path))) { path = item->s->desktopEntryName(); } cg.writePathEntry(QString("Item%1").arg(i), path); item = (Item *) item->nextSibling(); } cg.writeEntry("NrOfItems", i); } void KCustomMenuEditor::slotNewItem() { Q3ListViewItem *item = m_listView->currentItem(); KOpenWithDialog dlg(this); dlg.setSaveNewApplications(true); if (dlg.exec()) { KService::Ptr s = dlg.service(); if (s && s->isValid()) { Item *newItem = new Item(m_listView, s); newItem->moveItem(item); } refreshButton(); } } void KCustomMenuEditor::slotRemoveItem() { Q3ListViewItem *item = m_listView->currentItem(); if (!item) { return; } delete item; refreshButton(); } void KCustomMenuEditor::slotMoveUp() { Q3ListViewItem *item = m_listView->currentItem(); if (!item) { return; } Q3ListViewItem *searchItem = m_listView->firstChild(); while (searchItem) { Q3ListViewItem *next = searchItem->nextSibling(); if (next == item) { searchItem->moveItem(item); break; } searchItem = next; } refreshButton(); } void KCustomMenuEditor::slotMoveDown() { Q3ListViewItem *item = m_listView->currentItem(); if (!item) { return; } Q3ListViewItem *after = item->nextSibling(); if (!after) { return; } item->moveItem(after); refreshButton(); } diff --git a/settings/konqhtml/css/kcmcss.cpp b/settings/konqhtml/css/kcmcss.cpp index b4937917b..70d27cee5 100644 --- a/settings/konqhtml/css/kcmcss.cpp +++ b/settings/konqhtml/css/kcmcss.cpp @@ -1,358 +1,358 @@ // Own #include "kcmcss.h" // Qt #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include // Local #include "template.h" #include "ui_cssconfig.h" class CSSConfigWidget: public QWidget, public Ui::CSSConfigWidget { public: CSSConfigWidget(QWidget *parent) : QWidget(parent) { setupUi(this); } }; CSSConfig::CSSConfig(QWidget *parent, const QVariantList &) : QWidget(parent) , configWidget(new CSSConfigWidget(this)) , customDialogBase(new KDialog(this)) , customDialog(new CSSCustomDialog(customDialogBase)) { customDialogBase->setObjectName(QStringLiteral("customCSSDialog")); customDialogBase->setModal(true); customDialogBase->setButtons(KDialog::Close); customDialogBase->setDefaultButton(KDialog::Close); customDialogBase->setMainWidget(customDialog); // setQuickHelp( i18n("

Konqueror Stylesheets

This module allows you to apply your own color" setWhatsThis(i18n("

Konqueror Stylesheets

This module allows you to apply your own color" " and font settings to Konqueror by using" " stylesheets (CSS). You can either specify" " options or apply your own self-written" " stylesheet by pointing to its location.
" " Note that these settings will always have" " precedence before all other settings made" " by the site author. This can be useful to" " visually impaired people or for web pages" " that are unreadable due to bad design.")); connect(configWidget->useDefault, SIGNAL(clicked()), SIGNAL(changed())); connect(configWidget->useAccess, SIGNAL(clicked()), SIGNAL(changed())); connect(configWidget->useUser, SIGNAL(clicked()), SIGNAL(changed())); connect(configWidget->urlRequester, SIGNAL(textChanged(QString)), SIGNAL(changed())); connect(configWidget->customize, SIGNAL(clicked()), SLOT(slotCustomize())); connect(customDialog, SIGNAL(changed()), SIGNAL(changed())); QVBoxLayout *vbox = new QVBoxLayout(this); - vbox->setMargin(0); + vbox->setContentsMargins(0, 0, 0, 0); vbox->addWidget(configWidget); } void CSSConfig::load() { const bool signalsBlocked = customDialog->blockSignals(true); KConfig *c = new KConfig(QStringLiteral("kcmcssrc"), KConfig::NoGlobals); KConfigGroup group = c->group("Stylesheet"); QString u = group.readEntry("Use", "default"); configWidget->useDefault->setChecked(u == QLatin1String("default")); configWidget->useUser->setChecked(u == QLatin1String("user")); configWidget->useAccess->setChecked(u == QLatin1String("access")); configWidget->urlRequester->setUrl(QUrl::fromUserInput(group.readEntry("SheetName"))); group = c->group("Font"); customDialog->basefontsize->setEditText(QString::number(group.readEntry("BaseSize", 12))); customDialog->dontScale->setChecked(group.readEntry("DontScale", false)); const QString fname(group.readEntry("Family", "Arial")); for (int i = 0; i < customDialog->fontFamily->count(); ++i) { if (customDialog->fontFamily->itemText(i) == fname) { customDialog->fontFamily->setCurrentIndex(i); break; } } customDialog->sameFamily->setChecked(group.readEntry("SameFamily", false)); group = c->group("Colors"); QString m = group.readEntry("Mode", "black-on-white"); customDialog->blackOnWhite->setChecked(m == QLatin1String("black-on-white")); customDialog->whiteOnBlack->setChecked(m == QLatin1String("white-on-black")); customDialog->customColor->setChecked(m == QLatin1String("custom")); QColor white(Qt::white); QColor black(Qt::black); customDialog->backgroundColorButton->setColor(group.readEntry("BackColor", white)); customDialog->foregroundColorButton->setColor(group.readEntry("ForeColor", black)); customDialog->sameColor->setChecked(group.readEntry("SameColor", false)); // Images group = c->group("Images"); customDialog->hideImages->setChecked(group.readEntry("Hide", false)); customDialog->hideBackground->setChecked(group.readEntry("HideBackground", true)); customDialog->blockSignals(signalsBlocked); delete c; } void CSSConfig::save() { // write to config file KConfig *c = new KConfig(QStringLiteral("kcmcssrc"), KConfig::NoGlobals); KConfigGroup group = c->group("Stylesheet"); if (configWidget->useDefault->isChecked()) { group.writeEntry("Use", "default"); } if (configWidget->useUser->isChecked()) { group.writeEntry("Use", "user"); } if (configWidget->useAccess->isChecked()) { group.writeEntry("Use", "access"); } group.writeEntry("SheetName", configWidget->urlRequester->url().url()); group = c->group("Font"); group.writeEntry("BaseSize", customDialog->basefontsize->currentText()); group.writeEntry("DontScale", customDialog->dontScale->isChecked()); group.writeEntry("SameFamily", customDialog->sameFamily->isChecked()); group.writeEntry("Family", customDialog->fontFamily->currentText()); group = c->group("Colors"); if (customDialog->blackOnWhite->isChecked()) { group.writeEntry("Mode", "black-on-white"); } if (customDialog->whiteOnBlack->isChecked()) { group.writeEntry("Mode", "white-on-black"); } if (customDialog->customColor->isChecked()) { group.writeEntry("Mode", "custom"); } group.writeEntry("BackColor", customDialog->backgroundColorButton->color()); group.writeEntry("ForeColor", customDialog->foregroundColorButton->color()); group.writeEntry("SameColor", customDialog->sameColor->isChecked()); group = c->group("Images"); group.writeEntry("Hide", customDialog->hideImages->isChecked()); group.writeEntry("HideBackground", customDialog->hideBackground->isChecked()); c->sync(); delete c; // generate CSS template QString dest; const QString templ(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kcmcss/template.css"))); if (!templ.isEmpty()) { CSSTemplate css(templ); dest = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/kcmcss/"; QDir().mkpath(dest); dest += QLatin1String("override.css"); css.expandToFile(dest, customDialog->cssDict()); } // make konqueror use the right stylesheet c = new KConfig(QStringLiteral("konquerorrc"), KConfig::NoGlobals); group = c->group("HTML Settings"); group.writeEntry("UserStyleSheetEnabled", !configWidget->useDefault->isChecked()); if (configWidget->useUser->isChecked()) { group.writeEntry("UserStyleSheet", configWidget->urlRequester->url().url()); } if (configWidget->useAccess->isChecked()) { group.writeEntry("UserStyleSheet", dest); } c->sync(); delete c; } void CSSConfig::defaults() { configWidget->useDefault->setChecked(true); configWidget->useUser->setChecked(false); configWidget->useAccess->setChecked(false); configWidget->urlRequester->setUrl(QUrl()); customDialog->basefontsize->setEditText(QString::number(12)); customDialog->dontScale->setChecked(false); const QString fname(QStringLiteral("Arial")); for (int i = 0; i < customDialog->fontFamily->count(); ++i) { if (customDialog->fontFamily->itemText(i) == fname) { customDialog->fontFamily->setCurrentIndex(i); break; } } customDialog->sameFamily->setChecked(false); customDialog->blackOnWhite->setChecked(true); customDialog->whiteOnBlack->setChecked(false); customDialog->customColor->setChecked(false); customDialog->backgroundColorButton->setColor(Qt::white); customDialog->foregroundColorButton->setColor(Qt::black); customDialog->sameColor->setChecked(false); customDialog->hideImages->setChecked(false); customDialog->hideBackground->setChecked(true); } static QString px(int i, double scale) { QString px; px.setNum(static_cast(i * scale)); px += QLatin1String("px"); return px; } QMap CSSCustomDialog::cssDict() { QMap dict; // Fontsizes ------------------------------------------------------ int bfs = basefontsize->currentText().toInt(); dict.insert(QStringLiteral("fontsize-base"), px(bfs, 1.0)); if (dontScale->isChecked()) { dict.insert(QStringLiteral("fontsize-small-1"), px(bfs, 1.0)); dict.insert(QStringLiteral("fontsize-large-1"), px(bfs, 1.0)); dict.insert(QStringLiteral("fontsize-large-2"), px(bfs, 1.0)); dict.insert(QStringLiteral("fontsize-large-3"), px(bfs, 1.0)); dict.insert(QStringLiteral("fontsize-large-4"), px(bfs, 1.0)); dict.insert(QStringLiteral("fontsize-large-5"), px(bfs, 1.0)); } else { // TODO: use something harmonic here dict.insert(QStringLiteral("fontsize-small-1"), px(bfs, 0.8)); dict.insert(QStringLiteral("fontsize-large-1"), px(bfs, 1.2)); dict.insert(QStringLiteral("fontsize-large-2"), px(bfs, 1.4)); dict.insert(QStringLiteral("fontsize-large-3"), px(bfs, 1.5)); dict.insert(QStringLiteral("fontsize-large-4"), px(bfs, 1.6)); dict.insert(QStringLiteral("fontsize-large-5"), px(bfs, 1.8)); } // Colors -------------------------------------------------------- if (customColor->isChecked()) { dict.insert(QStringLiteral("background-color"), backgroundColorButton->color().name()); dict.insert(QStringLiteral("foreground-color"), foregroundColorButton->color().name()); } else { const char *blackOnWhiteFG[2] = {"White", "Black"}; bool bw = blackOnWhite->isChecked(); dict.insert(QStringLiteral("foreground-color"), QLatin1String(blackOnWhiteFG[bw])); dict.insert(QStringLiteral("background-color"), QLatin1String(blackOnWhiteFG[!bw])); } const char *notImportant[2] = {"", "! important"}; dict.insert(QStringLiteral("force-color"), QLatin1String(notImportant[sameColor->isChecked()])); // Fonts ------------------------------------------------------------- dict.insert(QStringLiteral("font-family"), fontFamily->currentText()); dict.insert(QStringLiteral("force-font"), QLatin1String(notImportant[sameFamily->isChecked()])); // Images const char *bgNoneImportant[2] = {"", "background-image : none ! important"}; dict.insert(QStringLiteral("display-images"), QLatin1String(bgNoneImportant[hideImages->isChecked()])); dict.insert(QStringLiteral("display-background"), QLatin1String(bgNoneImportant[hideBackground->isChecked()])); return dict; } void CSSConfig::slotCustomize() { customDialog->slotPreview(); customDialogBase->exec(); } CSSCustomDialog::CSSCustomDialog(QWidget *parent) : QWidget(parent) { setupUi(this); connect(this, SIGNAL(changed()), SLOT(slotPreview())); connect(basefontsize, SIGNAL(activated(int)), SIGNAL(changed())); connect(basefontsize, SIGNAL(editTextChanged(QString)), SIGNAL(changed())); connect(dontScale, SIGNAL(clicked()), SIGNAL(changed())); connect(blackOnWhite, SIGNAL(clicked()), SIGNAL(changed())); connect(whiteOnBlack, SIGNAL(clicked()), SIGNAL(changed())); connect(customColor, SIGNAL(clicked()), SIGNAL(changed())); connect(foregroundColorButton, SIGNAL(changed(QColor)), SIGNAL(changed())); connect(backgroundColorButton, SIGNAL(changed(QColor)), SIGNAL(changed())); connect(fontFamily, SIGNAL(activated(int)), SIGNAL(changed())); connect(fontFamily, SIGNAL(editTextChanged(QString)), SIGNAL(changed())); connect(sameFamily, SIGNAL(clicked()), SIGNAL(changed())); connect(sameColor, SIGNAL(clicked()), SIGNAL(changed())); connect(hideImages, SIGNAL(clicked()), SIGNAL(changed())); connect(hideBackground, SIGNAL(clicked()), SIGNAL(changed())); //QStringList fonts; //KFontChooser::getFontList(fonts, 0); //fontFamily->addItems(fonts); part = KMimeTypeTrader::createPartInstanceFromQuery(QStringLiteral("text/html"), parent, this); QVBoxLayout *l = new QVBoxLayout(previewBox); l->addWidget(part->widget()); } static QUrl toDataUri(const QString &content, const QByteArray &contentType) { QByteArray data("data:"); data += contentType; data += ";charset=utf-8;base64,"; data += content.toUtf8().toBase64(); return QUrl::fromEncoded(data); } void CSSCustomDialog::slotPreview() { const QString templ(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kcmcss/template.css"))); if (templ.isEmpty()) { return; } CSSTemplate css(templ); QString data(i18n("\n\n\n\n" "\n" "

Heading 1

\n" "

Heading 2

\n" "

Heading 3

\n" "\n" "

User-defined stylesheets allow increased\n" "accessibility for visually handicapped\n" "people.

\n" "\n" "\n" "\n", css.expandToString(cssDict()))); KParts::OpenUrlArguments args(part->arguments()); args.setReload(true); // Make sure the content is always freshly reloaded. part->setArguments(args); part->openUrl(toDataUri(data, "text/html")); } diff --git a/settings/konqhtml/filteropts.cpp b/settings/konqhtml/filteropts.cpp index 7313a48ae..6282fc5a7 100644 --- a/settings/konqhtml/filteropts.cpp +++ b/settings/konqhtml/filteropts.cpp @@ -1,587 +1,587 @@ /* Copyright (C) 2005 Ivor Hewitt This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Own #include "filteropts.h" // Qt #include #include #include #include #include #include #include #include #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include KCMFilter::KCMFilter(QWidget *parent, const QVariantList &) : KCModule(parent), mGroupname(QStringLiteral("Filter Settings")), mSelCount(0), mOriginalString(QString()) { mConfig = KSharedConfig::openConfig(QStringLiteral("khtmlrc"), KConfig::NoGlobals); setButtons(Default | Apply | Help); QVBoxLayout *topLayout = new QVBoxLayout(this); mEnableCheck = new QCheckBox(i18n("Enable filters"), this); topLayout->addWidget(mEnableCheck); mKillCheck = new QCheckBox(i18n("Hide filtered images"), this); topLayout->addWidget(mKillCheck); mFilterWidget = new KTabWidget(this); topLayout->addWidget(mFilterWidget); QWidget *container = new QWidget(mFilterWidget); mFilterWidget->addTab(container, i18n("Manual Filter")); QVBoxLayout *vbox = new QVBoxLayout; mListBox = new QListWidget; mListBox->setSelectionMode(QListWidget::ExtendedSelection); // If the filter list were sensitive to ordering, then we would need to // preserve the order of items inserted or arranged by the user (and the // GUI would need "Move Up" and "Move Down" buttons to reorder the filters). // However, now the filters are applied in an unpredictable order because // of the new hashed matching algorithm. So the list can stay sorted. mListBox->setSortingEnabled(true); QWidget *searchBox = new QWidget; QHBoxLayout *searchBoxHBoxLayout = new QHBoxLayout(searchBox); - searchBoxHBoxLayout->setMargin(0); + searchBoxHBoxLayout->setContentsMargins(0, 0, 0, 0); searchBoxHBoxLayout->setSpacing(-1); new QLabel(i18n("Search:"), searchBox); mSearchLine = new KListWidgetSearchLine(searchBox, mListBox); vbox->addWidget(searchBox); vbox->addWidget(mListBox); QLabel *exprLabel = new QLabel(i18n("Filter expression (e.g. http://www.example.com/ad/*, more information):"), this); connect(exprLabel, SIGNAL(linkActivated(QString)), SLOT(slotInfoLinkActivated(QString))); vbox->addWidget(exprLabel); mString = new KLineEdit; vbox->addWidget(mString); QWidget *buttonBox = new QWidget; QHBoxLayout *buttonBoxHBoxLayout = new QHBoxLayout(buttonBox); - buttonBoxHBoxLayout->setMargin(0); + buttonBoxHBoxLayout->setContentsMargins(0, 0, 0, 0); vbox->addWidget(buttonBox); container->setLayout(vbox); /** tab for automatic filter lists */ container = new QWidget(mFilterWidget); mFilterWidget->addTab(container, i18n("Automatic Filter")); QGridLayout *grid = new QGridLayout; grid->setColumnStretch(2, 1); container->setLayout(grid); mAutomaticFilterList = new QTreeView(container); mAutomaticFilterList->setModel(&mAutomaticFilterModel); grid->addWidget(mAutomaticFilterList, 0, 0, 1, 3); QLabel *label = new QLabel(i18n("Automatic update interval:"), container); grid->addWidget(label, 1, 0); mRefreshFreqSpinBox = new KIntSpinBox(container); grid->addWidget(mRefreshFreqSpinBox, 1, 1); mRefreshFreqSpinBox->setRange(1, 365); mRefreshFreqSpinBox->setSuffix(ki18np(" day", " days")); /** connect signals and slots */ connect(&mAutomaticFilterModel, SIGNAL(changed(bool)), this, SIGNAL(changed(bool))); connect(mRefreshFreqSpinBox, SIGNAL(valueChanged(int)), this, SLOT(spinBoxChanged(int))); mInsertButton = new QPushButton(QIcon::fromTheme(QStringLiteral("list-add")), i18n("Insert"), buttonBox); buttonBoxHBoxLayout->addWidget(mInsertButton); connect(mInsertButton, &QAbstractButton::clicked, this, &KCMFilter::insertFilter); mUpdateButton = new QPushButton(QIcon::fromTheme(QStringLiteral("document-edit")), i18n("Update"), buttonBox); buttonBoxHBoxLayout->addWidget(mUpdateButton); connect(mUpdateButton, &QAbstractButton::clicked, this, &KCMFilter::updateFilter); mRemoveButton = new QPushButton(QIcon::fromTheme(QStringLiteral("list-remove")), i18n("Remove"), buttonBox); buttonBoxHBoxLayout->addWidget(mRemoveButton); connect(mRemoveButton, &QAbstractButton::clicked, this, &KCMFilter::removeFilter); mImportButton = new QPushButton(QIcon::fromTheme(QStringLiteral("document-import")), i18n("Import..."), buttonBox); buttonBoxHBoxLayout->addWidget(mImportButton); connect(mImportButton, &QAbstractButton::clicked, this, &KCMFilter::importFilters); mExportButton = new QPushButton(QIcon::fromTheme(QStringLiteral("document-export")), i18n("Export..."), buttonBox); buttonBoxHBoxLayout->addWidget(mExportButton); connect(mExportButton, &QAbstractButton::clicked, this, &KCMFilter::exportFilters); QWidget *impexpBox = new QWidget; QHBoxLayout *impexpBoxHBoxLayout = new QHBoxLayout(impexpBox); - impexpBoxHBoxLayout->setMargin(0); + impexpBoxHBoxLayout->setContentsMargins(0, 0, 0, 0); QLabel *impexpLabel = new QLabel(i18n("More information on " "import format, " "export format"), impexpBox); connect(impexpLabel, SIGNAL(linkActivated(QString)), SLOT(slotInfoLinkActivated(QString))); vbox->addWidget(impexpBox, 0, Qt::AlignRight); connect(mEnableCheck, SIGNAL(toggled(bool)), this, SLOT(slotEnableChecked())); connect(mKillCheck, &QAbstractButton::clicked, this, &KCMFilter::slotKillChecked); connect(mListBox, SIGNAL(itemSelectionChanged()), this, SLOT(slotItemSelected())); connect(mString, SIGNAL(textChanged(QString)), this, SLOT(updateButton())); /* * Whats this items */ mEnableCheck->setWhatsThis(i18n("Enable or disable AdBlocK filters. When enabled, a set of URL expressions " "should be defined in the filter list for blocking to take effect.")); mKillCheck->setWhatsThis(i18n("When enabled blocked images will be removed from the page completely, " "otherwise a placeholder 'blocked' image will be used.")); // The list is no longer sensitive to order, because of the new hashed // matching. So this tooltip doesn't imply that. // // FIXME: blocking of frames is not currently implemented by KHTML mListBox->setWhatsThis(i18n("This is the list of URL filters that will be applied to all embedded " "images and media objects.")); // "images, objects and frames.") ); mString->setWhatsThis(i18n("

Enter an expression to filter. Filters can be defined as either:" "

  • a shell-style wildcard, e.g. http://www.example.com/ads*, the wildcards *?[] may be used
  • " "
  • a full regular expression by surrounding the string with '/', e.g. /\\/(ad|banner)\\./
" "

Any filter string can be preceded by '@@' to whitelist (allow) any matching URL, " "which takes priority over any blacklist (blocking) filter.")); } KCMFilter::~KCMFilter() { } void KCMFilter::slotInfoLinkActivated(const QString &url) { if (url == QLatin1String("filterhelp")) { QWhatsThis::showText(QCursor::pos(), mString->whatsThis()); } else if (url == QLatin1String("importhelp")) QWhatsThis::showText(QCursor::pos(), i18n("

The filter import format is a plain text file. " "Blank lines, comment lines starting with '!' " "and the header line [AdBlock] are ignored. " "Any other line is added as a filter expression.")); else if (url == QLatin1String("exporthelp")) QWhatsThis::showText(QCursor::pos(), i18n("

The filter export format is a plain text file. " "The file begins with a header line [AdBlock], then all of " "the filters follow each on a separate line.")); } void KCMFilter::slotKillChecked() { emit changed(true); } void KCMFilter::slotEnableChecked() { updateButton(); emit changed(true); } void KCMFilter::slotItemSelected() { int currentId = -1; int i; for (i = 0, mSelCount = 0; i < mListBox->count() && mSelCount < 2; ++i) { if (mListBox->item(i)->isSelected()) { currentId = i; mSelCount++; } } if (currentId >= 0) { mOriginalString = mListBox->item(currentId)->text(); mString->setText(mOriginalString); mString->setFocus(Qt::OtherFocusReason); } updateButton(); } void KCMFilter::updateButton() { bool state = mEnableCheck->isChecked(); bool expressionIsNotEmpty = !mString->text().isEmpty(); bool filterEdited = expressionIsNotEmpty && mOriginalString != mString->text(); mInsertButton->setEnabled(state && expressionIsNotEmpty && filterEdited); mUpdateButton->setEnabled(state && (mSelCount == 1) && expressionIsNotEmpty && filterEdited); mRemoveButton->setEnabled(state && (mSelCount > 0)); mImportButton->setEnabled(state); mExportButton->setEnabled(state && mListBox->count() > 0); mListBox->setEnabled(state); mString->setEnabled(state); mKillCheck->setEnabled(state); if (filterEdited) { if (mSelCount == 1 && mUpdateButton->isEnabled()) { mUpdateButton->setDefault(true); } else if (mInsertButton->isEnabled()) { mInsertButton->setDefault(true); } } else { mInsertButton->setDefault(false); mUpdateButton->setDefault(false); } mAutomaticFilterList->setEnabled(state); mRefreshFreqSpinBox->setEnabled(state); } void KCMFilter::importFilters() { QString inFile = KFileDialog::getOpenFileName(QUrl(), QString(), this); if (!inFile.isEmpty()) { QFile f(inFile); if (f.open(QIODevice::ReadOnly)) { QTextStream ts(&f); QStringList paths; QString line; while (!ts.atEnd()) { line = ts.readLine(); if (line.isEmpty() || line.compare(QLatin1String("[adblock]"), Qt::CaseInsensitive) == 0) { continue; } // Treat leading ! as filter comment, otherwise check expressions // are valid. if (!line.startsWith(QLatin1String("!"))) { //krazy:exclude=doublequote_chars if (line.length() > 2 && line[0] == '/' && line[line.length() - 1] == '/') { QString inside = line.mid(1, line.length() - 2); QRegExp rx(inside); if (!rx.isValid()) { continue; } } else { QRegExp rx(line); rx.setPatternSyntax(QRegExp::Wildcard); if (!rx.isValid()) { continue; } } if (mListBox->findItems(line, Qt::MatchCaseSensitive | Qt::MatchExactly).isEmpty()) { paths.append(line); } } } f.close(); mListBox->addItems(paths); emit changed(true); } } } void KCMFilter::exportFilters() { QString outFile = KFileDialog::getSaveFileName(QUrl(), QString(), this); if (!outFile.isEmpty()) { QFile f(outFile); if (f.open(QIODevice::WriteOnly)) { QTextStream ts(&f); ts.setCodec("UTF-8"); ts << "[AdBlock]" << endl; int nbLine = mListBox->count(); for (int i = 0; i < nbLine; ++i) { ts << mListBox->item(i)->text() << endl; } f.close(); } } } void KCMFilter::defaults() { mAutomaticFilterModel.defaults(); mListBox->clear(); mEnableCheck->setChecked(false); mKillCheck->setChecked(false); mString->clear(); updateButton(); } void KCMFilter::save() { KConfigGroup cg(mConfig, mGroupname); cg.deleteGroup(); cg = KConfigGroup(mConfig, mGroupname); cg.writeEntry("Enabled", mEnableCheck->isChecked()); cg.writeEntry("Shrink", mKillCheck->isChecked()); int i; for (i = 0; i < mListBox->count(); ++i) { QString key = "Filter-" + QString::number(i); cg.writeEntry(key, mListBox->item(i)->text()); } cg.writeEntry("Count", mListBox->count()); mAutomaticFilterModel.save(cg); cg.writeEntry("HTMLFilterListMaxAgeDays", mRefreshFreqSpinBox->value()); cg.sync(); QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration")); QDBusConnection::sessionBus().send(message); } void KCMFilter::load() { QStringList paths; KConfigGroup cg(mConfig, mGroupname); mAutomaticFilterModel.load(cg); mAutomaticFilterList->resizeColumnToContents(0); int refreshFreq = cg.readEntry("HTMLFilterListMaxAgeDays", 7); mRefreshFreqSpinBox->setValue(refreshFreq < 1 ? 1 : refreshFreq); mEnableCheck->setChecked(cg.readEntry("Enabled", false)); mKillCheck->setChecked(cg.readEntry("Shrink", false)); QMap entryMap = cg.entryMap(); QMap::ConstIterator it; int num = cg.readEntry("Count", 0); for (int i = 0; i < num; ++i) { QString key = "Filter-" + QString::number(i); it = entryMap.constFind(key); if (it != entryMap.constEnd()) { paths.append(it.value()); } } mListBox->addItems(paths); updateButton(); } void KCMFilter::insertFilter() { QString newFilter = mString->text(); if (!newFilter.isEmpty() && mListBox->findItems(newFilter, Qt::MatchCaseSensitive | Qt::MatchExactly).isEmpty()) { mListBox->clearSelection(); mListBox->addItem(newFilter); // The next line assumed that the new item would be added at the end // of the list, but that may not be the case if sorting is enabled. // So we search again to locate the just-added item. //int id = mListBox->count()-1; QListWidgetItem *newItem = mListBox->findItems(newFilter, Qt::MatchCaseSensitive | Qt::MatchExactly).first(); if (newItem != nullptr) { int id = mListBox->row(newItem); mListBox->item(id)->setSelected(true); mListBox->setCurrentRow(id); } updateButton(); emit changed(true); } } void KCMFilter::removeFilter() { for (int i = mListBox->count(); i >= 0; --i) { if (mListBox->item(i) && mListBox->item(i)->isSelected()) { delete mListBox->takeItem(i); } } mString->clear(); emit changed(true); updateButton(); } void KCMFilter::updateFilter() { if (!mString->text().isEmpty()) { int index = mListBox->currentRow(); if (index >= 0) { mListBox->item(index)->setText(mString->text()); emit changed(true); } } updateButton(); } QString KCMFilter::quickHelp() const { return i18n("

Konqueror AdBlocK

Konqueror AdBlocK allows you to create a list of filters" " that are checked against linked images and frames. URL's that match are either discarded or" " replaced with a placeholder image. "); } void KCMFilter::spinBoxChanged(int) { emit changed(true); } AutomaticFilterModel::AutomaticFilterModel(QObject *parent) : QAbstractItemModel(parent), mGroupname(QStringLiteral("Filter Settings")) { //mConfig = KSharedConfig::openConfig("khtmlrc", KConfig::NoGlobals); mConfig = KSharedConfig::openConfig(QStringLiteral("khtmlrc"), KConfig::IncludeGlobals); } void AutomaticFilterModel::load(KConfigGroup &cg) { beginResetModel(); mFilters.clear(); const int maxNumFilters = 1024; const bool defaultHTMLFilterListEnabled = false; for (int numFilters = 1; numFilters < maxNumFilters; ++numFilters) { struct FilterConfig filterConfig; filterConfig.filterName = cg.readEntry(QStringLiteral("HTMLFilterListName-") + QString::number(numFilters), ""); if (filterConfig.filterName == QLatin1String("")) { break; } filterConfig.enableFilter = cg.readEntry(QStringLiteral("HTMLFilterListEnabled-") + QString::number(numFilters), defaultHTMLFilterListEnabled); filterConfig.filterURL = cg.readEntry(QStringLiteral("HTMLFilterListURL-") + QString::number(numFilters), ""); filterConfig.filterLocalFilename = cg.readEntry(QStringLiteral("HTMLFilterListLocalFilename-") + QString::number(numFilters), ""); mFilters << filterConfig; } endResetModel(); } void AutomaticFilterModel::save(KConfigGroup &cg) { for (int i = mFilters.count() - 1; i >= 0; --i) { cg.writeEntry(QStringLiteral("HTMLFilterListLocalFilename-") + QString::number(i + 1), mFilters[i].filterLocalFilename); cg.writeEntry(QStringLiteral("HTMLFilterListURL-") + QString::number(i + 1), mFilters[i].filterURL); cg.writeEntry(QStringLiteral("HTMLFilterListName-") + QString::number(i + 1), mFilters[i].filterName); cg.writeEntry(QStringLiteral("HTMLFilterListEnabled-") + QString::number(i + 1), mFilters[i].enableFilter); } } void AutomaticFilterModel::defaults() { mConfig = KSharedConfig::openConfig(QStringLiteral("khtmlrc"), KConfig::IncludeGlobals); KConfigGroup cg(mConfig, mGroupname); load(cg); } QModelIndex AutomaticFilterModel::index(int row, int column, const QModelIndex & /*parent*/) const { return createIndex(row, column, (void *)nullptr); } QModelIndex AutomaticFilterModel::parent(const QModelIndex & /*index*/) const { return QModelIndex(); } bool AutomaticFilterModel::hasChildren(const QModelIndex &parent) const { return parent == QModelIndex(); } int AutomaticFilterModel::rowCount(const QModelIndex & /*parent*/) const { return mFilters.count(); } int AutomaticFilterModel::columnCount(const QModelIndex & /*parent*/) const { return 2; } QVariant AutomaticFilterModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } if (role == Qt::DisplayRole && index.row() < mFilters.count()) switch (index.column()) { case 0: return QVariant(mFilters[index.row()].filterName); case 1: return QVariant(mFilters[index.row()].filterURL); default: return QVariant("?"); } else if (role == Qt::CheckStateRole && index.column() == 0 && index.row() < mFilters.count()) { return mFilters[index.row()].enableFilter ? Qt::Checked : Qt::Unchecked; } else { return QVariant(); } } bool AutomaticFilterModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role == Qt::CheckStateRole && index.column() == 0 && index.row() < mFilters.count()) { mFilters[index.row()].enableFilter = static_cast(value.toInt()) == Qt::Checked; emit dataChanged(index, index); emit changed(true); return true; } return false; } QVariant AutomaticFilterModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole || orientation != Qt::Horizontal) { return QVariant(); } switch (section) { case 0: return QVariant(i18n("Name")); case 1: return QVariant(i18n("URL")); default: return QVariant("?"); } } Qt::ItemFlags AutomaticFilterModel::flags(const QModelIndex &index) const { Qt::ItemFlags rc = Qt::ItemIsSelectable | Qt::ItemIsEnabled; if (index.column() == 0) { rc |= Qt::ItemIsUserCheckable; } return rc; } diff --git a/settings/konqhtml/generalopts.cpp b/settings/konqhtml/generalopts.cpp index ec3b8c359..2d97fbf40 100644 --- a/settings/konqhtml/generalopts.cpp +++ b/settings/konqhtml/generalopts.cpp @@ -1,287 +1,287 @@ /* * Add here all general options - those that apply to both web browsing and filemanagement mode * * Copyright (c) Sven Radej 1998 * Copyright (c) David Faure 1998 * Copyright (c) 2001 Waldo Bastian * Copyright (c) 2007 Nick Shaforostoff * */ // Own #include "generalopts.h" // Qt #include #include #include #include #include #include #include #include #include #include // KDE #include #include #include #include #include // Local #include "ui_advancedTabOptions.h" // Keep in sync with konqueror.kcfg static const char DEFAULT_STARTPAGE[] = "about:konqueror"; static const char DEFAULT_HOMEPAGE[] = "https://www.kde.org/"; // Keep in sync with the order in the combo enum StartPage { ShowAboutPage, ShowStartUrlPage, ShowBlankPage, ShowBookmarksPage }; //----------------------------------------------------------------------------- KKonqGeneralOptions::KKonqGeneralOptions(QWidget *parent, const QVariantList &) : KCModule(parent) { m_pConfig = KSharedConfig::openConfig(QStringLiteral("konquerorrc"), KConfig::NoGlobals); QVBoxLayout *lay = new QVBoxLayout(this); - lay->setMargin(0); + lay->setContentsMargins(0, 0, 0, 0); addHomeUrlWidgets(lay); QGroupBox *tabsGroup = new QGroupBox(i18n("Tabbed Browsing")); tabOptions = new Ui_advancedTabOptions; tabOptions->setupUi(tabsGroup); connect(tabOptions->m_pShowMMBInTabs, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pDynamicTabbarHide, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pNewTabsInBackground, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pOpenAfterCurrentPage, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pTabConfirm, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pTabCloseActivatePrevious, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pPermanentCloseButton, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pKonquerorTabforExternalURL, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pPopupsWithinTabs, SIGNAL(toggled(bool)), SLOT(slotChanged())); connect(tabOptions->m_pMiddleClickClose, SIGNAL(toggled(bool)), SLOT(slotChanged())); lay->addWidget(tabsGroup); emit changed(false); } void KKonqGeneralOptions::addHomeUrlWidgets(QVBoxLayout *lay) { QFormLayout *formLayout = new QFormLayout; lay->addLayout(formLayout); QLabel *startLabel = new QLabel(i18nc("@label:listbox", "When &Konqueror starts:"), this); QWidget *containerWidget = new QWidget(this); QHBoxLayout *hboxLayout = new QHBoxLayout(containerWidget); - hboxLayout->setMargin(0); + hboxLayout->setContentsMargins(0, 0, 0, 0); formLayout->addRow(startLabel, containerWidget); m_startCombo = new QComboBox(this); m_startCombo->setEditable(false); m_startCombo->addItem(i18nc("@item:inlistbox", "Show Introduction Page"), ShowAboutPage); m_startCombo->addItem(i18nc("@item:inlistbox", "Show My Start Page"), ShowStartUrlPage); m_startCombo->addItem(i18nc("@item:inlistbox", "Show Blank Page"), ShowBlankPage); m_startCombo->addItem(i18nc("@item:inlistbox", "Show My Bookmarks"), ShowBookmarksPage); startLabel->setBuddy(m_startCombo); connect(m_startCombo, SIGNAL(currentIndexChanged(int)), SLOT(slotChanged())); hboxLayout->addWidget(m_startCombo); startURL = new QLineEdit(this); startURL->setWindowTitle(i18nc("@title:window", "Select Start Page")); hboxLayout->addWidget(startURL); connect(startURL, SIGNAL(textChanged(QString)), SLOT(slotChanged())); QString startstr = i18n("This is the URL of the web page " "Konqueror will show when starting."); startURL->setWhatsThis(startstr); connect(m_startCombo, static_cast(&QComboBox::currentIndexChanged), this, [this](int idx) { startURL->setEnabled(idx == ShowStartUrlPage); }); startURL->setEnabled(false); //// QLabel *label = new QLabel(i18n("Home page:"), this); homeURL = new QLineEdit(this); homeURL->setWindowTitle(i18nc("@title:window", "Select Home Page")); formLayout->addRow(label, homeURL); connect(homeURL, SIGNAL(textChanged(QString)), SLOT(slotChanged())); label->setBuddy(homeURL); QString homestr = i18n("This is the URL of the web page where " "Konqueror will jump to when " "the \"Home\" button is pressed."); label->setWhatsThis(homestr); homeURL->setWhatsThis(homestr); //// QLabel *webLabel = new QLabel(i18n("Default web browser engine:"), this); m_webEngineCombo = new QComboBox(this); m_webEngineCombo->setEditable(false); m_webEngineCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents); formLayout->addRow(webLabel, m_webEngineCombo); webLabel->setBuddy(m_webEngineCombo); connect(m_webEngineCombo, SIGNAL(currentIndexChanged(int)), SLOT(slotChanged())); } KKonqGeneralOptions::~KKonqGeneralOptions() { delete tabOptions; } static StartPage urlToStartPageEnum(const QString &startUrl) { if (startUrl == QLatin1String("about:blank")) { return ShowBlankPage; } if (startUrl == QLatin1String("about:") || startUrl == QLatin1String("about:konqueror")) { return ShowAboutPage; } if (startUrl == QLatin1String("bookmarks:") || startUrl == QLatin1String("bookmarks:/")) { return ShowBookmarksPage; } return ShowStartUrlPage; } static QString startPageEnumToUrl(StartPage startPage) { switch (startPage) { case ShowBlankPage: return QStringLiteral("about:blank"); case ShowAboutPage: return QStringLiteral("about:konqueror"); case ShowBookmarksPage: return QStringLiteral("bookmarks:/"); case ShowStartUrlPage: return QString(); } return QString(); } void KKonqGeneralOptions::load() { KConfigGroup userSettings(m_pConfig, "UserSettings"); const QUrl homeUrl(QUrl(userSettings.readEntry("HomeURL", DEFAULT_HOMEPAGE))); const QUrl startUrl(QUrl(userSettings.readEntry("StartURL", DEFAULT_STARTPAGE))); homeURL->setText(homeUrl.toString()); startURL->setText(startUrl.toString()); const StartPage startPage = urlToStartPageEnum(startUrl.toString()); const int startComboIndex = m_startCombo->findData(startPage); Q_ASSERT(startComboIndex != -1); m_startCombo->setCurrentIndex(startComboIndex); m_webEngineCombo->clear(); // ## Well, the problem with using the trader to find the available parts, is that if a user // removed a part in keditfiletype text/html, it won't be in the list anymore. Oh well. const KService::List partOfferList = KMimeTypeTrader::self()->query(QStringLiteral("text/html"), QStringLiteral("KParts/ReadOnlyPart"), QStringLiteral("not ('KParts/ReadWritePart' in ServiceTypes)")); // Sorted list, so the first one is the preferred one, no need for a setCurrentIndex. Q_FOREACH (const KService::Ptr partService, partOfferList) { // We want only the HTML-capable parts, not any text/plain part (via inheritance) // This is a small "private inheritance" hack, pending a more general solution if (!partService->hasMimeType(QStringLiteral("text/plain"))) { m_webEngineCombo->addItem(QIcon::fromTheme(partService->icon()), partService->name(), QVariant(partService->storageId())); } } KConfigGroup cg(m_pConfig, "FMSettings"); // ### what a wrong group name for these settings... tabOptions->m_pShowMMBInTabs->setChecked(cg.readEntry("MMBOpensTab", true)); tabOptions->m_pDynamicTabbarHide->setChecked(!(cg.readEntry("AlwaysTabbedMode", false))); tabOptions->m_pNewTabsInBackground->setChecked(!(cg.readEntry("NewTabsInFront", false))); tabOptions->m_pOpenAfterCurrentPage->setChecked(cg.readEntry("OpenAfterCurrentPage", false)); tabOptions->m_pPermanentCloseButton->setChecked(cg.readEntry("PermanentCloseButton", true)); tabOptions->m_pKonquerorTabforExternalURL->setChecked(cg.readEntry("KonquerorTabforExternalURL", false)); tabOptions->m_pPopupsWithinTabs->setChecked(cg.readEntry("PopupsWithinTabs", false)); tabOptions->m_pTabCloseActivatePrevious->setChecked(cg.readEntry("TabCloseActivatePrevious", false)); tabOptions->m_pMiddleClickClose->setChecked(cg.readEntry("MouseMiddleClickClosesTab", false)); cg = KConfigGroup(m_pConfig, "Notification Messages"); tabOptions->m_pTabConfirm->setChecked(!cg.hasKey("MultipleTabConfirm")); } void KKonqGeneralOptions::defaults() { homeURL->setText(QUrl(DEFAULT_HOMEPAGE).toString()); startURL->setText(QUrl(DEFAULT_STARTPAGE).toString()); bool old = m_pConfig->readDefaults(); m_pConfig->setReadDefaults(true); load(); m_pConfig->setReadDefaults(old); } void KKonqGeneralOptions::save() { KConfigGroup userSettings(m_pConfig, "UserSettings"); const int startComboIndex = m_startCombo->currentIndex(); const int choice = m_startCombo->itemData(startComboIndex).toInt(); QString startUrl(startPageEnumToUrl(static_cast(choice))); if (startUrl.isEmpty()) startUrl = startURL->text(); userSettings.writeEntry("StartURL", startUrl); userSettings.writeEntry("HomeURL", homeURL->text()); if (m_webEngineCombo->currentIndex() > 0) { // The user changed the preferred web engine, save into mimeapps.list. const QString preferredWebEngine = m_webEngineCombo->itemData(m_webEngineCombo->currentIndex()).toString(); //qDebug() << "preferredWebEngine=" << preferredWebEngine; KSharedConfig::Ptr profile = KSharedConfig::openConfig(QStringLiteral("mimeapps.list"), KConfig::NoGlobals, QStandardPaths::ConfigLocation); KConfigGroup addedServices(profile, "Added KDE Service Associations"); Q_FOREACH (const QString &mimeType, QStringList() << "text/html" << "application/xhtml+xml" << "application/xml") { QStringList services = addedServices.readXdgListEntry(mimeType); services.removeAll(preferredWebEngine); services.prepend(preferredWebEngine); // make it the preferred one addedServices.writeXdgListEntry(mimeType, services); } profile->sync(); // kbuildsycoca is the one reading mimeapps.list, so we need to run it now KBuildSycocaProgressDialog::rebuildKSycoca(this); } KConfigGroup cg(m_pConfig, "FMSettings"); cg.writeEntry("MMBOpensTab", tabOptions->m_pShowMMBInTabs->isChecked()); cg.writeEntry("AlwaysTabbedMode", !(tabOptions->m_pDynamicTabbarHide->isChecked())); cg.writeEntry("NewTabsInFront", !(tabOptions->m_pNewTabsInBackground->isChecked())); cg.writeEntry("OpenAfterCurrentPage", tabOptions->m_pOpenAfterCurrentPage->isChecked()); cg.writeEntry("PermanentCloseButton", tabOptions->m_pPermanentCloseButton->isChecked()); cg.writeEntry("KonquerorTabforExternalURL", tabOptions->m_pKonquerorTabforExternalURL->isChecked()); cg.writeEntry("PopupsWithinTabs", tabOptions->m_pPopupsWithinTabs->isChecked()); cg.writeEntry("TabCloseActivatePrevious", tabOptions->m_pTabCloseActivatePrevious->isChecked()); cg.writeEntry("MouseMiddleClickClosesTab", tabOptions->m_pMiddleClickClose->isChecked()); cg.sync(); // It only matters whether the key is present, its value has no meaning cg = KConfigGroup(m_pConfig, "Notification Messages"); if (tabOptions->m_pTabConfirm->isChecked()) { cg.deleteEntry("MultipleTabConfirm"); } else { cg.writeEntry("MultipleTabConfirm", true); } // Send signal to all konqueror instances QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration")); QDBusConnection::sessionBus().send(message); emit changed(false); } void KKonqGeneralOptions::slotChanged() { emit changed(true); } diff --git a/settings/konqhtml/javaopts.cpp b/settings/konqhtml/javaopts.cpp index 0b9444a13..67558d112 100644 --- a/settings/konqhtml/javaopts.cpp +++ b/settings/konqhtml/javaopts.cpp @@ -1,343 +1,343 @@ /* * Copyright (c) Martin R. Jones 1996 * Copyright (c) Bernd Wuebben 1998 * * Copyright (c) Torben Weis 1998 * KControl port & modifications * * Copyright (c) David Faure 1998 * End of the KControl port, added 'kfmclient configure' call. * * Copyright (c) Kalle Dalheimer 2000 * New configuration scheme for Java/JavaScript * * Copyright (c) Daniel Molkentin 2000 * Redesign and cleanup * * Copyright (c) Leo Savernik 2002-2003 * Big changes to accommodate per-domain settings * */ // Own #include "javaopts.h" // Qt #include #include #include // KDE #include #include #include #include #include #include #include #include // Local #include "htmlopts.h" #include "policydlg.h" // == class JavaPolicies ===== JavaPolicies::JavaPolicies(const KSharedConfig::Ptr &config, const QString &group, bool global, const QString &domain) : Policies(config, group, global, domain, QStringLiteral("java."), QStringLiteral("EnableJava")) { } /* JavaPolicies::JavaPolicies() : Policies(0,QString(),false, QString(),QString(),QString()) { } */ JavaPolicies::~JavaPolicies() { } // == class KJavaOptions ===== KJavaOptions::KJavaOptions(const KSharedConfig::Ptr &config, const QString &group, QWidget *parent) : KCModule(parent), _removeJavaScriptDomainAdvice(false), m_pConfig(config), m_groupname(group), java_global_policies(config, group, true), _removeJavaDomainSettings(false) { QVBoxLayout *toplevel = new QVBoxLayout(this); /*************************************************************************** ********************* Global Settings ************************************* **************************************************************************/ enableJavaGloballyCB = new QCheckBox(i18n("Enable Ja&va globally"), this); connect(enableJavaGloballyCB, &QAbstractButton::clicked, this, &KJavaOptions::slotChanged); connect(enableJavaGloballyCB, &QAbstractButton::clicked, this, &KJavaOptions::toggleJavaControls); toplevel->addWidget(enableJavaGloballyCB); /*************************************************************************** ***************** Domain Specific Settings ******************************** **************************************************************************/ domainSpecific = new JavaDomainListView(m_pConfig, m_groupname, this, this); connect(domainSpecific, &DomainListView::changed, this, &KJavaOptions::slotChanged); toplevel->addWidget(domainSpecific, 2); /*************************************************************************** ***************** Java Runtime Settings *********************************** **************************************************************************/ QGroupBox *javartGB = new QGroupBox(i18n("Java Runtime Settings"), this); QFormLayout *laygroup1 = new QFormLayout(javartGB); toplevel->addWidget(javartGB); javaSecurityManagerCB = new QCheckBox(i18n("&Use security manager"), this); laygroup1->addRow(javaSecurityManagerCB); connect(javaSecurityManagerCB, &QAbstractButton::toggled, this, &KJavaOptions::slotChanged); useKioCB = new QCheckBox(i18n("Use &KIO"), this); laygroup1->addRow(useKioCB); connect(useKioCB, &QAbstractButton::toggled, this, &KJavaOptions::slotChanged); enableShutdownCB = new QCheckBox(i18n("Shu&tdown applet server when inactive for more than"), this); connect(enableShutdownCB, &QAbstractButton::toggled, this, &KJavaOptions::slotChanged); connect(enableShutdownCB, &QAbstractButton::clicked, this, &KJavaOptions::toggleJavaControls); QWidget *secondsHB = new QWidget(javartGB); QHBoxLayout *secondsHBHBoxLayout = new QHBoxLayout(secondsHB); - secondsHBHBoxLayout->setMargin(0); + secondsHBHBoxLayout->setContentsMargins(0, 0, 0, 0); laygroup1->addWidget(secondsHB); serverTimeoutSB = new KIntNumInput(secondsHB); secondsHBHBoxLayout->addWidget(serverTimeoutSB); serverTimeoutSB->setRange(0, 1000, 5); serverTimeoutSB->setSuffix(ki18np(" second", " seconds")); connect(serverTimeoutSB, &KIntNumInput::valueChanged, this, &KJavaOptions::slotChanged); laygroup1->addRow(enableShutdownCB, serverTimeoutSB); pathED = new KUrlRequester(this); connect(pathED, &KUrlRequester::textChanged, this, &KJavaOptions::slotChanged); laygroup1->addRow(i18n("&Path to Java executable, or 'java':"), pathED); addArgED = new QLineEdit(this); connect(addArgED, &QLineEdit::textChanged, this, &KJavaOptions::slotChanged); laygroup1->addRow(i18n("Additional Java a&rguments:"), addArgED); /*************************************************************************** ********************** WhatsThis? items *********************************** **************************************************************************/ enableJavaGloballyCB->setWhatsThis(i18n("Enables the execution of scripts written in Java " "that can be contained in HTML pages. " "Note that, as with any browser, enabling active contents can be a security problem.")); QString wtstr = i18n("

This box contains the domains and hosts you have set " "a specific Java policy for. This policy will be used " "instead of the default policy for enabling or disabling Java applets on pages sent by these " "domains or hosts.

Select a policy and use the controls on " "the right to modify it.

"); domainSpecific->listView()->setWhatsThis(wtstr); #if 0 domainSpecific->importButton()->setWhatsThis(i18n("Click this button to choose the file that contains " "the Java policies. These policies will be merged " "with the existing ones. Duplicate entries are ignored.")); domainSpecific->exportButton()->setWhatsThis(i18n("Click this button to save the Java policy to a zipped " "file. The file, named java_policy.tgz, will be " "saved to a location of your choice.")); #endif domainSpecific->setWhatsThis(i18n("Here you can set specific Java policies for any particular " "host or domain. To add a new policy, simply click the New... " "button and supply the necessary information requested by the " "dialog box. To change an existing policy, click on the Change... " "button and choose the new policy from the policy dialog box. Clicking " "on the Delete button will remove the selected policy, causing the default " "policy setting to be used for that domain.")); #if 0 "The Import and Export " "button allows you to easily share your policies with other people by allowing " "you to save and retrieve them from a zipped file.")); #endif javaSecurityManagerCB->setWhatsThis(i18n("Enabling the security manager will cause the jvm to run with a Security " "Manager in place. This will keep applets from being able to read and " "write to your file system, creating arbitrary sockets, and other actions " "which could be used to compromise your system. Disable this option at your " "own risk. You can modify your $HOME/.java.policy file with the Java " "policytool utility to give code downloaded from certain sites more " "permissions.")); useKioCB->setWhatsThis(i18n("Enabling this will cause the jvm to use KIO for network transport ")); pathED->setWhatsThis(i18n("Enter the path to the java executable. If you want to use the jre in " "your path, simply leave it as 'java'. If you need to use a different jre, " "enter the path to the java executable (e.g. /usr/lib/jdk/bin/java), " "or the path to the directory that contains 'bin/java' (e.g. /opt/IBMJava2-13).")); addArgED->setWhatsThis(i18n("If you want special arguments to be passed to the virtual machine, enter them here.")); QString shutdown = i18n("When all the applets have been destroyed, the applet server should shut down. " "However, starting the jvm takes a lot of time. If you would like to " "keep the java process running while you are " "browsing, you can set the timeout value to whatever you like. To keep " "the java process running for the whole time that the konqueror process is, " "leave the Shutdown Applet Server checkbox unchecked."); serverTimeoutSB->setWhatsThis(shutdown); enableShutdownCB->setWhatsThis(shutdown); } void KJavaOptions::load() { // *** load *** java_global_policies.load(); bool bJavaGlobal = java_global_policies.isFeatureEnabled(); bool bSecurityManager = m_pConfig->group(m_groupname).readEntry("UseSecurityManager", true); bool bUseKio = m_pConfig->group(m_groupname).readEntry("UseKio", false); bool bServerShutdown = m_pConfig->group(m_groupname).readEntry("ShutdownAppletServer", true); int serverTimeout = m_pConfig->group(m_groupname).readEntry("AppletServerTimeout", 60); QString sJavaPath = m_pConfig->group(m_groupname).readPathEntry("JavaPath", QStringLiteral("java")); if (sJavaPath == QLatin1String("/usr/lib/jdk")) { sJavaPath = QStringLiteral("java"); } if (m_pConfig->group(m_groupname).hasKey("JavaDomains")) { domainSpecific->initialize(m_pConfig->group(m_groupname).readEntry("JavaDomains", QStringList())); } else if (m_pConfig->group(m_groupname).hasKey("JavaDomainSettings")) { domainSpecific->updateDomainListLegacy(m_pConfig->group(m_groupname).readEntry("JavaDomainSettings", QStringList())); _removeJavaDomainSettings = true; } else { domainSpecific->updateDomainListLegacy(m_pConfig->group(m_groupname).readEntry("JavaScriptDomainAdvice", QStringList())); _removeJavaScriptDomainAdvice = true; } // *** apply to GUI *** enableJavaGloballyCB->setChecked(bJavaGlobal); javaSecurityManagerCB->setChecked(bSecurityManager); useKioCB->setChecked(bUseKio); addArgED->setText(m_pConfig->group(m_groupname).readEntry("JavaArgs")); pathED->lineEdit()->setText(sJavaPath); enableShutdownCB->setChecked(bServerShutdown); serverTimeoutSB->setValue(serverTimeout); toggleJavaControls(); emit changed(false); } void KJavaOptions::defaults() { java_global_policies.defaults(); enableJavaGloballyCB->setChecked(false); javaSecurityManagerCB->setChecked(true); useKioCB->setChecked(false); pathED->lineEdit()->setText(QStringLiteral("java")); addArgED->setText(QLatin1String("")); enableShutdownCB->setChecked(true); serverTimeoutSB->setValue(60); toggleJavaControls(); emit changed(true); } void KJavaOptions::save() { java_global_policies.save(); m_pConfig->group(m_groupname).writeEntry("JavaArgs", addArgED->text()); m_pConfig->group(m_groupname).writePathEntry("JavaPath", pathED->lineEdit()->text()); m_pConfig->group(m_groupname).writeEntry("UseSecurityManager", javaSecurityManagerCB->isChecked()); m_pConfig->group(m_groupname).writeEntry("UseKio", useKioCB->isChecked()); m_pConfig->group(m_groupname).writeEntry("ShutdownAppletServer", enableShutdownCB->isChecked()); m_pConfig->group(m_groupname).writeEntry("AppletServerTimeout", serverTimeoutSB->value()); domainSpecific->save(m_groupname, QStringLiteral("JavaDomains")); if (_removeJavaDomainSettings) { m_pConfig->group(m_groupname).deleteEntry("JavaDomainSettings"); _removeJavaDomainSettings = false; } // sync moved to KJSParts::save // m_pConfig->sync(); emit changed(false); } void KJavaOptions::slotChanged() { emit changed(true); } void KJavaOptions::toggleJavaControls() { bool isEnabled = true; //enableJavaGloballyCB->isChecked(); java_global_policies.setFeatureEnabled(enableJavaGloballyCB->isChecked()); javaSecurityManagerCB->setEnabled(isEnabled); useKioCB->setEnabled(isEnabled); addArgED->setEnabled(isEnabled); pathED->setEnabled(isEnabled); enableShutdownCB->setEnabled(isEnabled); serverTimeoutSB->setEnabled(enableShutdownCB->isChecked() && isEnabled); } // == class JavaDomainListView ===== JavaDomainListView::JavaDomainListView(KSharedConfig::Ptr config, const QString &group, KJavaOptions *options, QWidget *parent) : DomainListView(config, i18nc("@title:group", "Doma&in-Specific"), parent), group(group), options(options) { } JavaDomainListView::~JavaDomainListView() { } void JavaDomainListView::updateDomainListLegacy(const QStringList &domainConfig) { domainSpecificLV->clear(); JavaPolicies pol(config, group, false); pol.defaults(); const QStringList::ConstIterator itEnd = domainConfig.end(); for (QStringList::ConstIterator it = domainConfig.begin(); it != itEnd; ++it) { QString domain; KParts::HtmlSettingsInterface::JavaScriptAdvice javaAdvice; KParts::HtmlSettingsInterface::JavaScriptAdvice javaScriptAdvice; KParts::HtmlSettingsInterface::splitDomainAdvice(*it, domain, javaAdvice, javaScriptAdvice); if (javaAdvice != KParts::HtmlSettingsInterface::JavaScriptDunno) { QTreeWidgetItem *index = new QTreeWidgetItem(domainSpecificLV, QStringList() << domain << i18n(KParts::HtmlSettingsInterface::javascriptAdviceToText(javaAdvice))); pol.setDomain(domain); pol.setFeatureEnabled(javaAdvice != KParts::HtmlSettingsInterface::JavaScriptReject); domainPolicies[index] = new JavaPolicies(pol); } } } void JavaDomainListView::setupPolicyDlg(PushButton trigger, PolicyDialog &pDlg, Policies *pol) { QString caption; switch (trigger) { case AddButton: caption = i18nc("@title:window", "New Java Policy"); pol->setFeatureEnabled(!options->enableJavaGloballyCB->isChecked()); break; case ChangeButton: caption = i18nc("@title:window", "Change Java Policy"); break; default:; // inhibit gcc warning }/*end switch*/ pDlg.setCaption(caption); pDlg.setFeatureEnabledLabel(i18n("&Java policy:")); pDlg.setFeatureEnabledWhatsThis(i18n("Select a Java policy for " "the above host or domain.")); pDlg.refresh(); } JavaPolicies *JavaDomainListView::createPolicies() { return new JavaPolicies(config, group, false); } JavaPolicies *JavaDomainListView::copyPolicies(Policies *pol) { return new JavaPolicies(*static_cast(pol)); } diff --git a/settings/konqhtml/policydlg.cpp b/settings/konqhtml/policydlg.cpp index b04172897..0f2da9fe1 100644 --- a/settings/konqhtml/policydlg.cpp +++ b/settings/konqhtml/policydlg.cpp @@ -1,146 +1,146 @@ /* * Copyright (C) < 2002 to whoever created and edited this file before * Copyright (C) 2002 Leo Savernik * Generalizing the policy dialog * */ // Own #include "policydlg.h" // Qt #include #include #include #include // KDE #include #include // Local #include "policies.h" PolicyDialog::PolicyDialog(Policies *policies, QWidget *parent, const char *name) : KDialog(parent), policies(policies) { setObjectName(name); setModal(true); setButtons(Ok | Cancel); QFrame *main = new QFrame(this); setMainWidget(main); insertIdx = 1; // index where to insert additional panels topl = new QVBoxLayout(main); - topl->setMargin(0); + topl->setContentsMargins(0, 0, 0, 0); QGridLayout *grid = new QGridLayout(); topl->addLayout(grid); grid->setColumnStretch(1, 1); QLabel *l = new QLabel(i18n("&Host or domain name:"), main); grid->addWidget(l, 0, 0); le_domain = new QLineEdit(main); l->setBuddy(le_domain); grid->addWidget(le_domain, 0, 1); connect(le_domain, SIGNAL(textChanged(QString)), SLOT(slotTextChanged(QString))); le_domain->setWhatsThis(i18n("Enter the name of a host (like www.kde.org) " "or a domain, starting with a dot (like .kde.org or .org)")); l_feature_policy = new QLabel(main); grid->addWidget(l_feature_policy, 1, 0); cb_feature_policy = new QComboBox(main); l_feature_policy->setBuddy(cb_feature_policy); policy_values << i18n("Use Global") << i18n("Accept") << i18n("Reject"); cb_feature_policy->addItems(policy_values); grid->addWidget(cb_feature_policy, 1, 1); le_domain->setFocus(); enableButtonOk(!le_domain->text().isEmpty()); } PolicyDialog::FeatureEnabledPolicy PolicyDialog::featureEnabledPolicy() const { return (FeatureEnabledPolicy)cb_feature_policy->currentIndex(); } void PolicyDialog::slotTextChanged(const QString &text) { enableButtonOk(!text.isEmpty()); } void PolicyDialog::setDisableEdit(bool state, const QString &text) { le_domain->setText(text); le_domain->setEnabled(state); if (state) { cb_feature_policy->setFocus(); } } void PolicyDialog::refresh() { FeatureEnabledPolicy pol; if (policies->isFeatureEnabledPolicyInherited()) { pol = InheritGlobal; } else if (policies->isFeatureEnabled()) { pol = Accept; } else { pol = Reject; } cb_feature_policy->setCurrentIndex(pol); } void PolicyDialog::setFeatureEnabledLabel(const QString &text) { l_feature_policy->setText(text); } void PolicyDialog::setFeatureEnabledWhatsThis(const QString &text) { cb_feature_policy->setWhatsThis(text); } void PolicyDialog::addPolicyPanel(QWidget *panel) { topl->insertWidget(insertIdx++, panel); } QString PolicyDialog::featureEnabledPolicyText() const { int pol = cb_feature_policy->currentIndex(); if (pol >= 0 && pol < 3) { // Keep in sync with FeatureEnabledPolicy return policy_values[pol]; } else { return QString(); } } void PolicyDialog::accept() { if (le_domain->text().isEmpty()) { KMessageBox::information(nullptr, i18n("You must first enter a domain name.")); return; } FeatureEnabledPolicy pol = (FeatureEnabledPolicy) cb_feature_policy->currentIndex(); if (pol == InheritGlobal) { policies->inheritFeatureEnabledPolicy(); } else if (pol == Reject) { policies->setFeatureEnabled(false); } else { policies->setFeatureEnabled(true); } KDialog::accept(); } diff --git a/settings/performance/kcmperformance.cpp b/settings/performance/kcmperformance.cpp index cba6c4cb6..e39a50aa9 100644 --- a/settings/performance/kcmperformance.cpp +++ b/settings/performance/kcmperformance.cpp @@ -1,107 +1,107 @@ /* * Copyright (c) 2003 Lubos Lunak * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Own #include "kcmperformance.h" // Qt #include // KDE #include // Local #include "konqueror.h" #include "system.h" #include #include K_PLUGIN_FACTORY(KCMPerformanceConfigFactory, registerPlugin("performance"); registerPlugin("konqueror"); ) namespace KCMPerformance { Config::Config(QWidget *parent_P, const QVariantList &) : KCModule(parent_P) { setQuickHelp(i18n("

KDE Performance

" " You can configure settings that improve KDE performance here.")); QVBoxLayout *topLayout = new QVBoxLayout(this); QTabWidget *tabs = new QTabWidget(this); konqueror_widget = new Konqueror; connect(konqueror_widget, SIGNAL(changed()), SLOT(changed())); tabs->addTab(konqueror_widget, i18n("Konqueror")); system_widget = new SystemWidget; connect(system_widget, SIGNAL(changed()), SLOT(changed())); tabs->addTab(system_widget, i18n("System")); topLayout->addWidget(tabs); } void Config::load() { konqueror_widget->load(); system_widget->load(); } void Config::save() { konqueror_widget->save(); system_widget->save(); } void Config::defaults() { konqueror_widget->defaults(); system_widget->defaults(); } KonquerorConfig::KonquerorConfig(QWidget *parent_P, const QVariantList &) : KCModule(parent_P) { setQuickHelp(i18n("

Konqueror Performance

" " You can configure several settings that improve Konqueror performance here." " These include options for reusing already running instances" " and for keeping instances preloaded.")); QVBoxLayout *topLayout = new QVBoxLayout(this); - topLayout->setMargin(0); + topLayout->setContentsMargins(0, 0, 0, 0); widget = new Konqueror(this); connect(widget, SIGNAL(changed()), SLOT(changed())); topLayout->addWidget(widget); } void KonquerorConfig::load() { widget->load(); } void KonquerorConfig::save() { widget->save(); } void KonquerorConfig::defaults() { widget->defaults(); } } // namespace #include "kcmperformance.moc" diff --git a/settings/performance/konqueror.h b/settings/performance/konqueror.h index 783cb917d..1c0e6ec17 100644 --- a/settings/performance/konqueror.h +++ b/settings/performance/konqueror.h @@ -1,52 +1,52 @@ /* * Copyright (c) 2003 Lubos Lunak * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KCM_PERF_KONQUEROR_H #define _KCM_PERF_KONQUEROR_H #include "ui_konqueror_ui.h" namespace KCMPerformance { class Konqueror_ui : public QWidget, public Ui::Konqueror_ui { public: Konqueror_ui(QWidget *parent) : QWidget(parent) { setupUi(this); - layout()->setMargin(0); + layout()->setContentsMargins(0, 0, 0, 0); } }; class Konqueror : public Konqueror_ui { Q_OBJECT public: Konqueror(QWidget *parent_P = nullptr); void load(); void save(); void defaults(); Q_SIGNALS: void changed(); }; } // namespace #endif diff --git a/sidebar/history_module/kcmhistory.h b/sidebar/history_module/kcmhistory.h index 95be25a9a..5aa30510e 100644 --- a/sidebar/history_module/kcmhistory.h +++ b/sidebar/history_module/kcmhistory.h @@ -1,74 +1,74 @@ /* * kcmhistory.h * Copyright (c) 2002 Stephan Binner * * based on kcmtaskbar.h * Copyright (c) 2000 Kurt Granroth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software */ #ifndef __kcmhistory_h__ #define __kcmhistory_h__ #include #include "ui_history_dlg.h" class KonqHistoryManager; class KonqHistorySettings; class KonqSidebarHistoryDlg : public QWidget, public Ui::KonqSidebarHistoryDlg { public: KonqSidebarHistoryDlg(QWidget *parent) : QWidget(parent) { setupUi(this); - layout()->setMargin(0); + layout()->setContentsMargins(0, 0, 0, 0); } }; class HistorySidebarConfig : public KCModule { Q_OBJECT public: explicit HistorySidebarConfig(QWidget *parent = nullptr, const QVariantList &list = QVariantList()); void load(); void save(); void defaults(); QString quickHelp() const; private Q_SLOTS: void configChanged(); void slotGetFontNewer(); void slotGetFontOlder(); void slotExpireChanged(); void slotNewerChanged(int); void slotOlderChanged(int); void slotClearHistory(); private: QFont m_fontNewer; QFont m_fontOlder; KonqSidebarHistoryDlg *dialog; KonqHistorySettings *m_settings; KonqHistoryManager *mgr; }; #endif diff --git a/sidebar/sidebar_widget.cpp b/sidebar/sidebar_widget.cpp index 7783baaac..125625ac5 100644 --- a/sidebar/sidebar_widget.cpp +++ b/sidebar/sidebar_widget.cpp @@ -1,848 +1,848 @@ /*************************************************************************** sidebar_widget.cpp ------------------- begin : Sat June 2 16:25:27 CEST 2001 copyright : (C) 2001 Joseph Wenninger email : jowenn@kde.org Copyright (c) 2009 David Faure ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ // Own #include "sidebar_widget.h" #include "konqmultitabbar.h" // std #include // Qt #include #include #include #include #include #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void Sidebar_Widget::aboutToShowAddMenu() { m_addMenu->clear(); m_pluginForAction.clear(); QList existingGroups; // Collect the "already shown" modules for (int i = 0; i < m_buttons.count(); ++i) { existingGroups.append(m_buttons[i].configFile->group("Desktop Entry")); } // We need to instantiate all available plugins // And since the web module isn't in the default entries at all, we can't just collect // the plugins there. const KService::List list = m_moduleManager.availablePlugins(); Q_FOREACH (const KService::Ptr &service, list) { if (!service->isValid()) { continue; } KPluginLoader loader(*service); KPluginFactory *factory = loader.factory(); if (!factory) { kWarning() << "Error loading plugin" << service->desktopEntryName() << loader.errorString(); } else { KonqSidebarPlugin *plugin = factory->create(this); if (!plugin) { kWarning() << "Error creating KonqSidebarPlugin from" << service->desktopEntryName(); } else { const QList actions = plugin->addNewActions(&m_addMenuActionGroup, existingGroups, QVariant()); // Remember which plugin the action came from. // We can't use QAction::setData for that, because we let plugins use that already. Q_FOREACH (QAction *action, actions) { m_pluginForAction.insert(action, plugin); } m_addMenu->addActions(actions); } } } m_addMenu->addSeparator(); m_addMenu->addAction(i18n("Rollback to System Default"), this, SLOT(slotRollback())); } void Sidebar_Widget::triggeredAddMenu(QAction *action) { KonqSidebarPlugin *plugin = m_pluginForAction.value(action); m_pluginForAction.clear(); // save memory QString templ = plugin->templateNameForNewModule(action->data(), QVariant()); Q_ASSERT(!templ.contains('/')); if (templ.isEmpty()) { return; } const QString myFile = m_moduleManager.addModuleFromTemplate(templ); if (myFile.isEmpty()) { return; } kDebug() << myFile << "filename=" << templ; KDesktopFile df(myFile); KConfigGroup configGroup = df.desktopGroup(); const bool ok = plugin->createNewModule(action->data(), configGroup, this, QVariant()); df.sync(); if (ok) { m_moduleManager.moduleAdded(templ /*contains the final filename*/); // TODO only add the new button QTimer::singleShot(0, this, SLOT(updateButtons())); } else { QFile::remove(myFile); } } Sidebar_Widget::Sidebar_Widget(QWidget *parent, KParts::ReadOnlyPart *par, const QString ¤tProfile) : QWidget(parent), m_partParent(par), m_addMenuActionGroup(this), m_config(new KConfigGroup(KSharedConfig::openConfig("konqsidebartngrc"), currentProfile)), m_moduleManager(m_config) { m_somethingVisible = false; m_noUpdate = false; m_layout = 0; m_currentButtonIndex = -1; m_activeModule = 0; //m_userMovedSplitter = false; //kDebug() << "**** Sidebar_Widget:SidebarWidget()"; m_hasStoredUrl = false; m_latestViewed = -1; setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); m_area = new QSplitter(Qt::Vertical, this); m_area->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); m_area->setMinimumWidth(0); m_buttonBar = new KonqMultiTabBar(this); connect(m_buttonBar, SIGNAL(urlsDropped(QList)), this, SLOT(slotUrlsDropped(QList))); m_menu = new QMenu(this); m_menu->setIcon(QIcon::fromTheme("configure")); m_menu->setTitle(i18n("Configure Sidebar")); m_addMenu = m_menu->addMenu(i18n("Add New")); connect(m_addMenu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowAddMenu())); connect(&m_addMenuActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(triggeredAddMenu(QAction*))); m_menu->addSeparator(); m_multiViews = m_menu->addAction(i18n("Multiple Views"), this, SLOT(slotMultipleViews())); m_multiViews->setCheckable(true); m_showTabLeft = m_menu->addAction(i18n("Show Tabs Left"), this, SLOT(slotShowTabsLeft())); m_showConfigButton = m_menu->addAction(i18n("Show Configuration Button"), this, SLOT(slotShowConfigurationButton())); m_showConfigButton->setCheckable(true); m_menu->addSeparator(); m_menu->addAction(QIcon::fromTheme("window-close"), i18n("Close Sidebar"), par, SLOT(deleteLater())); connect(m_menu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowConfigMenu())); m_configTimer.setSingleShot(true); connect(&m_configTimer, SIGNAL(timeout()), this, SLOT(saveConfig())); readConfig(); m_openViews = m_config->readEntry("OpenViews", QStringList()); m_savedWidth = m_config->readEntry("SavedWidth", 200); m_somethingVisible = !m_openViews.isEmpty(); doLayout(); QTimer::singleShot(0, this, SLOT(createButtons())); } bool Sidebar_Widget::createDirectModule(const QString &templ, const QString &name, const QUrl &url, const QString &icon, const QString &module, const QString &treeModule) { QString filename = templ; const QString myFile = m_moduleManager.addModuleFromTemplate(filename); if (!myFile.isEmpty()) { kDebug() << "Writing" << myFile; KDesktopFile df(myFile); KConfigGroup scf = df.desktopGroup(); scf.writeEntry("Type", "Link"); scf.writePathEntry("URL", url.url()); scf.writeEntry("Icon", icon); scf.writeEntry("Name", name); scf.writeEntry("X-KDE-KonqSidebarModule", module); if (!treeModule.isEmpty()) { scf.writeEntry("X-KDE-TreeModule", treeModule); } scf.sync(); m_moduleManager.moduleAdded(filename); QTimer::singleShot(0, this, SLOT(updateButtons())); return true; } return false; } void Sidebar_Widget::addWebSideBar(const QUrl &url, const QString &name) { //kDebug() << "Web sidebar entry to be added: " << url << name << endl; // Look for existing ones with this URL const QStringList files = m_moduleManager.localModulePaths("websidebarplugin*.desktop"); Q_FOREACH (const QString &file, files) { KConfig _scf(file, KConfig::SimpleConfig); KConfigGroup scf(&_scf, "Desktop Entry"); if (scf.readPathEntry("URL", QString()) == url.url()) { // We already have this one! KMessageBox::information(this, i18n("This entry already exists.")); return; } } createDirectModule("websidebarplugin%1.desktop", name, url, "internet-web-browser", "konqsidebar_web"); } void Sidebar_Widget::slotRollback() { if (KMessageBox::warningContinueCancel(this, i18n("This removes all your entries from the sidebar and adds the system default ones.
This procedure is irreversible
Do you want to proceed?
")) == KMessageBox::Continue) { m_moduleManager.rollbackToDefault(); QTimer::singleShot(0, this, SLOT(updateButtons())); } } void Sidebar_Widget::saveConfig() { m_config->writeEntry("SingleWidgetMode", m_singleWidgetMode); m_config->writeEntry("ShowExtraButtons", m_showExtraButtons); m_config->writeEntry("ShowTabsLeft", m_showTabsLeft); m_config->writeEntry("HideTabs", m_hideTabs); m_config->writeEntry("SavedWidth", m_savedWidth); m_config->sync(); } void Sidebar_Widget::doLayout() { delete m_layout; m_layout = new QHBoxLayout(this); - m_layout->setMargin(0); + m_layout->setContentsMargins(0, 0, 0, 0); m_layout->setSpacing(0); if (m_showTabsLeft) { m_layout->addWidget(m_buttonBar); m_layout->addWidget(m_area); m_buttonBar->setPosition(KMultiTabBar::Left); } else { m_layout->addWidget(m_area); m_layout->addWidget(m_buttonBar); m_buttonBar->setPosition(KMultiTabBar::Right); } m_layout->activate(); if (m_hideTabs) { m_buttonBar->hide(); } else { m_buttonBar->show(); } } void Sidebar_Widget::aboutToShowConfigMenu() { m_multiViews->setChecked(!m_singleWidgetMode); m_showTabLeft->setText(m_showTabsLeft ? i18n("Show Tabs Right") : i18n("Show Tabs Left")); m_showConfigButton->setChecked(m_showExtraButtons); } void Sidebar_Widget::slotSetName() { // Set a name for this sidebar tab bool ok; // Pop up the dialog asking the user for name. const QString name = KInputDialog::getText(i18nc("@title:window", "Set Name"), i18n("Enter the name:"), currentButtonInfo().displayName, &ok, this); if (ok) { m_moduleManager.setModuleName(currentButtonInfo().file, name); // Update the buttons with a QTimer (why?) // Because we're in the RMB of a button that updateButtons deletes... // TODO: update THAT button only. QTimer::singleShot(0, this, SLOT(updateButtons())); } } // TODO make this less generic. Bookmarks and history have no URL, only folders and websidebars do. // So this should move to the modules that need it. void Sidebar_Widget::slotSetURL() { KUrlRequesterDialog dlg(currentButtonInfo().URL, i18n("Enter a URL:"), this); dlg.urlRequester()->setMode(KFile::Directory); if (dlg.exec()) { m_moduleManager.setModuleUrl(currentButtonInfo().file, dlg.selectedUrl()); // TODO: update THAT button only. QTimer::singleShot(0, this, SLOT(updateButtons())); } } void Sidebar_Widget::slotSetIcon() { // kicd.setStrictIconSize(true); const QString iconname = KIconDialog::getIcon(KIconLoader::Small); if (!iconname.isEmpty()) { m_moduleManager.setModuleIcon(currentButtonInfo().file, iconname); // TODO: update THAT button only. QTimer::singleShot(0, this, SLOT(updateButtons())); } } void Sidebar_Widget::slotRemove() { if (KMessageBox::warningContinueCancel(this, i18n("Do you really want to remove the %1 tab?", currentButtonInfo().displayName), QString(), KStandardGuiItem::del()) == KMessageBox::Continue) { m_moduleManager.removeModule(currentButtonInfo().file); QTimer::singleShot(0, this, SLOT(updateButtons())); } } void Sidebar_Widget::slotMultipleViews() { m_singleWidgetMode = !m_singleWidgetMode; if ((m_singleWidgetMode) && (m_visibleViews.count() > 1)) { int tmpViewID = m_latestViewed; for (int i = 0; i < m_buttons.count(); i++) { if (i != tmpViewID) { const ButtonInfo &button = m_buttons.at(i); if (button.dock && button.dock->isVisibleTo(this)) { showHidePage(i); } } } m_latestViewed = tmpViewID; } m_configTimer.start(400); } void Sidebar_Widget::slotShowTabsLeft() { m_showTabsLeft = ! m_showTabsLeft; doLayout(); m_configTimer.start(400); } void Sidebar_Widget::slotShowConfigurationButton() { m_showExtraButtons = ! m_showExtraButtons; if (m_showExtraButtons) { m_buttonBar->button(-1)->show(); } else { m_buttonBar->button(-1)->hide(); KMessageBox::information(this, i18n("You have hidden the sidebar configuration button. To make it visible again, click the right mouse button on any of the sidebar buttons and select \"Show Configuration Button\".")); } m_configTimer.start(400); } void Sidebar_Widget::readConfig() { m_singleWidgetMode = m_config->readEntry("SingleWidgetMode", true); m_showExtraButtons = m_config->readEntry("ShowExtraButtons", false); m_showTabsLeft = m_config->readEntry("ShowTabsLeft", true); m_hideTabs = m_config->readEntry("HideTabs", false); } void Sidebar_Widget::stdAction(const char *handlestd) { // ### problem: what about multi mode? We could have multiple modules shown, // and if we use Edit/Copy, which one should be used? Need to care about focus... kDebug() << handlestd << "m_activeModule=" << m_activeModule; if (m_activeModule) { QMetaObject::invokeMethod(m_activeModule, handlestd); } } void Sidebar_Widget::updateButtons() { //PARSE ALL DESKTOP FILES m_openViews = m_visibleViews; for (int i = 0; i < m_buttons.count(); ++i) { const ButtonInfo &button = m_buttons.at(i); if (button.dock) { m_noUpdate = true; if (button.dock->isVisibleTo(this)) { showHidePage(i); } delete button.module; delete button.dock; } m_buttonBar->removeTab(i); } m_buttons.clear(); readConfig(); doLayout(); createButtons(); } void Sidebar_Widget::createButtons() { const QStringList modules = m_moduleManager.modules(); Q_FOREACH (const QString &fileName, modules) { addButton(fileName); } if (!m_buttonBar->button(-1)) { m_buttonBar->appendButton(SmallIcon("configure"), -1, m_menu, i18n("Configure Sidebar")); } if (m_showExtraButtons) { m_buttonBar->button(-1)->show(); } else { m_buttonBar->button(-1)->hide(); } for (int i = 0; i < m_buttons.count(); i++) { const ButtonInfo &button = m_buttons.at(i); if (m_openViews.contains(button.file)) { m_buttonBar->setTab(i, true); m_noUpdate = true; showHidePage(i); if (m_singleWidgetMode) { break; } } } collapseExpandSidebar(); m_noUpdate = false; } bool Sidebar_Widget::openUrl(const QUrl &url) { if (url.scheme() == "sidebar") { for (int i = 0; i < m_buttons.count(); i++) if (m_buttons.at(i).file == url.path()) { KMultiTabBarTab *tab = m_buttonBar->tab(i); if (!tab->isChecked()) { tab->animateClick(); } return true; } return false; } m_storedUrl = url; m_hasStoredUrl = true; bool ret = false; for (int i = 0; i < m_buttons.count(); i++) { const ButtonInfo &button = m_buttons.at(i); if (button.dock) { if ((button.dock->isVisibleTo(this)) && (button.module)) { ret = true; button.module->openUrl(url); } } } return ret; } bool Sidebar_Widget::addButton(const QString &desktopFileName, int pos) { int lastbtn = m_buttons.count(); kDebug() << "addButton:" << desktopFileName; const QString moduleDataPath = m_moduleManager.moduleDataPath(desktopFileName); // Check the desktop file still exists if (QStandardPaths::locate(QStandardPaths::GenericDataLocation, moduleDataPath).isEmpty()) { return false; } KSharedConfig::Ptr config = KSharedConfig::openConfig(moduleDataPath, KConfig::NoGlobals, QStandardPaths::GenericDataLocation); KConfigGroup configGroup(config, "Desktop Entry"); const QString icon = configGroup.readEntry("Icon", QString()); const QString name = configGroup.readEntry("Name", QString()); const QString comment = configGroup.readEntry("Comment", QString()); const QUrl url(configGroup.readPathEntry("URL", QString())); const QString lib = configGroup.readEntry("X-KDE-KonqSidebarModule"); if (pos == -1) { // TODO handle insertion m_buttonBar->appendTab(SmallIcon(icon), lastbtn, name); ButtonInfo buttonInfo(config, desktopFileName, url, lib, name, icon); m_buttons.insert(lastbtn, buttonInfo); KMultiTabBarTab *tab = m_buttonBar->tab(lastbtn); tab->installEventFilter(this); connect(tab, SIGNAL(clicked(int)), this, SLOT(showHidePage(int))); // Set Whats This help // This uses the comments in the .desktop files tab->setWhatsThis(comment); } return true; } bool Sidebar_Widget::eventFilter(QObject *obj, QEvent *ev) { if (ev->type() == QEvent::MouseButtonPress && ((QMouseEvent *)ev)->button() == Qt::RightButton) { KMultiTabBarTab *bt = dynamic_cast(obj); if (bt) { kDebug() << "Request for popup"; m_currentButtonIndex = -1; for (int i = 0; i < m_buttons.count(); i++) { if (bt == m_buttonBar->tab(i)) { m_currentButtonIndex = i; break; } } if (m_currentButtonIndex > -1) { KMenu *buttonPopup = new KMenu(this); buttonPopup->addTitle(SmallIcon(currentButtonInfo().iconName), currentButtonInfo().displayName); buttonPopup->addAction(QIcon::fromTheme("edit-rename"), i18n("Set Name..."), this, SLOT(slotSetName())); // Item to open a dialog to change the name of the sidebar item (by Pupeno) buttonPopup->addAction(QIcon::fromTheme("internet-web-browser"), i18n("Set URL..."), this, SLOT(slotSetURL())); buttonPopup->addAction(QIcon::fromTheme("preferences-desktop-icons"), i18n("Set Icon..."), this, SLOT(slotSetIcon())); buttonPopup->addSeparator(); buttonPopup->addAction(QIcon::fromTheme("edit-delete"), i18n("Remove"), this, SLOT(slotRemove())); buttonPopup->addSeparator(); buttonPopup->addMenu(m_menu); buttonPopup->exec(QCursor::pos()); delete buttonPopup; } return true; } } return false; } void Sidebar_Widget::mousePressEvent(QMouseEvent *ev) { // TODO move to contextMenuEvent? if (ev->type() == QEvent::MouseButtonPress && ev->button() == Qt::RightButton) { m_menu->exec(QCursor::pos()); } } KonqSidebarModule *Sidebar_Widget::loadModule(QWidget *parent, const QString &desktopName, ButtonInfo &buttonInfo, const KSharedConfig::Ptr &config) { const KConfigGroup configGroup = config->group("Desktop Entry"); KonqSidebarPlugin *plugin = buttonInfo.plugin(this); if (!plugin) { return 0; } return plugin->createModule(parent, configGroup, desktopName, QVariant()); } KParts::BrowserExtension *Sidebar_Widget::getExtension() { return KParts::BrowserExtension::childObject(m_partParent); } bool Sidebar_Widget::createView(ButtonInfo &buttonInfo) { buttonInfo.dock = 0; buttonInfo.module = loadModule(m_area, buttonInfo.file, buttonInfo, buttonInfo.configFile); if (buttonInfo.module == 0) { return false; } buttonInfo.dock = buttonInfo.module->getWidget(); connectModule(buttonInfo.module); connect(this, SIGNAL(fileSelection(KFileItemList)), buttonInfo.module, SLOT(openPreview(KFileItemList))); connect(this, SIGNAL(fileMouseOver(KFileItem)), buttonInfo.module, SLOT(openPreviewOnMouseOver(KFileItem))); return true; } void Sidebar_Widget::showHidePage(int page) { Q_ASSERT(page >= 0); Q_ASSERT(page < m_buttons.count()); ButtonInfo &buttonInfo = m_buttons[page]; if (!buttonInfo.dock) { if (m_buttonBar->isTabRaised(page)) { //SingleWidgetMode if (m_singleWidgetMode) { if (m_latestViewed != -1) { m_noUpdate = true; showHidePage(m_latestViewed); } } if (!createView(buttonInfo)) { m_buttonBar->setTab(page, false); return; } m_buttonBar->setTab(page, true); connect(buttonInfo.module, SIGNAL(setIcon(QString)), m_buttonBar->tab(page), SLOT(setIcon(QString))); connect(buttonInfo.module, SIGNAL(setCaption(QString)), m_buttonBar->tab(page), SLOT(setText(QString))); m_area->addWidget(buttonInfo.dock); buttonInfo.dock->show(); m_area->show(); if (m_hasStoredUrl) { buttonInfo.module->openUrl(m_storedUrl); } m_visibleViews << buttonInfo.file; m_latestViewed = page; } } else { if ((!buttonInfo.dock->isVisibleTo(this)) && (m_buttonBar->isTabRaised(page))) { //SingleWidgetMode if (m_singleWidgetMode) { if (m_latestViewed != -1) { m_noUpdate = true; showHidePage(m_latestViewed); } } buttonInfo.dock->show(); m_area->show(); m_latestViewed = page; if (m_hasStoredUrl) { buttonInfo.module->openUrl(m_storedUrl); } m_visibleViews << buttonInfo.file; m_buttonBar->setTab(page, true); } else { m_buttonBar->setTab(page, false); buttonInfo.dock->hide(); m_latestViewed = -1; m_visibleViews.removeAll(buttonInfo.file); if (m_visibleViews.empty()) { m_area->hide(); } } } if (!m_noUpdate) { collapseExpandSidebar(); } m_noUpdate = false; } void Sidebar_Widget::collapseExpandSidebar() { if (!parentWidget()) { return; // Can happen during destruction } if (m_visibleViews.count() == 0) { m_somethingVisible = false; parentWidget()->setMaximumWidth(minimumSizeHint().width()); updateGeometry(); emit panelHasBeenExpanded(false); } else { m_somethingVisible = true; parentWidget()->setMaximumWidth(32767); updateGeometry(); emit panelHasBeenExpanded(true); } } QSize Sidebar_Widget::sizeHint() const { if (m_somethingVisible) { return QSize(m_savedWidth, 200); } return minimumSizeHint(); } void Sidebar_Widget::submitFormRequest(const char *action, const QString &url, const QByteArray &formData, const QString & /*target*/, const QString &contentType, const QString & /*boundary*/) { KParts::OpenUrlArguments arguments; KParts::BrowserArguments browserArguments; browserArguments.setContentType("Content-Type: " + contentType); browserArguments.postData = formData; browserArguments.setDoPost(QByteArray(action).toLower() == "post"); // boundary? emit getExtension()->openUrlRequest(QUrl(url), arguments, browserArguments); } void Sidebar_Widget::openUrlRequest(const QUrl &url, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs) { getExtension()->openUrlRequest(url, args, browserArgs); } void Sidebar_Widget::createNewWindow(const QUrl &url, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs, const KParts::WindowArgs &windowArgs) { getExtension()->createNewWindow(url, args, browserArgs, windowArgs); } void Sidebar_Widget::slotEnableAction(KonqSidebarModule *module, const char *name, bool enabled) { if (module->getWidget()->isVisible()) { emit getExtension()->enableAction(name, enabled); } } void Sidebar_Widget::doEnableActions() { if (m_activeModule) { getExtension()->enableAction("copy", m_activeModule->isCopyEnabled()); getExtension()->enableAction("cut", m_activeModule->isCutEnabled()); getExtension()->enableAction("paste", m_activeModule->isPasteEnabled()); } } void Sidebar_Widget::connectModule(KonqSidebarModule *mod) { connect(mod, SIGNAL(started(KIO::Job*)), this, SIGNAL(started(KIO::Job*))); connect(mod, SIGNAL(completed()), this, SIGNAL(completed())); connect(mod, SIGNAL(popupMenu(KonqSidebarModule*,QPoint,KFileItemList,KParts::OpenUrlArguments,KParts::BrowserArguments,KParts::BrowserExtension::PopupFlags,KParts::BrowserExtension::ActionGroupMap)), this, SLOT(slotPopupMenu(KonqSidebarModule*,QPoint,KFileItemList,KParts::OpenUrlArguments,KParts::BrowserArguments,KParts::BrowserExtension::PopupFlags,KParts::BrowserExtension::ActionGroupMap))); connect(mod, SIGNAL(openUrlRequest(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), this, SLOT(openUrlRequest(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments))); connect(mod, SIGNAL(createNewWindow(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments,KParts::WindowArgs)), this, SLOT(createNewWindow(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments,KParts::WindowArgs))); // TODO define in base class if (mod->metaObject()->indexOfSignal("submitFormRequest(const char*,QString,QByteArray,QString,QString,QString)") != -1) { connect(mod, SIGNAL(submitFormRequest(const char*,QString,QByteArray,QString,QString,QString)), this, SLOT(submitFormRequest(const char*,QString,QByteArray,QString,QString,QString))); } connect(mod, SIGNAL(enableAction(KonqSidebarModule*,const char*,bool)), this, SLOT(slotEnableAction(KonqSidebarModule*,const char*,bool))); } Sidebar_Widget::~Sidebar_Widget() { m_config->writeEntry("OpenViews", m_visibleViews); if (m_configTimer.isActive()) { saveConfig(); } delete m_config; m_buttons.clear(); m_noUpdate = true; } void Sidebar_Widget::customEvent(QEvent *ev) { if (KonqFileSelectionEvent::test(ev)) { emit fileSelection(static_cast(ev)->selection()); } else if (KonqFileMouseOverEvent::test(ev)) { emit fileMouseOver(static_cast(ev)->item()); } } KonqSidebarPlugin *ButtonInfo::plugin(QObject *parent) { if (!m_plugin) { KPluginLoader loader(libName); KPluginFactory *factory = loader.factory(); if (!factory) { kWarning() << "error loading" << libName << loader.errorString(); return 0; } KonqSidebarPlugin *plugin = factory->create(parent); if (!plugin) { kWarning() << "error creating object from" << libName; return 0; } m_plugin = plugin; } return m_plugin; } void Sidebar_Widget::slotPopupMenu(KonqSidebarModule *module, const QPoint &global, const KFileItemList &items, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs, KParts::BrowserExtension::PopupFlags flags, const KParts::BrowserExtension::ActionGroupMap &actionGroups) { m_activeModule = module; doEnableActions(); emit getExtension()->popupMenu(global, items, args, browserArgs, flags, actionGroups); } void Sidebar_Widget::slotUrlsDropped(const QList &urls) { Q_FOREACH (const QUrl &url, urls) { KIO::StatJob *job = KIO::stat(url); KJobWidgets::setWindow(job, this); connect(job, &KIO::StatJob::result, this, &Sidebar_Widget::slotStatResult); } } void Sidebar_Widget::slotStatResult(KJob *job) { KIO::StatJob *statJob = static_cast(job); if (statJob->error()) { statJob->uiDelegate()->showErrorMessage(); } else { const QUrl url = statJob->url(); KFileItem item(statJob->statResult(), url); if (item.isDir()) { createDirectModule("folder%1.desktop", url.fileName(), url, item.iconName(), "konqsidebar_tree", "Directory"); } else if (item.currentMimeType().inherits("text/html") || url.scheme().startsWith("http")) { const QString name = i18n("Web module"); createDirectModule("websidebarplugin%1.desktop", name, url, "internet-web-browser", "konqsidebar_web"); } else { // What to do about other kinds of files? kWarning() << "The dropped URL" << url << "is" << item.mimetype() << ", which is not a directory nor an HTML page, what should we do with it?"; } } } diff --git a/sidebar/trees/konqsidebar_oldtreemodule.cpp b/sidebar/trees/konqsidebar_oldtreemodule.cpp index 37800378a..a59509e08 100644 --- a/sidebar/trees/konqsidebar_oldtreemodule.cpp +++ b/sidebar/trees/konqsidebar_oldtreemodule.cpp @@ -1,210 +1,210 @@ #include "konqsidebar_oldtreemodule.h" #include #include "konq_sidebartree.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include KonqSidebarOldTreeModule::KonqSidebarOldTreeModule(const KComponentData &componentData, QWidget *parent, const QString &desktopName_, const KConfigGroup &configGroup) : KonqSidebarModule(componentData, parent, configGroup) { const ModuleType virt = configGroup.readEntry("X-KDE-TreeModule", QString()) == "Virtual" ? VIRT_Folder : VIRT_Link; QString path; if (virt == VIRT_Folder) { path = configGroup.readEntry("X-KDE-RelURL", QString()); } else { // The whole idea of using the same desktop file for the module // and for the toplevel item is broken. When renaming the toplevel item, // the module isn't renamed until the next konqueror restart (!). // We probably want to get rid of toplevel items when there's only one? path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "konqsidebartng/entries/" + desktopName_); // ### this breaks global/local merging! } widget = new QWidget(parent); QVBoxLayout *widgetVBoxLayout = new QVBoxLayout(widget); - widgetVBoxLayout->setMargin(0); + widgetVBoxLayout->setContentsMargins(0, 0, 0, 0); // TODO use QVBoxLayout if (configGroup.readEntry("X-KDE-SearchableTreeModule", false)) { QWidget *searchLine = new QWidget(widget); QVBoxLayout *searchLineVBoxLayout = new QVBoxLayout(searchLine); - searchLineVBoxLayout->setMargin(0); + searchLineVBoxLayout->setContentsMargins(0, 0, 0, 0); widgetVBoxLayout->addWidget(searchLine); tree = new KonqSidebarTree(this, widget, virt, path); new K3ListViewSearchLineWidget(tree, searchLine); } else { tree = new KonqSidebarTree(this, widget, virt, path); } connect(tree, SIGNAL(openUrlRequest(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), this, SIGNAL(openUrlRequest(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments))); connect(tree, SIGNAL(createNewWindow(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), this, SIGNAL(createNewWindow(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments))); connect(tree, SIGNAL(copy()), this, SLOT(copy())); connect(tree, SIGNAL(cut()), this, SLOT(cut())); connect(tree, SIGNAL(paste()), this, SLOT(pasteToSelection())); } KonqSidebarOldTreeModule::~KonqSidebarOldTreeModule() {} QWidget *KonqSidebarOldTreeModule::getWidget() { return widget; } void KonqSidebarOldTreeModule::handleURL(const QUrl &url) { emit started(0); tree->followURL(url); emit completed(); } void KonqSidebarOldTreeModule::cut() { QMimeData *mimeData = new QMimeData; if (static_cast(tree->selectedItem())->populateMimeData(mimeData, true)) { QApplication::clipboard()->setMimeData(mimeData); } else { delete mimeData; } } void KonqSidebarOldTreeModule::copy() { kDebug(); QMimeData *mimeData = new QMimeData; if (static_cast(tree->selectedItem())->populateMimeData(mimeData, false)) { kDebug() << "setting" << mimeData->formats(); QApplication::clipboard()->setMimeData(mimeData); } else { delete mimeData; } } void KonqSidebarOldTreeModule::paste() { // Not implemented. Would be for pasting into the toplevel. kDebug() << "not implemented. Didn't think it would be called - tell me (David Faure)"; } void KonqSidebarOldTreeModule::pasteToSelection() { if (tree->currentItem()) { tree->currentItem()->paste(); } } class KonqSidebarTreePlugin : public KonqSidebarPlugin { public: KonqSidebarTreePlugin(QObject *parent, const QVariantList &args) : KonqSidebarPlugin(parent, args) {} virtual ~KonqSidebarTreePlugin() {} virtual KonqSidebarModule *createModule(const KComponentData &componentData, QWidget *parent, const KConfigGroup &configGroup, const QString &desktopname, const QVariant &unused) { Q_UNUSED(unused); return new KonqSidebarOldTreeModule(componentData, parent, desktopname, configGroup); } virtual QList addNewActions(QObject *parent, const QList &existingModules, const QVariant &unused) { Q_UNUSED(unused); QStringList existingTreeModules; Q_FOREACH (const KConfigGroup &cfg, existingModules) { existingTreeModules.append(cfg.readEntry("X-KDE-TreeModule", QString())); } QList actions; const QStringList list = KGlobal::dirs()->findAllResources("data", "konqsidebartng/dirtree/*.desktop", KStandardDirs::NoDuplicates); Q_FOREACH (const QString &desktopFile, list) { KDesktopFile df(desktopFile); const KConfigGroup desktopGroup = df.desktopGroup(); const bool hasUrl = !(desktopGroup.readEntry("X-KDE-Default-URL", QString()).isEmpty()); const QString treeModule = desktopGroup.readEntry("X-KDE-TreeModule", QString()); // Assumption: modules without a default URL, don't use URLs at all, // and therefore are "unique" (no point in having two bookmarks modules // or two history modules). Modules with URLs can be added multiple times. if (hasUrl || !existingTreeModules.contains(treeModule)) { const QString name = df.readName(); QAction *action = new QAction(parent); //action->setText(i18nc("@action:inmenu Add folder sidebar module", "Folder")); action->setText(name); action->setData(desktopFile); action->setIcon(QIcon::fromTheme(df.readIcon())); actions.append(action); } } return actions; } virtual QString templateNameForNewModule(const QVariant &actionData, const QVariant &unused) const { Q_UNUSED(unused); // Example: /full/path/to/bookmarks_module.desktop -> bookmarks%1.desktop QString str = actionData.toString(); str = str.mid(str.lastIndexOf('/') + 1); str.replace(".desktop", "%1.desktop"); str.remove("_module"); return str; } virtual bool createNewModule(const QVariant &actionData, KConfigGroup &configGroup, QWidget *parentWidget, const QVariant &unused) { Q_UNUSED(unused); const KDesktopFile df(actionData.toString()); const KConfigGroup desktopGroup = df.desktopGroup(); QUrl url = desktopGroup.readEntry("X-KDE-Default-URL"); KNameAndUrlInputDialog dlg(i18nc("@label", "Name:"), i18nc("@label", "Path or URL:"), QUrl(), parentWidget); dlg.setCaption(i18nc("@title:window", "Add folder sidebar module")); dlg.setSuggestedName(df.readName()); if (!dlg.exec()) { return false; } configGroup.writeEntry("Type", "Link"); configGroup.writeEntry("Icon", df.readIcon()); configGroup.writeEntry("Name", dlg.name()); configGroup.writeEntry("Open", false); configGroup.writePathEntry("URL", dlg.url().url()); configGroup.writeEntry("X-KDE-KonqSidebarModule", "konqsidebar_tree"); configGroup.writeEntry("X-KDE-TreeModule", desktopGroup.readEntry("X-KDE-TreeModule")); configGroup.writeEntry("X-KDE-TreeModule-ShowHidden", desktopGroup.readEntry("X-KDE-TreeModule-ShowHidden")); return true; } }; K_PLUGIN_FACTORY(KonqSidebarTreePluginFactory, registerPlugin();) K_EXPORT_PLUGIN(KonqSidebarTreePluginFactory()) #include "konqsidebar_oldtreemodule.moc" diff --git a/sidebar/web_module/web_module.cpp b/sidebar/web_module/web_module.cpp index ae40455ea..754519a77 100644 --- a/sidebar/web_module/web_module.cpp +++ b/sidebar/web_module/web_module.cpp @@ -1,320 +1,320 @@ /* This file is part of the KDE project Copyright (C) 2003, George Staikos This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "web_module.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include KHTMLSideBar::KHTMLSideBar() : KHTMLPart() { setStatusMessagesEnabled(false); setMetaRefreshEnabled(true); setJavaEnabled(false); setPluginsEnabled(false); setFormNotification(KHTMLPart::Only); connect(this, SIGNAL(formSubmitNotification(const char*,QString,QByteArray,QString,QString,QString)), this, SLOT(formProxy(const char*,QString,QByteArray,QString,QString,QString)) ); _linkMenu = new KMenu(widget()); QAction *openLinkAction = new QAction(i18n("&Open Link"), this); _linkMenu->addAction(openLinkAction); connect(openLinkAction, SIGNAL(triggered()), this, SLOT(loadPage())); QAction *openWindowAction = new QAction(i18n("Open in New &Window"), this); _linkMenu->addAction(openWindowAction); connect(openWindowAction, SIGNAL(triggered()), this, SLOT(loadNewWindow())); _menu = new KMenu(widget()); QAction *reloadAction = new QAction(i18n("&Reload"), this); reloadAction->setIcon(QIcon::fromTheme("view-refresh")); _menu->addAction(reloadAction); connect(reloadAction, SIGNAL(triggered()), this, SIGNAL(reload())); QAction *autoReloadAction = new QAction(i18n("Set &Automatic Reload"), this); autoReloadAction->setIcon(QIcon::fromTheme("view-refresh")); _menu->addAction(autoReloadAction); connect(autoReloadAction, SIGNAL(triggered()), this, SIGNAL(setAutoReload())); connect(this, SIGNAL(popupMenu(QString,QPoint)), this, SLOT(showMenu(QString,QPoint))); } //// KonqSideBarWebModule::KonqSideBarWebModule(QWidget *parent, const KConfigGroup &configGroup) : KonqSidebarModule(parent, configGroup) { _htmlPart = new KHTMLSideBar(); _htmlPart->setAutoDeletePart(false); connect(_htmlPart, SIGNAL(reload()), this, SLOT(reload())); connect(_htmlPart, SIGNAL(completed()), this, SLOT(pageLoaded())); connect(_htmlPart, SIGNAL(setWindowCaption(QString)), this, SLOT(setTitle(QString))); connect(_htmlPart, SIGNAL(openUrlRequest(QString,KParts::OpenUrlArguments,KParts::BrowserArguments)), this, SLOT(urlClicked(QString,KParts::OpenUrlArguments,KParts::BrowserArguments))); connect(_htmlPart->browserExtension(), SIGNAL(openUrlRequest(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), this, SLOT(formClicked(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments))); connect(_htmlPart, SIGNAL(setAutoReload()), this, SLOT(setAutoReload())); connect(_htmlPart, SIGNAL(openUrlNewWindow(QString,KParts::OpenUrlArguments,KParts::BrowserArguments,KParts::WindowArgs)), this, SLOT(urlNewWindow(QString,KParts::OpenUrlArguments,KParts::BrowserArguments,KParts::WindowArgs))); connect(_htmlPart, SIGNAL(submitFormRequest(const char*,QString,QByteArray,QString,QString,QString)), this, SIGNAL(submitFormRequest(const char*,QString,QByteArray,QString,QString,QString))); reloadTimeout = configGroup.readEntry("Reload", 0); _url = QUrl(configGroup.readPathEntry("URL", QString())); _htmlPart->openUrl(_url); // Must load this delayed QTimer::singleShot(0, this, SLOT(loadFavicon())); } KonqSideBarWebModule::~KonqSideBarWebModule() { delete _htmlPart; _htmlPart = 0L; } QWidget *KonqSideBarWebModule::getWidget() { return _htmlPart->widget(); } void KonqSideBarWebModule::setAutoReload() { KDialog dlg(0); dlg.setModal(true); dlg.setCaption(i18nc("@title:window", "Set Refresh Timeout (0 disables)")); dlg.setButtons(KDialog::Ok | KDialog::Cancel); QWidget *hbox = new QWidget(&dlg); QHBoxLayout *hboxHBoxLayout = new QHBoxLayout(hbox); - hboxHBoxLayout->setMargin(0); + hboxHBoxLayout->setContentsMargins(0, 0, 0, 0); dlg.setMainWidget(hbox); KIntNumInput *mins = new KIntNumInput(hbox); hboxHBoxLayout->addWidget(mins); mins->setRange(0, 120); mins->setSuffix(ki18np(" minute", " minutes")); KIntNumInput *secs = new KIntNumInput(hbox); hboxHBoxLayout->addWidget(secs); secs->setRange(0, 59); secs->setSuffix(ki18np(" second", " seconds")); if (reloadTimeout > 0) { int seconds = reloadTimeout / 1000; secs->setValue(seconds % 60); mins->setValue((seconds - secs->value()) / 60); } if (dlg.exec() == KDialog::Accepted) { int msec = (mins->value() * 60 + secs->value()) * 1000; reloadTimeout = msec; configGroup().writeEntry("Reload", reloadTimeout); reload(); } } void KonqSideBarWebModule::handleURL(const QUrl &) { } void KonqSideBarWebModule::urlNewWindow(const QString &url, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs, const KParts::WindowArgs &windowArgs) { emit createNewWindow(QUrl(url), args, browserArgs, windowArgs); } void KonqSideBarWebModule::urlClicked(const QString &url, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs) { emit openUrlRequest(QUrl(url), args, browserArgs); } void KonqSideBarWebModule::formClicked(const QUrl &url, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs) { _htmlPart->setArguments(args); _htmlPart->browserExtension()->setBrowserArguments(browserArgs); _htmlPart->openUrl(url); } void KonqSideBarWebModule::loadFavicon() { const QString icon = KIO::favIconForUrl(_url); if (icon.isEmpty()) { KIO::FavIconRequestJob *job = new KIO::FavIconRequestJob(_url); connect(job, &KIO::FavIconRequestJob::result, this, [this, job](KJob *) { if (!job->error()) { loadFavicon(); } }); return; } emit setIcon(icon); if (icon != configGroup().readEntry("Icon", QString())) { configGroup().writeEntry("Icon", icon); } } void KonqSideBarWebModule::reload() { _htmlPart->openUrl(_url); } void KonqSideBarWebModule::setTitle(const QString &title) { kDebug() << title; if (!title.isEmpty()) { emit setCaption(title); if (title != configGroup().readEntry("Name", QString())) { configGroup().writeEntry("Name", title); } } } void KonqSideBarWebModule::pageLoaded() { if (reloadTimeout > 0) { QTimer::singleShot(reloadTimeout, this, SLOT(reload())); } } bool KHTMLSideBar::urlSelected(const QString &url, int button, int state, const QString &_target, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments &browserArgs) { if (button == Qt::LeftButton) { if (_target.toLower() == "_self") { openUrl(completeURL(url)); } else if (_target.toLower() == "_blank") { emit openUrlNewWindow(completeURL(url).url(), args); } else { // isEmpty goes here too emit openUrlRequest(completeURL(url).url(), args); } return true; } if (button == Qt::MidButton) { emit openUrlNewWindow(completeURL(url).url(), args); return true; } // A refresh if (button == 0 && _target.toLower() == "_self") { openUrl(completeURL(url)); return true; } return KHTMLPart::urlSelected(url, button, state, _target, args, browserArgs); } class KonqSidebarWebPlugin : public KonqSidebarPlugin { public: KonqSidebarWebPlugin(QObject *parent, const QVariantList &args) : KonqSidebarPlugin(parent, args) {} virtual ~KonqSidebarWebPlugin() {} virtual KonqSidebarModule *createModule(QWidget *parent, const KConfigGroup &configGroup, const QString &desktopname, const QVariant &unused) { Q_UNUSED(unused); Q_UNUSED(desktopname); return new KonqSideBarWebModule(parent, configGroup); } virtual QList addNewActions(QObject *parent, const QList &existingModules, const QVariant &unused) { Q_UNUSED(unused); Q_UNUSED(existingModules); QAction *action = new QAction(parent); action->setText(i18nc("@action:inmenu Add", "Web Sidebar Module")); action->setIcon(QIcon::fromTheme("internet-web-browser")); return QList() << action; } virtual QString templateNameForNewModule(const QVariant &actionData, const QVariant &unused) const { Q_UNUSED(actionData); Q_UNUSED(unused); return QString::fromLatin1("websidebarplugin%1.desktop"); } virtual bool createNewModule(const QVariant &actionData, KConfigGroup &configGroup, QWidget *parentWidget, const QVariant &unused) { Q_UNUSED(actionData); Q_UNUSED(unused); KNameAndUrlInputDialog dlg(i18nc("@label", "Name:"), i18nc("@label", "Path or URL:"), QUrl(), parentWidget); dlg.setWindowTitle(i18nc("@title:window", "Add web sidebar module")); if (!dlg.exec()) { return false; } configGroup.writeEntry("Type", "Link"); configGroup.writeEntry("Icon", "internet-web-browser"); configGroup.writeEntry("Name", dlg.name()); configGroup.writeEntry("URL", dlg.url().url()); configGroup.writeEntry("X-KDE-KonqSidebarModule", "konqsidebar_web"); return true; } }; K_PLUGIN_FACTORY(KonqSidebarWebPluginFactory, registerPlugin();) #include "web_module.moc" diff --git a/src/konqframe.cpp b/src/konqframe.cpp index aeae738ed..dd2b0affc 100644 --- a/src/konqframe.cpp +++ b/src/konqframe.cpp @@ -1,264 +1,264 @@ /* This file is part of the KDE project Copyright (C) 1998, 1999 Michael Reiher This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Own #include "konqframe.h" // Local #include "konqtabs.h" #include "konqview.h" #include "konqviewmanager.h" #include "konqframevisitor.h" #include "konqframestatusbar.h" // Qt #include #include #include #include // KDE #include #include "konqdebug.h" #include #include #include #include #include KonqFrameBase::KonqFrameBase() : m_pParentContainer(nullptr) { } QString KonqFrameBase::frameTypeToString(const KonqFrameBase::FrameType frameType) { switch (frameType) { case View : return QStringLiteral("View"); case Tabs : return QStringLiteral("Tabs"); case ContainerBase : return QStringLiteral("ContainerBase"); case Container : return QStringLiteral("Container"); case MainWindow : return QStringLiteral("MainWindow"); } Q_ASSERT(0); return QString(); } KonqFrameBase::FrameType frameTypeFromString(const QString &str) { if (str == QLatin1String("View")) { return KonqFrameBase::View; } if (str == QLatin1String("Tabs")) { return KonqFrameBase::Tabs; } if (str == QLatin1String("ContainerBase")) { return KonqFrameBase::ContainerBase; } if (str == QLatin1String("Container")) { return KonqFrameBase::Container; } if (str == QLatin1String("MainWindow")) { return KonqFrameBase::MainWindow; } Q_ASSERT(0); return KonqFrameBase::View; } KonqFrame::KonqFrame(QWidget *parent, KonqFrameContainerBase *parentContainer) : QWidget(parent) { //qCDebug(KONQUEROR_LOG) << "KonqFrame::KonqFrame()"; m_pLayout = nullptr; m_pView = nullptr; // the frame statusbar m_pStatusBar = new KonqFrameStatusBar(this); m_pStatusBar->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_pStatusBar, &KonqFrameStatusBar::clicked, this, &KonqFrame::slotStatusBarClicked); connect(m_pStatusBar, &KonqFrameStatusBar::linkedViewClicked, this, &KonqFrame::slotLinkedViewClicked); m_separator = nullptr; m_pParentContainer = parentContainer; } KonqFrame::~KonqFrame() { //qCDebug(KONQUEROR_LOG) << this; } bool KonqFrame::isActivePart() { return (m_pView && static_cast(m_pView) == m_pView->mainWindow()->currentView()); } void KonqFrame::saveConfig(KConfigGroup &config, const QString &prefix, const KonqFrameBase::Options &options, KonqFrameBase *docContainer, int /*id*/, int /*depth*/) { if (m_pView) { m_pView->saveConfig(config, prefix, options); } //config.writeEntry( QString::fromLatin1( "ShowStatusBar" ).prepend( prefix ), statusbar()->isVisible() ); if (this == docContainer) { config.writeEntry(QStringLiteral("docContainer").prepend(prefix), true); } } void KonqFrame::copyHistory(KonqFrameBase *other) { Q_ASSERT(other->frameType() == KonqFrameBase::View); if (m_pView) { m_pView->copyHistory(static_cast(other)->childView()); } } KParts::ReadOnlyPart *KonqFrame::attach(const KonqViewFactory &viewFactory) { KonqViewFactory factory(viewFactory); // Note that we set the parent to 0. // We don't want that deleting the widget deletes the part automatically // because we already have that taken care of in KParts... m_pPart = factory.create(this, nullptr); if (!m_pPart) { qCWarning(KONQUEROR_LOG) << "No part was created!"; return nullptr; } if (!m_pPart->widget()) { qCWarning(KONQUEROR_LOG) << "The part" << m_pPart << "didn't create a widget!"; delete m_pPart; m_pPart = nullptr; return nullptr; } attachWidget(m_pPart->widget()); m_pStatusBar->slotConnectToNewView(nullptr, nullptr, m_pPart); return m_pPart; } void KonqFrame::attachWidget(QWidget *widget) { //qCDebug(KONQUEROR_LOG) << "KonqFrame::attachInternal()"; delete m_pLayout; m_pLayout = new QVBoxLayout(this); m_pLayout->setObjectName(QStringLiteral("KonqFrame's QVBoxLayout")); - m_pLayout->setMargin(0); + m_pLayout->setContentsMargins(0, 0, 0, 0); m_pLayout->setSpacing(0); m_pLayout->addWidget(widget, 1); m_pLayout->addWidget(m_pStatusBar, 0); widget->show(); m_pLayout->activate(); installEventFilter(m_pView->mainWindow()); // for Ctrl+Tab } void KonqFrame::insertTopWidget(QWidget *widget) { Q_ASSERT(m_pLayout); Q_ASSERT(widget); m_pLayout->insertWidget(0, widget); installEventFilter(m_pView->mainWindow()); // for Ctrl+Tab } void KonqFrame::setView(KonqView *child) { m_pView = child; if (m_pView) { connect(m_pView, SIGNAL(sigPartChanged(KonqView*,KParts::ReadOnlyPart*,KParts::ReadOnlyPart*)), m_pStatusBar, SLOT(slotConnectToNewView(KonqView*,KParts::ReadOnlyPart*,KParts::ReadOnlyPart*))); } } void KonqFrame::setTitle(const QString &title, QWidget * /*sender*/) { //qCDebug(KONQUEROR_LOG) << "KonqFrame::setTitle( " << title << " )"; m_title = title; if (m_pParentContainer) { m_pParentContainer->setTitle(title, this); } } void KonqFrame::setTabIcon(const QUrl &url, QWidget * /*sender*/) { //qCDebug(KONQUEROR_LOG) << "KonqFrame::setTabIcon( " << url << " )"; if (m_pParentContainer) { m_pParentContainer->setTabIcon(url, this); } } void KonqFrame::slotStatusBarClicked() { if (!isActivePart() && m_pView && !m_pView->isPassiveMode()) { m_pView->mainWindow()->viewManager()->setActivePart(part()); } } void KonqFrame::slotLinkedViewClicked(bool mode) { if (m_pView->mainWindow()->linkableViewsCount() == 2) { m_pView->mainWindow()->slotLinkView(); } else { m_pView->setLinkedView(mode); } } void KonqFrame::slotRemoveView() { m_pView->mainWindow()->viewManager()->removeView(m_pView); } void KonqFrame::activateChild() { if (m_pView && !m_pView->isPassiveMode()) { m_pView->mainWindow()->viewManager()->setActivePart(part()); if (!m_pView->isLoading() && (m_pView->url().isEmpty() || m_pView->url() == QUrl(QStringLiteral("about:blank")))) { //qCDebug(KONQUEROR_LOG) << "SET FOCUS on the location bar"; m_pView->mainWindow()->focusLocationBar(); // #84867 usability improvement } } } KonqView *KonqFrame::childView() const { return m_pView; } KonqView *KonqFrame::activeChildView() const { return m_pView; } bool KonqFrame::accept(KonqFrameVisitor *visitor) { return visitor->visit(this); } diff --git a/src/konqhistorydialog.cpp b/src/konqhistorydialog.cpp index f1b35a49c..d98461ee8 100644 --- a/src/konqhistorydialog.cpp +++ b/src/konqhistorydialog.cpp @@ -1,114 +1,114 @@ /* This file is part of the KDE project Copyright 2009 Pino Toscano This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "konqhistorydialog.h" #include "konqhistoryview.h" #include "konqhistory.h" #include "konqmainwindow.h" #include "konqmainwindowfactory.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include KonqHistoryDialog::KonqHistoryDialog(KonqMainWindow *parent) : KDialog(parent), m_mainWindow(parent) { setCaption(i18nc("@title:window", "History")); setButtons(KDialog::Close); QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget()); - mainLayout->setMargin(0); + mainLayout->setContentsMargins(0, 0, 0, 0); m_historyView = new KonqHistoryView(mainWidget()); connect(m_historyView->treeView(), SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotOpenWindowForIndex(QModelIndex))); connect(m_historyView, &KonqHistoryView::openUrlInNewWindow, this, &KonqHistoryDialog::slotOpenWindow); connect(m_historyView, &KonqHistoryView::openUrlInNewTab, this, &KonqHistoryDialog::slotOpenTab); KActionCollection *collection = m_historyView->actionCollection(); QToolBar *toolBar = new QToolBar(mainWidget()); toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QToolButton *sortButton = new QToolButton(toolBar); sortButton->setText(i18nc("@action:inmenu Parent of 'By Name' and 'By Date'", "Sort")); sortButton->setIcon(QIcon::fromTheme(QStringLiteral("view-sort-ascending"))); sortButton->setPopupMode(QToolButton::InstantPopup); sortButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QMenu *sortMenu = new QMenu(sortButton); sortMenu->addAction(collection->action(QStringLiteral("byName"))); sortMenu->addAction(collection->action(QStringLiteral("byDate"))); sortButton->setMenu(sortMenu); toolBar->addWidget(sortButton); toolBar->addSeparator(); toolBar->addAction(collection->action(QStringLiteral("preferences"))); mainLayout->addWidget(toolBar); mainLayout->addWidget(m_historyView); restoreDialogSize(KSharedConfig::openConfig()->group("History Dialog")); // give focus to the search line edit when opening the dialog (#240513) m_historyView->lineEdit()->setFocus(); } KonqHistoryDialog::~KonqHistoryDialog() { KConfigGroup group(KSharedConfig::openConfig(), "History Dialog"); saveDialogSize(group); } QSize KonqHistoryDialog::sizeHint() const { return QSize(500, 400); } void KonqHistoryDialog::slotOpenWindow(const QUrl &url) { KonqMainWindow *mw = KonqMainWindowFactory::createNewWindow(url); mw->show(); } void KonqHistoryDialog::slotOpenTab(const QUrl &url) { m_mainWindow->openMultiURL(QList() << url); } // Called when double-clicking on a row void KonqHistoryDialog::slotOpenWindowForIndex(const QModelIndex &index) { const QUrl url = m_historyView->urlForIndex(index); if (url.isValid()) { slotOpenWindow(url); // should we call slotOpenTab instead? } } diff --git a/src/konqhistoryview.cpp b/src/konqhistoryview.cpp index 346aa43b1..036d7888c 100644 --- a/src/konqhistoryview.cpp +++ b/src/konqhistoryview.cpp @@ -1,259 +1,259 @@ /* This file is part of the KDE project Copyright 2009 Pino Toscano Copyright 2009 Daivd Faure This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "konqhistoryview.h" #include "konqhistory.h" #include "konq_historyprovider.h" #include "konqhistorymodel.h" #include "konqhistoryproxymodel.h" #include "konqhistorysettings.h" #include #include #include #include #include #include #include #include #include #include "konqdebug.h" #include #include #include #include #include KonqHistoryView::KonqHistoryView(QWidget *parent) : QWidget(parent) , m_searchTimer(nullptr) { m_treeView = new QTreeView(this); m_treeView->setContextMenuPolicy(Qt::CustomContextMenu); m_treeView->setHeaderHidden(true); m_historyProxyModel = new KonqHistoryProxyModel(KonqHistorySettings::self(), m_treeView); connect(m_treeView, &QTreeView::customContextMenuRequested, this, &KonqHistoryView::slotContextMenu); m_historyModel = new KonqHistoryModel(m_historyProxyModel); m_treeView->setModel(m_historyProxyModel); m_historyProxyModel->setSourceModel(m_historyModel); m_historyProxyModel->sort(0); m_collection = new KActionCollection(this); m_collection->addAssociatedWidget(m_treeView); // make shortcuts work QAction *action = m_collection->addAction(QStringLiteral("open_new")); action->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); action->setText(i18n("Open in New &Window")); connect(action, &QAction::triggered, this, &KonqHistoryView::slotNewWindow); action = m_collection->addAction(QStringLiteral("open_tab")); action->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); action->setText(i18n("Open in New Tab")); connect(action, &QAction::triggered, this, &KonqHistoryView::slotNewTab); action = m_collection->addAction(QStringLiteral("copylinklocation")); action->setText(i18n("&Copy Link Address")); connect(action, &QAction::triggered, this, &KonqHistoryView::slotCopyLinkLocation); action = m_collection->addAction(QStringLiteral("remove")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete"))); action->setText(i18n("&Remove Entry")); m_collection->setDefaultShortcut(action, QKeySequence(Qt::Key_Delete)); // #135966 action->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(action, &QAction::triggered, this, &KonqHistoryView::slotRemoveEntry); action = m_collection->addAction(QStringLiteral("clear")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history"))); action->setText(i18n("C&lear History")); connect(action, &QAction::triggered, this, &KonqHistoryView::slotClearHistory); action = m_collection->addAction(QStringLiteral("preferences")); action->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); action->setText(i18n("&Preferences...")); connect(action, &QAction::triggered, this, &KonqHistoryView::slotPreferences); QActionGroup *sortGroup = new QActionGroup(this); sortGroup->setExclusive(true); action = m_collection->addAction(QStringLiteral("byName")); action->setText(i18n("By &Name")); action->setCheckable(true); action->setData(qVariantFromValue(0)); sortGroup->addAction(action); action = m_collection->addAction(QStringLiteral("byDate")); action->setText(i18n("By &Date")); action->setCheckable(true); action->setData(qVariantFromValue(1)); sortGroup->addAction(action); KonqHistorySettings *settings = KonqHistorySettings::self(); sortGroup->actions().at(settings->m_sortsByName ? 0 : 1)->setChecked(true); connect(sortGroup, &QActionGroup::triggered, this, &KonqHistoryView::slotSortChange); m_searchLineEdit = new KLineEdit(this); m_searchLineEdit->setPlaceholderText(i18n("Search in history")); m_searchLineEdit->setClearButtonShown(true); connect(m_searchLineEdit, &KLineEdit::textChanged, this, &KonqHistoryView::slotFilterTextChanged); QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setMargin(0); + mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->addWidget(m_searchLineEdit); mainLayout->addWidget(m_treeView); } void KonqHistoryView::slotContextMenu(const QPoint &pos) { const QModelIndex index = m_treeView->indexAt(pos); if (!index.isValid()) { return; } const int nodeType = index.data(KonqHistory::TypeRole).toInt(); QMenu *menu = new QMenu(this); if (nodeType == KonqHistory::HistoryType) { menu->addAction(m_collection->action(QStringLiteral("open_new"))); menu->addAction(m_collection->action(QStringLiteral("open_tab"))); menu->addAction(m_collection->action(QStringLiteral("copylinklocation"))); menu->addSeparator(); } menu->addAction(m_collection->action(QStringLiteral("remove"))); menu->addAction(m_collection->action(QStringLiteral("clear"))); menu->addSeparator(); QMenu *sortMenu = menu->addMenu(i18nc("@action:inmenu Parent of 'By Name' and 'By Date'", "Sort")); sortMenu->addAction(m_collection->action(QStringLiteral("byName"))); sortMenu->addAction(m_collection->action(QStringLiteral("byDate"))); menu->addSeparator(); menu->addAction(m_collection->action(QStringLiteral("preferences"))); menu->exec(m_treeView->viewport()->mapToGlobal(pos)); delete menu; } void KonqHistoryView::slotRemoveEntry() { const QModelIndex index = m_treeView->currentIndex(); if (!index.isValid()) { return; } // TODO undo/redo support m_historyModel->deleteItem(m_historyProxyModel->mapToSource(index)); } void KonqHistoryView::slotClearHistory() { KGuiItem guiitem = KStandardGuiItem::clear(); guiitem.setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history"))); if (KMessageBox::warningContinueCancel(this, i18n("Do you really want to clear the entire history?"), i18nc("@title:window", "Clear History?"), guiitem) == KMessageBox::Continue) { KonqHistoryProvider::self()->emitClear(); } } void KonqHistoryView::slotPreferences() { // Run the history sidebar settings. KRun::run(QStringLiteral("kcmshell5 kcmhistory"), QList(), this); } void KonqHistoryView::slotSortChange(QAction *action) { if (!action) { return; } const int which = action->data().toInt(); KonqHistorySettings *settings = KonqHistorySettings::self(); settings->m_sortsByName = (which == 0); settings->applySettings(); } void KonqHistoryView::slotFilterTextChanged(const QString &text) { Q_UNUSED(text); if (!m_searchTimer) { m_searchTimer = new QTimer(this); m_searchTimer->setSingleShot(true); connect(m_searchTimer, &QTimer::timeout, this, &KonqHistoryView::slotTimerTimeout); } m_searchTimer->start(600); } void KonqHistoryView::slotTimerTimeout() { m_historyProxyModel->setFilterFixedString(m_searchLineEdit->text()); } QTreeView *KonqHistoryView::treeView() const { return m_treeView; } KLineEdit *KonqHistoryView::lineEdit() const { return m_searchLineEdit; } void KonqHistoryView::slotNewWindow() { const QUrl url = urlForIndex(m_treeView->currentIndex()); if (url.isValid()) { emit openUrlInNewWindow(url); } } void KonqHistoryView::slotNewTab() { const QUrl url = urlForIndex(m_treeView->currentIndex()); if (url.isValid()) { emit openUrlInNewTab(url); } } QUrl KonqHistoryView::urlForIndex(const QModelIndex &index) const { if (!index.isValid() || (index.data(KonqHistory::TypeRole).toInt() != KonqHistory::HistoryType)) { return QUrl(); } return index.data(KonqHistory::UrlRole).toUrl(); } // Code taken from KHTMLPopupGUIClient::slotCopyLinkLocation void KonqHistoryView::slotCopyLinkLocation() { QUrl safeURL = urlForIndex(m_treeView->currentIndex()).adjusted(QUrl::RemovePassword); // Set it in both the mouse selection and in the clipboard QMimeData *mimeData = new QMimeData; mimeData->setUrls(QList() << safeURL); QApplication::clipboard()->setMimeData(mimeData, QClipboard::Clipboard); QApplication::clipboard()->setMimeData(mimeData, QClipboard::Selection); } diff --git a/src/konqsessiondlg.cpp b/src/konqsessiondlg.cpp index 1abbf10dc..9d4a697a6 100644 --- a/src/konqsessiondlg.cpp +++ b/src/konqsessiondlg.cpp @@ -1,281 +1,281 @@ /* This file is part of the KDE project Copyright (C) 2008 Eduardo Robles Elvira This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "konqsessiondlg.h" #include "konqsettingsxt.h" #include "konqviewmanager.h" #include "konqsessionmanager.h" #include "konqmainwindow.h" #include "ui_konqsessiondlg_base.h" #include "ui_konqnewsessiondlg_base.h" #include #include #include #include #include "konqdebug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class KonqSessionDlg::KonqSessionDlgPrivate : public QWidget, public Ui::KonqSessionDlgBase { public: KonqSessionDlgPrivate(KonqViewManager *manager, QWidget *parent = nullptr) : QWidget(parent), m_pViewManager(manager), m_pParent(parent) { setupUi(this); } KonqViewManager *const m_pViewManager; KDirModel *m_pModel; QWidget *m_pParent; }; #define BTN_OPEN KDialog::User1 KonqSessionDlg::KonqSessionDlg(KonqViewManager *manager, QWidget *parent) : KDialog(parent) , d(new KonqSessionDlgPrivate(manager, this)) { - d->layout()->setMargin(0); + d->layout()->setContentsMargins(0, 0, 0, 0); setMainWidget(d); setObjectName(QStringLiteral("konq_session_dialog")); setModal(true); setCaption(i18nc("@title:window", "Manage Sessions")); setButtons(BTN_OPEN | Close); setDefaultButton(Close); setButtonGuiItem(BTN_OPEN, KGuiItem(i18n("&Open"), QStringLiteral("document-open"))); d->m_pSaveCurrentButton->setIcon(QIcon::fromTheme(QStringLiteral("document-save"))); d->m_pRenameButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename"))); d->m_pDeleteButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete"))); d->m_pNewButton->setIcon(QIcon::fromTheme(QStringLiteral("document-new"))); QString dir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + QLatin1String("sessions/"); QDir().mkpath(dir); d->m_pModel = new KDirModel(d->m_pListView); d->m_pModel->sort(QDir::Name); d->m_pModel->dirLister()->setDirOnlyMode(true); d->m_pModel->dirLister()->openUrl(QUrl::fromLocalFile(dir)); d->m_pListView->setModel(d->m_pModel); d->m_pListView->setMinimumSize(d->m_pListView->sizeHint()); connect(d->m_pListView->selectionModel(), SIGNAL(selectionChanged( const QItemSelection &, const QItemSelection &)), this, SLOT( slotSelectionChanged())); enableButton(BTN_OPEN, d->m_pListView->currentIndex().isValid()); slotSelectionChanged(); d->m_pOpenTabsInsideCurrentWindow->setChecked( KonqSettings::openTabsInsideCurrentWindow()); connect(this, &KonqSessionDlg::user1Clicked, this, &KonqSessionDlg::slotOpen); connect(d->m_pNewButton, &QPushButton::clicked, this, &KonqSessionDlg::slotNew); connect(d->m_pSaveCurrentButton, &QPushButton::clicked, this, &KonqSessionDlg::slotSave); connect(d->m_pRenameButton, SIGNAL(clicked()), SLOT(slotRename())); connect(d->m_pDeleteButton, &QPushButton::clicked, this, &KonqSessionDlg::slotDelete); resize(sizeHint()); } KonqSessionDlg::~KonqSessionDlg() { KonqSettings::setOpenTabsInsideCurrentWindow( d->m_pOpenTabsInsideCurrentWindow->isChecked()); } void KonqSessionDlg::slotOpen() { if (!d->m_pListView->currentIndex().isValid()) { return; } KonqSessionManager::self()->restoreSessions(d->m_pModel->itemForIndex( d->m_pListView->currentIndex()).url().path(), d->m_pOpenTabsInsideCurrentWindow->isChecked(), d->m_pViewManager->mainWindow()); close(); } void KonqSessionDlg::slotSave() { if (!d->m_pListView->currentIndex().isValid()) { return; } QFileInfo fileInfo( d->m_pModel->itemForIndex(d->m_pListView->currentIndex()).url().path()); KonqNewSessionDlg newDialog(this, d->m_pViewManager->mainWindow(), KIO::encodeFileName(fileInfo.fileName()), KonqNewSessionDlg::ReplaceFile); newDialog.exec(); } void KonqSessionDlg::slotNew() { KonqNewSessionDlg newDialog(this, d->m_pViewManager->mainWindow()); newDialog.exec(); } void KonqSessionDlg::slotDelete() { if (!d->m_pListView->currentIndex().isValid()) { return; } const QString dir = d->m_pModel->itemForIndex(d->m_pListView->currentIndex()).url().toLocalFile(); if (!KTempDir::removeDir(dir)) { // TODO show error msg box } } void KonqSessionDlg::slotRename(QUrl dirpathTo) { if (!d->m_pListView->currentIndex().isValid()) { return; } QUrl dirpathFrom = d->m_pModel->itemForIndex( d->m_pListView->currentIndex()).url(); dirpathTo = (dirpathTo == QUrl()) ? dirpathFrom : dirpathTo; KIO::RenameDialog dlg(this, i18nc("@title:window", "Rename Session"), dirpathFrom, dirpathTo, KIO::RenameDialog_Options(nullptr)); if (dlg.exec() == KIO::R_RENAME) { dirpathTo = dlg.newDestUrl(); QDir dir(dirpathTo.path()); if (dir.exists()) { slotRename(dirpathTo); } else { QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + "sessions/"); dir.rename(dirpathFrom.fileName(), dlg.newDestUrl().fileName()); } } } void KonqSessionDlg::slotSelectionChanged() { bool enable = !d->m_pListView->selectionModel()->selectedIndexes().isEmpty(); d->m_pSaveCurrentButton->setEnabled(enable); d->m_pRenameButton->setEnabled(enable); d->m_pDeleteButton->setEnabled(enable); enableButton(BTN_OPEN, enable); } #undef BTN_OPEN class KonqNewSessionDlg::KonqNewSessionDlgPrivate : public QWidget, public Ui::KonqNewSessionDlgBase { public: KonqNewSessionDlgPrivate(QWidget *parent = nullptr, KonqMainWindow *mainWindow = nullptr, KonqNewSessionDlg::Mode m = KonqNewSessionDlg::NewFile) : QWidget(parent), m_pParent(parent), m_mainWindow(mainWindow), m_mode(m) { setupUi(this); } QWidget *m_pParent; KonqMainWindow *m_mainWindow; KonqNewSessionDlg::Mode m_mode; }; KonqNewSessionDlg::KonqNewSessionDlg(QWidget *parent, KonqMainWindow *mainWindow, QString sessionName, Mode mode) : KDialog(parent) , d(new KonqNewSessionDlgPrivate(this, mainWindow, mode)) { - d->layout()->setMargin(0); + d->layout()->setContentsMargins(0, 0, 0, 0); setMainWidget(d); setObjectName(QStringLiteral("konq_new_session_dialog")); setModal(true); setCaption(i18nc("@title:window", "Save Session")); setButtons(Ok | Cancel); setDefaultButton(Ok); enableButton(Ok, false); if (!sessionName.isEmpty()) { d->m_pSessionName->setText(sessionName); enableButton(Ok, true); } d->m_pSessionName->setFocus(); connect(this, &KonqNewSessionDlg::okClicked, this, &KonqNewSessionDlg::slotAddSession); connect(d->m_pSessionName, SIGNAL(textChanged(QString)), this, SLOT(slotTextChanged(QString))); resize(sizeHint()); } void KonqNewSessionDlg::slotAddSession() { QString dirpath = KStandardDirs::locateLocal("appdata", "sessions/" + KIO::encodeFileName(d->m_pSessionName->text())); QDir dir(dirpath); if (dir.exists()) { if ((d->m_mode == ReplaceFile) || KMessageBox::questionYesNo(this, i18n("A session with the name '%1' already exists, do you want to overwrite it?", d->m_pSessionName->text()), i18nc("@title:window", "Session exists. Overwrite?")) == KMessageBox::Yes) { KTempDir::removeDir(dirpath); } else { return; } } if (d->m_pAllWindows->isChecked()) { KonqSessionManager::self()->saveCurrentSessions(dirpath); } else { KonqSessionManager::self()->saveCurrentSessionToFile(dirpath + QLatin1String("/1"), d->m_mainWindow); } } void KonqNewSessionDlg::slotTextChanged(const QString &text) { enableButton(Ok, !text.isEmpty()); } KonqNewSessionDlg::~KonqNewSessionDlg() { } diff --git a/src/konqsessionmanager.cpp b/src/konqsessionmanager.cpp index 6112bc3de..56c16b24c 100644 --- a/src/konqsessionmanager.cpp +++ b/src/konqsessionmanager.cpp @@ -1,695 +1,695 @@ /* This file is part of the KDE project Copyright (C) 2008 Eduardo Robles Elvira This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "konqsessionmanager.h" #include "konqmisc.h" #include "konqmainwindow.h" #include "konqsessionmanager_interface.h" #include "konqsessionmanageradaptor.h" #include "konqviewmanager.h" #include "konqsettingsxt.h" #include #include "konqdebug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class KonqSessionManagerPrivate { public: KonqSessionManagerPrivate() : instance(nullptr) { } ~KonqSessionManagerPrivate() { delete instance; } KonqSessionManager *instance; }; K_GLOBAL_STATIC(KonqSessionManagerPrivate, myKonqSessionManagerPrivate) static QString viewIdFor(const QString &sessionFile, const QString &viewId) { return (sessionFile + viewId); } static const QList windowConfigGroups(/*NOT const, we'll use writeEntry*/ KConfig &config) { QList groups; KConfigGroup generalGroup(&config, "General"); const int size = generalGroup.readEntry("Number of Windows", 0); for (int i = 0; i < size; i++) { groups << KConfigGroup(&config, "Window" + QString::number(i)); } return groups; } SessionRestoreDialog::SessionRestoreDialog(const QStringList &sessionFilePaths, QWidget *parent) : KDialog(parent, nullptr) , m_sessionItemsCount(0) , m_dontShowChecked(false) { setCaption(i18nc("@title:window", "Restore Session?")); setButtons(KDialog::Yes | KDialog::No | KDialog::Cancel); setObjectName(QStringLiteral("restoresession")); setButtonGuiItem(KDialog::Yes, KGuiItem(i18nc("@action:button yes", "Restore Session"), QStringLiteral("window-new"))); setButtonGuiItem(KDialog::No, KGuiItem(i18nc("@action:button no", "Do Not Restore"), QStringLiteral("dialog-close"))); setButtonGuiItem(KDialog::Cancel, KGuiItem(i18nc("@action:button ask later", "Ask Me Later"), QStringLiteral("chronometer"))); setDefaultButton(KDialog::Yes); setButtonFocus(KDialog::Yes); setModal(true); QWidget *mainWidget = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget); mainLayout->setSpacing(KDialog::spacingHint() * 2); // provide extra spacing - mainLayout->setMargin(0); + mainLayout->setContentsMargins(0, 0, 0, 0); QHBoxLayout *hLayout = new QHBoxLayout(); - hLayout->setMargin(0); + hLayout->setContentsMargins(0, 0, 0, 0); hLayout->setSpacing(-1); // use default spacing mainLayout->addLayout(hLayout, 5); QIcon icon(QLatin1String("dialog-warning")); if (!icon.isNull()) { QLabel *iconLabel = new QLabel(mainWidget); QStyleOption option; option.initFrom(mainWidget); iconLabel->setPixmap(icon.pixmap(mainWidget->style()->pixelMetric(QStyle::PM_MessageBoxIconSize, &option, mainWidget))); QVBoxLayout *iconLayout = new QVBoxLayout(); iconLayout->addStretch(1); iconLayout->addWidget(iconLabel); iconLayout->addStretch(5); hLayout->addLayout(iconLayout, 0); } const QString text(i18n("Konqueror did not close correctly. Would you like to restore these previous sessions?")); QLabel *messageLabel = new QLabel(text, mainWidget); Qt::TextInteractionFlags flags = (Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); messageLabel->setTextInteractionFlags(flags); messageLabel->setWordWrap(true); hLayout->addSpacing(KDialog::spacingHint()); hLayout->addWidget(messageLabel, 5); Q_ASSERT(!sessionFilePaths.isEmpty()); m_treeWidget = new QTreeWidget(mainWidget); m_treeWidget->setHeader(nullptr); m_treeWidget->setHeaderHidden(true); m_treeWidget->setToolTip(i18nc("@tooltip:session list", "Uncheck the sessions you do not want to be restored")); QStyleOptionViewItem styleOption; styleOption.initFrom(m_treeWidget); QFontMetrics fm(styleOption.font); int w = m_treeWidget->width(); const QRect desktop = QApplication::desktop()->screenGeometry(this); // Collect info from the sessions to restore Q_FOREACH (const QString &sessionFile, sessionFilePaths) { qCDebug(KONQUEROR_LOG) << sessionFile; QTreeWidgetItem *windowItem = nullptr; KConfig config(sessionFile, KConfig::SimpleConfig); const QList groups = windowConfigGroups(config); Q_FOREACH (const KConfigGroup &group, groups) { // To avoid a recursive search, let's do linear search on Foo_CurrentHistoryItem=1 Q_FOREACH (const QString &key, group.keyList()) { if (key.endsWith(QLatin1String("_CurrentHistoryItem"))) { const QString viewId = key.left(key.length() - qstrlen("_CurrentHistoryItem")); const QString historyIndex = group.readEntry(key, QString()); const QString prefix = "HistoryItem" + viewId + '_' + historyIndex; // Ignore the sidebar views if (group.readEntry(prefix + "StrServiceName", QString()).startsWith(QLatin1String("konq_sidebar"))) { continue; } const QString url = group.readEntry(prefix + "Url", QString()); const QString title = group.readEntry(prefix + "Title", QString()); qCDebug(KONQUEROR_LOG) << viewId << url << title; const QString displayText = (title.trimmed().isEmpty() ? url : title); if (!displayText.isEmpty()) { if (!windowItem) { windowItem = new QTreeWidgetItem(m_treeWidget); const int index = sessionFilePaths.indexOf(sessionFile) + 1; windowItem->setText(0, i18nc("@item:treewidget", "Window %1", index)); windowItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); windowItem->setCheckState(0, Qt::Checked); windowItem->setExpanded(true); } QTreeWidgetItem *item = new QTreeWidgetItem(windowItem); item->setText(0, displayText); item->setData(0, Qt::UserRole, viewIdFor(sessionFile, viewId)); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); item->setCheckState(0, Qt::Checked); w = qMax(w, fm.width(displayText)); m_sessionItemsCount++; } } } } if (windowItem) { m_checkedSessionItems.insert(windowItem, windowItem->childCount()); } } const int borderWidth = m_treeWidget->width() - m_treeWidget->viewport()->width() + m_treeWidget->verticalScrollBar()->height(); w += borderWidth; if (w > desktop.width() * 0.85) { // limit treeWidget size to 85% of screen width w = qRound(desktop.width() * 0.85); } m_treeWidget->setMinimumWidth(w); mainLayout->addWidget(m_treeWidget, 50); m_treeWidget->setSelectionMode(QTreeWidget::NoSelection); messageLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); // Do not connect the itemChanged signal until after the treewidget // is completely populated to prevent the firing of the itemChanged // signal while in the process of adding the original session items. connect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(slotItemChanged(QTreeWidgetItem*,int))); QCheckBox *checkbox = new QCheckBox(i18n("Do not ask again"), mainWidget); connect(checkbox, &QCheckBox::clicked, this, &SessionRestoreDialog::slotClicked); mainLayout->addWidget(checkbox); setMainWidget(mainWidget); } SessionRestoreDialog::~SessionRestoreDialog() { } bool SessionRestoreDialog::isEmpty() const { return m_treeWidget->topLevelItemCount() == 0; } QStringList SessionRestoreDialog::discardedSessionList() const { return m_discardedSessionList; } bool SessionRestoreDialog::isDontShowChecked() const { return m_dontShowChecked; } void SessionRestoreDialog::slotClicked(bool checked) { m_dontShowChecked = checked; } void SessionRestoreDialog::slotItemChanged(QTreeWidgetItem *item, int column) { Q_ASSERT(item); const int itemChildCount = item->childCount(); QTreeWidgetItem *parentItem = nullptr; const bool blocked = item->treeWidget()->blockSignals(true); if (itemChildCount > 0) { parentItem = item; for (int i = 0; i < itemChildCount; ++i) { QTreeWidgetItem *childItem = item->child(i); if (childItem) { childItem->setCheckState(column, item->checkState(column)); switch (childItem->checkState(column)) { case Qt::Checked: m_sessionItemsCount++; m_discardedSessionList.removeAll(childItem->data(column, Qt::UserRole).toString()); m_checkedSessionItems[item]++; break; case Qt::Unchecked: m_sessionItemsCount--; m_discardedSessionList.append(childItem->data(column, Qt::UserRole).toString()); m_checkedSessionItems[item]--; break; default: break; } } } } else { parentItem = item->parent(); switch (item->checkState(column)) { case Qt::Checked: m_sessionItemsCount++; m_discardedSessionList.removeAll(item->data(column, Qt::UserRole).toString()); m_checkedSessionItems[parentItem]++; break; case Qt::Unchecked: m_sessionItemsCount--; m_discardedSessionList.append(item->data(column, Qt::UserRole).toString()); m_checkedSessionItems[parentItem]--; break; default: break; } } const int numCheckSessions = m_checkedSessionItems.value(parentItem); switch (parentItem->checkState(column)) { case Qt::Checked: if (numCheckSessions == 0) { parentItem->setCheckState(column, Qt::Unchecked); } case Qt::Unchecked: if (numCheckSessions > 0) { parentItem->setCheckState(column, Qt::Checked); } default: break; } enableButton(KDialog::Yes, m_sessionItemsCount > 0); item->treeWidget()->blockSignals(blocked); } void SessionRestoreDialog::saveDontShow(const QString &dontShowAgainName, int result) { if (dontShowAgainName.isEmpty()) { return; } KConfigGroup::WriteConfigFlags flags = KConfig::Persistent; if (dontShowAgainName[0] == ':') { flags |= KConfigGroup::Global; } KConfigGroup cg(KSharedConfig::openConfig().data(), "Notification Messages"); cg.writeEntry(dontShowAgainName, result == Yes, flags); cg.sync(); } bool SessionRestoreDialog::shouldBeShown(const QString &dontShowAgainName, int *result) { if (dontShowAgainName.isEmpty()) { return true; } KConfigGroup cg(KSharedConfig::openConfig().data(), "Notification Messages"); const QString dontAsk = cg.readEntry(dontShowAgainName, QString()).toLower(); if (dontAsk == QLatin1String("yes") || dontAsk == QLatin1String("true")) { if (result) { *result = Yes; } return false; } if (dontAsk == QLatin1String("no") || dontAsk == QLatin1String("false")) { if (result) { *result = No; } return false; } return true; } KonqSessionManager::KonqSessionManager() : m_autosaveDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + "autosave") , m_autosaveEnabled(false) // so that enableAutosave works , m_createdOwnedByDir(false) , m_sessionConfig(nullptr) { // Initialize dbus interfaces new KonqSessionManagerAdaptor(this); const QString dbusPath = QStringLiteral("/KonqSessionManager"); const QString dbusInterface = QStringLiteral("org.kde.Konqueror.SessionManager"); QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.registerObject(dbusPath, this); m_baseService = KonqMisc::encodeFilename(dbus.baseService()); dbus.connect(QString(), dbusPath, dbusInterface, QStringLiteral("saveCurrentSession"), this, SLOT(slotSaveCurrentSession(QString))); // Initialize the timer const int interval = KonqSettings::autoSaveInterval(); if (interval > 0) { m_autoSaveTimer.setInterval(interval * 1000); connect(&m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSaveSession())); } enableAutosave(); connect(qApp, &QGuiApplication::commitDataRequest, this, &KonqSessionManager::slotCommitData); } KonqSessionManager::~KonqSessionManager() { if (m_sessionConfig) { QFile::remove(m_sessionConfig->name()); } delete m_sessionConfig; } // Don't restore preloaded konquerors void KonqSessionManager::slotCommitData(QSessionManager &sm) { if (!m_autosaveEnabled) { sm.setRestartHint(QSessionManager::RestartNever); } } void KonqSessionManager::disableAutosave() { if (!m_autosaveEnabled) { return; } m_autosaveEnabled = false; m_autoSaveTimer.stop(); if (m_sessionConfig) { QFile::remove(m_sessionConfig->name()); delete m_sessionConfig; m_sessionConfig = nullptr; } } void KonqSessionManager::enableAutosave() { if (m_autosaveEnabled) { return; } // Create the config file for autosaving current session QString filename = QLatin1String("autosave/") + m_baseService; const QString filePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + filename; delete m_sessionConfig; m_sessionConfig = new KConfig(filePath, KConfig::SimpleConfig); //qCDebug(KONQUEROR_LOG) << "config filename:" << m_sessionConfig->name(); m_autosaveEnabled = true; m_autoSaveTimer.start(); } void KonqSessionManager::deleteOwnedSessions() { // Not dealing with the sessions about to remove anymore if (m_createdOwnedByDir && KTempDir::removeDir(dirForMyOwnedSessionFiles())) { m_createdOwnedByDir = false; } } KonqSessionManager *KonqSessionManager::self() { if (!myKonqSessionManagerPrivate->instance) { myKonqSessionManagerPrivate->instance = new KonqSessionManager(); } return myKonqSessionManagerPrivate->instance; } void KonqSessionManager::autoSaveSession() { if (!m_autosaveEnabled) { return; } const bool isActive = m_autoSaveTimer.isActive(); if (isActive) { m_autoSaveTimer.stop(); } saveCurrentSessionToFile(m_sessionConfig); m_sessionConfig->sync(); m_sessionConfig->markAsClean(); // Now that we have saved current session it's safe to remove our owned_by // directory deleteOwnedSessions(); if (isActive) { m_autoSaveTimer.start(); } } void KonqSessionManager::saveCurrentSessions(const QString &path) { emit saveCurrentSession(path); } void KonqSessionManager::slotSaveCurrentSession(const QString &path) { const QString filename = path + '/' + m_baseService; saveCurrentSessionToFile(filename); } void KonqSessionManager::saveCurrentSessionToFile(const QString &sessionConfigPath, KonqMainWindow *mainWindow) { QFile::remove(sessionConfigPath); KConfig config(sessionConfigPath, KConfig::SimpleConfig); QList mainWindows; if (mainWindow) { mainWindows << mainWindow; } saveCurrentSessionToFile(&config, mainWindows); } void KonqSessionManager::saveCurrentSessionToFile(KConfig *config, const QList &theMainWindows) { QList mainWindows = theMainWindows; if (mainWindows.isEmpty() && KonqMainWindow::mainWindowList()) { mainWindows = *KonqMainWindow::mainWindowList(); } unsigned int counter = 0; if (mainWindows.isEmpty()) { return; } foreach (KonqMainWindow *window, mainWindows) { if (!window->isPreloaded()) { KConfigGroup configGroup(config, "Window" + QString::number(counter)); window->saveProperties(configGroup); counter++; } } KConfigGroup configGroup(config, "General"); configGroup.writeEntry("Number of Windows", counter); } QString KonqSessionManager::autosaveDirectory() const { return m_autosaveDir; } QStringList KonqSessionManager::takeSessionsOwnership() { // Tell to other konqueror instances that we are the one dealing with // these sessions QDir dir(dirForMyOwnedSessionFiles()); QDir parentDir(m_autosaveDir); if (!dir.exists()) { m_createdOwnedByDir = parentDir.mkdir("owned_by" + m_baseService); } QDirIterator it(m_autosaveDir, QDir::Writable | QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); QStringList sessionFilePaths; QDBusConnectionInterface *idbus = QDBusConnection::sessionBus().interface(); while (it.hasNext()) { it.next(); // this is the case where another konq started to restore that session, // but crashed immediately. So we try to restore that session again if (it.fileInfo().isDir()) { // The remove() removes the "owned_by" part if (!idbus->isServiceRegistered( KonqMisc::decodeFilename(it.fileName().remove(0, 8)))) { QDirIterator it2(it.filePath(), QDir::Writable | QDir::Files); while (it2.hasNext()) { it2.next(); // take ownership of the abandoned file const QString newFileName = dirForMyOwnedSessionFiles() + '/' + it2.fileName(); QFile::rename(it2.filePath(), newFileName); sessionFilePaths.append(newFileName); } // Remove the old directory KTempDir::removeDir(it.filePath()); } } else { // it's a file if (!idbus->isServiceRegistered(KonqMisc::decodeFilename(it.fileName()))) { // and it's abandoned: take its ownership const QString newFileName = dirForMyOwnedSessionFiles() + '/' + it.fileName(); QFile::rename(it.filePath(), newFileName); sessionFilePaths.append(newFileName); } } } return sessionFilePaths; } void KonqSessionManager::restoreSessions(const QStringList &sessionFilePathsList, bool openTabsInsideCurrentWindow, KonqMainWindow *parent) { foreach (const QString &sessionFilePath, sessionFilePathsList) { restoreSession(sessionFilePath, openTabsInsideCurrentWindow, parent); } } void KonqSessionManager::restoreSessions(const QString &sessionsDir, bool openTabsInsideCurrentWindow, KonqMainWindow *parent) { QDirIterator it(sessionsDir, QDir::Readable | QDir::Files); while (it.hasNext()) { QFileInfo fi(it.next()); restoreSession(fi.filePath(), openTabsInsideCurrentWindow, parent); } } void KonqSessionManager::restoreSession(const QString &sessionFilePath, bool openTabsInsideCurrentWindow, KonqMainWindow *parent) { if (!QFile::exists(sessionFilePath)) { return; } KConfig config(sessionFilePath, KConfig::SimpleConfig); const QList groups = windowConfigGroups(config); Q_FOREACH (const KConfigGroup &configGroup, groups) { if (!openTabsInsideCurrentWindow) { KonqViewManager::openSavedWindow(configGroup)->show(); } else { parent->viewManager()->openSavedWindow(configGroup, true); } } } static void removeDiscardedSessions(const QStringList &sessionFiles, const QStringList &discardedSessions) { if (discardedSessions.isEmpty()) { return; } Q_FOREACH (const QString &sessionFile, sessionFiles) { KConfig config(sessionFile, KConfig::SimpleConfig); QList groups = windowConfigGroups(config); for (int i = 0, count = groups.count(); i < count; ++i) { KConfigGroup &group = groups[i]; const QString rootItem = group.readEntry("RootItem", "empty"); const QString viewsKey(rootItem + QLatin1String("_Children")); QStringList views = group.readEntry(viewsKey, QStringList()); QMutableStringListIterator it(views); while (it.hasNext()) { if (discardedSessions.contains(viewIdFor(sessionFile, it.next()))) { it.remove(); } } group.writeEntry(viewsKey, views); } } } bool KonqSessionManager::askUserToRestoreAutosavedAbandonedSessions() { const QStringList sessionFilePaths = takeSessionsOwnership(); if (sessionFilePaths.isEmpty()) { return false; } disableAutosave(); int result; QStringList discardedSessionList; const QLatin1String dontAskAgainName("Restore session when konqueror didn't close correctly"); if (SessionRestoreDialog::shouldBeShown(dontAskAgainName, &result)) { SessionRestoreDialog *restoreDlg = new SessionRestoreDialog(sessionFilePaths); if (restoreDlg->isEmpty()) { result = KDialog::No; } else { result = restoreDlg->exec(); discardedSessionList = restoreDlg->discardedSessionList(); if (restoreDlg->isDontShowChecked()) { SessionRestoreDialog::saveDontShow(dontAskAgainName, result); } } delete restoreDlg; } switch (result) { case KDialog::Yes: // Remove the discarded session list files. removeDiscardedSessions(sessionFilePaths, discardedSessionList); restoreSessions(sessionFilePaths); enableAutosave(); return true; case KDialog::No: deleteOwnedSessions(); enableAutosave(); return false; default: // Remove the ownership of the currently owned files QDirIterator it(dirForMyOwnedSessionFiles(), QDir::Writable | QDir::Files); while (it.hasNext()) { it.next(); // remove ownership of the abandoned file QFile::rename(it.filePath(), m_autosaveDir + '/' + it.fileName()); } // Remove the owned_by directory KTempDir::removeDir(dirForMyOwnedSessionFiles()); enableAutosave(); return false; } }