id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
748,831
savejob.cpp
KDE_gwenview/lib/document/savejob.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "savejob.h" // Qt #include <QApplication> #include <QFuture> #include <QFutureWatcher> #include <QSaveFile> #include <QScopedPointer> #include <QTemporaryFile> #include <QUrl> #include <QtConcurrentRun> // KF #include <KIO/CopyJob> #include <KIO/JobUiDelegate> #include <KJobWidgets> #include <KLocalizedString> // Local #include "documentloadedimpl.h" namespace Gwenview { struct SaveJobPrivate { DocumentLoadedImpl *mImpl = nullptr; QUrl mOldUrl; QUrl mNewUrl; QByteArray mFormat; QScopedPointer<QTemporaryFile> mTemporaryFile; QScopedPointer<QSaveFile> mSaveFile; QScopedPointer<QFutureWatcher<void>> mInternalSaveWatcher; bool mKillReceived; }; SaveJob::SaveJob(DocumentLoadedImpl *impl, const QUrl &url, const QByteArray &format) : d(new SaveJobPrivate) { d->mImpl = impl; d->mOldUrl = impl->document()->url(); d->mNewUrl = url; d->mFormat = format; d->mKillReceived = false; setCapabilities(Killable); } SaveJob::~SaveJob() { delete d; } void SaveJob::saveInternal() { if (!d->mImpl->saveInternal(d->mSaveFile.data(), d->mFormat)) { d->mSaveFile->cancelWriting(); setError(UserDefinedError + 2); setErrorText(d->mImpl->document()->errorString()); } } void SaveJob::doStart() { if (d->mKillReceived) { return; } QString fileName; if (d->mNewUrl.isLocalFile()) { fileName = d->mNewUrl.toLocalFile(); } else { d->mTemporaryFile.reset(new QTemporaryFile); d->mTemporaryFile->setAutoRemove(true); d->mTemporaryFile->open(); fileName = d->mTemporaryFile->fileName(); } d->mSaveFile.reset(new QSaveFile(fileName)); if (!d->mSaveFile->open(QSaveFile::WriteOnly)) { QUrl dirUrl = d->mNewUrl; dirUrl = dirUrl.adjusted(QUrl::RemoveFilename); setError(UserDefinedError + 1); // Don't use xi18n* with markup substitution here, this is done in GvCore::slotSaveResult or SaveAllHelper::slotResult setErrorText(i18nc("@info", "Could not open file for writing, check that you have the necessary rights in <filename>%1</filename>.", dirUrl.toDisplayString(QUrl::PreferLocalFile))); uiDelegate()->setAutoErrorHandlingEnabled(false); uiDelegate()->setAutoWarningHandlingEnabled(false); emitResult(); return; } QFuture<void> future = QtConcurrent::run(&SaveJob::saveInternal, this); d->mInternalSaveWatcher.reset(new QFutureWatcher<void>(this)); connect(d->mInternalSaveWatcher.data(), &QFutureWatcherBase::finished, this, &SaveJob::finishSave); d->mInternalSaveWatcher->setFuture(future); } void SaveJob::finishSave() { d->mInternalSaveWatcher.reset(nullptr); if (d->mKillReceived) { return; } if (error()) { emitResult(); return; } if (!d->mSaveFile->commit()) { setErrorText( xi18nc("@info", "Could not overwrite file, check that you have the necessary rights to write in <filename>%1</filename>.", d->mNewUrl.toString())); setError(UserDefinedError + 3); return; } if (d->mNewUrl.isLocalFile()) { emitResult(); } else { KIO::Job *job = KIO::copy(QUrl::fromLocalFile(d->mTemporaryFile->fileName()), d->mNewUrl); KJobWidgets::setWindow(job, qApp->activeWindow()); addSubjob(job); } } void SaveJob::slotResult(KJob *job) { DocumentJob::slotResult(job); if (!error()) { emitResult(); } } QUrl SaveJob::oldUrl() const { return d->mOldUrl; } QUrl SaveJob::newUrl() const { return d->mNewUrl; } bool SaveJob::doKill() { d->mKillReceived = true; if (d->mInternalSaveWatcher) { d->mInternalSaveWatcher->waitForFinished(); } return true; } } // namespace #include "moc_savejob.cpp"
4,721
C++
.cpp
150
26.913333
159
0.694035
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,832
documentfactory.cpp
KDE_gwenview/lib/document/documentfactory.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "documentfactory.h" // Qt #include <QByteArray> #include <QDateTime> #include <QMap> #include <QUndoGroup> #include <QUrl> // KF // Local #include "gwenview_lib_debug.h" #include <gvdebug.h> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_LIB_LOG) << x #else #define LOG(x) ; #endif inline int getMaxUnreferencedImages() { int defaultValue = 3; QByteArray ba = qgetenv("GV_MAX_UNREFERENCED_IMAGES"); if (ba.isEmpty()) { return defaultValue; } LOG("Custom value for max unreferenced images:" << ba); bool ok; const int value = ba.toInt(&ok); return ok ? value : defaultValue; } static const int MAX_UNREFERENCED_IMAGES = getMaxUnreferencedImages(); /** * This internal structure holds the document and the last time it has been * accessed. This access time is used to "garbage collect" the loaded * documents. */ struct DocumentInfo { Document::Ptr mDocument; QDateTime mLastAccess; }; /** * Our collection of DocumentInfo instances. We keep them as pointers to avoid * altering DocumentInfo::mDocument refcount, since we rely on it to garbage * collect documents. */ using DocumentMap = QMap<QUrl, DocumentInfo *>; struct DocumentFactoryPrivate { DocumentMap mDocumentMap; QUndoGroup mUndoGroup; /** * Removes items in a map if they are no longer referenced elsewhere */ void garbageCollect(DocumentMap &map) { // Build a map of all unreferenced images. We use a MultiMap because in // rare cases documents may get accessed at the same millisecond. // See https://bugs.kde.org/show_bug.cgi?id=296401 using UnreferencedImages = QMultiMap<QDateTime, QUrl>; UnreferencedImages unreferencedImages; DocumentMap::Iterator it = map.begin(), end = map.end(); for (; it != end; ++it) { DocumentInfo *info = it.value(); if (info->mDocument->ref == 1 && !info->mDocument->isModified()) { unreferencedImages.insert(info->mLastAccess, it.key()); } } // Remove oldest unreferenced images. Since the map is sorted by key, // the oldest one is always unreferencedImages.begin(). for (UnreferencedImages::Iterator unreferencedIt = unreferencedImages.begin(); unreferencedImages.count() > MAX_UNREFERENCED_IMAGES; unreferencedIt = unreferencedImages.erase(unreferencedIt)) { const QUrl url = unreferencedIt.value(); LOG("Collecting" << url); it = map.find(url); Q_ASSERT(it != map.end()); delete it.value(); map.erase(it); } #ifdef ENABLE_LOG logDocumentMap(map); #endif } void logDocumentMap(const DocumentMap &map) { LOG("map:"); DocumentMap::ConstIterator it = map.constBegin(), end = map.constEnd(); for (; it != end; ++it) { LOG("-" << it.key() << "refCount=" << it.value()->mDocument.count() << "lastAccess=" << it.value()->mLastAccess); } } QList<QUrl> mModifiedDocumentList; }; DocumentFactory::DocumentFactory() : d(new DocumentFactoryPrivate) { } DocumentFactory::~DocumentFactory() { qDeleteAll(d->mDocumentMap); delete d; } DocumentFactory *DocumentFactory::instance() { static DocumentFactory factory; return &factory; } Document::Ptr DocumentFactory::getCachedDocument(const QUrl &url) const { const DocumentInfo *info = d->mDocumentMap.value(url); return info ? info->mDocument : Document::Ptr(); } Document::Ptr DocumentFactory::load(const QUrl &url) { GV_RETURN_VALUE_IF_FAIL(!url.isEmpty(), Document::Ptr()); DocumentInfo *info = nullptr; DocumentMap::Iterator it = d->mDocumentMap.find(url); if (it != d->mDocumentMap.end()) { LOG(url.fileName() << "url in mDocumentMap"); info = it.value(); info->mLastAccess = QDateTime::currentDateTime(); return info->mDocument; } // At this point we couldn't find the document in the map // Start loading the document LOG(url.fileName() << "loading"); auto doc = new Document(url); connect(doc, &Document::loaded, this, &DocumentFactory::slotLoaded); connect(doc, &Document::saved, this, &DocumentFactory::slotSaved); connect(doc, &Document::modified, this, &DocumentFactory::slotModified); connect(doc, &Document::busyChanged, this, &DocumentFactory::slotBusyChanged); // Make sure that an url passed as command line argument is loaded // and shown before a possibly long running dirlister on a slow // network device is started. So start the dirlister after url is // loaded or failed to load. connect(doc, &Document::loaded, [this, url]() { Q_EMIT readyForDirListerStart(url); }); connect(doc, &Document::loadingFailed, [this, url]() { Q_EMIT readyForDirListerStart(url); }); connect(doc, &Document::downSampledImageReady, [this, url]() { Q_EMIT readyForDirListerStart(url); }); doc->reload(); // Create DocumentInfo instance info = new DocumentInfo; Document::Ptr docPtr(doc); info->mDocument = docPtr; info->mLastAccess = QDateTime::currentDateTime(); // Place DocumentInfo in the map d->mDocumentMap[url] = info; d->garbageCollect(d->mDocumentMap); return docPtr; } QList<QUrl> DocumentFactory::modifiedDocumentList() const { return d->mModifiedDocumentList; } bool DocumentFactory::hasUrl(const QUrl &url) const { return d->mDocumentMap.contains(url); } void DocumentFactory::clearCache() { qDeleteAll(d->mDocumentMap); d->mDocumentMap.clear(); d->mModifiedDocumentList.clear(); } void DocumentFactory::slotLoaded(const QUrl &url) { if (d->mModifiedDocumentList.contains(url)) { d->mModifiedDocumentList.removeAll(url); Q_EMIT modifiedDocumentListChanged(); Q_EMIT documentChanged(url); } } void DocumentFactory::slotSaved(const QUrl &oldUrl, const QUrl &newUrl) { const bool oldIsNew = oldUrl == newUrl; const bool oldUrlWasModified = d->mModifiedDocumentList.removeOne(oldUrl); bool newUrlWasModified = false; if (!oldIsNew) { newUrlWasModified = d->mModifiedDocumentList.removeOne(newUrl); DocumentInfo *info = d->mDocumentMap.take(oldUrl); d->mDocumentMap.insert(newUrl, info); } d->garbageCollect(d->mDocumentMap); if (oldUrlWasModified || newUrlWasModified) { Q_EMIT modifiedDocumentListChanged(); } if (oldUrlWasModified) { Q_EMIT documentChanged(oldUrl); } if (!oldIsNew) { Q_EMIT documentChanged(newUrl); } } void DocumentFactory::slotModified(const QUrl &url) { if (!d->mModifiedDocumentList.contains(url)) { d->mModifiedDocumentList << url; Q_EMIT modifiedDocumentListChanged(); } Q_EMIT documentChanged(url); } void DocumentFactory::slotBusyChanged(const QUrl &url, bool busy) { Q_EMIT documentBusyStateChanged(url, busy); } QUndoGroup *DocumentFactory::undoGroup() { return &d->mUndoGroup; } void DocumentFactory::forget(const QUrl &url) { DocumentInfo *info = d->mDocumentMap.take(url); if (!info) { return; } delete info; if (d->mModifiedDocumentList.contains(url)) { d->mModifiedDocumentList.removeAll(url); Q_EMIT modifiedDocumentListChanged(); } } } // namespace #include "moc_documentfactory.cpp"
8,293
C++
.cpp
244
29.352459
140
0.696913
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,833
loadingjob.cpp
KDE_gwenview/lib/document/loadingjob.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "loadingjob.h" // Qt #include <QUrl> // KF #include <KLocalizedString> // Local #include "gwenview_lib_debug.h" namespace Gwenview { void LoadingJob::doStart() { Document::LoadingState state = document()->loadingState(); if (state == Document::Loaded || state == Document::LoadingFailed) { setError(NoError); emitResult(); } else { connect(document().data(), &Document::loaded, this, &LoadingJob::slotLoaded); connect(document().data(), &Document::loadingFailed, this, &LoadingJob::slotLoadingFailed); } } void LoadingJob::slotLoaded() { setError(NoError); emitResult(); } void LoadingJob::slotLoadingFailed() { setError(UserDefinedError + 1); setErrorText(i18n("Could not load document %1", document()->url().toDisplayString())); emitResult(); } } // namespace #include "moc_loadingjob.cpp"
1,700
C++
.cpp
50
31.36
99
0.75
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,834
loadingdocumentimpl.cpp
KDE_gwenview/lib/document/loadingdocumentimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "loadingdocumentimpl.h" // STL #include <memory> // Exiv2 #include <exiv2/exiv2.hpp> // Qt #include <QBuffer> #include <QByteArray> #include <QColorSpace> #include <QFile> #include <QFuture> #include <QFutureWatcher> #include <QImage> #include <QImageReader> #include <QPointer> #include <QUrl> #include <QtConcurrent> // KF #include <KIO/TransferJob> #include <KLocalizedString> #include <KProtocolInfo> #ifdef KDCRAW_FOUND #include <kdcraw/kdcraw.h> #endif // Local #include "animateddocumentloadedimpl.h" #include "cms/cmsprofile.h" #include "document.h" #include "documentloadedimpl.h" #include "emptydocumentimpl.h" #include "exiv2imageloader.h" #include "gvdebug.h" #include "gwenview_lib_debug.h" #include "gwenviewconfig.h" #include "jpegcontent.h" #include "jpegdocumentloadedimpl.h" #include "svgdocumentloadedimpl.h" #include "urlutils.h" #include "videodocumentloadedimpl.h" namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) // qCDebug(GWENVIEW_LIB_LOG) << x #else #define LOG(x) ; #endif const int HEADER_SIZE = 256; struct LoadingDocumentImplPrivate { LoadingDocumentImpl *q; QPointer<KIO::TransferJob> mTransferJob; QFuture<bool> mMetaInfoFuture; QFutureWatcher<bool> mMetaInfoFutureWatcher; QFuture<void> mImageDataFuture; QFutureWatcher<void> mImageDataFutureWatcher; // If != 0, this means we need to load an image at zoom = // 1/mImageDataInvertedZoom int mImageDataInvertedZoom; bool mMetaInfoLoaded; bool mAnimated; bool mDownSampledImageLoaded; QByteArray mFormatHint; QByteArray mData; QByteArray mFormat; QSize mImageSize; std::unique_ptr<Exiv2::Image> mExiv2Image; std::unique_ptr<JpegContent> mJpegContent; QImage mImage; Cms::Profile::Ptr mCmsProfile; QMimeType mMimeType; /** * Determine kind of document and switch to an implementation if it is not * necessary to download more data. * @return true if switched to another implementation. */ bool determineKind() { const QUrl &url = q->document()->url(); QMimeDatabase db; if (KProtocolInfo::determineMimetypeFromExtension(url.scheme())) { mMimeType = db.mimeTypeForFileNameAndData(url.fileName(), mData); } else { mMimeType = db.mimeTypeForData(mData); } MimeTypeUtils::Kind kind = MimeTypeUtils::mimeTypeKind(mMimeType.name()); LOG("mimeType:" << mMimeType.name()); LOG("kind:" << kind); q->setDocumentKind(kind); switch (kind) { case MimeTypeUtils::KIND_RASTER_IMAGE: case MimeTypeUtils::KIND_SVG_IMAGE: return false; case MimeTypeUtils::KIND_VIDEO: q->switchToImpl(new VideoDocumentLoadedImpl(q->document())); return true; default: q->setDocumentErrorString(i18nc("@info", "Gwenview cannot display documents of type %1.", mMimeType.name())); Q_EMIT q->loadingFailed(); q->switchToImpl(new EmptyDocumentImpl(q->document())); return true; } } void startLoading() { Q_ASSERT(!mMetaInfoLoaded); switch (q->document()->kind()) { case MimeTypeUtils::KIND_RASTER_IMAGE: // The hint is used to: // - Speed up loadMetaInfo(): QImageReader will try to decode the // image using plugins matching this format first. // - Avoid breakage: Because of a bug in Qt TGA image plugin, some // PNG were incorrectly identified as PCX! See: // https://bugs.kde.org/show_bug.cgi?id=289819 // mFormatHint = mMimeType.preferredSuffix().toLocal8Bit().toLower(); mMetaInfoFuture = QtConcurrent::run(&LoadingDocumentImplPrivate::loadMetaInfo, this); mMetaInfoFutureWatcher.setFuture(mMetaInfoFuture); break; case MimeTypeUtils::KIND_SVG_IMAGE: q->switchToImpl(new SvgDocumentLoadedImpl(q->document(), mData)); break; case MimeTypeUtils::KIND_VIDEO: break; default: qCWarning(GWENVIEW_LIB_LOG) << "We should not reach this point!"; break; } } void startImageDataLoading() { LOG(""); Q_ASSERT(mMetaInfoLoaded); Q_ASSERT(mImageDataInvertedZoom != 0); Q_ASSERT(!mImageDataFuture.isRunning()); mImageDataFuture = QtConcurrent::run(&LoadingDocumentImplPrivate::loadImageData, this); mImageDataFutureWatcher.setFuture(mImageDataFuture); } bool loadMetaInfo() { LOG("mFormatHint" << mFormatHint); QBuffer buffer; buffer.setBuffer(&mData); buffer.open(QIODevice::ReadOnly); Exiv2ImageLoader loader; if (loader.load(mData)) { mExiv2Image = loader.popImage(); } QImageReader reader; #ifdef KDCRAW_FOUND if (!QImageReader::supportedImageFormats().contains(QByteArray("raw")) && KDcrawIface::KDcraw::rawFilesList().contains(QString::fromLatin1(mFormatHint))) { QByteArray previewData; // if the image is in format supported by dcraw, fetch its embedded preview mJpegContent = std::make_unique<JpegContent>(); // use KDcraw for getting the embedded preview // KDcraw functionality cloned locally (temp. solution) bool ret = KDcrawIface::KDcraw::loadEmbeddedPreview(previewData, buffer); if (!ret) { // if the embedded preview loading failed, load half preview instead. // That's slower but it works even for images containing // small (160x120px) or none embedded preview. if (!KDcrawIface::KDcraw::loadHalfPreview(previewData, buffer)) { qCWarning(GWENVIEW_LIB_LOG) << "unable to get half preview for " << q->document()->url().fileName(); return false; } } buffer.close(); // now it's safe to replace mData with the jpeg data mData = previewData; // need to fill mFormat so gwenview can tell the type when trying to save mFormat = mFormatHint; } else { #else { #endif reader.setFormat(mFormatHint); reader.setDevice(&buffer); mImageSize = reader.size(); if (!reader.canRead()) { qCWarning(GWENVIEW_LIB_LOG) << "QImageReader::read() using format hint" << mFormatHint << "failed:" << reader.errorString(); if (buffer.pos() != 0) { qCWarning(GWENVIEW_LIB_LOG) << "A bad Qt image decoder moved the buffer to" << buffer.pos() << "in a call to canRead()! Rewinding."; buffer.seek(0); } reader.setFormat(QByteArray()); // Set buffer again, otherwise QImageReader won't restart from scratch reader.setDevice(&buffer); if (!reader.canRead()) { qCWarning(GWENVIEW_LIB_LOG) << "QImageReader::read() without format hint failed:" << reader.errorString(); return false; } qCWarning(GWENVIEW_LIB_LOG) << "Image format is actually" << reader.format() << "not" << mFormatHint; } mFormat = reader.format(); if (mFormat == "jpg") { // if mFormatHint was "jpg", then mFormat is "jpg", but the rest of // Gwenview code assumes JPEG images have "jpeg" format. mFormat = "jpeg"; } } LOG("mFormat" << mFormat); GV_RETURN_VALUE_IF_FAIL(!mFormat.isEmpty(), false); if (mFormat == "jpeg" && mExiv2Image.get()) { mJpegContent = std::make_unique<JpegContent>(); } if (mJpegContent.get()) { if (!mJpegContent->loadFromData(mData, mExiv2Image.get()) && !mJpegContent->loadFromData(mData)) { qCWarning(GWENVIEW_LIB_LOG) << "Unable to use preview of " << q->document()->url().fileName(); return false; } // Use the size from JpegContent, as its correctly transposed if the // image has been rotated mImageSize = mJpegContent->size(); mCmsProfile = Cms::Profile::loadFromExiv2Image(mExiv2Image.get()); } LOG("mImageSize" << mImageSize); if (!mCmsProfile) { mCmsProfile = Cms::Profile::loadFromImageData(mData, mFormat); } if (!mCmsProfile && reader.canRead()) { const QImage qtimage = reader.read(); if (!qtimage.isNull()) { mCmsProfile = Cms::Profile::loadFromICC(qtimage.colorSpace().iccProfile()); } } return true; } void loadImageData() { QBuffer buffer; buffer.setBuffer(&mData); buffer.open(QIODevice::ReadOnly); QImageReader reader(&buffer, mFormat); LOG("mImageDataInvertedZoom=" << mImageDataInvertedZoom); if (mImageSize.isValid() && mImageDataInvertedZoom != 1 && reader.supportsOption(QImageIOHandler::ScaledSize)) { // Do not use mImageSize here: QImageReader needs a non-transposed // image size QSize size = reader.size() / mImageDataInvertedZoom; if (!size.isEmpty()) { LOG("Setting scaled size to" << size); reader.setScaledSize(size); } else { LOG("Not setting scaled size as it is empty" << size); } } if (GwenviewConfig::applyExifOrientation()) { reader.setAutoTransform(true); } bool ok = reader.read(&mImage); if (!ok) { LOG("QImageReader::read() failed"); return; } if (reader.supportsAnimation() && reader.nextImageDelay() > 0 // Assume delay == 0 <=> only one frame ) { /* * QImageReader is not really helpful to detect animated gif: * - QImageReader::imageCount() returns 0 * - QImageReader::nextImageDelay() may return something > 0 if the * image consists of only one frame but includes a "Graphic * Control Extension" (usually only present if we have an * animation) (Bug #185523) * * Decoding the next frame is the only reliable way I found to * detect an animated gif */ LOG("May be an animated image. delay:" << reader.nextImageDelay()); QImage nextImage; if (reader.read(&nextImage)) { LOG("Really an animated image (more than one frame)"); mAnimated = true; } else { qCWarning(GWENVIEW_LIB_LOG) << q->document()->url() << "is not really an animated image (only one frame)"; } } } }; LoadingDocumentImpl::LoadingDocumentImpl(Document *document) : AbstractDocumentImpl(document) , d(new LoadingDocumentImplPrivate) { d->q = this; d->mMetaInfoLoaded = false; d->mAnimated = false; d->mDownSampledImageLoaded = false; d->mImageDataInvertedZoom = 0; connect(&d->mMetaInfoFutureWatcher, &QFutureWatcherBase::finished, this, &LoadingDocumentImpl::slotMetaInfoLoaded); connect(&d->mImageDataFutureWatcher, &QFutureWatcherBase::finished, this, &LoadingDocumentImpl::slotImageLoaded); } LoadingDocumentImpl::~LoadingDocumentImpl() { LOG(""); // Disconnect watchers to make sure they do not trigger further work d->mMetaInfoFutureWatcher.disconnect(); d->mImageDataFutureWatcher.disconnect(); d->mMetaInfoFutureWatcher.waitForFinished(); d->mImageDataFutureWatcher.waitForFinished(); if (d->mTransferJob) { d->mTransferJob->kill(); } delete d; } void LoadingDocumentImpl::init() { QUrl url = document()->url(); if (UrlUtils::urlIsFastLocalFile(url)) { // Load file content directly QFile file(url.toLocalFile()); if (!file.open(QIODevice::ReadOnly)) { setDocumentErrorString(i18nc("@info", "Could not open file %1", url.toLocalFile())); Q_EMIT loadingFailed(); switchToImpl(new EmptyDocumentImpl(document())); return; } d->mData = file.read(HEADER_SIZE); if (d->determineKind()) { return; } d->mData += file.readAll(); d->startLoading(); } else { // Transfer file via KIO d->mTransferJob = KIO::get(document()->url(), KIO::NoReload, KIO::HideProgressInfo); connect(d->mTransferJob.data(), &KIO::TransferJob::data, this, &LoadingDocumentImpl::slotDataReceived); connect(d->mTransferJob.data(), &KJob::result, this, &LoadingDocumentImpl::slotTransferFinished); d->mTransferJob->start(); } } void LoadingDocumentImpl::loadImage(int invertedZoom) { if (d->mImageDataInvertedZoom == invertedZoom) { LOG("Already loading an image at invertedZoom=" << invertedZoom); return; } if (d->mImageDataInvertedZoom == 1) { LOG("Ignoring request: we are loading a full image"); return; } d->mImageDataFutureWatcher.waitForFinished(); d->mImageDataInvertedZoom = invertedZoom; if (d->mMetaInfoLoaded) { // Do not test on mMetaInfoFuture.isRunning() here: it might not have // started if we are downloading the image from a remote url d->startImageDataLoading(); } } void LoadingDocumentImpl::slotDataReceived(KIO::Job *job, const QByteArray &chunk) { d->mData.append(chunk); if (document()->kind() == MimeTypeUtils::KIND_UNKNOWN && d->mData.length() >= HEADER_SIZE) { if (d->determineKind()) { job->kill(); return; } } } void LoadingDocumentImpl::slotTransferFinished(KJob *job) { if (job->error()) { setDocumentErrorString(job->errorString()); Q_EMIT loadingFailed(); switchToImpl(new EmptyDocumentImpl(document())); return; } else if (document()->kind() == MimeTypeUtils::KIND_UNKNOWN) { // Transfer finished. If the mime type is still unknown (e.g. for files < HEADER_SIZE) // determine the kind again. if (d->determineKind()) { return; } } d->startLoading(); } bool LoadingDocumentImpl::isEditable() const { return d->mDownSampledImageLoaded; } Document::LoadingState LoadingDocumentImpl::loadingState() const { if (!document()->image().isNull()) { return Document::Loaded; } else if (d->mMetaInfoLoaded) { return Document::MetaInfoLoaded; } else if (document()->kind() != MimeTypeUtils::KIND_UNKNOWN) { return Document::KindDetermined; } else { return Document::Loading; } } void LoadingDocumentImpl::slotMetaInfoLoaded() { LOG(""); Q_ASSERT(!d->mMetaInfoFuture.isRunning()); if (!d->mMetaInfoFuture.result()) { setDocumentErrorString(i18nc("@info", "Loading meta information failed.")); Q_EMIT loadingFailed(); switchToImpl(new EmptyDocumentImpl(document())); return; } setDocumentFormat(d->mFormat); setDocumentImageSize(d->mImageSize); setDocumentExiv2Image(std::move(d->mExiv2Image)); setDocumentCmsProfile(d->mCmsProfile); d->mMetaInfoLoaded = true; Q_EMIT metaInfoLoaded(); // Start image loading if necessary // We test if mImageDataFuture is not already running because code connected to // metaInfoLoaded() signal could have called loadImage() if (!d->mImageDataFuture.isRunning() && d->mImageDataInvertedZoom != 0) { d->startImageDataLoading(); } } void LoadingDocumentImpl::slotImageLoaded() { LOG(""); if (d->mImage.isNull()) { setDocumentErrorString(i18nc("@info", "Loading image failed.")); Q_EMIT loadingFailed(); switchToImpl(new EmptyDocumentImpl(document())); return; } if (d->mAnimated) { if (d->mImage.size() == d->mImageSize) { // We already decoded the first frame at the right size, let's show // it setDocumentImage(d->mImage); } switchToImpl(new AnimatedDocumentLoadedImpl(document(), d->mData)); return; } if (d->mImageDataInvertedZoom != 1 && d->mImage.size() != d->mImageSize) { LOG("Loaded a down sampled image"); d->mDownSampledImageLoaded = true; // We loaded a down sampled image setDocumentDownSampledImage(d->mImage, d->mImageDataInvertedZoom); return; } LOG("Loaded a full image"); setDocumentImage(d->mImage); DocumentLoadedImpl *impl; if (d->mJpegContent.get()) { impl = new JpegDocumentLoadedImpl(document(), d->mJpegContent.release()); } else { impl = new DocumentLoadedImpl(document(), d->mData); } switchToImpl(impl); } } // namespace #include "moc_loadingdocumentimpl.cpp"
18,029
C++
.cpp
467
30.740899
152
0.634138
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,835
videodocumentloadedimpl.cpp
KDE_gwenview/lib/document/videodocumentloadedimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "videodocumentloadedimpl.h" // Qt // KF // Local #include "gwenview_lib_debug.h" namespace Gwenview { struct VideoDocumentLoadedImplPrivate { }; VideoDocumentLoadedImpl::VideoDocumentLoadedImpl(Document *document) : AbstractDocumentImpl(document) , d(new VideoDocumentLoadedImplPrivate) { } VideoDocumentLoadedImpl::~VideoDocumentLoadedImpl() { delete d; } void VideoDocumentLoadedImpl::init() { Q_EMIT loaded(); } Document::LoadingState VideoDocumentLoadedImpl::loadingState() const { return Document::Loaded; } void VideoDocumentLoadedImpl::setImage(const QImage &) { qCWarning(GWENVIEW_LIB_LOG) << "Should not be called"; } } // namespace #include "moc_videodocumentloadedimpl.cpp"
1,552
C++
.cpp
49
29.836735
81
0.802153
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,836
documentloadedimpl.cpp
KDE_gwenview/lib/document/documentloadedimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "documentloadedimpl.h" // Qt #include <QByteArray> #include <QImage> #include <QImageWriter> #include <QTransform> #include <QUrl> // KF // Local #include "documentjob.h" #include "gwenviewconfig.h" #include "imageutils.h" #include "savejob.h" namespace Gwenview { struct DocumentLoadedImplPrivate { QByteArray mRawData; bool mQuietInit; }; DocumentLoadedImpl::DocumentLoadedImpl(Document *document, const QByteArray &rawData, bool quietInit) : AbstractDocumentImpl(document) , d(new DocumentLoadedImplPrivate) { if (document->keepRawData()) { d->mRawData = rawData; } d->mQuietInit = quietInit; } DocumentLoadedImpl::~DocumentLoadedImpl() { delete d; } void DocumentLoadedImpl::init() { if (!d->mQuietInit) { Q_EMIT imageRectUpdated(document()->image().rect()); Q_EMIT loaded(); } } bool DocumentLoadedImpl::isEditable() const { return true; } Document::LoadingState DocumentLoadedImpl::loadingState() const { return Document::Loaded; } bool DocumentLoadedImpl::saveInternal(QIODevice *device, const QByteArray &format) { QImageWriter writer(device, format); // If we're saving a non-JPEG image as a JPEG, respect the quality setting if (format == QByteArrayLiteral("jpeg") || format == QByteArrayLiteral("jxl") || format == QByteArrayLiteral("webp") || format == QByteArrayLiteral("avif") || format == QByteArrayLiteral("heif") || format == QByteArrayLiteral("heic")) { writer.setQuality(GwenviewConfig::jPEGQuality()); } bool ok = writer.write(document()->image()); if (ok) { setDocumentFormat(format); } else { setDocumentErrorString(writer.errorString()); } return ok; } DocumentJob *DocumentLoadedImpl::save(const QUrl &url, const QByteArray &format) { return new SaveJob(this, url, format); } AbstractDocumentEditor *DocumentLoadedImpl::editor() { return this; } void DocumentLoadedImpl::setImage(const QImage &image) { setDocumentImage(image); Q_EMIT imageRectUpdated(image.rect()); } void DocumentLoadedImpl::applyTransformation(Orientation orientation) { QImage image = document()->image(); const QTransform matrix = ImageUtils::transformMatrix(orientation); image = image.transformed(matrix); setDocumentImage(image); Q_EMIT imageRectUpdated(image.rect()); } QByteArray DocumentLoadedImpl::rawData() const { return d->mRawData; } } // namespace #include "moc_documentloadedimpl.cpp"
3,320
C++
.cpp
107
28.130841
159
0.750784
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,837
animateddocumentloadedimpl.cpp
KDE_gwenview/lib/document/animateddocumentloadedimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "animateddocumentloadedimpl.h" // Qt #include <QBuffer> #include <QImage> #include <QMovie> // KF // Local #include "gwenview_lib_debug.h" namespace Gwenview { struct AnimatedDocumentLoadedImplPrivate { QByteArray mRawData; QBuffer mMovieBuffer; QMovie mMovie; }; AnimatedDocumentLoadedImpl::AnimatedDocumentLoadedImpl(Document *document, const QByteArray &rawData) : AbstractDocumentImpl(document) , d(new AnimatedDocumentLoadedImplPrivate) { d->mRawData = rawData; connect(&d->mMovie, &QMovie::frameChanged, this, &AnimatedDocumentLoadedImpl::slotFrameChanged); d->mMovieBuffer.setBuffer(&d->mRawData); d->mMovieBuffer.open(QIODevice::ReadOnly); d->mMovie.setDevice(&d->mMovieBuffer); } AnimatedDocumentLoadedImpl::~AnimatedDocumentLoadedImpl() { delete d; } void AnimatedDocumentLoadedImpl::init() { Q_EMIT isAnimatedUpdated(); if (!document()->image().isNull()) { // We may reach this point without an image if the first frame got // downsampled by LoadingDocumentImpl (unlikely for now because the gif // io handler does not support the QImageIOHandler::ScaledSize option) Q_EMIT imageRectUpdated(document()->image().rect()); Q_EMIT loaded(); } } Document::LoadingState AnimatedDocumentLoadedImpl::loadingState() const { return Document::Loaded; } QByteArray AnimatedDocumentLoadedImpl::rawData() const { return d->mRawData; } void AnimatedDocumentLoadedImpl::slotFrameChanged(int /*frameNumber*/) { QImage image = d->mMovie.currentImage(); setDocumentImage(image); Q_EMIT imageRectUpdated(image.rect()); } bool AnimatedDocumentLoadedImpl::isAnimated() const { return true; } void AnimatedDocumentLoadedImpl::startAnimation() { d->mMovie.start(); if (d->mMovie.state() == QMovie::NotRunning) { // This is true with qt-copy as of 2008.08.23 // qCDebug(GWENVIEW_LIB_LOG) << "QMovie didn't start. This can happen in some cases when starting for the second time."; // qCDebug(GWENVIEW_LIB_LOG) << "Trying to start again, it usually fixes the bug."; d->mMovie.start(); } } void AnimatedDocumentLoadedImpl::stopAnimation() { d->mMovie.stop(); } } // namespace #include "moc_animateddocumentloadedimpl.cpp"
3,122
C++
.cpp
91
31.208791
128
0.755984
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,838
emptydocumentimpl.cpp
KDE_gwenview/lib/document/emptydocumentimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "emptydocumentimpl.h" // Qt // KF // Local namespace Gwenview { EmptyDocumentImpl::EmptyDocumentImpl(Document *document) : AbstractDocumentImpl(document) { } EmptyDocumentImpl::~EmptyDocumentImpl() = default; void EmptyDocumentImpl::init() { } Document::LoadingState EmptyDocumentImpl::loadingState() const { return Document::LoadingFailed; } } // namespace
1,203
C++
.cpp
36
31.805556
78
0.80399
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,839
documentjob.cpp
KDE_gwenview/lib/document/documentjob.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "documentjob.h" // Qt #include <QApplication> #include <QFuture> #include <QFutureWatcher> #include <QtConcurrentRun> // KF #include <KDialogJobUiDelegate> #include <KLocalizedString> // Local #include "gwenview_lib_debug.h" namespace Gwenview { struct DocumentJobPrivate { Document::Ptr mDoc; }; DocumentJob::DocumentJob() : KCompositeJob(nullptr) , d(new DocumentJobPrivate) { auto delegate = new KDialogJobUiDelegate; delegate->setWindow(qApp->activeWindow()); delegate->setAutoErrorHandlingEnabled(true); setUiDelegate(delegate); } DocumentJob::~DocumentJob() { delete d; } Document::Ptr DocumentJob::document() const { return d->mDoc; } void DocumentJob::setDocument(const Document::Ptr &doc) { d->mDoc = doc; } void DocumentJob::start() { QMetaObject::invokeMethod(this, &DocumentJob::doStart, Qt::QueuedConnection); } bool DocumentJob::checkDocumentEditor() { if (!document()->editor()) { setError(NoDocumentEditorError); setErrorText(i18nc("@info", "Gwenview cannot edit this kind of image.")); return false; } return true; } void ThreadedDocumentJob::doStart() { QFuture<void> future = QtConcurrent::run(&ThreadedDocumentJob::threadedStart, this); auto watcher = new QFutureWatcher<void>(this); connect(watcher, SIGNAL(finished()), SLOT(emitResult())); watcher->setFuture(future); } } // namespace #include "moc_documentjob.cpp"
2,279
C++
.cpp
76
27.473684
88
0.763278
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,840
svgdocumentloadedimpl.cpp
KDE_gwenview/lib/document/svgdocumentloadedimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "svgdocumentloadedimpl.h" // Qt #include <QSvgRenderer> // Local #include "gwenview_lib_debug.h" namespace Gwenview { struct SvgDocumentLoadedImplPrivate { QByteArray mRawData; QSvgRenderer *mRenderer = nullptr; }; SvgDocumentLoadedImpl::SvgDocumentLoadedImpl(Document *document, const QByteArray &data) : AbstractDocumentImpl(document) , d(new SvgDocumentLoadedImplPrivate) { d->mRawData = data; d->mRenderer = new QSvgRenderer(this); } SvgDocumentLoadedImpl::~SvgDocumentLoadedImpl() { delete d; } void SvgDocumentLoadedImpl::init() { d->mRenderer->load(d->mRawData); setDocumentImageSize(d->mRenderer->defaultSize()); Q_EMIT loaded(); } Document::LoadingState SvgDocumentLoadedImpl::loadingState() const { return Document::Loaded; } void SvgDocumentLoadedImpl::setImage(const QImage &) { qCWarning(GWENVIEW_LIB_LOG) << "Should not be called"; } QByteArray SvgDocumentLoadedImpl::rawData() const { return d->mRawData; } QSvgRenderer *SvgDocumentLoadedImpl::svgRenderer() const { return d->mRenderer; } } // namespace #include "moc_svgdocumentloadedimpl.cpp"
1,960
C++
.cpp
63
28.936508
88
0.788185
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,841
jpegdocumentloadedimpl.cpp
KDE_gwenview/lib/document/jpegdocumentloadedimpl.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "jpegdocumentloadedimpl.h" // Qt #include <QIODevice> #include <QImage> // KF // Local #include "jpegcontent.h" namespace Gwenview { struct JpegDocumentLoadedImplPrivate { JpegContent *mJpegContent = nullptr; }; JpegDocumentLoadedImpl::JpegDocumentLoadedImpl(Document *doc, JpegContent *jpegContent) : DocumentLoadedImpl(doc, QByteArray() /* rawData */) , d(new JpegDocumentLoadedImplPrivate) { Q_ASSERT(jpegContent); d->mJpegContent = jpegContent; } JpegDocumentLoadedImpl::~JpegDocumentLoadedImpl() { delete d->mJpegContent; delete d; } bool JpegDocumentLoadedImpl::saveInternal(QIODevice *device, const QByteArray &format) { if (format == "jpeg") { if (!d->mJpegContent->thumbnail().isNull()) { const QImage thumbnail = document()->image().scaled(128, 128, Qt::KeepAspectRatio); d->mJpegContent->setThumbnail(thumbnail); } bool ok = d->mJpegContent->save(device); if (!ok) { setDocumentErrorString(d->mJpegContent->errorString()); } return ok; } else { return DocumentLoadedImpl::saveInternal(device, format); } } void JpegDocumentLoadedImpl::setImage(const QImage &image) { d->mJpegContent->setImage(image); DocumentLoadedImpl::setImage(image); } void JpegDocumentLoadedImpl::applyTransformation(Orientation orientation) { DocumentLoadedImpl::applyTransformation(orientation); // Apply Exif transformation first to normalize image d->mJpegContent->transform(d->mJpegContent->orientation()); d->mJpegContent->resetOrientation(); d->mJpegContent->transform(orientation); } QByteArray JpegDocumentLoadedImpl::rawData() const { return d->mJpegContent->rawData(); } } // namespace #include "moc_jpegdocumentloadedimpl.cpp"
2,630
C++
.cpp
76
31.171053
95
0.754047
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,842
tagmodel.cpp
KDE_gwenview/lib/semanticinfo/tagmodel.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "tagmodel.h" // Qt #include <QIcon> // KF // Local #include "abstractsemanticinfobackend.h" namespace Gwenview { struct TagModelPrivate { AbstractSemanticInfoBackEnd *mBackEnd; }; static QStandardItem *createItem(const SemanticInfoTag &tag, const QString &label, TagModel::AssignmentStatus status) { auto item = new QStandardItem(label); item->setData(tag, TagModel::TagRole); item->setData(label.toLower(), TagModel::SortRole); item->setData(status, TagModel::AssignmentStatusRole); item->setData(QIcon::fromTheme(QStringLiteral("mail-tagged")), Qt::DecorationRole); return item; } TagModel::TagModel(QObject *parent) : QStandardItemModel(parent) , d(new TagModelPrivate) { d->mBackEnd = nullptr; setSortRole(SortRole); } TagModel::~TagModel() { delete d; } void TagModel::setSemanticInfoBackEnd(AbstractSemanticInfoBackEnd *backEnd) { d->mBackEnd = backEnd; } void TagModel::setTagSet(const TagSet &set) { clear(); for (const SemanticInfoTag &tag : set) { QString label = d->mBackEnd->labelForTag(tag); QStandardItem *item = createItem(tag, label, TagModel::FullyAssigned); appendRow(item); } sort(0); } void TagModel::addTag(const SemanticInfoTag &tag, const QString &_label, TagModel::AssignmentStatus status) { int row; QString label = _label.isEmpty() ? d->mBackEnd->labelForTag(tag) : _label; const QString sortLabel = label.toLower(); // This is not optimal, implement dichotomic search if necessary for (row = 0; row < rowCount(); ++row) { const QModelIndex idx = index(row, 0); if (idx.data(SortRole).toString().compare(sortLabel) > 0) { break; } } if (row > 0) { QStandardItem *_item = item(row - 1); Q_ASSERT(_item); if (_item->data(TagRole).toString() == tag) { // Update, do not add _item->setData(label.toLower(), SortRole); _item->setData(status, AssignmentStatusRole); return; } } QStandardItem *_item = createItem(tag, label, status); insertRow(row, _item); } void TagModel::removeTag(const SemanticInfoTag &tag) { // This is not optimal, implement dichotomic search if necessary for (int row = 0; row < rowCount(); ++row) { if (index(row, 0).data(TagRole).toString() == tag) { removeRow(row); return; } } } TagModel *TagModel::createAllTagsModel(QObject *parent, AbstractSemanticInfoBackEnd *backEnd) { auto tagModel = new TagModel(parent); tagModel->setSemanticInfoBackEnd(backEnd); tagModel->setTagSet(backEnd->allTags()); connect(backEnd, SIGNAL(tagAdded(SemanticInfoTag, QString)), tagModel, SLOT(addTag(SemanticInfoTag, QString))); return tagModel; } } // namespace #include "moc_tagmodel.cpp"
3,685
C++
.cpp
107
30.252336
117
0.709306
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,843
tagitemdelegate.cpp
KDE_gwenview/lib/semanticinfo/tagitemdelegate.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "tagitemdelegate.h" // Qt #include <QAbstractItemView> #include <QPainter> #include <QToolButton> // KF #include <KIconLoader> #include <KLocalizedString> // Local #include "gwenview_lib_debug.h" #include <lib/semanticinfo/tagmodel.h> namespace Gwenview { class DummyButton : public QToolButton { public: int buttonSize(QAbstractItemView *view) { const int iconSize = KIconLoader::global()->currentSize(KIconLoader::Small); QStyleOptionToolButton styleOption; initStyleOption(&styleOption); const auto size = view->style()->sizeFromContents(QStyle::CT_ToolButton, &styleOption, QSize(iconSize, iconSize)); return qMax(size.width(), size.height()); } }; TagItemDelegate::TagItemDelegate(QAbstractItemView *view) : KWidgetItemDelegate(view, view) { #define pm(x) view->style()->pixelMetric(QStyle::x) mMargin = pm(PM_ToolBarItemMargin); mSpacing = pm(PM_ToolBarItemSpacing); #undef pm DummyButton dummyButton; mButtonSize = dummyButton.buttonSize(view); } QList<QWidget *> TagItemDelegate::createItemWidgets(const QModelIndex &index) const { #define initButton(x) \ (x)->setAutoRaise(true); \ setBlockedEventTypes((x), QList<QEvent::Type>() << QEvent::MouseButtonPress << QEvent::MouseButtonRelease << QEvent::MouseButtonDblClick); Q_UNUSED(index); auto assignToAllButton = new QToolButton; initButton(assignToAllButton); assignToAllButton->setIcon(QIcon::fromTheme(QStringLiteral("fill-color"))); /* FIXME: Probably not the appropriate icon */ assignToAllButton->setToolTip(i18nc("@info:tooltip", "Assign this tag to all selected images")); connect(assignToAllButton, &QToolButton::clicked, this, &TagItemDelegate::slotAssignToAllButtonClicked); auto removeButton = new QToolButton; initButton(removeButton); removeButton->setIcon(QIcon::fromTheme(QStringLiteral("list-remove"))); connect(removeButton, &QToolButton::clicked, this, &TagItemDelegate::slotRemoveButtonClicked); #undef initButton return QList<QWidget *>() << removeButton << assignToAllButton; } void TagItemDelegate::updateItemWidgets(const QList<QWidget *> &widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const { const bool fullyAssigned = index.data(TagModel::AssignmentStatusRole).toInt() == int(TagModel::FullyAssigned); auto removeButton = static_cast<QToolButton *>(widgets[0]); auto assignToAllButton = static_cast<QToolButton *>(widgets[1]); QSize buttonSize(mButtonSize, option.rect.height() - 2 * mMargin); removeButton->resize(buttonSize); assignToAllButton->resize(buttonSize); removeButton->move(option.rect.width() - mButtonSize - mMargin, mMargin); if (fullyAssigned) { assignToAllButton->hide(); } else { assignToAllButton->move(removeButton->x() - mButtonSize - mSpacing, mMargin); } } void TagItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) { return; } const bool selected = option.state & QStyle::State_Selected; const bool fullyAssigned = index.data(TagModel::AssignmentStatusRole).toInt() == int(TagModel::FullyAssigned); itemView()->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, nullptr); QRect textRect = option.rect; textRect.setLeft(textRect.left() + mMargin); textRect.setWidth(textRect.width() - mButtonSize - mMargin - mSpacing); if (!fullyAssigned) { textRect.setWidth(textRect.width() - mButtonSize - mSpacing); } painter->setPen(option.palette.color(QPalette::Normal, selected ? QPalette::HighlightedText : QPalette::Text)); painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, index.data().toString()); } QSize TagItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { const int width = option.fontMetrics.boundingRect(index.data().toString()).width(); const int height = qMax(mButtonSize, option.fontMetrics.height()); return QSize(width + 2 * mMargin, height + 2 * mMargin); } void TagItemDelegate::slotRemoveButtonClicked() { const QModelIndex index = focusedIndex(); if (!index.isValid()) { qCWarning(GWENVIEW_LIB_LOG) << "!index.isValid()"; return; } Q_EMIT removeTagRequested(index.data(TagModel::TagRole).toString()); } void TagItemDelegate::slotAssignToAllButtonClicked() { const QModelIndex index = focusedIndex(); if (!index.isValid()) { qCWarning(GWENVIEW_LIB_LOG) << "!index.isValid()"; return; } Q_EMIT assignTagToAllRequested(index.data(TagModel::TagRole).toString()); } } // namespace #include "moc_tagitemdelegate.cpp"
5,866
C++
.cpp
128
42.070313
160
0.713409
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,844
fakesemanticinfobackend.cpp
KDE_gwenview/lib/semanticinfo/fakesemanticinfobackend.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "fakesemanticinfobackend.h" // Qt #include <QStringList> // KF // Local namespace Gwenview { FakeSemanticInfoBackEnd::FakeSemanticInfoBackEnd(QObject *parent, InitializeMode mode) : AbstractSemanticInfoBackEnd(parent) , mInitializeMode(mode) { mAllTags << tagForLabel("beach") << tagForLabel("mountains") << tagForLabel("wallpaper"); } void FakeSemanticInfoBackEnd::storeSemanticInfo(const QUrl &url, const SemanticInfo &semanticInfo) { mSemanticInfoForUrl[url] = semanticInfo; mergeTagsWithAllTags(semanticInfo.mTags); } void FakeSemanticInfoBackEnd::mergeTagsWithAllTags(const TagSet &set) { int size = mAllTags.size(); mAllTags |= set; if (mAllTags.size() > size) { // Q_EMIT allTagsUpdated(); } } TagSet FakeSemanticInfoBackEnd::allTags() const { return mAllTags; } void FakeSemanticInfoBackEnd::refreshAllTags() { } void FakeSemanticInfoBackEnd::retrieveSemanticInfo(const QUrl &url) { if (!mSemanticInfoForUrl.contains(url)) { QString urlString = url.url(); SemanticInfo semanticInfo; if (mInitializeMode == InitializeRandom) { semanticInfo.mRating = int(urlString.length()) % 6; semanticInfo.mDescription = url.fileName(); const QStringList lst = url.path().split('/'); for (const QString &token : lst) { if (!token.isEmpty()) { semanticInfo.mTags << '#' + token.toLower(); } } semanticInfo.mTags << QString("#length-%1").arg(url.fileName().length()); mergeTagsWithAllTags(semanticInfo.mTags); } else { semanticInfo.mRating = 0; } mSemanticInfoForUrl[url] = semanticInfo; } Q_EMIT semanticInfoRetrieved(url, mSemanticInfoForUrl.value(url)); } QString FakeSemanticInfoBackEnd::labelForTag(const SemanticInfoTag &tag) const { return tag[1].toUpper() + tag.mid(2); } SemanticInfoTag FakeSemanticInfoBackEnd::tagForLabel(const QString &label) { return '#' + label.toLower(); } } // namespace #include "moc_fakesemanticinfobackend.cpp"
2,948
C++
.cpp
83
31.096386
98
0.723023
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,845
abstractsemanticinfobackend.cpp
KDE_gwenview/lib/semanticinfo/abstractsemanticinfobackend.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "abstractsemanticinfobackend.h" // Qt #include <QStringList> #include <QVariant> // KF // Local namespace Gwenview { TagSet::TagSet() : QSet<SemanticInfoTag>() { } TagSet::TagSet(const QSet<SemanticInfoTag> &set) : QSet<QString>(set) { } TagSet::TagSet(const QList<SemanticInfoTag> &list) : QSet(list.begin(), list.end()) { } QVariant TagSet::toVariant() const { QStringList lst = values(); return QVariant(lst); } TagSet TagSet::fromVariant(const QVariant &variant) { QStringList lst = variant.toStringList(); return TagSet::fromList(lst); } TagSet TagSet::fromList(const QList<SemanticInfoTag> &list) { return TagSet(list); } AbstractSemanticInfoBackEnd::AbstractSemanticInfoBackEnd(QObject *parent) : QObject(parent) { qRegisterMetaType<SemanticInfo>("SemanticInfo"); } } // namespace #include "moc_abstractsemanticinfobackend.cpp"
1,719
C++
.cpp
58
27.637931
81
0.780889
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,846
semanticinfodirmodel.cpp
KDE_gwenview/lib/semanticinfo/semanticinfodirmodel.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "semanticinfodirmodel.h" #include <config-gwenview.h> // Qt #include <QHash> // KF // Local #include "../archiveutils.h" #include "abstractsemanticinfobackend.h" #include "gwenview_lib_debug.h" #ifdef GWENVIEW_SEMANTICINFO_BACKEND_FAKE #include "fakesemanticinfobackend.h" #elif defined(GWENVIEW_SEMANTICINFO_BACKEND_BALOO) #include "baloosemanticinfobackend.h" #else #ifdef __GNUC__ #error No metadata backend defined #endif #endif namespace Gwenview { struct SemanticInfoCacheItem { SemanticInfoCacheItem() = default; QPersistentModelIndex mIndex; bool mValid = false; SemanticInfo mInfo; }; using SemanticInfoCache = QHash<QUrl, SemanticInfoCacheItem>; struct SemanticInfoDirModelPrivate { SemanticInfoCache mSemanticInfoCache; AbstractSemanticInfoBackEnd *mBackEnd; }; SemanticInfoDirModel::SemanticInfoDirModel(QObject *parent) : KDirModel(parent) , d(new SemanticInfoDirModelPrivate) { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_FAKE d->mBackEnd = new FakeSemanticInfoBackEnd(this, FakeSemanticInfoBackEnd::InitializeRandom); #elif defined(GWENVIEW_SEMANTICINFO_BACKEND_BALOO) d->mBackEnd = new BalooSemanticInfoBackend(this); #endif connect(d->mBackEnd, &AbstractSemanticInfoBackEnd::semanticInfoRetrieved, this, &SemanticInfoDirModel::slotSemanticInfoRetrieved, Qt::QueuedConnection); connect(this, &SemanticInfoDirModel::modelAboutToBeReset, this, &SemanticInfoDirModel::slotModelAboutToBeReset); connect(this, &SemanticInfoDirModel::rowsAboutToBeRemoved, this, &SemanticInfoDirModel::slotRowsAboutToBeRemoved); } SemanticInfoDirModel::~SemanticInfoDirModel() { delete d; } void SemanticInfoDirModel::clearSemanticInfoCache() { d->mSemanticInfoCache.clear(); } bool SemanticInfoDirModel::semanticInfoAvailableForIndex(const QModelIndex &index) const { if (!index.isValid()) { return false; } KFileItem item = itemForIndex(index); if (item.isNull()) { return false; } SemanticInfoCache::const_iterator it = d->mSemanticInfoCache.constFind(item.targetUrl()); if (it == d->mSemanticInfoCache.constEnd()) { return false; } return it.value().mValid; } SemanticInfo SemanticInfoDirModel::semanticInfoForIndex(const QModelIndex &index) const { if (!index.isValid()) { qCWarning(GWENVIEW_LIB_LOG) << "invalid index"; return {}; } KFileItem item = itemForIndex(index); if (item.isNull()) { qCWarning(GWENVIEW_LIB_LOG) << "no item for index"; return {}; } return d->mSemanticInfoCache.value(item.targetUrl()).mInfo; } void SemanticInfoDirModel::retrieveSemanticInfoForIndex(const QModelIndex &index) { if (!index.isValid()) { return; } KFileItem item = itemForIndex(index); if (item.isNull()) { qCWarning(GWENVIEW_LIB_LOG) << "invalid item"; return; } if (ArchiveUtils::fileItemIsDirOrArchive(item)) { return; } SemanticInfoCacheItem cacheItem; cacheItem.mIndex = QPersistentModelIndex(index); d->mSemanticInfoCache[item.targetUrl()] = cacheItem; d->mBackEnd->retrieveSemanticInfo(item.targetUrl()); } QVariant SemanticInfoDirModel::data(const QModelIndex &index, int role) const { if (role == RatingRole || role == DescriptionRole || role == TagsRole) { KFileItem item = itemForIndex(index); if (item.isNull()) { return {}; } SemanticInfoCache::ConstIterator it = d->mSemanticInfoCache.constFind(item.targetUrl()); if (it != d->mSemanticInfoCache.constEnd()) { if (!it.value().mValid) { return {}; } const SemanticInfo &info = it.value().mInfo; if (role == RatingRole) { return info.mRating; } else if (role == DescriptionRole) { return info.mDescription; } else if (role == TagsRole) { return info.mTags.toVariant(); } else { // We should never reach this part Q_ASSERT(0); return {}; } } else { const_cast<SemanticInfoDirModel *>(this)->retrieveSemanticInfoForIndex(index); return {}; } } else { return KDirModel::data(index, role); } } bool SemanticInfoDirModel::setData(const QModelIndex &index, const QVariant &data, int role) { if (role == RatingRole || role == DescriptionRole || role == TagsRole) { KFileItem item = itemForIndex(index); if (item.isNull()) { qCWarning(GWENVIEW_LIB_LOG) << "no item found for this index"; return false; } QUrl url = item.targetUrl(); SemanticInfoCache::iterator it = d->mSemanticInfoCache.find(url); if (it == d->mSemanticInfoCache.end()) { qCWarning(GWENVIEW_LIB_LOG) << "No index for" << url; return false; } if (!it.value().mValid) { qCWarning(GWENVIEW_LIB_LOG) << "Semantic info cache for" << url << "is invalid"; return false; } SemanticInfo &semanticInfo = it.value().mInfo; if (role == RatingRole) { semanticInfo.mRating = data.toInt(); } else if (role == DescriptionRole) { semanticInfo.mDescription = data.toString(); } else if (role == TagsRole) { semanticInfo.mTags = TagSet::fromVariant(data); } else { // We should never reach this part Q_ASSERT(0); } Q_EMIT dataChanged(index, index); d->mBackEnd->storeSemanticInfo(url, semanticInfo); return true; } else { return KDirModel::setData(index, data, role); } } void SemanticInfoDirModel::slotSemanticInfoRetrieved(const QUrl &url, const SemanticInfo &semanticInfo) { SemanticInfoCache::iterator it = d->mSemanticInfoCache.find(url); if (it == d->mSemanticInfoCache.end()) { qCWarning(GWENVIEW_LIB_LOG) << "No index for" << url; return; } SemanticInfoCacheItem &cacheItem = it.value(); if (!cacheItem.mIndex.isValid()) { qCWarning(GWENVIEW_LIB_LOG) << "Index for" << url << "is invalid"; return; } cacheItem.mInfo = semanticInfo; cacheItem.mValid = true; Q_EMIT dataChanged(cacheItem.mIndex, cacheItem.mIndex); } void SemanticInfoDirModel::slotRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { for (int pos = start; pos <= end; ++pos) { QModelIndex idx = index(pos, 0, parent); KFileItem item = itemForIndex(idx); if (item.isNull()) { continue; } d->mSemanticInfoCache.remove(item.targetUrl()); } } void SemanticInfoDirModel::slotModelAboutToBeReset() { d->mSemanticInfoCache.clear(); } AbstractSemanticInfoBackEnd *SemanticInfoDirModel::semanticInfoBackEnd() const { return d->mBackEnd; } } // namespace #include "moc_semanticinfodirmodel.cpp"
7,822
C++
.cpp
220
29.840909
156
0.683974
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,847
sorteddirmodel.cpp
KDE_gwenview/lib/semanticinfo/sorteddirmodel.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "sorteddirmodel.h" // Qt #include <QTimer> #include <QUrl> // KF #include <KDirLister> #ifdef GWENVIEW_SEMANTICINFO_BACKEND_NONE #include <KDirModel> #endif // Local #include <lib/archiveutils.h> #include <lib/timeutils.h> #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE #include "abstractsemanticinfobackend.h" #include "semanticinfodirmodel.h" #include <lib/sorting.h> #endif namespace Gwenview { AbstractSortedDirModelFilter::AbstractSortedDirModelFilter(SortedDirModel *model) : QObject(model) , mModel(model) { if (mModel) { mModel->addFilter(this); } } AbstractSortedDirModelFilter::~AbstractSortedDirModelFilter() { if (mModel) { mModel->removeFilter(this); } } struct SortedDirModelPrivate { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_NONE KDirModel *mSourceModel; #else SemanticInfoDirModel *mSourceModel; #endif QStringList mBlackListedExtensions; QList<AbstractSortedDirModelFilter *> mFilters; QTimer mDelayedApplyFiltersTimer; MimeTypeUtils::Kinds mKindFilter; }; SortedDirModel::SortedDirModel(QObject *parent) : KDirSortFilterProxyModel(parent) , d(new SortedDirModelPrivate) { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_NONE d->mSourceModel = new KDirModel(this); #else d->mSourceModel = new SemanticInfoDirModel(this); #endif setSourceModel(d->mSourceModel); d->mSourceModel->dirLister()->setRequestMimeTypeWhileListing(true); d->mDelayedApplyFiltersTimer.setInterval(0); d->mDelayedApplyFiltersTimer.setSingleShot(true); connect(&d->mDelayedApplyFiltersTimer, &QTimer::timeout, this, &SortedDirModel::doApplyFilters); } SortedDirModel::~SortedDirModel() { delete d; } MimeTypeUtils::Kinds SortedDirModel::kindFilter() const { return d->mKindFilter; } void SortedDirModel::setKindFilter(MimeTypeUtils::Kinds kindFilter) { if (d->mKindFilter == kindFilter) { return; } d->mKindFilter = kindFilter; applyFilters(); } void SortedDirModel::adjustKindFilter(MimeTypeUtils::Kinds kinds, bool set) { MimeTypeUtils::Kinds kindFilter = d->mKindFilter; if (set) { kindFilter |= kinds; } else { kindFilter &= ~kinds; } setKindFilter(kindFilter); } void SortedDirModel::addFilter(AbstractSortedDirModelFilter *filter) { d->mFilters << filter; applyFilters(); } void SortedDirModel::removeFilter(AbstractSortedDirModelFilter *filter) { d->mFilters.removeAll(filter); applyFilters(); } KDirLister *SortedDirModel::dirLister() const { return d->mSourceModel->dirLister(); } void SortedDirModel::reload() { #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE d->mSourceModel->clearSemanticInfoCache(); #endif dirLister()->updateDirectory(dirLister()->url()); } void SortedDirModel::setBlackListedExtensions(const QStringList &list) { d->mBlackListedExtensions = list; } KFileItem SortedDirModel::itemForIndex(const QModelIndex &index) const { if (!index.isValid()) { return {}; } QModelIndex sourceIndex = mapToSource(index); return d->mSourceModel->itemForIndex(sourceIndex); } QUrl SortedDirModel::urlForIndex(const QModelIndex &index) const { KFileItem item = itemForIndex(index); return item.isNull() ? QUrl() : item.url(); } KFileItem SortedDirModel::itemForSourceIndex(const QModelIndex &sourceIndex) const { if (!sourceIndex.isValid()) { return {}; } return d->mSourceModel->itemForIndex(sourceIndex); } QModelIndex SortedDirModel::indexForItem(const KFileItem &item) const { if (item.isNull()) { return {}; } QModelIndex sourceIndex = d->mSourceModel->indexForItem(item); return mapFromSource(sourceIndex); } QModelIndex SortedDirModel::indexForUrl(const QUrl &url) const { if (!url.isValid()) { return {}; } QModelIndex sourceIndex = d->mSourceModel->indexForUrl(url); return mapFromSource(sourceIndex); } bool SortedDirModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = d->mSourceModel->index(row, 0, parent); KFileItem fileItem = d->mSourceModel->itemForIndex(index); MimeTypeUtils::Kinds kind = MimeTypeUtils::fileItemKind(fileItem); if (d->mKindFilter != MimeTypeUtils::Kinds() && !(d->mKindFilter & kind)) { return false; } if (kind != MimeTypeUtils::KIND_ARCHIVE) { int dotPos = fileItem.name().lastIndexOf(QLatin1Char('.')); if (dotPos >= 1) { QString extension = fileItem.name().mid(dotPos + 1).toLower(); if (d->mBlackListedExtensions.contains(extension)) { return false; } } #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE if (!d->mSourceModel->semanticInfoAvailableForIndex(index)) { for (const AbstractSortedDirModelFilter *filter : qAsConst(d->mFilters)) { // Make sure we have semanticinfo, otherwise retrieve it and // return false, we will be called again later when it is // there. if (filter->needsSemanticInfo()) { d->mSourceModel->retrieveSemanticInfoForIndex(index); return false; } } } #endif for (const AbstractSortedDirModelFilter *filter : qAsConst(d->mFilters)) { if (!filter->acceptsIndex(index)) { return false; } } } return KDirSortFilterProxyModel::filterAcceptsRow(row, parent); } AbstractSemanticInfoBackEnd *SortedDirModel::semanticInfoBackEnd() const { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_NONE return 0; #else return d->mSourceModel->semanticInfoBackEnd(); #endif } #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE SemanticInfo SortedDirModel::semanticInfoForSourceIndex(const QModelIndex &sourceIndex) const { return d->mSourceModel->semanticInfoForIndex(sourceIndex); } #endif void SortedDirModel::applyFilters() { d->mDelayedApplyFiltersTimer.start(); } void SortedDirModel::doApplyFilters() { QSortFilterProxyModel::invalidateFilter(); } bool SortedDirModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { const KFileItem leftItem = itemForSourceIndex(left); const KFileItem rightItem = itemForSourceIndex(right); const bool leftIsDirOrArchive = ArchiveUtils::fileItemIsDirOrArchive(leftItem); const bool rightIsDirOrArchive = ArchiveUtils::fileItemIsDirOrArchive(rightItem); if (leftIsDirOrArchive != rightIsDirOrArchive) { return sortOrder() == Qt::AscendingOrder ? leftIsDirOrArchive : rightIsDirOrArchive; } // Apply special sort handling only to images. For folders/archives or when // a secondary criterion is needed, delegate sorting to the parent class. if (!leftIsDirOrArchive) { if (sortColumn() == KDirModel::ModifiedTime) { const QDateTime leftDate = TimeUtils::dateTimeForFileItem(leftItem); const QDateTime rightDate = TimeUtils::dateTimeForFileItem(rightItem); if (leftDate != rightDate) { return leftDate < rightDate; } } #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE if (sortRole() == SemanticInfoDirModel::RatingRole) { const int leftRating = d->mSourceModel->data(left, SemanticInfoDirModel::RatingRole).toInt(); const int rightRating = d->mSourceModel->data(right, SemanticInfoDirModel::RatingRole).toInt(); if (leftRating != rightRating) { return leftRating < rightRating; } } #endif } return KDirSortFilterProxyModel::lessThan(left, right); } bool SortedDirModel::hasDocuments() const { const int count = rowCount(); if (count == 0) { return false; } for (int row = 0; row < count; ++row) { const QModelIndex idx = index(row, 0); const KFileItem item = itemForIndex(idx); if (!ArchiveUtils::fileItemIsDirOrArchive(item)) { return true; } } return false; } void SortedDirModel::setDirLister(KDirLister *dirLister) { d->mSourceModel->setDirLister(dirLister); } } // namespace #include "moc_sorteddirmodel.cpp"
8,959
C++
.cpp
272
28.290441
107
0.720801
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,848
baloosemanticinfobackend.cpp
KDE_gwenview/lib/semanticinfo/baloosemanticinfobackend.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> Copyright 2014 Vishesh Handa <me@vhanda.in> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "baloosemanticinfobackend.h" // Local #include <lib/gvdebug.h> // Qt #include <QUrl> // KF #include <Baloo/TagListJob> #include <KFileMetaData/UserMetaData> namespace Gwenview { struct BalooSemanticInfoBackend::Private { TagSet mAllTags; }; BalooSemanticInfoBackend::BalooSemanticInfoBackend(QObject *parent) : AbstractSemanticInfoBackEnd(parent) , d(new BalooSemanticInfoBackend::Private) { } BalooSemanticInfoBackend::~BalooSemanticInfoBackend() { delete d; } TagSet BalooSemanticInfoBackend::allTags() const { if (d->mAllTags.isEmpty()) { const_cast<BalooSemanticInfoBackend *>(this)->refreshAllTags(); } return d->mAllTags; } void BalooSemanticInfoBackend::refreshAllTags() { auto job = new Baloo::TagListJob(); job->exec(); d->mAllTags.clear(); const QStringList tags = job->tags(); for (const QString &tag : tags) { d->mAllTags << tag; } } void BalooSemanticInfoBackend::storeSemanticInfo(const QUrl &url, const SemanticInfo &semanticInfo) { KFileMetaData::UserMetaData md(url.toLocalFile()); md.setRating(semanticInfo.mRating); md.setUserComment(semanticInfo.mDescription); md.setTags(semanticInfo.mTags.values()); } void BalooSemanticInfoBackend::retrieveSemanticInfo(const QUrl &url) { KFileMetaData::UserMetaData md(url.toLocalFile()); SemanticInfo si; si.mRating = md.rating(); si.mDescription = md.userComment(); si.mTags = TagSet::fromList(md.tags()); Q_EMIT semanticInfoRetrieved(url, si); } QString BalooSemanticInfoBackend::labelForTag(const SemanticInfoTag &uriString) const { return uriString; } SemanticInfoTag BalooSemanticInfoBackend::tagForLabel(const QString &label) { return label; } } // namespace #include "moc_baloosemanticinfobackend.cpp"
2,676
C++
.cpp
83
29.566265
99
0.775097
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,849
tagwidget.cpp
KDE_gwenview/lib/semanticinfo/tagwidget.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "tagwidget.h" // Qt #include <QComboBox> #include <QCompleter> #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> #include <QListView> #include <QPushButton> #include <QSortFilterProxyModel> #include <QTimer> #include <QVBoxLayout> // KF #include <KLocalizedString> // Local #include <lib/semanticinfo/tagitemdelegate.h> #include <lib/semanticinfo/tagmodel.h> namespace Gwenview { class TagCompleterModel : public QSortFilterProxyModel { public: TagCompleterModel(QObject *parent) : QSortFilterProxyModel(parent) { } void setTagInfo(const TagInfo &tagInfo) { mExcludedTagSet.clear(); TagInfo::ConstIterator it = tagInfo.begin(), end = tagInfo.end(); for (; it != end; ++it) { if (it.value()) { mExcludedTagSet << it.key(); } } invalidate(); } void setSemanticInfoBackEnd(AbstractSemanticInfoBackEnd *backEnd) { setSourceModel(TagModel::createAllTagsModel(this, backEnd)); } protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override { QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent); SemanticInfoTag tag = sourceIndex.data(TagModel::TagRole).toString(); return !mExcludedTagSet.contains(tag); } private: TagSet mExcludedTagSet; }; /** * A simple class to eat return keys. We use it to avoid propagating the return * key from our KLineEdit to a dialog using TagWidget. * We can't use KLineEdit::setTrapReturnKey() because it does not play well * with QCompleter, it only deals with KCompletion. */ class ReturnKeyEater : public QObject { public: explicit ReturnKeyEater(QObject *parent = nullptr) : QObject(parent) { } protected: bool eventFilter(QObject *, QEvent *event) override { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { auto keyEvent = static_cast<QKeyEvent *>(event); switch (keyEvent->key()) { case Qt::Key_Return: case Qt::Key_Enter: return true; default: return false; } } return false; } }; struct TagWidgetPrivate { TagWidget *q = nullptr; TagInfo mTagInfo; QListView *mListView = nullptr; QComboBox *mComboBox = nullptr; QPushButton *mAddButton = nullptr; AbstractSemanticInfoBackEnd *mBackEnd = nullptr; TagCompleterModel *mTagCompleterModel = nullptr; TagModel *mAssignedTagModel = nullptr; void setupWidgets() { mListView = new QListView; auto delegate = new TagItemDelegate(mListView); QObject::connect(delegate, SIGNAL(removeTagRequested(SemanticInfoTag)), q, SLOT(removeTag(SemanticInfoTag))); QObject::connect(delegate, SIGNAL(assignTagToAllRequested(SemanticInfoTag)), q, SLOT(assignTag(SemanticInfoTag))); mListView->setItemDelegate(delegate); mListView->setModel(mAssignedTagModel); mComboBox = new QComboBox; mComboBox->setEditable(true); mComboBox->setInsertPolicy(QComboBox::NoInsert); mTagCompleterModel = new TagCompleterModel(q); auto completer = new QCompleter(q); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setModel(mTagCompleterModel); mComboBox->setCompleter(completer); mComboBox->setModel(mTagCompleterModel); mAddButton = new QPushButton; mAddButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add"))); mAddButton->setToolTip(i18n("Add tag")); mAddButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QObject::connect(mAddButton, SIGNAL(clicked()), q, SLOT(addTagFromComboBox())); auto layout = new QVBoxLayout(q); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mListView); auto hLayout = new QHBoxLayout; hLayout->addWidget(mComboBox); hLayout->addWidget(mAddButton); layout->addLayout(hLayout); q->setTabOrder(mComboBox, mListView); } void fillTagModel() { Q_ASSERT(mBackEnd); mAssignedTagModel->clear(); TagInfo::ConstIterator it = mTagInfo.constBegin(), end = mTagInfo.constEnd(); for (; it != end; ++it) { mAssignedTagModel->addTag(it.key(), QString(), it.value() ? TagModel::FullyAssigned : TagModel::PartiallyAssigned); } } void updateCompleterModel() { mTagCompleterModel->setTagInfo(mTagInfo); mComboBox->setCurrentIndex(-1); } }; TagWidget::TagWidget(QWidget *parent) : QWidget(parent) , d(new TagWidgetPrivate) { d->q = this; d->mBackEnd = nullptr; d->mAssignedTagModel = new TagModel(this); d->setupWidgets(); installEventFilter(new ReturnKeyEater(this)); connect(d->mComboBox->lineEdit(), &QLineEdit::returnPressed, this, &TagWidget::addTagFromComboBox); } TagWidget::~TagWidget() { delete d; } void TagWidget::setSemanticInfoBackEnd(AbstractSemanticInfoBackEnd *backEnd) { d->mBackEnd = backEnd; d->mAssignedTagModel->setSemanticInfoBackEnd(backEnd); d->mTagCompleterModel->setSemanticInfoBackEnd(backEnd); } void TagWidget::setTagInfo(const TagInfo &tagInfo) { d->mTagInfo = tagInfo; d->fillTagModel(); d->updateCompleterModel(); } void TagWidget::addTagFromComboBox() { Q_ASSERT(d->mBackEnd); QString label = d->mComboBox->currentText(); if (label.isEmpty()) { return; } assignTag(d->mBackEnd->tagForLabel(label.trimmed())); // Use a QTimer because if the tag is new, it will be inserted in the model // and QComboBox will sometimes select it. At least it does so when the // model is empty. QTimer::singleShot(0, d->mComboBox, &QComboBox::clearEditText); } void TagWidget::assignTag(const SemanticInfoTag &tag) { d->mTagInfo[tag] = true; d->mAssignedTagModel->addTag(tag); d->updateCompleterModel(); Q_EMIT tagAssigned(tag); } void TagWidget::removeTag(const SemanticInfoTag &tag) { d->mTagInfo.remove(tag); d->mAssignedTagModel->removeTag(tag); d->updateCompleterModel(); Q_EMIT tagRemoved(tag); } } // namespace #include "moc_tagwidget.cpp"
7,155
C++
.cpp
208
29.197115
127
0.701274
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,850
zoomcombobox.cpp
KDE_gwenview/lib/zoomcombobox/zoomcombobox.cpp
// SPDX-FileCopyrightText: 2021 Noah Davis <noahadvs@gmail.com> // SPDX-License-Identifier: LGPL-2.1-or-later #include "zoomcombobox.h" #include "zoomcombobox_p.h" #include <KLocalizedString> #include <QAbstractItemView> #include <QAction> #include <QEvent> #include <QLineEdit> #include <QSignalBlocker> #include <QWheelEvent> #include <cmath> bool fuzzyEqual(qreal a, qreal b) { return (qFuzzyIsNull(a) && qFuzzyIsNull(b)) || qFuzzyCompare(a, b); } bool fuzzyLessEqual(qreal a, qreal b) { return fuzzyEqual(a, b) || a < b; } bool fuzzyGreaterEqual(qreal a, qreal b) { return fuzzyEqual(a, b) || a > b; } using namespace Gwenview; struct LineEditSelectionKeeper { LineEditSelectionKeeper(QLineEdit *lineEdit) : m_lineEdit(lineEdit) { Q_ASSERT(m_lineEdit); m_cursorPos = m_lineEdit->cursorPosition(); } ~LineEditSelectionKeeper() { m_lineEdit->end(false); m_lineEdit->cursorBackward(true, m_lineEdit->text().length() - m_cursorPos); } private: QLineEdit *m_lineEdit; int m_cursorPos; }; ZoomValidator::ZoomValidator(qreal minimum, qreal maximum, ZoomComboBox *q, ZoomComboBoxPrivate *d, QWidget *parent) : QValidator(parent) , m_minimum(minimum) , m_maximum(maximum) , m_zoomComboBox(q) , m_zoomComboBoxPrivate(d) { } ZoomValidator::~ZoomValidator() noexcept = default; qreal ZoomValidator::minimum() const { return m_minimum; } void ZoomValidator::setMinimum(const qreal minimum) { if (fuzzyEqual(m_minimum, minimum)) { return; } m_minimum = minimum; Q_EMIT changed(); } qreal ZoomValidator::maximum() const { return m_maximum; } void ZoomValidator::setMaximum(const qreal maximum) { if (fuzzyEqual(m_maximum, maximum)) { return; } m_maximum = maximum; Q_EMIT changed(); } QValidator::State ZoomValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos) if (m_zoomComboBox->findText(input, Qt::MatchFixedString) > -1) { return QValidator::Acceptable; } QString copy = input.trimmed(); copy.remove(locale().groupSeparator()); copy.remove(locale().percent()); const bool startsWithNumber = copy.constBegin()->isNumber(); if (startsWithNumber || copy.isEmpty()) { return QValidator::Intermediate; } QValidator::State state; bool ok = false; int value = locale().toInt(copy, &ok); if (!ok || value < std::ceil(m_minimum * 100) || value > std::floor(m_maximum * 100)) { state = QValidator::Intermediate; } else { state = QValidator::Acceptable; } return state; } ZoomComboBoxPrivate::ZoomComboBoxPrivate(ZoomComboBox *q) : q_ptr(q) , validator(new ZoomValidator(0, 0, q, this, q)) { } ZoomComboBox::ZoomComboBox(QWidget *parent) : QComboBox(parent) , d_ptr(new ZoomComboBoxPrivate(this)) { Q_D(ZoomComboBox); d->validator->setObjectName(QLatin1String("zoomValidator")); setValidator(d->validator); setEditable(true); setInsertPolicy(QComboBox::NoInsert); // QLocale::percent() will return a QString in Qt 6. // Qt encourages using QString(locale().percent()) in QLocale documentation. const int percentLength = QString(locale().percent()).length(); setMinimumContentsLength(locale().toString(9999).length() + percentLength); connect(lineEdit(), &QLineEdit::textEdited, this, [this, d](const QString &text) { const bool startsWithNumber = text.constBegin()->isNumber(); int matchedIndex = -1; if (startsWithNumber) { matchedIndex = findText(text, Qt::MatchFixedString); } else { // check if there is more than 1 match for (int i = 0, n = count(); i < n; ++i) { if (itemText(i).startsWith(text, Qt::CaseInsensitive)) { if (matchedIndex != -1) { // there is more than 1 match return; } matchedIndex = i; } } } if (matchedIndex != -1) { LineEditSelectionKeeper selectionKeeper(lineEdit()); updateCurrentIndex(); if (matchedIndex == currentIndex()) { updateDisplayedText(); } else { activateAndChangeZoomTo(matchedIndex); } } else if (startsWithNumber) { bool ok = false; qreal value = valueFromText(text, &ok); if (ok && value > 0 && fuzzyLessEqual(value, maximum())) { // emulate autocompletion for valid values that aren't predefined while (value < minimum()) { value *= 10; if (value > maximum()) { // autocompletion cannot be emulated for this value return; } } LineEditSelectionKeeper selectionKeeper(lineEdit()); if (fuzzyEqual(value, d->value)) { updateDisplayedText(); } else { d->lastCustomZoomValue = value; activateAndChangeZoomTo(-1); } } } }); connect(this, qOverload<int>(&ZoomComboBox::highlighted), this, &ZoomComboBox::changeZoomTo); view()->installEventFilter(this); connect(this, qOverload<int>(&ZoomComboBox::activated), this, &ZoomComboBox::activateAndChangeZoomTo); } ZoomComboBox::~ZoomComboBox() noexcept = default; void ZoomComboBox::setActions(QAction *zoomToFitAction, QAction *zoomToFillAction, QAction *actualSizeAction) { Q_D(ZoomComboBox); d->setActions(zoomToFitAction, zoomToFillAction, actualSizeAction); connect(zoomToFitAction, &QAction::toggled, this, &ZoomComboBox::updateDisplayedText); connect(zoomToFillAction, &QAction::toggled, this, &ZoomComboBox::updateDisplayedText); } void ZoomComboBoxPrivate::setActions(QAction *zoomToFitAction, QAction *zoomToFillAction, QAction *actualSizeAction) { Q_Q(ZoomComboBox); q->clear(); q->addItem(zoomToFitAction->iconText(), QVariant::fromValue(zoomToFitAction)); // index = 0 q->addItem(zoomToFillAction->iconText(), QVariant::fromValue(zoomToFillAction)); // index = 1 q->addItem(actualSizeAction->iconText(), QVariant::fromValue(actualSizeAction)); // index will change later mZoomToFitAction = zoomToFitAction; mZoomToFillAction = zoomToFillAction; mActualSizeAction = actualSizeAction; } qreal ZoomComboBox::value() const { Q_D(const ZoomComboBox); return d->value; } void ZoomComboBox::setValue(qreal value) { Q_D(ZoomComboBox); d->value = value; updateDisplayedText(); } qreal ZoomComboBox::minimum() const { Q_D(const ZoomComboBox); return d->validator->minimum(); } void ZoomComboBox::setMinimum(qreal minimum) { Q_D(ZoomComboBox); if (fuzzyEqual(this->minimum(), minimum)) { return; } d->validator->setMinimum(minimum); setValue(qMax(minimum, d->value)); // Generate zoom presets below 100% // FIXME: combobox value gets reset to last index value when this code runs const int zoomToFillActionIndex = findData(QVariant::fromValue(d->mZoomToFillAction)); const int actualSizeActionIndex = findData(QVariant::fromValue(d->mActualSizeAction)); for (int i = actualSizeActionIndex - 1; i > zoomToFillActionIndex; --i) { removeItem(i); } qreal value = minimum * 2; // The minimum zoom value itself is already available through "fit". for (int i = zoomToFillActionIndex + 1; value < 1.0; ++i) { insertItem(i, textFromValue(value), QVariant::fromValue(value)); value *= 2; } } qreal ZoomComboBox::maximum() const { Q_D(const ZoomComboBox); return d->validator->maximum(); } void ZoomComboBox::setMaximum(qreal maximum) { Q_D(ZoomComboBox); if (fuzzyEqual(this->maximum(), maximum)) { return; } d->validator->setMaximum(maximum); setValue(qMin(d->value, maximum)); // Generate zoom presets above 100% // NOTE: This probably has the same problem as setMinimum(), // but the problem is never enountered since max zoom doesn't actually change const int actualSizeActionIndex = findData(QVariant::fromValue(d->mActualSizeAction)); const int count = this->count(); for (int i = actualSizeActionIndex + 1; i < count; ++i) { removeItem(i); } qreal value = 2.0; while (value < maximum) { addItem(textFromValue(value), QVariant::fromValue(value)); value *= 2; } if (fuzzyGreaterEqual(value, maximum)) { addItem(textFromValue(maximum), QVariant::fromValue(maximum)); } } qreal ZoomComboBox::valueFromText(const QString &text, bool *ok) const { Q_D(const ZoomComboBox); const QLocale l = locale(); QString s = text; s.remove(l.groupSeparator()); if (s.endsWith(l.percent())) { s = s.chopped(1); } if (s.startsWith(l.percent())) { s = s.remove(0, 1); } return l.toDouble(s, ok) / 100.0; } QString ZoomComboBox::textFromValue(const qreal value) const { Q_D(const ZoomComboBox); QLocale l = locale(); l.setNumberOptions(QLocale::OmitGroupSeparator); QString formattedValue = l.toString(qRound(value * 100)); return i18nc("Percent value", "%1%", formattedValue); } void ZoomComboBox::updateDisplayedText() { Q_D(ZoomComboBox); if (d->mZoomToFitAction->isChecked()) { lineEdit()->setText(d->mZoomToFitAction->iconText()); } else if (d->mZoomToFillAction->isChecked()) { lineEdit()->setText(d->mZoomToFillAction->iconText()); } else if (d->mActualSizeAction->isChecked()) { lineEdit()->setText(d->mActualSizeAction->iconText()); } else { lineEdit()->setText(textFromValue(d->value)); } } void Gwenview::ZoomComboBox::showPopup() { updateCurrentIndex(); // We don't want to emit a QComboBox::highlighted event just because the popup is opened. const QSignalBlocker blocker(this); QComboBox::showPopup(); } bool ZoomComboBox::eventFilter(QObject *watched, QEvent *event) { if (watched == view()) { switch (event->type()) { case QEvent::Hide: { Q_D(ZoomComboBox); changeZoomTo(d->lastSelectedIndex); break; } case QEvent::ShortcutOverride: { if (view()->isVisibleTo(this)) { auto keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Escape) { event->accept(); } } break; } default: break; } } return QComboBox::eventFilter(watched, event); } void ZoomComboBox::focusOutEvent(QFocusEvent *event) { Q_D(ZoomComboBox); // Should the user have started typing a custom value // that was out of our range, then we have a temporary // state that is illegal. This is needed to allow a user // to type a zoom with multiple keystrokes, but when the // user leaves focus we should reset to the last known 'good' // zoom value. if (d->lastSelectedIndex == -1) setValue(d->lastCustomZoomValue); QComboBox::focusOutEvent(event); } void ZoomComboBox::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Down: case Qt::Key_Up: case Qt::Key_PageDown: case Qt::Key_PageUp: { updateCurrentIndex(); if (currentIndex() != -1) { break; } moveCurrentIndex(event->key() == Qt::Key_Down || event->key() == Qt::Key_PageDown); return; } default: break; } QComboBox::keyPressEvent(event); } void ZoomComboBox::wheelEvent(QWheelEvent *event) { updateCurrentIndex(); if (currentIndex() != -1) { // Everything should work as expected. QComboBox::wheelEvent(event); return; } moveCurrentIndex(event->angleDelta().y() < 0); } void ZoomComboBox::updateCurrentIndex() { Q_D(ZoomComboBox); if (d->mZoomToFitAction->isChecked()) { setCurrentIndex(0); d->lastSelectedIndex = 0; } else if (d->mZoomToFillAction->isChecked()) { setCurrentIndex(1); d->lastSelectedIndex = 1; } else if (d->mActualSizeAction->isChecked()) { const int actualSizeActionIndex = findData(QVariant::fromValue(d->mActualSizeAction)); setCurrentIndex(actualSizeActionIndex); d->lastSelectedIndex = actualSizeActionIndex; } else { // Now is a good time to save the zoom value that was selected before the user changes it through the popup. d->lastCustomZoomValue = d->value; // Highlight the correct index if the current zoom value exists as an option in the popup. // If it doesn't exist, it is set to -1. d->lastSelectedIndex = findText(textFromValue(d->value)); setCurrentIndex(d->lastSelectedIndex); } } void ZoomComboBox::moveCurrentIndex(bool moveUp) { // There is no exact match for the current zoom value in the // ComboBox. We need to find the closest matches, so scrolling // works as expected. Q_D(ZoomComboBox); int newIndex; if (moveUp) { // switch to a larger item newIndex = count() - 1; for (int i = 2; i < newIndex; ++i) { const QVariant data = itemData(i); qreal value; if (data.value<QAction *>() == d->mActualSizeAction) { value = 1; } else { value = data.value<qreal>(); } if (value > d->value) { newIndex = i; break; } } } else { // switch to a smaller item newIndex = 1; for (int i = count() - 1; i > newIndex; --i) { const QVariant data = itemData(i); qreal value; if (data.value<QAction *>() == d->mActualSizeAction) { value = 1; } else { value = data.value<qreal>(); } if (value < d->value) { newIndex = i; break; } } } setCurrentIndex(newIndex); Q_EMIT activated(newIndex); } void ZoomComboBox::changeZoomTo(int index) { if (index < 0) { Q_D(ZoomComboBox); Q_EMIT zoomChanged(d->lastCustomZoomValue); return; } QVariant itemData = this->itemData(index); auto action = itemData.value<QAction *>(); if (action) { if (!action->isCheckable() || !action->isChecked()) { action->trigger(); } } else if (itemData.canConvert(QMetaType::QReal)) { Q_EMIT zoomChanged(itemData.toReal()); } } void ZoomComboBox::activateAndChangeZoomTo(int index) { Q_D(ZoomComboBox); d->lastSelectedIndex = index; // The user has explicitly selected this zoom value so we // remember it the same way as if they had typed it themselves. QVariant itemData = this->itemData(index); if (!itemData.value<QAction *>() && itemData.canConvert(QMetaType::QReal)) { d->lastCustomZoomValue = itemData.toReal(); } changeZoomTo(index); } #include "moc_zoomcombobox.cpp" #include "moc_zoomcombobox_p.cpp"
15,375
C++
.cpp
456
27.129386
116
0.634435
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,851
waylandgestures.cpp
KDE_gwenview/lib/waylandgestures/waylandgestures.cpp
/* Gwenview: an image viewer Copyright 2019 Steffen Hartleib <steffenhartleib@t-online.de> Copyright 2022 Carl Schwan <carlschwan@kde.org> Copyright 2022 Bharadwaj Raju <bharadwaj.raju777@protonmail.com> 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, Cambridge, MA 02110-1301, USA. */ #include "qwayland-pointer-gestures-unstable-v1.h" #include <QGuiApplication> #include <QtWaylandClient/qwaylandclientextension.h> #include <qnamespace.h> #include <qpa/qplatformnativeinterface.h> #include <wayland-util.h> #include "wayland-pointer-gestures-unstable-v1-client-protocol.h" #include "waylandgestures.h" using namespace Gwenview; class PointerGestures : public QWaylandClientExtensionTemplate<PointerGestures>, public QtWayland::zwp_pointer_gestures_v1 { public: PointerGestures() : QWaylandClientExtensionTemplate<PointerGestures>(3) { } }; class PinchGesture : public QObject, public QtWayland::zwp_pointer_gesture_pinch_v1 { Q_OBJECT public: public: PinchGesture(struct ::zwp_pointer_gesture_pinch_v1 *object, QObject *parent) : QObject(parent) , zwp_pointer_gesture_pinch_v1(object) { } Q_SIGNALS: void gestureBegin(uint32_t serial, uint32_t time, uint32_t fingers); void gestureUpdate(uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation); void gestureEnd(uint32_t serial, uint32_t time, int32_t cancelled); private: virtual void zwp_pointer_gesture_pinch_v1_begin(uint32_t serial, uint32_t time, struct ::wl_surface *surface, uint32_t fingers) override { Q_UNUSED(surface); Q_EMIT gestureBegin(serial, time, fingers); } virtual void zwp_pointer_gesture_pinch_v1_update(uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation) override { Q_EMIT gestureUpdate(time, dx, dy, scale, rotation); } virtual void zwp_pointer_gesture_pinch_v1_end(uint32_t serial, uint32_t time, int32_t cancelled) override { Q_EMIT gestureEnd(serial, time, cancelled); } }; WaylandGestures::WaylandGestures(QObject *parent) : QObject(parent) { m_startZoom = 1.0; m_zoomModifier = 1.0; m_pointerGestures = new PointerGestures(); connect(m_pointerGestures, &PointerGestures::activeChanged, this, [this]() { init(); }); } WaylandGestures::~WaylandGestures() { if (m_pointerGestures) { m_pointerGestures->release(); } if (m_pinchGesture) { m_pinchGesture->destroy(); } } void WaylandGestures::setStartZoom(double startZoom) { m_startZoom = startZoom; } void WaylandGestures::init() { QPlatformNativeInterface *native = qGuiApp->platformNativeInterface(); if (!native) { return; } const auto pointer = reinterpret_cast<wl_pointer *>(native->nativeResourceForIntegration(QByteArrayLiteral("wl_pointer"))); if (!pointer) { return; } m_pinchGesture = new PinchGesture(m_pointerGestures->get_pinch_gesture(pointer), this); connect(m_pinchGesture, &PinchGesture::gestureBegin, this, [this]() { Q_EMIT pinchGestureStarted(); }); connect(m_pinchGesture, &PinchGesture::gestureUpdate, this, [this](uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation) { Q_EMIT pinchZoomChanged(m_startZoom * wl_fixed_to_double(scale) * m_zoomModifier); }); } #include "waylandgestures.moc" #include "moc_waylandgestures.cpp"
4,066
C++
.cpp
106
34.537736
156
0.741935
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,852
mprismediaplayer2.cpp
KDE_gwenview/lib/mpris2/mprismediaplayer2.cpp
/* Gwenview: an image viewer Copyright 2018 Friedrich W. H. Kossebau <kossebau@kde.org> 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 "mprismediaplayer2.h" // Qt #include <QAction> #include <QGuiApplication> namespace Gwenview { MprisMediaPlayer2::MprisMediaPlayer2(const QString &objectDBusPath, QAction *fullScreenAction, QObject *parent) : DBusAbstractAdaptor(objectDBusPath, parent) , mFullScreenAction(fullScreenAction) { connect(mFullScreenAction, &QAction::toggled, this, &MprisMediaPlayer2::onFullScreenActionToggled); } MprisMediaPlayer2::~MprisMediaPlayer2() = default; bool MprisMediaPlayer2::canQuit() const { return true; } bool MprisMediaPlayer2::canRaise() const { // spec: "If true, calling Raise will cause the media application to attempt to bring its user interface to the front, // Which seems to be about the app specific control UI, less about the rendered media (display). // Could perhaps be supported by pulling in the toppanel when invoked? return false; } bool MprisMediaPlayer2::canSetFullscreen() const { return true; } bool MprisMediaPlayer2::hasTrackList() const { return false; } void MprisMediaPlayer2::Quit() { QGuiApplication::quit(); } void MprisMediaPlayer2::Raise() { } QString MprisMediaPlayer2::identity() const { return QGuiApplication::applicationDisplayName(); } QString MprisMediaPlayer2::desktopEntry() const { return QGuiApplication::desktopFileName(); } QStringList MprisMediaPlayer2::supportedUriSchemes() const { return {}; } QStringList MprisMediaPlayer2::supportedMimeTypes() const { return {}; } bool MprisMediaPlayer2::isFullscreen() const { return mFullScreenAction->isChecked(); } void MprisMediaPlayer2::setFullscreen(bool isFullscreen) { if (isFullscreen == mFullScreenAction->isChecked()) { return; } mFullScreenAction->trigger(); } void MprisMediaPlayer2::onFullScreenActionToggled(bool checked) { signalPropertyChange(QStringLiteral("Fullscreen"), checked); } } #include "moc_mprismediaplayer2.cpp"
2,716
C++
.cpp
87
28.942529
122
0.792018
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,853
dbusabstractadaptor.cpp
KDE_gwenview/lib/mpris2/dbusabstractadaptor.cpp
/* Gwenview: an image viewer Copyright 2018 Friedrich W. H. Kossebau <kossebau@kde.org> 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 "dbusabstractadaptor.h" // Qt #include <QDBusConnection> #include <QDBusMessage> #include <QMetaClassInfo> namespace Gwenview { DBusAbstractAdaptor::DBusAbstractAdaptor(const QString &objectDBusPath, QObject *parent) : QDBusAbstractAdaptor(parent) , mObjectPath(objectDBusPath) { Q_ASSERT(!mObjectPath.isEmpty()); } void DBusAbstractAdaptor::signalPropertyChange(const QString &propertyName, const QVariant &value) { const bool firstChange = mChangedProperties.isEmpty(); mChangedProperties.insert(propertyName, value); if (firstChange) { // trigger signal emission on next event loop QMetaObject::invokeMethod(this, &DBusAbstractAdaptor::emitPropertiesChangeDBusSignal, Qt::QueuedConnection); } } void DBusAbstractAdaptor::emitPropertiesChangeDBusSignal() { if (mChangedProperties.isEmpty()) { return; } const QMetaObject *metaObject = this->metaObject(); const int dBusInterfaceNameIndex = metaObject->indexOfClassInfo("D-Bus Interface"); Q_ASSERT(dBusInterfaceNameIndex >= 0); const char *dBusInterfaceName = metaObject->classInfo(dBusInterfaceNameIndex).value(); QDBusMessage signalMessage = QDBusMessage::createSignal(mObjectPath, QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("PropertiesChanged")); signalMessage << dBusInterfaceName << mChangedProperties << QStringList(); QDBusConnection::sessionBus().send(signalMessage); mChangedProperties.clear(); } } #include "moc_dbusabstractadaptor.cpp"
2,318
C++
.cpp
54
39.777778
136
0.787811
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,854
mprismediaplayer2player.cpp
KDE_gwenview/lib/mpris2/mprismediaplayer2player.cpp
/* Gwenview: an image viewer Copyright 2018 Friedrich W. H. Kossebau <kossebau@kde.org> 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 "mprismediaplayer2player.h" #include <config-gwenview.h> // lib #include "gwenview_lib_debug.h" #include <contextmanager.h> #include <document/documentfactory.h> #include <imagemetainfomodel.h> #include <mimetypeutils.h> #include <semanticinfo/semanticinfodirmodel.h> #include <semanticinfo/sorteddirmodel.h> #include <slideshow.h> // KF #include <KFileItem> #include <KLocalizedString> // Qt #include <QAction> #include <QDBusObjectPath> namespace Gwenview { static const double MAX_RATE = 1.0; static const double MIN_RATE = 1.0; MprisMediaPlayer2Player::MprisMediaPlayer2Player(const QString &objectDBusPath, SlideShow *slideShow, ContextManager *contextManager, QAction *toggleSlideShowAction, QAction *fullScreenAction, QAction *previousAction, QAction *nextAction, QObject *parent) : DBusAbstractAdaptor(objectDBusPath, parent) , mSlideShow(slideShow) , mContextManager(contextManager) , mToggleSlideShowAction(toggleSlideShowAction) , mFullScreenAction(fullScreenAction) , mPreviousAction(previousAction) , mNextAction(nextAction) , mSlideShowEnabled(mToggleSlideShowAction->isEnabled()) , mPreviousEnabled(mPreviousAction->isEnabled()) , mNextEnabled(mNextAction->isEnabled()) { updatePlaybackStatus(); connect(mSlideShow, &SlideShow::stateChanged, this, &MprisMediaPlayer2Player::onSlideShowStateChanged); connect(mSlideShow, &SlideShow::intervalChanged, this, &MprisMediaPlayer2Player::onMetaInfoUpdated); connect(mContextManager, &ContextManager::currentUrlChanged, this, &MprisMediaPlayer2Player::onCurrentUrlChanged); connect(mSlideShow->randomAction(), &QAction::toggled, this, &MprisMediaPlayer2Player::onRandomActionToggled); connect(mToggleSlideShowAction, &QAction::changed, this, &MprisMediaPlayer2Player::onToggleSlideShowActionChanged); connect(mNextAction, &QAction::changed, this, &MprisMediaPlayer2Player::onNextActionChanged); connect(mPreviousAction, &QAction::changed, this, &MprisMediaPlayer2Player::onPreviousActionChanged); } MprisMediaPlayer2Player::~MprisMediaPlayer2Player() = default; bool MprisMediaPlayer2Player::updatePlaybackStatus() { const QString newStatus = mSlideShow->isRunning() ? QStringLiteral("Playing") : QStringLiteral("Stopped"); const bool changed = (newStatus != mPlaybackStatus); if (changed) { mPlaybackStatus = newStatus; } return changed; } QString MprisMediaPlayer2Player::playbackStatus() const { return mPlaybackStatus; } bool MprisMediaPlayer2Player::canGoNext() const { return mNextEnabled; } void MprisMediaPlayer2Player::Next() { mNextAction->trigger(); } bool MprisMediaPlayer2Player::canGoPrevious() const { return mPreviousEnabled; } void MprisMediaPlayer2Player::Previous() { mPreviousAction->trigger(); } bool MprisMediaPlayer2Player::canPause() const { return mSlideShowEnabled; } void MprisMediaPlayer2Player::Pause() { mSlideShow->pause(); } void MprisMediaPlayer2Player::PlayPause() { mToggleSlideShowAction->trigger(); } void MprisMediaPlayer2Player::Stop() { if (mFullScreenAction->isChecked()) { mFullScreenAction->trigger(); } } bool MprisMediaPlayer2Player::canPlay() const { return mSlideShowEnabled; } void MprisMediaPlayer2Player::Play() { if (mSlideShow->isRunning()) { return; } mToggleSlideShowAction->trigger(); } double MprisMediaPlayer2Player::volume() const { return 0; } void MprisMediaPlayer2Player::setVolume(double volume) { Q_UNUSED(volume); } void MprisMediaPlayer2Player::setShuffle(bool isShuffle) { mSlideShow->randomAction()->setChecked(isShuffle); } QVariantMap MprisMediaPlayer2Player::metadata() const { return mMetaData; } qlonglong MprisMediaPlayer2Player::position() const { // milliseconds -> microseconds return mSlideShow->position() * 1000; } double MprisMediaPlayer2Player::rate() const { return 1.0; } void MprisMediaPlayer2Player::setRate(double newRate) { Q_UNUSED(newRate); } double MprisMediaPlayer2Player::minimumRate() const { return MIN_RATE; } double MprisMediaPlayer2Player::maximumRate() const { return MAX_RATE; } bool MprisMediaPlayer2Player::isShuffle() const { return mSlideShow->randomAction()->isChecked(); } bool MprisMediaPlayer2Player::canSeek() const { return false; } bool MprisMediaPlayer2Player::canControl() const { return true; } void MprisMediaPlayer2Player::Seek(qlonglong offset) { Q_UNUSED(offset); } void MprisMediaPlayer2Player::SetPosition(const QDBusObjectPath &trackId, qlonglong pos) { Q_UNUSED(trackId); Q_UNUSED(pos); } void MprisMediaPlayer2Player::OpenUri(const QString &uri) { Q_UNUSED(uri); } void MprisMediaPlayer2Player::onSlideShowStateChanged() { if (!updatePlaybackStatus()) { return; } signalPropertyChange(QStringLiteral("Position"), position()); signalPropertyChange(QStringLiteral("PlaybackStatus"), mPlaybackStatus); } void MprisMediaPlayer2Player::onCurrentUrlChanged(const QUrl &url) { if (url.isEmpty()) { mCurrentDocument = Document::Ptr(); } else { mCurrentDocument = DocumentFactory::instance()->load(url); connect(mCurrentDocument.data(), &Document::metaInfoUpdated, this, &MprisMediaPlayer2Player::onMetaInfoUpdated); } onMetaInfoUpdated(); signalPropertyChange(QStringLiteral("Position"), position()); } void MprisMediaPlayer2Player::onMetaInfoUpdated() { QVariantMap updatedMetaData; if (mCurrentDocument) { const QUrl url = mCurrentDocument->url(); ImageMetaInfoModel *metaInfoModel = mCurrentDocument->metaInfo(); // We need some unique id mapping to urls. The index in the list is not reliable, // as images can be added/removed during a running slideshow // To allow some bidrectional mapping, convert the url to base64 to encode it for // matching the D-Bus object path spec const QString slideId = QString::fromLatin1(url.toString().toUtf8().toBase64(QByteArray::OmitTrailingEquals).replace('+', "")); const QDBusObjectPath trackId(QStringLiteral("/org/kde/gwenview/imagelist/") + slideId); updatedMetaData.insert(QStringLiteral("mpris:trackid"), QVariant::fromValue<QDBusObjectPath>(trackId)); // TODO: for videos also get and report the length if (MimeTypeUtils::urlKind(url) != MimeTypeUtils::KIND_VIDEO) { // convert seconds in microseconds const auto duration = qlonglong(mSlideShow->interval() * 1000000); updatedMetaData.insert(QStringLiteral("mpris:length"), duration); } // TODO: update on metadata changes, given user can edit most of this data const QString name = metaInfoModel->getValueForKey(QStringLiteral("General.Name")); updatedMetaData.insert(QStringLiteral("xesam:title"), name); const QString comment = metaInfoModel->getValueForKey(QStringLiteral("General.Comment")); if (!comment.isEmpty()) { updatedMetaData.insert(QStringLiteral("xesam:comment"), comment); } updatedMetaData.insert(QStringLiteral("xesam:url"), url.toString()); // slight bending of semantics :) const KFileItem folderItem(mContextManager->currentDirUrl()); updatedMetaData.insert(QStringLiteral("xesam:album"), folderItem.text()); // TODO: hook up with thumbnail cache and pass that as arturl // updatedMetaData.insert(QStringLiteral("mpris:artUrl"), url.toString()); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE const QModelIndex index = mContextManager->dirModel()->indexForUrl(url); if (index.isValid()) { const double rating = index.data(SemanticInfoDirModel::RatingRole).toInt() / 10.0; updatedMetaData.insert(QStringLiteral("xesam:userRating"), rating); } #endif // consider export of other metadata where mapping works } if (updatedMetaData != mMetaData) { mMetaData = updatedMetaData; signalPropertyChange(QStringLiteral("Metadata"), mMetaData); } } void MprisMediaPlayer2Player::onRandomActionToggled(bool checked) { signalPropertyChange(QStringLiteral("Shuffle"), checked); } void MprisMediaPlayer2Player::onToggleSlideShowActionChanged() { const bool isEnabled = mToggleSlideShowAction->isEnabled(); if (mSlideShowEnabled == isEnabled) { return; } mSlideShowEnabled = isEnabled; const bool playbackStatusChanged = updatePlaybackStatus(); signalPropertyChange(QStringLiteral("CanPlay"), mSlideShowEnabled); signalPropertyChange(QStringLiteral("CanPause"), mSlideShowEnabled); if (playbackStatusChanged) { signalPropertyChange(QStringLiteral("Position"), position()); signalPropertyChange(QStringLiteral("PlaybackStatus"), mPlaybackStatus); } } void MprisMediaPlayer2Player::onNextActionChanged() { const bool isEnabled = mNextAction->isEnabled(); if (mNextEnabled == isEnabled) { return; } mNextEnabled = isEnabled; signalPropertyChange(QStringLiteral("CanGoNext"), mNextEnabled); } void MprisMediaPlayer2Player::onPreviousActionChanged() { const bool isEnabled = mPreviousAction->isEnabled(); if (mPreviousEnabled == isEnabled) { return; } mPreviousEnabled = isEnabled; signalPropertyChange(QStringLiteral("CanGoPrevious"), mPreviousEnabled); } } #include "moc_mprismediaplayer2player.cpp"
10,616
C++
.cpp
289
31.692042
135
0.734555
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,855
mpris2service.cpp
KDE_gwenview/lib/mpris2/mpris2service.cpp
/* Gwenview: an image viewer Copyright 2018 Friedrich W. H. Kossebau <kossebau@kde.org> 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 "mpris2service.h" // lib #include "lockscreenwatcher.h" #include "mprismediaplayer2.h" #include "mprismediaplayer2player.h" #include <slideshow.h> // Qt #include <QDBusConnection> // std #include <unistd.h> namespace Gwenview { inline QString mediaPlayer2ObjectPath() { return QStringLiteral("/org/mpris/MediaPlayer2"); } Mpris2Service::Mpris2Service(SlideShow *slideShow, ContextManager *contextManager, QAction *toggleSlideShowAction, QAction *fullScreenAction, QAction *previousAction, QAction *nextAction, QObject *parent) : QObject(parent) , m_fullscreenAction(fullScreenAction) { new MprisMediaPlayer2(mediaPlayer2ObjectPath(), fullScreenAction, this); new MprisMediaPlayer2Player(mediaPlayer2ObjectPath(), slideShow, contextManager, toggleSlideShowAction, fullScreenAction, previousAction, nextAction, this); // To avoid appearing in the media controller on the lock screen, // which might be not expected or wanted for Gwenview, // the MPRIS service is unregistered while the lockscreen is active. auto lockScreenWatcher = new LockScreenWatcher(this); connect(lockScreenWatcher, &LockScreenWatcher::isLockedChanged, this, &Mpris2Service::onLockScreenLockedChanged); connect(fullScreenAction, &QAction::toggled, this, &Mpris2Service::onFullScreenActionToggled); if (!lockScreenWatcher->isLocked() && fullScreenAction->isChecked()) { registerOnDBus(); } } Mpris2Service::~Mpris2Service() { unregisterOnDBus(); } void Mpris2Service::registerOnDBus() { QDBusConnection sessionBus = QDBusConnection::sessionBus(); // try to register MPRIS presentation object // to be done before registering the service name, so it is already present // when controllers react to the service name having appeared const bool objectRegistered = sessionBus.registerObject(mediaPlayer2ObjectPath(), this, QDBusConnection::ExportAdaptors); // try to register MPRIS presentation service if (objectRegistered) { mMpris2ServiceName = QStringLiteral("org.mpris.MediaPlayer2.Gwenview"); bool serviceRegistered = QDBusConnection::sessionBus().registerService(mMpris2ServiceName); // Perhaps not the first instance? Try again with another name, as specified by MPRIS2 spec: if (!serviceRegistered) { mMpris2ServiceName = mMpris2ServiceName + QLatin1String(".instance") + QString::number(getpid()); serviceRegistered = QDBusConnection::sessionBus().registerService(mMpris2ServiceName); } if (!serviceRegistered) { mMpris2ServiceName.clear(); sessionBus.unregisterObject(mediaPlayer2ObjectPath()); } } } void Mpris2Service::unregisterOnDBus() { if (mMpris2ServiceName.isEmpty()) { return; } QDBusConnection sessionBus = QDBusConnection::sessionBus(); sessionBus.unregisterService(mMpris2ServiceName); sessionBus.unregisterObject(mediaPlayer2ObjectPath()); } void Mpris2Service::onLockScreenLockedChanged(bool isLocked) { if (isLocked) { unregisterOnDBus(); } else { registerOnDBus(); } } void Mpris2Service::onFullScreenActionToggled() { if (m_fullscreenAction->isChecked()) { registerOnDBus(); } else { unregisterOnDBus(); } } } #include "moc_mpris2service.cpp"
4,294
C++
.cpp
106
35
160
0.732726
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,856
lockscreenwatcher.cpp
KDE_gwenview/lib/mpris2/lockscreenwatcher.cpp
/* Gwenview: an image viewer Copyright 2013 Martin Gräßlin <mgraesslin@kde.org> Copyright 2018 Friedrich W. H. Kossebau <kossebau@kde.org> 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 "lockscreenwatcher.h" // lib #include <screensaverdbusinterface.h> // Qt #include <QDBusServiceWatcher> #include <QFutureWatcher> #include <QtConcurrentRun> namespace Gwenview { using DBusBoolReplyWatcher = QFutureWatcher<QDBusReply<bool>>; using DBusStringReplyWatcher = QFutureWatcher<QDBusReply<QString>>; inline QString screenSaverServiceName() { return QStringLiteral("org.freedesktop.ScreenSaver"); } LockScreenWatcher::LockScreenWatcher(QObject *parent) : QObject(parent) { auto screenLockServiceWatcher = new QDBusServiceWatcher(this); connect(screenLockServiceWatcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &LockScreenWatcher::onScreenSaverServiceOwnerChanged); screenLockServiceWatcher->setWatchMode(QDBusServiceWatcher::WatchForOwnerChange); screenLockServiceWatcher->addWatchedService(screenSaverServiceName()); if (QDBusConnection::sessionBus().interface()) { auto watcher = new DBusBoolReplyWatcher(this); connect(watcher, &DBusBoolReplyWatcher::finished, this, &LockScreenWatcher::onServiceRegisteredQueried); connect(watcher, &DBusBoolReplyWatcher::canceled, watcher, &DBusBoolReplyWatcher::deleteLater); watcher->setFuture( QtConcurrent::run(&QDBusConnectionInterface::isServiceRegistered, QDBusConnection::sessionBus().interface(), screenSaverServiceName())); } } LockScreenWatcher::~LockScreenWatcher() = default; bool LockScreenWatcher::isLocked() const { return mLocked; } void LockScreenWatcher::onScreenSaverServiceOwnerChanged(const QString &serviceName, const QString &oldOwner, const QString &newOwner) { Q_UNUSED(oldOwner) if (serviceName != screenSaverServiceName()) { return; } delete mScreenSaverInterface; mScreenSaverInterface = nullptr; if (!newOwner.isEmpty()) { mScreenSaverInterface = new OrgFreedesktopScreenSaverInterface(newOwner, QStringLiteral("/ScreenSaver"), QDBusConnection::sessionBus(), this); connect(mScreenSaverInterface, &OrgFreedesktopScreenSaverInterface::ActiveChanged, this, &LockScreenWatcher::onScreenSaverActiveChanged); auto watcher = new QDBusPendingCallWatcher(mScreenSaverInterface->GetActive(), this); connect(watcher, &QDBusPendingCallWatcher::finished, this, &LockScreenWatcher::onActiveQueried); } else { if (mLocked) { // reset mLocked = false; Q_EMIT isLockedChanged(mLocked); } } } void LockScreenWatcher::onServiceRegisteredQueried() { auto watcher = dynamic_cast<DBusBoolReplyWatcher *>(sender()); if (!watcher) { return; } const QDBusReply<bool> &reply = watcher->result(); if (reply.isValid() && reply.value()) { auto ownerWatcher = new DBusStringReplyWatcher(this); connect(ownerWatcher, &DBusStringReplyWatcher::finished, this, &LockScreenWatcher::onServiceOwnerQueried); connect(ownerWatcher, &DBusStringReplyWatcher::canceled, ownerWatcher, &DBusStringReplyWatcher::deleteLater); ownerWatcher->setFuture( QtConcurrent::run(&QDBusConnectionInterface::serviceOwner, QDBusConnection::sessionBus().interface(), screenSaverServiceName())); } watcher->deleteLater(); } void LockScreenWatcher::onServiceOwnerQueried() { auto watcher = dynamic_cast<DBusStringReplyWatcher *>(sender()); if (!watcher) { return; } const QDBusReply<QString> reply = watcher->result(); if (reply.isValid()) { onScreenSaverServiceOwnerChanged(screenSaverServiceName(), QString(), reply.value()); } watcher->deleteLater(); } void LockScreenWatcher::onActiveQueried(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<bool> reply = *watcher; if (!reply.isError()) { onScreenSaverActiveChanged(reply.value()); } watcher->deleteLater(); } void LockScreenWatcher::onScreenSaverActiveChanged(bool isActive) { if (mLocked == isActive) { return; } mLocked = isActive; Q_EMIT isLockedChanged(mLocked); } } #include "moc_lockscreenwatcher.cpp"
4,934
C++
.cpp
118
37.338983
150
0.76077
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,857
decoratedtag.cpp
KDE_gwenview/lib/decoratedtag/decoratedtag.cpp
// SPDX-FileCopyrightText: 2021 Noah Davis <noahadvs@gmail.com> // SPDX-License-Identifier: LGPL-2.1-or-later #include "decoratedtag.h" #include <KColorUtils> #include <QEvent> #include <QPaintEvent> #include <QStylePainter> using namespace Gwenview; class Gwenview::DecoratedTagPrivate { Q_DECLARE_PUBLIC(DecoratedTag) public: DecoratedTagPrivate(DecoratedTag *q) : q_ptr(q) { } DecoratedTag *q_ptr = nullptr; void updateMargins(); qreal horizontalMargin; qreal verticalMargin; }; void DecoratedTagPrivate::updateMargins() { Q_Q(DecoratedTag); horizontalMargin = q->fontMetrics().descent() + 2; verticalMargin = 2; q->setContentsMargins(horizontalMargin, verticalMargin, horizontalMargin, verticalMargin); } DecoratedTag::DecoratedTag(QWidget *parent, Qt::WindowFlags f) : QLabel(parent, f) , d_ptr(new DecoratedTagPrivate(this)) { Q_D(DecoratedTag); d->updateMargins(); } DecoratedTag::DecoratedTag(const QString &text, QWidget *parent, Qt::WindowFlags f) : QLabel(text, parent, f) , d_ptr(new DecoratedTagPrivate(this)) { Q_D(DecoratedTag); d->updateMargins(); } Gwenview::DecoratedTag::~DecoratedTag() noexcept = default; void DecoratedTag::changeEvent(QEvent *event) { Q_D(DecoratedTag); if (event->type() == QEvent::FontChange) { d->updateMargins(); } } void DecoratedTag::paintEvent(QPaintEvent *event) { Q_D(const DecoratedTag); QStylePainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const QColor penColor = KColorUtils::mix(palette().base().color(), palette().text().color(), 0.3); // QPainter is bad at drawing lines that are exactly 1px. // Using QPen::setCosmetic(true) with a 1px pen width // doesn't look quite as good as just using 1.001px. const qreal penWidth = 1.001; const qreal penMargin = penWidth / 2; QPen pen(penColor, penWidth); pen.setCosmetic(true); QRectF rect = event->rect(); rect.adjust(penMargin, penMargin, -penMargin, -penMargin); painter.setBrush(palette().base()); painter.setPen(pen); painter.drawRoundedRect(rect, d->horizontalMargin, d->horizontalMargin); QLabel::paintEvent(event); } #include "moc_decoratedtag.cpp"
2,264
C++
.cpp
71
28.253521
102
0.72319
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,858
thumbnailgenerator.cpp
KDE_gwenview/lib/thumbnailprovider/thumbnailgenerator.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "thumbnailgenerator.h" // Local #include "gwenview_lib_debug.h" #include "gwenviewconfig.h" #include "jpegcontent.h" // KDCRAW #ifdef KDCRAW_FOUND #include <KDCRAW/KDcraw> #endif // KF // Qt #include <QBuffer> #include <QCoreApplication> #include <QImageReader> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) // qCDebug(GWENVIEW_LIB_LOG) << x #else #define LOG(x) ; #endif //------------------------------------------------------------------------ // // ThumbnailContext // //------------------------------------------------------------------------ bool ThumbnailContext::load(const QString &pixPath, int pixelSize) { mImage = QImage(); mNeedCaching = true; QImage originalImage; QSize originalSize; QByteArray formatHint = pixPath.section(QLatin1Char('.'), -1).toLocal8Bit().toLower(); QImageReader reader(pixPath); JpegContent content; QByteArray format; QByteArray data; QBuffer buffer; int previewRatio = 1; #ifdef KDCRAW_FOUND // raw images deserve special treatment if (KDcrawIface::KDcraw::rawFilesList().contains(QString::fromLatin1(formatHint))) { // use KDCraw to extract the preview bool ret = KDcrawIface::KDcraw::loadEmbeddedPreview(data, pixPath); // We need QImage. Loading JpegContent from QImage - exif lost // Loading QImage from JpegContent - unimplemented, would go with loadFromData if (!ret) { // if the embedded preview loading failed, load half preview instead. That's slower... if (!KDcrawIface::KDcraw::loadHalfPreview(data, pixPath)) { qCWarning(GWENVIEW_LIB_LOG) << "unable to get preview for " << pixPath.toUtf8().constData(); return false; } previewRatio = 2; } // And we need JpegContent too because of EXIF (orientation!). if (!content.loadFromData(data)) { qCWarning(GWENVIEW_LIB_LOG) << "unable to load preview for " << pixPath.toUtf8().constData(); return false; } buffer.setBuffer(&data); buffer.open(QIODevice::ReadOnly); reader.setDevice(&buffer); reader.setFormat("jpg"); } else { #else { #endif if (QImageReader::imageFormat(pixPath) == QByteArray("raw")) { // make preview generation faster (same as KDcrawIface::KDcraw::loadHalfPreview) reader.setQuality(1); previewRatio = 2; } if (!reader.canRead()) { reader.setDecideFormatFromContent(true); // Set filename again, otherwise QImageReader won't restart from scratch reader.setFileName(pixPath); } if (reader.format() == "jpeg" && GwenviewConfig::applyExifOrientation()) { content.load(pixPath); } } // If there's jpeg content (from jpg or raw files), try to load an embedded thumbnail, if available. if (!content.rawData().isEmpty()) { QImage thumbnail = content.thumbnail(); // If the user does not care about the generated thumbnails (by deleting them on exit), use ANY // embedded thumnail, even if it's too small. if (!thumbnail.isNull() && (GwenviewConfig::lowResourceUsageMode() || qMax(thumbnail.width(), thumbnail.height()) >= pixelSize)) { mImage = std::move(thumbnail); mOriginalWidth = content.size().width(); mOriginalHeight = content.size().height(); return true; } } // Generate thumbnail from full image originalSize = reader.size(); if (originalSize.isValid() && reader.supportsOption(QImageIOHandler::ScaledSize) && qMax(originalSize.width(), originalSize.height()) >= pixelSize) { QSizeF scaledSize = originalSize; scaledSize.scale(pixelSize, pixelSize, Qt::KeepAspectRatio); if (!scaledSize.isEmpty()) { reader.setScaledSize(scaledSize.toSize()); } } // Rotate if necessary if (GwenviewConfig::applyExifOrientation()) { reader.setAutoTransform(true); } // format() is empty after QImageReader::read() is called format = reader.format(); if (!reader.read(&originalImage)) { return false; } if (!originalSize.isValid()) { originalSize = originalImage.size(); } mOriginalWidth = originalSize.width() * previewRatio; mOriginalHeight = originalSize.height() * previewRatio; if (qMax(mOriginalWidth, mOriginalHeight) <= pixelSize) { mImage = originalImage; mNeedCaching = format != "png"; } else { mImage = originalImage.scaled(pixelSize, pixelSize, Qt::KeepAspectRatio); } if (reader.autoTransform() && (reader.transformation() & QImageIOHandler::TransformationRotate90)) { std::swap(mOriginalWidth, mOriginalHeight); } return true; } //------------------------------------------------------------------------ // // ThumbnailGenerator // //------------------------------------------------------------------------ ThumbnailGenerator::ThumbnailGenerator() : mCancel(false) { connect( qApp, &QCoreApplication::aboutToQuit, this, [=]() { cancel(); wait(); }, Qt::DirectConnection); start(); } void ThumbnailGenerator::load(const QString &originalUri, time_t originalTime, KIO::filesize_t originalFileSize, const QString &originalMimeType, const QString &pixPath, const QString &thumbnailPath, ThumbnailGroup::Enum group) { QMutexLocker lock(&mMutex); Q_ASSERT(mPixPath.isNull()); mOriginalUri = originalUri; mOriginalTime = originalTime; mOriginalFileSize = originalFileSize; mOriginalMimeType = originalMimeType; mPixPath = pixPath; mThumbnailPath = thumbnailPath; mThumbnailGroup = group; mCond.wakeOne(); } QString ThumbnailGenerator::originalUri() const { return mOriginalUri; } bool ThumbnailGenerator::isStopped() { QMutexLocker lock(&mMutex); return mStopped; } time_t ThumbnailGenerator::originalTime() const { return mOriginalTime; } KIO::filesize_t ThumbnailGenerator::originalFileSize() const { return mOriginalFileSize; } QString ThumbnailGenerator::originalMimeType() const { return mOriginalMimeType; } bool ThumbnailGenerator::testCancel() { QMutexLocker lock(&mMutex); return mCancel; } void ThumbnailGenerator::cancel() { QMutexLocker lock(&mMutex); mCancel = true; mCond.wakeOne(); } void ThumbnailGenerator::run() { while (!testCancel()) { QString pixPath; int pixelSize; { QMutexLocker lock(&mMutex); // empty mPixPath means nothing to do if (mPixPath.isNull()) { mCond.wait(&mMutex); } } if (testCancel()) { break; } { QMutexLocker lock(&mMutex); pixPath = mPixPath; pixelSize = ThumbnailGroup::pixelSize(mThumbnailGroup); } Q_ASSERT(!pixPath.isNull()); LOG("Loading" << pixPath); ThumbnailContext context; bool ok = context.load(pixPath, pixelSize); { QMutexLocker lock(&mMutex); if (ok) { mImage = context.mImage; mOriginalWidth = context.mOriginalWidth; mOriginalHeight = context.mOriginalHeight; if (context.mNeedCaching && mThumbnailGroup <= ThumbnailGroup::XXLarge) { cacheThumbnail(); } } else { // avoid emitting the thumb from the previous successful run mImage = QImage(); qCWarning(GWENVIEW_LIB_LOG) << "Could not generate thumbnail for file" << mOriginalUri; } mPixPath.clear(); // done, ready for next } if (testCancel()) { break; } { QSize size(mOriginalWidth, mOriginalHeight); LOG("emitting done signal, size=" << size); QMutexLocker lock(&mMutex); Q_EMIT done(mImage, size); LOG("Done"); } } LOG("Ending thread"); QMutexLocker lock(&mMutex); mStopped = true; deleteLater(); } void ThumbnailGenerator::cacheThumbnail() { mImage.setText(QStringLiteral("Thumb::URI"), mOriginalUri); mImage.setText(QStringLiteral("Thumb::MTime"), QString::number(mOriginalTime)); mImage.setText(QStringLiteral("Thumb::Size"), QString::number(mOriginalFileSize)); mImage.setText(QStringLiteral("Thumb::Mimetype"), mOriginalMimeType); mImage.setText(QStringLiteral("Thumb::Image::Width"), QString::number(mOriginalWidth)); mImage.setText(QStringLiteral("Thumb::Image::Height"), QString::number(mOriginalHeight)); mImage.setText(QStringLiteral("Software"), QStringLiteral("Gwenview")); Q_EMIT thumbnailReadyToBeCached(mThumbnailPath, mImage); } } // namespace #include "moc_thumbnailgenerator.cpp"
10,077
C++
.cpp
286
28.374126
153
0.630709
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,859
thumbnailwriter.cpp
KDE_gwenview/lib/thumbnailprovider/thumbnailwriter.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "thumbnailwriter.h" // Local #include "gwenview_lib_debug.h" #include "gwenviewconfig.h" // Qt #include <QImage> #include <QTemporaryFile> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) // qCDebug(GWENVIEW_LIB_LOG) << x #else #define LOG(x) ; #endif static void storeThumbnailToDiskCache(const QString &path, const QImage &image) { if (GwenviewConfig::lowResourceUsageMode()) { return; } LOG(path); QTemporaryFile tmp(path + QStringLiteral(".gwenview.tmpXXXXXX.png")); if (!tmp.open()) { qCWarning(GWENVIEW_LIB_LOG) << "Could not create a temporary file."; return; } if (!image.save(tmp.fileName(), "png")) { qCWarning(GWENVIEW_LIB_LOG) << "Could not save thumbnail"; return; } QFile::rename(tmp.fileName(), path); } void ThumbnailWriter::queueThumbnail(const QString &path, const QImage &image) { if (GwenviewConfig::lowResourceUsageMode()) { return; } LOG(path); QMutexLocker locker(&mMutex); mCache.insert(path, image); start(); } void ThumbnailWriter::run() { QMutexLocker locker(&mMutex); while (!mCache.isEmpty() && !isInterruptionRequested()) { Cache::ConstIterator it = mCache.constBegin(); const QString path = it.key(); const QImage image = it.value(); // This part of the thread is the most time consuming but it does not // depend on mCache so we can unlock here. This way other thumbnails // can be added or queried locker.unlock(); storeThumbnailToDiskCache(path, image); locker.relock(); mCache.remove(path); } } QImage ThumbnailWriter::value(const QString &path) const { QMutexLocker locker(&mMutex); return mCache.value(path); } bool ThumbnailWriter::isEmpty() const { QMutexLocker locker(&mMutex); return mCache.isEmpty(); } } // namespace #include "moc_thumbnailwriter.cpp"
2,815
C++
.cpp
89
27.955056
81
0.719305
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,860
thumbnailprovider.cpp
KDE_gwenview/lib/thumbnailprovider/thumbnailprovider.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview - A simple image viewer for KDE Copyright 2000-2007 Aurélien Gâteau <agateau@kde.org> This class is based on the ImagePreviewJob class from Konqueror. */ /* This file is part of the KDE project Copyright (C) 2000 David Faure <faure@kde.org> 2000 Carsten Pfeiffer <pfeiffer@kde.org> 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 "thumbnailprovider.h" #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> // Qt #include <QApplication> #include <QCryptographicHash> #include <QDir> #include <QFile> #include <QStandardPaths> #include <QTemporaryFile> // KF #include <KIO/FileCopyJob> #include <KIO/PreviewJob> #include <KIO/StatJob> #include <KJobWidgets> // Local #include "gwenview_lib_debug.h" #include "mimetypeutils.h" #include "thumbnailgenerator.h" #include "thumbnailwriter.h" #include "urlutils.h" namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_LIB_LOG) << x #else #define LOG(x) ; #endif Q_GLOBAL_STATIC(ThumbnailWriter, sThumbnailWriter) static const ThumbnailGroup::Enum s_thumbnailGroups[] = { ThumbnailGroup::Normal, ThumbnailGroup::Large, ThumbnailGroup::XLarge, ThumbnailGroup::XXLarge, }; static QString generateOriginalUri(const QUrl &url_) { QUrl url = url_; return url.adjusted(QUrl::RemovePassword).url(); } static QString generateThumbnailPath(const QString &uri, ThumbnailGroup::Enum group) { QString baseDir = ThumbnailProvider::thumbnailBaseDir(group); QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(QFile::encodeName(uri)); return baseDir + QFile::encodeName(QString::fromLatin1(md5.result().toHex())) + QStringLiteral(".png"); } //------------------------------------------------------------------------ // // ThumbnailProvider static methods // //------------------------------------------------------------------------ static QString sThumbnailBaseDir; QString ThumbnailProvider::thumbnailBaseDir() { if (sThumbnailBaseDir.isEmpty()) { const QByteArray customDir = qgetenv("GV_THUMBNAIL_DIR"); if (customDir.isEmpty()) { sThumbnailBaseDir = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/thumbnails/"); } else { sThumbnailBaseDir = QFile::decodeName(customDir) + QLatin1Char('/'); } } return sThumbnailBaseDir; } void ThumbnailProvider::setThumbnailBaseDir(const QString &dir) { sThumbnailBaseDir = dir; } QString ThumbnailProvider::thumbnailBaseDir(ThumbnailGroup::Enum group) { QString dir = thumbnailBaseDir(); switch (group) { case ThumbnailGroup::Normal: dir += QStringLiteral("normal/"); break; case ThumbnailGroup::Large: dir += QStringLiteral("large/"); break; case ThumbnailGroup::XLarge: dir += QStringLiteral("x-large/"); break; case ThumbnailGroup::XXLarge: dir += QStringLiteral("xx-large/"); break; default: dir += QLatin1String("x-gwenview/"); // Should never be hit, but just in case } return dir; } void ThumbnailProvider::deleteImageThumbnail(const QUrl &url) { QString uri = generateOriginalUri(url); for (auto group : s_thumbnailGroups) { QFile::remove(generateThumbnailPath(uri, group)); } } static void moveThumbnailHelper(const QString &oldUri, const QString &newUri, ThumbnailGroup::Enum group) { QString oldPath = generateThumbnailPath(oldUri, group); QString newPath = generateThumbnailPath(newUri, group); QImage thumb; if (!thumb.load(oldPath)) { return; } thumb.setText(QStringLiteral("Thumb::URI"), newUri); thumb.save(newPath, "png"); QFile::remove(QFile::encodeName(oldPath)); } void ThumbnailProvider::moveThumbnail(const QUrl &oldUrl, const QUrl &newUrl) { QString oldUri = generateOriginalUri(oldUrl); QString newUri = generateOriginalUri(newUrl); for (auto group : s_thumbnailGroups) { moveThumbnailHelper(oldUri, newUri, group); } } //------------------------------------------------------------------------ // // ThumbnailProvider implementation // //------------------------------------------------------------------------ ThumbnailProvider::ThumbnailProvider() : KIO::Job() , mState(STATE_NEXTTHUMB) , mOriginalTime(0) { LOG(this); // Make sure we have a place to store our thumbnails for (auto group : s_thumbnailGroups) { const QString thumbnailDir = ThumbnailProvider::thumbnailBaseDir(group); QDir().mkpath(thumbnailDir); QFile::setPermissions(thumbnailDir, QFileDevice::WriteOwner | QFileDevice::ReadOwner | QFileDevice::ExeOwner); } // Look for images and store the items in our todo list mCurrentItem = KFileItem(); mThumbnailGroup = ThumbnailGroup::XXLarge; createNewThumbnailGenerator(); } ThumbnailProvider::~ThumbnailProvider() { LOG(this); disconnect(mThumbnailGenerator, nullptr, this, nullptr); disconnect(mThumbnailGenerator, nullptr, sThumbnailWriter, nullptr); abortSubjob(); mThumbnailGenerator->cancel(); if (mPreviousThumbnailGenerator) { disconnect(mPreviousThumbnailGenerator, nullptr, sThumbnailWriter, nullptr); } sThumbnailWriter->requestInterruption(); sThumbnailWriter->wait(); } void ThumbnailProvider::stop() { // Clear mItems and create a new ThumbnailGenerator if mThumbnailGenerator is running, // but also make sure that at most two ThumbnailGenerators are running. // startCreatingThumbnail() will take care that these two threads won't work on the same item. mItems.clear(); abortSubjob(); if (!mThumbnailGenerator->isStopped() && !mPreviousThumbnailGenerator) { mPreviousThumbnailGenerator = mThumbnailGenerator; mPreviousThumbnailGenerator->cancel(); disconnect(mPreviousThumbnailGenerator, nullptr, this, nullptr); connect(mPreviousThumbnailGenerator, SIGNAL(finished()), mPreviousThumbnailGenerator, SLOT(deleteLater())); createNewThumbnailGenerator(); mCurrentItem = KFileItem(); } } const KFileItemList &ThumbnailProvider::pendingItems() const { return mItems; } void ThumbnailProvider::setThumbnailGroup(ThumbnailGroup::Enum group) { mThumbnailGroup = group; } void ThumbnailProvider::appendItems(const KFileItemList &items) { if (!mItems.isEmpty()) { QSet<KFileItem> itemSet{mItems.begin(), mItems.end()}; for (const KFileItem &item : items) { if (!itemSet.contains(item)) { mItems.append(item); } } } else { mItems = items; } if (mCurrentItem.isNull()) { determineNextIcon(); } } void ThumbnailProvider::removeItems(const KFileItemList &itemList) { if (mItems.isEmpty()) { return; } for (const KFileItem &item : itemList) { // If we are removing the next item, update to be the item after or the // first if we removed the last item mItems.removeAll(item); if (item == mCurrentItem) { abortSubjob(); } } // No more current item, carry on to the next remaining item if (mCurrentItem.isNull()) { determineNextIcon(); } } void ThumbnailProvider::removePendingItems() { mItems.clear(); } bool ThumbnailProvider::isRunning() const { return !mCurrentItem.isNull(); } //-Internal-------------------------------------------------------------- void ThumbnailProvider::createNewThumbnailGenerator() { mThumbnailGenerator = new ThumbnailGenerator; connect(mThumbnailGenerator, SIGNAL(done(QImage, QSize)), SLOT(thumbnailReady(QImage, QSize)), Qt::QueuedConnection); connect(mThumbnailGenerator, SIGNAL(thumbnailReadyToBeCached(QString, QImage)), sThumbnailWriter, SLOT(queueThumbnail(QString, QImage)), Qt::QueuedConnection); } void ThumbnailProvider::abortSubjob() { if (hasSubjobs()) { LOG("Killing subjob"); KJob *job = subjobs().first(); job->kill(); removeSubjob(job); mCurrentItem = KFileItem(); } } void ThumbnailProvider::determineNextIcon() { LOG(this); mState = STATE_NEXTTHUMB; // No more items ? if (mItems.isEmpty()) { LOG("No more items. Nothing to do"); mCurrentItem = KFileItem(); Q_EMIT finished(); return; } mCurrentItem = mItems.takeFirst(); LOG("mCurrentItem.url=" << mCurrentItem.url()); // First, stat the orig file mState = STATE_STATORIG; mCurrentUrl = mCurrentItem.url().adjusted(QUrl::NormalizePathSegments); mOriginalFileSize = mCurrentItem.size(); // Do direct stat instead of using KIO if the file is local (faster) if (UrlUtils::urlIsFastLocalFile(mCurrentUrl)) { QFileInfo fileInfo(mCurrentUrl.toLocalFile()); mOriginalTime = fileInfo.lastModified().toSecsSinceEpoch(); QMetaObject::invokeMethod(this, &ThumbnailProvider::checkThumbnail, Qt::QueuedConnection); } else { KIO::Job *job = KIO::stat(mCurrentUrl, KIO::HideProgressInfo); KJobWidgets::setWindow(job, qApp->activeWindow()); LOG("KIO::stat orig" << mCurrentUrl.url()); addSubjob(job); } LOG("/determineNextIcon" << this); } void ThumbnailProvider::slotResult(KJob *job) { LOG(mState); removeSubjob(job); Q_ASSERT(subjobs().isEmpty()); // We should have only one job at a time switch (mState) { case STATE_NEXTTHUMB: Q_ASSERT(false); determineNextIcon(); return; case STATE_STATORIG: { // Could not stat original, drop this one and move on to the next one if (job->error()) { emitThumbnailLoadingFailed(); determineNextIcon(); return; } // Get modification time of the original file KIO::UDSEntry entry = static_cast<KIO::StatJob *>(job)->statResult(); mOriginalTime = entry.numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1); checkThumbnail(); return; } case STATE_DOWNLOADORIG: if (job->error()) { emitThumbnailLoadingFailed(); LOG("Delete temp file" << mTempPath); QFile::remove(mTempPath); mTempPath.clear(); determineNextIcon(); } else { startCreatingThumbnail(mTempPath); } return; case STATE_PREVIEWJOB: determineNextIcon(); return; } } void ThumbnailProvider::thumbnailReady(const QImage &_img, const QSize &_size) { QImage img = _img; QSize size = _size; if (!img.isNull()) { emitThumbnailLoaded(img, size); } else { emitThumbnailLoadingFailed(); } if (!mTempPath.isEmpty()) { LOG("Delete temp file" << mTempPath); QFile::remove(mTempPath); mTempPath.clear(); } determineNextIcon(); } QImage ThumbnailProvider::loadThumbnailFromCache() const { if (mThumbnailGroup > ThumbnailGroup::XXLarge) { return {}; } QImage image = sThumbnailWriter->value(mThumbnailPath); if (!image.isNull()) { return image; } if (!QFileInfo::exists(mThumbnailPath)) { return {}; } image = QImage(mThumbnailPath); int largeThumbnailGroup = mThumbnailGroup; while (image.isNull() && ++largeThumbnailGroup <= ThumbnailGroup::XXLarge) { // If there is a large-sized thumbnail, generate the small-sized version from it const QString largeThumbnailPath = generateThumbnailPath(mOriginalUri, static_cast<ThumbnailGroup::Enum>(largeThumbnailGroup)); const QImage largeImage(largeThumbnailPath); if (!largeImage.isNull()) { const int size = ThumbnailGroup::pixelSize(mThumbnailGroup); image = largeImage.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation); const QStringList textKeys = largeImage.textKeys(); for (const QString &key : textKeys) { QString text = largeImage.text(key); image.setText(key, text); } sThumbnailWriter->queueThumbnail(mThumbnailPath, image); break; } } return image; } void ThumbnailProvider::checkThumbnail() { if (mCurrentItem.isNull()) { // This can happen if current item has been removed by removeItems() determineNextIcon(); return; } // If we are in the thumbnail dir, just load the file if (mCurrentUrl.isLocalFile() && mCurrentUrl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).path().startsWith(thumbnailBaseDir())) { QImage image(mCurrentUrl.toLocalFile()); emitThumbnailLoaded(image, image.size()); determineNextIcon(); return; } mOriginalUri = generateOriginalUri(mCurrentUrl); mThumbnailPath = generateThumbnailPath(mOriginalUri, mThumbnailGroup); LOG("Stat thumb" << mThumbnailPath); QImage thumb = loadThumbnailFromCache(); KIO::filesize_t fileSize = thumb.text(QStringLiteral("Thumb::Size")).toULongLong(); if (!thumb.isNull()) { if (thumb.text(QStringLiteral("Thumb::URI")) == mOriginalUri && thumb.text(QStringLiteral("Thumb::MTime")).toInt() == mOriginalTime && (fileSize == 0 || fileSize == mOriginalFileSize)) { int width = 0, height = 0; QSize size; bool ok; width = thumb.text(QStringLiteral("Thumb::Image::Width")).toInt(&ok); if (ok) height = thumb.text(QStringLiteral("Thumb::Image::Height")).toInt(&ok); if (ok) { size = QSize(width, height); } else { LOG("Thumbnail for" << mOriginalUri << "does not contain correct image size information"); // Don't try to determine the size of a video, it probably won't work and // will cause high I/O usage with big files (bug #307007). if (MimeTypeUtils::urlKind(mCurrentUrl) == MimeTypeUtils::KIND_VIDEO) { emitThumbnailLoaded(thumb, QSize()); determineNextIcon(); return; } } emitThumbnailLoaded(thumb, size); determineNextIcon(); return; } } // Thumbnail not found or not valid if (MimeTypeUtils::fileItemKind(mCurrentItem) == MimeTypeUtils::KIND_RASTER_IMAGE) { if (mCurrentUrl.isLocalFile()) { // Original is a local file, create the thumbnail startCreatingThumbnail(mCurrentUrl.toLocalFile()); } else { // Original is remote, download it mState = STATE_DOWNLOADORIG; QTemporaryFile tempFile; tempFile.setAutoRemove(false); if (!tempFile.open()) { qCWarning(GWENVIEW_LIB_LOG) << "Couldn't create temp file to download " << mCurrentUrl.toDisplayString(); emitThumbnailLoadingFailed(); determineNextIcon(); return; } mTempPath = tempFile.fileName(); QUrl url = QUrl::fromLocalFile(mTempPath); KIO::Job *job = KIO::file_copy(mCurrentUrl, url, -1, KIO::Overwrite | KIO::HideProgressInfo); KJobWidgets::setWindow(job, qApp->activeWindow()); LOG("Download remote file" << mCurrentUrl.toDisplayString() << "to" << url.toDisplayString()); addSubjob(job); } } else { // Not a raster image, use a KPreviewJob LOG("Starting a KPreviewJob for" << mCurrentItem.url()); mState = STATE_PREVIEWJOB; KFileItemList list; list.append(mCurrentItem); const int pixelSize = ThumbnailGroup::pixelSize(mThumbnailGroup); if (mPreviewPlugins.isEmpty()) { mPreviewPlugins = KIO::PreviewJob::availablePlugins(); } KIO::Job *job = KIO::filePreview(list, QSize(pixelSize, pixelSize), &mPreviewPlugins); // KJobWidgets::setWindow(job, qApp->activeWindow()); connect(job, SIGNAL(gotPreview(KFileItem, QPixmap)), this, SLOT(slotGotPreview(KFileItem, QPixmap))); connect(job, SIGNAL(failed(KFileItem)), this, SLOT(emitThumbnailLoadingFailed())); addSubjob(job); } } void ThumbnailProvider::startCreatingThumbnail(const QString &pixPath) { LOG("Creating thumbnail from" << pixPath); // If mPreviousThumbnailGenerator is already working on our current item // its thumbnail will be passed to sThumbnailWriter when ready. So we // connect mPreviousThumbnailGenerator's signal "finished" to determineNextIcon // which will load the thumbnail from sThumbnailWriter or from disk // (because we re-add mCurrentItem to mItems). if (mPreviousThumbnailGenerator && !mPreviousThumbnailGenerator->isStopped() && mOriginalUri == mPreviousThumbnailGenerator->originalUri() && mOriginalTime == mPreviousThumbnailGenerator->originalTime() && mOriginalFileSize == mPreviousThumbnailGenerator->originalFileSize() && mCurrentItem.mimetype() == mPreviousThumbnailGenerator->originalMimeType()) { connect(mPreviousThumbnailGenerator, SIGNAL(finished()), SLOT(determineNextIcon())); mItems.prepend(mCurrentItem); return; } mThumbnailGenerator->load(mOriginalUri, mOriginalTime, mOriginalFileSize, mCurrentItem.mimetype(), pixPath, mThumbnailPath, mThumbnailGroup); } void ThumbnailProvider::slotGotPreview(const KFileItem &item, const QPixmap &pixmap) { if (mCurrentItem.isNull()) { // This can happen if current item has been removed by removeItems() return; } LOG(mCurrentItem.url()); QSize size; Q_EMIT thumbnailLoaded(item, pixmap, size, mOriginalFileSize); } void ThumbnailProvider::emitThumbnailLoaded(const QImage &img, const QSize &size) { if (mCurrentItem.isNull()) { // This can happen if current item has been removed by removeItems() return; } LOG(mCurrentItem.url()); QPixmap thumb = QPixmap::fromImage(img); Q_EMIT thumbnailLoaded(mCurrentItem, thumb, size, mOriginalFileSize); } void ThumbnailProvider::emitThumbnailLoadingFailed() { if (mCurrentItem.isNull()) { // This can happen if current item has been removed by removeItems() return; } LOG(mCurrentItem.url()); Q_EMIT thumbnailLoadingFailed(mCurrentItem); } bool ThumbnailProvider::isThumbnailWriterEmpty() { return sThumbnailWriter->isEmpty(); } } // namespace #include "moc_thumbnailprovider.cpp"
19,455
C++
.cpp
517
31.40619
147
0.66672
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,861
fitsplugin.cpp
KDE_gwenview/lib/imageformats/fitsplugin.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ #include "fitsplugin.h" #include "fitshandler.h" #include <QImageIOHandler> QImageIOPlugin::Capabilities FitsPlugin::capabilities(QIODevice *device, const QByteArray &format) const { if (format == "fits" || format == "fit") { return Capabilities(CanRead); } if (!format.isEmpty()) { return {}; } if (!device->isOpen()) { return {}; } Capabilities cap; if (device->isReadable()) { Gwenview::FitsHandler handler; handler.setDevice(device); handler.setFormat(format); if (handler.canRead()) { cap |= CanRead; } } return cap; } QImageIOHandler *FitsPlugin::create(QIODevice *device, const QByteArray &format) const { QImageIOHandler *handler = new Gwenview::FitsHandler; handler->setDevice(device); handler->setFormat(format); return handler; } #include "moc_fitsplugin.cpp"
1,728
C++
.cpp
49
31.244898
104
0.727601
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,862
fitshandler.cpp
KDE_gwenview/lib/imageformats/fitshandler.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ #include "fitshandler.h" #include "imageformats/fitsformat/fitsdata.h" #include "gwenview_lib_debug.h" #include <QImage> #include <QSize> #include <QVariant> namespace Gwenview { bool FitsHandler::canRead() const { if (!device()) { return false; } device()->seek(0); if (device()->peek(6) != "SIMPLE" && device()->peek(8) != "XTENSION") { return false; } FITSData fitsLoader; if (fitsLoader.loadFITS(*device())) { setFormat("fits"); return true; } return false; } bool FitsHandler::read(QImage *image) { if (!device()) { return false; } *image = FITSData::FITSToImage(*device()); return true; } bool FitsHandler::supportsOption(ImageOption option) const { return option == Size; } QVariant FitsHandler::option(ImageOption option) const { if (option == Size && device()) { FITSData fitsLoader; if (fitsLoader.loadFITS(*device())) { return QSize((int)fitsLoader.getWidth(), (int)fitsLoader.getHeight()); } } return QVariant(); } } // namespace
1,914
C++
.cpp
63
26.793651
82
0.712336
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,863
fitsdata.cpp
KDE_gwenview/lib/imageformats/fitsformat/fitsdata.cpp
/*************************************************************************** Gwenview: an image viewer fitsimage.cpp - FITS Image ------------------- begin : Tue Feb 24 2004 copyright : (C) 2004 by Jasem Mutlaq copyright : (C) 2017 by Csaba Kertesz email : mutlaqja@ikarustech.com ***************************************************************************/ /*************************************************************************** * * * 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. * * * * Some code fragments were adapted from Peter Kirchgessner's FITS plugin* * See http://members.aol.com/pkirchg for more details. * ***************************************************************************/ #include "fitsdata.h" // Qt #include <QImage> // STL #include <cmath> FITSData::FITSData() { mode = FITS_NORMAL; debayerParams.method = DC1394_BAYER_METHOD_NEAREST; debayerParams.filter = DC1394_COLOR_FILTER_RGGB; debayerParams.offsetX = debayerParams.offsetY = 0; } FITSData::~FITSData() { int status = 0; clearImageBuffers(); if (fptr) { fits_close_file(fptr, &status); } } bool FITSData::loadFITS(QIODevice &buffer) { int status = 0, anynull = 0; long naxes[3]; char error_status[512]; QString errMessage; qint64 oldPos = buffer.pos(); QByteArray imageData; char *imageDataBuf = nullptr; size_t imageDataSize = 0; buffer.seek(0); imageData = buffer.readAll(); imageDataBuf = imageData.data(); imageDataSize = (size_t)imageData.size(); if (fptr) { fits_close_file(fptr, &status); } if (fits_open_memfile(&fptr, "", READONLY, reinterpret_cast<void **>(&imageDataBuf), &imageDataSize, 3000, nullptr, &status)) { fits_report_error(stderr, status); fits_get_errstatus(status, error_status); errMessage = QString("Could not open file %1. Error %2").arg(filename, QString::fromUtf8(error_status)); buffer.seek(oldPos); return false; } if (fits_get_img_param(fptr, 3, &(stats.bitpix), &(stats.ndim), naxes, &status)) { fits_report_error(stderr, status); fits_get_errstatus(status, error_status); errMessage = QString("FITS file open error (fits_get_img_param): %1").arg(QString::fromUtf8(error_status)); buffer.seek(oldPos); return false; } if (stats.ndim < 2) { errMessage = "1D FITS images are not supported."; buffer.seek(oldPos); return false; } switch (stats.bitpix) { case BYTE_IMG: data_type = TBYTE; stats.bytesPerPixel = sizeof(uint8_t); break; case SHORT_IMG: // Read SHORT image as USHORT data_type = TUSHORT; stats.bytesPerPixel = sizeof(int16_t); break; case USHORT_IMG: data_type = TUSHORT; stats.bytesPerPixel = sizeof(uint16_t); break; case LONG_IMG: // Read LONG image as ULONG data_type = TULONG; stats.bytesPerPixel = sizeof(int32_t); break; case ULONG_IMG: data_type = TULONG; stats.bytesPerPixel = sizeof(uint32_t); break; case FLOAT_IMG: data_type = TFLOAT; stats.bytesPerPixel = sizeof(float); break; case LONGLONG_IMG: data_type = TLONGLONG; stats.bytesPerPixel = sizeof(int64_t); break; case DOUBLE_IMG: data_type = TDOUBLE; stats.bytesPerPixel = sizeof(double); break; default: errMessage = QString("Bit depth %1 is not supported.").arg(stats.bitpix); return false; break; } if (stats.ndim < 3) { naxes[2] = 1; } if (naxes[0] == 0 || naxes[1] == 0) { errMessage = QString("Image has invalid dimensions %1x%2").arg(naxes[0], naxes[1]); buffer.seek(oldPos); return false; } stats.width = naxes[0]; stats.height = naxes[1]; stats.samples_per_channel = stats.width * stats.height; clearImageBuffers(); channels = naxes[2]; if (channels != 1 && channels != 3) { // code in both calculateMinMax and convertToQImage assume that images have either // 1 channel or 3. File in bug 482615 has two, so bail out better than crashing errMessage = QString("Images with %1 channels are currently not supported.").arg(channels); buffer.seek(oldPos); return false; } imageBuffer = new uint8_t[stats.samples_per_channel * channels * stats.bytesPerPixel]; long nelements = stats.samples_per_channel * channels; if (fits_read_img(fptr, data_type, 1, nelements, nullptr, imageBuffer, &anynull, &status)) { char errmsg[512]; fits_get_errstatus(status, errmsg); errMessage = QString("Error reading image: %1").arg(errmsg); fits_report_error(stderr, status); buffer.seek(oldPos); return false; } calculateStats(); if (checkDebayer()) { bayerBuffer = imageBuffer; debayer(); } return true; } void FITSData::clearImageBuffers() { delete[] imageBuffer; imageBuffer = nullptr; bayerBuffer = nullptr; } void FITSData::calculateStats(bool refresh) { // Calculate min max calculateMinMax(refresh); // Get standard deviation and mean in one run switch (data_type) { case TBYTE: runningAverageStdDev<uint8_t>(); break; case TSHORT: runningAverageStdDev<int16_t>(); break; case TUSHORT: runningAverageStdDev<uint16_t>(); break; case TLONG: runningAverageStdDev<int32_t>(); break; case TULONG: runningAverageStdDev<uint32_t>(); break; case TFLOAT: runningAverageStdDev<float>(); break; case TLONGLONG: runningAverageStdDev<int64_t>(); break; case TDOUBLE: runningAverageStdDev<double>(); break; default: return; } stats.SNR = stats.mean[0] / stats.stddev[0]; } int FITSData::calculateMinMax(bool refresh) { int status, nfound = 0; status = 0; if (fptr && refresh == false) { if (fits_read_key_dbl(fptr, "DATAMIN", &(stats.min[0]), nullptr, &status) == 0) { nfound++; } if (fits_read_key_dbl(fptr, "DATAMAX", &(stats.max[0]), nullptr, &status) == 0) { nfound++; } // If we found both keywords, no need to calculate them, unless they are both zeros if (nfound == 2 && !(stats.min[0] == 0 && stats.max[0] == 0)) { return 0; } } stats.min[0] = 1.0E30; stats.max[0] = -1.0E30; stats.min[1] = 1.0E30; stats.max[1] = -1.0E30; stats.min[2] = 1.0E30; stats.max[2] = -1.0E30; switch (data_type) { case TBYTE: calculateMinMax<uint8_t>(); break; case TSHORT: calculateMinMax<int16_t>(); break; case TUSHORT: calculateMinMax<uint16_t>(); break; case TLONG: calculateMinMax<int32_t>(); break; case TULONG: calculateMinMax<uint32_t>(); break; case TFLOAT: calculateMinMax<float>(); break; case TLONGLONG: calculateMinMax<int64_t>(); break; case TDOUBLE: calculateMinMax<double>(); break; default: break; } // qCDebug(GWENVIEW_LIB_LOG) << "DATAMIN: " << stats.min << " - DATAMAX: " << stats.max; return 0; } template<typename T> void FITSData::calculateMinMax() { T *buffer = reinterpret_cast<T *>(imageBuffer); if (channels == 1) { for (unsigned int i = 0; i < stats.samples_per_channel; i++) { if (buffer[i] < stats.min[0]) { stats.min[0] = buffer[i]; } else if (buffer[i] > stats.max[0]) { stats.max[0] = buffer[i]; } } } else { int g_offset = stats.samples_per_channel; int b_offset = stats.samples_per_channel * 2; for (unsigned int i = 0; i < stats.samples_per_channel; i++) { if (buffer[i] < stats.min[0]) { stats.min[0] = buffer[i]; } else if (buffer[i] > stats.max[0]) { stats.max[0] = buffer[i]; } if (buffer[i + g_offset] < stats.min[1]) { stats.min[1] = buffer[i + g_offset]; } else if (buffer[i + g_offset] > stats.max[1]) { stats.max[1] = buffer[i + g_offset]; } if (buffer[i + b_offset] < stats.min[2]) { stats.min[2] = buffer[i + b_offset]; } else if (buffer[i + b_offset] > stats.max[2]) { stats.max[2] = buffer[i + b_offset]; } } } } template<typename T> void FITSData::runningAverageStdDev() { T *buffer = reinterpret_cast<T *>(imageBuffer); int m_n = 2; double m_oldM = 0, m_newM = 0, m_oldS = 0, m_newS = 0; m_oldM = m_newM = buffer[0]; for (unsigned int i = 1; i < stats.samples_per_channel; i++) { m_newM = m_oldM + (buffer[i] - m_oldM) / m_n; m_newS = m_oldS + (buffer[i] - m_oldM) * (buffer[i] - m_newM); m_oldM = m_newM; m_oldS = m_newS; m_n++; } double variance = (m_n == 2 ? 0 : m_newS / (m_n - 2)); stats.mean[0] = m_newM; stats.stddev[0] = sqrt(variance); } int FITSData::getFITSRecord(QString &recordList, int &nkeys) { char *header = nullptr; int status = 0; if (fits_hdr2str(fptr, 0, nullptr, 0, &header, &nkeys, &status)) { fits_report_error(stderr, status); free(header); return -1; } recordList = QString(header); free(header); return 0; } uint8_t *FITSData::getImageBuffer() { return imageBuffer; } bool FITSData::checkDebayer() { int status = 0; char bayerPattern[64]; // Let's search for BAYERPAT keyword, if it's not found we return as there is no bayer pattern in this image if (fits_read_keyword(fptr, "BAYERPAT", bayerPattern, nullptr, &status)) { return false; } if (stats.bitpix != 16 && stats.bitpix != 8) { return false; } QString pattern(bayerPattern); pattern = pattern.remove('\'').trimmed(); if (pattern == "RGGB") { debayerParams.filter = DC1394_COLOR_FILTER_RGGB; } else if (pattern == "GBRG") { debayerParams.filter = DC1394_COLOR_FILTER_GBRG; } else if (pattern == "GRBG") { debayerParams.filter = DC1394_COLOR_FILTER_GRBG; } else if (pattern == "BGGR") { debayerParams.filter = DC1394_COLOR_FILTER_BGGR; // We return unless we find a valid pattern } else { return false; } fits_read_key(fptr, TINT, "XBAYROFF", &debayerParams.offsetX, nullptr, &status); fits_read_key(fptr, TINT, "YBAYROFF", &debayerParams.offsetY, nullptr, &status); return true; } bool FITSData::debayer() { if (!bayerBuffer) { int anynull = 0, status = 0; bayerBuffer = imageBuffer; if (fits_read_img(fptr, data_type, 1, stats.samples_per_channel, nullptr, bayerBuffer, &anynull, &status)) { char errmsg[512]; fits_get_errstatus(status, errmsg); return false; } } switch (data_type) { case TBYTE: return debayer_8bit(); case TUSHORT: return debayer_16bit(); default: return false; } return false; } bool FITSData::debayer_8bit() { dc1394error_t error_code; int rgb_size = stats.samples_per_channel * 3 * stats.bytesPerPixel; uint8_t *destinationBuffer = new uint8_t[rgb_size]; int ds1394_height = stats.height; uint8_t *dc1394_source = bayerBuffer; if (debayerParams.offsetY == 1) { dc1394_source += stats.width; ds1394_height--; } if (debayerParams.offsetX == 1) { dc1394_source++; } error_code = dc1394_bayer_decoding_8bit(dc1394_source, destinationBuffer, stats.width, ds1394_height, debayerParams.filter, debayerParams.method); if (error_code != DC1394_SUCCESS) { channels = 1; delete[] destinationBuffer; return false; } if (channels == 1) { delete[] imageBuffer; imageBuffer = new uint8_t[rgb_size]; } // Data in R1G1B1, we need to copy them into 3 layers for FITS uint8_t *rBuff = imageBuffer; uint8_t *gBuff = imageBuffer + (stats.width * stats.height); uint8_t *bBuff = imageBuffer + (stats.width * stats.height * 2); int imax = stats.samples_per_channel * 3 - 3; for (int i = 0; i <= imax; i += 3) { *rBuff++ = destinationBuffer[i]; *gBuff++ = destinationBuffer[i + 1]; *bBuff++ = destinationBuffer[i + 2]; } channels = 3; delete[] destinationBuffer; bayerBuffer = nullptr; return true; } bool FITSData::debayer_16bit() { dc1394error_t error_code; int rgb_size = stats.samples_per_channel * 3 * stats.bytesPerPixel; uint8_t *destinationBuffer = new uint8_t[rgb_size]; uint16_t *buffer = reinterpret_cast<uint16_t *>(bayerBuffer); uint16_t *dstBuffer = reinterpret_cast<uint16_t *>(destinationBuffer); int ds1394_height = stats.height; uint16_t *dc1394_source = buffer; if (debayerParams.offsetY == 1) { dc1394_source += stats.width; ds1394_height--; } if (debayerParams.offsetX == 1) { dc1394_source++; } error_code = dc1394_bayer_decoding_16bit(dc1394_source, dstBuffer, stats.width, ds1394_height, debayerParams.filter, debayerParams.method, 16); if (error_code != DC1394_SUCCESS) { channels = 1; delete[] destinationBuffer; return false; } if (channels == 1) { delete[] imageBuffer; imageBuffer = new uint8_t[rgb_size]; if (!imageBuffer) { delete[] destinationBuffer; return false; } } buffer = reinterpret_cast<uint16_t *>(imageBuffer); // Data in R1G1B1, we need to copy them into 3 layers for FITS uint16_t *rBuff = buffer; uint16_t *gBuff = buffer + (stats.width * stats.height); uint16_t *bBuff = buffer + (stats.width * stats.height * 2); int imax = stats.samples_per_channel * 3 - 3; for (int i = 0; i <= imax; i += 3) { *rBuff++ = dstBuffer[i]; *gBuff++ = dstBuffer[i + 1]; *bBuff++ = dstBuffer[i + 2]; } channels = 3; delete[] destinationBuffer; bayerBuffer = nullptr; return true; } QString FITSData::getLastError() const { return lastError; } template<typename T> void FITSData::convertToQImage(double dataMin, double dataMax, double scale, double zero, QImage &image) { T *buffer = (T *)getImageBuffer(); const T limit = std::numeric_limits<T>::max(); T bMin = dataMin < 0 ? 0 : dataMin; T bMax = dataMax > limit ? limit : dataMax; uint16_t w = getWidth(); uint16_t h = getHeight(); uint32_t size = getSize(); double val; if (getNumOfChannels() == 1) { /* Fill in pixel values using indexed map, linear scale */ for (int j = 0; j < h; j++) { unsigned char *scanLine = image.scanLine(j); for (int i = 0; i < w; i++) { val = qBound(bMin, buffer[j * w + i], bMax); val = val * scale + zero; scanLine[i] = qBound<unsigned char>(0, (unsigned char)val, 255); } } } else { double rval = 0, gval = 0, bval = 0; QRgb value; /* Fill in pixel values using indexed map, linear scale */ for (int j = 0; j < h; j++) { QRgb *scanLine = reinterpret_cast<QRgb *>((image.scanLine(j))); for (int i = 0; i < w; i++) { rval = qBound(bMin, buffer[j * w + i], bMax); gval = qBound(bMin, buffer[j * w + i + size], bMax); bval = qBound(bMin, buffer[j * w + i + size * 2], bMax); value = qRgb(rval * scale + zero, gval * scale + zero, bval * scale + zero); scanLine[i] = value; } } } } QImage FITSData::FITSToImage(QIODevice &buffer) { QImage fitsImage; double min, max; FITSData data; bool rc = data.loadFITS(buffer); if (rc == false) { return fitsImage; } data.getMinMax(&min, &max); if (min == max) { fitsImage.fill(Qt::white); return fitsImage; } if (data.getNumOfChannels() == 1) { fitsImage = QImage(data.getWidth(), data.getHeight(), QImage::Format_Indexed8); fitsImage.setColorCount(256); for (int i = 0; i < 256; i++) { fitsImage.setColor(i, qRgb(i, i, i)); } } else { fitsImage = QImage(data.getWidth(), data.getHeight(), QImage::Format_RGB32); } double dataMin = data.stats.mean[0] - data.stats.stddev[0]; double dataMax = data.stats.mean[0] + data.stats.stddev[0] * 3; double bscale = 255. / (dataMax - dataMin); double bzero = (-dataMin) * (255. / (dataMax - dataMin)); // Long way to do this since we do not want to use templated functions here switch (data.getDataType()) { case TBYTE: data.convertToQImage<uint8_t>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TSHORT: data.convertToQImage<int16_t>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TUSHORT: data.convertToQImage<uint16_t>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TLONG: data.convertToQImage<int32_t>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TULONG: data.convertToQImage<uint32_t>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TFLOAT: data.convertToQImage<float>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TLONGLONG: data.convertToQImage<int64_t>(dataMin, dataMax, bscale, bzero, fitsImage); break; case TDOUBLE: data.convertToQImage<double>(dataMin, dataMax, bscale, bzero, fitsImage); break; default: break; } return fitsImage; }
18,721
C++
.cpp
549
27.154827
150
0.578661
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,864
imageloadbench.cpp
KDE_gwenview/tests/manual/imageloadbench.cpp
#include <QBuffer> #include <QCoreApplication> #include <QDebug> #include <QElapsedTimer> #include <QFile> #include <QImage> #include <QImageReader> const int ITERATIONS = 2; const QSize SCALED_SIZE(1280, 800); static void bench(QIODevice *device, const QString &outputName) { QElapsedTimer chrono; chrono.start(); for (int iteration = 0; iteration < ITERATIONS; ++iteration) { qDebug() << "Iteration:" << iteration; device->open(QIODevice::ReadOnly); QImageReader reader(device); QSize size = reader.size(); size.scale(SCALED_SIZE, Qt::KeepAspectRatio); reader.setScaledSize(size); QImage img = reader.read(); device->close(); if (iteration == ITERATIONS - 1) { qDebug() << "time:" << chrono.elapsed(); img.save(outputName, "png"); } } } int main(int argc, char **argv) { QCoreApplication app(argc, argv); if (argc != 2) { qDebug() << "Usage: imageloadbench <file.jpg>"; return 1; } const QString fileName = QString::fromUtf8(argv[1]); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { qDebug() << QStringLiteral("Could not open '%1'").arg(fileName); return 2; } QByteArray data = file.readAll(); QBuffer buffer(&data); qDebug() << "Using Qt loader"; bench(&buffer, "qt.png"); return 0; }
1,410
C++
.cpp
47
24.553191
72
0.626292
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,865
thumbnailgen.cpp
KDE_gwenview/tests/manual/thumbnailgen.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Local #include <../auto/testutils.h> #include <lib/about.h> #include <lib/thumbnailprovider/thumbnailprovider.h> // KF #include <KAboutData> #include <KLocalizedString> // Qt #include <QCommandLineParser> #include <QDir> #include <QtDebug> using namespace Gwenview; int main(int argc, char **argv) { KLocalizedString::setApplicationDomain("thumbnailgen"); QScopedPointer<KAboutData> aboutData(Gwenview::createAboutData(QStringLiteral("thumbnailgen"), /* component name */ i18n("thumbnailgen") /* display name */ )); QApplication app(argc, argv); QCommandLineParser parser; aboutData->setupCommandLine(&parser); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("image-dir", i18n("Image dir to open")); parser.addPositionalArgument("size", i18n("What size of thumbnails to generate. Can be either 'normal' or 'large'")); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("t") << QStringLiteral("thumbnail-dir"), i18n("Use <dir> instead of ~/.thumbnails to store thumbnails"), "thumbnail-dir")); parser.process(app); aboutData->processCommandLine(&parser); // Read cmdline options const QStringList args = parser.positionalArguments(); if (args.count() != 2) { qFatal("Wrong number of arguments"); return 1; } const QString imageDirName = args.first(); ThumbnailGroup::Enum group = ThumbnailGroup::Normal; if (args.last() == "large") { group = ThumbnailGroup::Large; } else if (args.last() == "normal") { // group is already set to the right value } else { qFatal("Invalid thumbnail size: %s", qPrintable(args.last())); } QString thumbnailBaseDirName = parser.value(QStringLiteral("thumbnail-dir")); // Set up thumbnail base dir if (!thumbnailBaseDirName.isEmpty()) { const QDir dir = QDir(thumbnailBaseDirName); thumbnailBaseDirName = dir.absolutePath(); if (!dir.exists()) { bool ok = QDir::root().mkpath(thumbnailBaseDirName); if (!ok) { qFatal("Could not create %s", qPrintable(thumbnailBaseDirName)); return 1; } } if (!thumbnailBaseDirName.endsWith(QLatin1Char('/'))) { thumbnailBaseDirName += QLatin1Char('/'); } ThumbnailProvider::setThumbnailBaseDir(thumbnailBaseDirName); } // List dir QDir dir(imageDirName); KFileItemList list; const auto entryList = dir.entryList(); for (const QString &name : entryList) { const QUrl url = QUrl::fromLocalFile(dir.absoluteFilePath(name)); KFileItem item(url); list << item; } qWarning() << "Generating thumbnails for" << list.count() << "files"; // Start the job QElapsedTimer chrono; ThumbnailProvider job; job.setThumbnailGroup(group); job.appendItems(list); chrono.start(); QEventLoop loop; QObject::connect(&job, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); qWarning() << "Time to generate thumbnails:" << chrono.restart(); waitForDeferredDeletes(); while (!ThumbnailProvider::isThumbnailWriterEmpty()) { QCoreApplication::processEvents(); } qWarning() << "Time to save pending thumbnails:" << chrono.restart(); return 0; }
4,378
C++
.cpp
105
34.647619
121
0.664864
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,867
importertest.cpp
KDE_gwenview/tests/auto/importertest.cpp
/* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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 "importertest.h" // stdlib #include <sys/stat.h> // Qt #include <QDateTime> #include <QSignalSpy> #include <QTest> // KF // Local #include "../importer/filenameformater.h" #include "../importer/fileutils.h" #include "../importer/importer.h" #include "testutils.h" QTEST_MAIN(ImporterTest) using namespace Gwenview; void ImporterTest::init() { mDocumentList = QList<QUrl>() << urlForTestFile("import/pict0001.jpg") << urlForTestFile("import/pict0002.jpg") << urlForTestFile("import/pict0003.jpg"); mTempDir = std::make_unique<QTemporaryDir>(); } void ImporterTest::testContentsAreIdentical() { QVERIFY(!FileUtils::contentsAreIdentical(mDocumentList[0], mDocumentList[1])); QVERIFY(FileUtils::contentsAreIdentical(mDocumentList[0], mDocumentList[0])); QUrl url1 = mDocumentList[0]; QUrl url2 = urlForTestOutputFile("foo"); // Test on a copy of a file QFile::remove(url2.toLocalFile()); QFile::copy(url1.toLocalFile(), url2.toLocalFile()); QVERIFY(FileUtils::contentsAreIdentical(url1, url2)); // Alter one byte of the copy and test again QFile file(url2.toLocalFile()); QVERIFY(file.open(QIODevice::ReadOnly)); QByteArray data = file.readAll(); file.close(); data[data.size() / 2] = 255 - data[data.size() / 2]; file.open(QIODevice::WriteOnly); file.write(data); file.close(); QVERIFY(!FileUtils::contentsAreIdentical(url1, url2)); } void ImporterTest::testSuccessfulImport() { QUrl destUrl = QUrl::fromLocalFile(mTempDir->path() + "/foo"); Importer importer(nullptr); QSignalSpy maximumChangedSpy(&importer, SIGNAL(maximumChanged(int))); QSignalSpy errorSpy(&importer, SIGNAL(error(QString))); QList<QUrl> list = mDocumentList; QEventLoop loop; connect(&importer, &Importer::importFinished, &loop, &QEventLoop::quit); importer.start(list, destUrl); loop.exec(); QCOMPARE(maximumChangedSpy.count(), 1); QCOMPARE(maximumChangedSpy.takeFirst().at(0).toInt(), list.count() * 100); QCOMPARE(errorSpy.count(), 0); QCOMPARE(importer.importedUrlList().count(), list.count()); QCOMPARE(importer.importedUrlList(), list); QCOMPARE(importer.skippedUrlList().count(), 0); QCOMPARE(importer.renamedCount(), 0); for (const QUrl &src : qAsConst(list)) { QUrl dst = destUrl; dst.setPath(dst.path() + '/' + src.fileName()); QVERIFY(FileUtils::contentsAreIdentical(src, dst)); } } void ImporterTest::testSuccessfulImportRemote() { // First test import from local to remote QUrl remoteUrl = setUpRemoteTestDir(); if (!remoteUrl.isValid()) { QSKIP("Not running this test: failed to setup remote test dir."); } Importer importer(nullptr); QSignalSpy maximumChangedSpy(&importer, SIGNAL(maximumChanged(int))); QSignalSpy errorSpy(&importer, SIGNAL(error(QString))); QList<QUrl> list = mDocumentList; QEventLoop loop; connect(&importer, &Importer::importFinished, &loop, &QEventLoop::quit); importer.start(list, remoteUrl); loop.exec(); QCOMPARE(maximumChangedSpy.count(), 1); QCOMPARE(maximumChangedSpy.takeFirst().at(0).toInt(), list.count() * 100); QCOMPARE(errorSpy.count(), 0); QCOMPARE(importer.importedUrlList().count(), list.count()); QCOMPARE(importer.importedUrlList(), list); QCOMPARE(importer.skippedUrlList().count(), 0); QCOMPARE(importer.renamedCount(), 0); for (const QUrl &src : qAsConst(list)) { QUrl dst = remoteUrl; dst.setPath(dst.path() + '/' + src.fileName()); QVERIFY(FileUtils::contentsAreIdentical(src, dst)); } // Secondly test import from remote back to local QUrl localUrl = QUrl::fromLocalFile(mTempDir->path() + "/foo"); importer.start(list, localUrl); loop.exec(); QCOMPARE(maximumChangedSpy.count(), 1); QCOMPARE(maximumChangedSpy.takeFirst().at(0).toInt(), list.count() * 100); QCOMPARE(errorSpy.count(), 0); QCOMPARE(importer.importedUrlList().count(), list.count()); QCOMPARE(importer.importedUrlList(), list); QCOMPARE(importer.skippedUrlList().count(), 0); QCOMPARE(importer.renamedCount(), 0); for (const QUrl &src : qAsConst(list)) { QUrl dst = localUrl; dst.setPath(dst.path() + '/' + src.fileName()); QVERIFY(FileUtils::contentsAreIdentical(src, dst)); } } void ImporterTest::testSkippedUrlList() { QUrl destUrl = QUrl::fromLocalFile(mTempDir->path() + "/foo"); Importer importer(nullptr); QList<QUrl> list = mDocumentList.mid(0, 1); QEventLoop loop; connect(&importer, &Importer::importFinished, &loop, &QEventLoop::quit); importer.start(list, destUrl); loop.exec(); QCOMPARE(importer.importedUrlList().count(), 1); QCOMPARE(importer.importedUrlList(), list); list = mDocumentList; QList<QUrl> expectedImportedList = mDocumentList.mid(1); QList<QUrl> expectedSkippedList = mDocumentList.mid(0, 1); importer.start(list, destUrl); loop.exec(); QCOMPARE(importer.importedUrlList().count(), 2); QCOMPARE(importer.importedUrlList(), expectedImportedList); QCOMPARE(importer.skippedUrlList(), expectedSkippedList); QCOMPARE(importer.renamedCount(), 0); } void ImporterTest::testRenamedCount() { QUrl destUrl = QUrl::fromLocalFile(mTempDir->path() + "/foo"); Importer importer(nullptr); QList<QUrl> list; list << mDocumentList.first(); QEventLoop loop; connect(&importer, &Importer::importFinished, &loop, &QEventLoop::quit); importer.start(list, destUrl); loop.exec(); QCOMPARE(importer.importedUrlList().count(), 1); QCOMPARE(importer.importedUrlList(), list); // Modify imported document so that next import does not skip it { QUrl url = destUrl; url.setPath(url.path() + '/' + mDocumentList.first().fileName()); QFile file(url.toLocalFile()); QVERIFY(file.open(QIODevice::Append)); file.write("foo"); } list = mDocumentList; importer.start(list, destUrl); loop.exec(); QCOMPARE(importer.importedUrlList().count(), 3); QCOMPARE(importer.importedUrlList(), mDocumentList); QCOMPARE(importer.skippedUrlList().count(), 0); QCOMPARE(importer.renamedCount(), 1); } void ImporterTest::testFileNameFormater() { QFETCH(QString, fileName); QFETCH(QString, dateTime); QFETCH(QString, format); QFETCH(QString, expected); QUrl url = QUrl("file://foo/bar/" + fileName); FileNameFormater fileNameFormater(format); QCOMPARE(fileNameFormater.format(url, QDateTime::fromString(dateTime, Qt::ISODate)), expected); } #define NEW_ROW(fileName, dateTime, format, expected) QTest::newRow(fileName) << fileName << dateTime << format << expected void ImporterTest::testFileNameFormater_data() { QTest::addColumn<QString>("fileName"); QTest::addColumn<QString>("dateTime"); QTest::addColumn<QString>("format"); QTest::addColumn<QString>("expected"); NEW_ROW("PICT0001.JPG", "2009-10-24T22:50:49", "{date}_{time}.{ext}", "2009-10-24_22-50-49.JPG"); NEW_ROW("PICT0001.JPG", "2009-10-24T22:50:49", "{date}_{time}.{ext.lower}", "2009-10-24_22-50-49.jpg"); NEW_ROW("2009.10.24.JPG", "2009-10-24T22:50:49", "{date}_{time}.{ext.lower}", "2009-10-24_22-50-49.jpg"); NEW_ROW("PICT0001.JPG", "2009-10-24T22:50:49", "{name}.{ext}", "PICT0001.JPG"); NEW_ROW("PICT0001.JPG", "2009-10-24T22:50:49", "{name.lower}.{ext.lower}", "pict0001.jpg"); NEW_ROW("iLikeCurlies", "2009-10-24T22:50:49", "{{{name}}", "{iLikeCurlies}"); NEW_ROW("UnknownKeyword", "2009-10-24T22:50:49", "foo{unknown}bar", "foobar"); NEW_ROW("MissingClosingCurly", "2009-10-24T22:50:49", "foo{date", "foo"); NEW_ROW("PICT0001.JPG", "2009-10-24T22:50:49", "{date}/{name}.{ext}", "2009-10-24/PICT0001.JPG"); } void ImporterTest::testAutoRenameFormat() { QStringList dates = QStringList() << "1979-02-23_10-20-00" << "2006-04-01_11-30-15" << "2009-10-01_21-15-27"; QStringList dates2 = QStringList() << "1979-02-23/10-20-00" << "2006-04-01/11-30-15" << "2009-10-01/21-15-27"; QCOMPARE(dates.count(), mDocumentList.count()); QCOMPARE(dates2.count(), mDocumentList.count()); QUrl destUrl = QUrl::fromLocalFile(mTempDir->path() + "/foo"); Importer importer(nullptr); importer.setAutoRenameFormat("{date}_{time}.{ext}"); QList<QUrl> list = mDocumentList; QEventLoop loop; connect(&importer, &Importer::importFinished, &loop, &QEventLoop::quit); importer.start(list, destUrl); loop.exec(); QCOMPARE(importer.importedUrlList().count(), list.count()); QCOMPARE(importer.importedUrlList(), list); for (int pos = 0; pos < dates.count(); ++pos) { QUrl src = list[pos]; QUrl dst = destUrl; dst.setPath(dst.path() + '/' + dates[pos] + ".jpg"); QVERIFY(FileUtils::contentsAreIdentical(src, dst)); } // Test again with slashes in AutoRenameFormat importer.setAutoRenameFormat("{date}/{time}.{ext}"); importer.start(list, destUrl); loop.exec(); QCOMPARE(importer.importedUrlList().count(), list.count()); QCOMPARE(importer.importedUrlList(), list); for (int pos = 0; pos < dates2.count(); ++pos) { QUrl src = list[pos]; QUrl dst = destUrl; dst.setPath(dst.path() + '/' + dates2[pos] + ".jpg"); QVERIFY(FileUtils::contentsAreIdentical(src, dst)); } } void ImporterTest::testReadOnlyDestination() { QUrl destUrl = QUrl::fromLocalFile(mTempDir->path() + "/foo"); chmod(QFile::encodeName(mTempDir->path()), 0555); Importer importer(nullptr); QSignalSpy errorSpy(&importer, SIGNAL(error(QString))); importer.start(mDocumentList, destUrl); QCOMPARE(errorSpy.count(), 1); QVERIFY(importer.importedUrlList().isEmpty()); } #include "moc_importertest.cpp"
10,796
C++
.cpp
250
37.968
157
0.684743
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,869
documenttest.cpp
KDE_gwenview/tests/auto/documenttest.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Qt #include <QConicalGradient> #include <QImage> #include <QPainter> #include <QTest> // KF #include <KIO/StatJob> #include <KJobUiDelegate> #include <kio_version.h> // KDCraw #include <KDCRAW/KDcraw> // Local #include "../lib/abstractimageoperation.h" #include "../lib/document/abstractdocumenteditor.h" #include "../lib/document/documentfactory.h" #include "../lib/document/documentjob.h" #include "../lib/imagemetainfomodel.h" #include "../lib/imageutils.h" #include "../lib/transformimageoperation.h" #include "testutils.h" #include <exiv2/exif.hpp> #include "documenttest.h" QTEST_MAIN(DocumentTest) using namespace Gwenview; static void waitUntilMetaInfoLoaded(Document::Ptr doc) { while (doc->loadingState() < Document::MetaInfoLoaded) { QTest::qWait(100); } } static bool waitUntilJobIsDone(DocumentJob *job) { JobWatcher watcher(job); watcher.wait(); return watcher.error() == KJob::NoError; } void DocumentTest::initTestCase() { qRegisterMetaType<QUrl>("QUrl"); } void DocumentTest::init() { DocumentFactory::instance()->clearCache(); } void DocumentTest::testLoad() { QFETCH(QString, fileName); QFETCH(QByteArray, expectedFormat); QFETCH(int, expectedKindInt); QFETCH(bool, expectedIsAnimated); QFETCH(QImage, expectedImage); QFETCH(int, maxHeight); // number of lines to test. -1 to test all lines auto expectedKind = MimeTypeUtils::Kind(expectedKindInt); QUrl url = urlForTestFile(fileName); // testing RAW loading. For raw, QImage directly won't work -> load it using KDCRaw QByteArray mFormatHint = url.fileName().section('.', -1).toLocal8Bit().toLower(); if (KDcrawIface::KDcraw::rawFilesList().contains(QString(mFormatHint))) { if (!KDcrawIface::KDcraw::loadEmbeddedPreview(expectedImage, url.toLocalFile())) { QSKIP( "Not running this test: failed to get expectedImage. Try running ./fetch_testing_raw.sh\ in the tests/data directory and then rerun the tests."); } } if (expectedKind != MimeTypeUtils::KIND_SVG_IMAGE) { if (expectedImage.isNull()) { QSKIP("Not running this test: QImage failed to load the test image"); } } Document::Ptr doc = DocumentFactory::instance()->load(url); QSignalSpy spy(doc.data(), SIGNAL(isAnimatedUpdated())); doc->waitUntilLoaded(); QCOMPARE(doc->loadingState(), Document::Loaded); QCOMPARE(doc->kind(), expectedKind); QCOMPARE(doc->isAnimated(), expectedIsAnimated); QCOMPARE(spy.count(), doc->isAnimated() ? 1 : 0); if (doc->kind() == MimeTypeUtils::KIND_RASTER_IMAGE) { QImage image = doc->image(); if (maxHeight > -1) { QRect poiRect(0, 0, image.width(), maxHeight); image = image.copy(poiRect); expectedImage = expectedImage.copy(poiRect); } QCOMPARE(image, expectedImage); QCOMPARE(QString(doc->format()), QString(expectedFormat)); } } static void testLoad_newRow(const char *fileName, const QByteArray &format, MimeTypeUtils::Kind kind = MimeTypeUtils::KIND_RASTER_IMAGE, bool isAnimated = false, int maxHeight = -1) { QTest::newRow(fileName) << fileName << QByteArray(format) << int(kind) << isAnimated << QImage(pathForTestFile(fileName), format) << maxHeight; } void DocumentTest::testLoad_data() { QTest::addColumn<QString>("fileName"); QTest::addColumn<QByteArray>("expectedFormat"); QTest::addColumn<int>("expectedKindInt"); QTest::addColumn<bool>("expectedIsAnimated"); QTest::addColumn<QImage>("expectedImage"); QTest::addColumn<int>("maxHeight"); testLoad_newRow("test.png", "png"); testLoad_newRow("160216_no_size_before_decoding.eps", "eps"); testLoad_newRow("160382_corrupted.jpeg", "jpeg", MimeTypeUtils::KIND_RASTER_IMAGE, false, 55); testLoad_newRow("1x10k.png", "png"); testLoad_newRow("1x10k.jpg", "jpeg"); testLoad_newRow("test.xcf", "xcf"); testLoad_newRow("188191_does_not_load.tga", "tga"); testLoad_newRow("289819_does_not_load.png", "png"); testLoad_newRow("png-with-jpeg-extension.jpg", "png"); testLoad_newRow("jpg-with-gif-extension.gif", "jpeg"); // RAW preview testLoad_newRow("CANON-EOS350D-02.CR2", "cr2", MimeTypeUtils::KIND_RASTER_IMAGE, false); testLoad_newRow("dsc_0093.nef", "nef", MimeTypeUtils::KIND_RASTER_IMAGE, false); // SVG testLoad_newRow("test.svg", "", MimeTypeUtils::KIND_SVG_IMAGE); // FIXME: Test svgz // Animated testLoad_newRow("4frames.gif", "gif", MimeTypeUtils::KIND_RASTER_IMAGE, true); testLoad_newRow("1frame.gif", "gif", MimeTypeUtils::KIND_RASTER_IMAGE, false); testLoad_newRow("185523_1frame_with_graphic_control_extension.gif", "gif", MimeTypeUtils::KIND_RASTER_IMAGE, false); } void DocumentTest::testLoadTwoPasses() { QUrl url = urlForTestFile("test.png"); QImage image; bool ok = image.load(url.toLocalFile()); QVERIFY2(ok, "Could not load 'test.png'"); Document::Ptr doc = DocumentFactory::instance()->load(url); waitUntilMetaInfoLoaded(doc); QVERIFY2(doc->image().isNull(), "Image shouldn't have been loaded at this time"); QCOMPARE(doc->format().data(), "png"); doc->waitUntilLoaded(); QCOMPARE(image, doc->image()); } void DocumentTest::testLoadEmpty() { QUrl url = urlForTestFile("empty.png"); Document::Ptr doc = DocumentFactory::instance()->load(url); while (doc->loadingState() <= Document::KindDetermined) { QTest::qWait(100); } QCOMPARE(doc->loadingState(), Document::LoadingFailed); } #define NEW_ROW(fileName) QTest::newRow(fileName) << fileName void DocumentTest::testLoadDownSampled_data() { QTest::addColumn<QString>("fileName"); NEW_ROW("orient6.jpg"); NEW_ROW("1x10k.jpg"); } #undef NEW_ROW void DocumentTest::testLoadDownSampled() { // Note: for now we only support down sampling on jpeg, do not use test.png // here QFETCH(QString, fileName); QUrl url = urlForTestFile(fileName); QImage image; bool ok = image.load(url.toLocalFile()); QVERIFY2(ok, "Could not load test image"); Document::Ptr doc = DocumentFactory::instance()->load(url); QSignalSpy downSampledImageReadySpy(doc.data(), SIGNAL(downSampledImageReady())); QSignalSpy loadingFailedSpy(doc.data(), SIGNAL(loadingFailed(QUrl))); QSignalSpy loadedSpy(doc.data(), SIGNAL(loaded(QUrl))); bool ready = doc->prepareDownSampledImageForZoom(0.2); QVERIFY2(!ready, "There should not be a down sampled image at this point"); while (downSampledImageReadySpy.isEmpty() && loadingFailedSpy.isEmpty() && loadedSpy.isEmpty()) { QTest::qWait(100); } QImage downSampledImage = doc->downSampledImageForZoom(0.2); QVERIFY2(!downSampledImage.isNull(), "Down sampled image should not be null"); QSize expectedSize = doc->size() / 2; if (expectedSize.isEmpty()) { expectedSize = image.size(); } QCOMPARE(downSampledImage.size(), expectedSize); } /** * Down sampling is not supported on png. We should get a complete image * instead. */ void DocumentTest::testLoadDownSampledPng() { QUrl url = urlForTestFile("test.png"); QImage image; bool ok = image.load(url.toLocalFile()); QVERIFY2(ok, "Could not load test image"); Document::Ptr doc = DocumentFactory::instance()->load(url); LoadingStateSpy stateSpy(doc); connect(doc.data(), &Document::loaded, &stateSpy, &LoadingStateSpy::readState); bool ready = doc->prepareDownSampledImageForZoom(0.2); QVERIFY2(!ready, "There should not be a down sampled image at this point"); doc->waitUntilLoaded(); QCOMPARE(stateSpy.mCallCount, 1); QCOMPARE(stateSpy.mState, Document::Loaded); } void DocumentTest::testLoadRemote() { QUrl url = setUpRemoteTestDir("test.png"); if (!url.isValid()) { QSKIP("Not running this test: failed to setup remote test dir."); } url = url.adjusted(QUrl::StripTrailingSlash); url.setPath(url.path() + '/' + "test.png"); QVERIFY2(KIO::stat(url, KIO::StatJob::SourceSide, KIO::StatNoDetails)->exec(), "test url not found"); Document::Ptr doc = DocumentFactory::instance()->load(url); doc->waitUntilLoaded(); QImage image = doc->image(); QCOMPARE(image.width(), 150); QCOMPARE(image.height(), 100); } void DocumentTest::testLoadAnimated() { QUrl srcUrl = urlForTestFile("40frames.gif"); Document::Ptr doc = DocumentFactory::instance()->load(srcUrl); QSignalSpy spy(doc.data(), SIGNAL(imageRectUpdated(QRect))); doc->waitUntilLoaded(); QVERIFY(doc->isAnimated()); // Test we receive only one imageRectUpdated() until animation is started // (the imageRectUpdated() is triggered by the loading of the first image) QTest::qWait(1000); QCOMPARE(spy.count(), 1); // Test we now receive some imageRectUpdated() doc->startAnimation(); QTest::qWait(1000); int count = spy.count(); doc->stopAnimation(); QVERIFY2(count > 0, "No imageRectUpdated() signal received"); // Test we do not receive imageRectUpdated() anymore QTest::qWait(1000); QCOMPARE(count, spy.count()); // Start again, we should receive imageRectUpdated() again doc->startAnimation(); QTest::qWait(1000); QVERIFY2(spy.count() > count, "No imageRectUpdated() signal received after restarting"); } void DocumentTest::testPrepareDownSampledAfterFailure() { QUrl url = urlForTestFile("empty.png"); Document::Ptr doc = DocumentFactory::instance()->load(url); doc->waitUntilLoaded(); QCOMPARE(doc->loadingState(), Document::LoadingFailed); bool ready = doc->prepareDownSampledImageForZoom(0.25); QVERIFY2(!ready, "Down sampled image should not be ready"); } void DocumentTest::testSaveRemote() { QUrl dstUrl = setUpRemoteTestDir(); if (!dstUrl.isValid()) { QSKIP("Not running this test: failed to setup remote test dir."); } QUrl srcUrl = urlForTestFile("test.png"); Document::Ptr doc = DocumentFactory::instance()->load(srcUrl); doc->waitUntilLoaded(); dstUrl = dstUrl.adjusted(QUrl::StripTrailingSlash); dstUrl.setPath(dstUrl.path() + '/' + "testSaveRemote.png"); QVERIFY(waitUntilJobIsDone(doc->save(dstUrl, "png"))); } /** * Check that deleting a document while it is loading does not crash */ void DocumentTest::testDeleteWhileLoading() { { QUrl url = urlForTestFile("test.png"); QImage image; bool ok = image.load(url.toLocalFile()); QVERIFY2(ok, "Could not load 'test.png'"); Document::Ptr doc = DocumentFactory::instance()->load(url); } DocumentFactory::instance()->clearCache(); // Wait two seconds. If the test fails we will get a segfault while waiting QTest::qWait(2000); } void DocumentTest::testLoadRotated() { QUrl url = urlForTestFile("orient6.jpg"); QImage image; bool ok = image.load(url.toLocalFile()); QVERIFY2(ok, "Could not load 'orient6.jpg'"); QTransform matrix = ImageUtils::transformMatrix(ROT_90); image = image.transformed(matrix); Document::Ptr doc = DocumentFactory::instance()->load(url); doc->waitUntilLoaded(); QCOMPARE(image, doc->image()); // RAW preview on rotated image url = urlForTestFile("dsd_1838.nef"); if (!KDcrawIface::KDcraw::loadEmbeddedPreview(image, url.toLocalFile())) { QSKIP( "Not running this test: failed to get image. Try running ./fetch_testing_raw.sh\ in the tests/data directory and then rerun the tests."); } matrix = ImageUtils::transformMatrix(ROT_270); image = image.transformed(matrix); doc = DocumentFactory::instance()->load(url); doc->waitUntilLoaded(); QCOMPARE(image, doc->image()); } /** * Checks that asking the DocumentFactory the same document twice in a row does * not load it twice */ void DocumentTest::testMultipleLoads() { QUrl url = urlForTestFile("orient6.jpg"); Document::Ptr doc1 = DocumentFactory::instance()->load(url); Document::Ptr doc2 = DocumentFactory::instance()->load(url); QCOMPARE(doc1.data(), doc2.data()); } void DocumentTest::testSaveAs() { QUrl url = urlForTestFile("orient6.jpg"); DocumentFactory *factory = DocumentFactory::instance(); Document::Ptr doc = factory->load(url); QSignalSpy savedSpy(doc.data(), SIGNAL(saved(QUrl, QUrl))); QSignalSpy modifiedDocumentListChangedSpy(factory, SIGNAL(modifiedDocumentListChanged())); QSignalSpy documentChangedSpy(factory, SIGNAL(documentChanged(QUrl))); doc->startLoadingFullImage(); QUrl destUrl = urlForTestOutputFile("result.png"); QVERIFY(waitUntilJobIsDone(doc->save(destUrl, "png"))); QCOMPARE(doc->format().data(), "png"); QCOMPARE(doc->url(), destUrl); QCOMPARE(doc->metaInfo()->getValueForKey("General.Name"), destUrl.fileName()); QVERIFY2(doc->loadingState() == Document::Loaded, "Document is supposed to finish loading before saving"); QTest::qWait(100); // saved() is emitted asynchronously QCOMPARE(savedSpy.count(), 1); QVariantList args = savedSpy.takeFirst(); QCOMPARE(args.at(0).toUrl(), url); QCOMPARE(args.at(1).toUrl(), destUrl); QImage image("result.png", "png"); QCOMPARE(doc->image(), image); QVERIFY(!DocumentFactory::instance()->hasUrl(url)); QVERIFY(DocumentFactory::instance()->hasUrl(destUrl)); QCOMPARE(modifiedDocumentListChangedSpy.count(), 0); // No changes were made QCOMPARE(documentChangedSpy.count(), 1); args = documentChangedSpy.takeFirst(); QCOMPARE(args.at(0).toUrl(), destUrl); } void DocumentTest::testLosslessSave() { QUrl url1 = urlForTestFile("orient6.jpg"); Document::Ptr doc = DocumentFactory::instance()->load(url1); doc->startLoadingFullImage(); QUrl url2 = urlForTestOutputFile("orient1.jpg"); QVERIFY(waitUntilJobIsDone(doc->save(url2, "jpeg"))); QImage image1; QVERIFY(image1.load(url1.toLocalFile())); QImage image2; QVERIFY(image2.load(url2.toLocalFile())); QCOMPARE(image1, image2); } void DocumentTest::testLosslessRotate() { // Generate test image QImage image1(200, 96, QImage::Format_RGB32); { QPainter painter(&image1); QConicalGradient gradient(QPointF(100, 48), 100); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, Qt::blue); painter.fillRect(image1.rect(), gradient); } QUrl url1 = urlForTestOutputFile("lossless1.jpg"); QVERIFY(image1.save(url1.toLocalFile(), "jpeg")); // Load it as a Gwenview document Document::Ptr doc = DocumentFactory::instance()->load(url1); doc->waitUntilLoaded(); // Rotate one time QVERIFY(doc->editor()); doc->editor()->applyTransformation(ROT_90); // Save it QUrl url2 = urlForTestOutputFile("lossless2.jpg"); waitUntilJobIsDone(doc->save(url2, "jpeg")); // Load the saved image doc = DocumentFactory::instance()->load(url2); doc->waitUntilLoaded(); // Rotate the other way QVERIFY(doc->editor()); doc->editor()->applyTransformation(ROT_270); waitUntilJobIsDone(doc->save(url2, "jpeg")); // Compare the saved images QVERIFY(image1.load(url1.toLocalFile())); QImage image2; QVERIFY(image2.load(url2.toLocalFile())); QCOMPARE(image1, image2); } void DocumentTest::testModifyAndSaveAs() { QVariantList args; class TestOperation : public AbstractImageOperation { public: void redo() override { QImage image(10, 10, QImage::Format_ARGB32); image.fill(QColor(Qt::white).rgb()); document()->editor()->setImage(image); finish(true); } }; QUrl url = urlForTestFile("orient6.jpg"); DocumentFactory *factory = DocumentFactory::instance(); Document::Ptr doc = factory->load(url); QSignalSpy savedSpy(doc.data(), SIGNAL(saved(QUrl, QUrl))); QSignalSpy modifiedDocumentListChangedSpy(factory, SIGNAL(modifiedDocumentListChanged())); QSignalSpy documentChangedSpy(factory, SIGNAL(documentChanged(QUrl))); doc->waitUntilLoaded(); QVERIFY(!doc->isModified()); QCOMPARE(modifiedDocumentListChangedSpy.count(), 0); // Modify image QVERIFY(doc->editor()); auto op = new TestOperation; op->applyToDocument(doc); QTest::qWait(100); QVERIFY(doc->isModified()); QCOMPARE(modifiedDocumentListChangedSpy.count(), 1); modifiedDocumentListChangedSpy.clear(); QList<QUrl> lst = factory->modifiedDocumentList(); QCOMPARE(lst.count(), 1); QCOMPARE(lst.first(), url); QCOMPARE(documentChangedSpy.count(), 1); args = documentChangedSpy.takeFirst(); QCOMPARE(args.at(0).toUrl(), url); // Save it under a new name QUrl destUrl = urlForTestOutputFile("modify.png"); QVERIFY(waitUntilJobIsDone(doc->save(destUrl, "png"))); // Wait a bit because save() will clear the undo stack when back to the // event loop QTest::qWait(100); QVERIFY(!doc->isModified()); QVERIFY(!factory->hasUrl(url)); QVERIFY(factory->hasUrl(destUrl)); QCOMPARE(modifiedDocumentListChangedSpy.count(), 1); QVERIFY(DocumentFactory::instance()->modifiedDocumentList().isEmpty()); QCOMPARE(documentChangedSpy.count(), 2); QList<QUrl> modifiedUrls = QList<QUrl>() << url << destUrl; QVERIFY(modifiedUrls.contains(url)); QVERIFY(modifiedUrls.contains(destUrl)); } void DocumentTest::testMetaInfoJpeg() { QUrl url = urlForTestFile("orient6.jpg"); Document::Ptr doc = DocumentFactory::instance()->load(url); // We cleared the cache, so the document should not be loaded Q_ASSERT(doc->loadingState() <= Document::KindDetermined); // Wait until we receive the metaInfoUpdated() signal QSignalSpy metaInfoUpdatedSpy(doc.data(), SIGNAL(metaInfoUpdated())); while (metaInfoUpdatedSpy.isEmpty()) { QTest::qWait(100); } // Extract an exif key QString value = doc->metaInfo()->getValueForKey("Exif.Image.Make"); QCOMPARE(value, QString::fromUtf8("Canon")); } void DocumentTest::testMetaInfoBmp() { QUrl url = urlForTestOutputFile("metadata.bmp"); const int width = 200; const int height = 100; QImage image(width, height, QImage::Format_ARGB32); image.fill(Qt::black); image.save(url.toLocalFile(), "BMP"); Document::Ptr doc = DocumentFactory::instance()->load(url); QSignalSpy metaInfoUpdatedSpy(doc.data(), SIGNAL(metaInfoUpdated())); waitUntilMetaInfoLoaded(doc); Q_ASSERT(metaInfoUpdatedSpy.count() >= 1); QString value = doc->metaInfo()->getValueForKey("General.ImageSize"); QString expectedValue = QStringLiteral("%1x%2").arg(width).arg(height); QCOMPARE(value, expectedValue); } void DocumentTest::testForgetModifiedDocument() { QSignalSpy spy(DocumentFactory::instance(), SIGNAL(modifiedDocumentListChanged())); DocumentFactory::instance()->forget(QUrl("file://does/not/exist.png")); QCOMPARE(spy.count(), 0); // Generate test image QImage image1(200, 96, QImage::Format_RGB32); { QPainter painter(&image1); QConicalGradient gradient(QPointF(100, 48), 100); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, Qt::blue); painter.fillRect(image1.rect(), gradient); } QUrl url = urlForTestOutputFile("testForgetModifiedDocument.png"); QVERIFY(image1.save(url.toLocalFile(), "png")); // Load it as a Gwenview document Document::Ptr doc = DocumentFactory::instance()->load(url); doc->waitUntilLoaded(); // Modify it auto op = new TransformImageOperation(ROT_90); op->applyToDocument(doc); QTest::qWait(100); QCOMPARE(spy.count(), 1); QList<QUrl> lst = DocumentFactory::instance()->modifiedDocumentList(); QCOMPARE(lst.length(), 1); QCOMPARE(lst.first(), url); // Forget it DocumentFactory::instance()->forget(url); QCOMPARE(spy.count(), 2); lst = DocumentFactory::instance()->modifiedDocumentList(); QVERIFY(lst.isEmpty()); } void DocumentTest::testModifiedAndSavedSignals() { TransformImageOperation *op; QUrl url = urlForTestFile("orient6.jpg"); Document::Ptr doc = DocumentFactory::instance()->load(url); QSignalSpy modifiedSpy(doc.data(), SIGNAL(modified(QUrl))); QSignalSpy savedSpy(doc.data(), SIGNAL(saved(QUrl, QUrl))); doc->waitUntilLoaded(); QCOMPARE(modifiedSpy.count(), 0); QCOMPARE(savedSpy.count(), 0); op = new TransformImageOperation(ROT_90); op->applyToDocument(doc); QTest::qWait(100); QCOMPARE(modifiedSpy.count(), 1); op = new TransformImageOperation(ROT_90); op->applyToDocument(doc); QTest::qWait(100); QCOMPARE(modifiedSpy.count(), 2); doc->undoStack()->undo(); QTest::qWait(100); QCOMPARE(modifiedSpy.count(), 3); doc->undoStack()->undo(); QTest::qWait(100); QCOMPARE(savedSpy.count(), 1); } class TestJob : public DocumentJob { public: TestJob(QString *str, char ch) : mStr(str) , mCh(ch) { } protected: void doStart() override { *mStr += mCh; emitResult(); } private: QString *mStr; char mCh; }; void DocumentTest::testJobQueue() { QUrl url = urlForTestFile("orient6.jpg"); Document::Ptr doc = DocumentFactory::instance()->load(url); QSignalSpy spy(doc.data(), SIGNAL(busyChanged(QUrl, bool))); QString str; doc->enqueueJob(new TestJob(&str, 'a')); doc->enqueueJob(new TestJob(&str, 'b')); doc->enqueueJob(new TestJob(&str, 'c')); QVERIFY(doc->isBusy()); QEventLoop loop; connect(doc.data(), &Document::allTasksDone, &loop, &QEventLoop::quit); loop.exec(); QVERIFY(!doc->isBusy()); QCOMPARE(spy.count(), 2); QVariantList row = spy.takeFirst(); QCOMPARE(row.at(0).toUrl(), url); QVERIFY(row.at(1).toBool()); row = spy.takeFirst(); QCOMPARE(row.at(0).toUrl(), url); QVERIFY(!row.at(1).toBool()); QCOMPARE(str, QStringLiteral("abc")); } class TestCheckDocumentEditorJob : public DocumentJob { public: TestCheckDocumentEditorJob(int *hasEditor) : mHasEditor(hasEditor) { *mHasEditor = -1; } protected: void doStart() override { document()->waitUntilLoaded(); *mHasEditor = checkDocumentEditor() ? 1 : 0; emitResult(); } private: int *mHasEditor; }; class TestUiDelegate : public KJobUiDelegate { public: TestUiDelegate(bool *showErrorMessageCalled) : mShowErrorMessageCalled(showErrorMessageCalled) { setAutoErrorHandlingEnabled(true); *mShowErrorMessageCalled = false; } void showErrorMessage() override { // qDebug(); *mShowErrorMessageCalled = true; } private: bool *mShowErrorMessageCalled; }; /** * Test that an error is reported when a DocumentJob fails because there is no * document editor available */ void DocumentTest::testCheckDocumentEditor() { int hasEditor; bool showErrorMessageCalled; QEventLoop loop; Document::Ptr doc; TestCheckDocumentEditorJob *job; doc = DocumentFactory::instance()->load(urlForTestFile("orient6.jpg")); job = new TestCheckDocumentEditorJob(&hasEditor); job->setUiDelegate(new TestUiDelegate(&showErrorMessageCalled)); doc->enqueueJob(job); connect(doc.data(), &Document::allTasksDone, &loop, &QEventLoop::quit); loop.exec(); QVERIFY(!showErrorMessageCalled); QCOMPARE(hasEditor, 1); doc = DocumentFactory::instance()->load(urlForTestFile("test.svg")); job = new TestCheckDocumentEditorJob(&hasEditor); job->setUiDelegate(new TestUiDelegate(&showErrorMessageCalled)); doc->enqueueJob(job); connect(doc.data(), &Document::allTasksDone, &loop, &QEventLoop::quit); loop.exec(); QVERIFY(showErrorMessageCalled); QCOMPARE(hasEditor, 0); } /** * An operation should only pushed to the document undo stack if it succeed */ void DocumentTest::testUndoStackPush() { class SuccessOperation : public AbstractImageOperation { protected: void redo() override { QMetaObject::invokeMethod( this, [this]() { finish(true); }, Qt::QueuedConnection); } }; class FailureOperation : public AbstractImageOperation { protected: void redo() override { QMetaObject::invokeMethod( this, [this]() { finish(false); }, Qt::QueuedConnection); } }; AbstractImageOperation *op; Document::Ptr doc = DocumentFactory::instance()->load(urlForTestFile("orient6.jpg")); // A successful operation should be added to the undo stack op = new SuccessOperation; op->applyToDocument(doc); QTest::qWait(100); QVERIFY(!doc->undoStack()->isClean()); // Reset doc->undoStack()->undo(); QVERIFY(doc->undoStack()->isClean()); // A failed operation should not be added to the undo stack op = new FailureOperation; op->applyToDocument(doc); QTest::qWait(100); QVERIFY(doc->undoStack()->isClean()); } void DocumentTest::testUndoRedo() { class SuccessOperation : public AbstractImageOperation { public: int mRedoCount = 0; int mUndoCount = 0; protected: void redo() override { mRedoCount++; finish(true); } void undo() override { mUndoCount++; finish(true); } }; Document::Ptr doc = DocumentFactory::instance()->load(urlForTestFile("orient6.jpg")); QSignalSpy modifiedSpy(doc.data(), &Document::modified); QSignalSpy savedSpy(doc.data(), &Document::saved); auto op = new SuccessOperation; QCOMPARE(op->mRedoCount, 0); QCOMPARE(op->mUndoCount, 0); // Apply (redo) operation op->applyToDocument(doc); QVERIFY(modifiedSpy.wait()); QCOMPARE(op->mRedoCount, 1); QCOMPARE(op->mUndoCount, 0); QCOMPARE(doc->undoStack()->count(), 1); QVERIFY(!doc->undoStack()->isClean()); // Undo operation doc->undoStack()->undo(); QVERIFY(savedSpy.wait()); QCOMPARE(op->mRedoCount, 1); QCOMPARE(op->mUndoCount, 1); QCOMPARE(doc->undoStack()->count(), 1); QVERIFY(doc->undoStack()->isClean()); // Redo operation doc->undoStack()->redo(); QVERIFY(modifiedSpy.wait()); QCOMPARE(op->mRedoCount, 2); QCOMPARE(op->mUndoCount, 1); QCOMPARE(doc->undoStack()->count(), 1); QVERIFY(!doc->undoStack()->isClean()); // Undo operation again doc->undoStack()->undo(); QVERIFY(savedSpy.wait()); QCOMPARE(op->mRedoCount, 2); QCOMPARE(op->mUndoCount, 2); QCOMPARE(doc->undoStack()->count(), 1); QVERIFY(doc->undoStack()->isClean()); } #include "moc_documenttest.cpp"
27,862
C++
.cpp
751
31.976032
147
0.685101
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,870
timeutilstest.cpp
KDE_gwenview/tests/auto/timeutilstest.cpp
/* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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 "timeutilstest.h" // libc #include <utime.h> // Qt #include <QTemporaryFile> #include <QTest> // KF #include <KFileItem> // Local #include "../lib/timeutils.h" #include "testutils.h" QTEST_MAIN(TimeUtilsTest) using namespace Gwenview; static void touchFile(const QString &path) { utime(QFile::encodeName(path).data(), nullptr); } #define NEW_ROW(fileName, dateTime) QTest::newRow(fileName) << fileName << dateTime void TimeUtilsTest::testBasic_data() { QTest::addColumn<QString>("fileName"); QTest::addColumn<QDateTime>("expectedDateTime"); NEW_ROW("date/exif-datetimeoriginal.jpg", QDateTime::fromString("2003-03-10T17:45:21", Qt::ISODate)); NEW_ROW("date/exif-datetime-only.jpg", QDateTime::fromString("2003-03-25T02:02:21", Qt::ISODate)); QUrl url = urlForTestFile("test.png"); KFileItem item(url); NEW_ROW("test.png", item.time(KFileItem::ModificationTime)); } void TimeUtilsTest::testBasic() { QFETCH(QString, fileName); QFETCH(QDateTime, expectedDateTime); QDateTime dateTime; QUrl url = urlForTestFile(fileName); KFileItem item(url); dateTime = TimeUtils::dateTimeForFileItem(item); QCOMPARE(dateTime, expectedDateTime); dateTime = TimeUtils::dateTimeForFileItem(item, TimeUtils::SkipCache); QCOMPARE(dateTime, expectedDateTime); } void TimeUtilsTest::testCache() { QTemporaryFile tempFile; QVERIFY(tempFile.open()); QUrl url = QUrl::fromLocalFile(tempFile.fileName()); KFileItem item1(url); QDateTime dateTime1 = TimeUtils::dateTimeForFileItem(item1); QCOMPARE(dateTime1, item1.time(KFileItem::ModificationTime)); QTest::qWait(1200); touchFile(url.toLocalFile()); KFileItem item2(url); QDateTime dateTime2 = TimeUtils::dateTimeForFileItem(item2); QVERIFY(dateTime1 != dateTime2); QCOMPARE(dateTime2, item2.time(KFileItem::ModificationTime)); } #include "moc_timeutilstest.cpp"
2,698
C++
.cpp
71
34.985915
105
0.763462
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,871
transformimageoperationtest.cpp
KDE_gwenview/tests/auto/transformimageoperationtest.cpp
/* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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. */ // Qt #include <QEventLoop> #include <QImage> #include <QTest> // KF // Local #include "../lib/document/documentfactory.h" #include "../lib/imageutils.h" #include "../lib/transformimageoperation.h" #include "testutils.h" #include "transformimageoperationtest.h" QTEST_MAIN(TransformImageOperationTest) using namespace Gwenview; void TransformImageOperationTest::initTestCase() { qRegisterMetaType<QUrl>("QUrl"); } void TransformImageOperationTest::init() { DocumentFactory::instance()->clearCache(); } void TransformImageOperationTest::testRotate90() { QUrl url = urlForTestFile("test.png"); QImage image; bool ok = image.load(url.toLocalFile()); QVERIFY2(ok, "Could not load 'test.png'"); QTransform matrix = ImageUtils::transformMatrix(ROT_90); image = image.transformed(matrix); Document::Ptr doc = DocumentFactory::instance()->load(url); auto op = new TransformImageOperation(ROT_90); QEventLoop loop; connect(doc.data(), &Document::allTasksDone, &loop, &QEventLoop::quit); op->applyToDocument(doc); loop.exec(); QCOMPARE(image, doc->image()); } #include "moc_transformimageoperationtest.cpp"
1,937
C++
.cpp
53
34.056604
79
0.771582
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,872
placetreemodeltest.cpp
KDE_gwenview/tests/auto/placetreemodeltest.cpp
/* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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 "placetreemodeltest.h" // Qt #include <QDebug> #include <QDir> #include <QFile> #include <QStandardPaths> #include <QTest> // KF // Local #include "../lib/placetreemodel.h" #include "testutils.h" // #define KEEP_TEMP_DIR QTEST_MAIN(PlaceTreeModelTest) using namespace Gwenview; const char *BOOKMARKS_XML = "<?xml version='1.0' encoding='UTF-8'?>" "<!DOCTYPE xbel>" "<xbel xmlns:bookmark='http://www.freedesktop.org/standards/desktop-bookmarks' xmlns:mime='http://www.freedesktop.org/standards/shared-mime-info' " "xmlns:kdepriv='http://www.kde.org/kdepriv' dbusName='kfilePlaces' >" " <bookmark href='%1' >" " <title>url1</title>" " <info>" " <metadata owner='http://freedesktop.org' >" " <bookmark:icon name='user-home' />" " </metadata>" " <metadata owner='http://www.kde.org' >" " <ID>1214343736/0</ID>" " <isSystemItem>true</isSystemItem>" " </metadata>" " </info>" " </bookmark>" " <bookmark href='%2' >" " <title>url2</title>" " <info>" " <metadata owner='http://freedesktop.org' >" " <bookmark:icon name='user-home' />" " </metadata>" " <metadata owner='http://www.kde.org' >" " <ID>1214343736/1</ID>" " <isSystemItem>true</isSystemItem>" " </metadata>" " </info>" " </bookmark>" "</xbel>"; void PlaceTreeModelTest::initTestCase() { Q_ASSERT(mTempDir.isValid()); QDir dir(mTempDir.path()); const bool dir1created = dir.mkdir("url1"); Q_ASSERT(dir1created); Q_UNUSED(dir1created); mUrl1 = QUrl::fromLocalFile(dir.filePath("url1")); const bool dir2created = dir.mkdir("url2"); Q_ASSERT(dir2created); Q_UNUSED(dir2created); mUrl2 = QUrl::fromLocalFile(dir.filePath("url2")); mUrl1Dirs << "aaa" << "zzz" << "bbb"; for (const QString &dirName : qAsConst(mUrl1Dirs)) { dir.mkdir("url1/" + dirName); } #ifdef KEEP_TEMP_DIR mTempDir.setAutoRemove(false); // qDebug() << "mTempDir:" << mTempDir.name(); #endif } void PlaceTreeModelTest::init() { QStandardPaths::setTestModeEnabled(true); TestUtils::purgeUserConfiguration(); const QString confDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); QDir().mkpath(confDir); QFile bookmark(confDir + "/user-places.xbel"); const bool bookmarkOpened = bookmark.open(QIODevice::WriteOnly); Q_ASSERT(bookmarkOpened); Q_UNUSED(bookmarkOpened); QString xml = QString(BOOKMARKS_XML).arg(mUrl1.url(), mUrl2.url()); bookmark.write(xml.toUtf8()); #ifdef KEEP_TEMP_DIR mTempDir.setAutoRemove(false); // qDebug() << "mTempDir:" << mTempDir.name(); #endif } void PlaceTreeModelTest::testListPlaces() { PlaceTreeModel model(nullptr); QCOMPARE(model.rowCount(), 8); QModelIndex index; index = model.index(0, 0); QCOMPARE(model.urlForIndex(index), mUrl1); index = model.index(1, 0); QCOMPARE(model.urlForIndex(index), mUrl2); } void PlaceTreeModelTest::testListUrl1() { PlaceTreeModel model(nullptr); QModelIndex index = model.index(0, 0); QCOMPARE(model.urlForIndex(index), mUrl1); // We should not have fetched content yet QCOMPARE(model.rowCount(index), 0); QVERIFY(model.canFetchMore(index)); while (model.canFetchMore(index)) { model.fetchMore(index); } QTest::qWait(1000); QCOMPARE(model.rowCount(index), mUrl1Dirs.length()); QStringList dirs = mUrl1Dirs; dirs.sort(); for (int row = 0; row < dirs.count(); ++row) { QModelIndex subIndex = model.index(row, 0, index); QVERIFY(subIndex.isValid()); QString dirName = model.data(subIndex).toString(); QCOMPARE(dirName, dirs.value(row)); } } #include "moc_placetreemodeltest.cpp"
4,610
C++
.cpp
132
30.757576
151
0.682718
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,873
cmsprofiletest.cpp
KDE_gwenview/tests/auto/cmsprofiletest.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "cmsprofiletest.h" // Local #include <lib/cms/cmsprofile.h> #include <lib/exiv2imageloader.h> #include <testutils.h> // KF // Qt #include <QTest> QTEST_MAIN(CmsProfileTest) using namespace Gwenview; void CmsProfileTest::testLoadFromImageData() { QFETCH(QString, fileName); QFETCH(QByteArray, format); QByteArray data; { QString path = pathForTestFile(fileName); QFile file(path); QVERIFY(file.open(QIODevice::ReadOnly)); data = file.readAll(); } Cms::Profile::Ptr ptr = Cms::Profile::loadFromImageData(data, format); QVERIFY(ptr); } #define NEW_ROW(fileName, format) QTest::newRow(fileName) << fileName << QByteArray(format) void CmsProfileTest::testLoadFromImageData_data() { QTest::addColumn<QString>("fileName"); QTest::addColumn<QByteArray>("format"); NEW_ROW("cms/colourTestFakeBRG.png", "png"); NEW_ROW("cms/colourTestsRGB.png", "png"); NEW_ROW("cms/Upper_Left.jpg", "jpeg"); NEW_ROW("cms/Upper_Right.jpg", "jpeg"); NEW_ROW("cms/Lower_Left.jpg", "jpeg"); NEW_ROW("cms/Lower_Right.jpg", "jpeg"); } #undef NEW_ROW #if 0 void CmsProfileTest::testLoadFromExiv2Image() { QFETCH(QString, fileName); std::unique_ptr<Exiv2::Image> image; { QByteArray data; QString path = pathForTestFile(fileName); qWarning() << path; QFile file(path); QVERIFY(file.open(QIODevice::ReadOnly)); data = file.readAll(); Exiv2ImageLoader loader; QVERIFY(loader.load(data)); image.reset(loader.popImage().release()); } Cms::Profile::Ptr ptr = Cms::Profile::loadFromExiv2Image(image.get()); QVERIFY(!ptr.isNull()); } #define NEW_ROW(fileName) QTest::newRow(fileName) << fileName void CmsProfileTest::testLoadFromExiv2Image_data() { QTest::addColumn<QString>("fileName"); } #undef NEW_ROW #endif #include "moc_cmsprofiletest.cpp"
2,742
C++
.cpp
81
30.246914
91
0.72483
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,874
historymodeltest.cpp
KDE_gwenview/tests/auto/historymodeltest.cpp
/* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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 "historymodeltest.h" // Qt #include <QDir> #include <QTemporaryDir> #include <QTest> // KF #include <KFilePlacesModel> // Local #include "../lib/historymodel.h" QTEST_MAIN(HistoryModelTest) using namespace Gwenview; void testModel(const HistoryModel &model, const QUrl &u1, const QUrl &u2) { QModelIndex index; QUrl url; QCOMPARE(model.rowCount(), 2); index = model.index(0, 0); QVERIFY(index.isValid()); url = model.data(index, KFilePlacesModel::UrlRole).toUrl(); QCOMPARE(url, u1); index = model.index(1, 0); QVERIFY(index.isValid()); url = model.data(index, KFilePlacesModel::UrlRole).toUrl(); QCOMPARE(url, u2); } void HistoryModelTest::testAddUrl() { QUrl u1 = QUrl::fromLocalFile("/home"); QDateTime d1 = QDateTime::fromString("2008-02-03T12:34:56", Qt::ISODate); QUrl u2 = QUrl::fromLocalFile("/root"); QDateTime d2 = QDateTime::fromString("2009-01-29T23:01:47", Qt::ISODate); QTemporaryDir dir; { HistoryModel model(nullptr, dir.path()); model.addUrl(u1, d1); model.addUrl(u2, d2); testModel(model, u2, u1); } HistoryModel model(nullptr, dir.path()); testModel(model, u2, u1); // Make u1 the most recent QDateTime d3 = QDateTime::fromString("2009-03-24T22:42:15", Qt::ISODate); model.addUrl(u1, d3); testModel(model, u1, u2); } void HistoryModelTest::testGarbageCollect() { QUrl u1 = QUrl::fromLocalFile("/home"); QDateTime d1 = QDateTime::fromString("2008-02-03T12:34:56", Qt::ISODate); QUrl u2 = QUrl::fromLocalFile("/root"); QDateTime d2 = QDateTime::fromString("2009-01-29T23:01:47", Qt::ISODate); QUrl u3 = QUrl::fromLocalFile("/usr"); QDateTime d3 = QDateTime::fromString("2009-03-24T22:42:15", Qt::ISODate); QTemporaryDir dir; { HistoryModel model(nullptr, dir.path(), 2); model.addUrl(u1, d1); model.addUrl(u2, d2); testModel(model, u2, u1); model.addUrl(u3, d3); } // Create a model with a larger history so that if garbage collecting fails // to remove the collected url, the size of the model won't pass // testModel() HistoryModel model(nullptr, dir.path(), 10); testModel(model, u3, u2); } void HistoryModelTest::testRemoveRows() { QUrl u1 = QUrl::fromLocalFile("/home"); QDateTime d1 = QDateTime::fromString("2008-02-03T12:34:56", Qt::ISODate); QUrl u2 = QUrl::fromLocalFile("/root"); QDateTime d2 = QDateTime::fromString("2009-01-29T23:01:47", Qt::ISODate); QTemporaryDir dir; HistoryModel model(nullptr, dir.path(), 2); model.addUrl(u1, d1); model.addUrl(u2, d2); model.removeRows(0, 1); QCOMPARE(model.rowCount(), 1); QDir qDir(dir.path()); QCOMPARE(qDir.entryList(QDir::Files | QDir::NoDotAndDotDot).count(), 1); } #include "moc_historymodeltest.cpp"
3,642
C++
.cpp
98
33.153061
79
0.702925
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,875
sorteddirmodeltest.cpp
KDE_gwenview/tests/auto/sorteddirmodeltest.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2011 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "sorteddirmodeltest.h" // Local #include <lib/semanticinfo/sorteddirmodel.h> // Qt #include <QTemporaryDir> #include <QTest> // KF #include <KDirLister> using namespace Gwenview; QTEST_MAIN(SortedDirModelTest) void SortedDirModelTest::initTestCase() { mSandBoxDir.mkdir("empty_dir"); mSandBoxDir.mkdir("dirs_only"); mSandBoxDir.mkdir("dirs_only/dir1"); mSandBoxDir.mkdir("dirs_only/dir2"); mSandBoxDir.mkdir("dirs_and_docs"); mSandBoxDir.mkdir("dirs_and_docs/dir"); createEmptyFile(mSandBoxDir.absoluteFilePath("dirs_and_docs/file.png")); mSandBoxDir.mkdir("docs_only"); createEmptyFile(mSandBoxDir.absoluteFilePath("docs_only/file.png")); } void SortedDirModelTest::testHasDocuments_data() { QTest::addColumn<QString>("dir"); QTest::addColumn<bool>("hasDocuments"); #define NEW_ROW(dir, hasDocuments) QTest::newRow(QString(dir).toLocal8Bit().data()) << mSandBoxDir.absoluteFilePath(dir) << hasDocuments NEW_ROW("empty_dir", false); NEW_ROW("dirs_only", false); NEW_ROW("dirs_and_docs", true); NEW_ROW("docs_only", true); #undef NEW_ROW } void SortedDirModelTest::testHasDocuments() { QFETCH(QString, dir); QFETCH(bool, hasDocuments); QUrl url = QUrl::fromLocalFile(dir); SortedDirModel model; QEventLoop loop; connect(model.dirLister(), SIGNAL(completed()), &loop, SLOT(quit())); model.dirLister()->openUrl(url); loop.exec(); QCOMPARE(model.hasDocuments(), hasDocuments); } #include "moc_sorteddirmodeltest.cpp"
2,349
C++
.cpp
63
34.507937
136
0.75815
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,876
contextmanagertest.cpp
KDE_gwenview/tests/auto/contextmanagertest.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2013 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "contextmanagertest.h" // Local #include <lib/contextmanager.h> #include <lib/semanticinfo/sorteddirmodel.h> // Qt #include <QEventLoop> #include <QItemSelectionModel> #include <QTest> // KF #include <KDirLister> using namespace Gwenview; using namespace TestUtils; QTEST_MAIN(ContextManagerTest) void ContextManagerTest::testRemove() { // When the current image is removed Gwenview must go to the next image if // there is any, otherwise to the previous image. SandBoxDir sandBox; sandBox.fill(QStringList() << QStringLiteral("a") << QStringLiteral("b") << QStringLiteral("c")); QUrl dirUrl = QUrl::fromLocalFile(sandBox.absolutePath()); SortedDirModel dirModel; { QEventLoop loop; connect(dirModel.dirLister(), SIGNAL(completed()), &loop, SLOT(quit())); dirModel.dirLister()->openUrl(dirUrl); loop.exec(); } QCOMPARE(dirModel.rowCount(), 3); ContextManager manager(&dirModel, nullptr); // Select second row manager.selectionModel()->setCurrentIndex(dirModel.index(1, 0), QItemSelectionModel::Select); // Remove "b", `manager` should select "c" sandBox.remove(QStringLiteral("b")); dirModel.dirLister()->updateDirectory(dirUrl); while (dirModel.rowCount() == 3) { QTest::qWait(100); } QModelIndex currentIndex = manager.selectionModel()->currentIndex(); QCOMPARE(currentIndex.row(), 1); QCOMPARE(currentIndex.data(Qt::DisplayRole).toString(), QStringLiteral("c")); // Remove "c", `manager` should select "a" sandBox.remove(QStringLiteral("c")); dirModel.dirLister()->updateDirectory(dirUrl); while (dirModel.rowCount() == 2) { QTest::qWait(100); } currentIndex = manager.selectionModel()->currentIndex(); QCOMPARE(currentIndex.row(), 0); QCOMPARE(currentIndex.data(Qt::DisplayRole).toString(), QStringLiteral("a")); } #include "moc_contextmanagertest.cpp"
2,762
C++
.cpp
68
36.955882
101
0.738122
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,877
thumbnailprovidertest.cpp
KDE_gwenview/tests/auto/thumbnailprovidertest.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "thumbnailprovidertest.h" // Qt #include <QDebug> #include <QDir> #include <QFile> #include <QImage> #include <QPainter> #include <QTest> // KF #include <KIO/CopyJob> #include <KIO/DeleteJob> // Local #include "../lib/thumbnailprovider/thumbnailprovider.h" #include "gwenviewconfig.h" #include "testutils.h" // libc #include <cerrno> #include <cstring> using namespace Gwenview; QTEST_MAIN(ThumbnailProviderTest) SandBox::SandBox() : mPath(QDir::currentPath() + "/sandbox") { } void SandBox::initDir() { KIO::Job *job; QDir dir(mPath); if (dir.exists()) { QUrl sandBoxUrl("file://" + mPath); job = KIO::del(sandBoxUrl); QVERIFY2(job->exec(), "Couldn't delete sandbox"); } dir.mkpath("."); } void SandBox::fill() { initDir(); createTestImage("red.png", 300, 200, Qt::red); createTestImage("blue.png", 200, 300, Qt::blue); createTestImage("small.png", 50, 50, Qt::green); copyTestImage("orient6.jpg", 128, 256); copyTestImage("orient6-small.jpg", 32, 64); } void SandBox::copyTestImage(const QString &testFileName, int width, int height) { QUrl testPath = urlForTestFile(testFileName); QUrl testDest = QUrl("file://" + mPath + '/' + testFileName); KIO::Job *job = KIO::copy(testPath, testDest); QVERIFY2(job->exec(), "Couldn't copy test image"); mSizeHash.insert(testFileName, QSize(width, height)); } static QImage createColoredImage(int width, int height, const QColor &color) { QImage image(width, height, QImage::Format_RGB32); QPainter painter(&image); painter.fillRect(image.rect(), color); return image; } void SandBox::createTestImage(const QString &name, int width, int height, const QColor &color) { QImage image = createColoredImage(width, height, color); image.save(mPath + '/' + name, "png"); mSizeHash.insert(name, QSize(width, height)); } void ThumbnailProviderTest::initTestCase() { qRegisterMetaType<KFileItem>("KFileItem"); } void ThumbnailProviderTest::init() { ThumbnailProvider::setThumbnailBaseDir(mSandBox.mPath + "/thumbnails/"); mSandBox.fill(); } static void syncRun(ThumbnailProvider *provider) { QEventLoop loop; QObject::connect(provider, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); } void ThumbnailProviderTest::testLoadLocal() { QDir dir(mSandBox.mPath); // Create a list of items which will be thumbnailed KFileItemList list; const auto entryInfoList = dir.entryInfoList(QDir::Files); for (const QFileInfo &info : entryInfoList) { QUrl url("file://" + info.absoluteFilePath()); KFileItem item(url); list << item; } // Generate the thumbnails ThumbnailProvider provider; provider.setThumbnailGroup(ThumbnailGroup::Normal); provider.appendItems(list); QSignalSpy spy(&provider, SIGNAL(thumbnailLoaded(KFileItem, QPixmap, QSize, qulonglong))); syncRun(&provider); while (!ThumbnailProvider::isThumbnailWriterEmpty()) { QTest::qWait(100); } // Check we generated the correct number of thumbnails QDir thumbnailDir = ThumbnailProvider::thumbnailBaseDir(ThumbnailGroup::Normal); // There should be one file less because small.png is a png and is too // small to have a thumbnail const QStringList entryList = thumbnailDir.entryList(QStringList("*.png")); QCOMPARE(entryList.count(), mSandBox.mSizeHash.size() - 1); // Check thumbnail keys QHash<KFileItem, QHash<QString, QString>> thumbnailHash; for (const QString &name : entryList) { QImage thumb; QVERIFY(thumb.load(thumbnailDir.filePath(name))); QUrl url(thumb.text("Thumb::URI")); KFileItem item = list.findByUrl(url); QVERIFY(!item.isNull()); QSize originalSize = mSandBox.mSizeHash.value(item.url().fileName()); uint mtime = item.time(KFileItem::ModificationTime).toSecsSinceEpoch(); if (mtime == uint(-1)) { // This happens from time to time on build.kde.org, but I haven't // been able to reproduce it locally, so let's try to gather more // information. qWarning() << "mtime == -1 for url" << url << ". This should not happen!"; qWarning() << "errno:" << errno << "message:" << strerror(errno); qWarning() << "QFile::exists(" << url.toLocalFile() << "):" << QFile::exists(url.toLocalFile()); qWarning() << "Recalculating mtime" << item.time(KFileItem::ModificationTime).toSecsSinceEpoch(); QFAIL("Invalid time for test KFileItem"); } QCOMPARE(thumb.text("Thumb::Image::Width"), QString::number(originalSize.width())); QCOMPARE(thumb.text("Thumb::Image::Height"), QString::number(originalSize.height())); QCOMPARE(thumb.text("Thumb::Mimetype"), item.mimetype()); QCOMPARE(thumb.text("Thumb::Size"), QString::number(item.size())); QCOMPARE(thumb.text("Thumb::MTime"), QString::number(mtime)); } // Check what was in the thumbnailLoaded() signals QCOMPARE(spy.count(), mSandBox.mSizeHash.size()); QSignalSpy::ConstIterator it = spy.constBegin(), end = spy.constEnd(); for (; it != end; ++it) { const QVariantList args = *it; const KFileItem item = qvariant_cast<KFileItem>(args.at(0)); const QSize size = args.at(2).toSize(); const QSize expectedSize = mSandBox.mSizeHash.value(item.url().fileName()); QCOMPARE(size, expectedSize); } } void ThumbnailProviderTest::testUseEmbeddedOrNot() { QImage expectedThumbnail; QPixmap thumbnailPix; SandBox sandBox; sandBox.initDir(); // This image is red (0xfe0000) and 256x128 but contains a white 128x64 thumbnail sandBox.copyTestImage("embedded-thumbnail.jpg", 256, 128); KFileItemList list; QUrl url("file://" + QDir(sandBox.mPath).absoluteFilePath("embedded-thumbnail.jpg")); list << KFileItem(url); // Loading a normal thumbnail should bring the white one { ThumbnailProvider provider; provider.setThumbnailGroup(ThumbnailGroup::Normal); provider.appendItems(list); QSignalSpy spy(&provider, SIGNAL(thumbnailLoaded(KFileItem, QPixmap, QSize, qulonglong))); syncRun(&provider); QCOMPARE(spy.count(), 1); expectedThumbnail = createColoredImage(128, 64, Qt::white); thumbnailPix = qvariant_cast<QPixmap>(spy.at(0).at(1)); QVERIFY(TestUtils::imageCompare(expectedThumbnail, thumbnailPix.toImage())); } // Loading a large thumbnail should bring the red one, unless thumbnails are deleted on exit, // which should bring the white one { ThumbnailProvider provider; provider.setThumbnailGroup(ThumbnailGroup::Large); provider.appendItems(list); QSignalSpy spy(&provider, SIGNAL(thumbnailLoaded(KFileItem, QPixmap, QSize, qulonglong))); syncRun(&provider); QCOMPARE(spy.count(), 1); if (GwenviewConfig::lowResourceUsageMode()) { expectedThumbnail = createColoredImage(128, 64, Qt::white); } else { expectedThumbnail = createColoredImage(256, 128, QColor(254, 0, 0)); } thumbnailPix = qvariant_cast<QPixmap>(spy.at(0).at(1)); QVERIFY(TestUtils::imageCompare(expectedThumbnail, thumbnailPix.toImage())); } } void ThumbnailProviderTest::testLoadRemote() { QUrl url = setUpRemoteTestDir("test.png"); if (!url.isValid()) { QSKIP("Not running this test: failed to setup remote test dir."); } url = url.adjusted(QUrl::StripTrailingSlash); url.setPath(url.path() + '/' + "test.png"); KFileItemList list; KFileItem item(url); list << item; ThumbnailProvider provider; provider.setThumbnailGroup(ThumbnailGroup::Normal); provider.appendItems(list); syncRun(&provider); while (!ThumbnailProvider::isThumbnailWriterEmpty()) { QTest::qWait(100); } QDir thumbnailDir = ThumbnailProvider::thumbnailBaseDir(ThumbnailGroup::Normal); QStringList entryList = thumbnailDir.entryList(QStringList("*.png")); QCOMPARE(entryList.count(), 1); } void ThumbnailProviderTest::testRemoveItemsWhileGenerating() { QDir dir(mSandBox.mPath); // Create a list of items which will be thumbnailed KFileItemList list; const auto entryInfoList = dir.entryInfoList(QDir::Files); for (const QFileInfo &info : entryInfoList) { QUrl url("file://" + info.absoluteFilePath()); KFileItem item(url); list << item; } // Start generating thumbnails for items ThumbnailProvider provider; provider.setThumbnailGroup(ThumbnailGroup::Normal); provider.appendItems(list); QEventLoop loop; connect(&provider, SIGNAL(finished()), &loop, SLOT(quit())); // Remove items, it should not crash provider.removeItems(list); loop.exec(); } #include "moc_thumbnailprovidertest.cpp"
9,719
C++
.cpp
243
34.868313
109
0.696044
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,878
imagemetainfomodeltest.cpp
KDE_gwenview/tests/auto/imagemetainfomodeltest.cpp
/* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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. */ // STL #include <memory> // Qt #include <QTest> // KF // Local #include "../lib/exiv2imageloader.h" #include "../lib/imagemetainfomodel.h" #include "testutils.h" // Exiv2 #include <exiv2/exiv2.hpp> #include "imagemetainfomodeltest.h" QTEST_MAIN(ImageMetaInfoModelTest) using namespace Gwenview; void ImageMetaInfoModelTest::testCatchExiv2Errors() { QByteArray data; { QString path = pathForTestFile("302350_exiv_0.23_exception.jpg"); QFile file(path); QVERIFY(file.open(QIODevice::ReadOnly)); data = file.readAll(); } std::unique_ptr<Exiv2::Image> image; { Exiv2ImageLoader loader; QVERIFY(loader.load(data)); image = loader.popImage(); } ImageMetaInfoModel model; model.setExiv2Image(image.get()); } #include "moc_imagemetainfomodeltest.cpp"
1,610
C++
.cpp
48
30.333333
79
0.755181
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,879
urlutilstest.cpp
KDE_gwenview/tests/auto/urlutilstest.cpp
/* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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 "urlutilstest.h" // Qt #include <QDir> #include <QTest> // KF // Local #include "../lib/urlutils.h" QTEST_MAIN(UrlUtilsTest) using namespace Gwenview; void UrlUtilsTest::testFixUserEnteredUrl() { QFETCH(QUrl, in); QFETCH(QUrl, expected); QUrl out = UrlUtils::fixUserEnteredUrl(in); QCOMPARE(out.url(), expected.url()); } #define NEW_ROW(in, expected) QTest::newRow(QString(in).toLocal8Bit().data()) << QUrl(in) << QUrl(expected) void UrlUtilsTest::testFixUserEnteredUrl_data() { QTest::addColumn<QUrl>("in"); QTest::addColumn<QUrl>("expected"); QString pwd = QDir::currentPath(); NEW_ROW("http://example.com", "http://example.com"); NEW_ROW("file://" + pwd + "/example.zip", "zip:" + pwd + "/example.zip"); NEW_ROW("file://" + pwd + "/example.cbz", "zip:" + pwd + "/example.cbz"); NEW_ROW("file://" + pwd + "/example.jpg", "file://" + pwd + "/example.jpg"); // Check it does not get turned into gzip://... NEW_ROW("file://" + pwd + "/example.svgz", "file://" + pwd + "/example.svgz"); } #include "moc_urlutilstest.cpp"
1,857
C++
.cpp
45
38.755556
107
0.713252
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,880
testutils.cpp
KDE_gwenview/tests/auto/testutils.cpp
/* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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 "testutils.h" // Qt #include <QStandardPaths> #include <QTimer> // KF #include <KIO/DeleteJob> #include <KIO/FileCopyJob> #include <KIO/MkdirJob> #include <KIO/StatJob> #include <KJobWidgets> QUrl setUpRemoteTestDir(const QString &testFile) { QWidget *authWindow = nullptr; if (qEnvironmentVariableIsEmpty("GV_REMOTE_TESTS_BASE_URL")) { qWarning() << "Environment variable GV_REMOTE_TESTS_BASE_URL not set: remote tests disabled"; return {}; } QUrl baseUrl(QString::fromLocal8Bit(qgetenv("GV_REMOTE_TESTS_BASE_URL"))); baseUrl = baseUrl.adjusted(QUrl::StripTrailingSlash); baseUrl.setPath(baseUrl.path() + "/gwenview-remote-tests"); auto statJob = KIO::stat(baseUrl, KIO::StatJob::DestinationSide, KIO::StatNoDetails); KJobWidgets::setWindow(statJob, authWindow); if (statJob->exec()) { KIO::DeleteJob *deleteJob = KIO::del(baseUrl); KJobWidgets::setWindow(deleteJob, authWindow); deleteJob->exec(); } KIO::MkdirJob *mkdirJob = KIO::mkdir(baseUrl); KJobWidgets::setWindow(mkdirJob, authWindow); if (!mkdirJob->exec()) { qCritical() << "Could not create dir" << baseUrl << ":" << mkdirJob->errorString(); return {}; } if (!testFile.isEmpty()) { QUrl dstUrl = baseUrl; dstUrl = dstUrl.adjusted(QUrl::StripTrailingSlash); dstUrl.setPath(dstUrl.path() + '/' + testFile); KIO::FileCopyJob *copyJob = KIO::file_copy(urlForTestFile(testFile), dstUrl); KJobWidgets::setWindow(copyJob, authWindow); if (!copyJob->exec()) { qCritical() << "Could not copy" << testFile << "to" << dstUrl << ":" << copyJob->errorString(); return {}; } } return baseUrl; } void createEmptyFile(const QString &path) { QVERIFY(!QFile::exists(path)); QFile file(path); bool ok = file.open(QIODevice::WriteOnly); QVERIFY(ok); } void waitForDeferredDeletes() { QCoreApplication::sendPostedEvents(); QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); QCoreApplication::processEvents(); } namespace TestUtils { void purgeUserConfiguration() { QString confDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); QVERIFY(confDir.endsWith(QStringLiteral(".qttest/share"))); // Better safe than sorry if (QFileInfo(confDir).isDir()) { KIO::DeleteJob *deleteJob = KIO::del(QUrl::fromLocalFile(confDir)); QVERIFY(deleteJob->exec()); } } static QImage simplifyFormats(const QImage &img) { switch (img.format()) { case QImage::Format_RGB32: case QImage::Format_ARGB32_Premultiplied: return img.convertToFormat(QImage::Format_ARGB32); default: return img; } } inline bool fuzzyColorComponentCompare(int c1, int c2, int delta) { return qAbs(c1 - c2) < delta; } bool fuzzyImageCompare(const QImage &img1_, const QImage &img2_, int delta) { if (img1_.size() != img2_.size()) { qWarning() << "Different sizes" << img1_.size() << "!=" << img2_.size(); return false; } QImage img1 = simplifyFormats(img1_); QImage img2 = simplifyFormats(img2_); if (img1.format() != img2.format()) { qWarning() << "Different formats" << img1.format() << "!=" << img2.format(); return false; } for (int posY = 0; posY < img1.height(); ++posY) { for (int posX = 0; posX < img2.width(); ++posX) { QColor col1 = img1.pixel(posX, posY); QColor col2 = img2.pixel(posX, posY); bool ok = fuzzyColorComponentCompare(col1.red(), col2.red(), delta) && fuzzyColorComponentCompare(col1.green(), col2.green(), delta) && fuzzyColorComponentCompare(col1.blue(), col2.blue(), delta) && fuzzyColorComponentCompare(col1.alpha(), col2.alpha(), delta); if (!ok) { qWarning() << "Different at" << QPoint(posX, posY) << col1.name() << "!=" << col2.name(); return false; } } } return true; } bool imageCompare(const QImage &img1, const QImage &img2) { return fuzzyImageCompare(img1, img2, 1); } SandBoxDir::SandBoxDir() : mTempDir(QDir::currentPath() + "/sandbox-") { setPath(mTempDir.path()); } void SandBoxDir::fill(const QStringList &filePaths) { for (const QString &filePath : filePaths) { QFileInfo info(*this, filePath); mkpath(info.absolutePath()); createEmptyFile(info.absoluteFilePath()); } } TimedEventLoop::TimedEventLoop(int maxDuration) : mTimer(new QTimer(this)) { mTimer->setSingleShot(true); mTimer->setInterval(maxDuration * 1000); connect(mTimer, &QTimer::timeout, this, &TimedEventLoop::fail); } int TimedEventLoop::exec(ProcessEventsFlags flags) { mTimer->start(); return QEventLoop::exec(flags); } void TimedEventLoop::fail() { if (isRunning()) { qFatal("TimedEventLoop has been running for %d seconds. Aborting.", mTimer->interval() / 1000); exit(1); } } } // namespace TestUtils #include "moc_testutils.cpp"
5,865
C++
.cpp
163
31.190184
144
0.67842
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,881
semanticinfobackendtest.cpp
KDE_gwenview/tests/auto/semanticinfobackendtest.cpp
/* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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. */ // Local #include "semanticinfobackendtest.h" // Qt #include <QSignalSpy> #include <QTemporaryFile> #include <QTest> // KF #include <KRandom> // Local #include "testutils.h" #include <config-gwenview.h> #ifdef GWENVIEW_SEMANTICINFO_BACKEND_FAKE #include <lib/semanticinfo/fakesemanticinfobackend.h> #elif defined(GWENVIEW_SEMANTICINFO_BACKEND_BALOO) #include <lib/semanticinfo/baloosemanticinfobackend.h> #else #ifdef __GNUC__ #error No metadata backend defined #endif #endif QTEST_MAIN(Gwenview::SemanticInfoBackEndTest) namespace Gwenview { SemanticInfoBackEndClient::SemanticInfoBackEndClient(AbstractSemanticInfoBackEnd *backEnd) : mBackEnd(backEnd) { connect(backEnd, SIGNAL(semanticInfoRetrieved(QUrl, SemanticInfo)), SLOT(slotSemanticInfoRetrieved(QUrl, SemanticInfo))); } void SemanticInfoBackEndClient::slotSemanticInfoRetrieved(const QUrl &url, const SemanticInfo &semanticInfo) { mSemanticInfoForUrl[url] = semanticInfo; } void SemanticInfoBackEndTest::initTestCase() { qRegisterMetaType<QUrl>("QUrl"); qRegisterMetaType<QString>("SemanticInfoTag"); } void SemanticInfoBackEndTest::init() { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_FAKE mBackEnd = new FakeSemanticInfoBackEnd(nullptr, FakeSemanticInfoBackEnd::InitializeEmpty); #elif defined(GWENVIEW_SEMANTICINFO_BACKEND_BALOO) mBackEnd = new BalooSemanticInfoBackend(nullptr); #endif } void SemanticInfoBackEndTest::cleanup() { delete mBackEnd; mBackEnd = nullptr; } /** * Get and set the rating of a temp file */ void SemanticInfoBackEndTest::testRating() { QTemporaryFile temp("XXXXXX.metadatabackendtest"); QVERIFY(temp.open()); QUrl url; url.setPath(temp.fileName()); SemanticInfoBackEndClient client(mBackEnd); QSignalSpy spy(mBackEnd, SIGNAL(semanticInfoRetrieved(QUrl, SemanticInfo))); mBackEnd->retrieveSemanticInfo(url); QVERIFY(waitForSignal(spy)); SemanticInfo semanticInfo = client.semanticInfoForUrl(url); QCOMPARE(semanticInfo.mRating, 0); semanticInfo.mRating = 5; mBackEnd->storeSemanticInfo(url, semanticInfo); } #if 0 // Disabled because Baloo does not work like Nepomuk: it does not create tags // independently of files. void SemanticInfoBackEndTest::testTagForLabel() { QSignalSpy spy(mBackEnd, SIGNAL(tagAdded(SemanticInfoTag,QString))); TagSet oldAllTags = mBackEnd->allTags(); QString label = "testTagForLabel-" + KRandom::randomString(5); SemanticInfoTag tag1 = mBackEnd->tagForLabel(label); QVERIFY(!tag1.isEmpty()); QVERIFY(!oldAllTags.contains(tag1)); QVERIFY(mBackEnd->allTags().contains(tag1)); // This is a new tag, we should receive a signal QCOMPARE(spy.count(), 1); SemanticInfoTag tag2 = mBackEnd->tagForLabel(label); QCOMPARE(tag1, tag2); // This is not a new tag, we should not receive a signal QCOMPARE(spy.count(), 1); QString label2 = mBackEnd->labelForTag(tag2); QCOMPARE(label, label2); } #endif } // namespace #include "moc_semanticinfobackendtest.cpp"
3,792
C++
.cpp
107
32.794393
125
0.786047
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,882
jpegcontenttest.cpp
KDE_gwenview/tests/auto/jpegcontenttest.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "jpegcontenttest.h" #include <iostream> // Qt #include <QDebug> #include <QDir> #include <QFile> #include <QImage> #include <QString> #include <QTest> // KF // Local #include "../lib/jpegcontent.h" #include "../lib/orientation.h" #include "testutils.h" using namespace std; const char *ORIENT6_FILE = "orient6.jpg"; const char *ORIENT1_VFLIP_FILE = "orient1_vflip.jpg"; const char *CUT_FILE = "cut.jpg"; const char *TMP_FILE = "tmp.jpg"; const char *THUMBNAIL_FILE = "test_thumbnail.jpg"; const int ORIENT6_WIDTH = 128; // This size is the size *after* orientation const int ORIENT6_HEIGHT = 256; // has been applied const QString ORIENT6_COMMENT = "a comment"; QTEST_MAIN(JpegContentTest) void JpegContentTest::initTestCase() { bool result; QFile in(pathForTestFile(ORIENT6_FILE)); result = in.open(QIODevice::ReadOnly); QVERIFY(result); QFileInfo info(in); int size = info.size() / 2; char *data = new char[size]; int readSize = in.read(data, size); QCOMPARE(size, readSize); QFile out(CUT_FILE); result = out.open(QIODevice::WriteOnly); QVERIFY(result); int wroteSize = out.write(data, size); QCOMPARE(size, wroteSize); delete[] data; } void JpegContentTest::cleanupTestCase() { QDir::current().remove(CUT_FILE); } using MetaInfoMap = QMap<QString, QString>; #if 0 MetaInfoMap getMetaInfo(const QString& path) { KFileMetaInfo fmi(path); QStringList list = fmi.supportedKeys(); QStringList::ConstIterator it = list.constBegin(); MetaInfoMap map; for (; it != list.constEnd(); ++it) { KFileMetaInfoItem item = fmi.item(*it); map[*it] = item.value().toString(); } return map; } void compareMetaInfo(const QString& path1, const QString& path2, const QStringList& ignoredKeys) { MetaInfoMap mim1 = getMetaInfo(path1); MetaInfoMap mim2 = getMetaInfo(path2); QCOMPARE(mim1.keys(), mim2.keys()); QList<QString> keys = mim1.keys(); QList<QString>::ConstIterator it = keys.constBegin(); for (; it != keys.constEnd(); ++it) { QString key = *it; if (ignoredKeys.contains(key)) continue; QString msg = QStringLiteral("Meta info differs for key '%1': v1=%2 v2=%3") .arg(key) .arg(mim1[key]) .arg(mim2[key]); QVERIFY2(mim1[key] == mim2[key], msg.toUtf8()); } } #endif void JpegContentTest::testResetOrientation() { Gwenview::JpegContent content; bool result; // Test resetOrientation without transform result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); content.resetOrientation(); result = content.save(TMP_FILE); QVERIFY(result); result = content.load(TMP_FILE); QVERIFY(result); QCOMPARE(content.orientation(), Gwenview::NORMAL); // Test resetOrientation with transform result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); content.resetOrientation(); content.transform(Gwenview::ROT_90); result = content.save(TMP_FILE); QVERIFY(result); result = content.load(TMP_FILE); QVERIFY(result); QCOMPARE(content.orientation(), Gwenview::NORMAL); } /** * This function tests JpegContent::transform() by applying a ROT_90 * transformation, saving, reloading and applying a ROT_270 to undo the ROT_90. * Saving and reloading are necessary because lossless transformation only * happens in JpegContent::save() */ void JpegContentTest::testTransform() { bool result; QImage finalImage, expectedImage; Gwenview::JpegContent content; result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); content.transform(Gwenview::ROT_90); result = content.save(TMP_FILE); QVERIFY(result); result = content.load(TMP_FILE); QVERIFY(result); content.transform(Gwenview::ROT_270); result = content.save(TMP_FILE); QVERIFY(result); result = finalImage.load(TMP_FILE); QVERIFY(result); result = expectedImage.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); QCOMPARE(finalImage, expectedImage); } void JpegContentTest::testSetComment() { QString comment = "test comment"; Gwenview::JpegContent content; bool result; result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); content.setComment(comment); QCOMPARE(content.comment(), comment); result = content.save(TMP_FILE); QVERIFY(result); result = content.load(TMP_FILE); QVERIFY(result); QCOMPARE(content.comment(), comment); } void JpegContentTest::testReadInfo() { Gwenview::JpegContent content; bool result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); QCOMPARE(int(content.orientation()), 6); QCOMPARE(content.comment(), ORIENT6_COMMENT); QCOMPARE(content.size(), QSize(ORIENT6_WIDTH, ORIENT6_HEIGHT)); } void JpegContentTest::testThumbnail() { Gwenview::JpegContent content; bool result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); QImage thumbnail = content.thumbnail(); result = thumbnail.save(THUMBNAIL_FILE, "JPEG"); QVERIFY(result); } void JpegContentTest::testMultipleRotations() { // Test that rotating a file a lot of times does not cause findJxform() to fail Gwenview::JpegContent content; bool result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); // 12*4 + 1 is the same as 1, since rotating four times brings you back for (int loop = 0; loop < 12 * 4 + 1; ++loop) { content.transform(Gwenview::ROT_90); } result = content.save(TMP_FILE); QVERIFY(result); result = content.load(TMP_FILE); QVERIFY(result); QCOMPARE(content.size(), QSize(ORIENT6_HEIGHT, ORIENT6_WIDTH)); // Check the other meta info are still here // QStringList ignoredKeys; // ignoredKeys << "Orientation" << "Comment"; // compareMetaInfo(pathForTestFile(ORIENT6_FILE), pathForTestFile(ORIENT1_VFLIP_FILE), ignoredKeys); } void JpegContentTest::testLoadTruncated() { // Test that loading and manipulating a truncated file does not crash Gwenview::JpegContent content; bool result = content.load(CUT_FILE); QVERIFY(result); QCOMPARE(int(content.orientation()), 6); QCOMPARE(content.comment(), ORIENT6_COMMENT); content.transform(Gwenview::VFLIP); qWarning() << "# Next function should output errors about incomplete image"; content.save(TMP_FILE); qWarning() << "#"; } void JpegContentTest::testRawData() { Gwenview::JpegContent content; bool result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); QByteArray fileData; QFile file(pathForTestFile(ORIENT6_FILE)); result = file.open(QIODevice::ReadOnly); QVERIFY(result); fileData = file.readAll(); QCOMPARE(content.rawData(), fileData); } void JpegContentTest::testSetImage() { Gwenview::JpegContent content; bool result = content.load(pathForTestFile(ORIENT6_FILE)); QVERIFY(result); QImage image = QImage(400, 300, QImage::Format_RGB32); image.fill(Qt::red); content.setImage(image); result = content.save(TMP_FILE); QVERIFY(result); result = content.load(TMP_FILE); QVERIFY(result); QCOMPARE(content.size(), image.size()); // QStringList ignoredKeys; // ignoredKeys << "Orientation"; // compareMetaInfo(pathForTestFile(ORIENT6_FILE), pathForTestFile(TMP_FILE), ignoredKeys); } #include "moc_jpegcontenttest.cpp"
8,408
C++
.cpp
243
30.514403
107
0.714691
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,883
recursivedirmodeltest.cpp
KDE_gwenview/tests/auto/recursivedirmodeltest.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "recursivedirmodeltest.h" // Local #include <lib/recursivedirmodel.h> // Qt #include <QDebug> #include <QTest> // KF #include <KDirModel> using namespace Gwenview; QTEST_MAIN(RecursiveDirModelTest) void RecursiveDirModelTest::testBasic_data() { QTest::addColumn<QStringList>("initialFiles"); QTest::addColumn<QStringList>("addedFiles"); QTest::addColumn<QStringList>("removedFiles"); #define NEW_ROW(name, initialFiles, addedFiles, removedFiles) QTest::newRow(name) << (initialFiles) << (addedFiles) << (removedFiles) NEW_ROW("empty_dir", QStringList(), QStringList() << "new.jpg", QStringList() << "new.jpg"); NEW_ROW("images_only", QStringList() << "pict01.jpg" << "pict02.jpg" << "pict03.jpg", QStringList() << "pict04.jpg", QStringList() << "pict02.jpg"); NEW_ROW("images_in_two_dirs", QStringList() << "d1/pict101.jpg" << "d1/pict102.jpg" << "d2/pict201.jpg", QStringList() << "d1/pict103.jpg" << "d2/pict202.jpg", QStringList() << "d2/pict202.jpg"); NEW_ROW("images_in_two_dirs_w_same_names", QStringList() << "d1/a.jpg" << "d1/b.jpg" << "d2/a.jpg" << "d2/b.jpg", QStringList() << "d3/a.jpg" << "d3/b.jpg", QStringList() << "d1/a.jpg" << "d2/a.jpg" << "d3/a.jpg"); #undef NEW_ROW } static QList<QUrl> listModelUrls(QAbstractItemModel *model) { QList<QUrl> out; for (int row = 0; row < model->rowCount(QModelIndex()); ++row) { QModelIndex index = model->index(row, 0); KFileItem item = index.data(KDirModel::FileItemRole).value<KFileItem>(); out << item.url(); } std::sort(out.begin(), out.end()); return out; } static QList<QUrl> listExpectedUrls(const QDir &dir, const QStringList &files) { QList<QUrl> lst; for (const QString &name : files) { lst << QUrl::fromLocalFile(dir.absoluteFilePath(name)); } std::sort(lst.begin(), lst.end()); return lst; } void logLst(const QList<QUrl> &lst) { for (const QUrl &url : lst) { qWarning() << url.fileName(); } } void RecursiveDirModelTest::testBasic() { QFETCH(QStringList, initialFiles); QFETCH(QStringList, addedFiles); QFETCH(QStringList, removedFiles); TestUtils::SandBoxDir sandBoxDir; RecursiveDirModel model; TestUtils::TimedEventLoop loop; connect(&model, &RecursiveDirModel::completed, &loop, &QEventLoop::quit); // Test initial files sandBoxDir.fill(initialFiles); model.setUrl(QUrl::fromLocalFile(sandBoxDir.absolutePath())); QList<QUrl> out, expected; do { loop.exec(); out = listModelUrls(&model); expected = listExpectedUrls(sandBoxDir, initialFiles); } while (out.size() != expected.size()); QCOMPARE(out, expected); // Test adding new files sandBoxDir.fill(addedFiles); do { loop.exec(); out = listModelUrls(&model); expected = listExpectedUrls(sandBoxDir, initialFiles + addedFiles); } while (out.size() != expected.size()); QCOMPARE(out, expected); #if 0 /* FIXME: This part of the test is not reliable :/ Sometimes some tests pass, * sometimes they don't. It feels like KDirLister::itemsDeleted() is not * always emitted. */ // Test removing files for (const QString &name : qAsConst(removedFiles)) { bool ok = sandBoxDir.remove(name); Q_ASSERT(ok); expected.removeOne(QUrl(sandBoxDir.absoluteFilePath(name))); } QTime chrono; chrono.start(); while (chrono.elapsed() < 2000) { waitForDeferredDeletes(); } out = listModelUrls(&model); if (out != expected) { qWarning() << "out:"; logLst(out); qWarning() << "expected:"; logLst(expected); } QCOMPARE(out, expected); #endif } void RecursiveDirModelTest::testSetNewUrl() { TestUtils::SandBoxDir sandBoxDir; sandBoxDir.fill(QStringList() << "d1/a.jpg" << "d1/b.jpg" << "d1/c.jpg" << "d1/d.jpg" << "d2/e.jpg" << "d2/f.jpg"); RecursiveDirModel model; TestUtils::TimedEventLoop loop; connect(&model, &RecursiveDirModel::completed, &loop, &QEventLoop::quit); model.setUrl(QUrl::fromLocalFile(sandBoxDir.absoluteFilePath("d1"))); loop.exec(); QCOMPARE(model.rowCount(QModelIndex()), 4); model.setUrl(QUrl::fromLocalFile(sandBoxDir.absoluteFilePath("d2"))); loop.exec(); QCOMPARE(model.rowCount(QModelIndex()), 2); } #include "moc_recursivedirmodeltest.cpp"
5,792
C++
.cpp
158
29.303797
133
0.621588
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,884
thumbnailviewhelper.cpp
KDE_gwenview/app/thumbnailviewhelper.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "thumbnailviewhelper.h" #include <config-gwenview.h> // Qt #include <QAction> #include <QCursor> #include <QMenu> // KF #include <KActionCollection> // Local #include "fileoperations.h" #include "gwenview_app_debug.h" #include <lib/document/documentfactory.h> namespace Gwenview { struct ThumbnailViewHelperPrivate { KActionCollection *mActionCollection = nullptr; QUrl mCurrentDirUrl; void addActionToMenu(QMenu &popup, const char *name) { QAction *action = mActionCollection->action(name); if (!action) { qCWarning(GWENVIEW_APP_LOG) << "Unknown action" << name; return; } if (action->isEnabled()) { popup.addAction(action); } } void addActionToMenu(QMenu &popup, const QString &name) { QAction *action = mActionCollection->action(name); if (!action) { qCWarning(GWENVIEW_APP_LOG) << "Unknown action" << name; return; } if (action->isEnabled()) { popup.addAction(action); } } }; ThumbnailViewHelper::ThumbnailViewHelper(QObject *parent, KActionCollection *actionCollection) : AbstractThumbnailViewHelper(parent) , d(new ThumbnailViewHelperPrivate) { d->mActionCollection = actionCollection; } ThumbnailViewHelper::~ThumbnailViewHelper() { delete d; } void ThumbnailViewHelper::setCurrentDirUrl(const QUrl &url) { d->mCurrentDirUrl = url; } void ThumbnailViewHelper::showContextMenu(QWidget *parent) { QMenu popup(parent); if (d->mCurrentDirUrl.scheme() == QLatin1String("trash")) { d->addActionToMenu(popup, "file_restore"); d->addActionToMenu(popup, "deletefile"); popup.addSeparator(); d->addActionToMenu(popup, "file_show_properties"); } else { d->addActionToMenu(popup, "file_create_folder"); popup.addSeparator(); d->addActionToMenu(popup, "file_rename"); d->addActionToMenu(popup, "file_trash"); d->addActionToMenu(popup, "deletefile"); popup.addSeparator(); d->addActionToMenu(popup, KStandardAction::name(KStandardAction::Copy)); d->addActionToMenu(popup, "file_copy_to"); d->addActionToMenu(popup, "file_move_to"); d->addActionToMenu(popup, "file_link_to"); popup.addSeparator(); d->addActionToMenu(popup, "file_open_in_new_window"); d->addActionToMenu(popup, "file_open_with"); d->addActionToMenu(popup, "file_open_containing_folder"); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE d->addActionToMenu(popup, "edit_tags"); #endif popup.addSeparator(); d->addActionToMenu(popup, "file_show_properties"); } popup.exec(QCursor::pos()); } void ThumbnailViewHelper::showMenuForUrlDroppedOnViewport(QWidget *parent, const QList<QUrl> &lst) { showMenuForUrlDroppedOnDir(parent, lst, d->mCurrentDirUrl); } void ThumbnailViewHelper::showMenuForUrlDroppedOnDir(QWidget *parent, const QList<QUrl> &urlList, const QUrl &destUrl) { FileOperations::showMenuForDroppedUrls(parent, urlList, destUrl); } } // namespace #include "moc_thumbnailviewhelper.cpp"
3,991
C++
.cpp
112
30.883929
118
0.713397
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,885
configdialog.cpp
KDE_gwenview/app/configdialog.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "configdialog.h" // Qt #include <QFontDatabase> // KF #include <KLocalizedString> // Local #include <lib/gwenviewconfig.h> #include <lib/invisiblebuttongroup.h> namespace Gwenview { template<class Ui> QWidget *setupPage(Ui &ui) { auto widget = new QWidget; ui.setupUi(widget); return widget; } ConfigDialog::ConfigDialog(QWidget *parent) : KConfigDialog(parent, QStringLiteral("Settings"), GwenviewConfig::self()) { setFaceType(KPageDialog::List); // General QWidget *widget = setupPage(mGeneralConfigPage); mWrapNavigationBehaviorGroup = new InvisibleButtonGroup(widget); mWrapNavigationBehaviorGroup->setObjectName(QStringLiteral("kcfg_NavigationEndNotification")); mWrapNavigationBehaviorGroup->addButton(mGeneralConfigPage.neverShowWrapNoticeRadioButton, int(SlideShow::NavigationEndNotification::NeverWarn)); mWrapNavigationBehaviorGroup->addButton(mGeneralConfigPage.wrapNoticeOnSlideshowRadioButton, int(SlideShow::NavigationEndNotification::WarnOnSlideshow)); mWrapNavigationBehaviorGroup->addButton(mGeneralConfigPage.alwaysShowWrapNoticeRadioButton, int(SlideShow::NavigationEndNotification::AlwaysWarn)); mFullScreenBackgroundGroup = new InvisibleButtonGroup(widget); mFullScreenBackgroundGroup->setObjectName(QStringLiteral("kcfg_FullScreenBackground")); mFullScreenBackgroundGroup->addButton(mGeneralConfigPage.fullscreenBackgroundBlackRadioButton, int(FullScreenBackground::Black)); mFullScreenBackgroundGroup->addButton(mGeneralConfigPage.fullscreenBackgroundImageRadioButton, int(FullScreenBackground::Image)); mThumbnailActionsGroup = new InvisibleButtonGroup(widget); mThumbnailActionsGroup->setObjectName(QStringLiteral("kcfg_ThumbnailActions")); mThumbnailActionsGroup->addButton(mGeneralConfigPage.allButtonsThumbnailActionsRadioButton, int(ThumbnailActions::AllButtons)); mThumbnailActionsGroup->addButton(mGeneralConfigPage.selectionOnlyThumbnailActionsRadioButton, int(ThumbnailActions::ShowSelectionButtonOnly)); mThumbnailActionsGroup->addButton(mGeneralConfigPage.noneThumbnailActionsRadioButton, int(ThumbnailActions::None)); mGeneralConfigPageItem = addPage(widget, i18n("General")); mGeneralConfigPageItem->setIcon(QIcon::fromTheme(QStringLiteral("gwenview"))); connect(mGeneralConfigPage.kcfg_JPEGQuality, &QAbstractSlider::valueChanged, this, [=](int value) { mGeneralConfigPage.jpegQualitySpinner->setValue(value); }); connect(mGeneralConfigPage.jpegQualitySpinner, QOverload<int>::of(&QSpinBox::valueChanged), this, [=](int value) { mGeneralConfigPage.kcfg_JPEGQuality->setValue(value); }); mGeneralConfigPage.jpegQualitySpinner->setValue(mGeneralConfigPage.kcfg_JPEGQuality->value()); mGeneralConfigPage.lossyImageFormatHelpLabel->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); mGeneralConfigPage.kcfg_AutoplayVideos->setEnabled(mGeneralConfigPage.kcfg_ListVideos->isChecked()); connect(mGeneralConfigPage.kcfg_ListVideos, &QCheckBox::stateChanged, this, [=](int state) { mGeneralConfigPage.kcfg_AutoplayVideos->setEnabled(state == Qt::Checked); }); // Image View widget = setupPage(mImageViewConfigPage); mAlphaBackgroundModeGroup = new InvisibleButtonGroup(widget); mAlphaBackgroundModeGroup->setObjectName(QStringLiteral("kcfg_AlphaBackgroundMode")); mAlphaBackgroundModeGroup->addButton(mImageViewConfigPage.surroundingRadioButton, int(AbstractImageView::AlphaBackgroundNone)); mAlphaBackgroundModeGroup->addButton(mImageViewConfigPage.checkBoardRadioButton, int(AbstractImageView::AlphaBackgroundCheckBoard)); mAlphaBackgroundModeGroup->addButton(mImageViewConfigPage.solidColorRadioButton, int(AbstractImageView::AlphaBackgroundSolid)); mWheelBehaviorGroup = new InvisibleButtonGroup(widget); mWheelBehaviorGroup->setObjectName(QStringLiteral("kcfg_MouseWheelBehavior")); mWheelBehaviorGroup->addButton(mImageViewConfigPage.mouseWheelScrollRadioButton, int(MouseWheelBehavior::Scroll)); mWheelBehaviorGroup->addButton(mImageViewConfigPage.mouseWheelBrowseRadioButton, int(MouseWheelBehavior::Browse)); mWheelBehaviorGroup->addButton(mImageViewConfigPage.mouseWheelZoomRadioButton, int(MouseWheelBehavior::Zoom)); mAnimationMethodGroup = new InvisibleButtonGroup(widget); mAnimationMethodGroup->setObjectName(QStringLiteral("kcfg_AnimationMethod")); #ifdef QT_NO_OPENGL mImageViewConfigPage.glAnimationRadioButton->setEnabled(false); mAnimationMethodGroup->addButton(mImageViewConfigPage.glAnimationRadioButton, int(DocumentView::NoAnimation)); #else mAnimationMethodGroup->addButton(mImageViewConfigPage.glAnimationRadioButton, int(DocumentView::GLAnimation)); #endif mAnimationMethodGroup->addButton(mImageViewConfigPage.softwareAnimationRadioButton, int(DocumentView::SoftwareAnimation)); mAnimationMethodGroup->addButton(mImageViewConfigPage.noAnimationRadioButton, int(DocumentView::NoAnimation)); mZoomModeGroup = new InvisibleButtonGroup(widget); mZoomModeGroup->setObjectName(QStringLiteral("kcfg_ZoomMode")); mZoomModeGroup->addButton(mImageViewConfigPage.autofitZoomModeRadioButton, int(ZoomMode::Autofit)); mZoomModeGroup->addButton(mImageViewConfigPage.keepSameZoomModeRadioButton, int(ZoomMode::KeepSame)); mZoomModeGroup->addButton(mImageViewConfigPage.individualZoomModeRadioButton, int(ZoomMode::Individual)); mThumbnailBarOrientationGroup = new InvisibleButtonGroup(widget); mThumbnailBarOrientationGroup->setObjectName(QStringLiteral("kcfg_ThumbnailBarOrientation")); mThumbnailBarOrientationGroup->addButton(mImageViewConfigPage.horizontalRadioButton, int(Qt::Horizontal)); mThumbnailBarOrientationGroup->addButton(mImageViewConfigPage.verticalRadioButton, int(Qt::Vertical)); mImageViewConfigPageItem = addPage(widget, i18n("Image View")); mImageViewConfigPageItem->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-display-color"))); // Advanced widget = setupPage(mAdvancedConfigPage); mRenderingIntentGroup = new InvisibleButtonGroup(widget); mRenderingIntentGroup->setObjectName(QStringLiteral("kcfg_RenderingIntent")); mRenderingIntentGroup->addButton(mAdvancedConfigPage.relativeRenderingIntentRadioButton, int(RenderingIntent::Relative)); mRenderingIntentGroup->addButton(mAdvancedConfigPage.perceptualRenderingIntentRadioButton, int(RenderingIntent::Perceptual)); mAdvancedConfigPageItem = addPage(widget, i18n("Advanced")); mAdvancedConfigPageItem->setIcon(QIcon::fromTheme(QStringLiteral("preferences-other"))); mAdvancedConfigPage.cacheHelpLabel->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); mAdvancedConfigPage.perceptualHelpLabel->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); mAdvancedConfigPage.relativeHelpLabel->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); mAdvancedConfigPage.colorProfileHelpLabel->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); } void ConfigDialog::setCurrentPage(int page) { switch (page) { case 1: return KPageDialog::setCurrentPage(mImageViewConfigPageItem); case 2: return KPageDialog::setCurrentPage(mAdvancedConfigPageItem); default: return KPageDialog::setCurrentPage(mGeneralConfigPageItem); } } } // namespace #include "moc_configdialog.cpp"
8,310
C++
.cpp
127
61.330709
157
0.825708
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,886
semanticinfocontextmanageritem.cpp
KDE_gwenview/app/semanticinfocontextmanageritem.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "semanticinfocontextmanageritem.h" // Qt #include <QAction> #include <QDialog> #include <QEvent> #include <QPainter> #include <QShortcut> #include <QStyle> #include <QTimer> #include <QVBoxLayout> // KF #include <KActionCategory> #include <KActionCollection> #include <KIconLoader> #include <KLocalizedString> #include <KRatingPainter> #include <KSharedConfig> #include <KWindowConfig> // Local #include "sidebar.h" #include "ui_semanticinfodialog.h" #include "ui_semanticinfosidebaritem.h" #include "viewmainpage.h" #include <lib/contextmanager.h> #include <lib/decoratedtag/decoratedtag.h> #include <lib/documentview/documentview.h> #include <lib/eventwatcher.h> #include <lib/flowlayout.h> #include <lib/hud/hudwidget.h> #include <lib/semanticinfo/semanticinfodirmodel.h> #include <lib/semanticinfo/sorteddirmodel.h> #include <lib/signalblocker.h> #include <lib/widgetfloater.h> namespace Gwenview { static const int RATING_INDICATOR_HIDE_DELAY = 2000; struct SemanticInfoDialog : public QDialog, public Ui_SemanticInfoDialog { SemanticInfoDialog(QWidget *parent) : QDialog(parent) { setLayout(new QVBoxLayout); auto mainWidget = new QWidget; layout()->addWidget(mainWidget); setupUi(mainWidget); mainWidget->layout()->setContentsMargins(0, 0, 0, 0); setWindowTitle(mainWidget->windowTitle()); KWindowConfig::restoreWindowSize(windowHandle(), configGroup()); } ~SemanticInfoDialog() override { KConfigGroup group = configGroup(); KWindowConfig::saveWindowSize(windowHandle(), group); } KConfigGroup configGroup() const { KSharedConfigPtr config = KSharedConfig::openConfig(); return KConfigGroup(config, "SemanticInfoDialog"); } }; /** * A QGraphicsPixmapItem-like class, but which inherits from QGraphicsWidget */ class GraphicsPixmapWidget : public QGraphicsWidget { public: void setPixmap(const QPixmap &pix) { mPix = pix; setMinimumSize(pix.size()); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override { painter->drawPixmap((size().width() - mPix.width()) / 2, (size().height() - mPix.height()) / 2, mPix); } private: QPixmap mPix; }; class RatingIndicator : public HudWidget { public: RatingIndicator() : HudWidget() , mPixmapWidget(new GraphicsPixmapWidget) , mDeleteTimer(new QTimer(this)) { updatePixmap(0); setOpacity(0); init(mPixmapWidget, OptionNone); mDeleteTimer->setInterval(RATING_INDICATOR_HIDE_DELAY); mDeleteTimer->setSingleShot(true); connect(mDeleteTimer, &QTimer::timeout, this, &HudWidget::fadeOut); connect(this, &HudWidget::fadedOut, this, &QObject::deleteLater); } void setRating(int rating) { updatePixmap(rating); update(); mDeleteTimer->start(); fadeIn(); } private: GraphicsPixmapWidget *mPixmapWidget = nullptr; QTimer *mDeleteTimer = nullptr; void updatePixmap(int rating) { KRatingPainter ratingPainter; const int iconSize = KIconLoader::global()->currentSize(KIconLoader::Small); QPixmap pix(iconSize * 5 + ratingPainter.spacing() * 4, iconSize); pix.fill(Qt::transparent); { QPainter painter(&pix); ratingPainter.paint(&painter, pix.rect(), rating); } mPixmapWidget->setPixmap(pix); } }; struct SemanticInfoContextManagerItemPrivate : public Ui_SemanticInfoSideBarItem { SemanticInfoContextManagerItem *q; SideBarGroup *mGroup; KActionCollection *mActionCollection; ViewMainPage *mViewMainPage; QPointer<SemanticInfoDialog> mSemanticInfoDialog; TagInfo mTagInfo; QAction *mEditTagsAction; /** A list of all actions, so that we can disable them when necessary */ QList<QAction *> mActions; QPointer<RatingIndicator> mRatingIndicator; FlowLayout *mTagLayout; QLabel *mEditLabel; void setupGroup() { mGroup = new SideBarGroup(); q->setWidget(mGroup); EventWatcher::install(mGroup, QEvent::Show, q, SLOT(update())); auto container = new QWidget; setupUi(container); container->layout()->setContentsMargins(0, 0, 0, 0); mGroup->addWidget(container); mTagLayout = new FlowLayout; mTagLayout->setHorizontalSpacing(2); mTagLayout->setVerticalSpacing(2); mTagLayout->setContentsMargins(0, 0, 0, 0); mTagContainerWidget->setLayout(mTagLayout); DecoratedTag tempTag; tempTag.setVisible(false); mEditLabel = new QLabel(QStringLiteral("<a href='edit'>%1</a>").arg(i18n("Edit"))); mEditLabel->setVisible(false); mEditLabel->setContentsMargins(tempTag.contentsMargins().left() / 2, tempTag.contentsMargins().top(), tempTag.contentsMargins().right() / 2, tempTag.contentsMargins().bottom()); label_2->setContentsMargins(mEditLabel->contentsMargins()); QObject::connect(mRatingWidget, SIGNAL(ratingChanged(int)), q, SLOT(slotRatingChanged(int))); mDescriptionTextEdit->installEventFilter(q); QObject::connect(mEditLabel, &QLabel::linkActivated, mEditTagsAction, &QAction::trigger); } void setupActions() { auto edit = new KActionCategory(i18nc("@title actions category", "Edit"), mActionCollection); mEditTagsAction = edit->addAction(QStringLiteral("edit_tags")); mEditTagsAction->setText(i18nc("@action", "Edit Tags")); mEditTagsAction->setIcon(QIcon::fromTheme(QStringLiteral("tag"))); mActionCollection->setDefaultShortcut(mEditTagsAction, Qt::CTRL | Qt::Key_T); QObject::connect(mEditTagsAction, &QAction::triggered, q, &SemanticInfoContextManagerItem::showSemanticInfoDialog); mActions << mEditTagsAction; for (int rating = 0; rating <= 5; ++rating) { QAction *action = edit->addAction(QStringLiteral("rate_%1").arg(rating)); if (rating == 0) { action->setText(i18nc("@action Rating value of zero", "Zero")); } else { action->setText(QString(rating, QChar(0x22C6))); /* 0x22C6 is the 'star' character */ } mActionCollection->setDefaultShortcut(action, Qt::Key_0 + rating); QObject::connect(action, &QAction::triggered, q, [this, rating]() { mRatingWidget->setRating(rating * 2); }); mActions << action; } } void updateTags() { QLayoutItem *item; while ((item = mTagLayout->takeAt(0))) { auto tag = item->widget(); if (tag != nullptr && tag != mEditLabel) { tag->deleteLater(); } } if (q->contextManager()->selectedFileItemList().isEmpty()) { mEditLabel->setVisible(false); return; } AbstractSemanticInfoBackEnd *backEnd = q->contextManager()->dirModel()->semanticInfoBackEnd(); TagInfo::ConstIterator it = mTagInfo.constBegin(), end = mTagInfo.constEnd(); QMap<QString, QString> labelMap; for (; it != end; ++it) { SemanticInfoTag tag = it.key(); QString label = backEnd->labelForTag(tag); if (!it.value()) { // Tag is not present for all urls label += '*'; } labelMap[label.toLower()] = label; } const QStringList labels(labelMap.values()); for (const QString &label : labels) { auto decoratedTag = new DecoratedTag(label); mTagLayout->addWidget(decoratedTag); } mTagLayout->addWidget(mEditLabel); mEditLabel->setVisible(true); mTagLayout->update(); } void updateSemanticInfoDialog() { mSemanticInfoDialog->mTagWidget->setEnabled(!q->contextManager()->selectedFileItemList().isEmpty()); mSemanticInfoDialog->mTagWidget->setTagInfo(mTagInfo); } }; SemanticInfoContextManagerItem::SemanticInfoContextManagerItem(ContextManager *manager, KActionCollection *actionCollection, ViewMainPage *viewMainPage) : AbstractContextManagerItem(manager) , d(new SemanticInfoContextManagerItemPrivate) { d->q = this; d->mActionCollection = actionCollection; d->mViewMainPage = viewMainPage; connect(contextManager(), &ContextManager::selectionChanged, this, &SemanticInfoContextManagerItem::slotSelectionChanged); connect(contextManager(), &ContextManager::selectionDataChanged, this, &SemanticInfoContextManagerItem::update); connect(contextManager(), &ContextManager::currentDirUrlChanged, this, &SemanticInfoContextManagerItem::update); d->setupActions(); d->setupGroup(); } SemanticInfoContextManagerItem::~SemanticInfoContextManagerItem() { delete d; } inline int ratingForVariant(const QVariant &variant) { if (variant.isValid()) { return variant.toInt(); } else { return 0; } } void SemanticInfoContextManagerItem::slotSelectionChanged() { update(); } void SemanticInfoContextManagerItem::update() { const KFileItemList itemList = contextManager()->selectedFileItemList(); bool first = true; int rating = 0; QString description; SortedDirModel *dirModel = contextManager()->dirModel(); // This hash stores for how many items the tag is present // If you have 3 items, and only 2 have the "Holiday" tag, // then tagHash["Holiday"] will be 2 at the end of the loop. using TagHash = QHash<QString, int>; TagHash tagHash; for (const KFileItem &item : itemList) { QModelIndex index = dirModel->indexForItem(item); QVariant value = dirModel->data(index, SemanticInfoDirModel::RatingRole); if (first) { rating = ratingForVariant(value); } else if (rating != ratingForVariant(value)) { // Ratings aren't the same, reset rating = 0; } QString indexDescription = index.data(SemanticInfoDirModel::DescriptionRole).toString(); if (first) { description = indexDescription; } else if (description != indexDescription) { description.clear(); } // Fill tagHash, incrementing the tag count if it's already there const TagSet tagSet = TagSet::fromVariant(index.data(SemanticInfoDirModel::TagsRole)); for (const QString &tag : tagSet) { TagHash::Iterator it = tagHash.find(tag); if (it == tagHash.end()) { tagHash[tag] = 1; } else { ++it.value(); } } first = false; } { SignalBlocker blocker(d->mRatingWidget); d->mRatingWidget->setRating(rating); } d->mDescriptionTextEdit->setText(description); // Init tagInfo from tagHash d->mTagInfo.clear(); int itemCount = itemList.count(); TagHash::ConstIterator it = tagHash.constBegin(), end = tagHash.constEnd(); for (; it != end; ++it) { QString tag = it.key(); int count = it.value(); d->mTagInfo[tag] = count == itemCount; } bool enabled = !contextManager()->selectedFileItemList().isEmpty(); for (QAction *action : qAsConst(d->mActions)) { action->setEnabled(enabled); } d->updateTags(); if (d->mSemanticInfoDialog) { d->updateSemanticInfoDialog(); } } void SemanticInfoContextManagerItem::slotRatingChanged(int rating) { const KFileItemList itemList = contextManager()->selectedFileItemList(); // Show rating indicator in view mode, and only if sidebar is not visible if (d->mViewMainPage->isVisible() && !d->mRatingWidget->isVisible()) { if (!d->mRatingIndicator.data()) { d->mRatingIndicator = new RatingIndicator; d->mViewMainPage->showMessageWidget(d->mRatingIndicator, Qt::AlignBottom | Qt::AlignHCenter); } d->mRatingIndicator->setRating(rating); } SortedDirModel *dirModel = contextManager()->dirModel(); for (const KFileItem &item : itemList) { QModelIndex index = dirModel->indexForItem(item); dirModel->setData(index, rating, SemanticInfoDirModel::RatingRole); } } void SemanticInfoContextManagerItem::storeDescription() { if (!d->mDescriptionTextEdit->document()->isModified()) { return; } d->mDescriptionTextEdit->document()->setModified(false); QString description = d->mDescriptionTextEdit->toPlainText(); const KFileItemList itemList = contextManager()->selectedFileItemList(); SortedDirModel *dirModel = contextManager()->dirModel(); for (const KFileItem &item : itemList) { QModelIndex index = dirModel->indexForItem(item); dirModel->setData(index, description, SemanticInfoDirModel::DescriptionRole); } } void SemanticInfoContextManagerItem::assignTag(const SemanticInfoTag &tag) { const KFileItemList itemList = contextManager()->selectedFileItemList(); SortedDirModel *dirModel = contextManager()->dirModel(); for (const KFileItem &item : itemList) { QModelIndex index = dirModel->indexForItem(item); TagSet tags = TagSet::fromVariant(dirModel->data(index, SemanticInfoDirModel::TagsRole)); if (!tags.contains(tag)) { tags << tag; dirModel->setData(index, tags.toVariant(), SemanticInfoDirModel::TagsRole); } } } void SemanticInfoContextManagerItem::removeTag(const SemanticInfoTag &tag) { const KFileItemList itemList = contextManager()->selectedFileItemList(); SortedDirModel *dirModel = contextManager()->dirModel(); for (const KFileItem &item : itemList) { QModelIndex index = dirModel->indexForItem(item); TagSet tags = TagSet::fromVariant(dirModel->data(index, SemanticInfoDirModel::TagsRole)); if (tags.contains(tag)) { tags.remove(tag); dirModel->setData(index, tags.toVariant(), SemanticInfoDirModel::TagsRole); } } } void SemanticInfoContextManagerItem::showSemanticInfoDialog() { if (!d->mSemanticInfoDialog) { d->mSemanticInfoDialog = new SemanticInfoDialog(d->mGroup); d->mSemanticInfoDialog->setAttribute(Qt::WA_DeleteOnClose, true); connect(d->mSemanticInfoDialog->mPreviousButton, &QAbstractButton::clicked, d->mActionCollection->action(QStringLiteral("go_previous")), &QAction::trigger); connect(d->mSemanticInfoDialog->mNextButton, &QAbstractButton::clicked, d->mActionCollection->action(QStringLiteral("go_next")), &QAction::trigger); connect(d->mSemanticInfoDialog->mButtonBox, &QDialogButtonBox::rejected, d->mSemanticInfoDialog.data(), &QWidget::close); AbstractSemanticInfoBackEnd *backEnd = contextManager()->dirModel()->semanticInfoBackEnd(); d->mSemanticInfoDialog->mTagWidget->setSemanticInfoBackEnd(backEnd); connect(d->mSemanticInfoDialog->mTagWidget, &TagWidget::tagAssigned, this, &SemanticInfoContextManagerItem::assignTag); connect(d->mSemanticInfoDialog->mTagWidget, &TagWidget::tagRemoved, this, &SemanticInfoContextManagerItem::removeTag); } d->updateSemanticInfoDialog(); d->mSemanticInfoDialog->show(); } bool SemanticInfoContextManagerItem::eventFilter(QObject *, QEvent *event) { if (event->type() == QEvent::FocusOut) { storeDescription(); } return false; } } // namespace #include "moc_semanticinfocontextmanageritem.cpp"
16,553
C++
.cpp
412
33.444175
156
0.680291
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,887
gvcore.cpp
KDE_gwenview/app/gvcore.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "gvcore.h" // Qt #include <QApplication> #include <QHBoxLayout> #include <QImageWriter> #include <QLabel> #include <QMimeDatabase> #include <QSpacerItem> #include <QSpinBox> #include <QUrl> // KF #include <KColorScheme> #include <KColorUtils> #include <KFileCustomDialog> #include <KFileWidget> #include <KLocalizedString> #include <KMessageBox> // Local #include "gwenview_app_debug.h" #include <lib/binder.h> #include <lib/document/documentfactory.h> #include <lib/document/documentjob.h> #include <lib/document/savejob.h> #include <lib/gwenviewconfig.h> #include <lib/historymodel.h> #include <lib/hud/hudbutton.h> #include <lib/hud/hudmessagebubble.h> #include <lib/mimetypeutils.h> #include <lib/recentfilesmodel.h> #include <lib/semanticinfo/semanticinfodirmodel.h> #include <lib/semanticinfo/sorteddirmodel.h> #include <lib/transformimageoperation.h> #include <mainwindow.h> #include <saveallhelper.h> #include <viewmainpage.h> namespace Gwenview { struct GvCorePrivate { GvCore *q = nullptr; MainWindow *mMainWindow = nullptr; SortedDirModel *mDirModel = nullptr; HistoryModel *mRecentFoldersModel = nullptr; RecentFilesModel *mRecentFilesModel = nullptr; QPalette mPalettes[4]; QString mFullScreenPaletteName; int configFileJPEGQualityValue = GwenviewConfig::jPEGQuality(); KFileCustomDialog *createSaveAsDialog(const QUrl &url) { // Build the JPEG quality chooser custom widget auto JPEGQualityChooserWidget = new QWidget; JPEGQualityChooserWidget->setVisible(false); // shown only for JPEGs auto JPEGQualityChooserLabel = new QLabel; JPEGQualityChooserLabel->setText(i18n("Image quality:")); JPEGQualityChooserLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); auto JPEGQualityChooserSpinBox = new QSpinBox; JPEGQualityChooserSpinBox->setMinimum(1); JPEGQualityChooserSpinBox->setMaximum(100); JPEGQualityChooserSpinBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); JPEGQualityChooserSpinBox->setSuffix(i18nc("Spinbox suffix; percentage 1 - 100", "%")); configFileJPEGQualityValue = GwenviewConfig::jPEGQuality(); JPEGQualityChooserSpinBox->setValue(configFileJPEGQualityValue); // Temporarily change JPEG quality value QObject::connect(JPEGQualityChooserSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), JPEGQualityChooserSpinBox, [=](int value) { GwenviewConfig::setJPEGQuality(value); }); auto horizontalSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed); auto JPEGQualityChooserLayout = new QHBoxLayout(JPEGQualityChooserWidget); JPEGQualityChooserLayout->setContentsMargins(0, 0, 0, 0); JPEGQualityChooserLayout->addWidget(JPEGQualityChooserLabel); JPEGQualityChooserLayout->addWidget(JPEGQualityChooserSpinBox); JPEGQualityChooserLayout->addItem(horizontalSpacer); // Set up the dialog auto dialog = new KFileCustomDialog(mMainWindow); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); KFileWidget *fileWidget = dialog->fileWidget(); dialog->setCustomWidget(JPEGQualityChooserWidget); fileWidget->setConfirmOverwrite(true); dialog->setOperationMode(KFileWidget::Saving); dialog->setWindowTitle(i18nc("@title:window", "Save Image")); // Temporary workaround for selectUrl() not setting the // initial directory to url (removed in D4193) dialog->setUrl(url.adjusted(QUrl::RemoveFilename)); fileWidget->setSelectedUrl(url); QList<KFileFilter> filters; for (const QByteArray &mimeName : QImageWriter::supportedMimeTypes()) { filters << KFileFilter::fromMimeType(mimeName); } fileWidget->setFilters(filters, KFileFilter::fromMimeType(MimeTypeUtils::urlMimeType(url))); // Only show the lossy image quality chooser when saving a lossy image QObject::connect(fileWidget, &KFileWidget::filterChanged, JPEGQualityChooserWidget, [=](const KFileFilter &filter) { const bool hasQuality = std::any_of(filter.mimePatterns().constBegin(), filter.mimePatterns().constEnd(), [](const QString &mime) { return mime.contains(QLatin1String("jpeg")) || mime.contains(QLatin1String("jxl")) || mime.contains(QLatin1String("webp")) || mime.contains(QLatin1String("avif")) || mime.contains(QLatin1String("heif")) || mime.contains(QLatin1String("heic")); }); JPEGQualityChooserWidget->setVisible(hasQuality); }); return dialog; } void setupPalettes() { // Normal KSharedConfigPtr config = KSharedConfig::openConfig(); mPalettes[GvCore::NormalPalette] = KColorScheme::createApplicationPalette(config); QPalette viewPalette = mPalettes[GvCore::NormalPalette]; DocumentView::BackgroundColorMode colorMode = GwenviewConfig::backgroundColorMode(); const bool usingLightTheme = qApp->palette().base().color().lightness() > qApp->palette().text().color().lightness(); if ((usingLightTheme && colorMode == DocumentView::BackgroundColorMode::Dark) || (!usingLightTheme && colorMode == DocumentView::BackgroundColorMode::Light)) { viewPalette.setColor(QPalette::Base, mPalettes[GvCore::NormalPalette].color(QPalette::Text)); viewPalette.setColor(QPalette::Text, mPalettes[GvCore::NormalPalette].color(QPalette::Base)); viewPalette.setColor(QPalette::Window, mPalettes[GvCore::NormalPalette].color(QPalette::WindowText)); viewPalette.setColor(QPalette::WindowText, mPalettes[GvCore::NormalPalette].color(QPalette::Window)); viewPalette.setColor(QPalette::Button, mPalettes[GvCore::NormalPalette].color(QPalette::ButtonText)); viewPalette.setColor(QPalette::ButtonText, mPalettes[GvCore::NormalPalette].color(QPalette::Button)); viewPalette.setColor(QPalette::ToolTipBase, mPalettes[GvCore::NormalPalette].color(QPalette::ToolTipText)); viewPalette.setColor(QPalette::ToolTipText, mPalettes[GvCore::NormalPalette].color(QPalette::ToolTipBase)); } else if (colorMode == DocumentView::BackgroundColorMode::Neutral) { QColor base = KColorUtils::mix(mPalettes[GvCore::NormalPalette].color(QPalette::Base), mPalettes[GvCore::NormalPalette].color(QPalette::Text), 0.5); QColor window = KColorUtils::mix(mPalettes[GvCore::NormalPalette].color(QPalette::Window), mPalettes[GvCore::NormalPalette].color(QPalette::WindowText), 0.5); QColor button = KColorUtils::mix(mPalettes[GvCore::NormalPalette].color(QPalette::Button), mPalettes[GvCore::NormalPalette].color(QPalette::ButtonText), 0.5); QColor toolTipBase = KColorUtils::mix(mPalettes[GvCore::NormalPalette].color(QPalette::ToolTipBase), mPalettes[GvCore::NormalPalette].color(QPalette::ToolTipText), 0.5); viewPalette.setColor(QPalette::Base, base); viewPalette.setColor(QPalette::Text, base.lightnessF() > 0.5 ? Qt::black : Qt::white); viewPalette.setColor(QPalette::Window, window); viewPalette.setColor(QPalette::WindowText, base.lightnessF() > 0.5 ? Qt::black : Qt::white); viewPalette.setColor(QPalette::Button, button); viewPalette.setColor(QPalette::ButtonText, base.lightnessF() > 0.5 ? Qt::black : Qt::white); viewPalette.setColor(QPalette::ToolTipBase, toolTipBase); viewPalette.setColor(QPalette::ToolTipText, base.lightnessF() > 0.5 ? Qt::black : Qt::white); } mPalettes[GvCore::NormalViewPalette] = viewPalette; // Fullscreen QString name = GwenviewConfig::fullScreenColorScheme(); if (name.isEmpty()) { // Default color scheme mFullScreenPaletteName = QStandardPaths::locate(QStandardPaths::AppDataLocation, QStringLiteral("color-schemes/fullscreen.colors")); config = KSharedConfig::openConfig(mFullScreenPaletteName); } else if (name.contains('/')) { // Full path to a .colors file mFullScreenPaletteName = name; config = KSharedConfig::openConfig(mFullScreenPaletteName); } else { // Standard KDE color scheme mFullScreenPaletteName = QStringLiteral("color-schemes/%1.colors").arg(name); config = KSharedConfig::openConfig(mFullScreenPaletteName, KConfig::FullConfig, QStandardPaths::AppDataLocation); } mPalettes[GvCore::FullScreenPalette] = KColorScheme::createApplicationPalette(config); // If we are using the default palette, adjust it to match the system color scheme if (name.isEmpty()) { adjustDefaultFullScreenPalette(); } // FullScreenView has either a solid black color or a textured background viewPalette = mPalettes[GvCore::FullScreenPalette]; QPixmap bgTexture(256, 256); if (Gwenview::GwenviewConfig::fullScreenBackground() == Gwenview::FullScreenBackground::Black) { bgTexture.fill(Qt::black); } else { QString path = QStandardPaths::locate(QStandardPaths::AppDataLocation, QStringLiteral("images/background.png")); bgTexture = path; } viewPalette.setBrush(QPalette::Base, bgTexture); mPalettes[GvCore::FullScreenViewPalette] = viewPalette; } void adjustDefaultFullScreenPalette() { // The Fullscreen palette by default does not use the system color scheme, and therefore uses an 'accent' color // of blue. So for every color group/role combination that uses the accent color, we use a muted version of the // Normal palette. We also use the normal HighlightedText color so it properly contrasts with Highlight. const QPalette normalPal = mPalettes[GvCore::NormalPalette]; QPalette fullscreenPal = mPalettes[GvCore::FullScreenPalette]; // Colors from the normal palette (source of the system theme's accent color) const QColor normalToolTipBase = normalPal.color(QPalette::Normal, QPalette::ToolTipBase); const QColor normalToolTipText = normalPal.color(QPalette::Normal, QPalette::ToolTipText); const QColor normalHighlight = normalPal.color(QPalette::Normal, QPalette::Highlight); const QColor normalHighlightedText = normalPal.color(QPalette::Normal, QPalette::HighlightedText); const QColor normalLink = normalPal.color(QPalette::Normal, QPalette::Link); const QColor normalActiveToolTipBase = normalPal.color(QPalette::Active, QPalette::ToolTipBase); const QColor normalActiveToolTipText = normalPal.color(QPalette::Active, QPalette::ToolTipText); const QColor normalActiveHighlight = normalPal.color(QPalette::Active, QPalette::Highlight); const QColor normalActiveHighlightedText = normalPal.color(QPalette::Active, QPalette::HighlightedText); const QColor normalActiveLink = normalPal.color(QPalette::Active, QPalette::Link); const QColor normalDisabledToolTipBase = normalPal.color(QPalette::Disabled, QPalette::ToolTipBase); const QColor normalDisabledToolTipText = normalPal.color(QPalette::Disabled, QPalette::ToolTipText); // Note: Disabled Highlight missing as they do not use the accent color const QColor normalDisabledLink = normalPal.color(QPalette::Disabled, QPalette::Link); const QColor normalInactiveToolTipBase = normalPal.color(QPalette::Inactive, QPalette::ToolTipBase); const QColor normalInactiveToolTipText = normalPal.color(QPalette::Inactive, QPalette::ToolTipText); const QColor normalInactiveHighlight = normalPal.color(QPalette::Inactive, QPalette::Highlight); const QColor normalInactiveHighlightedText = normalPal.color(QPalette::Inactive, QPalette::HighlightedText); const QColor normalInactiveLink = normalPal.color(QPalette::Inactive, QPalette::Link); // Colors of the fullscreen palette which we will be modifying QColor fullScreenToolTipBase = fullscreenPal.color(QPalette::Normal, QPalette::ToolTipBase); QColor fullScreenToolTipText = fullscreenPal.color(QPalette::Normal, QPalette::ToolTipText); QColor fullScreenHighlight = fullscreenPal.color(QPalette::Normal, QPalette::Highlight); QColor fullScreenLink = fullscreenPal.color(QPalette::Normal, QPalette::Link); QColor fullScreenActiveToolTipBase = fullscreenPal.color(QPalette::Active, QPalette::ToolTipBase); QColor fullScreenActiveToolTipText = fullscreenPal.color(QPalette::Active, QPalette::ToolTipText); QColor fullScreenActiveHighlight = fullscreenPal.color(QPalette::Active, QPalette::Highlight); QColor fullScreenActiveLink = fullscreenPal.color(QPalette::Active, QPalette::Link); QColor fullScreenDisabledToolTipBase = fullscreenPal.color(QPalette::Disabled, QPalette::ToolTipBase); QColor fullScreenDisabledToolTipText = fullscreenPal.color(QPalette::Disabled, QPalette::ToolTipText); QColor fullScreenDisabledLink = fullscreenPal.color(QPalette::Disabled, QPalette::Link); QColor fullScreenInactiveToolTipBase = fullscreenPal.color(QPalette::Inactive, QPalette::ToolTipBase); QColor fullScreenInactiveToolTipText = fullscreenPal.color(QPalette::Inactive, QPalette::ToolTipText); QColor fullScreenInactiveHighlight = fullscreenPal.color(QPalette::Inactive, QPalette::Highlight); QColor fullScreenInactiveLink = fullscreenPal.color(QPalette::Inactive, QPalette::Link); // Adjust the value of the normal color so it's not too dark/bright, and apply to the respective fullscreen color fullScreenToolTipBase.setHsv(normalToolTipBase.hue(), normalToolTipBase.saturation(), (127 + 2 * normalToolTipBase.value()) / 3); fullScreenToolTipText.setHsv(normalToolTipText.hue(), normalToolTipText.saturation(), (127 + 2 * normalToolTipText.value()) / 3); fullScreenHighlight.setHsv(normalHighlight.hue(), normalHighlight.saturation(), (127 + 2 * normalHighlight.value()) / 3); fullScreenLink.setHsv(normalLink.hue(), normalLink.saturation(), (127 + 2 * normalLink.value()) / 3); fullScreenActiveToolTipBase.setHsv(normalActiveToolTipBase.hue(), normalActiveToolTipBase.saturation(), (127 + 2 * normalActiveToolTipBase.value()) / 3); fullScreenActiveToolTipText.setHsv(normalActiveToolTipText.hue(), normalActiveToolTipText.saturation(), (127 + 2 * normalActiveToolTipText.value()) / 3); fullScreenActiveHighlight.setHsv(normalActiveHighlight.hue(), normalActiveHighlight.saturation(), (127 + 2 * normalActiveHighlight.value()) / 3); fullScreenActiveLink.setHsv(normalActiveLink.hue(), normalActiveLink.saturation(), (127 + 2 * normalActiveLink.value()) / 3); fullScreenDisabledToolTipBase.setHsv(normalDisabledToolTipBase.hue(), normalDisabledToolTipBase.saturation(), (127 + 2 * normalDisabledToolTipBase.value()) / 3); fullScreenDisabledToolTipText.setHsv(normalDisabledToolTipText.hue(), normalDisabledToolTipText.saturation(), (127 + 2 * normalDisabledToolTipText.value()) / 3); fullScreenDisabledLink.setHsv(normalDisabledLink.hue(), normalDisabledLink.saturation(), (127 + 2 * normalDisabledLink.value()) / 3); fullScreenInactiveToolTipBase.setHsv(normalInactiveToolTipBase.hue(), normalInactiveToolTipBase.saturation(), (127 + 2 * normalInactiveToolTipBase.value()) / 3); fullScreenInactiveToolTipText.setHsv(normalInactiveToolTipText.hue(), normalInactiveToolTipText.saturation(), (127 + 2 * normalInactiveToolTipText.value()) / 3); fullScreenInactiveHighlight.setHsv(normalInactiveHighlight.hue(), normalInactiveHighlight.saturation(), (127 + 2 * normalInactiveHighlight.value()) / 3); fullScreenInactiveLink.setHsv(normalInactiveLink.hue(), normalInactiveLink.saturation(), (127 + 2 * normalInactiveLink.value()) / 3); // Apply the modified colors to the fullscreen palette fullscreenPal.setColor(QPalette::Normal, QPalette::ToolTipBase, fullScreenToolTipBase); fullscreenPal.setColor(QPalette::Normal, QPalette::ToolTipText, fullScreenToolTipText); fullscreenPal.setColor(QPalette::Normal, QPalette::Highlight, fullScreenHighlight); fullscreenPal.setColor(QPalette::Normal, QPalette::Link, fullScreenLink); fullscreenPal.setColor(QPalette::Active, QPalette::ToolTipBase, fullScreenActiveToolTipBase); fullscreenPal.setColor(QPalette::Active, QPalette::ToolTipText, fullScreenActiveToolTipText); fullscreenPal.setColor(QPalette::Active, QPalette::Highlight, fullScreenActiveHighlight); fullscreenPal.setColor(QPalette::Active, QPalette::Link, fullScreenActiveLink); fullscreenPal.setColor(QPalette::Disabled, QPalette::ToolTipBase, fullScreenDisabledToolTipBase); fullscreenPal.setColor(QPalette::Disabled, QPalette::ToolTipText, fullScreenDisabledToolTipText); fullscreenPal.setColor(QPalette::Disabled, QPalette::Link, fullScreenDisabledLink); fullscreenPal.setColor(QPalette::Inactive, QPalette::ToolTipBase, fullScreenInactiveToolTipBase); fullscreenPal.setColor(QPalette::Inactive, QPalette::ToolTipText, fullScreenInactiveToolTipText); fullscreenPal.setColor(QPalette::Inactive, QPalette::Highlight, fullScreenInactiveHighlight); fullscreenPal.setColor(QPalette::Inactive, QPalette::Link, fullScreenInactiveLink); // Since we use an adjusted version of the normal highlight color, we need to use the normal version of the // text color so it contrasts fullscreenPal.setColor(QPalette::Normal, QPalette::HighlightedText, normalHighlightedText); fullscreenPal.setColor(QPalette::Active, QPalette::HighlightedText, normalActiveHighlightedText); fullscreenPal.setColor(QPalette::Inactive, QPalette::HighlightedText, normalInactiveHighlightedText); mPalettes[GvCore::FullScreenPalette] = fullscreenPal; } }; GvCore::GvCore(MainWindow *mainWindow, SortedDirModel *dirModel) : QObject(mainWindow) , d(new GvCorePrivate) { d->q = this; d->mMainWindow = mainWindow; d->mDirModel = dirModel; d->mRecentFoldersModel = nullptr; d->mRecentFilesModel = nullptr; d->setupPalettes(); connect(GwenviewConfig::self(), SIGNAL(configChanged()), SLOT(slotConfigChanged())); connect(qApp, &QApplication::paletteChanged, this, [this]() { d->setupPalettes(); }); } GvCore::~GvCore() { delete d; } QAbstractItemModel *GvCore::recentFoldersModel() const { if (!d->mRecentFoldersModel) { d->mRecentFoldersModel = new HistoryModel(const_cast<GvCore *>(this), QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/recentfolders/"); } return d->mRecentFoldersModel; } QAbstractItemModel *GvCore::recentFilesModel() const { if (!d->mRecentFilesModel) { d->mRecentFilesModel = new RecentFilesModel(const_cast<GvCore *>(this)); } return d->mRecentFilesModel; } AbstractSemanticInfoBackEnd *GvCore::semanticInfoBackEnd() const { return d->mDirModel->semanticInfoBackEnd(); } SortedDirModel *GvCore::sortedDirModel() const { return d->mDirModel; } void GvCore::addUrlToRecentFolders(QUrl url) { if (!GwenviewConfig::historyEnabled()) { return; } if (!url.isValid()) { return; } // For "sftp://localhost", "/" is a different path than "" (bug #312060) if (!url.path().isEmpty() && !url.path().endsWith('/')) { url.setPath(url.path() + '/'); } recentFoldersModel(); d->mRecentFoldersModel->addUrl(url); } void GvCore::addUrlToRecentFiles(const QUrl &url) { if (!GwenviewConfig::historyEnabled()) { return; } recentFilesModel(); d->mRecentFilesModel->addUrl(url); } void GvCore::saveAll() { SaveAllHelper helper(d->mMainWindow); helper.save(); } void GvCore::save(const QUrl &url) { Document::Ptr doc = DocumentFactory::instance()->load(url); QByteArray format = doc->format(); const QByteArrayList availableTypes = QImageWriter::supportedImageFormats(); if (availableTypes.contains(format)) { DocumentJob *job = doc->save(url, format); connect(job, SIGNAL(result(KJob *)), SLOT(slotSaveResult(KJob *))); } else { // We don't know how to save in 'format', ask the user for a format we can // write to. KGuiItem saveUsingAnotherFormat = KStandardGuiItem::saveAs(); saveUsingAnotherFormat.setText(i18n("Save using another format")); int result = KMessageBox::warningContinueCancel(d->mMainWindow, i18n("Gwenview cannot save images in '%1' format.", QString(format)), QString() /* caption */, saveUsingAnotherFormat); if (result == KMessageBox::Continue) { saveAs(url); } } } void GvCore::saveAs(const QUrl &url) { KFileCustomDialog *dialog = d->createSaveAsDialog(url); connect(dialog, &QDialog::accepted, this, [=]() { KFileWidget *fileWidget = dialog->fileWidget(); const QList<QUrl> files = fileWidget->selectedUrls(); if (files.isEmpty()) { return; } const QString filename = files.at(0).fileName(); const QMimeType mimeType = QMimeDatabase().mimeTypeForFile(filename, QMimeDatabase::MatchExtension); QByteArray format; if (mimeType.isValid()) { format = mimeType.preferredSuffix().toLocal8Bit(); } else { KMessageBox::error(d->mMainWindow, i18nc("@info", "Gwenview cannot save images as %1.", QFileInfo(filename).suffix())); } QUrl saveAsUrl = fileWidget->selectedUrls().constFirst(); if (format == "jpg") { // Gwenview code assumes JPEG images have "jpeg" format, so if the // dialog returned the format "jpg", use "jpeg" instead // This does not affect the actual filename extension format = "jpeg"; } // Start save Document::Ptr doc = DocumentFactory::instance()->load(url); KJob *job = doc->save(saveAsUrl, format); if (!job) { const QString saveName = saveAsUrl.fileName(); const QString name = !saveName.isEmpty() ? saveName : saveAsUrl.toDisplayString(); const QString msg = xi18nc("@info", "<emphasis strong='true'>Saving <filename>%1</filename> failed:</emphasis><nl />%2", name, doc->errorString()); KMessageBox::error(QApplication::activeWindow(), msg); } else { // Regardless of job result, reset JPEG config value if it was changed by // the Save As dialog connect(job, &KJob::result, this, [=]() { if (GwenviewConfig::jPEGQuality() != d->configFileJPEGQualityValue) { GwenviewConfig::setJPEGQuality(d->configFileJPEGQualityValue); } }); connect(job, &KJob::result, this, &GvCore::slotSaveResult); } }); dialog->show(); } static void applyTransform(const QUrl &url, Orientation orientation) { auto op = new TransformImageOperation(orientation); Document::Ptr doc = DocumentFactory::instance()->load(url); op->applyToDocument(doc); } void GvCore::slotSaveResult(KJob *_job) { auto job = static_cast<SaveJob *>(_job); QUrl oldUrl = job->oldUrl(); QUrl newUrl = job->newUrl(); if (job->error()) { QString name = newUrl.fileName().isEmpty() ? newUrl.toDisplayString() : newUrl.fileName(); const QString msg = xi18nc("@info", "<emphasis strong='true'>Saving <filename>%1</filename> failed:</emphasis><nl />%2", name, kxi18n(qPrintable(job->errorString()))); int result = KMessageBox::warningContinueCancel(d->mMainWindow, msg, QString() /* caption */, KStandardGuiItem::saveAs()); if (result == KMessageBox::Continue) { saveAs(oldUrl); } return; } if (oldUrl != newUrl) { d->mMainWindow->goToUrl(newUrl); ViewMainPage *page = d->mMainWindow->viewMainPage(); if (page->isVisible()) { auto bubble = new HudMessageBubble(); bubble->setText(i18n("You are now viewing the new document.")); KGuiItem item = KStandardGuiItem::back(); item.setText(i18n("Go back to the original")); HudButton *button = bubble->addButton(item); BinderRef<MainWindow, QUrl>::bind(button, SIGNAL(clicked()), d->mMainWindow, &MainWindow::goToUrl, oldUrl); connect(button, SIGNAL(clicked()), bubble, SLOT(deleteLater())); page->showMessageWidget(bubble); } } } void GvCore::rotateLeft(const QUrl &url) { applyTransform(url, ROT_270); } void GvCore::rotateRight(const QUrl &url) { applyTransform(url, ROT_90); } void GvCore::setRating(const QUrl &url, int rating) { QModelIndex index = d->mDirModel->indexForUrl(url); if (!index.isValid()) { qCWarning(GWENVIEW_APP_LOG) << "invalid index!"; return; } d->mDirModel->setData(index, rating, SemanticInfoDirModel::RatingRole); } static void clearModel(QAbstractItemModel *model) { model->removeRows(0, model->rowCount()); } void GvCore::clearRecentFilesAndFolders() { clearModel(recentFilesModel()); clearModel(recentFoldersModel()); } void GvCore::slotConfigChanged() { if (!GwenviewConfig::historyEnabled()) { clearRecentFilesAndFolders(); } d->setupPalettes(); } QPalette GvCore::palette(GvCore::PaletteType type) const { return d->mPalettes[type]; } QString GvCore::fullScreenPaletteName() const { return d->mFullScreenPaletteName; } void GvCore::setTrackFileManagerSorting(bool enable) { sortingTracksFileManager = enable; } bool GvCore::trackFileManagerSorting() { return sortingTracksFileManager; } } // namespace #include "moc_gvcore.cpp"
27,843
C++
.cpp
506
46.462451
160
0.693976
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,888
main.cpp
KDE_gwenview/app/main.cpp
/* Gwenview: an image viewer Copyright 2007-2012 Aurélien Gâteau <agateau@kde.org> 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 <config-gwenview.h> // Qt #include <QApplication> #include <QCommandLineParser> #include <QPointer> #include <QScopedPointer> #include <QStringList> #include <QTemporaryDir> #include <QUrl> // KF #include <KAboutData> #include <KActionCollection> #include <KCrash> #include <KIO/CopyJob> #include <KLocalizedString> // Local #include "mainwindow.h" #include <lib/about.h> #include <lib/gwenviewconfig.h> #ifdef HAVE_FITS // This hack is needed to include the fitsplugin moc file in main.cpp // Otherwise the linker complains about: undefined reference to `qt_static_plugin_FitsPlugin()' // This symbol is defined in the moc file, but it is not a visible symbol after libgwenview is linked. // If Q_IMPORT_PLUGIN(FitsPlugin) is moved to the library, gwenview crashes on the first call to FitsPlugin() // when the vtable is looked up in the plugin registration. #include <../lib/imageformats/moc_fitsplugin.cpp> #endif // To shut up libtiff #ifdef HAVE_TIFF #include <QLoggingCategory> #include <tiffio.h> namespace { Q_DECLARE_LOGGING_CATEGORY(LibTiffLog) Q_LOGGING_CATEGORY(LibTiffLog, "gwenview.libtiff", QtWarningMsg) static void handleTiffWarning(const char *mod, const char *fmt, va_list ap) { qCDebug(LibTiffLog) << "Warning:" << mod << QString::vasprintf(fmt, ap); } static void handleTiffError(const char *mod, const char *fmt, va_list ap) { // Since we're doing thumbnails, we don't really care about warnings by default either qCWarning(LibTiffLog) << "Error" << mod << QString::vasprintf(fmt, ap); } } // namespace #endif // To enable AVIF/HEIF/JPEG-XL metadata support in Exiv2 #include <exiv2/exiv2.hpp> #ifdef KIMAGEANNOTATOR_FOUND #include <kImageAnnotator/KImageAnnotator.h> #endif class StartHelper { public: StartHelper(const QStringList &args, bool fullscreen, bool slideshow, bool spotlightmode) : mFullScreen(false) , mSlideShow(false) , mSpotlightMode(false) { if (!args.isEmpty()) { parseArgs(args, fullscreen, slideshow, spotlightmode); } } void parseArgs(const QStringList &args, bool fullscreen, bool slideshow, bool spotlightmode) { if (args.count() > 1) { // Create a temp dir containing links to url args mMultipleUrlsDir.reset(new QTemporaryDir); mUrl = QUrl::fromLocalFile(mMultipleUrlsDir->path()); QList<QUrl> list; QStringList tmpArgs = args; tmpArgs.removeDuplicates(); QStringList fileNames; for (const QString &url : qAsConst(tmpArgs)) { QUrl fileUrl = QUrl::fromUserInput(url, QDir::currentPath(), QUrl::AssumeLocalFile); if (!fileNames.contains(fileUrl.fileName())) { fileNames << fileUrl.fileName(); list << fileUrl; } } KIO::CopyJob *job = KIO::link(list, mUrl); job->exec(); } else { QString tmpArg = args.first(); mUrl = QUrl::fromUserInput(tmpArg, QDir::currentPath(), QUrl::AssumeLocalFile); } if (mUrl.isValid() && (fullscreen || slideshow)) { mFullScreen = true; if (slideshow) { mSlideShow = true; } } if (mUrl.isValid() && spotlightmode) { mSpotlightMode = true; } } void createMainWindow() { mMainWindow = new Gwenview::MainWindow(); if (mUrl.isValid()) { mMainWindow->setInitialUrl(mUrl); } else { mMainWindow->showStartMainPage(); } mMainWindow->show(); if (mFullScreen) { mMainWindow->actionCollection()->action(QStringLiteral("fullscreen"))->trigger(); } else if (mSpotlightMode) { mMainWindow->actionCollection()->action(QStringLiteral("view_toggle_spotlightmode"))->trigger(); } if (mSlideShow) { mMainWindow->startSlideShow(); } } private: QUrl mUrl; bool mFullScreen; bool mSlideShow; bool mSpotlightMode; QScopedPointer<QTemporaryDir> mMultipleUrlsDir; QPointer<Gwenview::MainWindow> mMainWindow; }; int main(int argc, char *argv[]) { // enable AVIF/HEIF/JPEG-XL metadata support #ifdef EXV_ENABLE_BMFF Exiv2::enableBMFF(true); #endif #ifdef HAVE_TIFF TIFFSetWarningHandler(handleTiffWarning); TIFFSetErrorHandler(handleTiffError); #endif /** * enable high dpi support */ QCoreApplication::setAttribute(Qt::AA_CompressHighFrequencyEvents, true); QApplication app(argc, argv); KLocalizedString::setApplicationDomain("gwenview"); QScopedPointer<KAboutData> aboutData(Gwenview::createAboutData(QStringLiteral("gwenview"), /* component name */ i18n("Gwenview") /* display name */ )); aboutData->setShortDescription(i18n("An Image Viewer")); aboutData->setOrganizationDomain(QByteArray("kde.org")); KAboutData::setApplicationData(*aboutData); QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("gwenview"), app.windowIcon())); KCrash::initialize(); QCommandLineParser parser; aboutData.data()->setupCommandLine(&parser); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("f") << QStringLiteral("fullscreen"), i18n("Start in fullscreen mode"))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("s") << QStringLiteral("slideshow"), i18n("Start in slideshow mode"))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("m") << QStringLiteral("spotlight"), i18n("Start in spotlight mode"))); parser.addPositionalArgument("url", i18n("A starting file or folders")); parser.process(app); aboutData.data()->processCommandLine(&parser); // startHelper must live for the whole life of the application StartHelper startHelper(parser.positionalArguments(), parser.isSet(QStringLiteral("f")) ? true : Gwenview::GwenviewConfig::fullScreenModeActive(), parser.isSet(QStringLiteral("s")), parser.isSet(QStringLiteral("m")) ? true : Gwenview::GwenviewConfig::spotlightMode()); if (app.isSessionRestored()) { kRestoreMainWindows<Gwenview::MainWindow>(); } else { startHelper.createMainWindow(); } // Workaround for QTBUG-38613 // Another solution would be to port BalooSemanticInfoBackend::refreshAllTags // to be async rather than using exec(). qApp->sendPostedEvents(nullptr, QEvent::DeferredDelete); #ifdef KIMAGEANNOTATOR_FOUND kImageAnnotator::loadTranslations(); #endif return app.exec(); } #ifdef HAVE_FITS Q_IMPORT_PLUGIN(FitsPlugin) #endif
7,665
C++
.cpp
191
33.680628
145
0.682668
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,889
preloader.cpp
KDE_gwenview/app/preloader.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "preloader.h" // Qt // KF // Local #include "gwenview_app_debug.h" #include <lib/document/documentfactory.h> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_APP_LOG) << x #else #define LOG(x) ; #endif struct PreloaderPrivate { Preloader *q = nullptr; Document::Ptr mDocument; QSize mSize; void forgetDocument() { // Forget about the document. Keeping a reference to it would prevent it // from being garbage collected. QObject::disconnect(mDocument.data(), nullptr, q, nullptr); mDocument = nullptr; } }; Preloader::Preloader(QObject *parent) : QObject(parent) , d(new PreloaderPrivate) { d->q = this; } Preloader::~Preloader() { delete d; } void Preloader::preload(const QUrl &url, const QSize &size) { LOG("url=" << url); if (d->mDocument) { disconnect(d->mDocument.data(), nullptr, this, nullptr); } d->mDocument = DocumentFactory::instance()->load(url); d->mSize = size; connect(d->mDocument.data(), &Document::metaInfoUpdated, this, &Preloader::doPreload); if (d->mDocument->size().isValid()) { LOG("size is already available"); doPreload(); } } void Preloader::doPreload() { if (!d->mDocument) { return; } if (d->mDocument->loadingState() == Document::LoadingFailed) { LOG("loading failed"); d->forgetDocument(); return; } if (!d->mDocument->size().isValid()) { LOG("size not available yet"); return; } qreal zoom = qMin(d->mSize.width() / qreal(d->mDocument->width()), d->mSize.height() / qreal(d->mDocument->height())); if (zoom < Document::maxDownSampledZoom()) { LOG("preloading down sampled, zoom=" << zoom); d->mDocument->prepareDownSampledImageForZoom(zoom); } else { LOG("preloading full image"); d->mDocument->startLoadingFullImage(); } d->forgetDocument(); } } // namespace #include "moc_preloader.cpp"
2,895
C++
.cpp
95
26.568421
122
0.690202
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,890
documentinfoprovider.cpp
KDE_gwenview/app/documentinfoprovider.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "documentinfoprovider.h" // Qt #include <QPixmap> // KF // Local #include <lib/document/documentfactory.h> #include <lib/semanticinfo/sorteddirmodel.h> namespace Gwenview { DocumentInfoProvider::DocumentInfoProvider(SortedDirModel *model) : AbstractDocumentInfoProvider(model) , mDirModel(model) { connect(DocumentFactory::instance(), &DocumentFactory::documentBusyStateChanged, this, &AbstractDocumentInfoProvider::busyStateChanged); connect(DocumentFactory::instance(), &DocumentFactory::documentChanged, this, &AbstractDocumentInfoProvider::documentChanged); } void DocumentInfoProvider::thumbnailForDocument(const QUrl &url, ThumbnailGroup::Enum group, QPixmap *outPix, QSize *outFullSize) const { Q_ASSERT(outPix); Q_ASSERT(outFullSize); *outPix = QPixmap(); *outFullSize = QSize(); const int pixelSize = ThumbnailGroup::pixelSize(group); Document::Ptr doc = DocumentFactory::instance()->getCachedDocument(url); if (!doc) { return; } if (doc->loadingState() != Document::Loaded) { return; } QImage image = doc->image(); if (image.width() > pixelSize || image.height() > pixelSize) { image = image.scaled(pixelSize, pixelSize, Qt::KeepAspectRatio); } *outPix = QPixmap::fromImage(image); *outFullSize = doc->size(); } bool DocumentInfoProvider::isModified(const QUrl &url) { Document::Ptr doc = DocumentFactory::instance()->getCachedDocument(url); if (doc) { return doc->loadingState() == Document::Loaded && doc->isModified(); } else { return false; } } bool DocumentInfoProvider::isBusy(const QUrl &url) { Document::Ptr doc = DocumentFactory::instance()->getCachedDocument(url); if (doc) { return doc->isBusy(); } else { return false; } } } // namespace #include "moc_documentinfoprovider.cpp"
2,708
C++
.cpp
74
33.135135
140
0.74159
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,891
filtercontroller.cpp
KDE_gwenview/app/filtercontroller.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "filtercontroller.h" // Qt #include <QAction> #include <QCompleter> #include <QIcon> #include <QLabel> #include <QLineEdit> #include <QPainter> #include <QPainterPath> #include <QTimer> #include <QToolButton> // KF #include <KComboBox> #include <KIconLoader> #include <KLocalizedString> // Local #include "gwenview_app_debug.h" #include <chrono> #include <lib/flowlayout.h> #include <lib/paintutils.h> using namespace std::chrono_literals; #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE // KF // Local #endif namespace Gwenview { NameFilterWidget::NameFilterWidget(SortedDirModel *model) : mFilter(new NameFilter(model)) { mModeComboBox = new KComboBox; mModeComboBox->addItem(i18n("Name contains"), QVariant(NameFilter::Contains)); mModeComboBox->addItem(i18n("Name does not contain"), QVariant(NameFilter::DoesNotContain)); mLineEdit = new QLineEdit; auto layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(2); layout->addWidget(mModeComboBox); layout->addWidget(mLineEdit); auto timer = new QTimer(this); timer->setInterval(350ms); timer->setSingleShot(true); connect(timer, &QTimer::timeout, this, &NameFilterWidget::applyNameFilter); connect(mLineEdit, SIGNAL(textChanged(QString)), timer, SLOT(start())); connect(mModeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(applyNameFilter())); QTimer::singleShot(0, mLineEdit, SLOT(setFocus())); } NameFilterWidget::~NameFilterWidget() { delete mFilter; } void NameFilterWidget::applyNameFilter() { const QVariant data = mModeComboBox->itemData(mModeComboBox->currentIndex()); mFilter->setMode(NameFilter::Mode(data.toInt())); mFilter->setText(mLineEdit->text()); } DateFilterWidget::DateFilterWidget(SortedDirModel *model) : mFilter(new DateFilter(model)) { mModeComboBox = new KComboBox; mModeComboBox->addItem(i18n("Date >="), DateFilter::GreaterOrEqual); mModeComboBox->addItem(i18n("Date ="), DateFilter::Equal); mModeComboBox->addItem(i18n("Date <="), DateFilter::LessOrEqual); mDateWidget = new DateWidget; auto layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mModeComboBox); layout->addWidget(mDateWidget); connect(mDateWidget, &DateWidget::dateChanged, this, &DateFilterWidget::applyDateFilter); connect(mModeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(applyDateFilter())); applyDateFilter(); } DateFilterWidget::~DateFilterWidget() { delete mFilter; } void DateFilterWidget::applyDateFilter() { const QVariant data = mModeComboBox->itemData(mModeComboBox->currentIndex()); mFilter->setMode(DateFilter::Mode(data.toInt())); mFilter->setDate(mDateWidget->date()); } #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE RatingFilterWidget::RatingFilterWidget(SortedDirModel *model) { mModeComboBox = new KComboBox; mModeComboBox->addItem(i18n("Rating >="), RatingFilter::GreaterOrEqual); mModeComboBox->addItem(i18n("Rating ="), RatingFilter::Equal); mModeComboBox->addItem(i18n("Rating <="), RatingFilter::LessOrEqual); mRatingWidget = new KRatingWidget; mRatingWidget->setHalfStepsEnabled(true); mRatingWidget->setMaxRating(10); auto layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mModeComboBox); layout->addWidget(mRatingWidget); mFilter = new RatingFilter(model); QObject::connect(mModeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(updateFilterMode())); QObject::connect(mRatingWidget, SIGNAL(ratingChanged(int)), SLOT(slotRatingChanged(int))); updateFilterMode(); } RatingFilterWidget::~RatingFilterWidget() { delete mFilter; } void RatingFilterWidget::slotRatingChanged(int value) { mFilter->setRating(value); } void RatingFilterWidget::updateFilterMode() { const QVariant data = mModeComboBox->itemData(mModeComboBox->currentIndex()); mFilter->setMode(RatingFilter::Mode(data.toInt())); } TagFilterWidget::TagFilterWidget(SortedDirModel *model) : mFilter(new TagFilter(model)) { mModeComboBox = new KComboBox; mModeComboBox->addItem(i18n("Tagged"), QVariant(true)); mModeComboBox->addItem(i18n("Not Tagged"), QVariant(false)); mTagComboBox = new QComboBox; auto layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mModeComboBox); layout->addWidget(mTagComboBox); AbstractSemanticInfoBackEnd *backEnd = model->semanticInfoBackEnd(); backEnd->refreshAllTags(); TagModel *tagModel = TagModel::createAllTagsModel(this, backEnd); auto completer = new QCompleter(mTagComboBox); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setModel(tagModel); mTagComboBox->setCompleter(completer); mTagComboBox->setInsertPolicy(QComboBox::NoInsert); mTagComboBox->setEditable(true); mTagComboBox->setModel(tagModel); mTagComboBox->setCurrentIndex(-1); connect(mTagComboBox, SIGNAL(currentIndexChanged(int)), SLOT(updateTagSetFilter())); connect(mModeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(updateTagSetFilter())); QTimer::singleShot(0, mTagComboBox, SLOT(setFocus())); } TagFilterWidget::~TagFilterWidget() { delete mFilter; } void TagFilterWidget::updateTagSetFilter() { QModelIndex index = mTagComboBox->model()->index(mTagComboBox->currentIndex(), 0); if (!index.isValid()) { qCWarning(GWENVIEW_APP_LOG) << "Invalid index"; return; } SemanticInfoTag tag = index.data(TagModel::TagRole).toString(); mFilter->setTag(tag); bool wantMatchingTag = mModeComboBox->itemData(mModeComboBox->currentIndex()).toBool(); mFilter->setWantMatchingTag(wantMatchingTag); } #endif ImageDimensionsWidget::ImageDimensionsWidget(SortedDirModel *model) { mFilter = new ImageDimensions(model); mModeComboBox = new KComboBox; mModeComboBox->addItem(i18n("Dimensions >="), ImageDimensions::GreaterOrEqual); mModeComboBox->addItem(i18n("Dimensions ="), ImageDimensions::Equal); mModeComboBox->addItem(i18n("Dimensions <="), ImageDimensions::LessOrEqual); mLineEditHeight = new QLineEdit; mLineEditHeight->setValidator(new QIntValidator(ImageDimensions::minImageSizePx, ImageDimensions::maxImageSizePx, this)); mLineEditWidth = new QLineEdit; mLineEditWidth->setValidator(new QIntValidator(ImageDimensions::minImageSizePx, ImageDimensions::maxImageSizePx, this)); mLabelHeight = new QLabel; mLabelHeight->setText(i18n("Height")); mLabelWidth = new QLabel; mLabelWidth->setText(i18n("Width")); auto *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mModeComboBox); layout->addWidget(mLabelWidth); layout->addWidget(mLineEditWidth); layout->addWidget(mLabelHeight); layout->addWidget(mLineEditHeight); connect(mModeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(applyImageDimensions())); connect(mLineEditHeight, &QLineEdit::editingFinished, this, &ImageDimensionsWidget::applyImageDimensions); connect(mLineEditWidth, &QLineEdit::editingFinished, this, &ImageDimensionsWidget::applyImageDimensions); applyImageDimensions(); } ImageDimensionsWidget::~ImageDimensionsWidget() { delete mFilter; } void ImageDimensionsWidget::applyImageDimensions() { QVariant data = mModeComboBox->itemData(mModeComboBox->currentIndex()); uint32_t width = 0; uint32_t height = 0; width = mLineEditWidth->text().toUInt(); height = mLineEditHeight->text().toUInt(); mFilter->setMode(ImageDimensions::Mode(data.toInt())); mFilter->setSizes(width, height); } /** * A container for all filter widgets. It features a close button on the right. */ class FilterWidgetContainer : public QFrame { public: FilterWidgetContainer() { QPalette pal = palette(); pal.setColor(QPalette::Window, pal.color(QPalette::Highlight)); setPalette(pal); } void setFilterWidget(QWidget *widget) { auto closeButton = new QToolButton; closeButton->setIcon(QIcon::fromTheme(QStringLiteral("window-close"))); closeButton->setAutoRaise(true); closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); int size = style()->pixelMetric(QStyle::PM_SmallIconSize); closeButton->setIconSize(QSize(size, size)); connect(closeButton, &QAbstractButton::clicked, this, &QObject::deleteLater); auto layout = new QHBoxLayout(this); layout->setContentsMargins(2, 2, 2, 2); layout->setSpacing(2); layout->addWidget(widget); layout->addWidget(closeButton); } protected: void paintEvent(QPaintEvent *) override { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const QPainterPath path = PaintUtils::roundedRectangle(QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5), 6); const QColor color = palette().color(QPalette::Highlight); painter.fillPath(path, PaintUtils::alphaAdjustedF(color, 0.5)); painter.setPen(color); painter.drawPath(path); } }; FilterController::FilterController(QFrame *frame, SortedDirModel *dirModel) : QObject(frame) { q = this; mFrame = frame; mDirModel = dirModel; mFilterWidgetCount = 0; mFrame->hide(); auto layout = new FlowLayout(mFrame); layout->setSpacing(2); addAction(i18nc("@action:inmenu", "Filter by Name"), SLOT(addFilterByName()), QKeySequence(Qt::CTRL | Qt::Key_I)); addAction(i18nc("@action:inmenu", "Filter by Date"), SLOT(addFilterByDate()), QKeySequence()); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE addAction(i18nc("@action:inmenu", "Filter by Rating"), SLOT(addFilterByRating()), QKeySequence()); addAction(i18nc("@action:inmenu", "Filter by Tag"), SLOT(addFilterByTag()), QKeySequence()); #endif addAction(i18nc("@action:inmenu", "Filter by Dimensions"), SLOT(addFilterByImageDimensions()), QKeySequence()); } QList<QAction *> FilterController::actionList() const { return mActionList; } void FilterController::addFilterByName() { addFilter(new NameFilterWidget(mDirModel)); } void FilterController::addFilterByDate() { addFilter(new DateFilterWidget(mDirModel)); } #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE void FilterController::addFilterByRating() { addFilter(new RatingFilterWidget(mDirModel)); } void FilterController::addFilterByTag() { addFilter(new TagFilterWidget(mDirModel)); } #endif void FilterController::addFilterByImageDimensions() { addFilter(new ImageDimensionsWidget(mDirModel)); } void FilterController::slotFilterWidgetClosed() { mFilterWidgetCount--; if (mFilterWidgetCount == 0) { mFrame->hide(); } } void FilterController::addAction(const QString &text, const char *slot, const QKeySequence &shortcut) { auto action = new QAction(text, q); action->setShortcut(shortcut); QObject::connect(action, SIGNAL(triggered()), q, slot); mActionList << action; } void FilterController::addFilter(QWidget *widget) { if (mFrame->isHidden()) { mFrame->show(); } auto container = new FilterWidgetContainer; container->setFilterWidget(widget); mFrame->layout()->addWidget(container); mFilterWidgetCount++; QObject::connect(container, &QObject::destroyed, q, &FilterController::slotFilterWidgetClosed); } } // namespace #include "moc_filtercontroller.cpp"
12,381
C++
.cpp
326
34.09816
125
0.747119
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,892
mainwindow.cpp
KDE_gwenview/app/mainwindow.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "mainwindow.h" #include <config-gwenview.h> // Qt #include <QActionGroup> #include <QApplication> #include <QClipboard> #include <QDateTime> #include <QDialog> #include <QFileDialog> #include <QImageReader> #include <QLineEdit> #include <QMenuBar> #include <QMouseEvent> #include <QPushButton> #include <QShortcut> #include <QSplitter> #include <QStackedWidget> #include <QTimer> #include <QUndoGroup> #include <QUrl> #include <QVBoxLayout> #ifdef Q_OS_OSX #include <QFileOpenEvent> #endif #include <QJsonArray> #include <QJsonObject> // KF #include <KActionCategory> #include <KActionCollection> #include <KDirLister> #include <KDirModel> #include <KFileItem> #include <KHamburgerMenu> #include <KLinkItemSelectionModel> #include <KLocalizedString> #include <KMessageBox> #include <KMessageWidget> #include <KProtocolManager> #include <KRecentFilesAction> #include <KStandardShortcut> #include <KToggleFullScreenAction> #include <KToolBar> #include <KToolBarPopupAction> #include <KUrlComboBox> #include <KUrlNavigator> #include <KXMLGUIFactory> #include <kwidgetsaddons_version.h> #include <kxmlgui_version.h> #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE #include "lib/semanticinfo/semanticinfodirmodel.h" #endif #if HAVE_PURPOSE #include <Purpose/AlternativesModel> #include <Purpose/Menu> #include <purpose_version.h> #endif // Local #include "alignwithsidebarwidgetaction.h" #include "configdialog.h" #include "documentinfoprovider.h" #include "fileopscontextmanageritem.h" #include "folderviewcontextmanageritem.h" #include "fullscreencontent.h" #include "gvcore.h" #include "gwenview_app_debug.h" #include "imageopscontextmanageritem.h" #include "infocontextmanageritem.h" #include "viewmainpage.h" #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE #include "semanticinfocontextmanageritem.h" #endif #include "browsemainpage.h" #include "preloader.h" #include "savebar.h" #include "sidebar.h" #include "splitter.h" #include "startmainpage.h" #include "thumbnailviewhelper.h" #include <lib/archiveutils.h> #include <lib/contextmanager.h> #include <lib/disabledactionshortcutmonitor.h> #include <lib/document/documentfactory.h> #include <lib/documentonlyproxymodel.h> #include <lib/gvdebug.h> #include <lib/gwenviewconfig.h> #include <lib/hud/hudbuttonbox.h> #include <lib/mimetypeutils.h> #ifdef HAVE_QTDBUS #include <QDBusConnection> #include <QDBusPendingReply> #include <QDBusReply> #include <lib/mpris2/mpris2service.h> #endif #include <lib/print/printhelper.h> #include <lib/semanticinfo/sorteddirmodel.h> #include <lib/signalblocker.h> #include <lib/slideshow.h> #include <lib/thumbnailprovider/thumbnailprovider.h> #include <lib/thumbnailview/thumbnailbarview.h> #include <lib/thumbnailview/thumbnailview.h> #include <lib/urlutils.h> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_APP_LOG) << x #else #define LOG(x) ; #endif static const int BROWSE_PRELOAD_DELAY = 1000; static const int VIEW_PRELOAD_DELAY = 100; static const char *SESSION_CURRENT_PAGE_KEY = "Page"; static const char *SESSION_URL_KEY = "Url"; enum MainPageId { StartMainPageId, BrowseMainPageId, ViewMainPageId, }; struct MainWindowState { bool mToolBarVisible; }; /* Layout of the main window looks like this: .-mCentralSplitter-----------------------------. |.-mSideBar--. .-mContentWidget---------------.| || | |.-mSaveBar-------------------.|| || | || ||| || | |'----------------------------'|| || | |.-mViewStackedWidget---------.|| || | || ||| || | || ||| || | || ||| || | || ||| || | |'----------------------------'|| |'-----------' '------------------------------'| '----------------------------------------------' */ struct MainWindow::Private { GvCore *mGvCore = nullptr; MainWindow *q = nullptr; QSplitter *mCentralSplitter = nullptr; QWidget *mContentWidget = nullptr; ViewMainPage *mViewMainPage = nullptr; KUrlNavigator *mUrlNavigator = nullptr; ThumbnailView *mThumbnailView = nullptr; ThumbnailView *mActiveThumbnailView = nullptr; DocumentInfoProvider *mDocumentInfoProvider = nullptr; ThumbnailViewHelper *mThumbnailViewHelper = nullptr; QPointer<ThumbnailProvider> mThumbnailProvider; BrowseMainPage *mBrowseMainPage = nullptr; StartMainPage *mStartMainPage = nullptr; SideBar *mSideBar = nullptr; KMessageWidget *mSharedMessage = nullptr; QStackedWidget *mViewStackedWidget = nullptr; FullScreenContent *mFullScreenContent = nullptr; SaveBar *mSaveBar = nullptr; bool mStartSlideShowWhenDirListerCompleted; SlideShow *mSlideShow = nullptr; #ifdef HAVE_QTDBUS Mpris2Service *mMpris2Service = nullptr; #endif Preloader *mPreloader = nullptr; bool mPreloadDirectionIsForward; QActionGroup *mViewModeActionGroup = nullptr; KRecentFilesAction *mFileOpenRecentAction = nullptr; QAction *mBrowseAction = nullptr; QAction *mViewAction = nullptr; QAction *mGoUpAction = nullptr; QAction *mGoToPreviousAction = nullptr; QAction *mGoToNextAction = nullptr; QAction *mGoToFirstAction = nullptr; QAction *mGoToLastAction = nullptr; KToggleAction *mToggleSideBarAction = nullptr; KToggleAction *mToggleOperationsSideBarAction = nullptr; QAction *mFullScreenAction = nullptr; QAction *mSpotlightModeAction = nullptr; QAction *mToggleSlideShowAction = nullptr; KToggleAction *mShowMenuBarAction = nullptr; KToggleAction *mShowStatusBarAction = nullptr; QPointer<HudButtonBox> hudButtonBox = nullptr; #if HAVE_PURPOSE Purpose::Menu *mShareMenu = nullptr; KToolBarPopupAction *mShareAction = nullptr; #endif KHamburgerMenu *mHamburgerMenu = nullptr; SortedDirModel *mDirModel = nullptr; DocumentOnlyProxyModel *mThumbnailBarModel = nullptr; KLinkItemSelectionModel *mThumbnailBarSelectionModel = nullptr; ContextManager *mContextManager = nullptr; MainWindowState mStateBeforeFullScreen; QString mCaption; MainPageId mCurrentMainPageId; QDateTime mFullScreenLeftAt; uint screenSaverDbusCookie = 0; void setupContextManager() { mContextManager = new ContextManager(mDirModel, q); connect(mContextManager, &ContextManager::selectionChanged, q, &MainWindow::slotSelectionChanged); connect(mContextManager, &ContextManager::currentDirUrlChanged, q, &MainWindow::slotCurrentDirUrlChanged); } void setupWidgets() { mFullScreenContent = new FullScreenContent(q, mGvCore); connect(mContextManager, &ContextManager::currentUrlChanged, mFullScreenContent, &FullScreenContent::setCurrentUrl); mCentralSplitter = new Splitter(Qt::Horizontal, q); q->setCentralWidget(mCentralSplitter); // Left side of splitter mSideBar = new SideBar(mCentralSplitter); // Right side of splitter mContentWidget = new QWidget(mCentralSplitter); mSharedMessage = new KMessageWidget(mContentWidget); mSharedMessage->setVisible(false); mSaveBar = new SaveBar(mContentWidget, q->actionCollection()); connect(mContextManager, &ContextManager::currentUrlChanged, mSaveBar, &SaveBar::setCurrentUrl); mViewStackedWidget = new QStackedWidget(mContentWidget); auto layout = new QVBoxLayout(mContentWidget); layout->addWidget(mSharedMessage); layout->addWidget(mSaveBar); layout->addWidget(mViewStackedWidget); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); //// mStartSlideShowWhenDirListerCompleted = false; mSlideShow = new SlideShow(q); connect(mContextManager, &ContextManager::currentUrlChanged, mSlideShow, &SlideShow::setCurrentUrl); setupThumbnailView(mViewStackedWidget); setupViewMainPage(mViewStackedWidget); setupStartMainPage(mViewStackedWidget); mViewStackedWidget->addWidget(mBrowseMainPage); mViewStackedWidget->addWidget(mViewMainPage); mViewStackedWidget->addWidget(mStartMainPage); mViewStackedWidget->setCurrentWidget(mBrowseMainPage); mCentralSplitter->setStretchFactor(0, 0); mCentralSplitter->setStretchFactor(1, 1); mCentralSplitter->setChildrenCollapsible(false); mThumbnailView->setFocus(); connect(mSaveBar, &SaveBar::requestSaveAll, mGvCore, &GvCore::saveAll); connect(mSaveBar, &SaveBar::goToUrl, q, &MainWindow::goToUrl); connect(mSlideShow, &SlideShow::goToUrl, q, &MainWindow::goToUrl); } void setupThumbnailView(QWidget *parent) { Q_ASSERT(mContextManager); mBrowseMainPage = new BrowseMainPage(parent, q->actionCollection(), mGvCore); mThumbnailView = mBrowseMainPage->thumbnailView(); mThumbnailView->viewport()->installEventFilter(q); mThumbnailView->setSelectionModel(mContextManager->selectionModel()); mUrlNavigator = mBrowseMainPage->urlNavigator(); mDocumentInfoProvider = new DocumentInfoProvider(mDirModel); mThumbnailView->setDocumentInfoProvider(mDocumentInfoProvider); mThumbnailViewHelper = new ThumbnailViewHelper(mDirModel, q->actionCollection()); connect(mContextManager, &ContextManager::currentDirUrlChanged, mThumbnailViewHelper, &ThumbnailViewHelper::setCurrentDirUrl); mThumbnailView->setThumbnailViewHelper(mThumbnailViewHelper); mThumbnailBarSelectionModel = new KLinkItemSelectionModel(mThumbnailBarModel, mContextManager->selectionModel(), q); // Connect thumbnail view connect(mThumbnailView, &ThumbnailView::indexActivated, q, &MainWindow::slotThumbnailViewIndexActivated); // Connect delegate QAbstractItemDelegate *delegate = mThumbnailView->itemDelegate(); connect(delegate, SIGNAL(saveDocumentRequested(QUrl)), mGvCore, SLOT(save(QUrl))); connect(delegate, SIGNAL(rotateDocumentLeftRequested(QUrl)), mGvCore, SLOT(rotateLeft(QUrl))); connect(delegate, SIGNAL(rotateDocumentRightRequested(QUrl)), mGvCore, SLOT(rotateRight(QUrl))); connect(delegate, SIGNAL(showDocumentInFullScreenRequested(QUrl)), q, SLOT(showDocumentInFullScreen(QUrl))); connect(delegate, SIGNAL(setDocumentRatingRequested(QUrl, int)), mGvCore, SLOT(setRating(QUrl, int))); // Connect url navigator connect(mUrlNavigator, &KUrlNavigator::urlChanged, q, &MainWindow::openDirUrl); } void setupViewMainPage(QWidget *parent) { mViewMainPage = new ViewMainPage(parent, mSlideShow, q->actionCollection(), mGvCore); connect(mViewMainPage, &ViewMainPage::captionUpdateRequested, q, &MainWindow::slotUpdateCaption); connect(mViewMainPage, &ViewMainPage::completed, q, &MainWindow::slotPartCompleted); connect(mViewMainPage, &ViewMainPage::previousImageRequested, q, &MainWindow::goToPrevious); connect(mViewMainPage, &ViewMainPage::nextImageRequested, q, &MainWindow::goToNext); connect(mViewMainPage, &ViewMainPage::openUrlRequested, q, &MainWindow::openUrl); connect(mViewMainPage, &ViewMainPage::openDirUrlRequested, q, &MainWindow::openDirUrl); setupThumbnailBar(mViewMainPage->thumbnailBar()); } void setupThumbnailBar(ThumbnailView *bar) { Q_ASSERT(mThumbnailBarModel); Q_ASSERT(mThumbnailBarSelectionModel); Q_ASSERT(mDocumentInfoProvider); Q_ASSERT(mThumbnailViewHelper); bar->setModel(mThumbnailBarModel); bar->setSelectionModel(mThumbnailBarSelectionModel); bar->setDocumentInfoProvider(mDocumentInfoProvider); bar->setThumbnailViewHelper(mThumbnailViewHelper); } void setupStartMainPage(QWidget *parent) { mStartMainPage = new StartMainPage(parent, mGvCore); connect(mStartMainPage, &StartMainPage::urlSelected, q, &MainWindow::slotStartMainPageUrlSelected); connect(mStartMainPage, &StartMainPage::recentFileRemoved, [this](const QUrl &url) { mFileOpenRecentAction->removeUrl(url); }); connect(mStartMainPage, &StartMainPage::recentFilesCleared, [this]() { mFileOpenRecentAction->clear(); }); } void installDisabledActionShortcutMonitor(QAction *action, const char *slot) { auto monitor = new DisabledActionShortcutMonitor(action, q); connect(monitor, SIGNAL(activated()), q, slot); } void setupActions() { KActionCollection *actionCollection = q->actionCollection(); auto file = new KActionCategory(i18nc("@title actions category", "File"), actionCollection); auto view = new KActionCategory(i18nc("@title actions category - means actions changing smth in interface", "View"), actionCollection); file->addAction(KStandardAction::Save, q, SLOT(saveCurrent())); file->addAction(KStandardAction::SaveAs, q, SLOT(saveCurrentAs())); file->addAction(KStandardAction::Open, q, SLOT(openFile())); mFileOpenRecentAction = KStandardAction::openRecent(q, SLOT(openUrl(QUrl)), q); connect(mFileOpenRecentAction, &KRecentFilesAction::recentListCleared, mGvCore, &GvCore::clearRecentFilesAndFolders); auto clearAction = mFileOpenRecentAction->menu()->findChild<QAction *>("clear_action"); if (clearAction) { clearAction->setText(i18nc("@action Open Recent menu", "Clear List")); } file->addAction("file_open_recent", mFileOpenRecentAction); file->addAction(KStandardAction::Print, q, SLOT(print())); file->addAction(KStandardAction::PrintPreview, q, SLOT(printPreview())); file->addAction(KStandardAction::Quit, qApp, SLOT(closeAllWindows())); QAction *action = file->addAction(QStringLiteral("reload"), q, SLOT(reload())); action->setText(i18nc("@action reload the currently viewed image", "Reload")); action->setIcon(QIcon::fromTheme(QStringLiteral("view-refresh"))); actionCollection->setDefaultShortcuts(action, KStandardShortcut::reload()); QAction *replaceLocationAction = actionCollection->addAction(QStringLiteral("replace_location")); replaceLocationAction->setText(i18nc("@action:inmenu Navigation Bar", "Replace Location")); actionCollection->setDefaultShortcut(replaceLocationAction, Qt::CTRL | Qt::Key_L); connect(replaceLocationAction, &QAction::triggered, q, &MainWindow::replaceLocation); mBrowseAction = view->addAction(QStringLiteral("browse")); mBrowseAction->setText(i18nc("@action:intoolbar Switch to file list", "Browse")); mBrowseAction->setToolTip(i18nc("@info:tooltip", "Browse folders for images")); mBrowseAction->setCheckable(true); mBrowseAction->setIcon(QIcon::fromTheme(QStringLiteral("view-list-icons"))); actionCollection->setDefaultShortcut(mBrowseAction, Qt::Key_Escape); connect(mViewMainPage, &ViewMainPage::goToBrowseModeRequested, mBrowseAction, &QAction::trigger); mViewAction = view->addAction(QStringLiteral("view")); mViewAction->setText(i18nc("@action:intoolbar Switch to image view", "View")); mViewAction->setToolTip(i18nc("@info:tooltip", "View selected images")); mViewAction->setIcon(QIcon::fromTheme(QStringLiteral("view-preview"))); mViewAction->setCheckable(true); mViewModeActionGroup = new QActionGroup(q); mViewModeActionGroup->addAction(mBrowseAction); mViewModeActionGroup->addAction(mViewAction); connect(mViewModeActionGroup, &QActionGroup::triggered, q, &MainWindow::setActiveViewModeAction); mFullScreenAction = KStandardAction::fullScreen(q, &MainWindow::toggleFullScreen, q, actionCollection); QList<QKeySequence> shortcuts = mFullScreenAction->shortcuts(); shortcuts.append(QKeySequence(Qt::Key_F11)); actionCollection->setDefaultShortcuts(mFullScreenAction, shortcuts); connect(mViewMainPage, &ViewMainPage::toggleFullScreenRequested, mFullScreenAction, &QAction::trigger); QAction *leaveFullScreenAction = view->addAction("leave_fullscreen", q, SLOT(leaveFullScreen())); leaveFullScreenAction->setIcon(QIcon::fromTheme(QStringLiteral("view-restore"))); leaveFullScreenAction->setText(i18nc("@action", "Exit Full Screen")); mSpotlightModeAction = view->addAction(QStringLiteral("view_toggle_spotlightmode"), q, SLOT(toggleSpotlightMode(bool))); mSpotlightModeAction->setCheckable(true); mSpotlightModeAction->setText(i18nc("@action", "Spotlight Mode")); mSpotlightModeAction->setIcon(QIcon::fromTheme(QStringLiteral("image-navigator-symbolic"))); mGoToPreviousAction = view->addAction("go_previous", q, SLOT(goToPrevious())); mGoToPreviousAction->setPriority(QAction::LowPriority); mGoToPreviousAction->setIcon(QIcon::fromTheme(QGuiApplication::layoutDirection() == Qt::LeftToRight ? "go-previous" : "go-previous-symbolic-rtl")); mGoToPreviousAction->setText(i18nc("@action Go to previous image", "Previous")); mGoToPreviousAction->setToolTip(i18nc("@info:tooltip", "Go to previous image")); installDisabledActionShortcutMonitor(mGoToPreviousAction, SLOT(showFirstDocumentReached())); mGoToNextAction = view->addAction(QStringLiteral("go_next"), q, SLOT(goToNext())); mGoToNextAction->setPriority(QAction::LowPriority); mGoToNextAction->setIcon(QIcon::fromTheme(QGuiApplication::layoutDirection() == Qt::LeftToRight ? "go-next" : "go-next-symbolic-rtl")); mGoToNextAction->setText(i18nc("@action Go to next image", "Next")); mGoToNextAction->setToolTip(i18nc("@info:tooltip", "Go to next image")); installDisabledActionShortcutMonitor(mGoToNextAction, SLOT(showLastDocumentReached())); mGoToFirstAction = view->addAction(QStringLiteral("go_first"), q, SLOT(goToFirst())); mGoToFirstAction->setPriority(QAction::LowPriority); mGoToFirstAction->setIcon(QIcon::fromTheme(QStringLiteral("go-first-view"))); mGoToFirstAction->setText(i18nc("@action Go to first image", "First")); mGoToFirstAction->setToolTip(i18nc("@info:tooltip", "Go to first image")); actionCollection->setDefaultShortcut(mGoToFirstAction, Qt::Key_Home); mGoToLastAction = view->addAction(QStringLiteral("go_last"), q, SLOT(goToLast())); mGoToLastAction->setPriority(QAction::LowPriority); mGoToLastAction->setIcon(QIcon::fromTheme(QStringLiteral("go-last-view"))); mGoToLastAction->setText(i18nc("@action Go to last image", "Last")); mGoToLastAction->setToolTip(i18nc("@info:tooltip", "Go to last image")); actionCollection->setDefaultShortcut(mGoToLastAction, Qt::Key_End); mPreloadDirectionIsForward = true; mGoUpAction = view->addAction(KStandardAction::Up, q, SLOT(goUp())); action = view->addAction("go_start_page", q, SLOT(showStartMainPage())); action->setPriority(QAction::LowPriority); action->setIcon(QIcon::fromTheme(QStringLiteral("go-home"))); action->setText(i18nc("@action", "Start Page")); action->setToolTip(i18nc("@info:tooltip", "Open the start page")); actionCollection->setDefaultShortcuts(action, KStandardShortcut::home()); mToggleSideBarAction = view->add<KToggleAction>(QStringLiteral("toggle_sidebar")); connect(mToggleSideBarAction, &KToggleAction::triggered, q, &MainWindow::toggleSideBar); mToggleSideBarAction->setIcon(QIcon::fromTheme(QStringLiteral("view-sidetree"))); actionCollection->setDefaultShortcut(mToggleSideBarAction, Qt::Key_F4); mToggleSideBarAction->setText(i18nc("@action", "Sidebar")); connect(mBrowseMainPage->toggleSideBarButton(), &QAbstractButton::clicked, mToggleSideBarAction, &QAction::trigger); connect(mViewMainPage->toggleSideBarButton(), &QAbstractButton::clicked, mToggleSideBarAction, &QAction::trigger); mToggleOperationsSideBarAction = view->add<KToggleAction>(QStringLiteral("toggle_operations_sidebar")); mToggleOperationsSideBarAction->setText(i18nc("@action opens crop, rename, etc.", "Show Editing Tools")); mToggleOperationsSideBarAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-image"), QIcon::fromTheme(QStringLiteral("document-edit")))); connect(mToggleOperationsSideBarAction, &KToggleAction::triggered, q, &MainWindow::toggleOperationsSideBar); connect(mSideBar, &QTabWidget::currentChanged, mToggleOperationsSideBarAction, [=]() { mToggleOperationsSideBarAction->setChecked(mSideBar->isVisible() && mSideBar->currentPage() == QLatin1String("operations")); }); mToggleSlideShowAction = view->addAction(QStringLiteral("toggle_slideshow"), q, SLOT(toggleSlideShow())); q->updateSlideShowAction(); connect(mSlideShow, &SlideShow::stateChanged, q, &MainWindow::updateSlideShowAction); q->setStandardToolBarMenuEnabled(true); mShowMenuBarAction = static_cast<KToggleAction *>(view->addAction(KStandardAction::ShowMenubar, q, SLOT(toggleMenuBar()))); mShowStatusBarAction = static_cast<KToggleAction *>(view->addAction(KStandardAction::ShowStatusbar, q, SLOT(toggleStatusBar(bool)))); actionCollection->setDefaultShortcut(mShowStatusBarAction, Qt::Key_F3); view->addAction(KStandardAction::name(KStandardAction::KeyBindings), KStandardAction::keyBindings(q, &MainWindow::configureShortcuts, actionCollection)); connect(q->guiFactory(), &KXMLGUIFactory::shortcutsSaved, q, [this]() { q->guiFactory()->refreshActionProperties(); }); view->addAction(KStandardAction::Preferences, q, SLOT(showConfigDialog())); view->addAction(KStandardAction::ConfigureToolbars, q, SLOT(configureToolbars())); #if HAVE_PURPOSE mShareAction = new KToolBarPopupAction(QIcon::fromTheme(QStringLiteral("document-share")), i18nc("@action Share images", "Share"), q); mShareAction->setPopupMode(KToolBarPopupAction::InstantPopup); actionCollection->addAction(QStringLiteral("share"), mShareAction); mShareMenu = new Purpose::Menu(q); mShareAction->setMenu(mShareMenu); connect(mShareMenu, &Purpose::Menu::finished, q, [this](const QJsonObject &output, int error, const QString &message) { if (error && error != KIO::ERR_USER_CANCELED) { mSharedMessage->setText(i18n("Error while sharing: %1", message)); mSharedMessage->setMessageType(KMessageWidget::MessageType::Error); mSharedMessage->animatedShow(); } else { const QString url = output[QStringLiteral("url")].toString(); if (!url.isEmpty()) { mSharedMessage->setText(i18n("The shared image link (<a href=\"%1\">%1</a>) has been copied to the clipboard.", url)); mSharedMessage->setMessageType(KMessageWidget::MessageType::Positive); mSharedMessage->animatedShow(); QApplication::clipboard()->setText(url); } else { mSharedMessage->setVisible(false); } } }); #endif auto alignWithSideBarWidgetAction = new AlignWithSideBarWidgetAction(q); alignWithSideBarWidgetAction->setSideBar(mSideBar); actionCollection->addAction("align_with_sidebar", alignWithSideBarWidgetAction); mHamburgerMenu = KStandardAction::hamburgerMenu(nullptr, nullptr, actionCollection); mHamburgerMenu->setShowMenuBarAction(mShowMenuBarAction); mHamburgerMenu->setMenuBar(q->menuBar()); connect(mHamburgerMenu, &KHamburgerMenu::aboutToShowMenu, q, [this]() { this->updateHamburgerMenu(); // Immediately disconnect. We only need to run this once, but on demand. // NOTE: The nullptr at the end disconnects all connections between // q and mHamburgerMenu's aboutToShowMenu signal. disconnect(mHamburgerMenu, &KHamburgerMenu::aboutToShowMenu, q, nullptr); }); } void updateHamburgerMenu() { KActionCollection *actionCollection = q->actionCollection(); auto menu = new QMenu; menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::Open))); menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::OpenRecent))); menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::Save))); menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::SaveAs))); menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::Print))); menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::PrintPreview))); menu->addSeparator(); menu->addAction(actionCollection->action(KStandardAction::name(KStandardAction::Copy))); menu->addAction(actionCollection->action(QStringLiteral("file_trash"))); menu->addSeparator(); menu->addAction(mBrowseAction); menu->addAction(mViewAction); menu->addAction(actionCollection->action(QStringLiteral("sort_by"))); menu->addAction(mFullScreenAction); menu->addAction(mToggleSlideShowAction); menu->addSeparator(); #if HAVE_PURPOSE menu->addMenu(mShareMenu); #endif auto configureMenu = new QMenu(i18nc("@title:menu submenu for actions that open configuration dialogs", "Configure")); configureMenu->addAction(actionCollection->action(QStringLiteral("options_configure_keybinding"))); configureMenu->addAction(actionCollection->action(QStringLiteral("options_configure_toolbars"))); configureMenu->addAction(actionCollection->action(QStringLiteral("options_configure"))); menu->addMenu(configureMenu); mHamburgerMenu->setMenu(menu); } void setupUndoActions() { // There is no KUndoGroup similar to KUndoStack. This code basically // does the same as KUndoStack, but for the KUndoGroup actions. QUndoGroup *undoGroup = DocumentFactory::instance()->undoGroup(); QAction *action; KActionCollection *actionCollection = q->actionCollection(); auto edit = new KActionCategory(i18nc("@title actions category - means actions changing smth in interface", "Edit"), actionCollection); action = undoGroup->createRedoAction(actionCollection); action->setObjectName(KStandardAction::name(KStandardAction::Redo)); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-redo"))); action->setIconText(i18n("Redo")); actionCollection->setDefaultShortcuts(action, KStandardShortcut::redo()); edit->addAction(action->objectName(), action); action = undoGroup->createUndoAction(actionCollection); action->setObjectName(KStandardAction::name(KStandardAction::Undo)); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-undo"))); action->setIconText(i18n("Undo")); actionCollection->setDefaultShortcuts(action, KStandardShortcut::undo()); edit->addAction(action->objectName(), action); } void setupContextManagerItems() { Q_ASSERT(mContextManager); KActionCollection *actionCollection = q->actionCollection(); // Create context manager items auto folderViewItem = new FolderViewContextManagerItem(mContextManager); connect(folderViewItem, &FolderViewContextManagerItem::urlChanged, q, &MainWindow::folderViewUrlChanged); auto infoItem = new InfoContextManagerItem(mContextManager); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE SemanticInfoContextManagerItem *semanticInfoItem = nullptr; semanticInfoItem = new SemanticInfoContextManagerItem(mContextManager, actionCollection, mViewMainPage); #endif auto imageOpsItem = new ImageOpsContextManagerItem(mContextManager, q); auto fileOpsItem = new FileOpsContextManagerItem(mContextManager, mThumbnailView, actionCollection, q); // Fill sidebar SideBarPage *page; page = new SideBarPage(QIcon::fromTheme(QStringLiteral("folder")), i18n("Folders")); page->setObjectName(QStringLiteral("folders")); page->addWidget(folderViewItem->widget()); page->layout()->setContentsMargins(0, 0, 0, 0); mSideBar->addPage(page); page = new SideBarPage(QIcon::fromTheme(QStringLiteral("documentinfo")), i18n("Information")); page->setObjectName(QStringLiteral("information")); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE // If we have semantic info, we want to share the sidebar using a splitter, // so the user can dynamically resize the two widgets. if (semanticInfoItem) { auto splitter = new QSplitter; splitter->setObjectName(QStringLiteral("information_splitter")); // This name is used to find it when loading previous sizes. splitter->setOrientation(Qt::Vertical); splitter->setHandleWidth(5); splitter->addWidget(infoItem->widget()); splitter->setCollapsible(0, false); // Cram the semantic info widget and a separator into a separate widget, // so that they can be added to the splitter together (layouts can't be added directly). // This will give the splitter a visible separator between the two widgets. auto separator = new QFrame; separator->setFrameShape(QFrame::HLine); separator->setLineWidth(1); auto container = new QWidget; auto containerLayout = new QVBoxLayout(container); containerLayout->setContentsMargins(0, 0, 0, 0); containerLayout->addWidget(separator); containerLayout->addWidget(semanticInfoItem->widget()); splitter->addWidget(container); splitter->setCollapsible(1, false); page->addWidget(splitter); } else { page->addWidget(infoItem->widget()); } #else page->addWidget(infoItem->widget()); #endif mSideBar->addPage(page); page = new SideBarPage(QIcon::fromTheme(QStringLiteral("document-edit")), i18n("Operations")); page->setObjectName(QStringLiteral("operations")); page->addWidget(imageOpsItem->widget()); auto separator = new QFrame; separator->setFrameShape(QFrame::HLine); separator->setLineWidth(1); page->addWidget(separator); page->addWidget(fileOpsItem->widget()); page->addStretch(); mSideBar->addPage(page); } void initDirModel() { mDirModel->setKindFilter(MimeTypeUtils::KIND_DIR | MimeTypeUtils::KIND_ARCHIVE | MimeTypeUtils::KIND_RASTER_IMAGE | MimeTypeUtils::KIND_SVG_IMAGE | MimeTypeUtils::KIND_VIDEO); connect(mDirModel, &QAbstractItemModel::rowsInserted, q, &MainWindow::slotDirModelNewItems); connect(mDirModel, &QAbstractItemModel::rowsRemoved, q, &MainWindow::updatePreviousNextActions); connect(mDirModel, &QAbstractItemModel::modelReset, q, &MainWindow::updatePreviousNextActions); connect(mDirModel->dirLister(), SIGNAL(completed()), q, SLOT(slotDirListerCompleted())); } void setupThumbnailBarModel() { mThumbnailBarModel = new DocumentOnlyProxyModel(q); mThumbnailBarModel->setSourceModel(mDirModel); } bool indexIsDirOrArchive(const QModelIndex &index) const { Q_ASSERT(index.isValid()); KFileItem item = mDirModel->itemForIndex(index); return ArchiveUtils::fileItemIsDirOrArchive(item); } void goTo(const QModelIndex &index) { if (!index.isValid()) { return; } mThumbnailView->setCurrentIndex(index); mThumbnailView->scrollTo(index); } void goTo(int offset) { mPreloadDirectionIsForward = offset > 0; QModelIndex index = mContextManager->selectionModel()->currentIndex(); index = mDirModel->index(index.row() + offset, 0); if (index.isValid() && !indexIsDirOrArchive(index)) { goTo(index); } } void goToFirstDocument() { QModelIndex index; for (int row = 0;; ++row) { index = mDirModel->index(row, 0); if (!index.isValid()) { return; } if (!indexIsDirOrArchive(index)) { break; } } goTo(index); } void goToLastDocument() { QModelIndex index = mDirModel->index(mDirModel->rowCount() - 1, 0); goTo(index); } void setupFullScreenContent() { mFullScreenContent->init(q->actionCollection(), mViewMainPage, mSlideShow); setupThumbnailBar(mFullScreenContent->thumbnailBar()); } inline void setActionEnabled(const char *name, bool enabled) { QAction *action = q->actionCollection()->action(name); if (action) { action->setEnabled(enabled); } else { qCWarning(GWENVIEW_APP_LOG) << "Action" << name << "not found"; } } void setActionsDisabledOnStartMainPageEnabled(bool enabled) { mBrowseAction->setEnabled(enabled); mViewAction->setEnabled(enabled); mToggleSideBarAction->setEnabled(enabled); mToggleOperationsSideBarAction->setEnabled(enabled); mShowStatusBarAction->setEnabled(enabled); mFullScreenAction->setEnabled(enabled); mToggleSlideShowAction->setEnabled(enabled); setActionEnabled("reload", enabled); setActionEnabled("go_start_page", enabled); setActionEnabled("add_folder_to_places", enabled); setActionEnabled("view_toggle_spotlightmode", enabled); } void updateActions() { bool isRasterImage = false; bool canSave = false; bool isModified = false; const QUrl url = mContextManager->currentUrl(); if (url.isValid()) { isRasterImage = mContextManager->currentUrlIsRasterImage(); canSave = isRasterImage; isModified = DocumentFactory::instance()->load(url)->isModified(); if (mCurrentMainPageId != ViewMainPageId && mContextManager->selectedFileItemList().count() != 1) { // Saving only makes sense if exactly one image is selected canSave = false; } } KActionCollection *actionCollection = q->actionCollection(); actionCollection->action(QStringLiteral("file_save"))->setEnabled(canSave && isModified); actionCollection->action(QStringLiteral("file_save_as"))->setEnabled(canSave); actionCollection->action(QStringLiteral("file_print"))->setEnabled(isRasterImage); actionCollection->action(QStringLiteral("file_print_preview"))->setEnabled(isRasterImage); #if HAVE_PURPOSE const KFileItemList selectedFiles = mContextManager->selectedFileItemList(); if (selectedFiles.isEmpty()) { mShareAction->setEnabled(false); } else { mShareAction->setEnabled(true); QJsonArray urls; for (const KFileItem &fileItem : selectedFiles) { urls << QJsonValue(fileItem.url().toString()); } mShareMenu->model()->setInputData(QJsonObject{{QStringLiteral("mimeType"), MimeTypeUtils::urlMimeType(url)}, {QStringLiteral("urls"), urls}}); mShareMenu->model()->setPluginType(QStringLiteral("Export")); mShareMenu->reload(); } #endif } bool sideBarVisibility() const { switch (mCurrentMainPageId) { case StartMainPageId: GV_WARN_AND_RETURN_VALUE(false, "Sidebar not implemented on start page"); break; case BrowseMainPageId: return GwenviewConfig::sideBarVisible(); case ViewMainPageId: return q->isFullScreen() ? GwenviewConfig::sideBarVisibleViewModeFullScreen() : GwenviewConfig::spotlightMode() ? GwenviewConfig::sideBarVisibleSpotlightMode() : GwenviewConfig::sideBarVisible(); } return false; } void saveSideBarVisibility(const bool visible) { switch (mCurrentMainPageId) { case StartMainPageId: GV_WARN_AND_RETURN("Sidebar not implemented on start page"); break; case BrowseMainPageId: GwenviewConfig::setSideBarVisible(visible); break; case ViewMainPageId: q->isFullScreen() ? GwenviewConfig::setSideBarVisibleViewModeFullScreen(visible) : GwenviewConfig::spotlightMode() ? GwenviewConfig::setSideBarVisibleSpotlightMode(visible) : GwenviewConfig::setSideBarVisible(visible); break; } } bool statusBarVisibility() const { switch (mCurrentMainPageId) { case StartMainPageId: GV_WARN_AND_RETURN_VALUE(false, "Statusbar not implemented on start page"); break; case BrowseMainPageId: return GwenviewConfig::statusBarVisibleBrowseMode(); case ViewMainPageId: return q->isFullScreen() ? GwenviewConfig::statusBarVisibleViewModeFullScreen() : GwenviewConfig::spotlightMode() ? GwenviewConfig::statusBarVisibleSpotlightMode() : GwenviewConfig::statusBarVisibleViewMode(); } return false; } void saveStatusBarVisibility(const bool visible) { switch (mCurrentMainPageId) { case StartMainPageId: GV_WARN_AND_RETURN("Statusbar not implemented on start page"); break; case BrowseMainPageId: GwenviewConfig::setStatusBarVisibleBrowseMode(visible); break; case ViewMainPageId: q->isFullScreen() ? GwenviewConfig::setStatusBarVisibleViewModeFullScreen(visible) : GwenviewConfig::spotlightMode() ? GwenviewConfig::setStatusBarVisibleSpotlightMode(visible) : GwenviewConfig::setStatusBarVisibleViewMode(visible); break; } } void loadSplitterConfig() { const QList<int> sizes = GwenviewConfig::sideBarSplitterSizes(); if (!sizes.isEmpty()) { mCentralSplitter->setSizes(sizes); } } void saveSplitterConfig() { if (mSideBar->isVisible()) { GwenviewConfig::setSideBarSplitterSizes(mCentralSplitter->sizes()); } } void loadInformationSplitterConfig() { const QList<int> sizes = GwenviewConfig::informationSplitterSizes(); if (!sizes.isEmpty()) { // Find the splitter inside the sidebar by objectName. auto informationSidebar = mSideBar->findChild<QSplitter *>(QStringLiteral("information_splitter"), Qt::FindChildrenRecursively); if (informationSidebar) { informationSidebar->setSizes(sizes); } else { qCWarning(GWENVIEW_APP_LOG) << "Could not find information splitter in sidebar when loading old position."; } } } void saveInformationSplitterConfig() { auto informationSidebar = mSideBar->findChild<QSplitter *>(QStringLiteral("information_splitter"), Qt::FindChildrenRecursively); if (informationSidebar) { GwenviewConfig::setInformationSplitterSizes(informationSidebar->sizes()); } else { qCWarning(GWENVIEW_APP_LOG) << "Could not find information splitter in sidebar when saving new position."; } } void setScreenSaverEnabled(bool enabled) { #ifdef HAVE_QTDBUS if (!enabled) { QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.ScreenSaver"), QStringLiteral("/ScreenSaver"), QStringLiteral("org.freedesktop.ScreenSaver"), QStringLiteral("Inhibit")); message << QGuiApplication::desktopFileName(); message << i18n("Viewing media"); QDBusReply<uint> reply = QDBusConnection::sessionBus().call(message); if (reply.isValid()) { screenSaverDbusCookie = reply.value(); } } else { if (screenSaverDbusCookie != 0) { QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.ScreenSaver"), QStringLiteral("/ScreenSaver"), QStringLiteral("org.freedesktop.ScreenSaver"), QStringLiteral("UnInhibit")); message << static_cast<uint>(screenSaverDbusCookie); screenSaverDbusCookie = 0; QDBusConnection::sessionBus().send(message); } } #endif } void assignThumbnailProviderToThumbnailView(ThumbnailView *thumbnailView) { GV_RETURN_IF_FAIL(thumbnailView); if (mActiveThumbnailView) { mActiveThumbnailView->setThumbnailProvider(nullptr); } thumbnailView->setThumbnailProvider(mThumbnailProvider); mActiveThumbnailView = thumbnailView; if (mActiveThumbnailView->isVisible()) { mThumbnailProvider->stop(); mActiveThumbnailView->generateThumbnailsForItems(); } } void autoAssignThumbnailProvider() { if (mCurrentMainPageId == ViewMainPageId) { if (q->windowState() & Qt::WindowFullScreen) { assignThumbnailProviderToThumbnailView(mFullScreenContent->thumbnailBar()); } else { assignThumbnailProviderToThumbnailView(mViewMainPage->thumbnailBar()); } } else if (mCurrentMainPageId == BrowseMainPageId) { assignThumbnailProviderToThumbnailView(mThumbnailView); } else if (mCurrentMainPageId == StartMainPageId) { assignThumbnailProviderToThumbnailView(mStartMainPage->recentFoldersView()); } } enum class ShowPreview { Yes, No }; void print(ShowPreview showPreview) { if (!mContextManager->currentUrlIsRasterImage()) { return; } Document::Ptr doc = DocumentFactory::instance()->load(mContextManager->currentUrl()); PrintHelper printHelper(q); if (showPreview == ShowPreview::Yes) { printHelper.printPreview(doc); } else { printHelper.print(doc); } } /// Handles the clicking of links in help texts if the clicked url uses the "gwenview:" scheme. class InternalUrlClickedHandler : public QObject { public: InternalUrlClickedHandler(MainWindow *parent) : QObject(parent) { Q_CHECK_PTR(parent); } inline bool eventFilter(QObject * /* watched */, QEvent *event) override { if (event->type() != QEvent::WhatsThisClicked) { return false; } const QString linkAddress = static_cast<QWhatsThisClickedEvent *>(event)->href(); if (!linkAddress.startsWith(QStringLiteral("gwenview:"))) { // This eventFilter only handles our internal "gwenview" scheme. Everything else is handled by KXmlGui::KToolTipHelper. return false; } event->accept(); auto linkPathList = linkAddress.split(QLatin1Char('/')); linkPathList.removeFirst(); // remove "gwenview:/" Q_ASSERT(!linkPathList.isEmpty()); Q_ASSERT_X(linkPathList.constFirst() == QStringLiteral("config"), "link resolver", "Handling of this URL is not yet implemented"); linkPathList.removeFirst(); // remove "config/" auto mainWindow = static_cast<MainWindow *>(parent()); if (linkPathList.isEmpty()) { mainWindow->showConfigDialog(); } else if (linkPathList.constFirst() == QStringLiteral("general")) { mainWindow->showConfigDialog(0); // "0" should open General. } else if (linkPathList.constFirst() == QStringLiteral("imageview")) { mainWindow->showConfigDialog(1); // "1" should open Image View. } else if (linkPathList.constFirst() == QStringLiteral("advanced")) { mainWindow->showConfigDialog(2); // "2" should open Advanced. } else { Q_ASSERT_X(false, "config link resolver", "Handling of this config URL is not yet implemented"); } return true; } }; }; MainWindow::MainWindow() : KXmlGuiWindow() , d(new MainWindow::Private) { d->q = this; d->mCurrentMainPageId = StartMainPageId; d->mDirModel = new SortedDirModel(this); d->setupContextManager(); d->setupThumbnailBarModel(); d->mGvCore = new GvCore(this, d->mDirModel); d->mPreloader = new Preloader(this); d->mThumbnailProvider = new ThumbnailProvider(); d->mActiveThumbnailView = nullptr; d->initDirModel(); d->setupWidgets(); d->setupActions(); d->setupUndoActions(); d->setupContextManagerItems(); d->setupFullScreenContent(); d->updateActions(); updatePreviousNextActions(); createGUI(); loadConfig(); QImageReader::setAllocationLimit(2000); connect(DocumentFactory::instance(), &DocumentFactory::modifiedDocumentListChanged, this, &MainWindow::slotModifiedDocumentListChanged); connect(qApp, &QApplication::focusChanged, this, &MainWindow::onFocusChanged); #ifdef HAVE_QTDBUS d->mMpris2Service = new Mpris2Service(d->mSlideShow, d->mContextManager, d->mToggleSlideShowAction, d->mFullScreenAction, d->mGoToPreviousAction, d->mGoToNextAction, this); #endif auto ratingMenu = static_cast<QMenu *>(guiFactory()->container(QStringLiteral("rating"), this)); ratingMenu->setIcon(QIcon::fromTheme(QStringLiteral("rating-unrated"))); #ifdef GWENVIEW_SEMANTICINFO_BACKEND_NONE if (ratingMenu) { ratingMenu->menuAction()->setVisible(false); } #endif setAutoSaveSettings(); #ifdef Q_OS_OSX qApp->installEventFilter(this); #endif qApp->installEventFilter(new Private::InternalUrlClickedHandler(this)); } MainWindow::~MainWindow() { delete d->mThumbnailProvider; delete d; } ContextManager *MainWindow::contextManager() const { return d->mContextManager; } ViewMainPage *MainWindow::viewMainPage() const { return d->mViewMainPage; } void MainWindow::setCaption(const QString &caption) { // Keep a trace of caption to use it in slotModifiedDocumentListChanged() d->mCaption = caption; KXmlGuiWindow::setCaption(caption); } void MainWindow::setCaption(const QString &caption, bool modified) { d->mCaption = caption; KXmlGuiWindow::setCaption(caption, modified); } void MainWindow::slotUpdateCaption(const QString &caption) { const QUrl url = d->mContextManager->currentUrl(); const QList<QUrl> list = DocumentFactory::instance()->modifiedDocumentList(); setCaption(caption, list.contains(url)); } void MainWindow::slotModifiedDocumentListChanged() { d->updateActions(); slotUpdateCaption(d->mCaption); } void MainWindow::setInitialUrl(const QUrl &_url) { Q_ASSERT(_url.isValid()); QUrl url = UrlUtils::fixUserEnteredUrl(_url); d->mGvCore->setTrackFileManagerSorting(true); syncSortOrder(url); if (UrlUtils::urlIsDirectory(url)) { d->mBrowseAction->trigger(); openDirUrl(url); } else { openUrl(url); } } void MainWindow::startSlideShow() { d->mViewAction->trigger(); // We need to wait until we have listed all images in the dirlister to // start the slideshow because the SlideShow objects needs an image list to // work. d->mStartSlideShowWhenDirListerCompleted = true; } void MainWindow::setActiveViewModeAction(QAction *action) { if (action == d->mViewAction) { d->mCurrentMainPageId = ViewMainPageId; // Switching to view mode d->mViewStackedWidget->setCurrentWidget(d->mViewMainPage); openSelectedDocuments(); d->mPreloadDirectionIsForward = true; QTimer::singleShot(VIEW_PRELOAD_DELAY, this, &MainWindow::preloadNextUrl); } else { d->mCurrentMainPageId = BrowseMainPageId; // Switching to browse mode d->mViewStackedWidget->setCurrentWidget(d->mBrowseMainPage); if (!d->mViewMainPage->isEmpty() && KProtocolManager::supportsListing(d->mViewMainPage->url())) { // Reset the view to spare resources, but don't do it if we can't // browse the url, otherwise if the user starts Gwenview this way: // gwenview http://example.com/example.png // and switch to browse mode, switching back to view mode won't bring // his image back. d->mViewMainPage->reset(); } setCaption(d->mUrlNavigator->locationUrl().adjusted(QUrl::RemoveScheme).toString()); } d->autoAssignThumbnailProvider(); toggleSideBar(d->sideBarVisibility()); toggleStatusBar(d->statusBarVisibility()); Q_EMIT viewModeChanged(); } void MainWindow::slotThumbnailViewIndexActivated(const QModelIndex &index) { if (!index.isValid()) { return; } KFileItem item = d->mDirModel->itemForIndex(index); syncSortOrder(item.url()); if (item.isDir()) { // Item is a dir, open it openDirUrl(item.url()); } else { QString protocol = ArchiveUtils::protocolForMimeType(item.mimetype()); if (!protocol.isEmpty()) { // Item is an archive, tweak url then open it QUrl url = item.url(); url.setScheme(protocol); openDirUrl(url); } else { // Item is a document, switch to view mode d->mViewAction->trigger(); } } } void MainWindow::openSelectedDocuments() { if (d->mCurrentMainPageId != ViewMainPageId) { return; } int count = 0; QList<QUrl> urls; const auto list = d->mContextManager->selectedFileItemList(); for (const auto &item : list) { if (!item.isNull() && !ArchiveUtils::fileItemIsDirOrArchive(item)) { urls << item.url(); ++count; if (count == ViewMainPage::MaxViewCount) { break; } } } if (urls.isEmpty()) { // Selection contains no fitting items // Switch back to browsing mode d->mBrowseAction->trigger(); d->mViewMainPage->reset(); return; } QUrl currentUrl = d->mContextManager->currentUrl(); if (currentUrl.isEmpty() || !urls.contains(currentUrl)) { // There is no current URL or it doesn't belong to selection // This can happen when user manually selects a group of items currentUrl = urls.first(); } d->mViewMainPage->openUrls(urls, currentUrl); } void MainWindow::goUp() { if (d->mCurrentMainPageId == BrowseMainPageId) { QUrl url = d->mContextManager->currentDirUrl(); url = KIO::upUrl(url); openDirUrl(url); } else { d->mBrowseAction->trigger(); } } void MainWindow::showStartMainPage() { d->mCurrentMainPageId = StartMainPageId; d->setActionsDisabledOnStartMainPageEnabled(false); d->saveSplitterConfig(); d->mSideBar->hide(); d->mViewStackedWidget->setCurrentWidget(d->mStartMainPage); d->updateActions(); updatePreviousNextActions(); d->mContextManager->setCurrentDirUrl(QUrl()); d->mContextManager->setCurrentUrl(QUrl()); d->autoAssignThumbnailProvider(); } void MainWindow::slotStartMainPageUrlSelected(const QUrl &url) { d->setActionsDisabledOnStartMainPageEnabled(true); if (d->mBrowseAction->isChecked()) { // Silently uncheck the action so that setInitialUrl() does the right thing SignalBlocker blocker(d->mBrowseAction); d->mBrowseAction->setChecked(false); } setInitialUrl(url); } void MainWindow::openDirUrl(const QUrl &url) { const QUrl currentUrl = d->mContextManager->currentDirUrl(); if (url == currentUrl) { return; } if (url.isParentOf(currentUrl)) { // Keep first child between url and currentUrl selected // If currentPath is "/home/user/photos/2008/event" // and wantedPath is "/home/user/photos" // pathToSelect should be "/home/user/photos/2008" // To anyone considering using QUrl::toLocalFile() instead of // QUrl::path() here. Please don't, using QUrl::path() is the right // thing to do here. const QString currentPath = QDir::cleanPath(currentUrl.adjusted(QUrl::StripTrailingSlash).path()); const QString wantedPath = QDir::cleanPath(url.adjusted(QUrl::StripTrailingSlash).path()); const QChar separator('/'); const int slashCount = wantedPath.count(separator); const QString pathToSelect = currentPath.section(separator, 0, slashCount + 1); QUrl urlToSelect = url; urlToSelect.setPath(pathToSelect); d->mContextManager->setUrlToSelect(urlToSelect); } d->mThumbnailProvider->stop(); d->mContextManager->setCurrentDirUrl(url); d->mGvCore->addUrlToRecentFolders(url); d->mViewMainPage->reset(); } void MainWindow::folderViewUrlChanged(const QUrl &url) { const QUrl currentUrl = d->mContextManager->currentDirUrl(); if (url == currentUrl) { switch (d->mCurrentMainPageId) { case ViewMainPageId: d->mBrowseAction->trigger(); break; case BrowseMainPageId: d->mViewAction->trigger(); break; case StartMainPageId: break; } } else { openDirUrl(url); } } void MainWindow::syncSortOrder(const QUrl &url) { if (!d->mGvCore->trackFileManagerSorting()) { return; } #ifdef HAVE_QTDBUS QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.FileManager1"), QStringLiteral("/org/freedesktop/FileManager1"), QStringLiteral("org.freedesktop.FileManager1"), QStringLiteral("SortOrderForUrl")); QUrl dirUrl = url; dirUrl = dirUrl.adjusted(QUrl::RemoveFilename); message << dirUrl.toString(); QDBusPendingCall call = QDBusConnection::sessionBus().asyncCall(message); auto watcher = new QDBusPendingCallWatcher(call, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [this](QDBusPendingCallWatcher *call) { QDBusPendingReply<QString, QString> reply = *call; // Fail silently if (!reply.isError()) { QString columnName = reply.argumentAt<0>(); QString orderName = reply.argumentAt<1>(); int column = -1; int sortRole = -1; Qt::SortOrder order = orderName == QStringLiteral("descending") ? Qt::DescendingOrder : Qt::AscendingOrder; if (columnName == "text") { column = KDirModel::Name; sortRole = Qt::DisplayRole; qCDebug(GWENVIEW_APP_LOG) << "Sorting according to file manager: text"; } else if (columnName == "modificationtime") { column = KDirModel::ModifiedTime; sortRole = Qt::DisplayRole; qCDebug(GWENVIEW_APP_LOG) << "Sorting according to file manager: modtime"; } else if (columnName == "size") { column = KDirModel::Size; sortRole = Qt::DisplayRole; qCDebug(GWENVIEW_APP_LOG) << "Sorting according to file manager: size"; #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE } else if (columnName == "rating") { column = KDirModel::Name; sortRole = SemanticInfoDirModel::RatingRole; qCDebug(GWENVIEW_APP_LOG) << "Sorting according to file manager: rating"; #endif } if (column >= 0 && sortRole >= 0) { d->mDirModel->setSortRole(sortRole); d->mDirModel->sort(column, order); } } call->deleteLater(); }); #endif } void MainWindow::toggleSideBar(bool visible) { d->saveSplitterConfig(); d->mToggleSideBarAction->setChecked(visible); d->mToggleOperationsSideBarAction->setChecked(visible && d->mSideBar->currentPage() == QLatin1String("operations")); d->saveSideBarVisibility(visible); d->mSideBar->setVisible(visible); const QString iconName = QApplication::isRightToLeft() ? (visible ? "sidebar-collapse-right" : "sidebar-expand-right") : (visible ? "sidebar-collapse-left" : "sidebar-expand-left"); const QString toolTip = visible ? i18nc("@info:tooltip", "Hide sidebar") : i18nc("@info:tooltip", "Show sidebar"); const QList<QToolButton *> buttonList{d->mBrowseMainPage->toggleSideBarButton(), d->mViewMainPage->toggleSideBarButton()}; for (auto button : buttonList) { button->setIcon(QIcon::fromTheme(iconName)); button->setToolTip(toolTip); } } void MainWindow::toggleOperationsSideBar(bool visible) { if (visible) { d->mSideBar->setCurrentPage(QLatin1String("operations")); } toggleSideBar(visible); } void MainWindow::toggleStatusBar(bool visible) { d->mShowStatusBarAction->setChecked(visible); d->saveStatusBarVisibility(visible); d->mViewMainPage->setStatusBarVisible(visible); d->mBrowseMainPage->setStatusBarVisible(visible); } void MainWindow::slotPartCompleted() { d->updateActions(); const QUrl url = d->mContextManager->currentUrl(); if (!url.isEmpty() && GwenviewConfig::historyEnabled()) { d->mFileOpenRecentAction->addUrl(url); d->mGvCore->addUrlToRecentFiles(url); } if (KProtocolManager::supportsListing(url)) { const QUrl dirUrl = d->mContextManager->currentDirUrl(); d->mGvCore->addUrlToRecentFolders(dirUrl); } } void MainWindow::slotSelectionChanged() { if (d->mCurrentMainPageId == ViewMainPageId) { // The user selected a new file in the thumbnail view, since the // document view is visible, let's show it openSelectedDocuments(); } else { // No document view, we need to load the document to set the undo group // of document factory to the correct QUndoStack QModelIndex index = d->mThumbnailView->currentIndex(); KFileItem item; if (index.isValid()) { item = d->mDirModel->itemForIndex(index); } QUndoGroup *undoGroup = DocumentFactory::instance()->undoGroup(); if (!item.isNull() && !ArchiveUtils::fileItemIsDirOrArchive(item)) { QUrl url = item.url(); Document::Ptr doc = DocumentFactory::instance()->load(url); undoGroup->addStack(doc->undoStack()); undoGroup->setActiveStack(doc->undoStack()); } else { undoGroup->setActiveStack(nullptr); } } // Update UI d->updateActions(); updatePreviousNextActions(); // Start preloading int preloadDelay = d->mCurrentMainPageId == ViewMainPageId ? VIEW_PRELOAD_DELAY : BROWSE_PRELOAD_DELAY; QTimer::singleShot(preloadDelay, this, &MainWindow::preloadNextUrl); } void MainWindow::slotCurrentDirUrlChanged(const QUrl &url) { if (url.isValid()) { d->mUrlNavigator->setLocationUrl(url); d->mGoUpAction->setEnabled(url.path() != "/"); if (d->mCurrentMainPageId == BrowseMainPageId) { setCaption(d->mUrlNavigator->locationUrl().toDisplayString(QUrl::PreferLocalFile)); } } else { d->mGoUpAction->setEnabled(false); } } void MainWindow::slotDirModelNewItems() { if (d->mContextManager->selectionModel()->hasSelection()) { updatePreviousNextActions(); } } void MainWindow::slotDirListerCompleted() { if (d->mStartSlideShowWhenDirListerCompleted) { d->mStartSlideShowWhenDirListerCompleted = false; QTimer::singleShot(0, d->mToggleSlideShowAction, &QAction::trigger); } if (d->mContextManager->selectionModel()->hasSelection()) { updatePreviousNextActions(); } else if (!d->mContextManager->currentUrl().isValid()) { d->goToFirstDocument(); // Try to select the first directory in case there are no images to select if (!d->mContextManager->selectionModel()->hasSelection()) { const QModelIndex index = d->mThumbnailView->model()->index(0, 0); if (index.isValid()) { d->mThumbnailView->setCurrentIndex(index); } } } d->mThumbnailView->scrollToSelectedIndex(); d->mViewMainPage->thumbnailBar()->scrollToSelectedIndex(); d->mFullScreenContent->thumbnailBar()->scrollToSelectedIndex(); } void MainWindow::goToPrevious() { const QModelIndex currentIndex = d->mContextManager->selectionModel()->currentIndex(); QModelIndex previousIndex = d->mDirModel->index(currentIndex.row(), 0); constexpr QFlags<MimeTypeUtils::Kind> allowedKinds = MimeTypeUtils::KIND_RASTER_IMAGE | MimeTypeUtils::KIND_SVG_IMAGE | MimeTypeUtils::KIND_VIDEO; KFileItem fileItem; // Besides images also folders and archives are listed as well, // we need to skip them in the slideshow do { previousIndex = d->mDirModel->index(previousIndex.row() - 1, 0); fileItem = previousIndex.data(KDirModel::FileItemRole).value<KFileItem>(); } while (previousIndex.isValid() && !(allowedKinds & MimeTypeUtils::fileItemKind(fileItem))); if (!previousIndex.isValid() && (GwenviewConfig::navigationEndNotification() == SlideShow::NeverWarn || (GwenviewConfig::navigationEndNotification() == SlideShow::WarnOnSlideshow && !d->mSlideShow->isRunning() && !d->mFullScreenAction->isChecked()) || d->hudButtonBox)) { if (GwenviewConfig::wrapAfterLast()) { d->goToLastDocument(); } } else if (!previousIndex.isValid()) { showFirstDocumentReached(); } else { d->goTo(-1); } } void MainWindow::goToNext() { const QModelIndex currentIndex = d->mContextManager->selectionModel()->currentIndex(); QModelIndex nextIndex = d->mDirModel->index(currentIndex.row(), 0); constexpr QFlags<MimeTypeUtils::Kind> allowedKinds = MimeTypeUtils::KIND_RASTER_IMAGE | MimeTypeUtils::KIND_SVG_IMAGE | MimeTypeUtils::KIND_VIDEO; KFileItem fileItem; // Besides images also folders and archives are listed as well, // we need to skip them in the slideshow do { nextIndex = d->mDirModel->index(nextIndex.row() + 1, 0); fileItem = nextIndex.data(KDirModel::FileItemRole).value<KFileItem>(); } while (nextIndex.isValid() && !(allowedKinds & MimeTypeUtils::fileItemKind(fileItem))); if (!nextIndex.isValid() && (GwenviewConfig::navigationEndNotification() == SlideShow::NeverWarn || (GwenviewConfig::navigationEndNotification() == SlideShow::WarnOnSlideshow && !d->mSlideShow->isRunning() && !d->mFullScreenAction->isChecked()) || d->hudButtonBox)) { if (GwenviewConfig::wrapAfterLast()) { d->goToFirstDocument(); } } else if (!nextIndex.isValid()) { showLastDocumentReached(); } else { d->goTo(1); } } void MainWindow::goToFirst() { d->goToFirstDocument(); } void MainWindow::goToLast() { d->goToLastDocument(); } void MainWindow::goToUrl(const QUrl &url) { if (d->mCurrentMainPageId == ViewMainPageId) { d->mViewMainPage->openUrl(url); } QUrl dirUrl = url; dirUrl = dirUrl.adjusted(QUrl::RemoveFilename); if (dirUrl != d->mContextManager->currentDirUrl()) { d->mContextManager->setCurrentDirUrl(dirUrl); d->mGvCore->addUrlToRecentFolders(dirUrl); } d->mContextManager->setUrlToSelect(url); } void MainWindow::updatePreviousNextActions() { bool hasPrevious; bool hasNext; QModelIndex currentIndex = d->mContextManager->selectionModel()->currentIndex(); if (currentIndex.isValid() && !d->indexIsDirOrArchive(currentIndex)) { int row = currentIndex.row(); QModelIndex prevIndex = d->mDirModel->index(row - 1, 0); QModelIndex nextIndex = d->mDirModel->index(row + 1, 0); hasPrevious = ((GwenviewConfig::navigationEndNotification() != SlideShow::AlwaysWarn) && GwenviewConfig::wrapAfterLast()) || (prevIndex.isValid() && !d->indexIsDirOrArchive(prevIndex)); hasNext = ((GwenviewConfig::navigationEndNotification() != SlideShow::AlwaysWarn) && GwenviewConfig::wrapAfterLast()) || (nextIndex.isValid() && !d->indexIsDirOrArchive(nextIndex)); } else { hasPrevious = false; hasNext = false; } d->mGoToPreviousAction->setEnabled(hasPrevious); d->mGoToNextAction->setEnabled(hasNext); d->mGoToFirstAction->setEnabled(hasPrevious); d->mGoToLastAction->setEnabled(hasNext); } void MainWindow::leaveFullScreen() { if (d->mFullScreenAction->isChecked()) { d->mFullScreenAction->trigger(); } } void MainWindow::toggleFullScreen(bool checked) { setUpdatesEnabled(false); if (checked) { leaveSpotlightMode(); // Save MainWindow config now, this way if we quit while in // fullscreen, we are sure latest MainWindow changes are remembered. KConfigGroup saveConfigGroup = autoSaveConfigGroup(); if (!isFullScreen()) { // Save state if window manager did not already switch to fullscreen. saveMainWindowSettings(saveConfigGroup); d->mStateBeforeFullScreen.mToolBarVisible = toolBar()->isVisible(); } setAutoSaveSettings(saveConfigGroup, false); resetAutoSaveSettings(); // Go full screen KToggleFullScreenAction::setFullScreen(this, true); menuBar()->hide(); toolBar()->hide(); qApp->setProperty("KDE_COLOR_SCHEME_PATH", d->mGvCore->fullScreenPaletteName()); QApplication::setPalette(d->mGvCore->palette(GvCore::FullScreenPalette)); d->setScreenSaverEnabled(false); } else { setAutoSaveSettings(); // Back to normal qApp->setProperty("KDE_COLOR_SCHEME_PATH", QVariant()); QApplication::setPalette(d->mGvCore->palette(GvCore::NormalPalette)); d->mSlideShow->pause(); KToggleFullScreenAction::setFullScreen(this, false); menuBar()->setVisible(d->mShowMenuBarAction->isChecked()); toolBar()->setVisible(d->mStateBeforeFullScreen.mToolBarVisible); d->setScreenSaverEnabled(true); // See resizeEvent d->mFullScreenLeftAt = QDateTime::currentDateTime(); } d->mFullScreenContent->setFullScreenMode(checked); d->mBrowseMainPage->setFullScreenMode(checked); d->mViewMainPage->setFullScreenMode(checked); d->mSaveBar->setFullScreenMode(checked); toggleSideBar(d->sideBarVisibility()); toggleStatusBar(d->statusBarVisibility()); setUpdatesEnabled(true); d->autoAssignThumbnailProvider(); } void MainWindow::leaveSpotlightMode() { if (d->mSpotlightModeAction->isChecked()) { d->mSpotlightModeAction->trigger(); } } void MainWindow::toggleSpotlightMode(bool checked) { setUpdatesEnabled(false); if (checked) { leaveFullScreen(); KConfigGroup saveConfigGroup = autoSaveConfigGroup(); saveMainWindowSettings(saveConfigGroup); d->mStateBeforeFullScreen.mToolBarVisible = toolBar()->isVisible(); setAutoSaveSettings(saveConfigGroup, false); resetAutoSaveSettings(); menuBar()->hide(); toolBar()->hide(); } else { setAutoSaveSettings(); menuBar()->setVisible(d->mShowMenuBarAction->isChecked()); toolBar()->setVisible(d->mStateBeforeFullScreen.mToolBarVisible); } d->mViewMainPage->setSpotlightMode(checked); toggleSideBar(d->sideBarVisibility()); toggleStatusBar(d->statusBarVisibility()); setUpdatesEnabled(true); } void MainWindow::saveCurrent() { d->mGvCore->save(d->mContextManager->currentUrl()); } void MainWindow::saveCurrentAs() { d->mGvCore->saveAs(d->mContextManager->currentUrl()); } void MainWindow::reload() { if (d->mCurrentMainPageId == ViewMainPageId) { d->mViewMainPage->reload(); } else { d->mBrowseMainPage->reload(); } } void MainWindow::openFile() { const QUrl dirUrl = d->mContextManager->currentDirUrl(); auto dialog = new QFileDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); dialog->setDirectoryUrl(dirUrl); dialog->setWindowTitle(i18nc("@title:window", "Open Image")); dialog->setMimeTypeFilters(MimeTypeUtils::imageMimeTypes()); dialog->setAcceptMode(QFileDialog::AcceptOpen); connect(dialog, &QDialog::accepted, this, [this, dialog]() { if (!dialog->selectedUrls().isEmpty()) { openUrl(dialog->selectedUrls().at(0)); } }); dialog->show(); } void MainWindow::openUrl(const QUrl &url) { d->setActionsDisabledOnStartMainPageEnabled(true); d->mContextManager->setUrlToSelect(url); d->mViewAction->trigger(); } void MainWindow::showDocumentInFullScreen(const QUrl &url) { d->mContextManager->setUrlToSelect(url); d->mViewAction->trigger(); d->mFullScreenAction->trigger(); } void MainWindow::toggleSlideShow() { if (d->mSlideShow->isRunning()) { d->mSlideShow->pause(); } else { if (!d->mViewAction->isChecked()) { d->mViewAction->trigger(); } if (!d->mFullScreenAction->isChecked()) { d->mFullScreenAction->trigger(); } QList<QUrl> list; for (int pos = 0; pos < d->mDirModel->rowCount(); ++pos) { QModelIndex index = d->mDirModel->index(pos, 0); KFileItem item = d->mDirModel->itemForIndex(index); MimeTypeUtils::Kind kind = MimeTypeUtils::fileItemKind(item); switch (kind) { case MimeTypeUtils::KIND_SVG_IMAGE: case MimeTypeUtils::KIND_RASTER_IMAGE: case MimeTypeUtils::KIND_VIDEO: list << item.url(); break; default: break; } } d->mSlideShow->start(list); } updateSlideShowAction(); } void MainWindow::updateSlideShowAction() { if (d->mSlideShow->isRunning()) { d->mToggleSlideShowAction->setText(i18n("Pause Slideshow")); d->mToggleSlideShowAction->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-pause"))); } else { d->mToggleSlideShowAction->setText(d->mFullScreenAction->isChecked() ? i18n("Resume Slideshow") : i18n("Start Slideshow")); d->mToggleSlideShowAction->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start"))); } } bool MainWindow::queryClose() { saveConfig(); QList<QUrl> list = DocumentFactory::instance()->modifiedDocumentList(); if (list.size() == 0) { return true; } KGuiItem yes(i18n("Save All Changes"), "document-save-all"); KGuiItem no(i18n("Discard Changes"), "delete"); QString msg = i18np("One image has been modified.", "%1 images have been modified.", list.size()) + '\n' + i18n("If you quit now, your changes will be lost."); int answer = KMessageBox::warningTwoActionsCancel(this, msg, QString() /* caption */, yes, no); switch (answer) { case KMessageBox::PrimaryAction: d->mGvCore->saveAll(); // We need to wait a bit because the DocumentFactory is notified about // saved documents through a queued connection. qApp->processEvents(); return DocumentFactory::instance()->modifiedDocumentList().isEmpty(); case KMessageBox::SecondaryAction: return true; default: // cancel return false; } } void MainWindow::showConfigDialog(int page) { // Save first so changes like thumbnail zoom level are not lost when reloading config saveConfig(); auto dialog = new ConfigDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); connect(dialog, &KConfigDialog::settingsChanged, this, &MainWindow::loadConfig); dialog->setCurrentPage(page); dialog->show(); } void MainWindow::configureShortcuts() { guiFactory()->showConfigureShortcutsDialog(); } void MainWindow::toggleMenuBar() { if (!d->mFullScreenAction->isChecked()) { if (!d->mShowMenuBarAction->isChecked() && (!toolBar()->isVisible() || !toolBar()->actions().contains(d->mHamburgerMenu))) { const QString accel = d->mShowMenuBarAction->shortcut().toString(QKeySequence::NativeText); KMessageBox::information(this, i18n("This will hide the menu bar completely." " You can show it again by typing %1.", accel), i18n("Hide menu bar"), QLatin1String("HideMenuBarWarning")); } menuBar()->setVisible(d->mShowMenuBarAction->isChecked()); } } void MainWindow::loadConfig() { d->mDirModel->setBlackListedExtensions(GwenviewConfig::blackListedExtensions()); d->mDirModel->adjustKindFilter(MimeTypeUtils::KIND_VIDEO, GwenviewConfig::listVideos()); if (GwenviewConfig::historyEnabled()) { d->mFileOpenRecentAction->loadEntries(KConfigGroup(KSharedConfig::openConfig(), "Recent Files")); const auto mFileOpenRecentActionUrls = d->mFileOpenRecentAction->urls(); for (const QUrl &url : mFileOpenRecentActionUrls) { d->mGvCore->addUrlToRecentFiles(url); } } else { d->mFileOpenRecentAction->clear(); } d->mFileOpenRecentAction->setVisible(GwenviewConfig::historyEnabled()); d->mStartMainPage->loadConfig(); d->mViewMainPage->loadConfig(); d->mBrowseMainPage->loadConfig(); d->mContextManager->loadConfig(); d->mSideBar->loadConfig(); d->loadSplitterConfig(); d->loadInformationSplitterConfig(); } void MainWindow::saveConfig() { d->mFileOpenRecentAction->saveEntries(KConfigGroup(KSharedConfig::openConfig(), "Recent Files")); d->mViewMainPage->saveConfig(); d->mBrowseMainPage->saveConfig(); d->mContextManager->saveConfig(); d->saveSplitterConfig(); d->saveInformationSplitterConfig(); GwenviewConfig::setFullScreenModeActive(isFullScreen()); GwenviewConfig::setSpotlightMode(d->mSpotlightModeAction->isChecked()); // Save the last used version when Gwenview closes so we know which settings/features the user // is aware of which is needed for migration. The version format is: two digits each for // major minor bugfix version. Never decrease this number. Increase it when needed. GwenviewConfig::setLastUsedVersion(210800); } void MainWindow::print() { d->print(Private::ShowPreview::No); } void MainWindow::printPreview() { d->print(Private::ShowPreview::Yes); } void MainWindow::preloadNextUrl() { static bool disablePreload = qgetenv("GV_MAX_UNREFERENCED_IMAGES") == "0"; if (disablePreload) { qCDebug(GWENVIEW_APP_LOG) << "Preloading disabled"; return; } QItemSelection selection = d->mContextManager->selectionModel()->selection(); if (selection.size() != 1) { return; } QModelIndexList indexList = selection.indexes(); if (indexList.isEmpty()) { return; } QModelIndex index = indexList.at(0); if (!index.isValid()) { return; } if (d->mCurrentMainPageId == ViewMainPageId) { // If we are in view mode, preload the next url, otherwise preload the // selected one int offset = d->mPreloadDirectionIsForward ? 1 : -1; index = d->mDirModel->sibling(index.row() + offset, index.column(), index); if (!index.isValid()) { return; } } KFileItem item = d->mDirModel->itemForIndex(index); if (!ArchiveUtils::fileItemIsDirOrArchive(item)) { QUrl url = item.url(); if (url.isLocalFile()) { QSize size = d->mViewStackedWidget->size(); d->mPreloader->preload(url, size); } } } // Set a sane initial window size QSize MainWindow::sizeHint() const { return KXmlGuiWindow::sizeHint().expandedTo(QSize(1020, 700)); } void MainWindow::showEvent(QShowEvent *event) { // We need to delay initializing the action state until the menu bar has // been initialized, that's why it's done only in the showEvent() if (GwenviewConfig::lastUsedVersion() == -1 && toolBar()->actions().contains(d->mHamburgerMenu)) { menuBar()->hide(); } d->mShowMenuBarAction->setChecked(menuBar()->isVisible()); KXmlGuiWindow::showEvent(event); } void MainWindow::resizeEvent(QResizeEvent *event) { KXmlGuiWindow::resizeEvent(event); // This is a small hack to execute code after leaving fullscreen, and after // the window has been resized back to its former size. if (d->mFullScreenLeftAt.isValid() && d->mFullScreenLeftAt.secsTo(QDateTime::currentDateTime()) < 2) { if (d->mCurrentMainPageId == BrowseMainPageId) { d->mThumbnailView->scrollToSelectedIndex(); } d->mFullScreenLeftAt = QDateTime(); } } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { Q_UNUSED(obj); Q_UNUSED(event); #ifdef Q_OS_OSX /** * handle Mac OS X file open events (only exist on OS X) */ if (event->type() == QEvent::FileOpen) { QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent *>(event); openUrl(fileOpenEvent->url()); return true; } #endif if (obj == d->mThumbnailView->viewport()) { switch (event->type()) { case QEvent::MouseButtonPress: case QEvent::MouseButtonDblClick: mouseButtonNavigate(static_cast<QMouseEvent *>(event)); break; default:; } } return false; } void MainWindow::mousePressEvent(QMouseEvent *event) { mouseButtonNavigate(event); KXmlGuiWindow::mousePressEvent(event); } void MainWindow::mouseDoubleClickEvent(QMouseEvent *event) { mouseButtonNavigate(event); KXmlGuiWindow::mouseDoubleClickEvent(event); } void MainWindow::mouseButtonNavigate(QMouseEvent *event) { switch (event->button()) { case Qt::ForwardButton: if (d->mGoToNextAction->isEnabled()) { d->mGoToNextAction->trigger(); return; } break; case Qt::BackButton: if (d->mGoToPreviousAction->isEnabled()) { d->mGoToPreviousAction->trigger(); return; } break; default:; } } void MainWindow::setDistractionFreeMode(bool value) { d->mFullScreenContent->setDistractionFreeMode(value); } void MainWindow::saveProperties(KConfigGroup &group) { group.writeEntry(SESSION_CURRENT_PAGE_KEY, int(d->mCurrentMainPageId)); group.writeEntry(SESSION_URL_KEY, d->mContextManager->currentUrl().toString()); } void MainWindow::readProperties(const KConfigGroup &group) { const QUrl url = group.readEntry(SESSION_URL_KEY, QUrl()); if (url.isValid()) { goToUrl(url); } MainPageId pageId = MainPageId(group.readEntry(SESSION_CURRENT_PAGE_KEY, int(StartMainPageId))); if (pageId == StartMainPageId) { showStartMainPage(); } else if (pageId == BrowseMainPageId) { d->mBrowseAction->trigger(); } else { d->mViewAction->trigger(); } } void MainWindow::showFirstDocumentReached() { if (d->hudButtonBox || d->mCurrentMainPageId != ViewMainPageId) { return; } d->hudButtonBox = new HudButtonBox; d->hudButtonBox->setText(i18n("You reached the first document, what do you want to do?")); d->hudButtonBox->addButton(i18n("Stay There")); d->hudButtonBox->addAction(d->mGoToLastAction, i18n("Go to the Last Document")); d->hudButtonBox->addAction(d->mBrowseAction, i18n("Go Back to the Document List")); d->hudButtonBox->addCountDown(15000); d->mViewMainPage->showMessageWidget(d->hudButtonBox, Qt::AlignCenter); } void MainWindow::showLastDocumentReached() { if (d->hudButtonBox || d->mCurrentMainPageId != ViewMainPageId) { return; } d->hudButtonBox = new HudButtonBox; d->hudButtonBox->setText(i18n("You reached the last document, what do you want to do?")); d->hudButtonBox->addButton(i18n("Stay There")); d->hudButtonBox->addAction(d->mGoToFirstAction, i18n("Go to the First Document")); d->hudButtonBox->addAction(d->mBrowseAction, i18n("Go Back to the Document List")); d->hudButtonBox->addCountDown(15000); d->mViewMainPage->showMessageWidget(d->hudButtonBox, Qt::AlignCenter); } void MainWindow::replaceLocation() { QLineEdit *lineEdit = d->mUrlNavigator->editor()->lineEdit(); // If the text field currently has focus and everything is selected, // pressing the keyboard shortcut returns the whole thing to breadcrumb mode if (d->mUrlNavigator->isUrlEditable() && lineEdit->hasFocus() && lineEdit->selectedText() == lineEdit->text()) { d->mUrlNavigator->setUrlEditable(false); } else { d->mUrlNavigator->setUrlEditable(true); d->mUrlNavigator->setFocus(); lineEdit->selectAll(); } } void MainWindow::onFocusChanged(QWidget *old, QWidget *now) { if (old == nullptr) { if (now != nullptr && isFullScreen()) { d->setScreenSaverEnabled(false); } } else { if (now == nullptr) { d->setScreenSaverEnabled(true); } } } } // namespace #include "moc_mainwindow.cpp"
83,711
C++
.cpp
1,895
36.685488
160
0.675518
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,893
startmainpage.cpp
KDE_gwenview/app/startmainpage.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "startmainpage.h" #include <config-gwenview.h> // Qt #include <QListView> #include <QMenu> #ifdef GTK_WORKAROUND_BROKE_IN_KF5_PORT #include <QPlastiqueStyle> #endif #include <QIcon> #include <QStyledItemDelegate> // KF #include <KFilePlacesModel> #include <KLocalizedString> // Local #include "gwenview_app_debug.h" #include <gvcore.h> #include <lib/dialogguard.h> #include <lib/flowlayout.h> #include <lib/gvdebug.h> #include <lib/gwenviewconfig.h> #include <lib/scrollerutils.h> #include <lib/thumbnailprovider/thumbnailprovider.h> #include <lib/thumbnailview/abstractthumbnailviewhelper.h> #include <lib/thumbnailview/previewitemdelegate.h> #include <ui_startmainpage.h> #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE #include <lib/semanticinfo/tagmodel.h> #endif namespace Gwenview { class HistoryThumbnailViewHelper : public AbstractThumbnailViewHelper { public: HistoryThumbnailViewHelper(QObject *parent) : AbstractThumbnailViewHelper(parent) { } void showContextMenu(QWidget *) override { } void showMenuForUrlDroppedOnViewport(QWidget *, const QList<QUrl> &) override { } void showMenuForUrlDroppedOnDir(QWidget *, const QList<QUrl> &, const QUrl &) override { } }; struct StartMainPagePrivate : public Ui_StartMainPage { StartMainPage *q = nullptr; GvCore *mGvCore = nullptr; KFilePlacesModel *mBookmarksModel = nullptr; ThumbnailProvider *mRecentFilesThumbnailProvider = nullptr; bool mSearchUiInitialized; void setupSearchUi() { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_BALOO mTagView->setModel(TagModel::createAllTagsModel(mTagView, mGvCore->semanticInfoBackEnd())); mTagView->show(); mTagLabel->hide(); #else mTagView->hide(); mTagLabel->hide(); #endif } void updateHistoryTab() { mHistoryWidget->setVisible(GwenviewConfig::historyEnabled()); mHistoryDisabledLabel->setVisible(!GwenviewConfig::historyEnabled()); } void setupHistoryView(ThumbnailView *view) { view->setThumbnailViewHelper(new HistoryThumbnailViewHelper(view)); auto delegate = new PreviewItemDelegate(view); delegate->setContextBarActions(PreviewItemDelegate::NoAction); delegate->setTextElideMode(Qt::ElideLeft); view->setItemDelegate(delegate); view->setThumbnailWidth(128); view->setCreateThumbnailsForRemoteUrls(false); QModelIndex index = view->model()->index(0, 0); if (index.isValid()) { view->setCurrentIndex(index); } } }; static void initViewPalette(QAbstractItemView *view, const QColor &fgColor) { QWidget *viewport = view->viewport(); QPalette palette = viewport->palette(); palette.setColor(viewport->backgroundRole(), Qt::transparent); palette.setColor(QPalette::WindowText, fgColor); palette.setColor(QPalette::Text, fgColor); // QListView uses QStyledItemDelegate, which uses the view palette for // foreground color, while KFilePlacesView uses the viewport palette. viewport->setPalette(palette); view->setPalette(palette); } static bool styleIsGtkBased() { const char *name = QApplication::style()->metaObject()->className(); return qstrcmp(name, "QGtkStyle") == 0; } StartMainPage::StartMainPage(QWidget *parent, GvCore *gvCore) : QFrame(parent) , d(new StartMainPagePrivate) { d->mRecentFilesThumbnailProvider = nullptr; d->q = this; d->mGvCore = gvCore; d->mSearchUiInitialized = false; d->setupUi(this); if (styleIsGtkBased()) { #ifdef GTK_WORKAROUND_BROKE_IN_KF5_PORT // Gtk-based styles do not apply the correct background color on tabs. // As a workaround, use the Plastique style instead. QStyle *fix = new QPlastiqueStyle(); fix->setParent(this); d->mHistoryWidget->tabBar()->setStyle(fix); d->mPlacesTagsWidget->tabBar()->setStyle(fix); #endif } setFrameStyle(QFrame::NoFrame); // Bookmark view d->mBookmarksModel = new KFilePlacesModel(this); d->mBookmarksView->setModel(d->mBookmarksModel); d->mBookmarksView->setAutoResizeItemsEnabled(false); connect(d->mBookmarksView, &KFilePlacesView::urlChanged, this, &StartMainPage::urlSelected); // Tag view connect(d->mTagView, &QListView::clicked, this, &StartMainPage::slotTagViewClicked); // Recent folders view connect(d->mRecentFoldersView, &Gwenview::ThumbnailView::indexActivated, this, &StartMainPage::slotListViewActivated); connect(d->mRecentFoldersView, &Gwenview::ThumbnailView::customContextMenuRequested, this, &StartMainPage::showContextMenu); // Recent files view connect(d->mRecentFilesView, &Gwenview::ThumbnailView::indexActivated, this, &StartMainPage::slotListViewActivated); connect(d->mRecentFilesView, &Gwenview::ThumbnailView::customContextMenuRequested, this, &StartMainPage::showContextMenu); d->updateHistoryTab(); connect(GwenviewConfig::self(), &GwenviewConfig::configChanged, this, &StartMainPage::loadConfig); connect(qApp, &QApplication::paletteChanged, this, [this]() { applyPalette(d->mGvCore->palette(GvCore::NormalViewPalette)); }); d->mRecentFoldersView->setFocus(); ScrollerUtils::setQScroller(d->mBookmarksView->viewport()); d->mBookmarksView->viewport()->installEventFilter(this); } StartMainPage::~StartMainPage() { delete d->mRecentFilesThumbnailProvider; delete d; } bool StartMainPage::eventFilter(QObject *, QEvent *event) { if (event->type() == QEvent::MouseMove) { auto mouseEvent = static_cast<QMouseEvent *>(event); if (mouseEvent->source() == Qt::MouseEventSynthesizedByQt) { return true; } } return false; } void StartMainPage::slotTagViewClicked(const QModelIndex &index) { #ifdef GWENVIEW_SEMANTICINFO_BACKEND_BALOO if (!index.isValid()) { return; } // FIXME: Check label encoding const QString tag = index.data().toString(); Q_EMIT urlSelected(QUrl("tags:/" + tag)); #endif } void StartMainPage::applyPalette(const QPalette &newPalette) { QColor fgColor = newPalette.text().color(); QPalette pal = palette(); pal.setBrush(backgroundRole(), newPalette.base()); pal.setBrush(QPalette::Button, newPalette.base()); pal.setBrush(QPalette::WindowText, fgColor); pal.setBrush(QPalette::ButtonText, fgColor); pal.setBrush(QPalette::Text, fgColor); setPalette(pal); initViewPalette(d->mBookmarksView, fgColor); initViewPalette(d->mTagView, fgColor); initViewPalette(d->mRecentFoldersView, fgColor); initViewPalette(d->mRecentFilesView, fgColor); } void StartMainPage::slotListViewActivated(const QModelIndex &index) { if (!index.isValid()) { return; } QVariant data = index.data(KFilePlacesModel::UrlRole); QUrl url = data.toUrl(); // Prevent dir lister error if (!url.isValid()) { qCCritical(GWENVIEW_APP_LOG) << "Tried to open an invalid url"; return; } Q_EMIT urlSelected(url); } void StartMainPage::showEvent(QShowEvent *event) { if (GwenviewConfig::historyEnabled()) { if (!d->mRecentFoldersView->model()) { d->mRecentFoldersView->setModel(d->mGvCore->recentFoldersModel()); d->setupHistoryView(d->mRecentFoldersView); } if (!d->mRecentFilesView->model()) { d->mRecentFilesView->setModel(d->mGvCore->recentFilesModel()); d->mRecentFilesThumbnailProvider = new ThumbnailProvider(); d->mRecentFilesView->setThumbnailProvider(d->mRecentFilesThumbnailProvider); d->setupHistoryView(d->mRecentFilesView); } } if (!d->mSearchUiInitialized) { d->mSearchUiInitialized = true; d->setupSearchUi(); } QFrame::showEvent(event); } void StartMainPage::showContextMenu(const QPoint &pos) { // Create menu DialogGuard<QMenu> menu(this); QAction *addAction = menu->addAction(QIcon::fromTheme(QStringLiteral("bookmark-new")), QString()); QAction *forgetAction = menu->addAction(QIcon::fromTheme(QStringLiteral("edit-delete")), QString()); menu->addSeparator(); QAction *forgetAllAction = menu->addAction(QIcon::fromTheme(QStringLiteral("edit-delete-all")), QString()); if (d->mHistoryWidget->currentWidget() == d->mRecentFoldersTab) { addAction->setText(i18nc("@action Recent Folders view", "Add Folder to Places")); forgetAction->setText(i18nc("@action Recent Folders view", "Forget This Folder")); forgetAllAction->setText(i18nc("@action Recent Folders view", "Forget All Folders")); } else if (d->mHistoryWidget->currentWidget() == d->mRecentFilesTab) { addAction->setText(i18nc("@action Recent Files view", "Add Containing Folder to Places")); forgetAction->setText(i18nc("@action Recent Files view", "Forget This File")); forgetAllAction->setText(i18nc("@action Recent Files view", "Forget All Files")); } else { GV_WARN_AND_RETURN("Context menu not implemented on this tab page"); } const QAbstractItemView *view = qobject_cast<QAbstractItemView *>(sender()); const QModelIndex index = view->indexAt(pos); addAction->setEnabled(index.isValid()); forgetAction->setEnabled(index.isValid()); // Handle menu const QAction *action = menu->exec(view->mapToGlobal(pos)); if (!action) { return; } const QVariant data = index.data(KFilePlacesModel::UrlRole); QUrl url = data.toUrl(); if (action == addAction) { if (d->mHistoryWidget->currentWidget() == d->mRecentFilesTab) { url = url.adjusted(QUrl::RemoveFilename); } QString text = url.adjusted(QUrl::StripTrailingSlash).fileName(); if (text.isEmpty()) { text = url.toDisplayString(); } d->mBookmarksModel->addPlace(text, url); } else if (action == forgetAction) { view->model()->removeRow(index.row()); if (d->mHistoryWidget->currentWidget() == d->mRecentFilesTab) { Q_EMIT recentFileRemoved(url); } } else if (action == forgetAllAction) { view->model()->removeRows(0, view->model()->rowCount()); if (d->mHistoryWidget->currentWidget() == d->mRecentFilesTab) { Q_EMIT recentFilesCleared(); } } } void StartMainPage::loadConfig() { d->updateHistoryTab(); applyPalette(d->mGvCore->palette(GvCore::NormalViewPalette)); } ThumbnailView *StartMainPage::recentFoldersView() const { return d->mRecentFoldersView; } } // namespace #include "moc_startmainpage.cpp"
11,490
C++
.cpp
297
33.717172
128
0.713234
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,894
infocontextmanageritem.cpp
KDE_gwenview/app/infocontextmanageritem.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "infocontextmanageritem.h" // Qt #include <QLabel> #include <QPointer> #include <QPushButton> #include <QScrollArea> #include <QVBoxLayout> // KF #include <KFileItem> #include <KLocalizedString> // Local #include "imagemetainfodialog.h" #include "sidebar.h" #include <lib/archiveutils.h> #include <lib/contextmanager.h> #include <lib/document/document.h> #include <lib/document/documentfactory.h> #include <lib/eventwatcher.h> #include <lib/gvdebug.h> #include <lib/gwenviewconfig.h> #include <lib/preferredimagemetainfomodel.h> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_APP_LOG) << x #else #define LOG(x) ; #endif /** * This widget is capable of showing multiple lines of key/value pairs. */ class KeyValueWidget : public QWidget { struct Row { Row(QWidget *parent) : keyLabel(new QLabel(parent)) , valueLabel(new QLabel(parent)) { initLabel(keyLabel); initLabel(valueLabel); QPalette pal = keyLabel->palette(); QColor color = pal.color(QPalette::WindowText); color.setAlphaF(0.65); pal.setColor(QPalette::WindowText, color); keyLabel->setPalette(pal); valueLabel->setIndent(parent->fontInfo().pixelSize()); } ~Row() { delete keyLabel; delete valueLabel; } int setLabelGeometries(int rowY, int labelWidth) { int labelHeight = keyLabel->heightForWidth(labelWidth); keyLabel->setGeometry(0, rowY, labelWidth, labelHeight); rowY += labelHeight; labelHeight = valueLabel->heightForWidth(labelWidth); valueLabel->setGeometry(0, rowY, labelWidth, labelHeight); rowY += labelHeight; return rowY; } int heightForWidth(int width) const { return keyLabel->heightForWidth(width) + valueLabel->heightForWidth(width); } static void initLabel(QLabel *label) { label->setWordWrap(true); label->show(); label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); } QLabel *const keyLabel; QLabel *const valueLabel; }; public: explicit KeyValueWidget(QWidget *parent = nullptr) : QWidget(parent) { QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Fixed); policy.setHeightForWidth(true); setSizePolicy(policy); } ~KeyValueWidget() override { qDeleteAll(mRows); mRows.clear(); } QSize sizeHint() const override { int width = 150; int height = heightForWidth(width); return QSize(width, height); } int heightForWidth(int w) const override { int height = 0; for (Row *row : qAsConst(mRows)) { height += row->heightForWidth(w); } return height; } void clear() { qDeleteAll(mRows); mRows.clear(); updateGeometry(); } void addRow(const QString &key, const QString &value) { Row *row = new Row(this); row->keyLabel->setText(i18nc("@item:intext %1 is a key, we append a colon to it. A value is displayed after", "%1:", key)); row->valueLabel->setText(value); mRows << row; } static bool rowsLessThan(const Row *row1, const Row *row2) { return row1->keyLabel->text() < row2->keyLabel->text(); } void finishAddRows() { std::sort(mRows.begin(), mRows.end(), KeyValueWidget::rowsLessThan); updateGeometry(); } void layoutRows() { // Layout labels manually: I tried to use a QVBoxLayout but for some // reason when using software animations the widget blinks when going // from one image to another int rowY = 0; const int labelWidth = width(); for (Row *row : qAsConst(mRows)) { rowY = row->setLabelGeometries(rowY, labelWidth); } } protected: void showEvent(QShowEvent *event) override { QWidget::showEvent(event); layoutRows(); } void resizeEvent(QResizeEvent *event) override { QWidget::resizeEvent(event); layoutRows(); } private: QVector<Row *> mRows; }; struct InfoContextManagerItemPrivate { InfoContextManagerItem *q; SideBarGroup *mGroup; // One selection fields QScrollArea *mOneFileWidget; KeyValueWidget *mKeyValueWidget; Document::Ptr mDocument; // Multiple selection fields QLabel *mMultipleFilesLabel; QPointer<ImageMetaInfoDialog> mImageMetaInfoDialog; void updateMetaInfoDialog() { if (!mImageMetaInfoDialog) { return; } ImageMetaInfoModel *model = mDocument ? mDocument->metaInfo() : nullptr; mImageMetaInfoDialog->setMetaInfo(model, GwenviewConfig::preferredMetaInfoKeyList()); } void setupGroup() { mOneFileWidget = new QScrollArea(); mOneFileWidget->setFrameStyle(QFrame::NoFrame); mOneFileWidget->setWidgetResizable(true); mKeyValueWidget = new KeyValueWidget; auto moreLabel = new QLabel(mOneFileWidget); moreLabel->setText(QStringLiteral("<a href='#'>%1</a>").arg(i18nc("@action show more image meta info", "Show more details..."))); // for some reason, this label appears much further down the page without the following line moreLabel->setAlignment(Qt::AlignLeft); auto content = new QWidget; auto layout = new QVBoxLayout(content); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mKeyValueWidget); layout->addWidget(moreLabel); mOneFileWidget->setWidget(content); mMultipleFilesLabel = new QLabel(); mGroup = new SideBarGroup(i18nc("@title:group", "Image Information")); q->setWidget(mGroup); mGroup->addWidget(mOneFileWidget); mGroup->addWidget(mMultipleFilesLabel); EventWatcher::install(mGroup, QEvent::Show, q, SLOT(updateSideBarContent())); QObject::connect(moreLabel, &QLabel::linkActivated, q, &InfoContextManagerItem::showMetaInfoDialog); } void forgetCurrentDocument() { if (mDocument) { QObject::disconnect(mDocument.data(), nullptr, q, nullptr); // "Garbage collect" document mDocument = nullptr; } } }; InfoContextManagerItem::InfoContextManagerItem(ContextManager *manager) : AbstractContextManagerItem(manager) , d(new InfoContextManagerItemPrivate) { d->q = this; d->setupGroup(); connect(contextManager(), &ContextManager::selectionChanged, this, &InfoContextManagerItem::updateSideBarContent); connect(contextManager(), &ContextManager::selectionDataChanged, this, &InfoContextManagerItem::updateSideBarContent); } InfoContextManagerItem::~InfoContextManagerItem() { delete d; } void InfoContextManagerItem::updateSideBarContent() { LOG("updateSideBarContent"); if (!d->mGroup->isVisible()) { LOG("updateSideBarContent: not visible, not updating"); return; } LOG("updateSideBarContent: really updating"); KFileItemList itemList = contextManager()->selectedFileItemList(); if (itemList.isEmpty()) { d->forgetCurrentDocument(); d->mOneFileWidget->hide(); d->mMultipleFilesLabel->hide(); d->updateMetaInfoDialog(); return; } KFileItem item = itemList.first(); if (itemList.count() == 1 && !ArchiveUtils::fileItemIsDirOrArchive(item)) { fillOneFileGroup(item); } else { fillMultipleItemsGroup(itemList); } d->updateMetaInfoDialog(); } void InfoContextManagerItem::fillOneFileGroup(const KFileItem &item) { d->mOneFileWidget->show(); d->mMultipleFilesLabel->hide(); d->forgetCurrentDocument(); d->mDocument = DocumentFactory::instance()->load(item.url()); connect(d->mDocument.data(), &Document::metaInfoUpdated, this, &InfoContextManagerItem::updateOneFileInfo); d->updateMetaInfoDialog(); updateOneFileInfo(); } void InfoContextManagerItem::fillMultipleItemsGroup(const KFileItemList &itemList) { d->forgetCurrentDocument(); int folderCount = 0, fileCount = 0; for (const KFileItem &item : itemList) { if (item.isDir()) { folderCount++; } else { fileCount++; } } if (folderCount == 0) { d->mMultipleFilesLabel->setText(i18ncp("@label", "%1 file selected", "%1 files selected", fileCount)); } else if (fileCount == 0) { d->mMultipleFilesLabel->setText(i18ncp("@label", "%1 folder selected", "%1 folders selected", folderCount)); } else { d->mMultipleFilesLabel->setText(i18nc("@label. The two parameters are strings like '2 folders' and '1 file'.", "%1 and %2 selected", i18np("%1 folder", "%1 folders", folderCount), i18np("%1 file", "%1 files", fileCount))); } d->mOneFileWidget->hide(); d->mMultipleFilesLabel->show(); } void InfoContextManagerItem::updateOneFileInfo() { if (!d->mDocument) { return; } ImageMetaInfoModel *metaInfoModel = d->mDocument->metaInfo(); d->mKeyValueWidget->clear(); const QStringList preferredMetaInfoKeyList = GwenviewConfig::preferredMetaInfoKeyList(); for (const QString &key : preferredMetaInfoKeyList) { QString label; QString value; metaInfoModel->getInfoForKey(key, &label, &value); if (!label.isEmpty() && !value.isEmpty()) { d->mKeyValueWidget->addRow(label, value); } } d->mKeyValueWidget->finishAddRows(); d->mKeyValueWidget->layoutRows(); } void InfoContextManagerItem::showMetaInfoDialog() { if (!d->mImageMetaInfoDialog) { d->mImageMetaInfoDialog = new ImageMetaInfoDialog(d->mOneFileWidget); d->mImageMetaInfoDialog->setAttribute(Qt::WA_DeleteOnClose, true); connect(d->mImageMetaInfoDialog.data(), &ImageMetaInfoDialog::preferredMetaInfoKeyListChanged, this, &InfoContextManagerItem::slotPreferredMetaInfoKeyListChanged); } d->mImageMetaInfoDialog->setMetaInfo(d->mDocument ? d->mDocument->metaInfo() : nullptr, GwenviewConfig::preferredMetaInfoKeyList()); d->mImageMetaInfoDialog->show(); } void InfoContextManagerItem::slotPreferredMetaInfoKeyListChanged(const QStringList &list) { GwenviewConfig::setPreferredMetaInfoKeyList(list); GwenviewConfig::self()->save(); updateOneFileInfo(); } } // namespace #include "moc_infocontextmanageritem.cpp"
11,673
C++
.cpp
329
28.787234
137
0.666224
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,895
imagemetainfodialog.cpp
KDE_gwenview/app/imagemetainfodialog.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "imagemetainfodialog.h" // Qt #include <QApplication> #include <QDialogButtonBox> #include <QHeaderView> #include <QPainter> #include <QPushButton> #include <QStyledItemDelegate> #include <QTreeView> #include <QVBoxLayout> // KF #include <KLocalizedString> // STL #include <memory> // Local #include <lib/preferredimagemetainfomodel.h> namespace Gwenview { class MetaInfoDelegate : public QStyledItemDelegate { public: MetaInfoDelegate(QObject *parent) : QStyledItemDelegate(parent) { } protected: void paint(QPainter *painter, const QStyleOptionViewItem &_option, const QModelIndex &index) const override { QStyleOptionViewItem option = _option; if (!index.parent().isValid()) { option.displayAlignment = Qt::AlignCenter | Qt::AlignBottom; option.font.setBold(true); } QStyledItemDelegate::paint(painter, option, index); if (!index.parent().isValid()) { painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); } } QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override { QSize sh = QStyledItemDelegate::sizeHint(option, index); if (!index.parent().isValid()) { sh.setHeight(sh.height() * 3 / 2); } return sh; } }; /** * A tree view which is always fully expanded */ class ExpandedTreeView : public QTreeView { public: explicit ExpandedTreeView(QWidget *parent) : QTreeView(parent) { } protected: void rowsInserted(const QModelIndex &parent, int start, int end) override { QTreeView::rowsInserted(parent, start, end); if (!parent.isValid()) { for (int row = start; row <= end; ++row) { setUpRootIndex(row); } } } void reset() override { QTreeView::reset(); if (model()) { for (int row = 0; row < model()->rowCount(); ++row) { setUpRootIndex(row); } } } private: void setUpRootIndex(int row) { expand(model()->index(row, 0)); setFirstColumnSpanned(row, QModelIndex(), true); } }; struct ImageMetaInfoDialogPrivate { std::unique_ptr<PreferredImageMetaInfoModel> mModel; QTreeView *mTreeView; }; ImageMetaInfoDialog::ImageMetaInfoDialog(QWidget *parent) : QDialog(parent) , d(new ImageMetaInfoDialogPrivate) { d->mTreeView = new ExpandedTreeView(this); d->mTreeView->setRootIsDecorated(false); d->mTreeView->setIndentation(0); d->mTreeView->setItemDelegate(new MetaInfoDelegate(d->mTreeView)); setWindowTitle(i18nc("@title:window", "Image Information")); setLayout(new QVBoxLayout); layout()->addWidget(d->mTreeView); auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); layout()->addWidget(buttonBox); connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } ImageMetaInfoDialog::~ImageMetaInfoDialog() { delete d; } void ImageMetaInfoDialog::setMetaInfo(ImageMetaInfoModel *model, const QStringList &list) { if (model) { d->mModel = std::make_unique<PreferredImageMetaInfoModel>(model, list); connect(d->mModel.get(), &PreferredImageMetaInfoModel::preferredMetaInfoKeyListChanged, this, &ImageMetaInfoDialog::preferredMetaInfoKeyListChanged); } else { d->mModel.reset(nullptr); } d->mTreeView->setModel(d->mModel.get()); const int marginSize = QApplication::style()->pixelMetric(QStyle::PM_LayoutLeftMargin); d->mTreeView->header()->resizeSection(0, sizeHint().width() / 2 - marginSize * 2); } QSize ImageMetaInfoDialog::sizeHint() const { return QSize(400, 300); } } // namespace #include "moc_imagemetainfodialog.cpp"
4,713
C++
.cpp
142
28.556338
157
0.705391
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,896
sidebar.cpp
KDE_gwenview/app/sidebar.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "sidebar.h" // Qt #include <QAction> #include <QIcon> #include <QLabel> #include <QMenu> #include <QStyle> #include <QStyleOptionTab> #include <QToolButton> #include <QVBoxLayout> // KF #include <KIconLoader> // Local #include <lib/gwenviewconfig.h> #include <lib/signalblocker.h> namespace Gwenview { /** * A button which always leave room for an icon, even if there is none, so that * all button texts are correctly aligned. */ class SideBarButton : public QToolButton { protected: void paintEvent(QPaintEvent *event) override { forceIcon(); QToolButton::paintEvent(event); } QSize sizeHint() const override { const_cast<SideBarButton *>(this)->forceIcon(); return QToolButton::sizeHint(); } private: void forceIcon() { if (!icon().isNull()) { return; } // Assign an empty icon to the button if there is no icon associated // with the action so that all button texts are correctly aligned. QSize wantedSize = iconSize(); if (mEmptyIcon.isNull() || mEmptyIcon.actualSize(wantedSize) != wantedSize) { QPixmap pix(wantedSize); pix.fill(Qt::transparent); mEmptyIcon.addPixmap(pix); } setIcon(mEmptyIcon); } QIcon mEmptyIcon; }; //- SideBarGroup --------------------------------------------------------------- struct SideBarGroupPrivate { QFrame *mContainer = nullptr; QLabel *mTitleLabel = nullptr; }; SideBarGroup::SideBarGroup(const QString &title) : QFrame() , d(new SideBarGroupPrivate) { d->mContainer = nullptr; d->mTitleLabel = new QLabel(this); d->mTitleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QFont font(d->mTitleLabel->font()); font.setPointSizeF(font.pointSizeF() + 1); d->mTitleLabel->setFont(font); d->mTitleLabel->setText(title); d->mTitleLabel->setVisible(!d->mTitleLabel->text().isEmpty()); auto layout = new QVBoxLayout(this); layout->addWidget(d->mTitleLabel); layout->setContentsMargins(0, 0, 0, 0); clear(); } SideBarGroup::~SideBarGroup() { delete d; } void SideBarGroup::addWidget(QWidget *widget) { widget->setParent(d->mContainer); d->mContainer->layout()->addWidget(widget); } void SideBarGroup::clear() { if (d->mContainer) { d->mContainer->deleteLater(); } d->mContainer = new QFrame(this); auto containerLayout = new QVBoxLayout(d->mContainer); containerLayout->setContentsMargins(0, 0, 0, 0); containerLayout->setSpacing(0); layout()->addWidget(d->mContainer); } void SideBarGroup::addAction(QAction *action) { int size = KIconLoader::global()->currentSize(KIconLoader::Small); QToolButton *button = new SideBarButton(); button->setFocusPolicy(Qt::NoFocus); button->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); button->setAutoRaise(true); button->setDefaultAction(action); button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); button->setIconSize(QSize(size, size)); if (action->menu()) { button->setPopupMode(QToolButton::InstantPopup); } addWidget(button); } //- SideBarPage ---------------------------------------------------------------- struct SideBarPagePrivate { QIcon mIcon; QString mTitle; QVBoxLayout *mLayout = nullptr; }; SideBarPage::SideBarPage(const QIcon &icon, const QString &title) : QWidget() , d(new SideBarPagePrivate) { d->mIcon = icon; d->mTitle = title; d->mLayout = new QVBoxLayout(this); QMargins margins = d->mLayout->contentsMargins(); margins.setRight(qMax(0, margins.right() - style()->pixelMetric(QStyle::PM_SplitterWidth))); d->mLayout->setContentsMargins(margins); } SideBarPage::~SideBarPage() { delete d; } const QIcon &SideBarPage::icon() const { return d->mIcon; } const QString &SideBarPage::title() const { return d->mTitle; } void SideBarPage::addWidget(QWidget *widget) { d->mLayout->addWidget(widget); } void SideBarPage::addStretch() { d->mLayout->addStretch(); } //- SideBarTabBar -------------------------------------------------------------- struct SideBarTabBarPrivate { SideBarTabBar::TabButtonStyle tabButtonStyle = SideBarTabBar::TabButtonTextBesideIcon; }; SideBarTabBar::SideBarTabBar(QWidget *parent) : QTabBar(parent) , d(new SideBarTabBarPrivate) { setIconSize(QSize(KIconLoader::SizeSmallMedium, KIconLoader::SizeSmallMedium)); } SideBarTabBar::~SideBarTabBar() = default; SideBarTabBar::TabButtonStyle SideBarTabBar::tabButtonStyle() const { return d->tabButtonStyle; } QSize SideBarTabBar::sizeHint(const TabButtonStyle tabButtonStyle) const { QRect tabBarRect(0, 0, 0, 0); for (int i = 0; i < count(); ++i) { const QRect tabRect(tabBarRect.topRight(), tabSizeHint(i, tabButtonStyle)); tabBarRect = tabBarRect.united(tabRect); } return tabBarRect.size(); } QSize SideBarTabBar::sizeHint() const { return sizeHint(d->tabButtonStyle); } QSize SideBarTabBar::minimumSizeHint() const { return sizeHint(TabButtonIconOnly); } QSize SideBarTabBar::tabContentSize(const int index, const TabButtonStyle tabButtonStyle, const QStyleOptionTab &opt) const { if (index < 0 || index > count() - 1) { return QSize(); } const int textWidth = opt.fontMetrics.size(Qt::TextShowMnemonic, tabText(index)).width(); if (tabButtonStyle == TabButtonIconOnly) { return QSize(opt.iconSize.width(), qMax(opt.iconSize.height(), opt.fontMetrics.height())); } if (tabButtonStyle == TabButtonTextOnly) { return QSize(textWidth, qMax(opt.iconSize.height(), opt.fontMetrics.height())); } // 4 is the hardcoded spacing between icons and text used in Qt Widgets const int spacing = !opt.icon.isNull() ? 4 : 0; return QSize(opt.iconSize.width() + spacing + textWidth, qMax(opt.iconSize.height(), opt.fontMetrics.height())); } QSize SideBarTabBar::tabSizeHint(const int index, const TabButtonStyle tabButtonStyle) const { if (index < 0 || index > count() - 1) { return QSize(); } QStyleOptionTab opt; initStyleOption(&opt, index); if (tabButtonStyle == TabButtonIconOnly) { opt.text.clear(); } else if (tabButtonStyle == TabButtonTextOnly) { opt.icon = QIcon(); } const QSize contentSize = tabContentSize(index, tabButtonStyle, opt); const int buttonMargin = style()->pixelMetric(QStyle::PM_ButtonMargin); const int toolBarMargin = style()->pixelMetric(QStyle::PM_ToolBarFrameWidth) + style()->pixelMetric(QStyle::PM_ToolBarItemMargin); return QSize(contentSize.width() + buttonMargin * 2 + toolBarMargin * 2, contentSize.height() + buttonMargin * 2 + toolBarMargin * 2); } QSize SideBarTabBar::tabSizeHint(const int index) const { return tabSizeHint(index, d->tabButtonStyle); } QSize SideBarTabBar::minimumTabSizeHint(int index) const { return tabSizeHint(index, TabButtonIconOnly); } void SideBarTabBar::tabLayoutChange() { const int width = this->width(); if (width < sizeHint(TabButtonTextOnly).width()) { d->tabButtonStyle = TabButtonIconOnly; } else if (width < sizeHint(TabButtonTextBesideIcon).width()) { d->tabButtonStyle = TabButtonTextOnly; } else { d->tabButtonStyle = TabButtonTextBesideIcon; } } void SideBarTabBar::paintEvent(QPaintEvent *event) { Q_UNUSED(event) QStylePainter painter(this); // Don't need to draw PE_FrameTabBarBase because it's in a QTabWidget const int selected = currentIndex(); for (int i = 0; i < this->count(); ++i) { if (i == selected) { continue; } drawTab(i, painter); } // draw selected tab last so it appears on top if (selected >= 0) { drawTab(selected, painter); } } void SideBarTabBar::drawTab(int index, QStylePainter &painter) const { QStyleOptionTab opt; QTabBar::initStyleOption(&opt, index); // draw background before doing anything else painter.drawControl(QStyle::CE_TabBarTabShape, opt); const TabButtonStyle tabButtonStyle = this->tabButtonStyle(); if (tabButtonStyle == TabButtonTextOnly) { opt.icon = QIcon(); } else if (tabButtonStyle == TabButtonIconOnly) { opt.text.clear(); } const bool hasIcon = !opt.icon.isNull(); const bool hasText = !opt.text.isEmpty(); int flags = Qt::TextShowMnemonic; flags |= hasIcon && hasText ? Qt::AlignLeft | Qt::AlignVCenter : Qt::AlignCenter; if (!style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, this)) { flags |= Qt::TextHideMnemonic; } const QSize contentSize = tabContentSize(index, tabButtonStyle, opt); const QRect contentRect = QStyle::alignedRect(this->layoutDirection(), Qt::AlignCenter, contentSize, opt.rect); if (hasIcon) { painter.drawItemPixmap(contentRect, flags, opt.icon.pixmap(opt.iconSize)); } if (hasText) { // The available space to draw the text depends on wether we already drew an icon into our contentRect. const QSize availableSizeForText = !hasIcon ? contentSize : QSize(contentSize.width() - opt.iconSize.width() - 4, contentSize.height()); // The '4' above is the hardcoded spacing between icons and text used in Qt Widgets. const QRect availableRectForText = !hasIcon ? contentRect : QStyle::alignedRect(this->layoutDirection(), Qt::AlignRight, availableSizeForText, contentRect); painter.drawItemText(availableRectForText, flags, opt.palette, opt.state & QStyle::State_Enabled, opt.text, QPalette::WindowText); } } //- SideBar -------------------------------------------------------------------- struct SideBarPrivate { }; SideBar::SideBar(QWidget *parent) : QTabWidget(parent) , d(new SideBarPrivate) { setTabBar(new SideBarTabBar(this)); tabBar()->setDocumentMode(true); tabBar()->setUsesScrollButtons(false); tabBar()->setFocusPolicy(Qt::NoFocus); tabBar()->setExpanding(true); setTabPosition(QTabWidget::South); connect(tabBar(), &QTabBar::currentChanged, [=]() { GwenviewConfig::setSideBarPage(currentPage()); }); } SideBar::~SideBar() { delete d; } QSize SideBar::sizeHint() const { return QSize(200, 200); } void SideBar::addPage(SideBarPage *page) { // Prevent emitting currentChanged() while populating pages SignalBlocker blocker(tabBar()); addTab(page, page->icon(), page->title()); const int thisTabIndex = this->count() - 1; this->setTabToolTip(thisTabIndex, page->title()); } QString SideBar::currentPage() const { return currentWidget()->objectName(); } void SideBar::setCurrentPage(const QString &name) { for (int index = 0; index < count(); ++index) { if (widget(index)->objectName() == name) { setCurrentIndex(index); } } } void SideBar::loadConfig() { setCurrentPage(GwenviewConfig::sideBarPage()); } } // namespace #include "moc_sidebar.cpp"
11,854
C++
.cpp
346
30.106936
144
0.691521
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,897
fileoperations.cpp
KDE_gwenview/app/fileoperations.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "fileoperations.h" // Qt #include <QFileDialog> #include <QMenu> #include <QPushButton> // KF #include "kio_version.h" #include <KIO/CopyJob> #include <KIO/DeleteJob> #include <KIO/DeleteOrTrashJob> #include <KIO/JobUiDelegate> #include <KIO/SimpleJob> #include <KJobWidgets> #include <KLocalizedString> // Local #include "gwenview_app_debug.h" #include "renamedialog.h" #include <lib/contextmanager.h> #include <lib/document/documentfactory.h> #include <lib/thumbnailprovider/thumbnailprovider.h> namespace Gwenview { namespace FileOperations { static void copyMoveOrLink(Operation operation, const QList<QUrl> &urlList, QWidget *parent, ContextManager *contextManager) { Q_ASSERT(!urlList.isEmpty()); const int numberOfImages = urlList.count(); auto dialog = new QFileDialog(parent->nativeParentWidget(), QString()); dialog->setAcceptMode(QFileDialog::AcceptSave); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); // Figure out what the window title and buttons should say, // depending on the operation and how many images are selected switch (operation) { case COPY: if (numberOfImages == 1) { dialog->setWindowTitle(i18nc("@title:window %1 file name", "Copy %1", urlList.constFirst().fileName())); } else { dialog->setWindowTitle(i18ncp("@title:window %1 number of images", "Copy %1 image", "Copy %1 images", numberOfImages)); } dialog->setLabelText(QFileDialog::DialogLabel::Accept, i18nc("@action:button", "Copy")); break; case MOVE: if (numberOfImages == 1) { dialog->setWindowTitle(i18nc("@title:window %1 file name", "Move %1", urlList.constFirst().fileName())); } else { dialog->setWindowTitle(i18ncp("@title:window %1 number of images", "Move %1 image", "Move %1 images", numberOfImages)); } dialog->setLabelText(QFileDialog::DialogLabel::Accept, i18nc("@action:button", "Move")); break; case LINK: if (numberOfImages == 1) { dialog->setWindowTitle(i18nc("@title:window %1 file name", "Link %1", urlList.constFirst().fileName())); } else { dialog->setWindowTitle(i18ncp("@title:window %1 number of images", "Link %1 image", "Link %1 images", numberOfImages)); } dialog->setLabelText(QFileDialog::DialogLabel::Accept, i18nc("@action:button", "Link")); break; default: Q_ASSERT(0); } if (numberOfImages == 1) { dialog->setFileMode(QFileDialog::AnyFile); dialog->selectUrl(urlList.constFirst()); } else { dialog->setFileMode(QFileDialog::Directory); dialog->setOption(QFileDialog::ShowDirsOnly, true); } QUrl dirUrl = contextManager->targetDirUrl(); if (!dirUrl.isValid()) { dirUrl = urlList.constFirst().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash); } dialog->setDirectoryUrl(dirUrl); QObject::connect(dialog, &QDialog::accepted, parent, [=]() { QUrl destUrl = dialog->selectedUrls().at(0); KIO::CopyJob *job = nullptr; switch (operation) { case COPY: job = KIO::copy(urlList, destUrl); break; case MOVE: job = KIO::move(urlList, destUrl); break; case LINK: job = KIO::link(urlList, destUrl); break; default: Q_ASSERT(0); } KJobWidgets::setWindow(job, parent); job->uiDelegate()->setAutoErrorHandlingEnabled(true); if (numberOfImages == 1) { destUrl = destUrl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash); } contextManager->setTargetDirUrl(destUrl); }); dialog->show(); } static void delOrTrash(KIO::JobUiDelegate::DeletionType deletionType, const QList<QUrl> &urlList, QWidget *parent) { Q_ASSERT(urlList.count() > 0); KJob *job = nullptr; switch (deletionType) { case KIO::JobUiDelegate::Trash: job = new KIO::DeleteOrTrashJob(urlList, KIO::AskUserActionInterface::Trash, KIO::AskUserActionInterface::DefaultConfirmation, parent); break; case KIO::JobUiDelegate::Delete: job = new KIO::DeleteOrTrashJob(urlList, KIO::AskUserActionInterface::Delete, KIO::AskUserActionInterface::DefaultConfirmation, parent); break; default: // e.g. EmptyTrash return; } Q_ASSERT(job); KJobWidgets::setWindow(job, parent); job->start(); for (const QUrl &url : urlList) { DocumentFactory::instance()->forget(url); } } void copyTo(const QList<QUrl> &urlList, QWidget *parent, ContextManager *contextManager) { copyMoveOrLink(COPY, urlList, parent, contextManager); } void moveTo(const QList<QUrl> &urlList, QWidget *parent, ContextManager *contextManager) { copyMoveOrLink(MOVE, urlList, parent, contextManager); } void linkTo(const QList<QUrl> &urlList, QWidget *parent, ContextManager *contextManager) { copyMoveOrLink(LINK, urlList, parent, contextManager); } void trash(const QList<QUrl> &urlList, QWidget *parent) { delOrTrash(KIO::JobUiDelegate::Trash, urlList, parent); } void del(const QList<QUrl> &urlList, QWidget *parent) { delOrTrash(KIO::JobUiDelegate::Delete, urlList, parent); } void showMenuForDroppedUrls(QWidget *parent, const QList<QUrl> &urlList, const QUrl &destUrl) { if (urlList.isEmpty()) { qCWarning(GWENVIEW_APP_LOG) << "urlList is empty!"; return; } if (!destUrl.isValid()) { qCWarning(GWENVIEW_APP_LOG) << "destUrl is not valid!"; return; } QMenu menu(parent); QAction *moveAction = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-move"), QIcon::fromTheme(QStringLiteral("go-jump"))), i18n("Move Here")); QAction *copyAction = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18n("Copy Here")); QAction *linkAction = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-link")), i18n("Link Here")); menu.addSeparator(); menu.addAction(QIcon::fromTheme(QStringLiteral("process-stop")), i18n("Cancel")); QAction *action = menu.exec(QCursor::pos()); KIO::Job *job = nullptr; if (action == moveAction) { job = KIO::move(urlList, destUrl); } else if (action == copyAction) { job = KIO::copy(urlList, destUrl); } else if (action == linkAction) { job = KIO::link(urlList, destUrl); } else { return; } Q_ASSERT(job); KJobWidgets::setWindow(job, parent); } void rename(const QUrl &oldUrl, QWidget *parent, ContextManager *contextManager) { auto dialog = new RenameDialog(parent); dialog->setFilename(oldUrl.fileName()); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); QObject::connect(dialog, &QDialog::accepted, parent, [=]() { const QString name = dialog->filename(); if (name.isEmpty() || name == oldUrl.fileName()) { return; } QUrl newUrl = oldUrl; newUrl = newUrl.adjusted(QUrl::RemoveFilename); newUrl.setPath(newUrl.path() + name); KIO::SimpleJob *job = KIO::rename(oldUrl, newUrl, KIO::HideProgressInfo); KJobWidgets::setWindow(job, parent); job->uiDelegate()->setAutoErrorHandlingEnabled(true); QObject::connect(job, &KJob::result, parent, [contextManager, job, oldUrl, newUrl]() { if (!job->error()) { contextManager->setCurrentUrl(newUrl); ThumbnailProvider::moveThumbnail(oldUrl, newUrl); } }); }); dialog->show(); } } // namespace } // namespace
8,493
C++
.cpp
215
33.790698
152
0.678073
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,898
imageopscontextmanageritem.cpp
KDE_gwenview/app/imageopscontextmanageritem.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "imageopscontextmanageritem.h" // Qt #include <QAction> #include <QApplication> #include <QRect> // KF #include <KActionCategory> #include <KActionCollection> #include <KLocalizedString> #include <KMessageBox> // Local #include "config-gwenview.h" #include "gwenview_app_debug.h" #include "mainwindow.h" #include "sidebar.h" #include "viewmainpage.h" #ifdef KIMAGEANNOTATOR_FOUND #include <lib/annotate/annotatedialog.h> #include <lib/annotate/annotateoperation.h> #endif #include <lib/bcg/bcgtool.h> #include <lib/contextmanager.h> #include <lib/crop/croptool.h> #include <lib/document/documentfactory.h> #include <lib/documentview/rasterimageview.h> #include <lib/eventwatcher.h> #include <lib/gwenviewconfig.h> #include <lib/redeyereduction/redeyereductiontool.h> #include <lib/resize/resizeimagedialog.h> #include <lib/resize/resizeimageoperation.h> #include <lib/transformimageoperation.h> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_APP_LOG) << x #else #define LOG(x) ; #endif struct ImageOpsContextManagerItem::Private { ImageOpsContextManagerItem *q = nullptr; MainWindow *mMainWindow = nullptr; SideBarGroup *mGroup = nullptr; QRect *mCropStateRect = nullptr; QAction *mRotateLeftAction = nullptr; QAction *mRotateRightAction = nullptr; QAction *mMirrorAction = nullptr; QAction *mFlipAction = nullptr; QAction *mResizeAction = nullptr; QAction *mCropAction = nullptr; QAction *mBCGAction = nullptr; QAction *mRedEyeReductionAction = nullptr; #ifdef KIMAGEANNOTATOR_FOUND QAction *mAnnotateAction = nullptr; #endif QList<QAction *> mActionList; void setupActions() { KActionCollection *actionCollection = mMainWindow->actionCollection(); auto edit = new KActionCategory(i18nc("@title actions category - means actions changing image", "Edit"), actionCollection); mRotateLeftAction = edit->addAction(QStringLiteral("rotate_left"), q, SLOT(rotateLeft())); mRotateLeftAction->setText(i18n("Rotate Left")); mRotateLeftAction->setToolTip(i18nc("@info:tooltip", "Rotate image to the left")); mRotateLeftAction->setIcon(QIcon::fromTheme(QStringLiteral("object-rotate-left"))); actionCollection->setDefaultShortcut(mRotateLeftAction, Qt::CTRL | Qt::SHIFT | Qt::Key_R); mRotateRightAction = edit->addAction(QStringLiteral("rotate_right"), q, SLOT(rotateRight())); mRotateRightAction->setText(i18n("Rotate Right")); mRotateRightAction->setToolTip(i18nc("@info:tooltip", "Rotate image to the right")); mRotateRightAction->setIcon(QIcon::fromTheme(QStringLiteral("object-rotate-right"))); actionCollection->setDefaultShortcut(mRotateRightAction, Qt::CTRL | Qt::Key_R); mMirrorAction = edit->addAction(QStringLiteral("mirror"), q, SLOT(mirror())); mMirrorAction->setText(i18n("Mirror")); mMirrorAction->setIcon(QIcon::fromTheme(QStringLiteral("object-flip-horizontal"))); mFlipAction = edit->addAction(QStringLiteral("flip"), q, SLOT(flip())); mFlipAction->setText(i18n("Flip")); mFlipAction->setIcon(QIcon::fromTheme(QStringLiteral("object-flip-vertical"))); mResizeAction = edit->addAction(QStringLiteral("resize"), q, SLOT(resizeImage())); mResizeAction->setText(i18n("Resize")); mResizeAction->setIcon(QIcon::fromTheme(QStringLiteral("transform-scale"))); actionCollection->setDefaultShortcut(mResizeAction, Qt::SHIFT | Qt::Key_R); mCropAction = edit->addAction(QStringLiteral("crop"), q, SLOT(crop())); mCropAction->setText(i18n("Crop")); mCropAction->setIcon(QIcon::fromTheme(QStringLiteral("transform-crop-and-resize"))); actionCollection->setDefaultShortcut(mCropAction, Qt::SHIFT | Qt::Key_C); mBCGAction = edit->addAction(QStringLiteral("brightness_contrast_gamma"), q, SLOT(startBCG())); mBCGAction->setText(i18nc("@action:intoolbar", "Adjust Colors")); mBCGAction->setIcon(QIcon::fromTheme(QStringLiteral("contrast"))); actionCollection->setDefaultShortcut(mBCGAction, Qt::SHIFT | Qt::Key_B); mRedEyeReductionAction = edit->addAction(QStringLiteral("red_eye_reduction"), q, SLOT(startRedEyeReduction())); mRedEyeReductionAction->setText(i18n("Reduce Red Eye")); mRedEyeReductionAction->setIcon(QIcon::fromTheme(QStringLiteral("redeyes"))); actionCollection->setDefaultShortcut(mRedEyeReductionAction, Qt::SHIFT | Qt::Key_E); #ifdef KIMAGEANNOTATOR_FOUND mAnnotateAction = edit->addAction(QStringLiteral("annotate")); mAnnotateAction->setText(i18nc("@action:intoolbar", "Annotate")); mAnnotateAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-image"), QIcon::fromTheme(QStringLiteral("draw-brush")))); actionCollection->setDefaultShortcut(mAnnotateAction, Qt::SHIFT | Qt::Key_A); connect(mAnnotateAction, &QAction::triggered, q, [this]() { Document::Ptr doc = DocumentFactory::instance()->load(q->contextManager()->currentUrl()); doc->waitUntilLoaded(); AnnotateDialog dialog(mMainWindow); dialog.setWindowTitle(i18nc("@title:window Annotate [filename]", "Annotate %1", doc->url().fileName())); dialog.setImage(doc->image()); if (dialog.exec() == QDialog::Accepted) { q->applyImageOperation(new AnnotateOperation(dialog.getImage())); } }); #endif mActionList << mRotateLeftAction << mRotateRightAction << mMirrorAction << mFlipAction << mResizeAction << mCropAction << mBCGAction << mRedEyeReductionAction; #ifdef KIMAGEANNOTATOR_FOUND mActionList << mAnnotateAction; #endif } bool ensureEditable() { const QUrl url = q->contextManager()->currentUrl(); Document::Ptr doc = DocumentFactory::instance()->load(url); doc->waitUntilLoaded(); if (doc->isEditable()) { return true; } KMessageBox::error(QApplication::activeWindow(), i18nc("@info", "Gwenview cannot edit this kind of image.")); return false; } }; ImageOpsContextManagerItem::ImageOpsContextManagerItem(ContextManager *manager, MainWindow *mainWindow) : AbstractContextManagerItem(manager) , d(new Private) { d->q = this; d->mMainWindow = mainWindow; d->mGroup = new SideBarGroup(i18n("Image Operations")); setWidget(d->mGroup); EventWatcher::install(d->mGroup, QEvent::Show, this, SLOT(updateSideBarContent())); d->mCropStateRect = new QRect; d->setupActions(); updateActions(); connect(contextManager(), &ContextManager::selectionChanged, this, &ImageOpsContextManagerItem::updateActions); connect(mainWindow, &MainWindow::viewModeChanged, this, &ImageOpsContextManagerItem::updateActions); connect(mainWindow->viewMainPage(), &ViewMainPage::completed, this, &ImageOpsContextManagerItem::updateActions); } ImageOpsContextManagerItem::~ImageOpsContextManagerItem() { delete d->mCropStateRect; delete d; } void ImageOpsContextManagerItem::updateSideBarContent() { if (!d->mGroup->isVisible()) { return; } d->mGroup->clear(); for (QAction *action : qAsConst(d->mActionList)) { if (action->isEnabled() && action->priority() != QAction::LowPriority) { d->mGroup->addAction(action); } } } void ImageOpsContextManagerItem::updateActions() { bool canModify = contextManager()->currentUrlIsRasterImage(); bool viewMainPageIsVisible = d->mMainWindow->viewMainPage()->isVisible(); if (!viewMainPageIsVisible) { // Since we only support image operations on one image for now, // disable actions if several images are selected and the document // view is not visible. if (contextManager()->selectedFileItemList().count() != 1) { canModify = false; } } d->mRotateLeftAction->setEnabled(canModify); d->mRotateRightAction->setEnabled(canModify); d->mMirrorAction->setEnabled(canModify); d->mFlipAction->setEnabled(canModify); d->mResizeAction->setEnabled(canModify); d->mCropAction->setEnabled(canModify && viewMainPageIsVisible); d->mBCGAction->setEnabled(canModify && viewMainPageIsVisible); d->mRedEyeReductionAction->setEnabled(canModify && viewMainPageIsVisible); #ifdef KIMAGEANNOTATOR_FOUND d->mAnnotateAction->setEnabled(canModify); #endif updateSideBarContent(); } void ImageOpsContextManagerItem::rotateLeft() { auto op = new TransformImageOperation(ROT_270); applyImageOperation(op); } void ImageOpsContextManagerItem::rotateRight() { auto op = new TransformImageOperation(ROT_90); applyImageOperation(op); } void ImageOpsContextManagerItem::mirror() { auto op = new TransformImageOperation(HFLIP); applyImageOperation(op); } void ImageOpsContextManagerItem::flip() { auto op = new TransformImageOperation(VFLIP); applyImageOperation(op); } void ImageOpsContextManagerItem::resizeImage() { if (!d->ensureEditable()) { return; } Document::Ptr doc = DocumentFactory::instance()->load(contextManager()->currentUrl()); doc->startLoadingFullImage(); auto dialog = new ResizeImageDialog(d->mMainWindow); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); dialog->setOriginalSize(doc->size()); dialog->setCurrentImageUrl(doc->url()); connect(dialog, &QDialog::accepted, this, [this, dialog]() { applyImageOperation(new ResizeImageOperation(dialog->size())); }); dialog->show(); } void ImageOpsContextManagerItem::crop() { if (!d->ensureEditable()) { return; } RasterImageView *imageView = d->mMainWindow->viewMainPage()->imageView(); if (!imageView) { qCCritical(GWENVIEW_APP_LOG) << "No ImageView available!"; return; } auto tool = new CropTool(imageView); Document::Ptr doc = DocumentFactory::instance()->load(contextManager()->currentUrl()); QSize size = doc->size(); QRect sizeAsRect = QRect(0, 0, size.width(), size.height()); if (!d->mCropStateRect->isNull() && sizeAsRect.contains(*d->mCropStateRect)) { tool->setRect(*d->mCropStateRect); } connect(tool, &CropTool::imageOperationRequested, this, &ImageOpsContextManagerItem::applyImageOperation); connect(tool, &CropTool::rectReset, this, [this]() { this->resetCropState(); }); connect(tool, &CropTool::done, this, [this, tool]() { this->d->mCropStateRect->setTopLeft(tool->rect().topLeft()); this->d->mCropStateRect->setSize(tool->rect().size()); this->restoreDefaultImageViewTool(); }); d->mMainWindow->setDistractionFreeMode(true); imageView->setCurrentTool(tool); } void ImageOpsContextManagerItem::resetCropState() { // Set the rect to null (see QRect::isNull()) d->mCropStateRect->setRect(0, 0, -1, -1); } void ImageOpsContextManagerItem::startRedEyeReduction() { if (!d->ensureEditable()) { return; } RasterImageView *view = d->mMainWindow->viewMainPage()->imageView(); if (!view) { qCCritical(GWENVIEW_APP_LOG) << "No RasterImageView available!"; return; } auto tool = new RedEyeReductionTool(view); connect(tool, &RedEyeReductionTool::imageOperationRequested, this, &ImageOpsContextManagerItem::applyImageOperation); connect(tool, &RedEyeReductionTool::done, this, &ImageOpsContextManagerItem::restoreDefaultImageViewTool); d->mMainWindow->setDistractionFreeMode(true); view->setCurrentTool(tool); } void ImageOpsContextManagerItem::applyImageOperation(AbstractImageOperation *op) { // For now, we only support operations on one image QUrl url = contextManager()->currentUrl(); Document::Ptr doc = DocumentFactory::instance()->load(url); op->applyToDocument(doc); } void ImageOpsContextManagerItem::restoreDefaultImageViewTool() { RasterImageView *imageView = d->mMainWindow->viewMainPage()->imageView(); if (!imageView) { qCCritical(GWENVIEW_APP_LOG) << "No RasterImageView available!"; return; } AbstractRasterImageViewTool *tool = imageView->currentTool(); imageView->setCurrentTool(nullptr); tool->deleteLater(); d->mMainWindow->setDistractionFreeMode(false); } void ImageOpsContextManagerItem::startBCG() { if (!d->ensureEditable()) { return; } RasterImageView *view = d->mMainWindow->viewMainPage()->imageView(); if (!view) { qCCritical(GWENVIEW_APP_LOG) << "No RasterImageView available!"; return; } auto tool = new BCGTool(view); connect(tool, &BCGTool::imageOperationRequested, this, &ImageOpsContextManagerItem::applyImageOperation); connect(tool, &BCGTool::done, this, &ImageOpsContextManagerItem::restoreDefaultImageViewTool); d->mMainWindow->setDistractionFreeMode(true); view->setCurrentTool(tool); } } // namespace #include "moc_imageopscontextmanageritem.cpp"
13,928
C++
.cpp
327
37.590214
140
0.720402
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,899
viewmainpage.cpp
KDE_gwenview/app/viewmainpage.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "viewmainpage.h" #include "config-gwenview.h" // Qt #include <QApplication> #include <QCheckBox> #include <QItemSelectionModel> #include <QMenu> #include <QShortcut> #include <QVBoxLayout> // KF #include <KActionCategory> #include <KActionCollection> #include <KLocalizedString> #include <KMessageBox> #include <KModelIndexProxyMapper> #include <KSqueezedTextLabel> #include <KToggleAction> #if HAVE_KACTIVITIES #include <PlasmaActivities/ResourceInstance> #endif // Local #include "fileoperations.h" #include "gwenview_app_debug.h" #include "splitter.h" #include "spotlightmode.h" #include <gvcore.h> #include <lib/documentview/abstractdocumentviewadapter.h> #include <lib/documentview/abstractrasterimageviewtool.h> #include <lib/documentview/documentview.h> #include <lib/documentview/documentviewcontainer.h> #include <lib/documentview/documentviewcontroller.h> #include <lib/documentview/documentviewsynchronizer.h> #include <lib/fullscreenbar.h> #include <lib/gvdebug.h> #include <lib/gwenviewconfig.h> #include <lib/mimetypeutils.h> #include <lib/paintutils.h> #include <lib/semanticinfo/sorteddirmodel.h> #include <lib/slidecontainer.h> #include <lib/slideshow.h> #include <lib/statusbartoolbutton.h> #include <lib/stylesheetutils.h> #include <lib/thumbnailview/thumbnailbarview.h> #include <lib/zoommode.h> #include <lib/zoomwidget.h> namespace Gwenview { #undef ENABLE_LOG #undef LOG // #define ENABLE_LOG #ifdef ENABLE_LOG #define LOG(x) qCDebug(GWENVIEW_APP_LOG) << x #else #define LOG(x) ; #endif const int ViewMainPage::MaxViewCount = 6; /* * Layout of mThumbnailSplitter is: * * +-mThumbnailSplitter------------------------------------------------+ * |+-mAdapterContainer-----------------------------------------------+| * ||+-mDocumentViewContainer----------------------------------------+|| * |||+-DocumentView----------------++-DocumentView-----------------+||| * |||| || |||| * |||| || |||| * |||| || |||| * |||| || |||| * |||| || |||| * |||| || |||| * |||+-----------------------------++------------------------------+||| * ||+---------------------------------------------------------------+|| * ||+-mToolContainer------------------------------------------------+|| * ||| ||| * ||+---------------------------------------------------------------+|| * |+-----------------------------------------------------------------+| * |===================================================================| * |+-mThumbnailBar---------------------------------------------------+| * || || * || || * |+-mStatusBarContainer---------------------------------------------+| * ||[mToggleSideBarButton][mToggleThumbnailBarButton] [mZoomWidget]|| * |+-----------------------------------------------------------------+| * +-------------------------------------------------------------------+ */ struct ViewMainPagePrivate { ViewMainPage *q = nullptr; SlideShow *mSlideShow = nullptr; KActionCollection *mActionCollection = nullptr; GvCore *mGvCore = nullptr; KModelIndexProxyMapper *mDirModelToBarModelProxyMapper = nullptr; QSplitter *mThumbnailSplitter = nullptr; QWidget *mAdapterContainer = nullptr; DocumentViewController *mDocumentViewController = nullptr; QList<DocumentView *> mDocumentViews; DocumentViewSynchronizer *mSynchronizer = nullptr; QToolButton *mToggleSideBarButton = nullptr; QToolButton *mToggleThumbnailBarButton = nullptr; ZoomWidget *mZoomWidget = nullptr; DocumentViewContainer *mDocumentViewContainer = nullptr; SlideContainer *mToolContainer = nullptr; QWidget *mStatusBarContainer = nullptr; ThumbnailBarView *mThumbnailBar = nullptr; KToggleAction *mToggleThumbnailBarAction = nullptr; KToggleAction *mSynchronizeAction = nullptr; QCheckBox *mSynchronizeCheckBox = nullptr; KSqueezedTextLabel *mDocumentCountLabel = nullptr; SpotlightMode *mSpotlightMode = nullptr; bool mCompareMode; ZoomMode::Enum mZoomMode; void setupWidgets() { mToolContainer = new SlideContainer; mToolContainer->setAutoFillBackground(true); mToolContainer->setBackgroundRole(QPalette::Mid); //-- mStatusBarContainer = new QWidget; mStatusBarContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); mToggleSideBarButton = new StatusBarToolButton; mToggleThumbnailBarButton = new StatusBarToolButton; mZoomWidget = new ZoomWidget; mSynchronizeCheckBox = new QCheckBox(i18n("Synchronize")); mSynchronizeCheckBox->hide(); mDocumentCountLabel = new KSqueezedTextLabel; mDocumentCountLabel->setAlignment(Qt::AlignCenter); mDocumentCountLabel->setTextElideMode(Qt::ElideRight); QMargins labelMargins = mDocumentCountLabel->contentsMargins(); labelMargins.setLeft(15); labelMargins.setRight(15); mDocumentCountLabel->setContentsMargins(labelMargins); auto statusBarContainerLayout = new QHBoxLayout(mStatusBarContainer); // Use toolbar-like margins and spacing int margins = q->style()->pixelMetric(QStyle::PM_ToolBarItemMargin) + q->style()->pixelMetric(QStyle::PM_ToolBarFrameWidth); statusBarContainerLayout->setContentsMargins(margins, margins, margins, margins); statusBarContainerLayout->setSpacing(q->style()->pixelMetric(QStyle::PM_ToolBarItemSpacing)); statusBarContainerLayout->addWidget(mToggleSideBarButton); statusBarContainerLayout->addWidget(mToggleThumbnailBarButton); statusBarContainerLayout->addStretch(); statusBarContainerLayout->addWidget(mSynchronizeCheckBox); // Ensure document count label takes up all available space, // so its autohide feature works properly (stretch factor = 1) statusBarContainerLayout->addWidget(mDocumentCountLabel, 1); statusBarContainerLayout->addStretch(); statusBarContainerLayout->addWidget(mZoomWidget); //-- mAdapterContainer = new QWidget; auto adapterContainerLayout = new QVBoxLayout(mAdapterContainer); adapterContainerLayout->setContentsMargins(0, 0, 0, 0); adapterContainerLayout->setSpacing(0); mDocumentViewContainer = new DocumentViewContainer; mDocumentViewContainer->setAutoFillBackground(true); mDocumentViewContainer->setBackgroundRole(QPalette::Base); adapterContainerLayout->addWidget(mDocumentViewContainer); adapterContainerLayout->addWidget(mToolContainer); //-- mSpotlightMode = new SpotlightMode(mDocumentViewContainer, mActionCollection); adapterContainerLayout->addWidget(mDocumentViewContainer); adapterContainerLayout->addWidget(mToolContainer); //-- mThumbnailBar = new ThumbnailBarView; auto delegate = new ThumbnailBarItemDelegate(mThumbnailBar); mThumbnailBar->setItemDelegate(delegate); mThumbnailBar->setSelectionMode(QAbstractItemView::ExtendedSelection); //-- Qt::Orientation orientation = GwenviewConfig::thumbnailBarOrientation(); mThumbnailSplitter = new Splitter(orientation == Qt::Horizontal ? Qt::Vertical : Qt::Horizontal, q); mThumbnailBar->setOrientation(orientation); mThumbnailBar->setThumbnailAspectRatio(GwenviewConfig::thumbnailAspectRatio()); mThumbnailBar->setRowCount(GwenviewConfig::thumbnailBarRowCount()); mThumbnailSplitter->addWidget(mAdapterContainer); mThumbnailSplitter->addWidget(mThumbnailBar); mThumbnailSplitter->setSizes(GwenviewConfig::thumbnailSplitterSizes()); // Show the thumbnail bar after setting the parent to avoid recreating // the native window and to avoid QTBUG-87345. mThumbnailBar->setVisible(GwenviewConfig::thumbnailBarIsVisible()); mThumbnailBar->installEventFilter(q); auto viewMainPageLayout = new QVBoxLayout(q); viewMainPageLayout->setContentsMargins(0, 0, 0, 0); viewMainPageLayout->setSpacing(0); viewMainPageLayout->addWidget(mThumbnailSplitter); viewMainPageLayout->addWidget(mStatusBarContainer); //-- mDocumentViewController = new DocumentViewController(mActionCollection, q); mDocumentViewController->setZoomWidget(mZoomWidget); mDocumentViewController->setToolContainer(mToolContainer); mSynchronizer = new DocumentViewSynchronizer(&mDocumentViews, q); } void setupThumbnailBarStyleSheet() { QPalette pal = mGvCore->palette(GvCore::NormalViewPalette); mThumbnailBar->setPalette(pal); Qt::Orientation orientation = mThumbnailBar->orientation(); QColor bgColor = pal.color(QPalette::Normal, QPalette::Base); QColor bgSelColor = pal.color(QPalette::Normal, QPalette::Highlight); QColor bgHovColor = pal.color(QPalette::Normal, QPalette::Highlight); // Avoid dark and bright colors bgColor.setHsv(bgColor.hue(), bgColor.saturation(), (127 + 3 * bgColor.value()) / 4); // Hover uses lighter/faded version of select color. Combine with bgColor to adapt to different backgrounds bgHovColor.setHsv(bgHovColor.hue(), (bgHovColor.saturation() / 2), ((bgHovColor.value() + bgColor.value()) / 2)); QColor leftBorderColor = PaintUtils::adjustedHsv(bgColor, 0, 0, qMin(20, 255 - bgColor.value())); QColor rightBorderColor = PaintUtils::adjustedHsv(bgColor, 0, 0, -qMin(40, bgColor.value())); QColor borderSelColor = PaintUtils::adjustedHsv(bgSelColor, 0, 0, -qMin(60, bgSelColor.value())); QString itemCss = "QListView::item {" " background-color: %1;" " border-left: 1px solid %2;" " border-right: 1px solid %3;" "}"; itemCss = itemCss.arg(StyleSheetUtils::gradient(orientation, bgColor, 46), StyleSheetUtils::gradient(orientation, leftBorderColor, 36), StyleSheetUtils::gradient(orientation, rightBorderColor, 26)); QString itemSelCss = "QListView::item:selected {" " background-color: %1;" " border-left: 1px solid %2;" " border-right: 1px solid %2;" "}"; itemSelCss = itemSelCss.arg(StyleSheetUtils::gradient(orientation, bgSelColor, 56), StyleSheetUtils::rgba(borderSelColor)); QString itemHovCss = "QListView::item:hover:!selected {" " background-color: %1;" " border-left: 1px solid %2;" " border-right: 1px solid %3;" "}"; itemHovCss = itemHovCss.arg(StyleSheetUtils::gradient(orientation, bgHovColor, 56), StyleSheetUtils::rgba(leftBorderColor), StyleSheetUtils::rgba(rightBorderColor)); QString css = itemCss + itemSelCss + itemHovCss; if (orientation == Qt::Vertical) { css.replace(QLatin1String("left"), QLatin1String("top")).replace(QLatin1String("right"), QLatin1String("bottom")); } mThumbnailBar->setStyleSheet(css); } DocumentView *createDocumentView() { DocumentView *view = mDocumentViewContainer->createView(); // Connect context menu // If you need to connect another view signal, make sure it is disconnected in deleteDocumentView QObject::connect(view, &DocumentView::contextMenuRequested, q, &ViewMainPage::showContextMenu); QObject::connect(view, &DocumentView::completed, q, &ViewMainPage::completed); QObject::connect(view, &DocumentView::previousImageRequested, q, &ViewMainPage::previousImageRequested); QObject::connect(view, &DocumentView::nextImageRequested, q, &ViewMainPage::nextImageRequested); QObject::connect(view, &DocumentView::openUrlRequested, q, &ViewMainPage::openUrlRequested); QObject::connect(view, &DocumentView::openDirUrlRequested, q, &ViewMainPage::openDirUrlRequested); QObject::connect(view, &DocumentView::captionUpdateRequested, q, &ViewMainPage::captionUpdateRequested); QObject::connect(view, &DocumentView::toggleFullScreenRequested, q, &ViewMainPage::toggleFullScreenRequested); QObject::connect(view, &DocumentView::focused, q, &ViewMainPage::slotViewFocused); QObject::connect(view, &DocumentView::hudTrashClicked, q, &ViewMainPage::trashView); QObject::connect(view, &DocumentView::hudDeselectClicked, q, &ViewMainPage::deselectView); QObject::connect(view, &DocumentView::videoFinished, mSlideShow, &SlideShow::resumeAndGoToNextUrl); mDocumentViews << view; return view; } void deleteDocumentView(DocumentView *view) { if (mDocumentViewController->view() == view) { mDocumentViewController->setView(nullptr); } // Make sure we do not get notified about this view while it is going away. // mDocumentViewController->deleteView() animates the view deletion so // the view still exists for a short while when we come back to the // event loop) QObject::disconnect(view, nullptr, q, nullptr); QObject::disconnect(view, nullptr, mSlideShow, nullptr); mDocumentViews.removeOne(view); mDocumentViewContainer->deleteView(view); } void saveSplitterConfig() { if (mThumbnailBar->isVisible()) { if (mThumbnailSplitter->sizes().constLast() > 0) { GwenviewConfig::setThumbnailSplitterSizes(mThumbnailSplitter->sizes()); } else { // mThumbnailBar's size has been collapsed to 0. We reset the sizes to default so users can't "lose" the bar. const bool didUseDefaults = GwenviewConfig::self()->useDefaults(true); const auto defaultSplitterSizes = GwenviewConfig::thumbnailSplitterSizes(); GwenviewConfig::self()->useDefaults(didUseDefaults); GwenviewConfig::setThumbnailSplitterSizes(defaultSplitterSizes); } } } DocumentView *currentView() const { return mDocumentViewController->view(); } void setCurrentView(DocumentView *view) { DocumentView *oldView = currentView(); if (view == oldView) { return; } if (oldView) { oldView->setCurrent(false); } view->setCurrent(true); mDocumentViewController->setView(view); mSynchronizer->setCurrentView(view); QModelIndex index = indexForView(view); if (index.isValid()) { // Index may be invalid when Gwenview is started as // `gwenview /foo/image.png` because in this situation it loads image.png // *before* listing /foo (because it matters less to the user) mThumbnailBar->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Current); } QObject::connect(view, &DocumentView::currentToolChanged, q, &ViewMainPage::updateFocus); } QModelIndex indexForView(DocumentView *view) const { QUrl url = view->url(); if (!url.isValid()) { qCWarning(GWENVIEW_APP_LOG) << "View does not display any document!"; return {}; } SortedDirModel *dirModel = mGvCore->sortedDirModel(); QModelIndex srcIndex = dirModel->indexForUrl(url); if (!mDirModelToBarModelProxyMapper) { // Delay the initialization of the mapper to its first use because // mThumbnailBar->model() is not set after ViewMainPage ctor is // done. const_cast<ViewMainPagePrivate *>(this)->mDirModelToBarModelProxyMapper = new KModelIndexProxyMapper(dirModel, mThumbnailBar->model(), q); } QModelIndex index = mDirModelToBarModelProxyMapper->mapLeftToRight(srcIndex); return index; } void applyPalette(bool fullScreenMode) { mDocumentViewContainer->applyPalette(mGvCore->palette(fullScreenMode ? GvCore::FullScreenViewPalette : GvCore::NormalViewPalette)); setupThumbnailBarStyleSheet(); } void updateDocumentCountLabel() { const int current = mThumbnailBar->currentIndex().row() + 1; // zero-based const int total = mThumbnailBar->model()->rowCount(); const QString text = i18nc("@info:status %1 current document index, %2 total documents", "%1 of %2", current, total); mDocumentCountLabel->setText(text); } }; ViewMainPage::ViewMainPage(QWidget *parent, SlideShow *slideShow, KActionCollection *actionCollection, GvCore *gvCore) : QWidget(parent) , d(new ViewMainPagePrivate) { d->q = this; d->mDirModelToBarModelProxyMapper = nullptr; // Initialized later d->mSlideShow = slideShow; d->mActionCollection = actionCollection; d->mGvCore = gvCore; d->mCompareMode = false; auto enterKeyShortcut = new QShortcut(Qt::Key_Return, this); connect(enterKeyShortcut, &QShortcut::activated, this, &ViewMainPage::slotEnterPressed); d->setupWidgets(); auto view = new KActionCategory(i18nc("@title actions category - means actions changing smth in interface", "View"), actionCollection); d->mToggleThumbnailBarAction = view->add<KToggleAction>(QStringLiteral("toggle_thumbnailbar")); d->mToggleThumbnailBarAction->setText(i18n("Show Thumbnails")); // clang-format off // i18n: For languages that are read right to left, "right side" refers to the left side in this context. d->mToggleThumbnailBarAction->setWhatsThis(xi18nc("@info:whatsthis", "<para>This toggles a small bar showing all the other images in the current folder. " "Selecting one of them changes the currently viewed image.</para><para>Select multiple images at the same time to see them side by side.</para>" "<para>The bar can optionally be moved to the right side of the screen and contain multiple rows of images; <link url='%1'>configure these options in the settings</link>.</para>", QStringLiteral("gwenview:/config/imageview"))); // Keep the previous link address in sync with MainWindow::Private::SettingsOpenerHelper::eventFilter(). // clang-format on actionCollection->setDefaultShortcut(d->mToggleThumbnailBarAction, Qt::CTRL | Qt::Key_B); connect(d->mToggleThumbnailBarAction, &KToggleAction::triggered, this, &ViewMainPage::setThumbnailBarVisibility); d->mToggleThumbnailBarButton->setDefaultAction(d->mToggleThumbnailBarAction); connect(d->mThumbnailSplitter, &QSplitter::splitterMoved, this, [this]() { // The splitter can be moved until the bar has a size of zero which makes it invisible. const bool isThumbnailBarVisible = d->mThumbnailSplitter->sizes().constLast() > 0; GwenviewConfig::setThumbnailBarIsVisible(isThumbnailBarVisible); d->mToggleThumbnailBarAction->setChecked(isThumbnailBarVisible); }); d->mSynchronizeAction = view->add<KToggleAction>(QStringLiteral("synchronize_views")); d->mSynchronizeAction->setText(i18n("Synchronize")); actionCollection->setDefaultShortcut(d->mSynchronizeAction, Qt::CTRL | Qt::Key_Y); connect(d->mSynchronizeAction, &QAction::toggled, d->mSynchronizer, &DocumentViewSynchronizer::setActive); // Ensure mSynchronizeAction and mSynchronizeCheckBox are in sync connect(d->mSynchronizeAction, &QAction::toggled, d->mSynchronizeCheckBox, &QAbstractButton::setChecked); connect(d->mSynchronizeCheckBox, &QAbstractButton::toggled, d->mSynchronizeAction, &QAction::setChecked); // Connections for the document count connect(d->mThumbnailBar, &ThumbnailBarView::rowsInsertedSignal, this, &ViewMainPage::slotDirModelItemsAddedOrRemoved); connect(d->mThumbnailBar, &ThumbnailBarView::rowsRemovedSignal, this, &ViewMainPage::slotDirModelItemsAddedOrRemoved); connect(qApp, &QApplication::paletteChanged, this, [this]() { d->applyPalette(window()->isFullScreen()); }); installEventFilter(this); } ViewMainPage::~ViewMainPage() { delete d; } void ViewMainPage::loadConfig() { d->applyPalette(window()->isFullScreen()); // FIXME: Not symmetric with saveConfig(). Check if it matters. for (DocumentView *view : qAsConst(d->mDocumentViews)) { view->loadAdapterConfig(); } Qt::Orientation orientation = GwenviewConfig::thumbnailBarOrientation(); d->mThumbnailSplitter->setOrientation(orientation == Qt::Horizontal ? Qt::Vertical : Qt::Horizontal); d->mThumbnailBar->setOrientation(orientation); d->setupThumbnailBarStyleSheet(); d->mThumbnailBar->setVisible(GwenviewConfig::thumbnailBarIsVisible()); d->mToggleThumbnailBarAction->setChecked(GwenviewConfig::thumbnailBarIsVisible()); int oldRowCount = d->mThumbnailBar->rowCount(); int newRowCount = GwenviewConfig::thumbnailBarRowCount(); if (oldRowCount != newRowCount) { d->mThumbnailBar->setUpdatesEnabled(false); int gridSize = d->mThumbnailBar->gridSize().width(); d->mThumbnailBar->setRowCount(newRowCount); // Adjust splitter to ensure thumbnail size remains the same int delta = (newRowCount - oldRowCount) * gridSize; QList<int> sizes = d->mThumbnailSplitter->sizes(); Q_ASSERT(sizes.count() == 2); sizes[0] -= delta; sizes[1] += delta; d->mThumbnailSplitter->setSizes(sizes); d->mThumbnailBar->setUpdatesEnabled(true); } d->mZoomMode = GwenviewConfig::zoomMode(); if (GwenviewConfig::spotlightMode() != d->mActionCollection->action(QStringLiteral("view_toggle_spotlightmode"))->isChecked()) if (parentWidget()->isVisible()) d->mActionCollection->action(QStringLiteral("view_toggle_spotlightmode"))->trigger(); } void ViewMainPage::saveConfig() { d->saveSplitterConfig(); GwenviewConfig::setThumbnailBarIsVisible(d->mToggleThumbnailBarAction->isChecked()); } void ViewMainPage::setThumbnailBarVisibility(bool visible) { d->saveSplitterConfig(); d->mThumbnailBar->setVisible(visible); if (visible && d->mThumbnailSplitter->sizes().constLast() <= 0) { // mThumbnailBar is supposed to be made visible but its splitter has a size of 0 making it invisible. // We load the last good sizes from the config. d->mThumbnailSplitter->setSizes(GwenviewConfig::thumbnailSplitterSizes()); } } int ViewMainPage::statusBarHeight() const { return d->mStatusBarContainer->height(); } void ViewMainPage::setStatusBarVisible(bool visible) { d->mStatusBarContainer->setVisible(visible); } void ViewMainPage::setFullScreenMode(bool fullScreenMode) { if (fullScreenMode) { d->mThumbnailBar->setVisible(false); } else { d->mThumbnailBar->setVisible(d->mToggleThumbnailBarAction->isChecked()); } d->applyPalette(fullScreenMode); d->mToggleThumbnailBarAction->setEnabled(!fullScreenMode); } ThumbnailBarView *ViewMainPage::thumbnailBar() const { return d->mThumbnailBar; } inline void addActionToMenu(QMenu *menu, KActionCollection *actionCollection, const char *name) { QAction *action = actionCollection->action(name); if (action) { menu->addAction(action); } } inline void addActionToMenu(QMenu *menu, KActionCollection *actionCollection, const QString &name) { QAction *action = actionCollection->action(name); if (action) { menu->addAction(action); } } void ViewMainPage::showContextMenu() { QMenu menu(this); addActionToMenu(&menu, d->mActionCollection, "fullscreen"); menu.addSeparator(); addActionToMenu(&menu, d->mActionCollection, "go_previous"); addActionToMenu(&menu, d->mActionCollection, "go_next"); if (d->currentView()->canZoom()) { menu.addSeparator(); addActionToMenu(&menu, d->mActionCollection, "view_actual_size"); addActionToMenu(&menu, d->mActionCollection, "view_zoom_to_fit"); addActionToMenu(&menu, d->mActionCollection, "view_zoom_in"); addActionToMenu(&menu, d->mActionCollection, "view_zoom_out"); addActionToMenu(&menu, d->mActionCollection, "view_toggle_birdeyeview"); } menu.addSeparator(); QMenu backgroundColorModeMenu(i18nc("@item:inmenu", "Background Color Mode"), this); addActionToMenu(&backgroundColorModeMenu, d->mActionCollection, "view_background_colormode_auto"); addActionToMenu(&backgroundColorModeMenu, d->mActionCollection, "view_background_colormode_light"); addActionToMenu(&backgroundColorModeMenu, d->mActionCollection, "view_background_colormode_neutral"); addActionToMenu(&backgroundColorModeMenu, d->mActionCollection, "view_background_colormode_dark"); backgroundColorModeMenu.setIcon(backgroundColorModeMenu.actions().at(0)->icon()); menu.addMenu(&backgroundColorModeMenu); if (d->mCompareMode) { menu.addSeparator(); addActionToMenu(&menu, d->mActionCollection, "synchronize_views"); } menu.addSeparator(); addActionToMenu(&menu, d->mActionCollection, KStandardAction::name(KStandardAction::Copy)); addActionToMenu(&menu, d->mActionCollection, "file_copy_to"); addActionToMenu(&menu, d->mActionCollection, "file_move_to"); addActionToMenu(&menu, d->mActionCollection, "file_link_to"); menu.addSeparator(); addActionToMenu(&menu, d->mActionCollection, "file_open_in_new_window"); addActionToMenu(&menu, d->mActionCollection, "file_open_with"); addActionToMenu(&menu, d->mActionCollection, "file_open_containing_folder"); menu.exec(QCursor::pos()); } QSize ViewMainPage::sizeHint() const { return QSize(400, 300); } QSize ViewMainPage::minimumSizeHint() const { if (!layout()) { return QSize(); } QSize minimumSize = layout()->minimumSize(); if (window()->isFullScreen()) { // Check minimum width of the overlay fullscreen bar // since there is no layout link which could do this const FullScreenBar *fullScreenBar = findChild<FullScreenBar *>(); if (fullScreenBar && fullScreenBar->layout()) { const int fullScreenBarWidth = fullScreenBar->layout()->minimumSize().width(); if (fullScreenBarWidth > minimumSize.width()) { minimumSize.setWidth(fullScreenBarWidth); } } } return minimumSize; } QUrl ViewMainPage::url() const { GV_RETURN_VALUE_IF_FAIL(d->currentView(), QUrl()); return d->currentView()->url(); } Document::Ptr ViewMainPage::currentDocument() const { if (!d->currentView()) { LOG("!d->documentView()"); return {}; } return d->currentView()->document(); } bool ViewMainPage::isEmpty() const { return !currentDocument(); } RasterImageView *ViewMainPage::imageView() const { if (!d->currentView()) { return nullptr; } return d->currentView()->imageView(); } DocumentView *ViewMainPage::documentView() const { return d->currentView(); } void ViewMainPage::openUrl(const QUrl &url) { openUrls(QList<QUrl>() << url, url); } void ViewMainPage::openUrls(const QList<QUrl> &allUrls, const QUrl &currentUrl) { DocumentView::Setup setup; QSet<QUrl> urls(allUrls.begin(), allUrls.end()); d->mCompareMode = urls.count() > 1; using ViewForUrlMap = QMap<QUrl, DocumentView *>; ViewForUrlMap viewForUrlMap; if (!d->mDocumentViews.isEmpty()) { d->mDocumentViewContainer->updateSetup(d->mDocumentViews.last()); } if (d->mDocumentViews.isEmpty() || d->mZoomMode == ZoomMode::Autofit) { setup.valid = true; setup.zoomToFit = true; } else { setup = d->mDocumentViews.last()->setup(); } // Destroy views which show urls we don't care about, remove from "urls" the // urls which already have a view. for (DocumentView *view : qAsConst(d->mDocumentViews)) { QUrl url = view->url(); if (urls.contains(url)) { // view displays an url we must display, keep it urls.remove(url); viewForUrlMap.insert(url, view); } else { // view url is not interesting, drop it d->deleteDocumentView(view); } } // Create view for remaining urls for (const QUrl &url : qAsConst(urls)) { if (d->mDocumentViews.count() >= MaxViewCount) { qCWarning(GWENVIEW_APP_LOG) << "Too many documents to show"; break; } DocumentView *view = d->createDocumentView(); viewForUrlMap.insert(url, view); } // Set sortKey to match url order int sortKey = 0; for (const QUrl &url : allUrls) { viewForUrlMap[url]->setSortKey(sortKey); ++sortKey; } d->mDocumentViewContainer->updateLayout(); // Load urls for new views. Do it only now because the view must have the // correct size before it starts loading its url. Do not do it later because // view->url() needs to be set for the next loop. ViewForUrlMap::ConstIterator it = viewForUrlMap.constBegin(), end = viewForUrlMap.constEnd(); for (; it != end; ++it) { QUrl url = it.key(); DocumentView *view = it.value(); DocumentView::Setup savedSetup = d->mDocumentViewContainer->savedSetup(url); view->openUrl(url, d->mZoomMode == ZoomMode::Individual && savedSetup.valid ? savedSetup : setup); #if HAVE_KACTIVITIES if (GwenviewConfig::historyEnabled()) { KActivities::ResourceInstance::notifyAccessed(url); } #endif } // Init views for (DocumentView *view : qAsConst(d->mDocumentViews)) { view->setCompareMode(d->mCompareMode); if (view->url() == currentUrl) { d->setCurrentView(view); } else { view->setCurrent(false); } } d->mSynchronizeCheckBox->setVisible(d->mCompareMode); if (d->mCompareMode) { d->mSynchronizer->setActive(d->mSynchronizeCheckBox->isChecked()); } else { d->mSynchronizer->setActive(false); } d->updateDocumentCountLabel(); d->mDocumentCountLabel->setVisible(!d->mCompareMode); } void ViewMainPage::reload() { DocumentView *view = d->currentView(); if (!view) { return; } Document::Ptr doc = view->document(); if (!doc) { qCWarning(GWENVIEW_APP_LOG) << "!doc"; return; } if (doc->isModified()) { KGuiItem cont = KStandardGuiItem::cont(); cont.setText(i18nc("@action:button", "Discard Changes and Reload")); int answer = KMessageBox::warningContinueCancel(this, i18nc("@info", "This image has been modified. Reloading it will discard all your changes."), QString() /* caption */, cont); if (answer != KMessageBox::Continue) { return; } } doc->reload(); // Call openUrl again because DocumentView may need to switch to a new // adapter (for example because document was broken and it is not anymore) d->currentView()->openUrl(doc->url(), d->currentView()->setup()); } void ViewMainPage::reset() { d->mDocumentViewController->reset(); d->mDocumentViewContainer->reset(); d->mDocumentViews.clear(); } void ViewMainPage::slotViewFocused(DocumentView *view) { d->setCurrentView(view); } void ViewMainPage::slotEnterPressed() { DocumentView *view = d->currentView(); if (view) { AbstractRasterImageViewTool *tool = view->currentTool(); if (tool) { QKeyEvent event(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier); tool->keyPressEvent(&event); if (event.isAccepted()) { return; } } } } bool ViewMainPage::eventFilter(QObject *watched, QEvent *event) { if (watched == d->mThumbnailBar && event->type() == QEvent::KeyPress) { auto ke = static_cast<QKeyEvent *>(event); switch (ke->key()) { case Qt::Key_Left: if (QApplication::isRightToLeft()) { Q_EMIT nextImageRequested(); } else { Q_EMIT previousImageRequested(); } return true; case Qt::Key_Up: Q_EMIT previousImageRequested(); return true; case Qt::Key_Right: if (QApplication::isRightToLeft()) { Q_EMIT previousImageRequested(); } else { Q_EMIT nextImageRequested(); } return true; case Qt::Key_Down: Q_EMIT nextImageRequested(); return true; default: break; } } else if (event->type() == QEvent::ShortcutOverride) { const int key = static_cast<QKeyEvent *>(event)->key(); if (key == Qt::Key_Space || key == Qt::Key_Escape) { const DocumentView *view = d->currentView(); if (view) { AbstractRasterImageViewTool *tool = view->currentTool(); if (tool) { QKeyEvent toolKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); tool->keyPressEvent(&toolKeyEvent); if (toolKeyEvent.isAccepted()) { event->accept(); } } } } // Leave fullscreen when viewing an image if (window()->isFullScreen() && key == Qt::Key_Escape) { d->mActionCollection->action(QStringLiteral("leave_fullscreen"))->trigger(); event->accept(); } } return QWidget::eventFilter(watched, event); } void ViewMainPage::trashView(DocumentView *view) { QUrl url = view->url(); deselectView(view); FileOperations::trash(QList<QUrl>() << url, this); } void ViewMainPage::deselectView(DocumentView *view) { DocumentView *newCurrentView = nullptr; if (view == d->currentView()) { // We need to find a new view to set as current int idx = d->mDocumentViews.indexOf(view); if (idx + 1 < d->mDocumentViews.count()) { newCurrentView = d->mDocumentViews.at(idx + 1); } else if (idx > 0) { newCurrentView = d->mDocumentViews.at(idx - 1); } else { GV_WARN_AND_RETURN("No view found to set as current"); } } QModelIndex index = d->indexForView(view); QItemSelectionModel *selectionModel = d->mThumbnailBar->selectionModel(); selectionModel->select(index, QItemSelectionModel::Deselect); if (newCurrentView) { d->setCurrentView(newCurrentView); } } QToolButton *ViewMainPage::toggleSideBarButton() const { return d->mToggleSideBarButton; } void ViewMainPage::showMessageWidget(QGraphicsWidget *widget, Qt::Alignment align) { d->mDocumentViewContainer->showMessageWidget(widget, align); } void ViewMainPage::updateFocus(const AbstractRasterImageViewTool *tool) { if (!tool) { d->mDocumentViewContainer->setFocus(); } } void ViewMainPage::slotDirModelItemsAddedOrRemoved() { d->updateDocumentCountLabel(); } void ViewMainPage::setSpotlightMode(bool spotlightmode) { GwenviewConfig::setSpotlightMode(spotlightmode); d->mSpotlightMode->setVisibleSpotlightModeQuitButton(spotlightmode); if (spotlightmode) { d->mThumbnailBar->setVisible(false); } else { d->mThumbnailBar->setVisible(d->mToggleThumbnailBarAction->isChecked()); } } } // namespace #include "moc_viewmainpage.cpp"
36,888
C++
.cpp
816
38.400735
235
0.661587
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,900
folderviewcontextmanageritem.cpp
KDE_gwenview/app/folderviewcontextmanageritem.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "folderviewcontextmanageritem.h" // Qt #include <QDir> #include <QDragEnterEvent> #include <QHeaderView> #include <QMimeData> #include <QTreeView> // KF #include <KUrlMimeData> // Local #include "fileoperations.h" #include "gwenview_app_debug.h" #include "lib/touch/touch_helper.h" #include <lib/contextmanager.h> #include <lib/eventwatcher.h> #include <lib/scrollerutils.h> namespace Gwenview { /** * This treeview accepts url drops */ class UrlDropTreeView : public QTreeView { public: explicit UrlDropTreeView(QWidget *parent = nullptr) : QTreeView(parent) { } protected: void dragEnterEvent(QDragEnterEvent *event) override { QAbstractItemView::dragEnterEvent(event); setDirtyRegion(mDropRect); if (event->mimeData()->hasUrls()) { event->acceptProposedAction(); } } void dragMoveEvent(QDragMoveEvent *event) override { QAbstractItemView::dragMoveEvent(event); const QModelIndex index = indexAt(event->pos()); // This code has been copied from Dolphin // (panels/folders/paneltreeview.cpp) setDirtyRegion(mDropRect); mDropRect = visualRect(index); setDirtyRegion(mDropRect); if (index.isValid()) { event->acceptProposedAction(); } else { event->ignore(); } } void dropEvent(QDropEvent *event) override { const QList<QUrl> urlList = KUrlMimeData::urlsFromMimeData(event->mimeData()); const QModelIndex index = indexAt(event->pos()); if (!index.isValid()) { qCWarning(GWENVIEW_APP_LOG) << "Invalid index!"; return; } const QUrl destUrl = static_cast<MODEL_CLASS *>(model())->urlForIndex(index); FileOperations::showMenuForDroppedUrls(this, urlList, destUrl); } bool viewportEvent(QEvent *event) override { if (event->type() == QEvent::TouchBegin) { return true; } const QPoint pos = Touch_Helper::simpleTapPosition(event); if (pos != QPoint(-1, -1)) { expand(indexAt(pos)); Q_EMIT activated(indexAt(pos)); } return QTreeView::viewportEvent(event); } private: QRect mDropRect; }; FolderViewContextManagerItem::FolderViewContextManagerItem(ContextManager *manager) : AbstractContextManagerItem(manager) { mModel = nullptr; setupView(); connect(contextManager(), &ContextManager::currentDirUrlChanged, this, &FolderViewContextManagerItem::slotCurrentDirUrlChanged); } void FolderViewContextManagerItem::slotCurrentDirUrlChanged(const QUrl &url) { if (url.isValid() && mUrlToSelect != url) { mUrlToSelect = url.adjusted(QUrl::StripTrailingSlash | QUrl::NormalizePathSegments); mExpandingIndex = QModelIndex(); } if (!mView->isVisible()) { return; } expandToSelectedUrl(); } void FolderViewContextManagerItem::expandToSelectedUrl() { if (!mUrlToSelect.isValid()) { return; } if (!mModel) { setupModel(); } const QModelIndex index = findClosestIndex(mExpandingIndex, mUrlToSelect); if (!index.isValid()) { return; } mExpandingIndex = index; QUrl url = mModel->urlForIndex(mExpandingIndex); if (mUrlToSelect == url) { // We found our url QItemSelectionModel *selModel = mView->selectionModel(); selModel->setCurrentIndex(mExpandingIndex, QItemSelectionModel::ClearAndSelect); mView->scrollTo(mExpandingIndex); mUrlToSelect = QUrl(); mExpandingIndex = QModelIndex(); } else { // We found a parent of our url mView->setExpanded(mExpandingIndex, true); } } void FolderViewContextManagerItem::slotRowsInserted(const QModelIndex &parentIndex, int /*start*/, int /*end*/) { // Can't trigger the case where parentIndex is invalid, but it most // probably happen when root items are created. In this case we trigger // expandToSelectedUrl without checking the url. // See bug #191771 if (!parentIndex.isValid() || mModel->urlForIndex(parentIndex).isParentOf(mUrlToSelect)) { mExpandingIndex = parentIndex; // Hack because otherwise indexes are not in correct order! QMetaObject::invokeMethod(this, &FolderViewContextManagerItem::expandToSelectedUrl, Qt::QueuedConnection); } } void FolderViewContextManagerItem::slotActivated(const QModelIndex &index) { if (!index.isValid()) { return; } QUrl url = mModel->urlForIndex(index); Q_EMIT urlChanged(url); } void FolderViewContextManagerItem::setupModel() { mModel = new MODEL_CLASS(this); mView->setModel(mModel); #ifndef USE_PLACETREE for (int col = 1; col <= mModel->columnCount(); ++col) { mView->header()->setSectionHidden(col, true); } mModel->dirLister()->openUrl(QUrl("/")); #endif QObject::connect(mModel, &MODEL_CLASS::rowsInserted, this, &FolderViewContextManagerItem::slotRowsInserted); } void FolderViewContextManagerItem::setupView() { mView = new UrlDropTreeView; mView->setEditTriggers(QAbstractItemView::NoEditTriggers); mView->setAcceptDrops(true); mView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); mView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); // Necessary to get the drop target highlighted mView->viewport()->setAttribute(Qt::WA_Hover); mView->setHeaderHidden(true); // This is tricky: QTreeView header has stretchLastSection set to true. // In this configuration, the header gets quite wide and cause an // horizontal scrollbar to appear. // To avoid this, set stretchLastSection to false and resizeMode to // Stretch (we still want the column to take the full width of the // widget). mView->header()->setStretchLastSection(false); mView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); ScrollerUtils::setQScroller(mView->viewport()); setWidget(mView); QObject::connect(mView, &QTreeView::activated, this, &FolderViewContextManagerItem::slotActivated); EventWatcher::install(mView, QEvent::Show, this, SLOT(expandToSelectedUrl())); } QModelIndex FolderViewContextManagerItem::findClosestIndex(const QModelIndex &parent, const QUrl &wantedUrl) { Q_ASSERT(mModel); QModelIndex index = parent; if (!index.isValid()) { index = findRootIndex(wantedUrl); if (!index.isValid()) { return {}; } } QUrl url = mModel->urlForIndex(index); if (!url.isParentOf(wantedUrl)) { qCWarning(GWENVIEW_APP_LOG) << url << "is not a parent of" << wantedUrl << "!"; return {}; } QString relativePath = QDir(url.path()).relativeFilePath(wantedUrl.path()); QModelIndex lastFoundIndex = index; const QStringList relativePathList = relativePath.split(QDir::separator(), Qt::SkipEmptyParts); for (const QString &pathPart : relativePathList) { bool found = false; for (int row = 0; row < mModel->rowCount(lastFoundIndex); ++row) { QModelIndex index = mModel->index(row, 0, lastFoundIndex); if (index.data().toString() == pathPart) { // FIXME: Check encoding found = true; lastFoundIndex = index; break; } } if (!found) { break; } } return lastFoundIndex; } QModelIndex FolderViewContextManagerItem::findRootIndex(const QUrl &wantedUrl) { QModelIndex matchIndex; int matchUrlLength = 0; for (int row = 0; row < mModel->rowCount(); ++row) { QModelIndex index = mModel->index(row, 0); QUrl url = mModel->urlForIndex(index); int urlLength = url.url().length(); if (url.isParentOf(wantedUrl) && urlLength > matchUrlLength) { matchIndex = index; matchUrlLength = urlLength; } } if (!matchIndex.isValid()) { qCWarning(GWENVIEW_APP_LOG) << "Found no root index for" << wantedUrl; } return matchIndex; } } // namespace #include "moc_folderviewcontextmanageritem.cpp"
9,013
C++
.cpp
249
30.546185
132
0.689335
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,901
savebar.cpp
KDE_gwenview/app/savebar.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "savebar.h" // Qt #include <QHBoxLayout> #include <QIcon> #include <QToolTip> #include <QUrl> // KF #include <KActionCollection> #include <KLocalizedString> #include <KMessageWidget> // Local #include "gwenview_app_debug.h" #include "lib/document/documentfactory.h" #include "lib/gwenviewconfig.h" #include "lib/memoryutils.h" namespace Gwenview { struct SaveBarPrivate { SaveBar *q = nullptr; KActionCollection *mActionCollection = nullptr; KMessageWidget *mSaveMessage = nullptr; KMessageWidget *mTooManyChangesMessage = nullptr; QAction *mSaveAllAction = nullptr; QUrl mCurrentUrl; void createTooManyChangesMessage() { mTooManyChangesMessage = new KMessageWidget; mTooManyChangesMessage->setIcon(QIcon::fromTheme(QStringLiteral("dialog-warning"))); mTooManyChangesMessage->setText(i18n("You have modified many images. To avoid memory problems, you should save your changes.")); mTooManyChangesMessage->setCloseButtonVisible(false); mTooManyChangesMessage->setPosition(KMessageWidget::Position::Header); } void updateTooManyChangesFrame(const QList<QUrl> &list) { qreal maxPercentageOfMemoryUsage = GwenviewConfig::percentageOfMemoryUsageWarning(); qulonglong maxMemoryUsage = MemoryUtils::getTotalMemory() * maxPercentageOfMemoryUsage; qulonglong memoryUsage = 0; for (const QUrl &url : list) { Document::Ptr doc = DocumentFactory::instance()->load(url); memoryUsage += doc->memoryUsage(); } mTooManyChangesMessage->setVisible(memoryUsage > maxMemoryUsage); } void updateTopRowWidget(const QList<QUrl> &lst) { mSaveMessage->clearActions(); QStringList links; QString message; if (lst.contains(mCurrentUrl)) { message = i18n("Current image modified"); mSaveMessage->addAction(mActionCollection->action(QStringLiteral("edit_undo"))); mSaveMessage->addAction(mActionCollection->action(QStringLiteral("edit_redo"))); mSaveMessage->addAction(mActionCollection->action(QStringLiteral("file_save"))); mSaveMessage->addAction(mActionCollection->action(QStringLiteral("file_save_as"))); if (lst.size() > 1) { mSaveMessage->addAction(mSaveAllAction); } if (lst.size() > 1) { QString previous = i18n("Previous modified image"); QString next = i18n("Next modified image"); if (mCurrentUrl == lst[0]) { links << previous; } else { links << QStringLiteral("<a href='previous'>%1</a>").arg(previous); } if (mCurrentUrl == lst[lst.size() - 1]) { links << next; } else { links << QStringLiteral("<a href='next'>%1</a>").arg(next); } } } else { message = i18np("One image modified", "%1 images modified", lst.size()); if (lst.size() > 1) { links << QStringLiteral("<a href='first'>%1</a>").arg(i18n("Go to first modified image")); } else { links << QStringLiteral("<a href='first'>%1</a>").arg(i18n("Go to it")); } } mSaveMessage->setText(message + QStringLiteral(" ") + links.join(QStringLiteral(" | "))); } }; SaveBar::SaveBar(QWidget *parent, KActionCollection *actionCollection) : SlideContainer(parent) , d(new SaveBarPrivate) { d->q = this; d->mActionCollection = actionCollection; d->mSaveMessage = new KMessageWidget(); d->mSaveMessage->setPosition(KMessageWidget::Position::Header); d->mSaveMessage->setCloseButtonVisible(false); d->mSaveMessage->setObjectName(QStringLiteral("saveBarWidget")); // Used for navigating between files when more than one is modified connect(d->mSaveMessage, &KMessageWidget::linkActivated, this, &SaveBar::triggerAction); d->mSaveAllAction = new QAction(); d->mSaveAllAction->setText(i18n("Save All")); d->mSaveAllAction->setToolTip(i18nc("@info:tooltip", "Save all modified images")); d->mSaveAllAction->setIcon(QIcon::fromTheme(QStringLiteral("document-save-all"))); connect(d->mSaveAllAction, &QAction::triggered, this, &SaveBar::requestSaveAll); d->createTooManyChangesMessage(); // The "save bar" and the "too many changes" headers could appear on top of each other, so let's do it auto headerLayout = new QVBoxLayout; headerLayout->setSpacing(0); headerLayout->setContentsMargins(0, 0, 0, 0); headerLayout->addWidget(d->mSaveMessage); headerLayout->addWidget(d->mTooManyChangesMessage); // Can't set the layout only, we use a widget to slide in and out auto dummyContent = new QWidget; dummyContent->setContentsMargins(0, 0, 0, 0); dummyContent->setLayout(headerLayout); setContent(dummyContent); connect(DocumentFactory::instance(), &DocumentFactory::modifiedDocumentListChanged, this, &SaveBar::updateContent); } SaveBar::~SaveBar() { delete d; } void SaveBar::setFullScreenMode(bool isFullScreen) { d->mTooManyChangesMessage->clearActions(); if (isFullScreen) { d->mTooManyChangesMessage->addAction(d->mSaveAllAction); } updateContent(); } void SaveBar::updateContent() { QList<QUrl> lst = DocumentFactory::instance()->modifiedDocumentList(); if (window()->isFullScreen()) { d->mSaveMessage->hide(); } else { d->mSaveMessage->show(); d->updateTopRowWidget(lst); } d->updateTooManyChangesFrame(lst); if (lst.isEmpty() || (window()->isFullScreen() && !d->mTooManyChangesMessage->isVisibleTo(d->mSaveMessage))) { slideOut(); } else { slideIn(); } } void SaveBar::triggerAction(const QString &action) { QList<QUrl> lst = DocumentFactory::instance()->modifiedDocumentList(); if (action == QLatin1String("first")) { Q_EMIT goToUrl(lst[0]); } else if (action == QLatin1String("previous")) { int pos = lst.indexOf(d->mCurrentUrl); --pos; Q_ASSERT(pos >= 0); Q_EMIT goToUrl(lst[pos]); } else if (action == QLatin1String("next")) { int pos = lst.indexOf(d->mCurrentUrl); ++pos; Q_ASSERT(pos < lst.size()); Q_EMIT goToUrl(lst[pos]); } else { qCWarning(GWENVIEW_APP_LOG) << "Unknown action: " << action; } } void SaveBar::setCurrentUrl(const QUrl &url) { d->mCurrentUrl = url; updateContent(); } } // namespace #include "moc_savebar.cpp"
7,485
C++
.cpp
184
34.228261
136
0.672817
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,902
slideshowfileitemaction.cpp
KDE_gwenview/app/slideshowfileitemaction.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2020 Méven Car <meven.car@kdemail.net> 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 "slideshowfileitemaction.h" #include <QMenu> #include <QMimeDatabase> #include <KFileItem> #include <KIO/CommandLauncherJob> #include <KLocalizedString> #include <KNotificationJobUiDelegate> #include <KPluginFactory> #include <QDir> K_PLUGIN_CLASS_WITH_JSON(SlideShowFileItemAction, "slideshowfileitemaction.json") SlideShowFileItemAction::SlideShowFileItemAction(QObject *parent, const QVariantList &) : KAbstractFileItemActionPlugin(parent) { } QList<QAction *> SlideShowFileItemAction::actions(const KFileItemListProperties &fileItemInfos, QWidget *parentWidget) { QStringList itemsForSlideShow; QString text; const KFileItemList &fileItems = fileItemInfos.items(); if (fileItemInfos.isDirectory()) { if (fileItemInfos.isLocal()) { QMimeDatabase db; // filter selected dirs containing at least one image for (const KFileItem &dirItem : fileItems) { QDir dir = QDir(dirItem.localPath()); const QStringList fileList = dir.entryList(QDir::Filter::Files); const bool containsAtLeastAnImage = std::any_of(fileList.cbegin(), fileList.cend(), [&db, &dir](const QString &fileName) { const auto mimeType = db.mimeTypeForFile(dir.absoluteFilePath(fileName), QMimeDatabase::MatchExtension); return mimeType.name().startsWith(QStringLiteral("image")); }); if (containsAtLeastAnImage) { itemsForSlideShow << dirItem.localPath(); } } } text = i18nc("@action:inmenu Start a slideshow Dolphin context menu", "Start a Slideshow"); } else if (fileItemInfos.mimeGroup() == QLatin1String("image") && fileItems.length() > 1) { for (const KFileItem &fileItem : fileItems) { itemsForSlideShow << fileItem.url().toString(); } text = i18nc("@action:inmenu Start a slideshow Dolphin context menu", "Start a Slideshow with selected images"); } if (itemsForSlideShow.isEmpty()) { return {}; } auto startSlideShowAction = new QAction(text, parentWidget); startSlideShowAction->setIcon(QIcon::fromTheme(QStringLiteral("gwenview"))); connect(startSlideShowAction, &QAction::triggered, this, [=]() { // gwenview -s %u auto job = new KIO::CommandLauncherJob(QStringLiteral("gwenview"), QStringList(QStringLiteral("-s")) << itemsForSlideShow); job->setDesktopName(QStringLiteral("org.kde.gwenview")); job->setUiDelegate(new KNotificationJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled)); job->start(); }); return {startSlideShowAction}; } #include "slideshowfileitemaction.moc" #include "moc_slideshowfileitemaction.cpp"
3,591
C++
.cpp
74
42.351351
138
0.716733
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,903
fullscreencontent.cpp
KDE_gwenview/app/fullscreencontent.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "fullscreencontent.h" // Qt #include <QAction> #include <QApplication> #include <QCheckBox> #include <QEvent> #include <QLabel> #include <QMenu> #include <QTimer> #include <QToolButton> #include <QWidgetAction> // KF #include <KActionCollection> #include <KActionMenu> #include <KIconLoader> #include <KLocalizedString> // Local #include "gwenview_app_debug.h" #include <gvcore.h> #include <lib/document/documentfactory.h> #include <lib/eventwatcher.h> #include <lib/fullscreenbar.h> #include <lib/gwenviewconfig.h> #include <lib/imagemetainfomodel.h> #include <lib/shadowfilter.h> #include <lib/slideshow.h> #include <lib/stylesheetutils.h> #include <lib/thumbnailview/thumbnailbarview.h> namespace Gwenview { /** * A widget which behaves more or less like a QToolBar, but which uses real * widgets for the toolbar items. We need a real widget to be able to position * the option menu. */ class FullScreenToolBar : public QWidget { public: explicit FullScreenToolBar(QWidget *parent = nullptr) : QWidget(parent) , mLayout(new QHBoxLayout(this)) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mLayout->setSpacing(0); mLayout->setContentsMargins(0, 0, 0, 0); } void addAction(QAction *action, Qt::ToolButtonStyle style = Qt::ToolButtonIconOnly) { auto button = new QToolButton; button->setDefaultAction(action); button->setToolButtonStyle(style); button->setAutoRaise(true); const int extent = KIconLoader::SizeMedium; button->setIconSize(QSize(extent, extent)); mLayout->addWidget(button); } void addSeparator() { mLayout->addSpacing(QApplication::style()->pixelMetric(QStyle::PM_LayoutVerticalSpacing)); } void addStretch() { mLayout->addStretch(); } void setDirection(QBoxLayout::Direction direction) { mLayout->setDirection(direction); } private: QBoxLayout *const mLayout; }; FullScreenContent::FullScreenContent(QObject *parent, GvCore *gvCore) : QObject(parent) { mGvCore = gvCore; mViewPageVisible = false; } void FullScreenContent::init(KActionCollection *actionCollection, QWidget *autoHideParentWidget, SlideShow *slideShow) { mSlideShow = slideShow; mActionCollection = actionCollection; connect(actionCollection->action(QStringLiteral("view")), &QAction::toggled, this, &FullScreenContent::slotViewModeActionToggled); // mAutoHideContainer mAutoHideContainer = new FullScreenBar(autoHideParentWidget); mAutoHideContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); auto layout = new QVBoxLayout(mAutoHideContainer); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); EventWatcher::install(autoHideParentWidget, QEvent::Resize, this, SLOT(adjustSize())); // mContent mContent = new QWidget; mContent->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); mContent->setAutoFillBackground(true); EventWatcher::install(mContent, QEvent::Show, this, SLOT(updateCurrentUrlWidgets())); layout->addWidget(mContent); createOptionsAction(); // mToolBar mToolBar = new FullScreenToolBar(mContent); #define addAction(name) mToolBar->addAction(actionCollection->action(name)) addAction(QStringLiteral("toggle_sidebar")); mToolBar->addSeparator(); addAction(QStringLiteral("browse")); addAction(QStringLiteral("view")); mToolBar->addSeparator(); addAction(QStringLiteral("go_previous")); addAction(QStringLiteral("toggle_slideshow")); addAction(QStringLiteral("go_next")); mToolBar->addSeparator(); addAction(QStringLiteral("rotate_left")); addAction(QStringLiteral("rotate_right")); #undef addAction mToolBarShadow = new ShadowFilter(mToolBar); // mInformationLabel mInformationLabel = new QLabel; mInformationLabel->setWordWrap(true); mInformationLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); // mDocumentCountLabel mDocumentCountLabel = new QLabel; mInformationContainer = new QWidget; const int infoContainerTopMargin = 6; const int infoContainerBottomMargin = 2; mInformationContainer->setContentsMargins(6, infoContainerTopMargin, 6, infoContainerBottomMargin); mInformationContainer->setAutoFillBackground(true); mInformationContainer->setBackgroundRole(QPalette::Mid); mInformationContainerShadow = new ShadowFilter(mInformationContainer); auto hLayout = new QHBoxLayout(mInformationContainer); hLayout->setContentsMargins(0, 0, 0, 0); hLayout->addWidget(mInformationLabel); hLayout->addWidget(mDocumentCountLabel); // Thumbnail bar mThumbnailBar = new ThumbnailBarView(mContent); mThumbnailBar->setThumbnailScaleMode(ThumbnailView::ScaleToSquare); auto delegate = new ThumbnailBarItemDelegate(mThumbnailBar); mThumbnailBar->setItemDelegate(delegate); mThumbnailBar->setSelectionMode(QAbstractItemView::ExtendedSelection); // Calculate minimum bar height to give mInformationLabel exactly two lines height const int lineHeight = mInformationLabel->fontMetrics().lineSpacing(); mMinimumThumbnailBarHeight = mToolBar->sizeHint().height() + lineHeight * 2 + infoContainerTopMargin + infoContainerBottomMargin; // Ensure document count is updated when items added/removed from folder connect(mThumbnailBar, &ThumbnailBarView::rowsInsertedSignal, this, &FullScreenContent::updateDocumentCountLabel); connect(mThumbnailBar, &ThumbnailBarView::rowsRemovedSignal, this, &FullScreenContent::updateDocumentCountLabel); connect(mThumbnailBar, &ThumbnailBarView::indexActivated, this, &FullScreenContent::updateDocumentCountLabel); // Right bar mRightToolBar = new FullScreenToolBar(mContent); mRightToolBar->addAction(mActionCollection->action(QStringLiteral("leave_fullscreen")), Qt::ToolButtonFollowStyle); mRightToolBar->addAction(mOptionsAction, Qt::ToolButtonFollowStyle); mRightToolBar->addStretch(); mRightToolBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); mRightToolBarShadow = new ShadowFilter(mRightToolBar); updateLayout(); updateContainerAppearance(); } ThumbnailBarView *FullScreenContent::thumbnailBar() const { return mThumbnailBar; } void FullScreenContent::setCurrentUrl(const QUrl &url) { if (url.isEmpty()) { mCurrentDocument = Document::Ptr(); } else { mCurrentDocument = DocumentFactory::instance()->load(url); connect(mCurrentDocument.data(), &Document::metaInfoUpdated, this, &FullScreenContent::updateCurrentUrlWidgets); } updateCurrentUrlWidgets(); // Give the thumbnail view time to update its "current index" QTimer::singleShot(0, this, &FullScreenContent::updateDocumentCountLabel); } void FullScreenContent::updateInformationLabel() { if (!mCurrentDocument) { return; } if (!mInformationLabel->isVisible()) { return; } ImageMetaInfoModel *model = mCurrentDocument->metaInfo(); QStringList valueList; const QStringList fullScreenPreferredMetaInfoKeyList = GwenviewConfig::fullScreenPreferredMetaInfoKeyList(); for (const QString &key : fullScreenPreferredMetaInfoKeyList) { const QString value = model->getValueForKey(key); if (!value.isEmpty()) { valueList << value; } } const QString text = valueList.join(i18nc("@item:intext fullscreen meta info separator", ", ")); mInformationLabel->setText(text); } void FullScreenContent::updateCurrentUrlWidgets() { updateInformationLabel(); updateMetaInfoDialog(); } void FullScreenContent::showImageMetaInfoDialog() { if (!mImageMetaInfoDialog) { mImageMetaInfoDialog = new ImageMetaInfoDialog(mInformationLabel); // Do not let the fullscreen theme propagate to this dialog for now, // it's already quite complicated to create a theme mImageMetaInfoDialog->setStyle(QApplication::style()); mImageMetaInfoDialog->setAttribute(Qt::WA_DeleteOnClose, true); connect(mImageMetaInfoDialog.data(), &ImageMetaInfoDialog::preferredMetaInfoKeyListChanged, this, &FullScreenContent::slotPreferredMetaInfoKeyListChanged); connect(mImageMetaInfoDialog.data(), &QObject::destroyed, this, &FullScreenContent::slotImageMetaInfoDialogClosed); } if (mCurrentDocument) { mImageMetaInfoDialog->setMetaInfo(mCurrentDocument->metaInfo(), GwenviewConfig::fullScreenPreferredMetaInfoKeyList()); } mAutoHideContainer->setAutoHidingEnabled(false); mImageMetaInfoDialog->show(); } void FullScreenContent::slotPreferredMetaInfoKeyListChanged(const QStringList &list) { GwenviewConfig::setFullScreenPreferredMetaInfoKeyList(list); GwenviewConfig::self()->save(); updateInformationLabel(); } void FullScreenContent::updateMetaInfoDialog() { if (!mImageMetaInfoDialog) { return; } ImageMetaInfoModel *model = mCurrentDocument ? mCurrentDocument->metaInfo() : nullptr; mImageMetaInfoDialog->setMetaInfo(model, GwenviewConfig::fullScreenPreferredMetaInfoKeyList()); } static QString formatSlideShowIntervalText(int value) { return i18ncp("Slideshow interval in seconds", "%1 sec", "%1 secs", value); } void FullScreenContent::updateLayout() { delete mContent->layout(); if (GwenviewConfig::showFullScreenThumbnails()) { mRightToolBar->setDirection(QBoxLayout::TopToBottom); auto layout = new QHBoxLayout(mContent); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); QVBoxLayout *vLayout; // First column vLayout = new QVBoxLayout; vLayout->addWidget(mToolBar); vLayout->addWidget(mInformationContainer); layout->addLayout(vLayout); // Second column layout->addSpacing(2); layout->addWidget(mThumbnailBar); layout->addSpacing(2); // Third column vLayout = new QVBoxLayout; vLayout->addWidget(mRightToolBar); layout->addLayout(vLayout); mInformationContainer->setMaximumWidth(mToolBar->sizeHint().width()); const int barHeight = qMax(GwenviewConfig::fullScreenBarHeight(), mMinimumThumbnailBarHeight); mThumbnailBar->setFixedHeight(barHeight); mAutoHideContainer->setFixedHeight(barHeight); mInformationLabel->setAlignment(Qt::AlignTop); mDocumentCountLabel->setAlignment(Qt::AlignBottom | Qt::AlignRight); // Shadows mToolBarShadow->reset(); mToolBarShadow->setShadow(ShadowFilter::RightEdge, QColor(0, 0, 0, 64)); mToolBarShadow->setShadow(ShadowFilter::BottomEdge, QColor(255, 255, 255, 8)); mInformationContainerShadow->reset(); mInformationContainerShadow->setShadow(ShadowFilter::LeftEdge, QColor(0, 0, 0, 64)); mInformationContainerShadow->setShadow(ShadowFilter::TopEdge, QColor(0, 0, 0, 64)); mInformationContainerShadow->setShadow(ShadowFilter::RightEdge, QColor(0, 0, 0, 128)); mInformationContainerShadow->setShadow(ShadowFilter::BottomEdge, QColor(255, 255, 255, 8)); mRightToolBarShadow->reset(); mRightToolBarShadow->setShadow(ShadowFilter::LeftEdge, QColor(0, 0, 0, 64)); mRightToolBarShadow->setShadow(ShadowFilter::BottomEdge, QColor(255, 255, 255, 8)); } else { mRightToolBar->setDirection(QBoxLayout::RightToLeft); auto layout = new QHBoxLayout(mContent); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(mToolBar); layout->addWidget(mInformationContainer); layout->addWidget(mRightToolBar); mInformationContainer->setMaximumWidth(QWIDGETSIZE_MAX); mAutoHideContainer->setFixedHeight(mToolBar->sizeHint().height()); mInformationLabel->setAlignment(Qt::AlignVCenter); mDocumentCountLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); // Shadows mToolBarShadow->reset(); mInformationContainerShadow->reset(); mInformationContainerShadow->setShadow(ShadowFilter::LeftEdge, QColor(0, 0, 0, 64)); mInformationContainerShadow->setShadow(ShadowFilter::RightEdge, QColor(0, 0, 0, 32)); mRightToolBarShadow->reset(); mRightToolBarShadow->setShadow(ShadowFilter::LeftEdge, QColor(255, 255, 255, 8)); } } void FullScreenContent::updateContainerAppearance() { if (!mContent->window()->isFullScreen() || !mViewPageVisible) { mAutoHideContainer->setActivated(false); return; } mThumbnailBar->setVisible(GwenviewConfig::showFullScreenThumbnails()); mAutoHideContainer->adjustSize(); mAutoHideContainer->setActivated(true); } void FullScreenContent::adjustSize() { if (mContent->window()->isFullScreen() && mViewPageVisible) { mAutoHideContainer->adjustSize(); } } void FullScreenContent::createOptionsAction() { // We do not use a KActionMenu because: // // - It causes the button to show a small down arrow on its right, // which makes it wider // // - We can't control where the menu shows: in no-thumbnail-mode, the // menu should not be aligned to the right edge of the screen because // if the mode is changed to thumbnail-mode, we want the option button // to remain visible mOptionsAction = new QAction(this); mOptionsAction->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); mOptionsAction->setText(i18n("Configure")); mOptionsAction->setToolTip(i18nc("@info:tooltip", "Configure full screen mode")); QObject::connect(mOptionsAction, &QAction::triggered, this, &FullScreenContent::showOptionsMenu); } void FullScreenContent::updateSlideShowIntervalLabel() { Q_ASSERT(mConfigWidget); const int value = mConfigWidget->mSlideShowIntervalSlider->value(); const QString text = formatSlideShowIntervalText(value); mConfigWidget->mSlideShowIntervalLabel->setText(text); } void FullScreenContent::setFullScreenBarHeight(int value) { mThumbnailBar->setFixedHeight(value); mAutoHideContainer->setFixedHeight(value); GwenviewConfig::setFullScreenBarHeight(value); } void FullScreenContent::showOptionsMenu() { Q_ASSERT(!mConfigWidget); mConfigWidget = new FullScreenConfigWidget; FullScreenConfigWidget *widget = mConfigWidget; // Put widget in a menu QMenu menu; auto action = new QWidgetAction(&menu); action->setDefaultWidget(widget); menu.addAction(action); // Slideshow checkboxes widget->mSlideShowLoopCheckBox->setChecked(mSlideShow->loopAction()->isChecked()); connect(widget->mSlideShowLoopCheckBox, &QAbstractButton::toggled, mSlideShow->loopAction(), &QAction::trigger); widget->mSlideShowRandomCheckBox->setChecked(mSlideShow->randomAction()->isChecked()); connect(widget->mSlideShowRandomCheckBox, &QAbstractButton::toggled, mSlideShow->randomAction(), &QAction::trigger); // Interval slider widget->mSlideShowIntervalSlider->setValue(int(GwenviewConfig::interval())); connect(widget->mSlideShowIntervalSlider, &QAbstractSlider::valueChanged, mSlideShow, &SlideShow::setInterval); connect(widget->mSlideShowIntervalSlider, &QAbstractSlider::valueChanged, this, &FullScreenContent::updateSlideShowIntervalLabel); // Interval label QString text = formatSlideShowIntervalText(88); int width = widget->mSlideShowIntervalLabel->fontMetrics().boundingRect(text).width(); widget->mSlideShowIntervalLabel->setFixedWidth(width); updateSlideShowIntervalLabel(); // Image information connect(widget->mConfigureDisplayedInformationButton, &QAbstractButton::clicked, this, &FullScreenContent::showImageMetaInfoDialog); // Thumbnails widget->mThumbnailGroupBox->setVisible(mViewPageVisible); if (mViewPageVisible) { widget->mShowThumbnailsCheckBox->setChecked(GwenviewConfig::showFullScreenThumbnails()); widget->mHeightSlider->setMinimum(mMinimumThumbnailBarHeight); widget->mHeightSlider->setValue(mThumbnailBar->height()); connect(widget->mShowThumbnailsCheckBox, &QAbstractButton::toggled, this, &FullScreenContent::slotShowThumbnailsToggled); connect(widget->mHeightSlider, &QAbstractSlider::valueChanged, this, &FullScreenContent::setFullScreenBarHeight); } // Show menu below its button QPoint pos; QWidget *button = mOptionsAction->associatedWidgets().constFirst(); Q_ASSERT(button); qCWarning(GWENVIEW_APP_LOG) << button << button->geometry(); if (QApplication::isRightToLeft()) { pos = button->mapToGlobal(button->rect().bottomLeft()); } else { pos = button->mapToGlobal(button->rect().bottomRight()); pos.rx() -= menu.sizeHint().width(); } qCWarning(GWENVIEW_APP_LOG) << pos; menu.exec(pos); } void FullScreenContent::setFullScreenMode(bool fullScreenMode) { Q_UNUSED(fullScreenMode); updateContainerAppearance(); setupThumbnailBarStyleSheet(); } void FullScreenContent::setDistractionFreeMode(bool distractionFreeMode) { mAutoHideContainer->setEdgeTriggerEnabled(!distractionFreeMode); } void FullScreenContent::slotImageMetaInfoDialogClosed() { mAutoHideContainer->setAutoHidingEnabled(true); } void FullScreenContent::slotShowThumbnailsToggled(bool value) { GwenviewConfig::setShowFullScreenThumbnails(value); GwenviewConfig::self()->save(); mThumbnailBar->setVisible(value); updateLayout(); mContent->adjustSize(); mAutoHideContainer->adjustSize(); } void FullScreenContent::slotViewModeActionToggled(bool value) { mViewPageVisible = value; updateContainerAppearance(); } void FullScreenContent::setupThumbnailBarStyleSheet() { const QPalette pal = mGvCore->palette(GvCore::NormalPalette); const QPalette fsPal = mGvCore->palette(GvCore::FullScreenPalette); QColor bgColor = fsPal.color(QPalette::Normal, QPalette::Base); QColor bgSelColor = pal.color(QPalette::Normal, QPalette::Highlight); QColor bgHovColor = pal.color(QPalette::Normal, QPalette::Highlight); // Darken the select color a little to suit dark theme of fullscreen mode bgSelColor.setHsv(bgSelColor.hue(), bgSelColor.saturation(), (bgSelColor.value() * 0.8)); // Calculate hover color based on background color in case it changes (matches ViewMainPage thumbnail bar) bgHovColor.setHsv(bgHovColor.hue(), (bgHovColor.saturation() / 2), ((bgHovColor.value() + bgColor.value()) / 2)); QString genCss = "QListView {" " background-color: %1;" "}"; genCss = genCss.arg(StyleSheetUtils::rgba(bgColor)); QString itemSelCss = "QListView::item:selected {" " background-color: %1;" "}"; itemSelCss = itemSelCss.arg(StyleSheetUtils::rgba(bgSelColor)); QString itemHovCss = "QListView::item:hover:!selected {" " background-color: %1;" "}"; itemHovCss = itemHovCss.arg(StyleSheetUtils::rgba(bgHovColor)); QString css = genCss + itemSelCss + itemHovCss; mThumbnailBar->setStyleSheet(css); } void FullScreenContent::updateDocumentCountLabel() { const int current = mThumbnailBar->currentIndex().row() + 1; const int total = mThumbnailBar->model()->rowCount(); const QString text = i18nc("@info:status %1 current document index, %2 total documents", "%1 of %2", current, total); mDocumentCountLabel->setText(text); } } // namespace #include "moc_fullscreencontent.cpp"
20,441
C++
.cpp
470
38.42766
136
0.744631
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,904
abstractcontextmanageritem.cpp
KDE_gwenview/app/abstractcontextmanageritem.cpp
/* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 "abstractcontextmanageritem.h" // Local #include <lib/contextmanager.h> namespace Gwenview { struct AbstractContextManagerItemPrivate { ContextManager *mContextManager = nullptr; QWidget *mWidget = nullptr; }; AbstractContextManagerItem::AbstractContextManagerItem(ContextManager *manager) : QObject(manager) , d(new AbstractContextManagerItemPrivate) { d->mContextManager = manager; d->mWidget = nullptr; } AbstractContextManagerItem::~AbstractContextManagerItem() { delete d; } ContextManager *AbstractContextManagerItem::contextManager() const { return d->mContextManager; } QWidget *AbstractContextManagerItem::widget() const { return d->mWidget; } void AbstractContextManagerItem::setWidget(QWidget *widget) { d->mWidget = widget; } } // namespace #include "moc_abstractcontextmanageritem.cpp"
1,624
C++
.cpp
49
31.020408
79
0.804487
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,905
fileopscontextmanageritem.cpp
KDE_gwenview/app/fileopscontextmanageritem.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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. */ // Self #include "fileopscontextmanageritem.h" // Qt #include <QAction> #include <QApplication> #include <QClipboard> #include <QListView> #include <QMenu> #include <QShortcut> // KF #include <KActionCategory> #include <KActionCollection> #include <KFileItem> #include <KFileItemActions> #include <KFileItemListProperties> #include <KIO/ApplicationLauncherJob> #include <KIO/JobUiDelegate> #include <KIO/JobUiDelegateFactory> #include <KIO/OpenFileManagerWindowJob> #include <KIO/Paste> #include <KIO/PasteJob> #include <KIO/RestoreJob> #include <KJobWidgets> #include <KLocalizedString> #include <KOpenWithDialog> #include <KPropertiesDialog> #include <KUrlMimeData> #include <KXMLGUIClient> // Local #include "fileoperations.h" #include "sidebar.h" #include <lib/contextmanager.h> #include <lib/eventwatcher.h> #include <lib/gvdebug.h> #include <lib/mimetypeutils.h> namespace Gwenview { QList<QUrl> FileOpsContextManagerItem::urlList() const { return contextManager()->selectedFileItemList().urlList(); } void FileOpsContextManagerItem::updateServiceList() { // This code is inspired from // kdebase/apps/lib/konq/konq_menuactions.cpp // Get list of all distinct mimetypes in selection QStringList mimeTypes; const auto selectedFileItemList = contextManager()->selectedFileItemList(); for (const KFileItem &item : selectedFileItemList) { const QString mimeType = item.mimetype(); if (!mimeTypes.contains(mimeType)) { mimeTypes << mimeType; } } mServiceList = KFileItemActions::associatedApplications(mimeTypes); } QMimeData *FileOpsContextManagerItem::selectionMimeData() { KFileItemList selectedFiles; // In Compare mode, restrict the returned mimedata to the focused image if (!mThumbnailView->isVisible()) { selectedFiles << KFileItem(contextManager()->currentUrl()); } else { selectedFiles = contextManager()->selectedFileItemList(); } return MimeTypeUtils::selectionMimeData(selectedFiles, MimeTypeUtils::ClipboardTarget); } QUrl FileOpsContextManagerItem::pasteTargetUrl() const { // If only one folder is selected, paste inside it, otherwise paste in // current const KFileItemList list = contextManager()->selectedFileItemList(); if (list.count() == 1 && list.first().isDir()) { return list.first().url(); } else { return contextManager()->currentDirUrl(); } } static QAction *createSeparator(QObject *parent) { auto action = new QAction(parent); action->setSeparator(true); return action; } FileOpsContextManagerItem::FileOpsContextManagerItem(ContextManager *manager, QListView *thumbnailView, KActionCollection *actionCollection, KXMLGUIClient *client) : AbstractContextManagerItem(manager) { mThumbnailView = thumbnailView; mXMLGUIClient = client; mGroup = new SideBarGroup(i18n("File Operations")); setWidget(mGroup); EventWatcher::install(mGroup, QEvent::Show, this, SLOT(updateSideBarContent())); mInTrash = false; mNewFileMenu = new KNewFileMenu(this); connect(contextManager(), &ContextManager::selectionChanged, this, &FileOpsContextManagerItem::updateActions); connect(contextManager(), &ContextManager::currentDirUrlChanged, this, &FileOpsContextManagerItem::updateActions); auto file = new KActionCategory(i18nc("@title actions category", "File"), actionCollection); auto edit = new KActionCategory(i18nc("@title actions category", "Edit"), actionCollection); mCutAction = edit->addAction(KStandardAction::Cut, this, SLOT(cut())); mCopyAction = edit->addAction(KStandardAction::Copy, this, SLOT(copy())); mPasteAction = edit->addAction(KStandardAction::Paste, this, SLOT(paste())); mCopyToAction = file->addAction(QStringLiteral("file_copy_to"), this, SLOT(copyTo())); mCopyToAction->setText(i18nc("Verb", "Copy To...")); mCopyToAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy"))); actionCollection->setDefaultShortcut(mCopyToAction, Qt::Key_F7); mMoveToAction = file->addAction(QStringLiteral("file_move_to"), this, SLOT(moveTo())); mMoveToAction->setText(i18nc("Verb", "Move To...")); mMoveToAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-move"), QIcon::fromTheme(QStringLiteral("go-jump")))); actionCollection->setDefaultShortcut(mMoveToAction, Qt::Key_F8); mLinkToAction = file->addAction(QStringLiteral("file_link_to"), this, SLOT(linkTo())); mLinkToAction->setText(i18nc("Verb: create link to the file where user wants", "Link To...")); mLinkToAction->setIcon(QIcon::fromTheme(QStringLiteral("link"))); actionCollection->setDefaultShortcut(mLinkToAction, Qt::Key_F9); mRenameAction = file->addAction(QStringLiteral("file_rename"), this, SLOT(rename())); mRenameAction->setText(i18nc("Verb", "Rename...")); mRenameAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename"))); actionCollection->setDefaultShortcut(mRenameAction, Qt::Key_F2); mTrashAction = file->addAction(QStringLiteral("file_trash"), this, SLOT(trash())); mTrashAction->setText(i18nc("Verb", "Trash")); mTrashAction->setIcon(QIcon::fromTheme(QStringLiteral("user-trash"))); actionCollection->setDefaultShortcut(mTrashAction, Qt::Key_Delete); mDelAction = file->addAction(KStandardAction::DeleteFile, this, SLOT(del())); mRestoreAction = file->addAction(QStringLiteral("file_restore"), this, SLOT(restore())); mRestoreAction->setText(i18n("Restore")); mRestoreAction->setIcon(QIcon::fromTheme(QStringLiteral("restoration"))); mShowPropertiesAction = file->addAction(QStringLiteral("file_show_properties"), this, SLOT(showProperties())); mShowPropertiesAction->setText(i18n("Properties")); mShowPropertiesAction->setIcon(QIcon::fromTheme(QStringLiteral("document-properties"))); actionCollection->setDefaultShortcut(mShowPropertiesAction, QKeySequence(Qt::ALT | Qt::Key_Return)); mCreateFolderAction = file->addAction(QStringLiteral("file_create_folder"), this, SLOT(createFolder())); mCreateFolderAction->setText(i18n("Create Folder...")); mCreateFolderAction->setIcon(QIcon::fromTheme(QStringLiteral("folder-new"))); mOpenInNewWindowAction = file->addAction(QStringLiteral("file_open_in_new_window")); mOpenInNewWindowAction->setText(i18nc("@action:inmenu", "Open in New Window")); mOpenInNewWindowAction->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); connect(mOpenInNewWindowAction, &QAction::triggered, this, &FileOpsContextManagerItem::openInNewWindow); mOpenWithAction = file->addAction(QStringLiteral("file_open_with")); mOpenWithAction->setText(i18n("Open With")); mOpenWithAction->setIcon(QIcon::fromTheme(QStringLiteral("system-run"))); auto menu = new QMenu; mOpenWithAction->setMenu(menu); connect(menu, &QMenu::aboutToShow, this, &FileOpsContextManagerItem::populateOpenMenu); connect(menu, &QMenu::triggered, this, &FileOpsContextManagerItem::openWith); mOpenContainingFolderAction = file->addAction(QStringLiteral("file_open_containing_folder"), this, SLOT(openContainingFolder())); mOpenContainingFolderAction->setText(i18n("Open Containing Folder")); mOpenContainingFolderAction->setIcon(QIcon::fromTheme(QStringLiteral("document-open-folder"))); mRegularFileActionList << mRenameAction << mTrashAction << mDelAction << createSeparator(this) << mCopyToAction << mMoveToAction << mLinkToAction << createSeparator(this) << mOpenInNewWindowAction << mOpenWithAction << mOpenContainingFolderAction << mShowPropertiesAction << createSeparator(this) << mCreateFolderAction; mTrashFileActionList << mRestoreAction << mDelAction << createSeparator(this) << mShowPropertiesAction; connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &FileOpsContextManagerItem::updatePasteAction); updatePasteAction(); // Delay action update because it must happen *after* main window has called // createGUI(), otherwise calling mXMLGUIClient->plugActionList() will // fail. QMetaObject::invokeMethod(this, &FileOpsContextManagerItem::updateActions, Qt::QueuedConnection); } FileOpsContextManagerItem::~FileOpsContextManagerItem() { delete mOpenWithAction->menu(); } void FileOpsContextManagerItem::updateActions() { const int count = contextManager()->selectedFileItemList().count(); const bool selectionNotEmpty = count > 0; const bool urlIsValid = contextManager()->currentUrl().isValid(); const bool dirUrlIsValid = contextManager()->currentDirUrl().isValid(); mInTrash = contextManager()->currentDirUrl().scheme() == QLatin1String("trash"); mCutAction->setEnabled(selectionNotEmpty); mCopyAction->setEnabled(selectionNotEmpty); mCopyToAction->setEnabled(selectionNotEmpty); mMoveToAction->setEnabled(selectionNotEmpty); mLinkToAction->setEnabled(selectionNotEmpty); mTrashAction->setEnabled(selectionNotEmpty); mRestoreAction->setEnabled(selectionNotEmpty); mDelAction->setEnabled(selectionNotEmpty); mOpenInNewWindowAction->setEnabled(selectionNotEmpty); mOpenWithAction->setEnabled(selectionNotEmpty); mRenameAction->setEnabled(count == 1); mOpenContainingFolderAction->setEnabled(selectionNotEmpty); mCreateFolderAction->setEnabled(dirUrlIsValid); mShowPropertiesAction->setEnabled(dirUrlIsValid || urlIsValid); mXMLGUIClient->unplugActionList(QStringLiteral("file_action_list")); QList<QAction *> &list = mInTrash ? mTrashFileActionList : mRegularFileActionList; mXMLGUIClient->plugActionList(QStringLiteral("file_action_list"), list); updateSideBarContent(); } void FileOpsContextManagerItem::updatePasteAction() { const QMimeData *mimeData = QApplication::clipboard()->mimeData(); bool enable; KFileItem destItem(pasteTargetUrl()); const QString text = KIO::pasteActionText(mimeData, &enable, destItem); mPasteAction->setEnabled(enable); mPasteAction->setText(text); } void FileOpsContextManagerItem::updateSideBarContent() { if (!mGroup->isVisible()) { return; } mGroup->clear(); // Some actions we want to exist in a general sense so they're accessible // via the menu structure and with keyboard shortcuts, but we don't want // them to appear in the sidebar because they're too dangerous, little-used, // and/or contribute to the main window being too tall on short screens; see // https://bugs.kde.org/458987. const QList<QAction *> itemsToOmit = {mDelAction, mCreateFolderAction, mOpenInNewWindowAction}; QList<QAction *> &list = mInTrash ? mTrashFileActionList : mRegularFileActionList; for (QAction *action : qAsConst(list)) { if (action->isEnabled() && !action->isSeparator() && !itemsToOmit.contains(action)) { mGroup->addAction(action); } } } void FileOpsContextManagerItem::showProperties() { const KFileItemList list = contextManager()->selectedFileItemList(); if (!list.isEmpty()) { KPropertiesDialog::showDialog(list, mGroup); } else { const QUrl url = contextManager()->currentDirUrl(); KPropertiesDialog::showDialog(url, mGroup); } } void FileOpsContextManagerItem::cut() { QMimeData *mimeData = selectionMimeData(); KIO::setClipboardDataCut(mimeData, true); QApplication::clipboard()->setMimeData(mimeData); } void FileOpsContextManagerItem::copy() { QMimeData *mimeData = selectionMimeData(); KIO::setClipboardDataCut(mimeData, false); QApplication::clipboard()->setMimeData(mimeData); } void FileOpsContextManagerItem::paste() { KIO::Job *job = KIO::paste(QApplication::clipboard()->mimeData(), pasteTargetUrl()); KJobWidgets::setWindow(job, mGroup); } void FileOpsContextManagerItem::trash() { FileOperations::trash(urlList(), mGroup); } void FileOpsContextManagerItem::del() { FileOperations::del(urlList(), mGroup); } void FileOpsContextManagerItem::restore() { KIO::RestoreJob *job = KIO::restoreFromTrash(urlList()); KJobWidgets::setWindow(job, mGroup); job->uiDelegate()->setAutoErrorHandlingEnabled(true); } void FileOpsContextManagerItem::copyTo() { FileOperations::copyTo(urlList(), widget(), contextManager()); } void FileOpsContextManagerItem::moveTo() { FileOperations::moveTo(urlList(), widget(), contextManager()); } void FileOpsContextManagerItem::linkTo() { FileOperations::linkTo(urlList(), widget(), contextManager()); } void FileOpsContextManagerItem::rename() { if (mThumbnailView->isVisible()) { QModelIndex index = mThumbnailView->currentIndex(); mThumbnailView->edit(index); } else { FileOperations::rename(urlList().constFirst(), mGroup, contextManager()); contextManager()->slotSelectionChanged(); } } void FileOpsContextManagerItem::createFolder() { const QUrl url = contextManager()->currentDirUrl(); mNewFileMenu->setParentWidget(mGroup); mNewFileMenu->setWorkingDirectory(url); mNewFileMenu->createDirectory(); } void FileOpsContextManagerItem::populateOpenMenu() { QMenu *openMenu = mOpenWithAction->menu(); qDeleteAll(openMenu->actions()); updateServiceList(); int idx = -1; for (const KService::Ptr &service : qAsConst(mServiceList)) { ++idx; if (service->name() == QLatin1String("Gwenview")) { continue; } QString text = service->name().replace('&', "&&"); QAction *action = openMenu->addAction(text); action->setIcon(QIcon::fromTheme(service->icon())); action->setData(idx); } openMenu->addSeparator(); QAction *action = openMenu->addAction(QIcon::fromTheme(QStringLiteral("system-run")), i18n("Other Application...")); action->setData(-1); } void FileOpsContextManagerItem::openInNewWindow() { const QList<QUrl> urls = urlList(); if (urls.isEmpty()) { return; } KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("org.kde.gwenview")); if (!service) { return; } auto job = new KIO::ApplicationLauncherJob(service); job->setUrls(urls); job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, nullptr)); job->start(); } void FileOpsContextManagerItem::openWith(QAction *action) { Q_ASSERT(action); KService::Ptr service; const QList<QUrl> list = urlList(); bool ok; int idx = action->data().toInt(&ok); GV_RETURN_IF_FAIL(ok); if (idx != -1) { service = mServiceList.at(idx); } // If service is null, ApplicationLauncherJob will invoke the open-with dialog auto job = new KIO::ApplicationLauncherJob(service); job->setUrls(list); job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, mGroup)); job->start(); } void FileOpsContextManagerItem::openContainingFolder() { KIO::highlightInFileManager(urlList()); } } // namespace #include "moc_fileopscontextmanageritem.cpp"
16,072
C++
.cpp
362
39.762431
152
0.737896
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,906
renamedialog.cpp
KDE_gwenview/app/renamedialog.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2018 Aurélien Gâteau <agateau@kde.org> Copyright 2018 Peter Mühlenpfordt <devel@ukn8.de> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "renamedialog.h" // Qt #include <QMimeDatabase> #include <QPushButton> // KF #include <KGuiItem> #include <KLocalizedString> // Local #include <ui_renamedialog.h> namespace Gwenview { struct RenameDialogPrivate : public Ui_RenameDialog { }; RenameDialog::RenameDialog(QWidget *parent) : QDialog(parent) , d(new RenameDialogPrivate) { d->setupUi(this); QPushButton *okButton = d->mButtonBox->button(QDialogButtonBox::Ok); KGuiItem::assign(okButton, KGuiItem(i18nc("@action:button", "Rename"), QStringLiteral("edit-rename"))); connect(d->mFilename, &QLineEdit::textChanged, this, &RenameDialog::updateButtons); } RenameDialog::~RenameDialog() { delete d; } void RenameDialog::setFilename(const QString &filename) { d->mFilename->setText(filename); d->mFilenameLabel->setText(xi18n("Rename <filename>%1</filename> to:", filename)); const QMimeDatabase db; const QString extension = db.suffixForFileName(filename); int selectionLength = filename.length(); if (!extension.isEmpty()) { // The filename contains an extension. Assure that only the filename // gets selected. selectionLength -= extension.length() + 1; } d->mFilename->setSelection(0, selectionLength); d->mFilename->setFocus(); } QString RenameDialog::filename() const { return d->mFilename->text(); } void RenameDialog::updateButtons() { const bool enableButton = !d->mFilename->text().isEmpty(); d->mButtonBox->button(QDialogButtonBox::Ok)->setEnabled(enableButton); } } // namespace #include "moc_renamedialog.cpp"
2,473
C++
.cpp
70
32.6
107
0.758186
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,907
browsemainpage.cpp
KDE_gwenview/app/browsemainpage.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "browsemainpage.h" // Qt #include <QActionGroup> #include <QDropEvent> #include <QMenu> #include <QVBoxLayout> // KF #include <KActionCategory> #include <KActionCollection> #include <KActionMenu> #include <KDirModel> #include <KFileItem> #include <KFilePlacesModel> #include <KIconLoader> #include <KLocalizedString> #include <KUrlMimeData> #include <KUrlNavigator> // Local #include <fileoperations.h> #include <filtercontroller.h> #include <gvcore.h> #include <lib/archiveutils.h> #include <lib/document/documentfactory.h> #include <lib/gvdebug.h> #include <lib/gwenviewconfig.h> #include <lib/semanticinfo/abstractsemanticinfobackend.h> #include <lib/semanticinfo/sorteddirmodel.h> #include <lib/semanticinfo/tagmodel.h> #include <lib/sorting.h> #include <lib/thumbnailview/previewitemdelegate.h> #include <lib/thumbnailview/thumbnailview.h> #include <mimetypeutils.h> #include <ui_browsemainpage.h> #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE #include "lib/semanticinfo/semanticinfodirmodel.h" #endif namespace Gwenview { inline Sorting::Enum sortingFromSortAction(const QAction *action) { Q_ASSERT(action); return Sorting::Enum(action->data().toInt()); } struct BrowseMainPagePrivate : public Ui_BrowseMainPage { BrowseMainPage *q = nullptr; GvCore *mGvCore = nullptr; KFilePlacesModel *mFilePlacesModel = nullptr; KUrlNavigator *mUrlNavigator = nullptr; SortedDirModel *mDirModel = nullptr; int mDocumentCountImages; int mDocumentCountVideos; KFileItemList *mSelectedMediaItems = nullptr; KActionCollection *mActionCollection = nullptr; FilterController *mFilterController = nullptr; QActionGroup *mSortAction = nullptr; KToggleAction *mSortDescendingAction = nullptr; QActionGroup *mThumbnailDetailsActionGroup = nullptr; PreviewItemDelegate *mDelegate = nullptr; void setupWidgets() { setupUi(q); q->layout()->setContentsMargins(0, 0, 0, 0); int margins = q->style()->pixelMetric(QStyle::PM_ToolBarItemMargin) + q->style()->pixelMetric(QStyle::PM_ToolBarFrameWidth); mStatusBarContainer->layout()->setContentsMargins(margins, margins, margins, margins); mStatusBarContainer->layout()->setSpacing(q->style()->pixelMetric(QStyle::PM_ToolBarItemSpacing)); // mThumbnailView mThumbnailView->setModel(mDirModel); mDelegate = new PreviewItemDelegate(mThumbnailView); mThumbnailView->setItemDelegate(mDelegate); mThumbnailView->setSelectionMode(QAbstractItemView::ExtendedSelection); // mUrlNavigator (use stupid layouting code because KUrlNavigator ctor // can't be used directly from Designer) mFilePlacesModel = new KFilePlacesModel(q); mUrlNavigator = new KUrlNavigator(mFilePlacesModel, QUrl(), mUrlNavigatorContainer); mUrlNavigatorContainer->setAutoFillBackground(true); mUrlNavigatorContainer->setBackgroundRole(QPalette::Mid); auto layout = new QVBoxLayout(mUrlNavigatorContainer); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mUrlNavigator); QObject::connect(mUrlNavigator, SIGNAL(urlsDropped(QUrl, QDropEvent *)), q, SLOT(slotUrlsDropped(QUrl, QDropEvent *))); // FullScreen Toolbar mFullScreenToolBar->setVisible(false); mFullScreenToolBar2->setVisible(false); mFullScreenToolBar->setAutoFillBackground(true); mFullScreenToolBar2->setAutoFillBackground(true); mFullScreenToolBar->setBackgroundRole(QPalette::Mid); mFullScreenToolBar2->setBackgroundRole(QPalette::Mid); // Thumbnail slider QObject::connect(mThumbnailSlider, &ZoomSlider::valueChanged, mThumbnailView, &ThumbnailView::setThumbnailWidth); QObject::connect(mThumbnailView, &ThumbnailView::thumbnailWidthChanged, mThumbnailSlider, &ZoomSlider::setValue); // Document count label QMargins labelMargins = mDocumentCountLabel->contentsMargins(); labelMargins.setLeft(15); labelMargins.setRight(15); mDocumentCountLabel->setContentsMargins(labelMargins); } QAction *thumbnailDetailAction(const QString &text, PreviewItemDelegate::ThumbnailDetail detail) { auto action = new QAction(q); action->setText(text); action->setCheckable(true); action->setChecked(GwenviewConfig::thumbnailDetails() & detail); action->setData(QVariant(detail)); mThumbnailDetailsActionGroup->addAction(action); QObject::connect(action, SIGNAL(triggered(bool)), q, SLOT(updateThumbnailDetails())); return action; } void setupActions(KActionCollection *actionCollection) { auto view = new KActionCategory(i18nc("@title actions category - means actions changing smth in interface", "View"), actionCollection); QAction *action = view->addAction("edit_location", q, SLOT(editLocation())); action->setText(i18nc("@action:inmenu Navigation Bar", "Edit Location")); actionCollection->setDefaultShortcut(action, Qt::Key_F6); auto sortActionMenu = view->add<KActionMenu>("sort_by"); sortActionMenu->setText(i18nc("@action:inmenu", "Sort By")); sortActionMenu->setIcon(QIcon::fromTheme(QStringLiteral("view-sort"))); sortActionMenu->setPopupMode(QToolButton::InstantPopup); mSortAction = new QActionGroup(actionCollection); action = new QAction(i18nc("@addAction:inmenu", "Name"), mSortAction); action->setCheckable(true); action->setData(QVariant(Sorting::Name)); action = new QAction(i18nc("@addAction:inmenu", "Date"), mSortAction); action->setCheckable(true); action->setData(QVariant(Sorting::Date)); action = new QAction(i18nc("@addAction:inmenu", "Size"), mSortAction); action->setCheckable(true); action->setData(QVariant(Sorting::Size)); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE action = new QAction(i18nc("@addAction:inmenu", "Rating"), mSortAction); action->setCheckable(true); action->setData(QVariant(Sorting::Rating)); #endif QObject::connect(mSortAction, SIGNAL(triggered(QAction *)), q, SLOT(updateSortOrder())); mSortDescendingAction = view->add<KToggleAction>(QStringLiteral("sort_desc")); mSortDescendingAction->setText(i18nc("@action:inmenu Sort", "Descending")); QObject::connect(mSortDescendingAction, SIGNAL(toggled(bool)), q, SLOT(updateSortOrder())); for (auto action : mSortAction->actions()) { sortActionMenu->addAction(action); } sortActionMenu->addSeparator(); sortActionMenu->addAction(mSortDescendingAction); mThumbnailDetailsActionGroup = new QActionGroup(q); mThumbnailDetailsActionGroup->setExclusive(false); auto thumbnailDetailsAction = view->add<KActionMenu>(QStringLiteral("thumbnail_details")); thumbnailDetailsAction->setText(i18nc("@action:inmenu", "Thumbnail Details")); thumbnailDetailsAction->addAction(thumbnailDetailAction(i18nc("@action:inmenu", "Filename"), PreviewItemDelegate::FileNameDetail)); thumbnailDetailsAction->addAction(thumbnailDetailAction(i18nc("@action:inmenu", "Date"), PreviewItemDelegate::DateDetail)); thumbnailDetailsAction->addAction(thumbnailDetailAction(i18nc("@action:inmenu", "Image Size"), PreviewItemDelegate::ImageSizeDetail)); thumbnailDetailsAction->addAction(thumbnailDetailAction(i18nc("@action:inmenu", "File Size"), PreviewItemDelegate::FileSizeDetail)); #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE thumbnailDetailsAction->addAction(thumbnailDetailAction(i18nc("@action:inmenu", "Rating"), PreviewItemDelegate::RatingDetail)); #endif auto file = new KActionCategory(i18nc("@title actions category", "File"), actionCollection); action = file->addAction(QStringLiteral("add_folder_to_places"), q, SLOT(addFolderToPlaces())); action->setText(i18nc("@action:inmenu", "Add Folder to Places")); action->setIcon(QIcon::fromTheme(QStringLiteral("bookmark-new"))); } void setupFilterController() { auto menu = new QMenu(mAddFilterButton); mFilterController = new FilterController(mFilterFrame, mDirModel); const auto actionList = mFilterController->actionList(); for (QAction *action : actionList) { menu->addAction(action); } mAddFilterButton->setMenu(menu); } void setupFullScreenToolBar() { mFullScreenToolBar->setIconDimensions(KIconLoader::SizeMedium); mFullScreenToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); mFullScreenToolBar->addAction(mActionCollection->action(QStringLiteral("browse"))); mFullScreenToolBar->addAction(mActionCollection->action(QStringLiteral("view"))); mFullScreenToolBar2->setIconDimensions(KIconLoader::SizeMedium); mFullScreenToolBar2->setToolButtonStyle(Qt::ToolButtonIconOnly); mFullScreenToolBar2->addAction(mActionCollection->action(QStringLiteral("leave_fullscreen"))); } void updateSelectedMediaItems(const QItemSelection &selected, const QItemSelection &deselected) { for (auto index : selected.indexes()) { KFileItem item = mDirModel->itemForIndex(index); if (!ArchiveUtils::fileItemIsDirOrArchive(item)) { mSelectedMediaItems->append(item); } } for (auto index : deselected.indexes()) { KFileItem item = mDirModel->itemForIndex(index); mSelectedMediaItems->removeOne(item); } } void updateDocumentCountLabel() { if (mSelectedMediaItems->count() > 1) { KIO::filesize_t totalSize = 0; for (const auto &item : *mSelectedMediaItems) { totalSize += item.size(); } const QString text = i18nc("@info:status %1 number of selected documents, %2 total number of documents, %3 total filesize of selected documents", "Selected %1 of %2 (%3)", mSelectedMediaItems->count(), mDocumentCountImages + mDocumentCountVideos, KIO::convertSize(totalSize)); mDocumentCountLabel->setText(text); } else { const QString imageText = i18ncp("@info:status Image files", "%1 image", "%1 images", mDocumentCountImages); const QString videoText = i18ncp("@info:status Video files", "%1 video", "%1 videos", mDocumentCountVideos); QString labelText; if (mDocumentCountImages > 0 && mDocumentCountVideos == 0) { labelText = imageText; } else if (mDocumentCountImages == 0 && mDocumentCountVideos > 0) { labelText = videoText; } else { labelText = i18nc("@info:status images, videos", "%1, %2", imageText, videoText); } mDocumentCountLabel->setText(labelText); } } void documentCountsForIndexRange(const QModelIndex &parent, int start, int end, int &imageCountOut, int &videoCountOut) { imageCountOut = 0; videoCountOut = 0; for (int row = start; row <= end; ++row) { QModelIndex index = mDirModel->index(row, 0, parent); KFileItem item = mDirModel->itemForIndex(index); if (!ArchiveUtils::fileItemIsDirOrArchive(item)) { MimeTypeUtils::Kind kind = MimeTypeUtils::mimeTypeKind(item.mimetype()); if (kind == MimeTypeUtils::KIND_RASTER_IMAGE || kind == MimeTypeUtils::KIND_SVG_IMAGE) { imageCountOut++; } else if (kind == MimeTypeUtils::KIND_VIDEO) { videoCountOut++; } } } } void updateContextBarActions() { PreviewItemDelegate::ContextBarActions actions; switch (GwenviewConfig::thumbnailActions()) { case ThumbnailActions::None: actions = PreviewItemDelegate::NoAction; break; case ThumbnailActions::ShowSelectionButtonOnly: actions = PreviewItemDelegate::SelectionAction; break; case ThumbnailActions::AllButtons: default: actions = PreviewItemDelegate::SelectionAction | PreviewItemDelegate::RotateAction; if (!q->window()->isFullScreen()) { actions |= PreviewItemDelegate::FullScreenAction; } break; } mDelegate->setContextBarActions(actions); } void applyPalette(bool fullScreenmode) { q->setPalette(mGvCore->palette(fullScreenmode ? GvCore::FullScreenPalette : GvCore::NormalPalette)); mThumbnailView->setPalette(mGvCore->palette(fullScreenmode ? GvCore::FullScreenViewPalette : GvCore::NormalViewPalette)); } }; BrowseMainPage::BrowseMainPage(QWidget *parent, KActionCollection *actionCollection, GvCore *gvCore) : QWidget(parent) , d(new BrowseMainPagePrivate) { d->q = this; d->mGvCore = gvCore; d->mDirModel = gvCore->sortedDirModel(); d->mDocumentCountImages = 0; d->mDocumentCountVideos = 0; d->mSelectedMediaItems = new KFileItemList; d->mActionCollection = actionCollection; d->setupWidgets(); d->setupActions(actionCollection); d->setupFilterController(); loadConfig(); updateSortOrder(); updateThumbnailDetails(); // Set up connections for document count connect(d->mDirModel, &SortedDirModel::rowsInserted, this, &BrowseMainPage::slotDirModelRowsInserted); connect(d->mDirModel, &SortedDirModel::rowsAboutToBeRemoved, this, &BrowseMainPage::slotDirModelRowsAboutToBeRemoved); connect(d->mDirModel, &SortedDirModel::modelReset, this, &BrowseMainPage::slotDirModelReset); connect(thumbnailView(), &ThumbnailView::selectionChangedSignal, this, &BrowseMainPage::slotSelectionChanged); connect(qApp, &QApplication::paletteChanged, this, [this]() { d->applyPalette(window()->isFullScreen()); }); installEventFilter(this); } BrowseMainPage::~BrowseMainPage() { d->mSelectedMediaItems->clear(); delete d->mSelectedMediaItems; delete d; } void BrowseMainPage::loadConfig() { d->applyPalette(window()->isFullScreen()); d->mUrlNavigator->setUrlEditable(GwenviewConfig::urlNavigatorIsEditable()); d->mUrlNavigator->setShowFullPath(GwenviewConfig::urlNavigatorShowFullPath()); d->mThumbnailSlider->setValue(GwenviewConfig::thumbnailSize()); d->mThumbnailSlider->updateToolTip(); // If GwenviewConfig::thumbnailSize() returns the current value of // mThumbnailSlider, it won't emit valueChanged() and the thumbnail view // won't be updated. That's why we do it ourself. d->mThumbnailView->setThumbnailAspectRatio(GwenviewConfig::thumbnailAspectRatio()); d->mThumbnailView->setThumbnailWidth(GwenviewConfig::thumbnailSize()); const auto actionsList = d->mSortAction->actions(); for (QAction *action : actionsList) { if (sortingFromSortAction(action) == GwenviewConfig::sorting()) { action->setChecked(true); break; } } d->mSortDescendingAction->setChecked(GwenviewConfig::sortDescending()); d->updateContextBarActions(); } void BrowseMainPage::saveConfig() const { GwenviewConfig::setUrlNavigatorIsEditable(d->mUrlNavigator->isUrlEditable()); GwenviewConfig::setUrlNavigatorShowFullPath(d->mUrlNavigator->showFullPath()); GwenviewConfig::setThumbnailSize(d->mThumbnailSlider->value()); GwenviewConfig::setSorting(sortingFromSortAction(d->mSortAction->checkedAction())); GwenviewConfig::setSortDescending(d->mSortDescendingAction->isChecked()); GwenviewConfig::setThumbnailDetails(d->mDelegate->thumbnailDetails()); } bool BrowseMainPage::eventFilter(QObject *watched, QEvent *event) { // Leave fullscreen when not viewing an image if (window()->isFullScreen() && event->type() == QEvent::ShortcutOverride) { const QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Escape) { d->mActionCollection->action(QStringLiteral("leave_fullscreen"))->trigger(); event->accept(); } } return QWidget::eventFilter(watched, event); } void BrowseMainPage::mousePressEvent(QMouseEvent *event) { switch (event->button()) { case Qt::ForwardButton: case Qt::BackButton: return; default: QWidget::mousePressEvent(event); } } ThumbnailView *BrowseMainPage::thumbnailView() const { return d->mThumbnailView; } KUrlNavigator *BrowseMainPage::urlNavigator() const { return d->mUrlNavigator; } void BrowseMainPage::reload() { const QModelIndexList list = d->mThumbnailView->selectionModel()->selectedIndexes(); for (const QModelIndex &index : list) { d->mThumbnailView->reloadThumbnail(index); } d->mDirModel->reload(); } void BrowseMainPage::editLocation() { d->mUrlNavigator->setUrlEditable(true); d->mUrlNavigator->setFocus(); } void BrowseMainPage::addFolderToPlaces() { QUrl url = d->mUrlNavigator->locationUrl(); QString text = url.adjusted(QUrl::StripTrailingSlash).fileName(); if (text.isEmpty()) { text = url.toDisplayString(); } d->mFilePlacesModel->addPlace(text, url); } void BrowseMainPage::slotDirModelRowsInserted(const QModelIndex &parent, int start, int end) { int imageCount; int videoCount; d->documentCountsForIndexRange(parent, start, end, imageCount, videoCount); if (imageCount > 0 || videoCount > 0) { d->mDocumentCountImages += imageCount; d->mDocumentCountVideos += videoCount; d->updateDocumentCountLabel(); } } void BrowseMainPage::slotDirModelRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { int imageCount; int videoCount; d->documentCountsForIndexRange(parent, start, end, imageCount, videoCount); if (imageCount > 0 || videoCount > 0) { d->mDocumentCountImages -= imageCount; d->mDocumentCountVideos -= videoCount; d->updateDocumentCountLabel(); } } void BrowseMainPage::slotDirModelReset() { d->mDocumentCountImages = 0; d->mDocumentCountVideos = 0; d->mSelectedMediaItems->clear(); d->updateDocumentCountLabel(); } void BrowseMainPage::slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { d->updateSelectedMediaItems(selected, deselected); d->updateDocumentCountLabel(); } void BrowseMainPage::updateSortOrder() { const QAction *action = d->mSortAction->checkedAction(); GV_RETURN_IF_FAIL(action); const Qt::SortOrder order = d->mSortDescendingAction->isChecked() ? Qt::DescendingOrder : Qt::AscendingOrder; KDirModel::ModelColumns column = KDirModel::Name; int sortRole = Qt::DisplayRole; // Map Sorting::Enum to model columns and sorting roles switch (sortingFromSortAction(action)) { case Sorting::Name: column = KDirModel::Name; break; case Sorting::Size: column = KDirModel::Size; break; case Sorting::Date: column = KDirModel::ModifiedTime; break; #ifndef GWENVIEW_SEMANTICINFO_BACKEND_NONE case Sorting::Rating: column = KDirModel::Name; sortRole = SemanticInfoDirModel::RatingRole; break; #endif } d->mDirModel->setSortRole(sortRole); d->mDirModel->sort(column, order); d->mGvCore->setTrackFileManagerSorting(false); } void BrowseMainPage::updateThumbnailDetails() { PreviewItemDelegate::ThumbnailDetails details = {}; const auto actionList = d->mThumbnailDetailsActionGroup->actions(); for (const QAction *action : actionList) { if (action->isChecked()) { details |= PreviewItemDelegate::ThumbnailDetail(action->data().toInt()); } } d->mDelegate->setThumbnailDetails(details); } void BrowseMainPage::setFullScreenMode(bool fullScreen) { d->applyPalette(fullScreen); d->mUrlNavigatorContainer->setContentsMargins(fullScreen ? 6 : 0, 0, 0, 0); d->updateContextBarActions(); d->mFullScreenToolBar->setVisible(fullScreen); d->mFullScreenToolBar2->setVisible(fullScreen); if (fullScreen && d->mFullScreenToolBar->actions().isEmpty()) { d->setupFullScreenToolBar(); } } void BrowseMainPage::setStatusBarVisible(bool visible) { d->mStatusBarContainer->setVisible(visible); } void BrowseMainPage::slotUrlsDropped(const QUrl &destUrl, QDropEvent *event) { const QList<QUrl> urlList = KUrlMimeData::urlsFromMimeData(event->mimeData()); if (urlList.isEmpty()) { return; } event->acceptProposedAction(); // We can't call FileOperations::showMenuForDroppedUrls() directly because // we need the slot to return so that the drop event is accepted. Otherwise // the drop cursor is still visible when the menu is shown. QMetaObject::invokeMethod( this, [this, urlList, destUrl]() { showMenuForDroppedUrls(urlList, destUrl); }, Qt::QueuedConnection); } void BrowseMainPage::showMenuForDroppedUrls(const QList<QUrl> &urlList, const QUrl &destUrl) { FileOperations::showMenuForDroppedUrls(d->mUrlNavigator, urlList, destUrl); } QToolButton *BrowseMainPage::toggleSideBarButton() const { return d->mToggleSideBarButton; } } // namespace #include "moc_browsemainpage.cpp"
22,396
C++
.cpp
509
37.550098
157
0.708576
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,908
saveallhelper.cpp
KDE_gwenview/app/saveallhelper.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "saveallhelper.h" // Qt #include <QFuture> #include <QFutureWatcher> #include <QProgressDialog> #include <QSet> #include <QStringList> #include <QUrl> // KF #include <KLocalizedString> #include <KMessageBox> // Local #include <lib/document/document.h> #include <lib/document/documentfactory.h> #include <lib/document/documentjob.h> namespace Gwenview { struct SaveAllHelperPrivate { QWidget *mParent = nullptr; QProgressDialog *mProgressDialog = nullptr; QSet<DocumentJob *> mJobSet; QStringList mErrorList; }; SaveAllHelper::SaveAllHelper(QWidget *parent) : d(new SaveAllHelperPrivate) { d->mParent = parent; d->mProgressDialog = new QProgressDialog(parent); connect(d->mProgressDialog, &QProgressDialog::canceled, this, &SaveAllHelper::slotCanceled); d->mProgressDialog->setLabelText(i18nc("@info:progress saving all image changes", "Saving...")); d->mProgressDialog->setCancelButtonText(i18n("&Stop")); d->mProgressDialog->setMinimum(0); } SaveAllHelper::~SaveAllHelper() { delete d; } void SaveAllHelper::save() { const QList<QUrl> list = DocumentFactory::instance()->modifiedDocumentList(); d->mProgressDialog->setRange(0, list.size()); d->mProgressDialog->setValue(0); for (const QUrl &url : list) { Document::Ptr doc = DocumentFactory::instance()->load(url); DocumentJob *job = doc->save(url, doc->format()); connect(job, &DocumentJob::result, this, &SaveAllHelper::slotResult); d->mJobSet << job; } d->mProgressDialog->exec(); // Done, show message if necessary if (!d->mErrorList.isEmpty()) { QString msg = i18ncp("@info", "One document could not be saved:", "%1 documents could not be saved:", d->mErrorList.count()); msg += QLatin1String("<ul>"); for (const QString &item : qAsConst(d->mErrorList)) { msg += "<li>" + item + "</li>"; } msg += QLatin1String("</ul>"); KMessageBox::error(d->mParent, msg); } } void SaveAllHelper::slotCanceled() { for (DocumentJob *job : qAsConst(d->mJobSet)) { job->kill(); } } void SaveAllHelper::slotResult(KJob *_job) { auto job = static_cast<DocumentJob *>(_job); if (job->error()) { const QUrl url = job->document()->url(); const QString name = url.fileName().isEmpty() ? url.toDisplayString() : url.fileName(); d->mErrorList << xi18nc("@info %1 is the name of the document which failed to save, %2 is the reason for the failure", "<filename>%1</filename>: %2", name, kxi18n(qPrintable(job->errorString()))); } d->mJobSet.remove(job); d->mProgressDialog->setValue(d->mProgressDialog->value() + 1); } } // namespace #include "moc_saveallhelper.cpp"
3,672
C++
.cpp
99
32.545455
133
0.689364
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,909
spotlightmode.cpp
KDE_gwenview/app/spotlightmode.cpp
/* This file is part of the KDE project SPDX-License-Identifier: GPL-2.0-or-later Project idea and initial maintainer: Aurélien Gâteau <agateau@kde.org> SPDX-FileCopyrightText: 2024 Ravil Saifullin <saifullin.dev@gmail.com> */ #include "spotlightmode.h" // Qt #include <QHBoxLayout> #include <QPushButton> // Local #include "gwenview_app_debug.h" #include <lib/gwenviewconfig.h> namespace Gwenview { struct SpotlightModePrivate { SpotlightMode *q = nullptr; QToolButton *mButtonQuit = nullptr; KActionCollection *mActionCollection = nullptr; }; SpotlightMode::SpotlightMode(QWidget *parent, KActionCollection *actionCollection) : QHBoxLayout(parent) , d(new SpotlightModePrivate) { d->q = this; d->mActionCollection = actionCollection; d->mButtonQuit = new QToolButton(); d->mButtonQuit->setIcon(QIcon::fromTheme(QStringLiteral("window-close"))); d->mButtonQuit->setAutoRaise(true); d->mButtonQuit->setVisible(false); addWidget(d->mButtonQuit, 0, Qt::AlignTop | Qt::AlignRight); connect(d->mButtonQuit, &QPushButton::released, this, &SpotlightMode::emitButtonQuitClicked); } SpotlightMode::~SpotlightMode() { delete d; } void SpotlightMode::setVisibleSpotlightModeQuitButton(bool visible) { d->mButtonQuit->setVisible(visible); } void SpotlightMode::emitButtonQuitClicked() { GwenviewConfig::setSpotlightMode(false); d->mActionCollection->action(QStringLiteral("view_toggle_spotlightmode"))->trigger(); } } // namespace #include "moc_spotlightmode.cpp"
1,536
C++
.cpp
48
29.270833
97
0.771894
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,910
alignwithsidebarwidgetaction.cpp
KDE_gwenview/app/alignwithsidebarwidgetaction.cpp
/* This file is part of the KDE project SPDX-FileCopyrightText: 2021 Felix Ernst <fe.a.ernst@gmail.com> SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alignwithsidebarwidgetaction.h" #include <lib/gwenviewconfig.h> #include <KLocalizedString> #include <QApplication> #include <QEvent> #include <QStyle> #include <cmath> AlignWithSideBarWidgetAction::AlignWithSideBarWidgetAction(QObject *parent) : QWidgetAction(parent) { setText(i18nc("@action:inmenu a spacer that aligns toolbar buttons with the sidebar", "Sidebar Alignment Spacer")); } void AlignWithSideBarWidgetAction::setSideBar(QWidget *sideBar) { mSideBar = sideBar; const QList<QWidget *> widgets = createdWidgets(); for (auto widget : widgets) { static_cast<AligningSpacer *>(widget)->setSideBar(sideBar); } } QWidget *AlignWithSideBarWidgetAction::createWidget(QWidget *parent) { auto aligningSpacer = new AligningSpacer(parent); aligningSpacer->setSideBar(mSideBar); return aligningSpacer; } AligningSpacer::AligningSpacer(QWidget *parent) : QWidget{parent} { if ((mToolbar = qobject_cast<QToolBar *>(parent))) { connect(mToolbar, &QToolBar::orientationChanged, this, &AligningSpacer::update); } } void AligningSpacer::setSideBar(QWidget *sideBar) { if (mSideBar) { mSideBar->removeEventFilter(this); } mSideBar = sideBar; if (mSideBar) { mSideBar->installEventFilter(this); } update(); } bool AligningSpacer::eventFilter(QObject * /* watched */, QEvent *event) { switch (event->type()) { case QEvent::Show: case QEvent::Hide: case QEvent::Resize: update(); return false; default: return false; } } void AligningSpacer::moveEvent(QMoveEvent * /* moved */) { update(); } void AligningSpacer::setFollowingSeparatorVisible(bool visible) { if (!mToolbar) { return; } if (mToolbar->orientation() == Qt::Vertical) { visible = true; } const QList<QAction *> toolbarActions = mToolbar->actions(); bool actionForThisSpacerFound = false; // If this is true, the next action in the iteration // is what we are interested in. for (auto action : toolbarActions) { if (actionForThisSpacerFound) { if (visible && mWasSeparatorRemoved) { mToolbar->insertSeparator(action); mWasSeparatorRemoved = false; } else if (!visible && action->isSeparator()) { mToolbar->removeAction(action); mWasSeparatorRemoved = true; } return; } if (mToolbar->widgetForAction(action) == this) { actionForThisSpacerFound = true; } } } void AligningSpacer::update() { const bool oldWasSeparatorRemoved = mWasSeparatorRemoved; if (updateWidth() < 8) { // Because the spacer is so small the separator should be visible to serve its purpose. if (mWasSeparatorRemoved) { setFollowingSeparatorVisible(true); } } else if (mSideBar) { setFollowingSeparatorVisible(mSideBar->isVisible()); } if (oldWasSeparatorRemoved != mWasSeparatorRemoved) { // One more updateWidth() is needed. updateWidth(); } } int AligningSpacer::updateWidth() { if (!mSideBar || (mToolbar && mToolbar->orientation() == Qt::Vertical)) { setFixedWidth(0); return 0; } const auto separatorWidth = static_cast<float>(style()->pixelMetric(QStyle::PM_ToolBarSeparatorExtent, nullptr, this)); int sideBarWidth = mSideBar->geometry().width(); if (sideBarWidth <= 0) { if (!Gwenview::GwenviewConfig::sideBarSplitterSizes().isEmpty()) { sideBarWidth = Gwenview::GwenviewConfig::sideBarSplitterSizes().constFirst(); } else { // We get to this code when gwenview.rc was deleted or when this is the first run. // There doesn't seem to be an easy way to get the width the sideBar is going // to have at this point in time so we set it to some value that leads to // a nice default appearance on the first run. if (QApplication::layoutDirection() != Qt::RightToLeft) { sideBarWidth = x() + separatorWidth * 2; // Leads to a nice default spacing. } else { sideBarWidth = mToolbar->width() - x() + separatorWidth * 2; } mSideBar->resize(sideBarWidth, mSideBar->height()); // Make sure it aligns. } } int newWidth; if (QApplication::layoutDirection() != Qt::RightToLeft) { newWidth = sideBarWidth - mapTo(window(), QPoint(0, 0)).x(); } else { newWidth = sideBarWidth - window()->width() + mapTo(window(), QPoint(width(), 0)).x(); } if (!mWasSeparatorRemoved) { // Make it so a potentially following separator looks aligned with the sidebar. newWidth -= std::ceil(separatorWidth * 0.3); } else { // Make it so removing the separator doesn't change the toolbutton positions. newWidth += std::floor(separatorWidth * 0.7); } // Make sure nothing weird can happen. if (newWidth < 0 || newWidth > sideBarWidth) { newWidth = 0; } setFixedWidth(newWidth); return newWidth; } #include "moc_alignwithsidebarwidgetaction.cpp"
5,417
C++
.cpp
152
29.236842
123
0.653633
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,911
gvpart.cpp
KDE_gwenview/part/gvpart.cpp
/* Gwenview: an image viewer Copyright 2007-2012 Aurélien Gâteau <agateau@kde.org> 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. */ // Qt #include <QAction> #include <QDebug> #include <QFileDialog> #include <QMenu> #include <QUrl> // KF #include <KActionCollection> #include <KIO/FileCopyJob> #include <KIO/JobUiDelegate> #include <KIO/StoredTransferJob> #include <KJobWidgets> #include <KLocalizedString> #include <KPluginFactory> #include <KPropertiesDialog> #include <KStandardAction> // Local #include "../lib/document/document.h" #include "../lib/document/documentfactory.h" #include "../lib/documentview/documentview.h" #include "../lib/documentview/documentviewcontainer.h" #include "../lib/documentview/documentviewcontroller.h" #include "../lib/urlutils.h" #include "gvbrowserextension.h" #include "gvpart.h" namespace Gwenview { K_PLUGIN_CLASS_WITH_JSON(GVPart, "gvpart.json") GVPart::GVPart(QWidget *parentWidget, QObject *parent, const KPluginMetaData &metaData, const QVariantList & /*args*/) : KParts::ReadOnlyPart(parent, metaData) { auto container = new DocumentViewContainer(parentWidget); setWidget(container); mDocumentView = container->createView(); connect(mDocumentView, &DocumentView::captionUpdateRequested, this, &KParts::Part::setWindowCaption); connect(mDocumentView, &DocumentView::completed, this, QOverload<>::of(&KParts::ReadOnlyPart::completed)); connect(mDocumentView, &DocumentView::contextMenuRequested, this, &GVPart::showContextMenu); // Necessary to have zoom actions auto documentViewController = new DocumentViewController(actionCollection(), this); documentViewController->setView(mDocumentView); auto action = new QAction(actionCollection()); action->setText(i18nc("@action", "Properties")); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Return)); connect(action, &QAction::triggered, this, &GVPart::showProperties); actionCollection()->addAction(QStringLiteral("file_show_properties"), action); KStandardAction::saveAs(this, SLOT(saveAs()), actionCollection()); new GVBrowserExtension(this); setXMLFile(QStringLiteral("gvpart.rc"), true); } void GVPart::showProperties() { KPropertiesDialog::showDialog(url(), widget()); } bool GVPart::openUrl(const QUrl &url) { if (!url.isValid()) { return false; } setUrl(url); Document::Ptr doc = DocumentFactory::instance()->load(url); if (arguments().reload()) { doc->reload(); } if (!UrlUtils::urlIsFastLocalFile(url)) { // Keep raw data of remote files to avoid downloading them again in // saveAs() doc->setKeepRawData(true); } DocumentView::Setup setup; setup.zoomToFit = true; mDocumentView->openUrl(url, setup); mDocumentView->setCurrent(true); return true; } inline void addActionToMenu(QMenu *menu, KActionCollection *actionCollection, const char *name) { QAction *action = actionCollection->action(name); if (action) { menu->addAction(action); } } void GVPart::showContextMenu() { QMenu menu(widget()); addActionToMenu(&menu, actionCollection(), "file_save_as"); menu.addSeparator(); addActionToMenu(&menu, actionCollection(), "view_actual_size"); addActionToMenu(&menu, actionCollection(), "view_zoom_to_fit"); addActionToMenu(&menu, actionCollection(), "view_zoom_in"); addActionToMenu(&menu, actionCollection(), "view_zoom_out"); menu.addSeparator(); addActionToMenu(&menu, actionCollection(), "file_show_properties"); menu.exec(QCursor::pos()); } void GVPart::saveAs() { const QUrl srcUrl = url(); const QUrl dstUrl = QFileDialog::getSaveFileUrl(widget(), QString(), srcUrl); if (!dstUrl.isValid()) { return; } KIO::Job *job; Document::Ptr doc = DocumentFactory::instance()->load(srcUrl); const QByteArray rawData = doc->rawData(); if (!rawData.isEmpty()) { job = KIO::storedPut(rawData, dstUrl, -1); } else { job = KIO::file_copy(srcUrl, dstUrl); } connect(job, &KJob::result, this, &GVPart::showJobError); } void GVPart::showJobError(KJob *job) { if (job->error() != 0) { KJobUiDelegate *ui = static_cast<KIO::Job *>(job)->uiDelegate(); if (!ui) { qCritical() << "Saving failed. job->ui() is null."; return; } KJobWidgets::setWindow(job, widget()); ui->showErrorMessage(); } } } // namespace #include "gvpart.moc" #include "moc_gvpart.cpp"
5,171
C++
.cpp
141
32.87234
118
0.719768
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,912
gvbrowserextension.cpp
KDE_gwenview/part/gvbrowserextension.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "gvbrowserextension.h" // Qt // KF #include <KIconLoader> #include <KParts/ReadOnlyPart> // Local #include "../lib/document/documentfactory.h" #include "../lib/print/printhelper.h" namespace Gwenview { struct GVBrowserExtensionPrivate { KParts::ReadOnlyPart *mPart = nullptr; }; GVBrowserExtension::GVBrowserExtension(KParts::ReadOnlyPart *part) : KParts::NavigationExtension(part) , d(new GVBrowserExtensionPrivate) { d->mPart = part; Q_EMIT enableAction("print", true); const QString iconPath = KIconLoader::global()->iconPath(QStringLiteral("image-x-generic"), KIconLoader::SizeSmall); Q_EMIT setIconUrl(QUrl::fromLocalFile(iconPath)); } GVBrowserExtension::~GVBrowserExtension() { delete d; } void GVBrowserExtension::print() { Document::Ptr doc = DocumentFactory::instance()->load(d->mPart->url()); PrintHelper printHelper(d->mPart->widget()); printHelper.print(doc); } } // namespace #include "moc_gvbrowserextension.cpp"
1,813
C++
.cpp
51
33.392157
120
0.777905
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,913
importerconfigdialog.cpp
KDE_gwenview/importer/importerconfigdialog.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "importerconfigdialog.h" // Qt #include <QDateTime> // KF // Local #include "filenameformater.h" #include "importerconfig.h" #include "ui_importerconfigdialog.h" namespace Gwenview { static const QString PREVIEW_FILENAME = QStringLiteral("PICT0012.JPG"); static const QDateTime PREVIEW_DATETIME = QDateTime(QDate(2009, 10, 25), QTime(17, 51, 18)); struct ImporterConfigDialogPrivate : public Ui_ImporterConfigDialog { ImporterConfigDialog *q = nullptr; void setupHelpText() { QString helpText = QStringLiteral("<ul>"); FileNameFormater::HelpMap map = FileNameFormater::helpMap(); FileNameFormater::HelpMap::ConstIterator it = map.constBegin(), end = map.constEnd(); for (; it != end; ++it) { const QString keyword = QLatin1Char('{') + it.key() + QLatin1Char('}'); const QString explanation = it.value().toHtmlEscaped(); const QString link = QStringLiteral("<a href='%1'>%1</a>").arg(keyword); helpText += QLatin1String("<li>") + i18nc("%1 is the importer keyword, %2 is keyword explanation", "%1: %2", link, explanation) + QLatin1String("</li>"); } helpText += QLatin1String("</ul>"); mRenameFormatHelpLabel->setText(helpText); QObject::connect(mRenameFormatHelpLabel, SIGNAL(linkActivated(QString)), q, SLOT(slotHelpLinkActivated(QString))); } }; ImporterConfigDialog::ImporterConfigDialog(QWidget *parent) : KConfigDialog(parent, QStringLiteral("Importer Settings"), ImporterConfig::self()) , d(new ImporterConfigDialogPrivate) { d->q = this; auto widget = new QWidget; d->setupUi(widget); setFaceType(KPageDialog::Plain); addPage(widget, QString()); connect(d->kcfg_AutoRenameFormat, &QLineEdit::textChanged, this, &ImporterConfigDialog::updatePreview); d->setupHelpText(); updatePreview(); } ImporterConfigDialog::~ImporterConfigDialog() { delete d; } void ImporterConfigDialog::slotHelpLinkActivated(const QString &keyword) { d->kcfg_AutoRenameFormat->insert(keyword); } void ImporterConfigDialog::updatePreview() { FileNameFormater formater(d->kcfg_AutoRenameFormat->text()); d->mPreviewOutputLabel->setText(formater.format(QUrl::fromLocalFile('/' + PREVIEW_FILENAME), PREVIEW_DATETIME)); } } // namespace #include "moc_importerconfigdialog.cpp"
3,199
C++
.cpp
76
38.184211
157
0.735977
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,914
documentdirfinder.cpp
KDE_gwenview/importer/documentdirfinder.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "documentdirfinder.h" // Qt // KF #include <KDirLister> #include <KIO/Job> #include <KJobUiDelegate> // Local #include <lib/mimetypeutils.h> namespace Gwenview { struct DocumentDirFinderPrivate { QUrl mRootUrl; KDirLister *mDirLister = nullptr; QUrl mFoundDirUrl; }; DocumentDirFinder::DocumentDirFinder(const QUrl &rootUrl) : d(new DocumentDirFinderPrivate) { d->mRootUrl = rootUrl; d->mDirLister = new KDirLister(this); connect(d->mDirLister, &KCoreDirLister::itemsAdded, this, &DocumentDirFinder::slotItemsAdded); connect(d->mDirLister, SIGNAL(completed()), SLOT(slotCompleted())); connect(d->mDirLister, &KCoreDirLister::jobError, this, [this](KIO::Job *job) { if (job->error() == KIO::Error::ERR_CANNOT_CREATE_WORKER) { Q_EMIT protocollNotSupportedError(job->errorText()); } else { job->uiDelegate()->showErrorMessage(); } }); d->mDirLister->setAutoErrorHandlingEnabled(false); d->mDirLister->openUrl(rootUrl); } DocumentDirFinder::~DocumentDirFinder() { delete d; } void DocumentDirFinder::start() { d->mDirLister->openUrl(d->mRootUrl); } void DocumentDirFinder::slotItemsAdded(const QUrl &dir, const KFileItemList &list) { for (const KFileItem &item : list) { MimeTypeUtils::Kind kind = MimeTypeUtils::fileItemKind(item); switch (kind) { case MimeTypeUtils::KIND_DIR: case MimeTypeUtils::KIND_ARCHIVE: if (d->mFoundDirUrl.isValid()) { // This is the second dir we find, stop now finish(dir, MultipleDirsFound); return; } else { // First dir d->mFoundDirUrl = item.url(); } break; case MimeTypeUtils::KIND_RASTER_IMAGE: case MimeTypeUtils::KIND_SVG_IMAGE: case MimeTypeUtils::KIND_VIDEO: finish(dir, DocumentDirFound); return; case MimeTypeUtils::KIND_UNKNOWN: case MimeTypeUtils::KIND_FILE: break; } } } void DocumentDirFinder::slotCompleted() { if (d->mFoundDirUrl.isValid()) { const QUrl url = d->mFoundDirUrl; d->mFoundDirUrl.clear(); d->mDirLister->openUrl(url); } else { finish(d->mRootUrl, NoDocumentFound); } } void DocumentDirFinder::finish(const QUrl &url, DocumentDirFinder::Status status) { disconnect(d->mDirLister, nullptr, this, nullptr); Q_EMIT done(url, status); deleteLater(); } } // namespace #include "moc_documentdirfinder.cpp"
3,414
C++
.cpp
102
28.22549
98
0.690368
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,915
filenameformater.cpp
KDE_gwenview/importer/filenameformater.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "filenameformater.h" // Qt #include <QDateTime> #include <QFileInfo> #include <QUrl> // KF #include <KLocalizedString> // Local namespace Gwenview { using Dict = QHash<QString, QString>; struct FileNameFormaterPrivate { QString mFormat; }; FileNameFormater::FileNameFormater(const QString &format) : d(new FileNameFormaterPrivate) { d->mFormat = format; } FileNameFormater::~FileNameFormater() { delete d; } QString FileNameFormater::format(const QUrl &url, const QDateTime &dateTime) { QFileInfo info(url.fileName()); // Keep in sync with helpMap() Dict dict; dict[QStringLiteral("date")] = dateTime.toString(QStringLiteral("yyyy-MM-dd")); dict[QStringLiteral("time")] = dateTime.toString(QStringLiteral("HH-mm-ss")); dict[QStringLiteral("ext")] = info.suffix(); dict[QStringLiteral("ext.lower")] = info.suffix().toLower(); dict[QStringLiteral("name")] = info.completeBaseName(); dict[QStringLiteral("name.lower")] = info.completeBaseName().toLower(); QString name; const int length = d->mFormat.length(); for (int pos = 0; pos < length; ++pos) { QChar ch = d->mFormat[pos]; if (ch == QLatin1Char('{')) { if (pos == length - 1) { // We are at the end, ignore this break; } if (d->mFormat[pos + 1] == QLatin1Char('{')) { // This is an escaped '{', skip one name += '{'; ++pos; continue; } int end = d->mFormat.indexOf('}', pos + 1); if (end == -1) { // No '}' found, stop here return name; } // Replace keyword with its value const QString keyword = d->mFormat.mid(pos + 1, end - pos - 1); name += dict.value(keyword); pos = end; } else { name += ch; } } return name; } FileNameFormater::HelpMap FileNameFormater::helpMap() { // Keep in sync with dict in format() static HelpMap map; if (map.isEmpty()) { map[QStringLiteral("date")] = i18n("Shooting date"); map[QStringLiteral("time")] = i18n("Shooting time"); map[QStringLiteral("ext")] = i18n("Original extension"); map[QStringLiteral("ext.lower")] = i18n("Original extension, in lower case"); map[QStringLiteral("name")] = i18n("Original filename"); map[QStringLiteral("name.lower")] = i18n("Original filename, in lower case"); } return map; } } // namespace
3,400
C++
.cpp
96
29.604167
85
0.644857
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,916
thumbnailpage.cpp
KDE_gwenview/importer/thumbnailpage.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "thumbnailpage.h" // Qt #include <QDesktopServices> #include <QDir> #include <QGraphicsOpacityEffect> #include <QIcon> #include <QProcess> #include <QPushButton> #include <QTreeView> // KF #include <KAcceleratorManager> #include <KDirLister> #include <KDirModel> #include <KIO/DesktopExecParser> #include <KIO/StatJob> #include <KIconLoader> #include <KJobWidgets> #include <KMessageBox> #include <KModelIndexProxyMapper> #include <kio/global.h> // Local #include <documentdirfinder.h> #include <importerconfigdialog.h> #include <lib/archiveutils.h> #include <lib/gwenviewconfig.h> #include <lib/kindproxymodel.h> #include <lib/recursivedirmodel.h> #include <lib/semanticinfo/sorteddirmodel.h> #include <lib/thumbnailprovider/thumbnailprovider.h> #include <lib/thumbnailview/abstractthumbnailviewhelper.h> #include <lib/thumbnailview/previewitemdelegate.h> #include <serializedurlmap.h> #include <ui_thumbnailpage.h> namespace Gwenview { static const int DEFAULT_THUMBNAIL_SIZE = 128; static const qreal DEFAULT_THUMBNAIL_ASPECT_RATIO = 3. / 2.; static const char *URL_FOR_BASE_URL_GROUP = "UrlForBaseUrl"; class ImporterThumbnailViewHelper : public AbstractThumbnailViewHelper { public: ImporterThumbnailViewHelper(QObject *parent) : AbstractThumbnailViewHelper(parent) { } void showContextMenu(QWidget *) override { } void showMenuForUrlDroppedOnViewport(QWidget *, const QList<QUrl> &) override { } void showMenuForUrlDroppedOnDir(QWidget *, const QList<QUrl> &, const QUrl &) override { } }; inline KFileItem itemForIndex(const QModelIndex &index) { return index.data(KDirModel::FileItemRole).value<KFileItem>(); } struct ThumbnailPagePrivate : public Ui_ThumbnailPage { ThumbnailPage *q = nullptr; SerializedUrlMap mUrlMap; QIcon mSrcBaseIcon; QString mSrcBaseName; QUrl mSrcBaseUrl; QUrl mSrcUrl; KModelIndexProxyMapper *mSrcUrlModelProxyMapper = nullptr; RecursiveDirModel *mRecursiveDirModel = nullptr; QAbstractItemModel *mFinalModel = nullptr; ThumbnailProvider mThumbnailProvider; // Placeholder view QLabel *mPlaceHolderIconLabel = nullptr; QLabel *mPlaceHolderLabel = nullptr; QLabel *mRequireRestartLabel = nullptr; QPushButton *mInstallProtocolSupportButton = nullptr; QVBoxLayout *mPlaceHolderLayout = nullptr; QWidget *mPlaceHolderWidget = nullptr; // To avoid clipping in gridLayout QPushButton *mImportSelectedButton; QPushButton *mImportAllButton; QList<QUrl> mUrlList; void setupDirModel() { mRecursiveDirModel = new RecursiveDirModel(q); auto kindProxyModel = new KindProxyModel(q); kindProxyModel->setKindFilter(MimeTypeUtils::KIND_RASTER_IMAGE | MimeTypeUtils::KIND_SVG_IMAGE | MimeTypeUtils::KIND_VIDEO); kindProxyModel->setSourceModel(mRecursiveDirModel); auto sortModel = new QSortFilterProxyModel(q); sortModel->setDynamicSortFilter(true); sortModel->setSourceModel(kindProxyModel); sortModel->sort(0); mFinalModel = sortModel; QObject::connect(mFinalModel, &QAbstractItemModel::rowsInserted, q, &ThumbnailPage::updateImportButtons); QObject::connect(mFinalModel, &QAbstractItemModel::rowsRemoved, q, &ThumbnailPage::updateImportButtons); QObject::connect(mFinalModel, &QAbstractItemModel::modelReset, q, &ThumbnailPage::updateImportButtons); } void setupIcons() { const int size = KIconLoader::SizeHuge; mSrcIconLabel->setPixmap(QIcon::fromTheme(QStringLiteral("camera-photo")).pixmap(size)); mDstIconLabel->setPixmap(QIcon::fromTheme(QStringLiteral("computer")).pixmap(size)); } void setupSrcUrlWidgets() { mSrcUrlModelProxyMapper = nullptr; QObject::connect(mSrcUrlButton, &QAbstractButton::clicked, q, &ThumbnailPage::setupSrcUrlTreeView); QObject::connect(mSrcUrlButton, &QAbstractButton::clicked, q, &ThumbnailPage::toggleSrcUrlTreeView); mSrcUrlTreeView->hide(); KAcceleratorManager::setNoAccel(mSrcUrlButton); } void setupDstUrlRequester() { mDstUrlRequester->setMode(KFile::Directory | KFile::LocalOnly); } void setupThumbnailView() { mThumbnailView->setModel(mFinalModel); mThumbnailView->setSelectionMode(QAbstractItemView::ExtendedSelection); mThumbnailView->setThumbnailViewHelper(new ImporterThumbnailViewHelper(q)); auto delegate = new PreviewItemDelegate(mThumbnailView); delegate->setThumbnailDetails(PreviewItemDelegate::FileNameDetail); PreviewItemDelegate::ContextBarActions actions; switch (GwenviewConfig::thumbnailActions()) { case ThumbnailActions::None: actions = PreviewItemDelegate::NoAction; break; case ThumbnailActions::ShowSelectionButtonOnly: case ThumbnailActions::AllButtons: actions = PreviewItemDelegate::SelectionAction; break; } delegate->setContextBarActions(actions); mThumbnailView->setItemDelegate(delegate); QObject::connect(mSlider, &ZoomSlider::valueChanged, mThumbnailView, &ThumbnailView::setThumbnailWidth); QObject::connect(mThumbnailView, &ThumbnailView::thumbnailWidthChanged, mSlider, &ZoomSlider::setValue); int thumbnailSize = DEFAULT_THUMBNAIL_SIZE; mSlider->setValue(thumbnailSize); mSlider->updateToolTip(); mThumbnailView->setThumbnailAspectRatio(DEFAULT_THUMBNAIL_ASPECT_RATIO); mThumbnailView->setThumbnailWidth(thumbnailSize); mThumbnailView->setThumbnailProvider(&mThumbnailProvider); QObject::connect(mThumbnailView->selectionModel(), &QItemSelectionModel::selectionChanged, q, &ThumbnailPage::updateImportButtons); } void setupPlaceHolderView(const QString &errorText) { mPlaceHolderWidget = new QWidget(q); // Use QSizePolicy::MinimumExpanding to avoid clipping mPlaceHolderWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); // Icon mPlaceHolderIconLabel = new QLabel(mPlaceHolderWidget); const QSize iconSize(KIconLoader::SizeHuge, KIconLoader::SizeHuge); mPlaceHolderIconLabel->setMinimumSize(iconSize); mPlaceHolderIconLabel->setPixmap(QIcon::fromTheme(QStringLiteral("edit-none")).pixmap(iconSize)); auto iconEffect = new QGraphicsOpacityEffect(mPlaceHolderIconLabel); iconEffect->setOpacity(0.5); mPlaceHolderIconLabel->setGraphicsEffect(iconEffect); // Label: see dolphin/src/views/dolphinview.cpp const QSizePolicy labelSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred, QSizePolicy::Label); mPlaceHolderLabel = new QLabel(mPlaceHolderWidget); mPlaceHolderLabel->setSizePolicy(labelSizePolicy); QFont placeholderLabelFont; // To match the size of a level 2 Heading/KTitleWidget placeholderLabelFont.setPointSize(qRound(placeholderLabelFont.pointSize() * 1.3)); mPlaceHolderLabel->setFont(placeholderLabelFont); mPlaceHolderLabel->setTextInteractionFlags(Qt::NoTextInteraction); mPlaceHolderLabel->setWordWrap(true); mPlaceHolderLabel->setAlignment(Qt::AlignCenter); // Match opacity of QML placeholder label component auto effect = new QGraphicsOpacityEffect(mPlaceHolderLabel); effect->setOpacity(0.5); mPlaceHolderLabel->setGraphicsEffect(effect); // Show more friendly text when the protocol is "camera" (which is the usual case) const QString scheme(mSrcBaseUrl.scheme()); // Truncate long protocol name const QString truncatedScheme( scheme.length() <= 10 ? scheme : QStringView(scheme).left(5).toString() + QStringLiteral("…") + QStringView(scheme).right(5).toString()); // clang-format off if (scheme == QLatin1String("camera")) { mPlaceHolderLabel->setText(i18nc("@info above install button when Kamera is not installed", "Support for your camera is not installed.")); } else if (!errorText.isEmpty()) { mPlaceHolderLabel->setText(i18nc("@info above install button, %1 protocol name %2 error text from KIO", "The protocol support library for \"%1\" is not installed. Error: %2", truncatedScheme, errorText)); } else { mPlaceHolderLabel->setText(i18nc("@info above install button, %1 protocol name", "The protocol support library for \"%1\" is not installed.", truncatedScheme)); } // Label to guide the user to restart the wizard after installing the protocol support library mRequireRestartLabel = new QLabel(mPlaceHolderWidget); mRequireRestartLabel->setSizePolicy(labelSizePolicy); mRequireRestartLabel->setTextInteractionFlags(Qt::NoTextInteraction); mRequireRestartLabel->setWordWrap(true); mRequireRestartLabel->setAlignment(Qt::AlignCenter); auto effect2 = new QGraphicsOpacityEffect(mRequireRestartLabel); effect2->setOpacity(0.5); mRequireRestartLabel->setGraphicsEffect(effect2); mRequireRestartLabel->setText(i18nc("@info:usagetip above install button", "After finishing the installation process, restart this Importer to continue.")); // Button // Check if Discover is installed q->mDiscoverAvailable = !QStandardPaths::findExecutable("plasma-discover").isEmpty(); QIcon buttonIcon(q->mDiscoverAvailable ? QIcon::fromTheme("plasmadiscover") : QIcon::fromTheme("install")); QString buttonText, whatsThisText; QString tooltipText(i18nc("@info:tooltip for a button, %1 protocol name", "Launch Discover to install the protocol support library for \"%1\"", scheme)); if (scheme == QLatin1String("camera")) { buttonText = i18nc("@action:button", "Install Support for this Camera…"); whatsThisText = i18nc("@info:whatsthis for a button when Kamera is not installed", "You need Kamera installed on your system to read from the camera. Click here to launch Discover to install Kamera to enable protocol support for \"camera:/\" on your system."); } else { if (q->mDiscoverAvailable) { buttonText = i18nc("@action:button %1 protocol name", "Install Protocol Support for \"%1\"…", truncatedScheme); whatsThisText = i18nc("@info:whatsthis for a button, %1 protocol name", "Click here to launch Discover to install the missing protocol support library to enable the protocol support for \"%1:/\" on your system.", scheme); } else { // If Discover is not found on the system, guide the user to search the web. buttonIcon = QIcon::fromTheme("internet-web-browser"); buttonText = i18nc("@action:button %1 protocol name", "Search the Web for How to Install Protocol Support for \"%1\"…", truncatedScheme); tooltipText.clear(); } } mInstallProtocolSupportButton = new QPushButton(buttonIcon, buttonText, mPlaceHolderWidget); mInstallProtocolSupportButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); mInstallProtocolSupportButton->setToolTip(tooltipText); mInstallProtocolSupportButton->setWhatsThis(whatsThisText); // Highlight the button so the user can notice it more easily. mInstallProtocolSupportButton->setDefault(true); mInstallProtocolSupportButton->setFocus(); // Button action if (q->mDiscoverAvailable || scheme == QLatin1String("camera")) { QObject::connect(mInstallProtocolSupportButton, &QAbstractButton::clicked, q, &ThumbnailPage::installProtocolSupport); } else { QObject::connect(mInstallProtocolSupportButton, &QAbstractButton::clicked, q, [scheme]() { const QString searchKeyword(QUrl::toPercentEncoding(i18nc("@info this text will be used as a search term in an online search engine, %1 protocol name", "How to install protocol support for \"%1\" on Linux", scheme)).constData()); const QString searchEngineURL(i18nc("search engine URL, %1 search keyword, and translators can replace duckduckgo with other search engines", "https://duckduckgo.com/?q=%1", searchKeyword)); QDesktopServices::openUrl(QUrl(searchEngineURL)); }); } // clang-format on // VBoxLayout mPlaceHolderLayout = new QVBoxLayout(mPlaceHolderWidget); mPlaceHolderLayout->addStretch(); mPlaceHolderLayout->addWidget(mPlaceHolderIconLabel, 0, Qt::AlignCenter); mPlaceHolderLayout->addWidget(mPlaceHolderLabel); mPlaceHolderLayout->addWidget(mRequireRestartLabel); mPlaceHolderLayout->addWidget(mInstallProtocolSupportButton, 0, Qt::AlignCenter); // Do not stretch the button mPlaceHolderLayout->addStretch(); // Hide other controls gridLayout->removeItem(verticalLayout); gridLayout->removeItem(verticalLayout_2); gridLayout->removeWidget(label); gridLayout->removeWidget(label_2); gridLayout->removeWidget(widget); gridLayout->removeWidget(widget); gridLayout->removeWidget(mDstUrlRequester); mDstIconLabel->hide(); mSrcIconLabel->hide(); label->hide(); label_2->hide(); mDstUrlRequester->hide(); widget->hide(); widget_2->hide(); mConfigureButton->hide(); mImportSelectedButton->hide(); mImportAllButton->hide(); gridLayout->addWidget(mPlaceHolderWidget, 0, 0, 1, 0); } void setupButtonBox() { QObject::connect(mConfigureButton, &QAbstractButton::clicked, q, &ThumbnailPage::showConfigDialog); mImportSelectedButton = mButtonBox->addButton(i18n("Import Selected"), QDialogButtonBox::AcceptRole); QObject::connect(mImportSelectedButton, &QAbstractButton::clicked, q, &ThumbnailPage::slotImportSelected); mImportAllButton = mButtonBox->addButton(i18n("Import All"), QDialogButtonBox::AcceptRole); QObject::connect(mImportAllButton, &QAbstractButton::clicked, q, &ThumbnailPage::slotImportAll); QObject::connect(mButtonBox, &QDialogButtonBox::rejected, q, &ThumbnailPage::rejected); } QUrl urlForBaseUrl() const { QUrl url = mUrlMap.value(mSrcBaseUrl); if (!url.isValid()) { return {}; } KIO::StatJob *job = KIO::stat(url); KJobWidgets::setWindow(job, q); if (!job->exec()) { return {}; } KFileItem item(job->statResult(), url, true /* delayedMimeTypes */); return item.isDir() ? url : QUrl(); } void rememberUrl(const QUrl &url) { mUrlMap.insert(mSrcBaseUrl, url); } }; ThumbnailPage::ThumbnailPage() : d(new ThumbnailPagePrivate) { d->q = this; d->mUrlMap.setConfigGroup(KConfigGroup(KSharedConfig::openConfig(), URL_FOR_BASE_URL_GROUP)); d->setupUi(this); d->setupIcons(); d->setupDirModel(); d->setupSrcUrlWidgets(); d->setupDstUrlRequester(); d->setupThumbnailView(); d->setupButtonBox(); updateImportButtons(); } ThumbnailPage::~ThumbnailPage() { delete d; } void ThumbnailPage::setSourceUrl(const QUrl &srcBaseUrl, const QString &iconName, const QString &name) { d->mSrcBaseIcon = QIcon::fromTheme(iconName); d->mSrcBaseName = name; const int size = KIconLoader::SizeHuge; d->mSrcIconLabel->setPixmap(d->mSrcBaseIcon.pixmap(size)); d->mSrcBaseUrl = srcBaseUrl; if (!d->mSrcBaseUrl.path().endsWith('/')) { d->mSrcBaseUrl.setPath(d->mSrcBaseUrl.path() + '/'); } QUrl url = d->urlForBaseUrl(); if (url.isValid()) { openUrl(url); } else { auto finder = new DocumentDirFinder(srcBaseUrl); connect(finder, &DocumentDirFinder::done, this, &ThumbnailPage::slotDocumentDirFinderDone); connect(finder, &DocumentDirFinder::protocollNotSupportedError, this, [this](const QString &errorText) { d->setupPlaceHolderView(errorText); }); finder->start(); } } void ThumbnailPage::slotDocumentDirFinderDone(const QUrl &url, DocumentDirFinder::Status /*status*/) { d->rememberUrl(url); openUrl(url); } void ThumbnailPage::openUrl(const QUrl &url) { d->mSrcUrl = url; QString path = QDir(d->mSrcBaseUrl.path()).relativeFilePath(d->mSrcUrl.path()); QString text; if (path.isEmpty() || path == QLatin1String(".")) { text = d->mSrcBaseName; } else { path = QUrl::fromPercentEncoding(path.toUtf8()); path.replace('/', QString::fromUtf8(" › ")); text = QString::fromUtf8("%1 › %2").arg(d->mSrcBaseName, path); } d->mSrcUrlButton->setText(text); d->mRecursiveDirModel->setUrl(url); } QList<QUrl> ThumbnailPage::urlList() const { return d->mUrlList; } void ThumbnailPage::setDestinationUrl(const QUrl &url) { d->mDstUrlRequester->setUrl(url); } QUrl ThumbnailPage::destinationUrl() const { return d->mDstUrlRequester->url(); } void ThumbnailPage::slotImportSelected() { importList(d->mThumbnailView->selectionModel()->selectedIndexes()); } void ThumbnailPage::slotImportAll() { QModelIndexList list; QAbstractItemModel *model = d->mThumbnailView->model(); for (int row = model->rowCount() - 1; row >= 0; --row) { list << model->index(row, 0); } importList(list); } void ThumbnailPage::importList(const QModelIndexList &list) { d->mUrlList.clear(); for (const QModelIndex &index : list) { KFileItem item = itemForIndex(index); if (!ArchiveUtils::fileItemIsDirOrArchive(item)) { d->mUrlList << item.url(); } // FIXME: Handle dirs (do we want to import recursively?) } Q_EMIT importRequested(); } void ThumbnailPage::updateImportButtons() { d->mImportSelectedButton->setEnabled(d->mThumbnailView->selectionModel()->hasSelection()); d->mImportAllButton->setEnabled(d->mThumbnailView->model()->rowCount(QModelIndex()) > 0); } void ThumbnailPage::showConfigDialog() { auto dialog = new ImporterConfigDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModal(true); dialog->show(); } void ThumbnailPage::installProtocolSupport() const { const QString scheme(d->mSrcBaseUrl.scheme()); // clang-format off if (scheme == QLatin1String("camera")) { const QUrl kameraInstallUrl("appstream://org.kde.kamera"); if (KIO::DesktopExecParser::hasSchemeHandler(kameraInstallUrl)) { QDesktopServices::openUrl(kameraInstallUrl); } else { KMessageBox::error(d->widget, xi18nc("@info when failing to open the appstream URL", "Opening Discover failed.<nl/>Please check if Discover is installed on your system, or use your system's package manager to install \"Kamera\" package.")); } } else if (!QProcess::startDetached(QStringLiteral("plasma-discover"), QStringList({"--search", scheme}))) { // For other protocols, search for the protocol name in Discover. KMessageBox::error(d->widget, xi18nc("@info when failing to launch plasma-discover, %1 protocol name", "Opening Discover failed.<nl/>Please check if Discover is installed on your system, or use your system's package manager to install the protocol support library for \"%1\".", scheme)); } // clang-format on } /** * This model allows only the url passed in the constructor to appear at the root * level. This makes it possible to select the url, but not its siblings. * It also provides custom role values for the root item. */ class OnlyBaseUrlProxyModel : public QSortFilterProxyModel { public: OnlyBaseUrlProxyModel(const QUrl &url, const QIcon &icon, const QString &name, QObject *parent) : QSortFilterProxyModel(parent) , mUrl(url) , mIcon(icon) , mName(name) { } bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override { if (sourceParent.isValid()) { return true; } QModelIndex index = sourceModel()->index(sourceRow, 0); KFileItem item = itemForIndex(index); return item.url().matches(mUrl, QUrl::StripTrailingSlash); } QVariant data(const QModelIndex &index, int role) const override { if (index.parent().isValid()) { return QSortFilterProxyModel::data(index, role); } switch (role) { case Qt::DisplayRole: return mName; case Qt::DecorationRole: return mIcon; case Qt::ToolTipRole: return mUrl.toDisplayString(QUrl::PreferLocalFile); default: return QSortFilterProxyModel::data(index, role); } } private: QUrl mUrl; QIcon mIcon; QString mName; }; void ThumbnailPage::setupSrcUrlTreeView() { if (d->mSrcUrlTreeView->model()) { // Already initialized return; } auto dirModel = new KDirModel(this); dirModel->dirLister()->setDirOnlyMode(true); dirModel->dirLister()->openUrl(KIO::upUrl(d->mSrcBaseUrl)); auto onlyBaseUrlModel = new OnlyBaseUrlProxyModel(d->mSrcBaseUrl, d->mSrcBaseIcon, d->mSrcBaseName, this); onlyBaseUrlModel->setSourceModel(dirModel); auto sortModel = new QSortFilterProxyModel(this); sortModel->setDynamicSortFilter(true); sortModel->setSourceModel(onlyBaseUrlModel); sortModel->sort(0); d->mSrcUrlModelProxyMapper = new KModelIndexProxyMapper(dirModel, sortModel, this); d->mSrcUrlTreeView->setModel(sortModel); for (int i = 1; i < dirModel->columnCount(); ++i) { d->mSrcUrlTreeView->hideColumn(i); } connect(d->mSrcUrlTreeView, &QAbstractItemView::activated, this, &ThumbnailPage::openUrlFromIndex); connect(d->mSrcUrlTreeView, &QAbstractItemView::clicked, this, &ThumbnailPage::openUrlFromIndex); dirModel->expandToUrl(d->mSrcUrl); connect(dirModel, &KDirModel::expand, this, &ThumbnailPage::slotSrcUrlModelExpand); } void ThumbnailPage::slotSrcUrlModelExpand(const QModelIndex &index) { QModelIndex viewIndex = d->mSrcUrlModelProxyMapper->mapLeftToRight(index); d->mSrcUrlTreeView->expand(viewIndex); KFileItem item = itemForIndex(index); if (item.url() == d->mSrcUrl) { d->mSrcUrlTreeView->selectionModel()->select(viewIndex, QItemSelectionModel::ClearAndSelect); } } void ThumbnailPage::toggleSrcUrlTreeView() { d->mSrcUrlTreeView->setVisible(!d->mSrcUrlTreeView->isVisible()); } void ThumbnailPage::openUrlFromIndex(const QModelIndex &index) { KFileItem item = itemForIndex(index); if (item.isNull()) { return; } QUrl url = item.url(); d->rememberUrl(url); openUrl(url); } } // namespace #include "moc_thumbnailpage.cpp"
23,789
C++
.cpp
525
38.982857
295
0.710876
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,917
progresspage.cpp
KDE_gwenview/importer/progresspage.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "progresspage.h" // Local #include "importer.h" #include <ui_progresspage.h> namespace Gwenview { struct ProgressPagePrivate : public Ui_ProgressPage { ProgressPage *q = nullptr; Importer *mImporter = nullptr; }; ProgressPage::ProgressPage(Importer *importer) : d(new ProgressPagePrivate) { d->q = this; d->mImporter = importer; d->setupUi(this); connect(d->mImporter, &Importer::progressChanged, d->mProgressBar, &QProgressBar::setValue); connect(d->mImporter, &Importer::maximumChanged, d->mProgressBar, &QProgressBar::setMaximum); } ProgressPage::~ProgressPage() { delete d; } } // namespace #include "moc_progresspage.cpp"
1,502
C++
.cpp
42
33.595238
97
0.777471
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,918
importer.cpp
KDE_gwenview/importer/importer.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "importer.h" // Qt #include <QDateTime> #include <QTemporaryDir> #include <QUrl> // KF #include <KFileItem> #include <KIO/CopyJob> #include <KIO/DeleteJob> #include <KIO/JobUiDelegate> #include <KIO/MkpathJob> #include <KIO/SimpleJob> #include <KJobWidgets> #include <KLocalizedString> // stdc++ #include <memory> // Local #include "gwenview_importer_debug.h" #include <QDir> #include <filenameformater.h> #include <fileutils.h> #include <lib/timeutils.h> #include <lib/urlutils.h> namespace Gwenview { struct ImporterPrivate { Importer *q = nullptr; QWidget *mAuthWindow = nullptr; std::unique_ptr<FileNameFormater> mFileNameFormater; QUrl mTempImportDirUrl; QTemporaryDir *mTempImportDir = nullptr; QUrl mDestinationDirUrl; /* @defgroup reset Should be reset in start() * @{ */ QList<QUrl> mUrlList; QList<QUrl> mImportedUrlList; QList<QUrl> mSkippedUrlList; QList<QUrl> mFailedUrlList; QList<QUrl> mFailedSubFolderList; int mRenamedCount; int mProgress; int mJobProgress; /* @} */ QUrl mCurrentUrl; bool createImportDir(const QUrl &url) { KIO::Job *job = KIO::mkpath(url, QUrl(), KIO::HideProgressInfo); KJobWidgets::setWindow(job, mAuthWindow); if (!job->exec()) { Q_EMIT q->error(i18n("Could not create destination folder.")); return false; } // Check if local and fast url. The check for fast url is needed because // otherwise the retrieved date will not be correct: see implementation // of TimeUtils::dateTimeForFileItem if (UrlUtils::urlIsFastLocalFile(url)) { QString tempDirPath = url.toLocalFile() + "/.gwenview_importer-XXXXXX"; mTempImportDir = new QTemporaryDir(tempDirPath); } else { mTempImportDir = new QTemporaryDir(); } if (!mTempImportDir->isValid()) { Q_EMIT q->error(i18n("Could not create temporary upload folder.")); return false; } mTempImportDirUrl = QUrl::fromLocalFile(mTempImportDir->path() + QLatin1Char('/')); if (!mTempImportDirUrl.isValid()) { Q_EMIT q->error(i18n("Could not create temporary upload folder.")); return false; } return true; } void importNext() { if (mUrlList.empty()) { q->finalizeImport(); return; } mCurrentUrl = mUrlList.takeFirst(); QUrl dst = mTempImportDirUrl; dst.setPath(dst.path() + mCurrentUrl.fileName()); KIO::Job *job = KIO::copy(mCurrentUrl, dst, KIO::HideProgressInfo | KIO::Overwrite); KJobWidgets::setWindow(job, mAuthWindow); QObject::connect(job, &KJob::result, q, &Importer::slotCopyDone); QObject::connect(job, SIGNAL(percent(KJob *, ulong)), q, SLOT(slotPercent(KJob *, ulong))); } void renameImportedUrl(const QUrl &src) { QUrl dst = mDestinationDirUrl; QString fileName; if (mFileNameFormater.get()) { KFileItem item(src); item.setDelayedMimeTypes(true); // Get the document time, but do not cache the result because the // 'src' url is temporary: if we import "foo/image.jpg" and // "bar/image.jpg", both images will be temporarily saved in the // 'src' url. const QDateTime dateTime = TimeUtils::dateTimeForFileItem(item, TimeUtils::SkipCache); fileName = mFileNameFormater->format(src, dateTime); } else { fileName = src.fileName(); } dst.setPath(dst.path() + QLatin1Char('/') + fileName); FileUtils::RenameResult result; // Create additional subfolders if needed (e.g. when extra slashes in FileNameFormater) QUrl subFolder = dst.adjusted(QUrl::RemoveFilename); KIO::Job *job = KIO::mkpath(subFolder, QUrl(), KIO::HideProgressInfo); KJobWidgets::setWindow(job, mAuthWindow); if (!job->exec()) { // if subfolder creation fails qCWarning(GWENVIEW_IMPORTER_LOG) << "Could not create subfolder:" << subFolder; if (!mFailedSubFolderList.contains(subFolder)) { mFailedSubFolderList << subFolder; } result = FileUtils::RenameFailed; } else { // if subfolder creation succeeds result = FileUtils::rename(src, dst, mAuthWindow); } switch (result) { case FileUtils::RenamedOK: mImportedUrlList << mCurrentUrl; break; case FileUtils::RenamedUnderNewName: mRenamedCount++; mImportedUrlList << mCurrentUrl; break; case FileUtils::Skipped: mSkippedUrlList << mCurrentUrl; break; case FileUtils::RenameFailed: mFailedUrlList << mCurrentUrl; qCWarning(GWENVIEW_IMPORTER_LOG) << "Rename failed for" << mCurrentUrl; } q->advance(); importNext(); } }; Importer::Importer(QWidget *parent) : QObject(parent) , d(new ImporterPrivate) { d->q = this; d->mAuthWindow = parent; } Importer::~Importer() { delete d; } void Importer::setAutoRenameFormat(const QString &format) { if (format.isEmpty()) { d->mFileNameFormater.reset(nullptr); } else { d->mFileNameFormater = std::make_unique<FileNameFormater>(format); } } void Importer::start(const QList<QUrl> &list, const QUrl &destination) { d->mDestinationDirUrl = destination; d->mUrlList = list; d->mImportedUrlList.clear(); d->mSkippedUrlList.clear(); d->mFailedUrlList.clear(); d->mFailedSubFolderList.clear(); d->mRenamedCount = 0; d->mProgress = 0; d->mJobProgress = 0; emitProgressChanged(); Q_EMIT maximumChanged(d->mUrlList.count() * 100); if (!d->createImportDir(destination)) { qCWarning(GWENVIEW_IMPORTER_LOG) << "Could not create import dir"; return; } d->importNext(); } void Importer::slotCopyDone(KJob *_job) { auto job = static_cast<KIO::CopyJob *>(_job); const QUrl url = job->destUrl(); if (job->error()) { // Add document to failed url list and proceed with next one d->mFailedUrlList << d->mCurrentUrl; advance(); d->importNext(); return; } d->renameImportedUrl(url); } void Importer::finalizeImport() { delete d->mTempImportDir; Q_EMIT importFinished(); } void Importer::advance() { ++d->mProgress; d->mJobProgress = 0; emitProgressChanged(); } void Importer::slotPercent(KJob *, unsigned long percent) { d->mJobProgress = percent; emitProgressChanged(); } void Importer::emitProgressChanged() { Q_EMIT progressChanged(d->mProgress * 100 + d->mJobProgress); } QList<QUrl> Importer::importedUrlList() const { return d->mImportedUrlList; } QList<QUrl> Importer::skippedUrlList() const { return d->mSkippedUrlList; } QList<QUrl> Importer::failedUrlList() const { return d->mFailedUrlList; } QList<QUrl> Importer::failedSubFolderList() const { return d->mFailedSubFolderList; } int Importer::renamedCount() const { return d->mRenamedCount; } } // namespace #include "moc_importer.cpp"
8,114
C++
.cpp
246
27.178862
99
0.663984
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,919
main.cpp
KDE_gwenview/importer/main.cpp
/* Gwenview: an image viewer Copyright 2000-2009 Aurélien Gâteau <agateau@kde.org> 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. */ // Qt #include <QApplication> #include <QCommandLineParser> #include <QDir> #include <QScopedPointer> #include <QUrl> // KF #include <KAboutData> #include <KCrash> #include <KLocalizedString> // Local #include "gwenview_importer_debug.h" #include "importdialog.h" #include <lib/about.h> int main(int argc, char *argv[]) { KLocalizedString::setApplicationDomain("gwenview"); QApplication app(argc, argv); QScopedPointer<KAboutData> aboutData(Gwenview::createAboutData(QStringLiteral("gwenview_importer"), /* component name */ i18n("Gwenview Importer") /* programName */ )); aboutData->setShortDescription(i18n("Photo Importer")); KAboutData::setApplicationData(*aboutData); KCrash::initialize(); QCommandLineParser parser; aboutData.data()->setupCommandLine(&parser); parser.addOption( QCommandLineOption(QStringLiteral("udi"), i18n("The device UDI, used to retrieve information about the device (name, icon...)"), i18n("Device UDI"))); parser.addPositionalArgument(QStringLiteral("folder"), i18n("Source folder")); parser.process(app); aboutData.data()->processCommandLine(&parser); if (parser.positionalArguments().isEmpty()) { qCWarning(GWENVIEW_IMPORTER_LOG) << i18n("Missing required source folder argument."); parser.showHelp(); } if (parser.positionalArguments().count() > 1) { qCWarning(GWENVIEW_IMPORTER_LOG) << i18n("Too many arguments."); parser.showHelp(); } const QString urlString = parser.positionalArguments().constFirst(); const QUrl url = QUrl::fromUserInput(urlString, QDir::currentPath(), QUrl::AssumeLocalFile); if (!url.isValid()) { qCCritical(GWENVIEW_IMPORTER_LOG) << i18n("Invalid source folder."); return 1; } const QString deviceUdi = parser.isSet(QStringLiteral("udi")) ? parser.value(QStringLiteral("udi")) : QString(); auto dialog = new Gwenview::ImportDialog(); dialog->show(); QMetaObject::invokeMethod( dialog, [dialog, url, deviceUdi]() { dialog->setSourceUrl(url, deviceUdi); }, Qt::QueuedConnection); return app.exec(); }
3,071
C++
.cpp
71
37.352113
158
0.697924
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,920
importdialog.cpp
KDE_gwenview/importer/importdialog.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "importdialog.h" // Qt #include <QApplication> #include <QDate> #include <QStackedWidget> #include <QStandardPaths> // KF #include <KIO/ApplicationLauncherJob> #include <KIO/DeleteJob> #include <KIO/JobUiDelegate> #include <KIO/JobUiDelegateFactory> #include <KLocalizedString> #include <KMessageBox> #include <KProtocolInfo> #include <KService> #include <KStandardGuiItem> #include <Solid/Device> #include <kwidgetsaddons_version.h> // Local #include "dialogpage.h" #include "gwenview_importer_debug.h" #include "importer.h" #include "importerconfig.h" #include "progresspage.h" #include "thumbnailpage.h" namespace Gwenview { class ImportDialogPrivate { public: ImportDialog *q = nullptr; QStackedWidget *mCentralWidget = nullptr; ThumbnailPage *mThumbnailPage = nullptr; ProgressPage *mProgressPage = nullptr; DialogPage *mDialogPage = nullptr; Importer *mImporter = nullptr; void checkForFailedUrls() { // First check for errors on file imports or subfolder creation const QList<QUrl> failedUrls = mImporter->failedUrlList(); const QList<QUrl> failedSubFolders = mImporter->failedSubFolderList(); const int failedUrlCount = failedUrls.count(); const int failedSubFolderCount = failedSubFolders.count(); if (failedUrlCount + failedSubFolderCount > 0) { QStringList files, dirs; for (int i = 0; i < failedUrlCount; i++) { files << failedUrls[i].toString(QUrl::PreferLocalFile); } for (int i = 0; i < failedSubFolderCount; i++) { dirs << failedSubFolders[i].toString(QUrl::PreferLocalFile); } Q_EMIT q->showErrors(files, dirs); } } void deleteImportedUrls() { const QList<QUrl> importedUrls = mImporter->importedUrlList(); const QList<QUrl> skippedUrls = mImporter->skippedUrlList(); const int importedCount = importedUrls.count(); const int skippedCount = skippedUrls.count(); if (importedCount == 0 && skippedCount == 0) { return; } QStringList message; message << i18np("One document has been imported.", "%1 documents have been imported.", importedCount); if (skippedCount > 0) { message << i18np("One document has been skipped because it had already been imported.", "%1 documents have been skipped because they had already been imported.", skippedCount); } if (mImporter->renamedCount() > 0) { message[0].append(QStringLiteral("*")); message << QStringLiteral("<small>* ") + i18np("One of them has been renamed because another document with the same name had already been imported.", "%1 of them have been renamed because other documents with the same name had already been imported.", mImporter->renamedCount()) + "</small>"; } message << QString(); if (skippedCount == 0) { message << i18np("Delete the imported document from the device?", "Delete the %1 imported documents from the device?", importedCount); } else if (importedCount == 0) { message << i18np("Delete the skipped document from the device?", "Delete the %1 skipped documents from the device?", skippedCount); } else { message << i18ncp("Singular sentence is actually never used.", "Delete the imported or skipped document from the device?", "Delete the %1 imported and skipped documents from the device?", importedCount + skippedCount); } int answer = KMessageBox::questionTwoActions(mCentralWidget, QStringLiteral("<qt>") + message.join(QStringLiteral("<br/>")) + QStringLiteral("</qt>"), i18nc("@title:window", "Import Finished"), KGuiItem(i18n("Keep")), KStandardGuiItem::del()); if (answer == KMessageBox::PrimaryAction) { return; } QList<QUrl> urls = importedUrls + skippedUrls; while (true) { KIO::Job *job = KIO::del(urls); if (job->exec()) { break; } // Deleting failed int answer = KMessageBox::warningTwoActions(mCentralWidget, i18np("Failed to delete the document:\n%2", "Failed to delete documents:\n%2", urls.count(), job->errorString()), QString(), KGuiItem(i18n("Retry")), KGuiItem(i18n("Ignore"))); if (answer != KMessageBox::PrimaryAction) { // Ignore break; } } } void startGwenview() { KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("org.kde.gwenview")); if (!service) { qCCritical(GWENVIEW_IMPORTER_LOG) << "Could not find gwenview"; } else { auto job = new KIO::ApplicationLauncherJob(service); job->setUrls({mThumbnailPage->destinationUrl()}); job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, nullptr)); job->start(); } } void showWhatNext() { mCentralWidget->setCurrentWidget(mDialogPage); mDialogPage->setText(i18n("What do you want to do now?")); mDialogPage->removeButtons(); int gwenview = mDialogPage->addButton(KGuiItem(i18n("View Imported Documents with Gwenview"), QStringLiteral("gwenview"))); int importMore = mDialogPage->addButton(KGuiItem(i18n("Import more Documents"))); mDialogPage->addButton(KGuiItem(i18n("Quit"), QStringLiteral("dialog-cancel"))); int answer = mDialogPage->exec(); if (answer == gwenview) { startGwenview(); qApp->quit(); } else if (answer == importMore) { mCentralWidget->setCurrentWidget(mThumbnailPage); } else { /* quit */ qApp->quit(); } } }; ImportDialog::ImportDialog() : d(new ImportDialogPrivate) { d->q = this; d->mImporter = new Importer(this); connect(d->mImporter, &Importer::error, this, &ImportDialog::showImportError); d->mThumbnailPage = new ThumbnailPage; QUrl url = ImporterConfig::destinationUrl(); if (!url.isValid()) { url = QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); const int year = QDate::currentDate().year(); url.setPath(url.path() + '/' + QString::number(year)); } d->mThumbnailPage->setDestinationUrl(url); d->mProgressPage = new ProgressPage(d->mImporter); d->mDialogPage = new DialogPage; d->mCentralWidget = new QStackedWidget; setCentralWidget(d->mCentralWidget); d->mCentralWidget->addWidget(d->mThumbnailPage); d->mCentralWidget->addWidget(d->mProgressPage); d->mCentralWidget->addWidget(d->mDialogPage); connect(d->mThumbnailPage, &ThumbnailPage::importRequested, this, &ImportDialog::startImport); connect(d->mThumbnailPage, &ThumbnailPage::rejected, this, &QWidget::close); connect(d->mImporter, &Importer::importFinished, this, &ImportDialog::slotImportFinished); connect(this, &ImportDialog::showErrors, d->mDialogPage, &DialogPage::slotShowErrors); d->mCentralWidget->setCurrentWidget(d->mThumbnailPage); setWindowIcon(QIcon::fromTheme(QStringLiteral("gwenview"))); setAutoSaveSettings(); } ImportDialog::~ImportDialog() { delete d; } QSize ImportDialog::sizeHint() const { return QSize(700, 500); } void ImportDialog::setSourceUrl(const QUrl &url, const QString &deviceUdi) { QString name, iconName; if (deviceUdi.isEmpty()) { name = url.url(QUrl::PreferLocalFile); iconName = KProtocolInfo::icon(url.scheme()); if (iconName.isEmpty()) { iconName = QStringLiteral("folder"); } } else { Solid::Device device(deviceUdi); name = device.vendor() + QLatin1Char(' ') + device.product(); iconName = device.icon(); } d->mThumbnailPage->setSourceUrl(url, iconName, name); } void ImportDialog::startImport() { const QUrl url = d->mThumbnailPage->destinationUrl(); ImporterConfig::setDestinationUrl(url); ImporterConfig::self()->save(); d->mCentralWidget->setCurrentWidget(d->mProgressPage); d->mImporter->setAutoRenameFormat(ImporterConfig::autoRename() ? ImporterConfig::autoRenameFormat() : QString()); d->mImporter->start(d->mThumbnailPage->urlList(), url); } void ImportDialog::slotImportFinished() { d->checkForFailedUrls(); d->deleteImportedUrls(); d->showWhatNext(); } void ImportDialog::showImportError(const QString &message) { KMessageBox::error(this, message); d->mCentralWidget->setCurrentWidget(d->mThumbnailPage); } } // namespace #include "moc_importdialog.cpp"
10,200
C++
.cpp
239
34.041841
160
0.637848
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,921
dialogpage.cpp
KDE_gwenview/importer/dialogpage.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "dialogpage.h" // Qt #include <QAction> #include <QEventLoop> #include <QList> #include <QPushButton> #include <QVBoxLayout> // KF #include <KGuiItem> #include <KMessageBox> // Local #include <ui_dialogpage.h> namespace Gwenview { struct DialogPagePrivate : public Ui_DialogPage { QVBoxLayout *mLayout = nullptr; QList<QPushButton *> mButtons; QEventLoop *mEventLoop = nullptr; DialogPage *q = nullptr; QStringList failedFileList; QStringList failedDirList; QAction *fileDetails = nullptr; QAction *dirDetails = nullptr; void setupFailedListActions() { fileDetails = new QAction(i18n("Show failed files...")); mErrorMessageWidget->addAction(fileDetails); QObject::connect(fileDetails, &QAction::triggered, q, &DialogPage::slotShowFailedFileDetails); fileDetails->setVisible(false); dirDetails = new QAction(i18n("Show failed subfolders...")); mErrorMessageWidget->addAction(dirDetails); QObject::connect(dirDetails, &QAction::triggered, q, &DialogPage::slotShowFailedDirDetails); dirDetails->setVisible(false); } void showErrors(const QStringList &files, const QStringList &dirs) { mErrorMessageWidget->setVisible(true); failedFileList.clear(); failedDirList.clear(); QStringList message; if (!files.isEmpty()) { failedFileList = files; message << i18np("Failed to import %1 document.", "Failed to import %1 documents.", files.count()); fileDetails->setVisible(true); } else fileDetails->setVisible(false); if (!dirs.isEmpty()) { failedDirList = dirs; message << i18np("Failed to create %1 destination subfolder.", "Failed to create %1 destination subfolders.", dirs.count()); dirDetails->setVisible(true); } else dirDetails->setVisible(false); mErrorMessageWidget->setText(message.join(QStringLiteral("<br/>"))); mErrorMessageWidget->animatedShow(); } void showFailedFileDetails() { const QString message = i18n("Failed to import documents:"); KMessageBox::errorList(q, message, failedFileList); } void showFailedDirDetails() { const QString message = i18n("Failed to create subfolders:"); KMessageBox::errorList(q, message, failedDirList); } }; DialogPage::DialogPage(QWidget *parent) : QWidget(parent) , d(new DialogPagePrivate) { d->q = this; d->setupUi(this); d->mLayout = new QVBoxLayout(d->mButtonContainer); d->setupFailedListActions(); d->mErrorMessageWidget->hide(); } DialogPage::~DialogPage() { delete d; } void DialogPage::removeButtons() { qDeleteAll(d->mButtons); d->mButtons.clear(); } void DialogPage::setText(const QString &text) { d->mLabel->setText(text); } int DialogPage::addButton(const KGuiItem &item) { const int id = d->mButtons.size(); auto button = new QPushButton; KGuiItem::assign(button, item); button->setFixedHeight(button->sizeHint().height() * 2); connect(button, &QAbstractButton::clicked, this, [this, id]() { d->mEventLoop->exit(id); }); d->mLayout->addWidget(button); d->mButtons << button; return id; } void DialogPage::slotShowErrors(const QStringList &files, const QStringList &dirs) { d->showErrors(files, dirs); } void DialogPage::slotShowFailedFileDetails() { d->showFailedFileDetails(); } void DialogPage::slotShowFailedDirDetails() { d->showFailedDirDetails(); } int DialogPage::exec() { QEventLoop loop; d->mEventLoop = &loop; return loop.exec(); } } // namespace #include "moc_dialogpage.cpp"
4,561
C++
.cpp
139
28.266187
136
0.705896
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,922
fileutils.cpp
KDE_gwenview/importer/fileutils.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include "fileutils.h" // Qt #include <QBuffer> #include <QFile> #include <QFileInfo> #include <QScopedPointer> #include <QUrl> // KF #include <KFileItem> #include <KIO/CopyJob> #include <KIO/Job> #include <KIO/JobUiDelegate> #include <KIO/StatJob> #include <KIO/StoredTransferJob> #include <KJobWidgets> // Local #include "gwenview_importer_debug.h" namespace Gwenview { namespace FileUtils { bool contentsAreIdentical(const QUrl &url1, const QUrl &url2, QWidget *authWindow) { KIO::StatJob *statJob = nullptr; KIO::StoredTransferJob *fileJob = nullptr; QScopedPointer<QIODevice> file1, file2; QByteArray file1Bytes, file2Bytes; if (url1.isLocalFile()) { statJob = KIO::mostLocalUrl(url1); KJobWidgets::setWindow(statJob, authWindow); if (!statJob->exec()) { qCWarning(GWENVIEW_IMPORTER_LOG) << "Unable to stat" << url1; return false; } file1.reset(new QFile(statJob->mostLocalUrl().toLocalFile())); } else { // file1 is remote fileJob = KIO::storedGet(url1, KIO::NoReload, KIO::HideProgressInfo); KJobWidgets::setWindow(fileJob, authWindow); if (!fileJob->exec()) { qCWarning(GWENVIEW_IMPORTER_LOG) << "Can't read" << url1; return false; } file1Bytes = QByteArray(fileJob->data()); file1.reset(new QBuffer(&file1Bytes)); } if (!file1->open(QIODevice::ReadOnly)) { // Can't read url1, assume it's different from url2 qCWarning(GWENVIEW_IMPORTER_LOG) << "Can't read" << url1; return false; } if (url2.isLocalFile()) { statJob = KIO::mostLocalUrl(url2); KJobWidgets::setWindow(statJob, authWindow); if (!statJob->exec()) { qCWarning(GWENVIEW_IMPORTER_LOG) << "Unable to stat" << url2; return false; } file2.reset(new QFile(statJob->mostLocalUrl().toLocalFile())); } else { // file2 is remote fileJob = KIO::storedGet(url2, KIO::NoReload, KIO::HideProgressInfo); KJobWidgets::setWindow(fileJob, authWindow); if (!fileJob->exec()) { qCWarning(GWENVIEW_IMPORTER_LOG) << "Can't read" << url2; return false; } file2Bytes = QByteArray(fileJob->data()); file2.reset(new QBuffer(&file2Bytes)); } if (!file2->open(QIODevice::ReadOnly)) { // Can't read url2, assume it's different from url1 qCWarning(GWENVIEW_IMPORTER_LOG) << "Can't read" << url2; return false; } const int CHUNK_SIZE = 4096; while (!file1->atEnd() && !file2->atEnd()) { QByteArray url1Array = file1->read(CHUNK_SIZE); QByteArray url2Array = file2->read(CHUNK_SIZE); if (url1Array != url2Array) { return false; } } if (file1->atEnd() && file2->atEnd()) { return true; } else { qCWarning(GWENVIEW_IMPORTER_LOG) << "One file ended before the other"; return false; } } RenameResult rename(const QUrl &src, const QUrl &dst_, QWidget *authWindow) { QUrl dst = dst_; RenameResult result = RenamedOK; int count = 1; QFileInfo fileInfo(dst.fileName()); QString prefix = fileInfo.completeBaseName() + QLatin1Char('_'); QString suffix = '.' + fileInfo.suffix(); // Get src size KIO::StatJob *sourceStat = KIO::stat(src); KJobWidgets::setWindow(sourceStat, authWindow); if (!sourceStat->exec()) { return RenameFailed; } KFileItem item(sourceStat->statResult(), src, true /* delayedMimeTypes */); KIO::filesize_t srcSize = item.size(); // Find unique name KIO::StatJob *statJob = KIO::stat(dst); KJobWidgets::setWindow(statJob, authWindow); while (statJob->exec()) { // File exists. If it's not the same, try to create a new name item = KFileItem(statJob->statResult(), dst, true /* delayedMimeTypes */); KIO::filesize_t dstSize = item.size(); if (srcSize == dstSize && contentsAreIdentical(src, dst, authWindow)) { // Already imported, skip it KIO::Job *job = KIO::file_delete(src, KIO::HideProgressInfo); KJobWidgets::setWindow(job, authWindow); return Skipped; } result = RenamedUnderNewName; dst.setPath(dst.adjusted(QUrl::RemoveFilename).path() + prefix + QString::number(count) + suffix); statJob = KIO::stat(dst); KJobWidgets::setWindow(statJob, authWindow); ++count; } // Rename KIO::Job *job = KIO::moveAs(src, dst, KIO::HideProgressInfo); KJobWidgets::setWindow(job, authWindow); if (!job->exec()) { result = RenameFailed; } return result; } } // namespace } // namespace
5,576
C++
.cpp
150
31.293333
106
0.657534
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,923
serializedurlmap.cpp
KDE_gwenview/importer/serializedurlmap.cpp
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2012 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ // Self #include <serializedurlmap.h> // Local // KF #include <KConfigGroup> // Qt #include <QUrl> namespace Gwenview { static const char *KEY_SUFFIX = "key"; static const char *VALUE_SUFFIX = "value"; static QUrl stripPass(const QUrl &url_) { QUrl url = url_; url.setPassword(QString()); return url; } struct SerializedUrlMapPrivate { KConfigGroup mGroup; QMap<QUrl, QUrl> mMap; void read() { mMap.clear(); for (int idx = 0;; ++idx) { const QString idxString = QString::number(idx); const QString key = idxString + QLatin1String(KEY_SUFFIX); if (!mGroup.hasKey(key)) { break; } const QVariant keyUrl = mGroup.readEntry(key, QVariant()); const QVariant valueUrl = mGroup.readEntry(idxString + QLatin1String(VALUE_SUFFIX), QVariant()); mMap.insert(keyUrl.toUrl(), valueUrl.toUrl()); } } void write() { mGroup.deleteGroup(); QMap<QUrl, QUrl>::ConstIterator it = mMap.constBegin(), end = mMap.constEnd(); int idx = 0; for (; it != end; ++it, ++idx) { const QString idxString = QString::number(idx); mGroup.writeEntry(idxString + QLatin1String(KEY_SUFFIX), QVariant(it.key())); mGroup.writeEntry(idxString + QLatin1String(VALUE_SUFFIX), QVariant(it.value())); } mGroup.sync(); } }; SerializedUrlMap::SerializedUrlMap() : d(new SerializedUrlMapPrivate) { } SerializedUrlMap::~SerializedUrlMap() { delete d; } void SerializedUrlMap::setConfigGroup(const KConfigGroup &group) { d->mGroup = group; d->read(); } QUrl SerializedUrlMap::value(const QUrl &key_) const { const QString pass = key_.password(); const QUrl key = stripPass(key_); QUrl url = d->mMap.value(key); url.setPassword(pass); return url; } void SerializedUrlMap::insert(const QUrl &key, const QUrl &value) { d->mMap.insert(stripPass(key), stripPass(value)); d->write(); } } // namespace
2,870
C++
.cpp
90
27.377778
108
0.686957
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
748,925
binder.h
KDE_gwenview/lib/binder.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ #ifndef BINDER_H #define BINDER_H #include <lib/gwenviewlib_export.h> // Qt #include <QObject> namespace Gwenview { /** * @internal * * Necessary helper class because a QObject class cannot be a template */ class GWENVIEWLIB_EXPORT BinderInternal : public QObject { Q_OBJECT public: explicit BinderInternal(QObject *parent); ~BinderInternal() override; protected Q_SLOTS: virtual void callMethod() { } }; /** * The Binder and BinderRef classes make it possible to "connect" a * parameter-less signal with a slot which accepts one argument. The * argument must be known at connection time. * * Example: * * Assuming a class like this: * * class Receiver * { * public: * void doSomething(Param* p); * }; * * This code: * * Binder<Receiver, Param*>::bind(emitter, SIGNAL(somethingHappened()), receiver, &Receiver::doSomething, p) * * Will result in receiver->doSomething(p) being called when emitter emits * the somethingHappened() signal. * * Just like a regular QObject connection, the connection will last until * either emitter or receiver are deleted. * * Using this system avoids creating an helper slot and adding a member to * the Receiver class to store the argument of the method to call. * * To call a method which accept a pointer or a value argument, use Binder. * To call a method which accept a const reference argument, use BinderRef. * * Note: the method does not need to be a slot. */ template<class Receiver, class Arg, typename MethodArg> class BaseBinder : public BinderInternal { public: using Method = void (Receiver::*)(MethodArg); static void bind(QObject *emitter, const char *signal, Receiver *receiver, Method method, MethodArg arg) { auto *binder = new BaseBinder<Receiver, Arg, MethodArg>(emitter); binder->mReceiver = receiver; binder->mMethod = method; binder->mArg = arg; QObject::connect(emitter, signal, binder, SLOT(callMethod())); QObject::connect(receiver, SIGNAL(destroyed(QObject *)), binder, SLOT(deleteLater())); } protected: void callMethod() override { (mReceiver->*mMethod)(mArg); } private: BaseBinder(QObject *emitter) : BinderInternal(emitter) , mReceiver(nullptr) , mMethod(nullptr) { } Receiver *mReceiver; Method mMethod; Arg mArg; }; template<class Receiver, class Arg> class Binder : public BaseBinder<Receiver, Arg, Arg> { }; template<class Receiver, class Arg> class BinderRef : public BaseBinder<Receiver, Arg, const Arg &> { }; } // namespace #endif /* BINDER_H */
3,440
C++
.h
112
27.839286
108
0.737462
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,926
jpegcontent.h
KDE_gwenview/lib/jpegcontent.h
// vim: set tabstop=4 shiftwidth=4 expandtab /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 JPEGCONTENT_H #define JPEGCONTENT_H // Local #include <QByteArray> #include <lib/gwenviewlib_export.h> #include <lib/orientation.h> class QImage; class QSize; class QString; class QIODevice; namespace Exiv2 { class Image; } namespace Gwenview { class GWENVIEWLIB_EXPORT JpegContent { public: JpegContent(); ~JpegContent(); Orientation orientation() const; void resetOrientation(); int dotsPerMeterX() const; int dotsPerMeterY() const; QSize size() const; QString comment() const; void setComment(const QString &); void transform(Orientation); QImage thumbnail() const; void setThumbnail(const QImage &); // Recreate raw data to represent image // Note: thumbnail must be updated separately void setImage(const QImage &image); bool load(const QString &file); bool loadFromData(const QByteArray &rawData); /** * Use this version of loadFromData if you already have an Exiv2::Image* */ bool loadFromData(const QByteArray &rawData, Exiv2::Image *); bool save(const QString &file); bool save(QIODevice *); QByteArray rawData() const; QString errorString() const; private: struct Private; Private *d; JpegContent(const JpegContent &) = delete; void operator=(const JpegContent &) = delete; void applyPendingTransformation(); int dotsPerMeter(const QString &keyName) const; }; } // namespace #endif /* JPEGCONTENT_H */
2,275
C++
.h
70
29.371429
79
0.756645
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,928
mousewheelbehavior.h
KDE_gwenview/lib/mousewheelbehavior.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2010 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ #ifndef MOUSEWHEELBEHAVIOR_H #define MOUSEWHEELBEHAVIOR_H // Qt // KF // Local namespace Gwenview { namespace MouseWheelBehavior { enum Enum { Scroll, Browse, Zoom, }; } // namespace MouseWheelBehavior } // namespace Gwenview #endif /* MOUSEWHEELBEHAVIOR_H */
1,094
C++
.h
33
31.393939
81
0.79771
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,930
disabledactionshortcutmonitor.h
KDE_gwenview/lib/disabledactionshortcutmonitor.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2014 Aurélien Gâteau <agateau@kde.org> 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, see <http://www.gnu.org/licenses/>. */ #ifndef DISABLEDACTIONSHORTCUTMONITOR_H #define DISABLEDACTIONSHORTCUTMONITOR_H #include <lib/gwenviewlib_export.h> // Local // KF // Qt #include <QObject> class QAction; namespace Gwenview { class DisabledActionShortcutMonitorPrivate; /** * Monitors an action and emits a signal if one tries to trigger the action * using its shortcut while it is disabled. */ class GWENVIEWLIB_EXPORT DisabledActionShortcutMonitor : public QObject { Q_OBJECT public: /** * parent must be a widget because we need to create a QShortcut */ DisabledActionShortcutMonitor(QAction *action, QObject *parent); ~DisabledActionShortcutMonitor() override; Q_SIGNALS: void activated(); protected: bool eventFilter(QObject *object, QEvent *event) override; private: DisabledActionShortcutMonitorPrivate *const d; }; } // namespace #endif /* DISABLEDACTIONSHORTCUTMONITOR_H */
1,643
C++
.h
48
32.041667
75
0.794807
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,931
transformimageoperation.h
KDE_gwenview/lib/transformimageoperation.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2007 Aurélien Gâteau <agateau@kde.org> 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 TRANSFORMIMAGEOPERATION_H #define TRANSFORMIMAGEOPERATION_H #include <lib/gwenviewlib_export.h> // Qt // KF // Local #include <lib/abstractimageoperation.h> #include <lib/document/documentjob.h> #include <lib/orientation.h> namespace Gwenview { class TransformJob : public ThreadedDocumentJob { Q_OBJECT public: TransformJob(Orientation orientation); void threadedStart() override; private: Orientation mOrientation; }; struct TransformImageOperationPrivate; class GWENVIEWLIB_EXPORT TransformImageOperation : public AbstractImageOperation { public: TransformImageOperation(Orientation); ~TransformImageOperation() override; void redo() override; void undo() override; private: TransformImageOperationPrivate *const d; }; } // namespace #endif /* TRANSFORMIMAGEOPERATION_H */
1,644
C++
.h
49
31.44898
80
0.807863
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,932
memoryutils.h
KDE_gwenview/lib/memoryutils.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2008 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ #ifndef MEMORYUTILS_H #define MEMORYUTILS_H #include <lib/gwenviewlib_export.h> // Qt #include <QtGlobal> // KF // Local namespace Gwenview { namespace MemoryUtils { /** * This function returns the amount of total memory installed on the system * FIXME: It lacks *BSD and MacOSX support! */ GWENVIEWLIB_EXPORT qulonglong getTotalMemory(); /** * This function returns the amount of available free memory installed on the * system * FIXME: It lacks *BSD and MacOSX support! */ GWENVIEWLIB_EXPORT qulonglong getFreeMemory(); } // namespace } // namespace #endif /* MEMORYUTILS_H */
1,410
C++
.h
41
32.853659
81
0.793205
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,933
eventwatcher.h
KDE_gwenview/lib/eventwatcher.h
/* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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 EVENTWATCHER_H #define EVENTWATCHER_H // Qt #include <QEvent> #include <QList> #include <QObject> // Local #include "gwenviewlib_export.h" namespace Gwenview { /** * This class emits a signal when some events are triggered on a watched * object. */ class GWENVIEWLIB_EXPORT EventWatcher : public QObject { Q_OBJECT public: EventWatcher(QObject *watched, const QList<QEvent::Type> &eventTypes); static EventWatcher *install(QObject *watched, const QList<QEvent::Type> &eventTypes, QObject *receiver, const char *slot); static EventWatcher *install(QObject *watched, QEvent::Type eventType, QObject *receiver, const char *slot); Q_SIGNALS: void eventTriggered(QEvent *); protected: bool eventFilter(QObject *, QEvent *event) override; private: QList<QEvent::Type> mEventTypes; }; } #endif /* EVENTWATCHER_H */
1,624
C++
.h
45
34.044444
127
0.783749
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,934
fullscreenbackground.h
KDE_gwenview/lib/fullscreenbackground.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2021 Antonio Prcela <antonio.prcela@gmail.com> 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, Cambridge, MA 02110-1301, USA. */ #ifndef FULLSCREENBACKGROUND_H #define FULLSCREENBACKGROUND_H // Qt // KF // Local namespace Gwenview { namespace FullScreenBackground { /** * This enum represents the different background types in fullscreen mode */ enum Enum { Black, Image, }; } // namespace FullScreenBackground } // namespace Gwenview #endif /* FULLSCREENBACKGROUND_H */
1,180
C++
.h
35
32.114286
73
0.800705
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
748,935
placetreemodel.h
KDE_gwenview/lib/placetreemodel.h
// vim: set tabstop=4 shiftwidth=4 expandtab: /* Gwenview: an image viewer Copyright 2009 Aurélien Gâteau <agateau@kde.org> 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, Cambridge, MA 02110-1301, USA. */ #ifndef PLACETREEMODEL_H #define PLACETREEMODEL_H #include <lib/gwenviewlib_export.h> // Qt #include <QAbstractItemModel> // KF // Local class QUrl; namespace Gwenview { struct PlaceTreeModelPrivate; class GWENVIEWLIB_EXPORT PlaceTreeModel : public QAbstractItemModel { Q_OBJECT public: explicit PlaceTreeModel(QObject *); ~PlaceTreeModel() override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; bool hasChildren(const QModelIndex &parent) const override; bool canFetchMore(const QModelIndex &parent) const override; void fetchMore(const QModelIndex &parent) override; QUrl urlForIndex(const QModelIndex &) const; private Q_SLOTS: void slotPlacesRowsInserted(const QModelIndex &, int start, int end); void slotPlacesRowsAboutToBeRemoved(const QModelIndex &, int start, int end); void slotDirRowsAboutToBeInserted(const QModelIndex &, int start, int end); void slotDirRowsInserted(const QModelIndex &, int start, int end); void slotDirRowsAboutToBeRemoved(const QModelIndex &, int start, int end); void slotDirRowsRemoved(const QModelIndex &, int start, int end); private: friend struct PlaceTreeModelPrivate; PlaceTreeModelPrivate *const d; }; } // namespace #endif /* PLACETREEMODEL_H */
2,441
C++
.h
55
41.6
101
0.789696
KDE/gwenview
117
25
0
GPL-2.0
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false