diff --git a/core/utilities/imageeditor/editor/editorstackview.cpp b/core/utilities/imageeditor/editor/editorstackview.cpp index 7699616d17..c7e4d9951f 100644 --- a/core/utilities/imageeditor/editor/editorstackview.cpp +++ b/core/utilities/imageeditor/editor/editorstackview.cpp @@ -1,336 +1,339 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2008-08-20 * Description : A widget stack to embed editor view. * * Copyright (C) 2008-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #include "editorstackview.h" // Local includes #include "dzoombar.h" #include "canvas.h" #include "thumbnailsize.h" #include "graphicsdimgview.h" #include "previewlayout.h" namespace Digikam { class Q_DECL_HIDDEN EditorStackView::Private { public: explicit Private() : toolView(nullptr), canvas(nullptr) { } QWidget* toolView; Canvas* canvas; }; EditorStackView::EditorStackView(QWidget* const parent) : QStackedWidget(parent), d(new Private) { } EditorStackView::~EditorStackView() { delete d; } void EditorStackView::setCanvas(Canvas* const canvas) { if (d->canvas) { return; } d->canvas = canvas; insertWidget(CanvasMode, d->canvas); connect(d->canvas, SIGNAL(signalZoomChanged(double)), this, SLOT(slotZoomChanged(double))); connect(d->canvas, SIGNAL(signalToggleOffFitToWindow()), this, SIGNAL(signalToggleOffFitToWindow())); } Canvas* EditorStackView::canvas() const { return d->canvas; } void EditorStackView::setToolView(QWidget* const view) { if (d->toolView) { removeWidget(d->toolView); } d->toolView = view; if (d->toolView) { insertWidget(ToolViewMode, d->toolView); } GraphicsDImgView* const preview = previewWidget(); if (preview) { connect(preview->layout(), SIGNAL(zoomFactorChanged(double)), this, SLOT(slotZoomChanged(double))); connect(preview->layout(), SIGNAL(fitToWindowToggled(bool)), this, SLOT(slotToggleOffFitToWindow(bool))); } } QWidget* EditorStackView::toolView() const { return d->toolView; } int EditorStackView::viewMode() const { return indexOf(currentWidget()); } void EditorStackView::setViewMode(int mode) { - if (mode != CanvasMode && mode != ToolViewMode) + if ((mode != CanvasMode) && (mode != ToolViewMode)) { return; } setCurrentIndex(mode); } void EditorStackView::increaseZoom() { if (viewMode() == CanvasMode) { d->canvas->layout()->increaseZoom(); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { preview->layout()->increaseZoom(); } } } void EditorStackView::decreaseZoom() { if (viewMode() == CanvasMode) { d->canvas->layout()->decreaseZoom(); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { preview->layout()->decreaseZoom(); } } } void EditorStackView::toggleFitToWindow() { // Fit to window action is common place to switch view in this mode. // User want to see the same behaviors between canvas and tool preview. // Both are toggle at the same time. + d->canvas->layout()->toggleFitToWindow(); GraphicsDImgView* const preview = previewWidget(); if (preview) { preview->layout()->toggleFitToWindow(); } } void EditorStackView::fitToSelect() { if (viewMode() == CanvasMode) { d->canvas->fitToSelect(); } } void EditorStackView::zoomTo100Percent() { if (viewMode() == CanvasMode) { d->canvas->layout()->toggleFitToWindowOr100(); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { preview->layout()->toggleFitToWindowOr100(); } } } void EditorStackView::setZoomFactor(double zoom) { if (viewMode() == CanvasMode) { d->canvas->layout()->setZoomFactor(zoom); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { preview->layout()->setZoomFactor(zoom); } } } double EditorStackView::zoomMax() const { if (viewMode() == CanvasMode) { return d->canvas->layout()->maxZoomFactor(); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { return preview->layout()->maxZoomFactor(); } else { - return -1.0; + return (-1.0); } } } double EditorStackView::zoomMin() const { if (viewMode() == CanvasMode) { return d->canvas->layout()->minZoomFactor(); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { return preview->layout()->minZoomFactor(); } else { - return -1.0; + return (-1.0); } } } void EditorStackView::slotZoomSliderChanged(int size) { - if (viewMode() == ToolViewMode && !isZoomablePreview()) + if ((viewMode() == ToolViewMode) && !isZoomablePreview()) { return; } double z = DZoomBar::zoomFromSize(size, zoomMin(), zoomMax()); if (viewMode() == CanvasMode) { d->canvas->layout()->setZoomFactorSnapped(z); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { return preview->layout()->setZoomFactorSnapped(z); } } } void EditorStackView::slotZoomChanged(double zoom) { bool max, min; if (viewMode() == CanvasMode) { max = d->canvas->layout()->atMaxZoom(); min = d->canvas->layout()->atMinZoom(); + emit signalZoomChanged(max, min, zoom); } else { GraphicsDImgView* const preview = previewWidget(); if (preview) { max = preview->layout()->atMaxZoom(); min = preview->layout()->atMinZoom(); + emit signalZoomChanged(max, min, zoom); } } } void EditorStackView::slotToggleOffFitToWindow(bool b) { if (b) { emit signalToggleOffFitToWindow(); } } GraphicsDImgView* EditorStackView::previewWidget() const { GraphicsDImgView* const preview = dynamic_cast(d->toolView); if (preview) { return preview; } return nullptr; } bool EditorStackView::isZoomablePreview() const { return previewWidget(); } } // namespace Digikam diff --git a/core/utilities/imageeditor/editor/editorstackview.h b/core/utilities/imageeditor/editor/editorstackview.h index 608f521915..b7aa1657ba 100644 --- a/core/utilities/imageeditor/editor/editorstackview.h +++ b/core/utilities/imageeditor/editor/editorstackview.h @@ -1,104 +1,104 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2008-08-20 * Description : A widget stack to embed editor view. * * Copyright (C) 2008-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #ifndef DIGIKAM_IMAGE_EDITOR_STACK_VIEW_H #define DIGIKAM_IMAGE_EDITOR_STACK_VIEW_H // Qt includes #include // Local includes #include "digikam_export.h" namespace Digikam { class Canvas; class GraphicsDImgView; class DIGIKAM_EXPORT EditorStackView : public QStackedWidget { Q_OBJECT public: enum StackViewMode { CanvasMode = 0, ToolViewMode }; public: explicit EditorStackView(QWidget* const parent = nullptr); ~EditorStackView(); void setCanvas(Canvas* const canvas); - Canvas* canvas() const; + Canvas* canvas() const; void setToolView(QWidget* const view); - QWidget* toolView() const; + QWidget* toolView() const; void setViewMode(int mode); - int viewMode() const; + int viewMode() const; void increaseZoom(); void decreaseZoom(); void toggleFitToWindow(); void fitToSelect(); void zoomTo100Percent(); double zoomMax() const; double zoomMin() const; bool isZoomablePreview() const; Q_SIGNALS: void signalZoomChanged(bool isMax, bool isMin, double zoom); void signalToggleOffFitToWindow(); public Q_SLOTS: void setZoomFactor(double); void slotZoomSliderChanged(int); private Q_SLOTS: void slotZoomChanged(double); void slotToggleOffFitToWindow(bool); private: GraphicsDImgView* previewWidget() const; private: class Private; Private* const d; }; } // namespace Digikam #endif // DIGIKAM_IMAGE_EDITOR_STACK_VIEW_H diff --git a/core/utilities/imageeditor/editor/editortool.cpp b/core/utilities/imageeditor/editor/editortool.cpp index 702ce618dc..0de1130581 100644 --- a/core/utilities/imageeditor/editor/editortool.cpp +++ b/core/utilities/imageeditor/editor/editortool.cpp @@ -1,721 +1,735 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2008-08-20 * Description : editor tool template class. * * Copyright (C) 2008-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #include "editortool.h" // Qt includes #include #include #include #include // KDE includes #include #include #include // Local includes #include "digikam_debug.h" #include "dimgthreadedfilter.h" #include "dimgthreadedanalyser.h" #include "imageguidewidget.h" #include "imageregionwidget.h" #include "histogramwidget.h" #include "histogrambox.h" #include "editortoolsettings.h" #include "editortooliface.h" namespace Digikam { class Q_DECL_HIDDEN EditorTool::Private { public: explicit Private() : initPreview(false), version(0), view(nullptr), timer(nullptr), settings(nullptr), category(FilterAction::ReproducibleFilter), plugin(nullptr) { } static const QString configGroupName; static const QString configRestoreSettingsEntry; bool initPreview; QString helpAnchor; QString name; int version; QWidget* view; QIcon icon; QTimer* timer; EditorToolSettings* settings; FilterAction::Category category; DPluginEditor* plugin; }; const QString EditorTool::Private::configGroupName(QLatin1String("ImageViewer Settings")); const QString EditorTool::Private::configRestoreSettingsEntry(QLatin1String("RestoreToolSettings")); // -------------------------------------------------------- EditorTool::EditorTool(QObject* const parent) : QObject(parent), d(new Private) { d->timer = new QTimer(this); // --- NOTE: use dynamic binding as slotPreview() is a virtual method which can be re-implemented in derived classes. connect(d->timer, &QTimer::timeout, this, &EditorTool::slotPreview); } EditorTool::~EditorTool() { delete d->settings; delete d->view; delete d; } void EditorTool::setPlugin(DPluginEditor* const plugin) { d->plugin = plugin; setToolName(d->plugin->name()); setToolIcon(d->plugin->icon()); d->settings->setTool(this); } DPluginEditor* EditorTool::plugin() const { return d->plugin; } void EditorTool::init() { QTimer::singleShot(0, this, SLOT(slotInit())); } void EditorTool::setInitPreview(bool b) { d->initPreview = b; } QIcon EditorTool::toolIcon() const { return d->icon; } void EditorTool::setToolIcon(const QIcon& icon) { d->icon = icon; } QString EditorTool::toolName() const { return d->name; } void EditorTool::setToolName(const QString& name) { d->name = name; } int EditorTool::toolVersion() const { return d->version; } void EditorTool::setToolVersion(const int version) { d->version = version; } FilterAction::Category EditorTool::toolCategory() const { return d->category; } void EditorTool::setToolCategory(const FilterAction::Category category) { d->category = category; } void EditorTool::setPreviewModeMask(int mask) { EditorToolIface::editorToolIface()->setPreviewModeMask(mask); } QWidget* EditorTool::toolView() const { return d->view; } void EditorTool::setToolView(QWidget* const view) { d->view = view; + // Will be unblocked in slotInit() // This will prevent resize event signals emit during tool init. + d->view->blockSignals(true); ImageGuideWidget* const wgt = dynamic_cast(d->view); if (wgt) { connect(d->view, SIGNAL(spotPositionChangedFromOriginal(Digikam::DColor,QPoint)), this, SLOT(slotUpdateSpotInfo(Digikam::DColor,QPoint))); connect(d->view, SIGNAL(spotPositionChangedFromTarget(Digikam::DColor,QPoint)), this, SLOT(slotUpdateSpotInfo(Digikam::DColor,QPoint))); } } EditorToolSettings* EditorTool::toolSettings() const { return d->settings; } void EditorTool::setToolSettings(EditorToolSettings* const settings) { d->settings = settings; d->settings->setTool(this); connect(d->settings, SIGNAL(signalOkClicked()), this, SLOT(slotOk())); connect(d->settings, SIGNAL(signalCancelClicked()), this, SLOT(slotCancel())); connect(d->settings, SIGNAL(signalDefaultClicked()), this, SLOT(slotResetSettings())); connect(d->settings, SIGNAL(signalSaveAsClicked()), this, SLOT(slotSaveAsSettings())); connect(d->settings, SIGNAL(signalLoadClicked()), this, SLOT(slotLoadSettings())); connect(d->settings, SIGNAL(signalTryClicked()), this, SLOT(slotPreview())); connect(d->settings, SIGNAL(signalChannelChanged()), this, SLOT(slotChannelChanged())); connect(d->settings, SIGNAL(signalScaleChanged()), this, SLOT(slotScaleChanged())); // Will be unblocked in slotInit() // This will prevent signals emit during tool init. + d->settings->blockSignals(true); } void EditorTool::slotInit() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(d->configGroupName); // We always have to call readSettings(), some tools need it. + if (group.readEntry(d->configRestoreSettingsEntry, true)) { readSettings(); } else { writeSettings(); readSettings(); } // Unlock signals from preview and settings widgets when init is done. + d->view->blockSignals(false); d->settings->blockSignals(false); if (d->initPreview) + { slotTimer(); + } } void EditorTool::setToolHelp(const QString& anchor) { d->helpAnchor = anchor; + // TODO: use this anchor with editor Help menu } QString EditorTool::toolHelp() const { if (d->helpAnchor.isEmpty()) { return (objectName() + QLatin1String(".anchor")); } return d->helpAnchor; } void EditorTool::setBusy(bool state) { d->settings->setBusy(state); } void EditorTool::readSettings() { d->settings->readSettings(); } void EditorTool::writeSettings() { d->settings->writeSettings(); } void EditorTool::slotResetSettings() { d->settings->resetSettings(); } void EditorTool::slotTimer() { d->timer->setSingleShot(true); d->timer->start(500); } void EditorTool::slotOk() { writeSettings(); finalRendering(); + emit okClicked(); } void EditorTool::slotCancel() { writeSettings(); + emit cancelClicked(); } void EditorTool::slotCloseTool() { slotCancel(); } void EditorTool::slotApplyTool() { slotOk(); } void EditorTool::slotPreviewModeChanged() { slotPreview(); } void EditorTool::setBackgroundColor(const QColor& bg) { ImageGuideWidget* const view = dynamic_cast(d->view); QPalette palette; if (view) { palette.setColor(view->backgroundRole(), bg); view->setPalette(palette); } ImageRegionWidget* const view2 = dynamic_cast(d->view); if (view2) { palette.setColor(view2->backgroundRole(), bg); view2->setPalette(palette); } } void EditorTool::ICCSettingsChanged() { ImageGuideWidget* const view = dynamic_cast(d->view); if (view) { view->ICCSettingsChanged(); } ImageRegionWidget* const view2 = dynamic_cast(d->view); if (view2) { view2->ICCSettingsChanged(); } } void EditorTool::exposureSettingsChanged() { ImageGuideWidget* const view = dynamic_cast(d->view); if (view) { view->exposureSettingsChanged(); } ImageRegionWidget* const view2 = dynamic_cast(d->view); if (view2) { view2->exposureSettingsChanged(); } } void EditorTool::setToolInfoMessage(const QString& txt) { EditorToolIface::editorToolIface()->setToolInfoMessage(txt); } void EditorTool::slotUpdateSpotInfo(const DColor& col, const QPoint& point) { DColor color = col; setToolInfoMessage(i18n("(%1,%2) RGBA:%3,%4,%5,%6", point.x(), point.y(), color.red(), color.green(), color.blue(), color.alpha())); } // ---------------------------------------------------------------- class Q_DECL_HIDDEN EditorToolThreaded::Private { public: explicit Private() : delFilter(true), currentRenderingMode(EditorToolThreaded::NoneRendering), threadedFilter(nullptr), threadedAnalyser(nullptr) { } bool delFilter; EditorToolThreaded::RenderingMode currentRenderingMode; QString progressMess; DImgThreadedFilter* threadedFilter; DImgThreadedAnalyser* threadedAnalyser; }; EditorToolThreaded::EditorToolThreaded(QObject* const parent) - : EditorTool(parent), d(new Private) + : EditorTool(parent), + d(new Private) { } EditorToolThreaded::~EditorToolThreaded() { delete d->threadedFilter; delete d; } EditorToolThreaded::RenderingMode EditorToolThreaded::renderingMode() const { return d->currentRenderingMode; } void EditorToolThreaded::setProgressMessage(const QString& mess) { d->progressMess = mess; } DImgThreadedFilter* EditorToolThreaded::filter() const { return d->threadedFilter; } void EditorToolThreaded::slotInit() { EditorTool::slotInit(); QWidget* const view = toolView(); if (dynamic_cast(view)) { connect(view, SIGNAL(signalResized()), this, SLOT(slotResized())); } if (dynamic_cast(view)) { connect(view, SIGNAL(signalOriginalClipFocusChanged()), this, SLOT(slotTimer())); } } void EditorToolThreaded::setFilter(DImgThreadedFilter* const filter) { delete d->threadedFilter; d->threadedFilter = filter; connect(d->threadedFilter, SIGNAL(started()), this, SLOT(slotFilterStarted())); connect(d->threadedFilter, SIGNAL(finished(bool)), this, SLOT(slotFilterFinished(bool))); connect(d->threadedFilter, SIGNAL(progress(int)), this, SLOT(slotProgress(int))); d->threadedFilter->startFilter(); } DImgThreadedAnalyser* EditorToolThreaded::analyser() const { return d->threadedAnalyser; } void EditorToolThreaded::setAnalyser(DImgThreadedAnalyser* const analyser) { qCDebug(DIGIKAM_GENERAL_LOG) << "Analys " << toolName() << " started..."; toolSettings()->enableButton(EditorToolSettings::Ok, false); toolSettings()->enableButton(EditorToolSettings::SaveAs, false); toolSettings()->enableButton(EditorToolSettings::Load, false); toolSettings()->enableButton(EditorToolSettings::Default, false); toolSettings()->enableButton(EditorToolSettings::Try, false); toolView()->setEnabled(false); EditorToolIface::editorToolIface()->setToolStartProgress(d->progressMess.isEmpty() ? toolName() : d->progressMess); qApp->setOverrideCursor(Qt::WaitCursor); delete d->threadedAnalyser; d->threadedAnalyser = analyser; connect(d->threadedAnalyser, SIGNAL(started()), this, SLOT(slotAnalyserStarted())); connect(d->threadedAnalyser, SIGNAL(finished(bool)), this, SLOT(slotAnalyserFinished(bool))); connect(d->threadedAnalyser, SIGNAL(progress(int)), this, SLOT(slotProgress(int))); d->threadedAnalyser->startFilter(); } void EditorToolThreaded::slotResized() { - if (d->currentRenderingMode == EditorToolThreaded::FinalRendering) + if (d->currentRenderingMode == EditorToolThreaded::FinalRendering) { toolView()->update(); return; } else if (d->currentRenderingMode == EditorToolThreaded::PreviewRendering) { if (filter()) { filter()->cancelFilter(); } } QTimer::singleShot(0, this, SLOT(slotPreview())); } void EditorToolThreaded::slotAbort() { d->currentRenderingMode = EditorToolThreaded::NoneRendering; if (analyser()) { analyser()->cancelFilter(); } if (filter()) { filter()->cancelFilter(); } EditorToolIface::editorToolIface()->setToolStopProgress(); toolSettings()->enableButton(EditorToolSettings::Ok, true); toolSettings()->enableButton(EditorToolSettings::Load, true); toolSettings()->enableButton(EditorToolSettings::SaveAs, true); toolSettings()->enableButton(EditorToolSettings::Try, true); toolSettings()->enableButton(EditorToolSettings::Default, true); toolView()->setEnabled(true); qApp->restoreOverrideCursor(); renderingFinished(); } void EditorToolThreaded::slotFilterStarted() { } void EditorToolThreaded::slotFilterFinished(bool success) { if (success) // Computation Completed ! { switch (d->currentRenderingMode) { case EditorToolThreaded::PreviewRendering: { qCDebug(DIGIKAM_GENERAL_LOG) << "Preview " << toolName() << " completed..."; setPreviewImage(); slotAbort(); break; } case EditorToolThreaded::FinalRendering: { qCDebug(DIGIKAM_GENERAL_LOG) << "Final" << toolName() << " completed..."; setFinalImage(); EditorToolIface::editorToolIface()->setToolStopProgress(); qApp->restoreOverrideCursor(); emit okClicked(); break; } default: break; } } else // Computation Failed ! { switch (d->currentRenderingMode) { case EditorToolThreaded::PreviewRendering: { qCDebug(DIGIKAM_GENERAL_LOG) << "Preview " << toolName() << " failed..."; slotAbort(); break; } case EditorToolThreaded::FinalRendering: default: break; } } } void EditorToolThreaded::slotProgress(int progress) { EditorToolIface::editorToolIface()->setToolProgress(progress); } void EditorToolThreaded::slotAnalyserStarted() { } void EditorToolThreaded::slotAnalyserFinished(bool success) { if (success) { qCDebug(DIGIKAM_GENERAL_LOG) << "Analys " << toolName() << " completed..."; analyserCompleted(); } else { qCDebug(DIGIKAM_GENERAL_LOG) << "Analys " << toolName() << " failed..."; slotAbort(); } } void EditorToolThreaded::slotOk() { // Computation already in process. + if (d->currentRenderingMode != EditorToolThreaded::PreviewRendering) { // See bug #305916 : cancel preview before. + slotAbort(); } writeSettings(); d->currentRenderingMode = EditorToolThreaded::FinalRendering; qCDebug(DIGIKAM_GENERAL_LOG) << "Final " << toolName() << " started..."; toolSettings()->enableButton(EditorToolSettings::Ok, false); toolSettings()->enableButton(EditorToolSettings::SaveAs, false); toolSettings()->enableButton(EditorToolSettings::Load, false); toolSettings()->enableButton(EditorToolSettings::Default, false); toolSettings()->enableButton(EditorToolSettings::Try, false); toolView()->setEnabled(false); EditorToolIface::editorToolIface()->setToolStartProgress(d->progressMess.isEmpty() ? toolName() : d->progressMess); qApp->setOverrideCursor(Qt::WaitCursor); if (d->delFilter && d->threadedFilter) { delete d->threadedFilter; d->threadedFilter = nullptr; } prepareFinal(); } void EditorToolThreaded::slotPreview() { // Computation already in process. + if (d->currentRenderingMode != EditorToolThreaded::NoneRendering) { return; } d->currentRenderingMode = EditorToolThreaded::PreviewRendering; qCDebug(DIGIKAM_GENERAL_LOG) << "Preview " << toolName() << " started..."; toolSettings()->enableButton(EditorToolSettings::Ok, false); toolSettings()->enableButton(EditorToolSettings::SaveAs, false); toolSettings()->enableButton(EditorToolSettings::Load, false); toolSettings()->enableButton(EditorToolSettings::Default, false); toolSettings()->enableButton(EditorToolSettings::Try, false); toolView()->setEnabled(false); EditorToolIface::editorToolIface()->setToolStartProgress(d->progressMess.isEmpty() ? toolName() : d->progressMess); qApp->setOverrideCursor(Qt::WaitCursor); if (d->delFilter && d->threadedFilter) { delete d->threadedFilter; d->threadedFilter = nullptr; } preparePreview(); } void EditorToolThreaded::slotCancel() { writeSettings(); slotAbort(); emit cancelClicked(); } void EditorToolThreaded::deleteFilterInstance(bool b) { d->delFilter = b; } } // namespace Digikam diff --git a/core/utilities/imageeditor/editor/editortool.h b/core/utilities/imageeditor/editor/editortool.h index 8e45e3a718..7d1e4c80b7 100644 --- a/core/utilities/imageeditor/editor/editortool.h +++ b/core/utilities/imageeditor/editor/editortool.h @@ -1,221 +1,231 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2008-08-20 * Description : editor tool template class. * * Copyright (C) 2008-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #ifndef DIGIKAM_IMAGE_EDITOR_TOOL_H #define DIGIKAM_IMAGE_EDITOR_TOOL_H // Qt includes #include #include #include #include // Local includes #include "digikam_export.h" #include "dcolor.h" #include "previewtoolbar.h" #include "filteraction.h" #include "dplugineditor.h" namespace Digikam { class DImgThreadedFilter; class DImgThreadedAnalyser; class EditorToolSettings; class DIGIKAM_EXPORT EditorTool : public QObject { Q_OBJECT public: explicit EditorTool(QObject* const parent); virtual ~EditorTool(); void setPlugin(DPluginEditor* const plugin); DPluginEditor* plugin() const; - /** Caller by editor tool interface to initialized tool when all is ready, through slotInit(). + /** + * Called by editor tool interface to initialized tool when all is ready, through slotInit(). */ void init(); - /** Set this option to on if you want to call slotPreview() in slotInit() at tool startup. + /** + * Set this option to on if you want to call slotPreview() in slotInit() at tool startup. */ void setInitPreview(bool b); QString toolHelp() const; QString toolName() const; int toolVersion() const; QIcon toolIcon() const; QWidget* toolView() const; EditorToolSettings* toolSettings() const; FilterAction::Category toolCategory() const; virtual void setBackgroundColor(const QColor& bg); virtual void ICCSettingsChanged(); virtual void exposureSettingsChanged(); public Q_SLOTS: void slotUpdateSpotInfo(const Digikam::DColor& col, const QPoint& point); void slotPreviewModeChanged(); virtual void slotCloseTool(); virtual void slotApplyTool(); Q_SIGNALS: void okClicked(); void cancelClicked(); protected: void setToolInfoMessage(const QString& txt); void setToolHelp(const QString& anchor); void setToolName(const QString& name); void setToolVersion(const int version); void setToolIcon(const QIcon& icon); void setPreviewModeMask(int mask); void setToolCategory(const FilterAction::Category category); virtual void setToolView(QWidget* const view); virtual void setToolSettings(EditorToolSettings* const settings); virtual void setBusy(bool); virtual void readSettings(); virtual void writeSettings(); - virtual void finalRendering() {}; + virtual void finalRendering() {}; protected Q_SLOTS: void slotTimer(); virtual void slotOk(); virtual void slotCancel(); virtual void slotInit(); virtual void slotResetSettings(); virtual void slotLoadSettings() {}; virtual void slotSaveAsSettings() {}; virtual void slotPreview() {}; virtual void slotChannelChanged() {}; virtual void slotScaleChanged() {}; private: class Private; Private* const d; }; // ----------------------------------------------------------------- class DIGIKAM_EXPORT EditorToolThreaded : public EditorTool { Q_OBJECT public: enum RenderingMode { NoneRendering = 0, PreviewRendering, FinalRendering }; public: explicit EditorToolThreaded(QObject* const parent); virtual ~EditorToolThreaded(); - /** Set the small text to show in editor status progress bar during - * tool computation. If it's not set, tool name is used instead. + /** + * Set the small text to show in editor status progress bar during + * tool computation. If it's not set, tool name is used instead. */ void setProgressMessage(const QString& mess); - /** return the current tool rendering mode. + /** + * return the current tool rendering mode. */ RenderingMode renderingMode() const; public Q_SLOTS: virtual void slotAbort(); protected: - /** Manage filter instance plugged in tool interface + /** + * Manage filter instance plugged in tool interface */ DImgThreadedFilter* filter() const; void setFilter(DImgThreadedFilter* const filter); - /** Manage analyser instance plugged in tool interface + /** + * Manage analyser instance plugged in tool interface */ DImgThreadedAnalyser* analyser() const; void setAnalyser(DImgThreadedAnalyser* const analyser); - /** If true, delete filter instance when preview or final rendering is processed. - * If false, filter instance will be managed outside for ex. with ContentAwareResizing tool. + /** + * If true, delete filter instance when preview or final rendering is processed. + * If false, filter instance will be managed outside for ex. with ContentAwareResizing tool. */ void deleteFilterInstance(bool b = true); virtual void preparePreview() {}; virtual void prepareFinal() {}; virtual void setPreviewImage() {}; virtual void setFinalImage() {}; virtual void renderingFinished() {}; virtual void analyserCompleted() {}; protected Q_SLOTS: - /** Manage start and end events from filter + /** + * Manage start and end events from filter */ void slotFilterStarted(); void slotFilterFinished(bool success); - /** Manage start and end events from analyser + /** + * Manage start and end events from analyser */ void slotAnalyserStarted(); void slotAnalyserFinished(bool success); - /** Dispatch progress event from filter and analyser + /** + * Dispatch progress event from filter and analyser */ void slotProgress(int progress); - virtual void slotInit() override; - virtual void slotOk() override; - virtual void slotCancel() override; + virtual void slotInit() override; + virtual void slotOk() override; + virtual void slotCancel() override; virtual void slotPreview() override; private Q_SLOTS: void slotResized(); private: class Private; Private* const d; }; } // namespace Digikam #endif // DIGIKAM_IMAGE_EDITOR_TOOL_H diff --git a/core/utilities/imageeditor/editor/editortooliface.cpp b/core/utilities/imageeditor/editor/editortooliface.cpp index 783e2cc40e..a7d1314bae 100644 --- a/core/utilities/imageeditor/editor/editortooliface.cpp +++ b/core/utilities/imageeditor/editor/editortooliface.cpp @@ -1,346 +1,347 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2008-08-20 * Description : Image editor interface used by editor tools. * * Copyright (C) 2008-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #include "editortooliface.h" // Qt includes #include // KDE includes #include // Local includes #include "sidebar.h" #include "canvas.h" #include "statusprogressbar.h" #include "editortool.h" #include "editortoolsettings.h" #include "editorstackview.h" #include "editorwindow.h" #include "imageguidewidget.h" #include "imageregionwidget.h" #include "previewlayout.h" #include "dcategorizedview.h" namespace Digikam { class Q_DECL_HIDDEN EditorToolIface::Private { public: explicit Private() : toolsIconView(nullptr), lastActiveTab(nullptr), tool(nullptr), editor(nullptr), splitterSize(0) { } DCategorizedView* toolsIconView; QWidget* lastActiveTab; EditorTool* tool; EditorWindow* editor; int splitterSize; }; EditorToolIface* EditorToolIface::m_iface = nullptr; EditorToolIface* EditorToolIface::editorToolIface() { return m_iface; } EditorToolIface::EditorToolIface(EditorWindow* const editor) : QObject(), d(new Private) { d->editor = editor; m_iface = this; } EditorToolIface::~EditorToolIface() { delete d->tool; delete d; if (m_iface == this) { m_iface = nullptr; } } void EditorToolIface::setToolsIconView(DCategorizedView* const view) { d->toolsIconView = view; d->editor->rightSideBar()->appendTab(d->toolsIconView, QIcon::fromTheme(QLatin1String("document-edit")), i18n("Tools")); } EditorTool* EditorToolIface::currentTool() const { return d->tool; } void EditorToolIface::loadTool(EditorTool* const tool) { if (d->tool) { unLoadTool(); } d->tool = tool; d->lastActiveTab = d->editor->rightSideBar()->getActiveTab(); d->splitterSize = d->editor->sidebarSplitter()->size(d->editor->rightSideBar()); d->editor->editorStackView()->setToolView(d->tool->toolView()); d->editor->editorStackView()->setViewMode(EditorStackView::ToolViewMode); d->editor->rightSideBar()->deleteTab(d->toolsIconView); d->editor->rightSideBar()->appendTab(d->tool->toolSettings(), d->tool->toolIcon(), d->tool->toolName()); d->editor->rightSideBar()->setActiveTab(d->tool->toolSettings()); int w = qMax(d->splitterSize, d->tool->toolSettings()->minimumSizeHint().width()); d->editor->sidebarSplitter()->setSize(d->editor->rightSideBar(), w); d->editor->toggleActions(false); d->editor->toggleToolActions(d->tool); // If editor tool has zoomable preview, switch on zoom actions. d->editor->toggleZoomActions(d->editor->editorStackView()->isZoomablePreview()); ImageGuideWidget* const view = dynamic_cast(d->tool->toolView()); if (view) { connect(d->editor, SIGNAL(signalPreviewModeChanged(int)), view, SLOT(slotPreviewModeChanged(int))); view->slotPreviewModeChanged(d->editor->previewMode()); } // To set zoomable preview zoom level and position accordingly with main canvas. ImageRegionWidget* const view2 = dynamic_cast(d->tool->toolView()); if (view2) { connect(d->editor, SIGNAL(signalPreviewModeChanged(int)), view2, SLOT(slotPreviewModeChanged(int))); connect(d->editor->editorStackView(), SIGNAL(signalZoomChanged(bool,bool,double)), view2, SLOT(slotOriginalImageRegionChangedDelayed())); if (d->editor->editorStackView()->canvas()->layout()->isFitToWindow()) { view2->fitToWindow(); } else { view2->layout()->setZoomFactor(d->editor->editorStackView()->canvas()->layout()->zoomFactor()); QPoint tl = d->editor->editorStackView()->canvas()->visibleArea().topLeft(); view2->setContentsPos(tl.x(), tl.y()); } view2->slotPreviewModeChanged(d->editor->previewMode()); } themeChanged(); updateExposureSettings(); updateICCSettings(); setToolInfoMessage(QString()); connect(d->editor, SIGNAL(signalPreviewModeChanged(int)), d->tool, SLOT(slotPreviewModeChanged())); connect(d->tool, SIGNAL(okClicked()), this, SLOT(slotToolApplied())); d->tool->init(); } void EditorToolIface::unLoadTool() { if (!d->tool) { return; } // To restore zoom level and position accordingly with zoomable preview. ImageRegionWidget* const view2 = dynamic_cast(d->tool->toolView()); if (view2) { if (view2->layout()->isFitToWindow()) { d->editor->editorStackView()->canvas()->fitToWindow(); } else { d->editor->editorStackView()->canvas()->layout()->setZoomFactor(view2->layout()->zoomFactor()); QPoint tl = view2->visibleArea().topLeft(); d->editor->editorStackView()->canvas()->setContentsPos(tl.x(), tl.y()); } } d->editor->editorStackView()->setViewMode(EditorStackView::CanvasMode); d->editor->editorStackView()->setToolView(nullptr); d->editor->rightSideBar()->deleteTab(d->tool->toolSettings()); d->editor->rightSideBar()->appendTab(d->toolsIconView, QIcon::fromTheme(QLatin1String("document-edit")), i18n("Tools")); d->editor->rightSideBar()->setActiveTab(d->lastActiveTab); if (d->splitterSize > 0) { d->editor->sidebarSplitter()->setSize(d->editor->rightSideBar(), d->splitterSize); } else { d->editor->rightSideBar()->shrink(); } d->editor->toggleActions(true); d->editor->toggleToolActions(); d->editor->slotUpdateItemInfo(); d->editor->setPreviewModeMask(PreviewToolBar::NoPreviewMode); delete d->tool; d->tool = nullptr; // Reset info label in status bar with canvas selection info. + d->editor->slotSelected(!d->editor->m_canvas->getSelectedArea().isNull()); d->editor->editorStackView()->canvas()->layout()->updateZoomAndSize(); } void EditorToolIface::setToolInfoMessage(const QString& txt) { d->editor->setToolInfoMessage(txt); } void EditorToolIface::setToolStartProgress(const QString& toolName) { d->editor->setToolStartProgress(toolName); d->editor->toggleZoomActions(!d->editor->editorStackView()->isZoomablePreview()); } void EditorToolIface::setToolProgress(int progress) { d->editor->setToolProgress(progress); } void EditorToolIface::setToolStopProgress() { d->editor->setToolStopProgress(); d->editor->toggleZoomActions(d->editor->editorStackView()->isZoomablePreview()); } void EditorToolIface::slotToolAborted() { EditorToolThreaded* const tool = dynamic_cast(d->tool); if (tool) { tool->slotAbort(); } } void EditorToolIface::slotCloseTool() { EditorTool* const tool = dynamic_cast(d->tool); if (tool) { tool->slotCloseTool(); } } void EditorToolIface::slotApplyTool() { EditorTool* const tool = dynamic_cast(d->tool); if (tool) { tool->slotApplyTool(); } } void EditorToolIface::setupICC() { d->editor->slotSetupICC(); } void EditorToolIface::themeChanged() { EditorTool* const tool = dynamic_cast(d->tool); if (tool) { tool->setBackgroundColor(d->editor->m_bgColor); } } void EditorToolIface::updateICCSettings() { EditorTool* const tool = dynamic_cast(d->tool); if (tool) { tool->ICCSettingsChanged(); } } void EditorToolIface::updateExposureSettings() { ExposureSettingsContainer* const expoSettings = d->editor->exposureSettings(); d->editor->editorStackView()->canvas()->setExposureSettings(expoSettings); EditorTool* const tool = dynamic_cast(d->tool); if (tool) { tool->exposureSettingsChanged(); } } void EditorToolIface::setPreviewModeMask(int mask) { d->editor->setPreviewModeMask(mask); } void EditorToolIface::slotToolApplied() { emit d->editor->signalToolApplied(); } } // namespace Digikam diff --git a/core/utilities/imageeditor/editor/editorwindow.cpp b/core/utilities/imageeditor/editor/editorwindow.cpp index 8bbf6a749e..a5af7ec4dc 100644 --- a/core/utilities/imageeditor/editor/editorwindow.cpp +++ b/core/utilities/imageeditor/editor/editorwindow.cpp @@ -1,2815 +1,2710 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2006-01-20 * Description : core image editor GUI implementation * * Copyright (C) 2006-2020 by Gilles Caulier * Copyright (C) 2009-2011 by Andi Clemens * Copyright (C) 2015 by Mohamed_Anwer * * 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, 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. * * ============================================================ */ -#include "editorwindow.h" #include "editorwindow_p.h" -// C++ includes - -#include - -// Qt includes - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// KDE includes - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef HAVE_KIO -# include -#endif - -// Local includes - -#include "digikam_debug.h" -#include "digikam_globals.h" -#include "dmessagebox.h" -#include "applicationsettings.h" -#include "actioncategorizedview.h" -#include "canvas.h" -#include "categorizeditemmodel.h" -#include "colorcorrectiondlg.h" -#include "editorcore.h" -#include "dlogoaction.h" -#include "dmetadata.h" -#include "dzoombar.h" -#include "drawdecoderwidget.h" -#include "editorstackview.h" -#include "editortool.h" -#include "editortoolsettings.h" -#include "editortooliface.h" -#include "exposurecontainer.h" -#include "dfileoperations.h" -#include "filereadwritelock.h" -#include "filesaveoptionsbox.h" -#include "filesaveoptionsdlg.h" -#include "iccpostloadingmanager.h" -#include "iccsettings.h" -#include "iccsettingscontainer.h" -#include "icctransform.h" -#include "imagedialog.h" -#include "iofilesettings.h" -#include "metaenginesettings.h" -#include "libsinfodlg.h" -#include "loadingcacheinterface.h" -#include "jpegsettings.h" -#include "pngsettings.h" -#include "savingcontext.h" -#include "sidebar.h" -#include "slideshowsettings.h" -#include "softproofdialog.h" -#include "statusprogressbar.h" -#include "thememanager.h" -#include "thumbnailsize.h" -#include "thumbnailloadthread.h" -#include "versioningpromptusersavedlg.h" -#include "undostate.h" -#include "versionmanager.h" -#include "dfiledialog.h" -#include "dexpanderbox.h" -#include "imageiface.h" - namespace Digikam { EditorWindow::EditorWindow(const QString& name) : DXmlGuiWindow(nullptr), d(new Private) { setConfigGroupName(QLatin1String("ImageViewer Settings")); setObjectName(name); setWindowFlags(Qt::Window); setFullScreenOptions(FS_EDITOR); m_nonDestructive = true; m_contextMenu = nullptr; m_servicesMenu = nullptr; m_serviceAction = nullptr; m_canvas = nullptr; m_openVersionAction = nullptr; m_saveAction = nullptr; m_saveAsAction = nullptr; m_saveCurrentVersionAction = nullptr; m_saveNewVersionAction = nullptr; m_saveNewVersionAsAction = nullptr; m_saveNewVersionInFormatAction = nullptr; m_resLabel = nullptr; m_nameLabel = nullptr; m_exportAction = nullptr; m_revertAction = nullptr; m_discardChangesAction = nullptr; m_fileDeleteAction = nullptr; m_forwardAction = nullptr; m_backwardAction = nullptr; m_firstAction = nullptr; m_lastAction = nullptr; m_applyToolAction = nullptr; m_closeToolAction = nullptr; m_undoAction = nullptr; m_redoAction = nullptr; m_showBarAction = nullptr; m_splitter = nullptr; m_vSplitter = nullptr; m_stackView = nullptr; m_setExifOrientationTag = true; m_editingOriginalImage = true; m_actionEnabledState = false; // Settings containers instance. d->exposureSettings = new ExposureSettingsContainer(); d->toolIface = new EditorToolIface(this); m_IOFileSettings = new IOFileSettings(); //d->waitingLoop = new QEventLoop(this); } EditorWindow::~EditorWindow() { delete m_canvas; delete m_IOFileSettings; delete d->toolIface; delete d->exposureSettings; delete d; } SidebarSplitter* EditorWindow::sidebarSplitter() const { return m_splitter; } EditorStackView* EditorWindow::editorStackView() const { return m_stackView; } ExposureSettingsContainer* EditorWindow::exposureSettings() const { return d->exposureSettings; } void EditorWindow::setupContextMenu() { m_contextMenu = new QMenu(this); addAction2ContextMenu(QLatin1String("editorwindow_fullscreen"), true); addAction2ContextMenu(QLatin1String("options_show_menubar"), true); m_contextMenu->addSeparator(); // -------------------------------------------------------- addAction2ContextMenu(QLatin1String("editorwindow_backward"), true); addAction2ContextMenu(QLatin1String("editorwindow_forward"), true); m_contextMenu->addSeparator(); // -------------------------------------------------------- addAction2ContextMenu(QLatin1String("editorwindow_slideshow"), true); addAction2ContextMenu(QLatin1String("editorwindow_transform_rotateleft"), true); addAction2ContextMenu(QLatin1String("editorwindow_transform_rotateright"), true); addAction2ContextMenu(QLatin1String("editorwindow_transform_crop"), true); m_contextMenu->addSeparator(); // -------------------------------------------------------- addAction2ContextMenu(QLatin1String("editorwindow_delete"), true); } void EditorWindow::setupStandardConnections() { connect(m_stackView, SIGNAL(signalToggleOffFitToWindow()), this, SLOT(slotToggleOffFitToWindow())); // -- Canvas connections ------------------------------------------------ connect(m_canvas, SIGNAL(signalShowNextImage()), this, SLOT(slotForward())); connect(m_canvas, SIGNAL(signalShowPrevImage()), this, SLOT(slotBackward())); connect(m_canvas, SIGNAL(signalRightButtonClicked()), this, SLOT(slotContextMenu())); connect(m_stackView, SIGNAL(signalZoomChanged(bool,bool,double)), this, SLOT(slotZoomChanged(bool,bool,double))); connect(m_canvas, SIGNAL(signalChanged()), this, SLOT(slotChanged())); connect(m_canvas, SIGNAL(signalAddedDropedItems(QDropEvent*)), this, SLOT(slotAddedDropedItems(QDropEvent*))); connect(m_canvas->interface(), SIGNAL(signalUndoStateChanged()), this, SLOT(slotUndoStateChanged())); connect(m_canvas, SIGNAL(signalSelected(bool)), this, SLOT(slotSelected(bool))); connect(m_canvas, SIGNAL(signalPrepareToLoad()), this, SLOT(slotPrepareToLoad())); connect(m_canvas, SIGNAL(signalLoadingStarted(QString)), this, SLOT(slotLoadingStarted(QString))); connect(m_canvas, SIGNAL(signalLoadingFinished(QString,bool)), this, SLOT(slotLoadingFinished(QString,bool))); connect(m_canvas, SIGNAL(signalLoadingProgress(QString,float)), this, SLOT(slotLoadingProgress(QString,float))); connect(m_canvas, SIGNAL(signalSavingStarted(QString)), this, SLOT(slotSavingStarted(QString))); connect(m_canvas, SIGNAL(signalSavingFinished(QString,bool)), this, SLOT(slotSavingFinished(QString,bool))); connect(m_canvas, SIGNAL(signalSavingProgress(QString,float)), this, SLOT(slotSavingProgress(QString,float))); connect(m_canvas, SIGNAL(signalSelectionChanged(QRect)), this, SLOT(slotSelectionChanged(QRect))); connect(m_canvas, SIGNAL(signalSelectionSetText(QRect)), this, SLOT(slotSelectionSetText(QRect))); connect(m_canvas->interface(), SIGNAL(signalFileOriginChanged(QString)), this, SLOT(slotFileOriginChanged(QString))); // -- status bar connections -------------------------------------- connect(m_nameLabel, SIGNAL(signalCancelButtonPressed()), this, SLOT(slotNameLabelCancelButtonPressed())); connect(m_nameLabel, SIGNAL(signalCancelButtonPressed()), d->toolIface, SLOT(slotToolAborted())); // -- Icc settings connections -------------------------------------- connect(IccSettings::instance(), SIGNAL(settingsChanged()), this, SLOT(slotColorManagementOptionsChanged())); } void EditorWindow::setupStandardActions() { // -- Standard 'File' menu actions --------------------------------------------- KActionCollection* const ac = actionCollection(); m_backwardAction = buildStdAction(StdBackAction, this, SLOT(slotBackward()), this); ac->addAction(QLatin1String("editorwindow_backward"), m_backwardAction); ac->setDefaultShortcuts(m_backwardAction, QList() << Qt::Key_PageUp << Qt::Key_Backspace << Qt::Key_Up << Qt::Key_Left); m_backwardAction->setEnabled(false); m_forwardAction = buildStdAction(StdForwardAction, this, SLOT(slotForward()), this); ac->addAction(QLatin1String("editorwindow_forward"), m_forwardAction); ac->setDefaultShortcuts(m_forwardAction, QList() << Qt::Key_PageDown << Qt::Key_Space << Qt::Key_Down << Qt::Key_Right); m_forwardAction->setEnabled(false); m_firstAction = new QAction(QIcon::fromTheme(QLatin1String("go-first")), i18n("&First"), this); connect(m_firstAction, SIGNAL(triggered()), this, SLOT(slotFirst())); ac->addAction(QLatin1String("editorwindow_first"), m_firstAction); ac->setDefaultShortcuts(m_firstAction, QList() << Qt::CTRL + Qt::Key_Home); m_firstAction->setEnabled(false); m_lastAction = new QAction(QIcon::fromTheme(QLatin1String("go-last")), i18n("&Last"), this); connect(m_lastAction, SIGNAL(triggered()), this, SLOT(slotLast())); ac->addAction(QLatin1String("editorwindow_last"), m_lastAction); ac->setDefaultShortcuts(m_lastAction, QList() << Qt::CTRL + Qt::Key_End); m_lastAction->setEnabled(false); m_openVersionAction = new QAction(QIcon::fromTheme(QLatin1String("view-preview")), i18nc("@action", "Open Original"), this); connect(m_openVersionAction, SIGNAL(triggered()), this, SLOT(slotOpenOriginal())); ac->addAction(QLatin1String("editorwindow_openversion"), m_openVersionAction); ac->setDefaultShortcuts(m_openVersionAction, QList() << Qt::CTRL + Qt::Key_End); m_saveAction = buildStdAction(StdSaveAction, this, SLOT(saveOrSaveAs()), this); ac->addAction(QLatin1String("editorwindow_save"), m_saveAction); m_saveAsAction = buildStdAction(StdSaveAsAction, this, SLOT(saveAs()), this); ac->addAction(QLatin1String("editorwindow_saveas"), m_saveAsAction); m_saveCurrentVersionAction = new QAction(QIcon::fromTheme(QLatin1String("dialog-ok-apply")), i18nc("@action Save changes to current version", "Save Changes"), this); m_saveCurrentVersionAction->setToolTip(i18nc("@info:tooltip", "Save the modifications to the current version of the file")); connect(m_saveCurrentVersionAction, SIGNAL(triggered()), this, SLOT(saveCurrentVersion())); ac->addAction(QLatin1String("editorwindow_savecurrentversion"), m_saveCurrentVersionAction); m_saveNewVersionAction = new KToolBarPopupAction(QIcon::fromTheme(QLatin1String("list-add")), i18nc("@action Save changes to a newly created version", "Save As New Version"), this); m_saveNewVersionAction->setToolTip(i18nc("@info:tooltip", "Save the current modifications to a new version of the file")); connect(m_saveNewVersionAction, SIGNAL(triggered()), this, SLOT(saveNewVersion())); ac->addAction(QLatin1String("editorwindow_savenewversion"), m_saveNewVersionAction); QAction* const m_saveNewVersionAsAction = new QAction(QIcon::fromTheme(QLatin1String("document-save-as")), i18nc("@action Save changes to a newly created version, specifying the filename and format", "Save New Version As..."), this); m_saveNewVersionAsAction->setToolTip(i18nc("@info:tooltip", "Save the current modifications to a new version of the file, " "specifying the filename and format")); connect(m_saveNewVersionAsAction, SIGNAL(triggered()), this, SLOT(saveNewVersionAs())); m_saveNewVersionInFormatAction = new QMenu(i18nc("@action Save As New Version...Save in format...", "Save in Format"), this); m_saveNewVersionInFormatAction->setIcon(QIcon::fromTheme(QLatin1String("view-preview"))); d->plugNewVersionInFormatAction(this, m_saveNewVersionInFormatAction, i18nc("@action:inmenu", "JPEG"), QLatin1String("JPG")); d->plugNewVersionInFormatAction(this, m_saveNewVersionInFormatAction, i18nc("@action:inmenu", "TIFF"), QLatin1String("TIFF")); d->plugNewVersionInFormatAction(this, m_saveNewVersionInFormatAction, i18nc("@action:inmenu", "PNG"), QLatin1String("PNG")); d->plugNewVersionInFormatAction(this, m_saveNewVersionInFormatAction, i18nc("@action:inmenu", "PGF"), QLatin1String("PGF")); #ifdef HAVE_JASPER d->plugNewVersionInFormatAction(this, m_saveNewVersionInFormatAction, i18nc("@action:inmenu", "JPEG 2000"), QLatin1String("JP2")); #endif // HAVE_JASPER #ifdef HAVE_X265 d->plugNewVersionInFormatAction(this, m_saveNewVersionInFormatAction, i18nc("@action:inmenu", "HEIC"), QLatin1String("HEIC")); #endif // HAVE_X265 m_saveNewVersionAction->menu()->addAction(m_saveNewVersionAsAction); m_saveNewVersionAction->menu()->addAction(m_saveNewVersionInFormatAction->menuAction()); // This also triggers saveAs, but in the context of non-destructive we want a slightly different appearance m_exportAction = new QAction(QIcon::fromTheme(QLatin1String("document-export")), i18nc("@action", "Export"), this); m_exportAction->setToolTip(i18nc("@info:tooltip", "Save the file in a folder outside your collection")); connect(m_exportAction, SIGNAL(triggered()), this, SLOT(saveAs())); ac->addAction(QLatin1String("editorwindow_export"), m_exportAction); ac->setDefaultShortcut(m_exportAction, Qt::CTRL + Qt::SHIFT + Qt::Key_E); // NOTE: Gimp shortcut m_revertAction = buildStdAction(StdRevertAction, this, SLOT(slotRevert()), this); ac->addAction(QLatin1String("editorwindow_revert"), m_revertAction); m_discardChangesAction = new QAction(QIcon::fromTheme(QLatin1String("task-reject")), i18nc("@action", "Discard Changes"), this); m_discardChangesAction->setToolTip(i18nc("@info:tooltip", "Discard all current changes to this file")); connect(m_discardChangesAction, SIGNAL(triggered()), this, SLOT(slotDiscardChanges())); ac->addAction(QLatin1String("editorwindow_discardchanges"), m_discardChangesAction); m_openVersionAction->setEnabled(false); m_saveAction->setEnabled(false); m_saveAsAction->setEnabled(false); m_saveCurrentVersionAction->setEnabled(false); m_saveNewVersionAction->setEnabled(false); m_revertAction->setEnabled(false); m_discardChangesAction->setEnabled(false); d->openWithAction = new QAction(QIcon::fromTheme(QLatin1String("preferences-desktop-filetype-association")), i18n("Open With Default Application"), this); d->openWithAction->setWhatsThis(i18n("Open the item with default assigned application.")); connect(d->openWithAction, SIGNAL(triggered()), this, SLOT(slotFileWithDefaultApplication())); ac->addAction(QLatin1String("open_with_default_application"), d->openWithAction); ac->setDefaultShortcut(d->openWithAction, Qt::CTRL + Qt::Key_F4); d->openWithAction->setEnabled(false); m_fileDeleteAction = new QAction(QIcon::fromTheme(QLatin1String("user-trash-full")), i18nc("Non-pluralized", "Move to Trash"), this); connect(m_fileDeleteAction, SIGNAL(triggered()), this, SLOT(slotDeleteCurrentItem())); ac->addAction(QLatin1String("editorwindow_delete"), m_fileDeleteAction); ac->setDefaultShortcut(m_fileDeleteAction, Qt::Key_Delete); m_fileDeleteAction->setEnabled(false); QAction* const closeAction = buildStdAction(StdCloseAction, this, SLOT(close()), this); ac->addAction(QLatin1String("editorwindow_close"), closeAction); // -- Standard 'Edit' menu actions --------------------------------------------- d->copyAction = buildStdAction(StdCopyAction, m_canvas, SLOT(slotCopy()), this); ac->addAction(QLatin1String("editorwindow_copy"), d->copyAction); d->copyAction->setEnabled(false); m_undoAction = new KToolBarPopupAction(QIcon::fromTheme(QLatin1String("edit-undo")), i18n("Undo"), this); m_undoAction->setEnabled(false); ac->addAction(QLatin1String("editorwindow_undo"), m_undoAction); ac->setDefaultShortcuts(m_undoAction, QList() << Qt::CTRL + Qt::Key_Z); connect(m_undoAction->menu(), SIGNAL(aboutToShow()), this, SLOT(slotAboutToShowUndoMenu())); // connect simple undo action connect(m_undoAction, &QAction::triggered, this, [this]() { m_canvas->slotUndo(1); }); m_redoAction = new KToolBarPopupAction(QIcon::fromTheme(QLatin1String("edit-redo")), i18n("Redo"), this); m_redoAction->setEnabled(false); ac->addAction(QLatin1String("editorwindow_redo"), m_redoAction); ac->setDefaultShortcuts(m_redoAction, QList() << Qt::CTRL + Qt::SHIFT + Qt::Key_Z); connect(m_redoAction->menu(), SIGNAL(aboutToShow()), this, SLOT(slotAboutToShowRedoMenu())); // connect simple redo action connect(m_redoAction, &QAction::triggered, this, [this]() { m_canvas->slotRedo(1); }); d->selectAllAction = new QAction(i18nc("Create a selection containing the full image", "Select All"), this); connect(d->selectAllAction, SIGNAL(triggered()), m_canvas, SLOT(slotSelectAll())); ac->addAction(QLatin1String("editorwindow_selectAll"), d->selectAllAction); ac->setDefaultShortcut(d->selectAllAction, Qt::CTRL + Qt::Key_A); d->selectNoneAction = new QAction(i18n("Select None"), this); connect(d->selectNoneAction, SIGNAL(triggered()), m_canvas, SLOT(slotSelectNone())); ac->addAction(QLatin1String("editorwindow_selectNone"), d->selectNoneAction); ac->setDefaultShortcut(d->selectNoneAction, Qt::CTRL + Qt::SHIFT + Qt::Key_A); // -- Standard 'View' menu actions --------------------------------------------- d->zoomPlusAction = buildStdAction(StdZoomInAction, this, SLOT(slotIncreaseZoom()), this); ac->addAction(QLatin1String("editorwindow_zoomplus"), d->zoomPlusAction); d->zoomMinusAction = buildStdAction(StdZoomOutAction, this, SLOT(slotDecreaseZoom()), this); ac->addAction(QLatin1String("editorwindow_zoomminus"), d->zoomMinusAction); d->zoomTo100percents = new QAction(QIcon::fromTheme(QLatin1String("zoom-original")), i18n("Zoom to 100%"), this); connect(d->zoomTo100percents, SIGNAL(triggered()), this, SLOT(slotZoomTo100Percents())); ac->addAction(QLatin1String("editorwindow_zoomto100percents"), d->zoomTo100percents); ac->setDefaultShortcut(d->zoomTo100percents, Qt::CTRL + Qt::Key_Period); d->zoomFitToWindowAction = new QAction(QIcon::fromTheme(QLatin1String("zoom-fit-best")), i18n("Fit to &Window"), this); d->zoomFitToWindowAction->setCheckable(true); connect(d->zoomFitToWindowAction, SIGNAL(triggered()), this, SLOT(slotToggleFitToWindow())); ac->addAction(QLatin1String("editorwindow_zoomfit2window"), d->zoomFitToWindowAction); ac->setDefaultShortcut(d->zoomFitToWindowAction, Qt::ALT + Qt::CTRL + Qt::Key_E); d->zoomFitToSelectAction = new QAction(QIcon::fromTheme(QLatin1String("zoom-select-fit")), i18n("Fit to &Selection"), this); connect(d->zoomFitToSelectAction, SIGNAL(triggered()), this, SLOT(slotFitToSelect())); ac->addAction(QLatin1String("editorwindow_zoomfit2select"), d->zoomFitToSelectAction); ac->setDefaultShortcut(d->zoomFitToSelectAction, Qt::ALT + Qt::CTRL + Qt::Key_S); // NOTE: Photoshop 7 use ALT+CTRL+0 d->zoomFitToSelectAction->setEnabled(false); d->zoomFitToSelectAction->setWhatsThis(i18n("This option can be used to zoom the image to the " "current selection area.")); // ********************************************************** QList actions = DPluginLoader::instance()->pluginsActions(DPluginAction::Generic, this); foreach (DPluginAction* const ac, actions) { ac->setEnabled(false); } QList actions2 = DPluginLoader::instance()->pluginsActions(DPluginAction::Editor, this); foreach (DPluginAction* const ac, actions2) { ac->setEnabled(false); } // -------------------------------------------------------- createFullScreenAction(QLatin1String("editorwindow_fullscreen")); createSidebarActions(); d->slideShowAction = new QAction(QIcon::fromTheme(QLatin1String("view-presentation")), i18n("Slideshow"), this); connect(d->slideShowAction, SIGNAL(triggered()), this, SLOT(slotToggleSlideShow())); ac->addAction(QLatin1String("editorwindow_slideshow"), d->slideShowAction); ac->setDefaultShortcut(d->slideShowAction, Qt::Key_F9); d->viewUnderExpoAction = new QAction(QIcon::fromTheme(QLatin1String("underexposure")), i18n("Under-Exposure Indicator"), this); d->viewUnderExpoAction->setCheckable(true); d->viewUnderExpoAction->setWhatsThis(i18n("Set this option to display black " "overlaid on the image. This will help you to avoid " "under-exposing the image.")); connect(d->viewUnderExpoAction, SIGNAL(triggered(bool)), this, SLOT(slotSetUnderExposureIndicator(bool))); ac->addAction(QLatin1String("editorwindow_underexposure"), d->viewUnderExpoAction); ac->setDefaultShortcut(d->viewUnderExpoAction, Qt::Key_F10); d->viewOverExpoAction = new QAction(QIcon::fromTheme(QLatin1String("overexposure")), i18n("Over-Exposure Indicator"), this); d->viewOverExpoAction->setCheckable(true); d->viewOverExpoAction->setWhatsThis(i18n("Set this option to display white " "overlaid on the image. This will help you to avoid " "over-exposing the image.")); connect(d->viewOverExpoAction, SIGNAL(triggered(bool)), this, SLOT(slotSetOverExposureIndicator(bool))); ac->addAction(QLatin1String("editorwindow_overexposure"), d->viewOverExpoAction); ac->setDefaultShortcut(d->viewOverExpoAction, Qt::Key_F11); d->viewCMViewAction = new QAction(QIcon::fromTheme(QLatin1String("video-display")), i18n("Color-Managed View"), this); d->viewCMViewAction->setCheckable(true); connect(d->viewCMViewAction, SIGNAL(triggered()), this, SLOT(slotToggleColorManagedView())); ac->addAction(QLatin1String("editorwindow_cmview"), d->viewCMViewAction); ac->setDefaultShortcut(d->viewCMViewAction, Qt::Key_F12); d->softProofOptionsAction = new QAction(QIcon::fromTheme(QLatin1String("printer")), i18n("Soft Proofing Options..."), this); connect(d->softProofOptionsAction, SIGNAL(triggered()), this, SLOT(slotSoftProofingOptions())); ac->addAction(QLatin1String("editorwindow_softproofoptions"), d->softProofOptionsAction); d->viewSoftProofAction = new QAction(QIcon::fromTheme(QLatin1String("document-print-preview")), i18n("Soft Proofing View"), this); d->viewSoftProofAction->setCheckable(true); connect(d->viewSoftProofAction, SIGNAL(triggered()), this, SLOT(slotUpdateSoftProofingState())); ac->addAction(QLatin1String("editorwindow_softproofview"), d->viewSoftProofAction); // -- Standard 'Transform' menu actions --------------------------------------------- d->cropAction = new QAction(QIcon::fromTheme(QLatin1String("transform-crop-and-resize")), i18nc("@action", "Crop to Selection"), this); connect(d->cropAction, SIGNAL(triggered()), m_canvas, SLOT(slotCrop())); d->cropAction->setEnabled(false); d->cropAction->setWhatsThis(i18n("This option can be used to crop the image. " "Select a region of the image to enable this action.")); ac->addAction(QLatin1String("editorwindow_transform_crop"), d->cropAction); ac->setDefaultShortcut(d->cropAction, Qt::CTRL + Qt::Key_X); // -- Standard 'Flip' menu actions --------------------------------------------- d->flipHorizAction = new QAction(QIcon::fromTheme(QLatin1String("object-flip-horizontal")), i18n("Flip Horizontally"), this); connect(d->flipHorizAction, SIGNAL(triggered()), m_canvas, SLOT(slotFlipHoriz())); connect(d->flipHorizAction, SIGNAL(triggered()), this, SLOT(slotFlipHIntoQue())); ac->addAction(QLatin1String("editorwindow_transform_fliphoriz"), d->flipHorizAction); ac->setDefaultShortcut(d->flipHorizAction, Qt::CTRL + Qt::Key_Asterisk); d->flipHorizAction->setEnabled(false); d->flipVertAction = new QAction(QIcon::fromTheme(QLatin1String("object-flip-vertical")), i18n("Flip Vertically"), this); connect(d->flipVertAction, SIGNAL(triggered()), m_canvas, SLOT(slotFlipVert())); connect(d->flipVertAction, SIGNAL(triggered()), this, SLOT(slotFlipVIntoQue())); ac->addAction(QLatin1String("editorwindow_transform_flipvert"), d->flipVertAction); ac->setDefaultShortcut(d->flipVertAction, Qt::CTRL + Qt::Key_Slash); d->flipVertAction->setEnabled(false); // -- Standard 'Rotate' menu actions ---------------------------------------- d->rotateLeftAction = new QAction(QIcon::fromTheme(QLatin1String("object-rotate-left")), i18n("Rotate Left"), this); connect(d->rotateLeftAction, SIGNAL(triggered()), m_canvas, SLOT(slotRotate270())); connect(d->rotateLeftAction, SIGNAL(triggered()), this, SLOT(slotRotateLeftIntoQue())); ac->addAction(QLatin1String("editorwindow_transform_rotateleft"), d->rotateLeftAction); ac->setDefaultShortcut(d->rotateLeftAction, Qt::CTRL + Qt::SHIFT + Qt::Key_Left); d->rotateLeftAction->setEnabled(false); d->rotateRightAction = new QAction(QIcon::fromTheme(QLatin1String("object-rotate-right")), i18n("Rotate Right"), this); connect(d->rotateRightAction, SIGNAL(triggered()), m_canvas, SLOT(slotRotate90())); connect(d->rotateRightAction, SIGNAL(triggered()), this, SLOT(slotRotateRightIntoQue())); ac->addAction(QLatin1String("editorwindow_transform_rotateright"), d->rotateRightAction); ac->setDefaultShortcut(d->rotateRightAction, Qt::CTRL + Qt::SHIFT + Qt::Key_Right); d->rotateRightAction->setEnabled(false); m_showBarAction = thumbBar()->getToggleAction(this); ac->addAction(QLatin1String("editorwindow_showthumbs"), m_showBarAction); ac->setDefaultShortcut(m_showBarAction, Qt::CTRL + Qt::Key_T); // Provides a menu entry that allows showing/hiding the toolbar(s) setStandardToolBarMenuEnabled(true); // Provides a menu entry that allows showing/hiding the statusbar createStandardStatusBarAction(); // Standard 'Configure' menu actions createSettingsActions(); // --------------------------------------------------------------------------------- ThemeManager::instance()->registerThemeActions(this); connect(ThemeManager::instance(), SIGNAL(signalThemeChanged()), this, SLOT(slotThemeChanged())); // -- Keyboard-only actions -------------------------------------------------------- QAction* const altBackwardAction = new QAction(i18n("Previous Image"), this); ac->addAction(QLatin1String("editorwindow_backward_shift_space"), altBackwardAction); ac->setDefaultShortcut(altBackwardAction, Qt::SHIFT + Qt::Key_Space); connect(altBackwardAction, SIGNAL(triggered()), this, SLOT(slotBackward())); // -- Tool control actions --------------------------------------------------------- m_applyToolAction = new QAction(QIcon::fromTheme(QLatin1String("dialog-ok-apply")), i18n("OK"), this); ac->addAction(QLatin1String("editorwindow_applytool"), m_applyToolAction); ac->setDefaultShortcut(m_applyToolAction, Qt::Key_Return); connect(m_applyToolAction, SIGNAL(triggered()), this, SLOT(slotApplyTool())); m_closeToolAction = new QAction(QIcon::fromTheme(QLatin1String("dialog-cancel")), i18n("Cancel"), this); ac->addAction(QLatin1String("editorwindow_closetool"), m_closeToolAction); ac->setDefaultShortcut(m_closeToolAction, Qt::Key_Escape); connect(m_closeToolAction, SIGNAL(triggered()), this, SLOT(slotCloseTool())); toggleNonDestructiveActions(); toggleToolActions(); } void EditorWindow::setupStatusBar() { m_nameLabel = new StatusProgressBar(statusBar()); m_nameLabel->setAlignment(Qt::AlignCenter); statusBar()->addWidget(m_nameLabel, 100); d->infoLabel = new DAdjustableLabel(statusBar()); d->infoLabel->setAdjustedText(i18n("No selection")); d->infoLabel->setAlignment(Qt::AlignCenter); statusBar()->addWidget(d->infoLabel, 100); d->infoLabel->setToolTip(i18n("Information about current image selection")); m_resLabel = new DAdjustableLabel(statusBar()); m_resLabel->setAlignment(Qt::AlignCenter); statusBar()->addWidget(m_resLabel, 100); m_resLabel->setToolTip(i18n("Information about image size")); d->zoomBar = new DZoomBar(statusBar()); d->zoomBar->setZoomToFitAction(d->zoomFitToWindowAction); d->zoomBar->setZoomTo100Action(d->zoomTo100percents); d->zoomBar->setZoomPlusAction(d->zoomPlusAction); d->zoomBar->setZoomMinusAction(d->zoomMinusAction); d->zoomBar->setBarMode(DZoomBar::PreviewZoomCtrl); statusBar()->addPermanentWidget(d->zoomBar); connect(d->zoomBar, SIGNAL(signalZoomSliderChanged(int)), m_stackView, SLOT(slotZoomSliderChanged(int))); connect(d->zoomBar, SIGNAL(signalZoomValueEdited(double)), m_stackView, SLOT(setZoomFactor(double))); d->previewToolBar = new PreviewToolBar(statusBar()); d->previewToolBar->registerMenuActionGroup(this); d->previewToolBar->setEnabled(false); statusBar()->addPermanentWidget(d->previewToolBar); connect(d->previewToolBar, SIGNAL(signalPreviewModeChanged(int)), this, SIGNAL(signalPreviewModeChanged(int))); QWidget* const buttonsBox = new QWidget(statusBar()); QHBoxLayout* const hlay = new QHBoxLayout(buttonsBox); QButtonGroup* const buttonsGrp = new QButtonGroup(buttonsBox); buttonsGrp->setExclusive(false); d->underExposureIndicator = new QToolButton(buttonsBox); d->underExposureIndicator->setDefaultAction(d->viewUnderExpoAction); d->underExposureIndicator->setFocusPolicy(Qt::NoFocus); d->overExposureIndicator = new QToolButton(buttonsBox); d->overExposureIndicator->setDefaultAction(d->viewOverExpoAction); d->overExposureIndicator->setFocusPolicy(Qt::NoFocus); d->cmViewIndicator = new QToolButton(buttonsBox); d->cmViewIndicator->setDefaultAction(d->viewCMViewAction); d->cmViewIndicator->setFocusPolicy(Qt::NoFocus); buttonsGrp->addButton(d->underExposureIndicator); buttonsGrp->addButton(d->overExposureIndicator); buttonsGrp->addButton(d->cmViewIndicator); hlay->setSpacing(0); hlay->setContentsMargins(QMargins()); hlay->addWidget(d->underExposureIndicator); hlay->addWidget(d->overExposureIndicator); hlay->addWidget(d->cmViewIndicator); statusBar()->addPermanentWidget(buttonsBox); } void EditorWindow::slotAboutToShowUndoMenu() { m_undoAction->menu()->clear(); QStringList titles = m_canvas->interface()->getUndoHistory(); for (int i = 0; i < titles.size(); ++i) { QAction* const action = m_undoAction->menu()->addAction(titles.at(i)); int id = i + 1; connect(action, &QAction::triggered, this, [this, id]() { m_canvas->slotUndo(id); }); } } void EditorWindow::slotAboutToShowRedoMenu() { m_redoAction->menu()->clear(); QStringList titles = m_canvas->interface()->getRedoHistory(); for (int i = 0; i < titles.size(); ++i) { QAction* const action = m_redoAction->menu()->addAction(titles.at(i)); int id = i + 1; connect(action, &QAction::triggered, this, [this, id]() { m_canvas->slotRedo(id); }); } } void EditorWindow::slotIncreaseZoom() { m_stackView->increaseZoom(); } void EditorWindow::slotDecreaseZoom() { m_stackView->decreaseZoom(); } void EditorWindow::slotToggleFitToWindow() { d->zoomPlusAction->setEnabled(true); d->zoomBar->setEnabled(true); d->zoomMinusAction->setEnabled(true); m_stackView->toggleFitToWindow(); } void EditorWindow::slotFitToSelect() { d->zoomPlusAction->setEnabled(true); d->zoomBar->setEnabled(true); d->zoomMinusAction->setEnabled(true); m_stackView->fitToSelect(); } void EditorWindow::slotZoomTo100Percents() { d->zoomPlusAction->setEnabled(true); d->zoomBar->setEnabled(true); d->zoomMinusAction->setEnabled(true); m_stackView->zoomTo100Percent(); } void EditorWindow::slotZoomChanged(bool isMax, bool isMin, double zoom) { //qCDebug(DIGIKAM_GENERAL_LOG) << "EditorWindow::slotZoomChanged"; d->zoomPlusAction->setEnabled(!isMax); d->zoomMinusAction->setEnabled(!isMin); double zmin = m_stackView->zoomMin(); double zmax = m_stackView->zoomMax(); d->zoomBar->setZoom(zoom, zmin, zmax); } void EditorWindow::slotToggleOffFitToWindow() { d->zoomFitToWindowAction->blockSignals(true); d->zoomFitToWindowAction->setChecked(false); d->zoomFitToWindowAction->blockSignals(false); } void EditorWindow::readStandardSettings() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(configGroupName()); // Restore Canvas layout if (group.hasKey(d->configVerticalSplitterSizesEntry) && m_vSplitter) { QByteArray state; state = group.readEntry(d->configVerticalSplitterStateEntry, state); m_vSplitter->restoreState(QByteArray::fromBase64(state)); } // Restore full screen Mode readFullScreenSettings(group); // Restore Auto zoom action bool autoZoom = group.readEntry(d->configAutoZoomEntry, true); if (autoZoom) { d->zoomFitToWindowAction->trigger(); } slotSetUnderExposureIndicator(group.readEntry(d->configUnderExposureIndicatorEntry, false)); slotSetOverExposureIndicator(group.readEntry(d->configOverExposureIndicatorEntry, false)); d->previewToolBar->readSettings(group); } void EditorWindow::applyStandardSettings() { applyColorManagementSettings(); d->toolIface->updateICCSettings(); applyIOSettings(); // -- GUI Settings ------------------------------------------------------- KConfigGroup group = KSharedConfig::openConfig()->group(configGroupName()); d->legacyUpdateSplitterState(group); m_splitter->restoreState(group); readFullScreenSettings(group); slotThemeChanged(); // -- Exposure Indicators Settings --------------------------------------- d->exposureSettings->underExposureColor = group.readEntry(d->configUnderExposureColorEntry, QColor(Qt::white)); d->exposureSettings->underExposurePercent = group.readEntry(d->configUnderExposurePercentsEntry, 1.0); d->exposureSettings->overExposureColor = group.readEntry(d->configOverExposureColorEntry, QColor(Qt::black)); d->exposureSettings->overExposurePercent = group.readEntry(d->configOverExposurePercentsEntry, 1.0); d->exposureSettings->exposureIndicatorMode = group.readEntry(d->configExpoIndicatorModeEntry, true); d->toolIface->updateExposureSettings(); // -- Metadata Settings -------------------------------------------------- MetaEngineSettingsContainer writeSettings = MetaEngineSettings::instance()->settings(); m_setExifOrientationTag = writeSettings.exifSetOrientation; m_canvas->setExifOrient(writeSettings.exifRotate); } void EditorWindow::applyIOSettings() { // -- JPEG, PNG, TIFF, JPEG2000, PGF files format settings ---------------- KConfigGroup group = KSharedConfig::openConfig()->group(configGroupName()); m_IOFileSettings->JPEGCompression = JPEGSettings::convertCompressionForLibJpeg(group.readEntry(d->configJpegCompressionEntry, 75)); m_IOFileSettings->JPEGSubSampling = group.readEntry(d->configJpegSubSamplingEntry, 1); // Medium subsampling m_IOFileSettings->PNGCompression = PNGSettings::convertCompressionForLibPng(group.readEntry(d->configPngCompressionEntry, 1)); // TIFF compression setting. m_IOFileSettings->TIFFCompression = group.readEntry(d->configTiffCompressionEntry, false); // JPEG2000 quality slider settings : 1 - 100 m_IOFileSettings->JPEG2000Compression = group.readEntry(d->configJpeg2000CompressionEntry, 100); // JPEG2000 LossLess setting. m_IOFileSettings->JPEG2000LossLess = group.readEntry(d->configJpeg2000LossLessEntry, true); // PGF quality slider settings : 1 - 9 m_IOFileSettings->PGFCompression = group.readEntry(d->configPgfCompressionEntry, 3); // PGF LossLess setting. m_IOFileSettings->PGFLossLess = group.readEntry(d->configPgfLossLessEntry, true); // -- RAW images decoding settings ------------------------------------------------------ m_IOFileSettings->useRAWImport = group.readEntry(d->configUseRawImportToolEntry, false); m_IOFileSettings->rawImportToolIid = group.readEntry(d->configRawImportToolIidEntry, QString::fromLatin1("org.kde.digikam.plugin.rawimport.Native")); DRawDecoderWidget::readSettings(m_IOFileSettings->rawDecodingSettings.rawPrm, group); // Raw Color Management settings: // If digiKam Color Management is enabled, no need to correct color of decoded RAW image, // else, sRGB color workspace will be used. ICCSettingsContainer settings = IccSettings::instance()->settings(); if (settings.enableCM) { if (settings.defaultUncalibratedBehavior & ICCSettingsContainer::AutomaticColors) { m_IOFileSettings->rawDecodingSettings.rawPrm.outputColorSpace = DRawDecoderSettings::CUSTOMOUTPUTCS; m_IOFileSettings->rawDecodingSettings.rawPrm.outputProfile = settings.workspaceProfile; } else { m_IOFileSettings->rawDecodingSettings.rawPrm.outputColorSpace = DRawDecoderSettings::RAWCOLOR; } } else { m_IOFileSettings->rawDecodingSettings.rawPrm.outputColorSpace = DRawDecoderSettings::SRGB; } } void EditorWindow::applyColorManagementSettings() { ICCSettingsContainer settings = IccSettings::instance()->settings(); d->toolIface->updateICCSettings(); m_canvas->setICCSettings(settings); d->viewCMViewAction->blockSignals(true); d->viewCMViewAction->setEnabled(settings.enableCM); d->viewCMViewAction->setChecked(settings.useManagedView); setColorManagedViewIndicatorToolTip(settings.enableCM, settings.useManagedView); d->viewCMViewAction->blockSignals(false); d->viewSoftProofAction->setEnabled(settings.enableCM && !settings.defaultProofProfile.isEmpty()); d->softProofOptionsAction->setEnabled(settings.enableCM); } void EditorWindow::saveStandardSettings() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(configGroupName()); group.writeEntry(d->configAutoZoomEntry, d->zoomFitToWindowAction->isChecked()); m_splitter->saveState(group); if (m_vSplitter) { group.writeEntry(d->configVerticalSplitterStateEntry, m_vSplitter->saveState().toBase64()); } group.writeEntry("Show Thumbbar", thumbBar()->shouldBeVisible()); group.writeEntry(d->configUnderExposureIndicatorEntry, d->exposureSettings->underExposureIndicator); group.writeEntry(d->configOverExposureIndicatorEntry, d->exposureSettings->overExposureIndicator); d->previewToolBar->writeSettings(group); config->sync(); } /** Method used by Editor Tools. Only tools based on imageregionwidget support zooming. TODO: Fix this behavior when editor tool preview widgets will be factored. */ void EditorWindow::toggleZoomActions(bool val) { d->zoomMinusAction->setEnabled(val); d->zoomPlusAction->setEnabled(val); d->zoomTo100percents->setEnabled(val); d->zoomFitToWindowAction->setEnabled(val); d->zoomBar->setEnabled(val); } void EditorWindow::readSettings() { readStandardSettings(); } void EditorWindow::saveSettings() { saveStandardSettings(); } void EditorWindow::toggleActions(bool val) { toggleStandardActions(val); } bool EditorWindow::actionEnabledState() const { return m_actionEnabledState; } void EditorWindow::toggleStandardActions(bool val) { d->zoomFitToSelectAction->setEnabled(val); toggleZoomActions(val); m_actionEnabledState = val; m_forwardAction->setEnabled(val); m_backwardAction->setEnabled(val); m_firstAction->setEnabled(val); m_lastAction->setEnabled(val); d->rotateLeftAction->setEnabled(val); d->rotateRightAction->setEnabled(val); d->flipHorizAction->setEnabled(val); d->flipVertAction->setEnabled(val); m_fileDeleteAction->setEnabled(val); m_saveAsAction->setEnabled(val); d->openWithAction->setEnabled(val); m_exportAction->setEnabled(val); d->selectAllAction->setEnabled(val); d->selectNoneAction->setEnabled(val); d->slideShowAction->setEnabled(val); QList actions = DPluginLoader::instance()->pluginsActions(DPluginAction::Generic, this); foreach (DPluginAction* const ac, actions) { ac->setEnabled(val); } // these actions are special: They are turned off if val is false, // but if val is true, they may be turned on or off. if (val) { // Update actions by retrieving current values slotUndoStateChanged(); } else { m_openVersionAction->setEnabled(false); m_revertAction->setEnabled(false); m_saveAction->setEnabled(false); m_saveCurrentVersionAction->setEnabled(false); m_saveNewVersionAction->setEnabled(false); m_discardChangesAction->setEnabled(false); m_undoAction->setEnabled(false); m_redoAction->setEnabled(false); } // Editor Tools actions QList actions2 = DPluginLoader::instance()->pluginsActions(DPluginAction::Editor, this); foreach (DPluginAction* const ac, actions2) { ac->setEnabled(val); } } void EditorWindow::toggleNonDestructiveActions() { m_saveAction->setVisible(!m_nonDestructive); m_saveAsAction->setVisible(!m_nonDestructive); m_revertAction->setVisible(!m_nonDestructive); m_openVersionAction->setVisible(m_nonDestructive); m_saveCurrentVersionAction->setVisible(m_nonDestructive); m_saveNewVersionAction->setVisible(m_nonDestructive); m_exportAction->setVisible(m_nonDestructive); m_discardChangesAction->setVisible(m_nonDestructive); } void EditorWindow::toggleToolActions(EditorTool* tool) { if (tool) { m_applyToolAction->setText(tool->toolSettings()->button(EditorToolSettings::Ok)->text()); m_applyToolAction->setIcon(tool->toolSettings()->button(EditorToolSettings::Ok)->icon()); m_applyToolAction->setToolTip(tool->toolSettings()->button(EditorToolSettings::Ok)->toolTip()); m_closeToolAction->setText(tool->toolSettings()->button(EditorToolSettings::Cancel)->text()); m_closeToolAction->setIcon(tool->toolSettings()->button(EditorToolSettings::Cancel)->icon()); m_closeToolAction->setToolTip(tool->toolSettings()->button(EditorToolSettings::Cancel)->toolTip()); } m_applyToolAction->setVisible(tool); m_closeToolAction->setVisible(tool); } void EditorWindow::slotLoadingProgress(const QString&, float progress) { m_nameLabel->setProgressValue((int)(progress * 100.0)); } void EditorWindow::slotSavingProgress(const QString&, float progress) { m_nameLabel->setProgressValue((int)(progress * 100.0)); if (m_savingProgressDialog) { m_savingProgressDialog->setValue((int)(progress * 100.0)); } } void EditorWindow::execSavingProgressDialog() { if (m_savingProgressDialog) { return; } m_savingProgressDialog = new QProgressDialog(this); m_savingProgressDialog->setWindowTitle(i18n("Saving image...")); m_savingProgressDialog->setLabelText(i18n("Please wait for the image to be saved...")); m_savingProgressDialog->setAttribute(Qt::WA_DeleteOnClose); m_savingProgressDialog->setAutoClose(true); m_savingProgressDialog->setMinimumDuration(1000); m_savingProgressDialog->setMaximum(100); // we must enter a fully modal dialog, no QEventLoop is sufficient for KWin to accept longer waiting times m_savingProgressDialog->setModal(true); m_savingProgressDialog->exec(); } bool EditorWindow::promptForOverWrite() { QUrl destination = saveDestinationUrl(); if (destination.isLocalFile()) { QFileInfo fi(m_canvas->currentImageFilePath()); QString warnMsg(i18n("About to overwrite file \"%1\"\nAre you sure?", QDir::toNativeSeparators(fi.fileName()))); return (DMessageBox::showContinueCancel(QMessageBox::Warning, this, i18n("Warning"), warnMsg, QLatin1String("editorWindowSaveOverwrite")) == QMessageBox::Yes); } else { // in this case it will handle the overwrite request return true; } } void EditorWindow::slotUndoStateChanged() { UndoState state = m_canvas->interface()->undoState(); // RAW conversion qualifies as a "non-undoable" action // You can save as new version, but cannot undo or revert m_undoAction->setEnabled(state.hasUndo); m_redoAction->setEnabled(state.hasRedo); m_revertAction->setEnabled(state.hasUndoableChanges); m_saveAction->setEnabled(state.hasChanges); m_saveCurrentVersionAction->setEnabled(state.hasChanges); m_saveNewVersionAction->setEnabled(state.hasChanges); m_discardChangesAction->setEnabled(state.hasUndoableChanges); m_openVersionAction->setEnabled(hasOriginalToRestore()); } bool EditorWindow::hasOriginalToRestore() { return m_canvas->interface()->getResolvedInitialHistory().hasOriginalReferredImage(); } DImageHistory EditorWindow::resolvedImageHistory(const DImageHistory& history) { // simple, database-less version DImageHistory r = history; QList::iterator it; for (it = r.entries().begin(); it != r.entries().end(); ++it) { QList::iterator hit; for (hit = it->referredImages.begin(); hit != it->referredImages.end();) { QFileInfo info(hit->m_filePath + QLatin1Char('/') + hit->m_fileName); if (!info.exists()) { hit = it->referredImages.erase(hit); } else { ++hit; } } } return r; } bool EditorWindow::promptUserSave(const QUrl& url, SaveAskMode mode, bool allowCancel) { if (d->currentWindowModalDialog) { d->currentWindowModalDialog->reject(); } if (m_canvas->interface()->undoState().hasUndoableChanges) { // if window is minimized, show it if (isMinimized()) { KWindowSystem::unminimizeWindow(winId()); } bool shallSave = true; bool shallDiscard = false; bool newVersion = false; if (mode == AskIfNeeded) { if (m_nonDestructive) { if (versionManager()->settings().editorClosingMode == VersionManagerSettings::AutoSave) { shallSave = true; } else { QPointer dialog = new VersioningPromptUserSaveDialog(this); dialog->exec(); if (!dialog) { return false; } shallSave = dialog->shallSave() || dialog->newVersion(); shallDiscard = dialog->shallDiscard(); newVersion = dialog->newVersion(); } } else { QString boxMessage; boxMessage = i18nc("@info", "The image %1 has been modified.
" "Do you want to save it?
", url.fileName()); int result; if (allowCancel) { result = QMessageBox::warning(this, qApp->applicationName(), boxMessage, QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); } else { result = QMessageBox::warning(this, qApp->applicationName(), boxMessage, QMessageBox::Save | QMessageBox::Discard); } shallSave = (result == QMessageBox::Save); shallDiscard = (result == QMessageBox::Discard); } } if (shallSave) { bool saving = false; switch (mode) { case AskIfNeeded: if (m_nonDestructive) { if (newVersion) { saving = saveNewVersion(); } else { // will know on its own if new version is required saving = saveCurrentVersion(); } } else { if (m_canvas->isReadOnly()) { saving = saveAs(); } else if (promptForOverWrite()) { saving = save(); } } break; case OverwriteWithoutAsking: if (m_nonDestructive) { if (newVersion) { saving = saveNewVersion(); } else { // will know on its own if new version is required saving = saveCurrentVersion(); } } else { if (m_canvas->isReadOnly()) { saving = saveAs(); } else { saving = save(); } } break; case AlwaysSaveAs: if (m_nonDestructive) { saving = saveNewVersion(); } else { saving = saveAs(); } break; } // save and saveAs return false if they were canceled and did not enter saving at all // In this case, do not call enterWaitingLoop because quitWaitingloop will not be called. if (saving) { // Waiting for asynchronous image file saving operation running in separate thread. m_savingContext.synchronizingState = SavingContext::SynchronousSaving; enterWaitingLoop(); m_savingContext.synchronizingState = SavingContext::NormalSaving; return m_savingContext.synchronousSavingResult; } else { return false; } } else if (shallDiscard) { // Discard m_saveAction->setEnabled(false); return true; } else { return false; } } return true; } bool EditorWindow::promptUserDelete(const QUrl& url) { if (d->currentWindowModalDialog) { d->currentWindowModalDialog->reject(); } if (m_canvas->interface()->undoState().hasUndoableChanges) { // if window is minimized, show it if (isMinimized()) { KWindowSystem::unminimizeWindow(winId()); } QString boxMessage = i18nc("@info", "The image %1 has been modified.
" "All changes will be lost.", url.fileName()); int result = DMessageBox::showContinueCancel(QMessageBox::Warning, this, QString(), boxMessage); if (result == QMessageBox::Cancel) { return false; } } return true; } bool EditorWindow::waitForSavingToComplete() { // avoid reentrancy - return false means we have reentered the loop already. if (m_savingContext.synchronizingState == SavingContext::SynchronousSaving) { return false; } if (m_savingContext.savingState != SavingContext::SavingStateNone) { // Waiting for asynchronous image file saving operation running in separate thread. m_savingContext.synchronizingState = SavingContext::SynchronousSaving; enterWaitingLoop(); m_savingContext.synchronizingState = SavingContext::NormalSaving; } return true; } void EditorWindow::enterWaitingLoop() { //d->waitingLoop->exec(QEventLoop::ExcludeUserInputEvents); execSavingProgressDialog(); } void EditorWindow::quitWaitingLoop() { //d->waitingLoop->quit(); if (m_savingProgressDialog) { m_savingProgressDialog->close(); } } void EditorWindow::slotSelected(bool val) { // Update menu actions. d->cropAction->setEnabled(val); d->zoomFitToSelectAction->setEnabled(val); d->copyAction->setEnabled(val); QRect sel = m_canvas->getSelectedArea(); // Update histogram into sidebar. emit signalSelectionChanged(sel); // Update status bar if (val) { slotSelectionSetText(sel); } else { setToolInfoMessage(i18n("No selection")); } } void EditorWindow::slotPrepareToLoad() { // Disable actions as appropriate during loading emit signalNoCurrentItem(); unsetCursor(); m_animLogo->stop(); toggleActions(false); slotUpdateItemInfo(); } void EditorWindow::slotLoadingStarted(const QString& /*filename*/) { setCursor(Qt::WaitCursor); toggleActions(false); m_animLogo->start(); m_nameLabel->setProgressBarMode(StatusProgressBar::ProgressBarMode, i18n("Loading:")); } void EditorWindow::slotLoadingFinished(const QString& filename, bool success) { m_nameLabel->setProgressBarMode(StatusProgressBar::TextMode); // Enable actions as appropriate after loading // No need to re-enable image properties sidebar here, it's will be done // automatically by a signal from canvas toggleActions(success); slotUpdateItemInfo(); unsetCursor(); m_animLogo->stop(); if (success) { colorManage(); // Set a history which contains all available files as referredImages DImageHistory resolved = resolvedImageHistory(m_canvas->interface()->getInitialImageHistory()); m_canvas->interface()->setResolvedInitialHistory(resolved); } else { DNotificationPopup::message(DNotificationPopup::Boxed, i18n("Cannot load \"%1\"", filename), m_canvas, m_canvas->mapToGlobal(QPoint(30, 30))); } } void EditorWindow::resetOrigin() { // With versioning, "only" resetting undo history does not work anymore // as we calculate undo state based on the initial history stored in the DImg resetOriginSwitchFile(); } void EditorWindow::resetOriginSwitchFile() { DImageHistory resolved = resolvedImageHistory(m_canvas->interface()->getItemHistory()); m_canvas->interface()->switchToLastSaved(resolved); } void EditorWindow::colorManage() { if (!IccSettings::instance()->isEnabled()) { return; } DImg image = m_canvas->currentImage(); if (image.isNull()) { return; } if (!IccManager::needsPostLoadingManagement(image)) { return; } IccPostLoadingManager manager(image, m_canvas->currentImageFilePath()); if (!manager.hasValidWorkspace()) { QString message = i18n("Cannot open the specified working space profile (\"%1\"). " "No color transformation will be applied. " "Please check the color management " "configuration in digiKam's setup.", IccSettings::instance()->settings().workspaceProfile); QMessageBox::information(this, qApp->applicationName(), message); } // Show dialog and get transform from user choice IccTransform trans = manager.postLoadingManage(this); // apply transform in thread. // Do _not_ test for willHaveEffect() here - there are more side effects when calling this method m_canvas->applyTransform(trans); slotUpdateItemInfo(); } void EditorWindow::slotNameLabelCancelButtonPressed() { // If we saving an image... if (m_savingContext.savingState != SavingContext::SavingStateNone) { m_savingContext.abortingSaving = true; m_canvas->abortSaving(); } } void EditorWindow::slotFileOriginChanged(const QString&) { // implemented in subclass } bool EditorWindow::saveOrSaveAs() { if (m_canvas->isReadOnly()) { return saveAs(); } return save(); } void EditorWindow::slotSavingStarted(const QString& /*filename*/) { setCursor(Qt::WaitCursor); m_animLogo->start(); // Disable actions as appropriate during saving emit signalNoCurrentItem(); toggleActions(false); m_nameLabel->setProgressBarMode(StatusProgressBar::CancelProgressBarMode, i18n("Saving:")); } void EditorWindow::slotSavingFinished(const QString& filename, bool success) { Q_UNUSED(filename); qCDebug(DIGIKAM_GENERAL_LOG) << filename << success << (m_savingContext.savingState != SavingContext::SavingStateNone); // only handle this if we really wanted to save a file... if (m_savingContext.savingState != SavingContext::SavingStateNone) { m_savingContext.executedOperation = m_savingContext.savingState; m_savingContext.savingState = SavingContext::SavingStateNone; if (!success) { if (!m_savingContext.abortingSaving) { QMessageBox::critical(this, qApp->applicationName(), i18n("Failed to save file\n\"%1\"\nto\n\"%2\".", m_savingContext.destinationURL.fileName(), m_savingContext.destinationURL.toLocalFile())); } finishSaving(false); return; } moveFile(); } else { qCWarning(DIGIKAM_GENERAL_LOG) << "Why was slotSavingFinished called if we did not want to save a file?"; } } void EditorWindow::movingSaveFileFinished(bool successful) { if (!successful) { finishSaving(false); return; } // now that we know the real destination file name, pass it to be recorded in image history m_canvas->interface()->setLastSaved(m_savingContext.destinationURL.toLocalFile()); // remove image from cache since it has changed LoadingCacheInterface::fileChanged(m_savingContext.destinationURL.toLocalFile()); ThumbnailLoadThread::deleteThumbnail(m_savingContext.destinationURL.toLocalFile()); // restore state of disabled actions. saveIsComplete can start any other task // (loading!) which might itself in turn change states finishSaving(true); switch (m_savingContext.executedOperation) { case SavingContext::SavingStateNone: break; case SavingContext::SavingStateSave: saveIsComplete(); break; case SavingContext::SavingStateSaveAs: saveAsIsComplete(); break; case SavingContext::SavingStateVersion: saveVersionIsComplete(); break; } // Take all actions necessary to update information and re-enable sidebar slotChanged(); } void EditorWindow::finishSaving(bool success) { m_savingContext.synchronousSavingResult = success; delete m_savingContext.saveTempFile; m_savingContext.saveTempFile = nullptr; // Exit of internal Qt event loop to unlock promptUserSave() method. if (m_savingContext.synchronizingState == SavingContext::SynchronousSaving) { quitWaitingLoop(); } // Enable actions as appropriate after saving toggleActions(true); unsetCursor(); m_animLogo->stop(); m_nameLabel->setProgressBarMode(StatusProgressBar::TextMode); /*if (m_savingProgressDialog) { m_savingProgressDialog->close(); }*/ // On error, continue using current image if (!success) { /* Why this? * m_canvas->switchToLastSaved(m_savingContext.srcURL.toLocalFile());*/ } } void EditorWindow::setupTempSaveFile(const QUrl& url) { // if the destination url is on local file system, try to set the temp file // location to the destination folder, otherwise use a local default QString tempDir = url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).toLocalFile(); if (!url.isLocalFile() || tempDir.isEmpty()) { tempDir = QDir::tempPath(); } QFileInfo fi(url.toLocalFile()); QString suffix = fi.suffix(); // use magic file extension which tells the digikamalbums ioslave to ignore the file m_savingContext.saveTempFile = new SafeTemporaryFile(tempDir + QLatin1String("/EditorWindow-XXXXXX.digikamtempfile.") + suffix); m_savingContext.saveTempFile->setAutoRemove(false); if (!m_savingContext.saveTempFile->open()) { QMessageBox::critical(this, qApp->applicationName(), i18n("Could not open a temporary file in the folder \"%1\": %2 (%3)", QDir::toNativeSeparators(tempDir), m_savingContext.saveTempFile->errorString(), m_savingContext.saveTempFile->error())); return; } m_savingContext.saveTempFileName = m_savingContext.saveTempFile->fileName(); delete m_savingContext.saveTempFile; m_savingContext.saveTempFile = nullptr; } void EditorWindow::startingSave(const QUrl& url) { qCDebug(DIGIKAM_GENERAL_LOG) << "startSaving url = " << url; // avoid any reentrancy. Should be impossible anyway since actions will be disabled. if (m_savingContext.savingState != SavingContext::SavingStateNone) { return; } m_savingContext = SavingContext(); if (!checkPermissions(url)) { return; } setupTempSaveFile(url); m_savingContext.srcURL = url; m_savingContext.destinationURL = m_savingContext.srcURL; m_savingContext.destinationExisted = true; m_savingContext.originalFormat = m_canvas->currentImageFileFormat(); m_savingContext.format = m_savingContext.originalFormat; m_savingContext.abortingSaving = false; m_savingContext.savingState = SavingContext::SavingStateSave; m_savingContext.executedOperation = SavingContext::SavingStateNone; m_canvas->interface()->saveAs(m_savingContext.saveTempFileName, m_IOFileSettings, m_setExifOrientationTag && m_canvas->exifRotated(), m_savingContext.format, m_savingContext.destinationURL.toLocalFile()); } bool EditorWindow::showFileSaveDialog(const QUrl& initialUrl, QUrl& newURL) { QString all; QStringList list = supportedImageMimeTypes(QIODevice::WriteOnly, all); DFileDialog* const imageFileSaveDialog = new DFileDialog(this); imageFileSaveDialog->setWindowTitle(i18n("New Image File Name")); imageFileSaveDialog->setDirectoryUrl(initialUrl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash)); imageFileSaveDialog->setAcceptMode(QFileDialog::AcceptSave); imageFileSaveDialog->setFileMode(QFileDialog::AnyFile); imageFileSaveDialog->setNameFilters(list); // restore old settings for the dialog KSharedConfig::Ptr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(configGroupName()); const QString optionLastExtension = QLatin1String("LastSavedImageExtension"); QString ext = group.readEntry(optionLastExtension, "png"); foreach (const QString& s, list) { if (s.contains(QString::fromLatin1("*.%1").arg(ext))) { imageFileSaveDialog->selectNameFilter(s); break; } } // adjust extension of proposed filename QString fileName = initialUrl.fileName(); if (!fileName.isNull()) { int lastDot = fileName.lastIndexOf(QLatin1Char('.')); QString completeBaseName = (lastDot == -1) ? fileName : fileName.left(lastDot); fileName = completeBaseName + QLatin1Char('.') + ext; } if (!fileName.isNull()) { imageFileSaveDialog->selectFile(fileName); } // Start dialog and check if canceled. int result; if (d->currentWindowModalDialog) { // go application-modal - we will create utter confusion if descending into more than one window-modal dialog imageFileSaveDialog->setModal(true); result = imageFileSaveDialog->exec(); } else { imageFileSaveDialog->setWindowModality(Qt::WindowModal); d->currentWindowModalDialog = imageFileSaveDialog; result = imageFileSaveDialog->exec(); d->currentWindowModalDialog = nullptr; } if (result != QDialog::Accepted || !imageFileSaveDialog) { qCDebug(DIGIKAM_GENERAL_LOG) << "File Save Dialog rejected"; return false; } QList urls = imageFileSaveDialog->selectedUrls(); if (urls.isEmpty()) { qCDebug(DIGIKAM_GENERAL_LOG) << "no target url"; return false; } newURL = urls.first(); newURL.setPath(QDir::cleanPath(newURL.path())); QFileInfo fi(newURL.fileName()); if (fi.suffix().isEmpty()) { ext = imageFileSaveDialog->selectedNameFilter().section(QLatin1String("*."), 1, 1); ext = ext.left(ext.length() - 1); if (ext.isEmpty()) { ext = QLatin1String("jpg"); } newURL.setPath(newURL.path() + QLatin1Char('.') + ext); } qCDebug(DIGIKAM_GENERAL_LOG) << "Writing file to " << newURL; //-- Show Settings Dialog ---------------------------------------------- const QString configShowImageSettingsDialog = QLatin1String("ShowImageSettingsDialog"); bool showDialog = group.readEntry(configShowImageSettingsDialog, true); FileSaveOptionsBox* const options = new FileSaveOptionsBox(); if (showDialog && options->discoverFormat(newURL.fileName(), DImg::NONE) != DImg::NONE) { FileSaveOptionsDlg* const fileSaveOptionsDialog = new FileSaveOptionsDlg(this, options); options->setImageFileFormat(newURL.fileName()); if (d->currentWindowModalDialog) { // go application-modal - we will create utter confusion if descending into more than one window-modal dialog fileSaveOptionsDialog->setModal(true); result = fileSaveOptionsDialog->exec(); } else { fileSaveOptionsDialog->setWindowModality(Qt::WindowModal); d->currentWindowModalDialog = fileSaveOptionsDialog; result = fileSaveOptionsDialog->exec(); d->currentWindowModalDialog = nullptr; } if (result != QDialog::Accepted || !fileSaveOptionsDialog) { return false; } } // write settings to config options->applySettings(); // read settings from config to local container applyIOSettings(); // select the format to save the image with m_savingContext.format = selectValidSavingFormat(newURL); if (m_savingContext.format.isNull()) { QMessageBox::critical(this, qApp->applicationName(), i18n("Unable to determine the format to save the target image with.")); return false; } if (!newURL.isValid()) { QMessageBox::critical(this, qApp->applicationName(), i18n("Cannot Save: Found file path %1 is invalid.", newURL.toDisplayString())); qCWarning(DIGIKAM_GENERAL_LOG) << "target URL is not valid !"; return false; } group.writeEntry(optionLastExtension, m_savingContext.format); config->sync(); return true; } QString EditorWindow::selectValidSavingFormat(const QUrl& targetUrl) { qCDebug(DIGIKAM_GENERAL_LOG) << "Trying to find a saving format from targetUrl = " << targetUrl; // build a list of valid types QString all; supportedImageMimeTypes(QIODevice::WriteOnly, all); qCDebug(DIGIKAM_GENERAL_LOG) << "Qt Offered types: " << all; QStringList validTypes = all.split(QLatin1String("*."), QString::SkipEmptyParts); validTypes.replaceInStrings(QLatin1String(" "), QString()); qCDebug(DIGIKAM_GENERAL_LOG) << "Writable formats: " << validTypes; // determine the format to use the format provided in the filename QString suffix; if (targetUrl.isLocalFile()) { // for local files QFileInfo can be used QFileInfo fi(targetUrl.toLocalFile()); suffix = fi.suffix(); qCDebug(DIGIKAM_GENERAL_LOG) << "Possible format from local file: " << suffix; } else { // for remote files string manipulation is needed unfortunately QString fileName = targetUrl.fileName(); const int periodLocation = fileName.lastIndexOf(QLatin1Char('.')); if (periodLocation >= 0) { suffix = fileName.right(fileName.size() - periodLocation - 1); } qCDebug(DIGIKAM_GENERAL_LOG) << "Possible format from remote file: " << suffix; } if (!suffix.isEmpty() && validTypes.contains(suffix, Qt::CaseInsensitive)) { qCDebug(DIGIKAM_GENERAL_LOG) << "Using format from target url " << suffix; return suffix; } // another way to determine the format is to use the original file { QString originalFormat = QString::fromUtf8(QImageReader::imageFormat(m_savingContext.srcURL.toLocalFile())); if (validTypes.contains(originalFormat, Qt::CaseInsensitive)) { qCDebug(DIGIKAM_GENERAL_LOG) << "Using format from original file: " << originalFormat; return originalFormat; } } qCDebug(DIGIKAM_GENERAL_LOG) << "No suitable format found"; return QString(); } bool EditorWindow::startingSaveAs(const QUrl& url) { qCDebug(DIGIKAM_GENERAL_LOG) << "startSavingAs called"; if (m_savingContext.savingState != SavingContext::SavingStateNone) { return false; } m_savingContext = SavingContext(); m_savingContext.srcURL = url; QUrl suggested = m_savingContext.srcURL; // Run dialog ------------------------------------------------------------------- QUrl newURL; if (!showFileSaveDialog(suggested, newURL)) { return false; } // if new and original URL are equal use save() ------------------------------ QUrl currURL(m_savingContext.srcURL); currURL.setPath(QDir::cleanPath(currURL.path())); newURL.setPath(QDir::cleanPath(newURL.path())); if (currURL.matches(newURL, QUrl::None)) { save(); return false; } // Check for overwrite ---------------------------------------------------------- QFileInfo fi(newURL.toLocalFile()); m_savingContext.destinationExisted = fi.exists(); if (m_savingContext.destinationExisted) { if (!checkOverwrite(newURL)) { return false; } // There will be two message boxes if the file is not writable. // This may be controversial, and it may be changed, but it was a deliberate decision. if (!checkPermissions(newURL)) { return false; } } // Now do the actual saving ----------------------------------------------------- setupTempSaveFile(newURL); m_savingContext.destinationURL = newURL; m_savingContext.originalFormat = m_canvas->currentImageFileFormat(); m_savingContext.savingState = SavingContext::SavingStateSaveAs; m_savingContext.executedOperation = SavingContext::SavingStateNone; m_savingContext.abortingSaving = false; // in any case, destructive (Save as) or non (Export), mark as New Version m_canvas->interface()->setHistoryIsBranch(true); m_canvas->interface()->saveAs(m_savingContext.saveTempFileName, m_IOFileSettings, m_setExifOrientationTag && m_canvas->exifRotated(), m_savingContext.format.toLower(), m_savingContext.destinationURL.toLocalFile()); return true; } bool EditorWindow::startingSaveCurrentVersion(const QUrl& url) { return startingSaveVersion(url, false, false, QString()); } bool EditorWindow::startingSaveNewVersion(const QUrl& url) { return startingSaveVersion(url, true, false, QString()); } bool EditorWindow::startingSaveNewVersionAs(const QUrl& url) { return startingSaveVersion(url, true, true, QString()); } bool EditorWindow::startingSaveNewVersionInFormat(const QUrl& url, const QString& format) { return startingSaveVersion(url, true, false, format); } VersionFileOperation EditorWindow::saveVersionFileOperation(const QUrl& url, bool fork) { DImageHistory resolvedHistory = m_canvas->interface()->getResolvedInitialHistory(); DImageHistory history = m_canvas->interface()->getItemHistory(); VersionFileInfo currentName(url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile(), url.fileName(), m_canvas->currentImageFileFormat()); return versionManager()->operation(fork ? VersionManager::NewVersionName : VersionManager::CurrentVersionName, currentName, resolvedHistory, history); } VersionFileOperation EditorWindow::saveAsVersionFileOperation(const QUrl& url, const QUrl& saveUrl, const QString& format) { DImageHistory resolvedHistory = m_canvas->interface()->getResolvedInitialHistory(); DImageHistory history = m_canvas->interface()->getItemHistory(); VersionFileInfo currentName(url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile(), url.fileName(), m_canvas->currentImageFileFormat()); VersionFileInfo saveLocation(saveUrl.adjusted(QUrl::RemoveFilename).toLocalFile(), saveUrl.fileName(), format); return versionManager()->operationNewVersionAs(currentName, saveLocation, resolvedHistory, history); } VersionFileOperation EditorWindow::saveInFormatVersionFileOperation(const QUrl& url, const QString& format) { DImageHistory resolvedHistory = m_canvas->interface()->getResolvedInitialHistory(); DImageHistory history = m_canvas->interface()->getItemHistory(); VersionFileInfo currentName(url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile(), url.fileName(), m_canvas->currentImageFileFormat()); return versionManager()->operationNewVersionInFormat(currentName, format, resolvedHistory, history); } bool EditorWindow::startingSaveVersion(const QUrl& url, bool fork, bool saveAs, const QString& format) { qCDebug(DIGIKAM_GENERAL_LOG) << "Saving image" << url << "non-destructive, new version:" << fork << ", saveAs:" << saveAs << "format:" << format; if (m_savingContext.savingState != SavingContext::SavingStateNone) { return false; } m_savingContext = SavingContext(); m_savingContext.versionFileOperation = saveVersionFileOperation(url, fork); m_canvas->interface()->setHistoryIsBranch(fork); if (saveAs) { QUrl suggested = m_savingContext.versionFileOperation.saveFile.fileUrl(); QUrl selectedUrl; if (!showFileSaveDialog(suggested, selectedUrl)) { return false; } m_savingContext.versionFileOperation = saveAsVersionFileOperation(url, selectedUrl, m_savingContext.format); } else if (!format.isNull()) { m_savingContext.versionFileOperation = saveInFormatVersionFileOperation(url, format); } const QUrl newURL = m_savingContext.versionFileOperation.saveFile.fileUrl(); qCDebug(DIGIKAM_GENERAL_LOG) << "Writing file to " << newURL; if (!newURL.isValid()) { QMessageBox::critical(this, qApp->applicationName(), i18nc("@info", "Cannot save file %1 to " "the suggested version file name %2", url.fileName(), newURL.fileName())); qCWarning(DIGIKAM_GENERAL_LOG) << "target URL is not valid !"; return false; } QFileInfo fi(newURL.toLocalFile()); m_savingContext.destinationExisted = fi.exists(); // Check for overwrite (saveAs only) -------------------------------------------- if (m_savingContext.destinationExisted) { // So, should we refuse to overwrite the original? // It's a frontal crash against non-destructive principles. // It is tempting to refuse, yet I think the user has to decide in the end /*QUrl currURL(m_savingContext.srcURL); currURL.cleanPath(); newURL.cleanPath(); if (currURL.equals(newURL)) { ... return false; }*/ // check for overwrite, unless the operation explicitly tells us to overwrite if (!(m_savingContext.versionFileOperation.tasks & VersionFileOperation::Replace) && !checkOverwrite(newURL)) { return false; } // There will be two message boxes if the file is not writable. // This may be controversial, and it may be changed, but it was a deliberate decision. if (!checkPermissions(newURL)) { return false; } } setupTempSaveFile(newURL); m_savingContext.srcURL = url; m_savingContext.destinationURL = newURL; m_savingContext.originalFormat = m_canvas->currentImageFileFormat(); m_savingContext.format = m_savingContext.versionFileOperation.saveFile.format; m_savingContext.abortingSaving = false; m_savingContext.savingState = SavingContext::SavingStateVersion; m_savingContext.executedOperation = SavingContext::SavingStateNone; m_canvas->interface()->saveAs(m_savingContext.saveTempFileName, m_IOFileSettings, m_setExifOrientationTag && m_canvas->exifRotated(), m_savingContext.format.toLower(), m_savingContext.versionFileOperation); return true; } bool EditorWindow::checkPermissions(const QUrl& url) { //TODO: Check that the permissions can actually be changed // if write permissions are not available. QFileInfo fi(url.toLocalFile()); if (fi.exists() && !fi.isWritable()) { int result = QMessageBox::warning(this, i18n("Overwrite File?"), i18n("You do not have write permissions " "for the file named \"%1\". " "Are you sure you want " "to overwrite it?", url.fileName()), QMessageBox::Save | QMessageBox::Cancel); if (result != QMessageBox::Save) { return false; } } return true; } bool EditorWindow::checkOverwrite(const QUrl& url) { int result = QMessageBox::warning(this, i18n("Overwrite File?"), i18n("A file named \"%1\" already " "exists. Are you sure you want " "to overwrite it?", url.fileName()), QMessageBox::Save | QMessageBox::Cancel); return (result == QMessageBox::Save); } bool EditorWindow::moveLocalFile(const QString& org, const QString& dst) { QString sidecarOrg = DMetadata::sidecarPath(org); QString source = m_savingContext.srcURL.toLocalFile(); if (QFileInfo::exists(sidecarOrg)) { QString sidecarDst = DMetadata::sidecarPath(dst); if (!DFileOperations::localFileRename(source, sidecarOrg, sidecarDst)) { qCDebug(DIGIKAM_GENERAL_LOG) << "Failed to move sidecar file"; } } if (!DFileOperations::localFileRename(source, org, dst)) { QMessageBox::critical(this, i18n("Error Saving File"), i18n("Failed to overwrite original file")); return false; } return true; } void EditorWindow::moveFile() { // Move local file. if (m_savingContext.executedOperation == SavingContext::SavingStateVersion) { // check if we need to move the current file to an intermediate name if (m_savingContext.versionFileOperation.tasks & VersionFileOperation::MoveToIntermediate) { //qCDebug(DIGIKAM_GENERAL_LOG) << "MoveToIntermediate: Moving " << m_savingContext.srcURL.toLocalFile() << "to" // << m_savingContext.versionFileOperation.intermediateForLoadedFile.filePath() moveLocalFile(m_savingContext.srcURL.toLocalFile(), m_savingContext.versionFileOperation.intermediateForLoadedFile.filePath()); LoadingCacheInterface::fileChanged(m_savingContext.destinationURL.toLocalFile()); ThumbnailLoadThread::deleteThumbnail(m_savingContext.destinationURL.toLocalFile()); } } bool moveSuccessful = moveLocalFile(m_savingContext.saveTempFileName, m_savingContext.destinationURL.toLocalFile()); if (m_savingContext.executedOperation == SavingContext::SavingStateVersion) { if (moveSuccessful && m_savingContext.versionFileOperation.tasks & VersionFileOperation::SaveAndDelete) { QFile file(m_savingContext.versionFileOperation.loadedFile.filePath()); file.remove(); } } movingSaveFileFinished(moveSuccessful); } void EditorWindow::slotDiscardChanges() { m_canvas->interface()->rollbackToOrigin(); } void EditorWindow::slotOpenOriginal() { // no-op in this base class } void EditorWindow::slotColorManagementOptionsChanged() { applyColorManagementSettings(); applyIOSettings(); } void EditorWindow::slotToggleColorManagedView() { if (!IccSettings::instance()->isEnabled()) { return; } bool cmv = !IccSettings::instance()->settings().useManagedView; IccSettings::instance()->setUseManagedView(cmv); } void EditorWindow::setColorManagedViewIndicatorToolTip(bool available, bool cmv) { QString tooltip; if (available) { if (cmv) { tooltip = i18n("Color-Managed View is enabled."); } else { tooltip = i18n("Color-Managed View is disabled."); } } else { tooltip = i18n("Color Management is not configured, so the Color-Managed View is not available."); } d->cmViewIndicator->setToolTip(tooltip); } void EditorWindow::slotSoftProofingOptions() { // Adjusts global settings QPointer dlg = new SoftProofDialog(this); dlg->exec(); d->viewSoftProofAction->setChecked(dlg->shallEnableSoftProofView()); slotUpdateSoftProofingState(); delete dlg; } void EditorWindow::slotUpdateSoftProofingState() { bool on = d->viewSoftProofAction->isChecked(); m_canvas->setSoftProofingEnabled(on); d->toolIface->updateICCSettings(); } void EditorWindow::slotSetUnderExposureIndicator(bool on) { d->exposureSettings->underExposureIndicator = on; d->toolIface->updateExposureSettings(); d->viewUnderExpoAction->setChecked(on); setUnderExposureToolTip(on); } void EditorWindow::setUnderExposureToolTip(bool on) { d->underExposureIndicator->setToolTip( on ? i18n("Under-Exposure indicator is enabled") : i18n("Under-Exposure indicator is disabled")); } void EditorWindow::slotSetOverExposureIndicator(bool on) { d->exposureSettings->overExposureIndicator = on; d->toolIface->updateExposureSettings(); d->viewOverExpoAction->setChecked(on); setOverExposureToolTip(on); } void EditorWindow::setOverExposureToolTip(bool on) { d->overExposureIndicator->setToolTip( on ? i18n("Over-Exposure indicator is enabled") : i18n("Over-Exposure indicator is disabled")); } void EditorWindow::slotToggleSlideShow() { SlideShowSettings settings; settings.readFromConfig(); slideShow(settings); } void EditorWindow::slotSelectionChanged(const QRect& sel) { slotSelectionSetText(sel); emit signalSelectionChanged(sel); } void EditorWindow::slotSelectionSetText(const QRect& sel) { setToolInfoMessage(QString::fromLatin1("(%1, %2) (%3 x %4)").arg(sel.x()).arg(sel.y()).arg(sel.width()).arg(sel.height())); } void EditorWindow::slotComponentsInfo() { LibsInfoDlg* const dlg = new LibsInfoDlg(this); dlg->show(); } void EditorWindow::setToolStartProgress(const QString& toolName) { m_animLogo->start(); m_nameLabel->setProgressValue(0); m_nameLabel->setProgressBarMode(StatusProgressBar::CancelProgressBarMode, QString::fromUtf8("%1:").arg(toolName)); } void EditorWindow::setToolProgress(int progress) { m_nameLabel->setProgressValue(progress); } void EditorWindow::setToolStopProgress() { m_animLogo->stop(); m_nameLabel->setProgressValue(0); m_nameLabel->setProgressBarMode(StatusProgressBar::TextMode); slotUpdateItemInfo(); } void EditorWindow::slotCloseTool() { if (d->toolIface) { d->toolIface->slotCloseTool(); } } void EditorWindow::slotApplyTool() { if (d->toolIface) { d->toolIface->slotApplyTool(); } } void EditorWindow::setPreviewModeMask(int mask) { d->previewToolBar->setPreviewModeMask(mask); } PreviewToolBar::PreviewMode EditorWindow::previewMode() const { return d->previewToolBar->previewMode(); } void EditorWindow::setToolInfoMessage(const QString& txt) { d->infoLabel->setAdjustedText(txt); } VersionManager* EditorWindow::versionManager() const { return &d->defaultVersionManager; } void EditorWindow::setupSelectToolsAction() { // Create action model ActionItemModel* const actionModel = new ActionItemModel(this); actionModel->setMode(ActionItemModel::ToplevelMenuCategory | ActionItemModel::SortCategoriesByInsertionOrder); // Builtin actions QString transformCategory = i18nc("@title Image Transform", "Transform"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::EditorTransform, this)) { actionModel->addAction(ac, transformCategory); } QString decorateCategory = i18nc("@title Image Decorate", "Decorate"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::EditorDecorate, this)) { actionModel->addAction(ac, decorateCategory); } QString effectsCategory = i18nc("@title Image Effect", "Effects"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::EditorFilters, this)) { actionModel->addAction(ac, effectsCategory); } QString colorsCategory = i18nc("@title Image Colors", "Colors"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::EditorColors, this)) { actionModel->addAction(ac, effectsCategory); } QString enhanceCategory = i18nc("@title Image Enhance", "Enhance"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::EditorEnhance, this)) { actionModel->addAction(ac, effectsCategory); } QString postCategory = i18nc("@title Post Processing Tools", "Post-Processing"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::GenericTool, this)) { actionModel->addAction(ac, postCategory); } foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::EditorFile, this)) { actionModel->addAction(ac, postCategory); } foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::GenericMetadata, this)) { actionModel->addAction(ac, postCategory); } QString exportCategory = i18nc("@title Export Tools", "Export"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::GenericExport, this)) { actionModel->addAction(ac, exportCategory); } QString importCategory = i18nc("@title Import Tools", "Import"); foreach (DPluginAction* const ac, DPluginLoader::instance()->pluginsActions(DPluginAction::GenericImport, this)) { actionModel->addAction(ac, importCategory); } // setup categorized view DCategorizedSortFilterProxyModel* const filterModel = actionModel->createFilterModel(); ActionCategorizedView* const selectToolsActionView = new ActionCategorizedView; selectToolsActionView->setupIconMode(); selectToolsActionView->setModel(filterModel); selectToolsActionView->adjustGridSize(); connect(selectToolsActionView, SIGNAL(clicked(QModelIndex)), actionModel, SLOT(trigger(QModelIndex))); EditorToolIface::editorToolIface()->setToolsIconView(selectToolsActionView); } void EditorWindow::slotThemeChanged() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(configGroupName()); if (!group.readEntry(d->configUseThemeBackgroundColorEntry, true)) { m_bgColor = group.readEntry(d->configBackgroundColorEntry, QColor(Qt::black)); } else { m_bgColor = palette().color(QPalette::Base); } m_canvas->setBackgroundBrush(QBrush(m_bgColor)); d->toolIface->themeChanged(); } void EditorWindow::addAction2ContextMenu(const QString& actionName, bool addDisabled) { if (!m_contextMenu) { return; } QAction* const action = actionCollection()->action(actionName); if (action && (action->isEnabled() || addDisabled)) { m_contextMenu->addAction(action); } } void EditorWindow::showSideBars(bool visible) { if (visible) { rightSideBar()->restore(QList() << thumbBar(), d->fullscreenSizeBackup); } else { // See bug #166472, a simple backup()/restore() will hide non-sidebar splitter child widgets // in horizontal mode thumbbar wont be member of the splitter, it is just ignored then rightSideBar()->backup(QList() << thumbBar(), &d->fullscreenSizeBackup); } } void EditorWindow::slotToggleRightSideBar() { rightSideBar()->isExpanded() ? rightSideBar()->shrink() : rightSideBar()->expand(); } void EditorWindow::slotPreviousRightSideBarTab() { rightSideBar()->activePreviousTab(); } void EditorWindow::slotNextRightSideBarTab() { rightSideBar()->activeNextTab(); } void EditorWindow::showThumbBar(bool visible) { visible ? thumbBar()->restoreVisibility() : thumbBar()->hide(); } bool EditorWindow::thumbbarVisibility() const { return thumbBar()->isVisible(); } void EditorWindow::customizedFullScreenMode(bool set) { set ? m_canvas->setBackgroundBrush(QBrush(Qt::black)) : m_canvas->setBackgroundBrush(QBrush(m_bgColor)); showStatusBarAction()->setEnabled(!set); toolBarMenuAction()->setEnabled(!set); showMenuBarAction()->setEnabled(!set); m_showBarAction->setEnabled(!set); } void EditorWindow::addServicesMenuForUrl(const QUrl& url) { KService::List offers = DFileOperations::servicesForOpenWith(QList() << url); qCDebug(DIGIKAM_GENERAL_LOG) << offers.count() << " services found to open " << url; if (m_servicesMenu) { delete m_servicesMenu; m_servicesMenu = nullptr; } if (m_serviceAction) { delete m_serviceAction; m_serviceAction = nullptr; } if (!offers.isEmpty()) { m_servicesMenu = new QMenu(this); QAction* const serviceAction = m_servicesMenu->menuAction(); serviceAction->setText(i18n("Open With")); foreach (const KService::Ptr& service, offers) { QString name = service->name().replace(QLatin1Char('&'), QLatin1String("&&")); QAction* const action = m_servicesMenu->addAction(name); action->setIcon(QIcon::fromTheme(service->icon())); action->setData(service->name()); d->servicesMap[name] = service; } #ifdef HAVE_KIO m_servicesMenu->addSeparator(); m_servicesMenu->addAction(i18n("Other...")); m_contextMenu->addAction(serviceAction); connect(m_servicesMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotOpenWith(QAction*))); } else { m_serviceAction = new QAction(i18n("Open With..."), this); m_contextMenu->addAction(m_serviceAction); connect(m_servicesMenu, SIGNAL(triggered()), this, SLOT(slotOpenWith())); #endif // HAVE_KIO } } void EditorWindow::openWith(const QUrl& url, QAction* action) { KService::Ptr service; QString name = action ? action->data().toString() : QString(); #ifdef HAVE_KIO if (name.isEmpty()) { QPointer dlg = new KOpenWithDialog(QList() << url); if (dlg->exec() != KOpenWithDialog::Accepted) { delete dlg; return; } service = dlg->service(); if (!service) { // User entered a custom command if (!dlg->text().isEmpty()) { DFileOperations::runFiles(dlg->text(), QList() << url); } delete dlg; return; } delete dlg; } else #endif // HAVE_KIO { service = d->servicesMap[name]; } DFileOperations::runFiles(service.data(), QList() << url); } void EditorWindow::loadTool(EditorTool* const tool) { EditorToolIface::editorToolIface()->loadTool(tool); connect(tool, SIGNAL(okClicked()), this, SLOT(slotToolDone())); connect(tool, SIGNAL(cancelClicked()), this, SLOT(slotToolDone())); } void EditorWindow::slotToolDone() { EditorToolIface::editorToolIface()->unLoadTool(); } void EditorWindow::slotRotateLeftIntoQue() { m_transformQue.append(TransformType::RotateLeft); } void EditorWindow::slotRotateRightIntoQue() { m_transformQue.append(TransformType::RotateRight); } void EditorWindow::slotFlipHIntoQue() { m_transformQue.append(TransformType::FlipHorizontal); } void EditorWindow::slotFlipVIntoQue() { m_transformQue.append(TransformType::FlipVertical); } void EditorWindow::registerExtraPluginsActions(QString& dom) { DPluginLoader* const dpl = DPluginLoader::instance(); dpl->registerEditorPlugins(this); dpl->registerRawImportPlugins(this); QList actions = dpl->pluginsActions(DPluginAction::Editor, this); foreach (DPluginAction* const ac, actions) { actionCollection()->addActions(QList() << ac); actionCollection()->setDefaultShortcuts(ac, ac->shortcuts()); } dom.replace(QLatin1String(""), dpl->pluginXmlSections(DPluginAction::EditorFile, this)); dom.replace(QLatin1String(""), dpl->pluginXmlSections(DPluginAction::EditorColors, this)); dom.replace(QLatin1String(""), dpl->pluginXmlSections(DPluginAction::EditorEnhance, this)); QString transformActions; transformActions.append(QLatin1String("\n")); transformActions.append(QLatin1String("\n")); transformActions.append(QLatin1String("\n")); transformActions.append(QLatin1String("\n")); transformActions.append(QLatin1String("\n")); transformActions.append(QLatin1String("\n")); transformActions.append(dpl->pluginXmlSections(DPluginAction::EditorTransform, this)); dom.replace(QLatin1String(""), transformActions); dom.replace(QLatin1String(""), dpl->pluginXmlSections(DPluginAction::EditorDecorate, this)); dom.replace(QLatin1String(""), dpl->pluginXmlSections(DPluginAction::EditorFilters, this)); } } // namespace Digikam diff --git a/core/utilities/imageeditor/editor/editorwindow.h b/core/utilities/imageeditor/editor/editorwindow.h index d58e1d3547..cd854aab39 100644 --- a/core/utilities/imageeditor/editor/editorwindow.h +++ b/core/utilities/imageeditor/editor/editorwindow.h @@ -1,398 +1,398 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2006-01-20 * Description : core image editor GUI implementation * * Copyright (C) 2006-2020 by Gilles Caulier * Copyright (C) 2009-2011 by Andi Clemens * Copyright (C) 2015 by Mohamed_Anwer * * 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, 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. * * ============================================================ */ #ifndef DIGIKAM_IMAGE_EDITOR_WINDOW_H #define DIGIKAM_IMAGE_EDITOR_WINDOW_H // C++ includes #include // Qt includes #include #include #include #include #include #include // Local includes #include "digikam_export.h" #include "digikam_config.h" #include "thumbbardock.h" #include "previewtoolbar.h" #include "savingcontext.h" #include "dxmlguiwindow.h" class QSplitter; class QMenu; class QAction; class KSelectAction; class KToolBarPopupAction; namespace Digikam { class DAdjustableLabel; class DCategorizedView; class Canvas; class DImageHistory; class EditorTool; class EditorStackView; class ExposureSettingsContainer; class IOFileSettings; class ICCSettingsContainer; class Sidebar; class SidebarSplitter; class SlideShowSettings; class StatusProgressBar; class VersionManager; class VersionFileOperation; class IccProfile; class DIGIKAM_EXPORT EditorWindow : public DXmlGuiWindow { Q_OBJECT public: enum TransformType { RotateLeft, RotateRight, FlipHorizontal, FlipVertical }; explicit EditorWindow(const QString& name); ~EditorWindow(); const static QString CONFIG_GROUP_NAME; void registerExtraPluginsActions(QString& dom) override; void loadTool(EditorTool* const tool); bool actionEnabledState() const; public Q_SLOTS: virtual void slotSetup() override = 0; - virtual void slotSetupICC() = 0; + virtual void slotSetupICC() = 0; Q_SIGNALS: void signalSelectionChanged(const QRect&); void signalNoCurrentItem(); void signalPreviewModeChanged(int); void signalToolApplied(); protected: bool m_nonDestructive; bool m_setExifOrientationTag; bool m_editingOriginalImage; bool m_actionEnabledState; DAdjustableLabel* m_resLabel; QColor m_bgColor; SidebarSplitter* m_splitter; QSplitter* m_vSplitter; QAction* m_openVersionAction; QAction* m_saveAction; QAction* m_saveAsAction; KToolBarPopupAction* m_saveNewVersionAction; QAction* m_saveCurrentVersionAction; QAction* m_saveNewVersionAsAction; QMenu* m_saveNewVersionInFormatAction; QAction* m_exportAction; QAction* m_revertAction; QAction* m_discardChangesAction; QAction* m_fileDeleteAction; QAction* m_forwardAction; QAction* m_backwardAction; QAction* m_lastAction; QAction* m_firstAction; QAction* m_applyToolAction; QAction* m_closeToolAction; QAction* m_showBarAction; KToolBarPopupAction* m_undoAction; KToolBarPopupAction* m_redoAction; QMenu* m_contextMenu; QMenu* m_servicesMenu; QAction* m_serviceAction; EditorStackView* m_stackView; Canvas* m_canvas; StatusProgressBar* m_nameLabel; IOFileSettings* m_IOFileSettings; QPointer m_savingProgressDialog; SavingContext m_savingContext; QString m_formatForRAWVersioning; QString m_formatForSubversions; - //using QVector to store transforms + /// NOTE: using QVector to store transforms QVector m_transformQue; protected: enum SaveAskMode { AskIfNeeded, OverwriteWithoutAsking, AlwaysSaveAs, SaveVersionWithoutAsking = OverwriteWithoutAsking, AlwaysNewVersion = AlwaysSaveAs }; protected: void saveStandardSettings(); void readStandardSettings(); void applyStandardSettings(); void applyIOSettings(); void applyColorManagementSettings(); void setupStandardConnections(); void setupStandardActions(); void setupStatusBar(); void setupContextMenu(); void setupSelectToolsAction(); void toggleStandardActions(bool val); void toggleZoomActions(bool val); void toggleNonDestructiveActions(); void toggleToolActions(EditorTool* tool = nullptr); bool promptForOverWrite(); bool promptUserDelete(const QUrl& url); bool promptUserSave(const QUrl& url, SaveAskMode mode = AskIfNeeded, bool allowCancel = true); bool waitForSavingToComplete(); void startingSave(const QUrl& url); bool startingSaveAs(const QUrl& url); bool startingSaveCurrentVersion(const QUrl& url); bool startingSaveNewVersion(const QUrl& url); bool startingSaveNewVersionAs(const QUrl& url); bool startingSaveNewVersionInFormat(const QUrl& url, const QString& format); bool checkPermissions(const QUrl& url); bool checkOverwrite(const QUrl& url); bool moveLocalFile(const QString& src, const QString& dest); void movingSaveFileFinished(bool successful); void colorManage(); void execSavingProgressDialog(); void resetOrigin(); void resetOriginSwitchFile(); void addServicesMenuForUrl(const QUrl& url); void openWith(const QUrl& url, QAction* action); SidebarSplitter* sidebarSplitter() const; EditorStackView* editorStackView() const; ExposureSettingsContainer* exposureSettings() const; VersionFileOperation saveVersionFileOperation(const QUrl& url, bool fork); VersionFileOperation saveAsVersionFileOperation(const QUrl& url, const QUrl& saveLocation, const QString& format); VersionFileOperation saveInFormatVersionFileOperation(const QUrl& url, const QString& format); virtual bool hasOriginalToRestore(); virtual DImageHistory resolvedImageHistory(const DImageHistory& history); virtual void moveFile(); virtual void finishSaving(bool success); virtual void readSettings(); virtual void saveSettings(); virtual void toggleActions(bool val); virtual ThumbBarDock* thumbBar() const = 0; virtual Sidebar* rightSideBar() const = 0; virtual void slideShow(SlideShowSettings& settings) = 0; virtual void setupConnections() = 0; virtual void setupActions() = 0; virtual void setupUserArea() = 0; virtual void addServicesMenu() = 0; virtual VersionManager* versionManager() const; /** * Hook method that subclasses must implement to return the destination url * of the image to save. This may also be a remote url. * * This method will only be called while saving. * * @return destination for the file that is currently being saved. */ virtual QUrl saveDestinationUrl() = 0; virtual void saveIsComplete() = 0; virtual void saveAsIsComplete() = 0; virtual void saveVersionIsComplete() = 0; protected Q_SLOTS: void slotAboutToShowUndoMenu(); void slotAboutToShowRedoMenu(); void slotSelected(bool); void slotLoadingProgress(const QString& filePath, float progress); void slotSavingProgress(const QString& filePath, float progress); void slotNameLabelCancelButtonPressed(); virtual void slotPrepareToLoad(); virtual void slotLoadingStarted(const QString& filename); virtual void slotLoadingFinished(const QString& filename, bool success); virtual void slotSavingStarted(const QString& filename); virtual void slotFileOriginChanged(const QString& filePath); virtual void slotComponentsInfo() override; virtual void slotDiscardChanges(); virtual void slotOpenOriginal(); virtual bool saveOrSaveAs(); virtual bool saveAs() = 0; virtual bool save() = 0; virtual bool saveNewVersion() = 0; virtual bool saveCurrentVersion() = 0; virtual bool saveNewVersionAs() = 0; virtual bool saveNewVersionInFormat(const QString&) = 0; virtual void slotFileWithDefaultApplication() = 0; virtual void slotDeleteCurrentItem() = 0; virtual void slotBackward() = 0; virtual void slotForward() = 0; virtual void slotFirst() = 0; virtual void slotLast() = 0; virtual void slotUpdateItemInfo() = 0; virtual void slotChanged() = 0; virtual void slotContextMenu() = 0; virtual void slotRevert() = 0; virtual void slotAddedDropedItems(QDropEvent* e) = 0; virtual void slotOpenWith(QAction* action = nullptr) = 0; private Q_SLOTS: void slotSetUnderExposureIndicator(bool); void slotSetOverExposureIndicator(bool); void slotColorManagementOptionsChanged(); void slotToggleColorManagedView(); void slotSoftProofingOptions(); void slotUpdateSoftProofingState(); void slotSavingFinished(const QString& filename, bool success); void slotToggleSlideShow(); void slotZoomTo100Percents(); void slotZoomChanged(bool isMax, bool isMin, double zoom); void slotSelectionChanged(const QRect& sel); void slotSelectionSetText(const QRect& sel); void slotToggleFitToWindow(); void slotToggleOffFitToWindow(); void slotFitToSelect(); void slotIncreaseZoom(); void slotDecreaseZoom(); void slotCloseTool(); void slotApplyTool(); void slotUndoStateChanged(); void slotThemeChanged(); void slotToggleRightSideBar() override; void slotPreviousRightSideBarTab() override; void slotNextRightSideBarTab() override; void slotToolDone(); void slotRotateLeftIntoQue(); void slotRotateRightIntoQue(); void slotFlipHIntoQue(); void slotFlipVIntoQue(); private: void enterWaitingLoop(); void quitWaitingLoop(); void showSideBars(bool visible) override; void showThumbBar(bool visible) override; void customizedFullScreenMode(bool set) override; bool thumbbarVisibility() const override; void setColorManagedViewIndicatorToolTip(bool available, bool cmv); void setUnderExposureToolTip(bool uei); void setOverExposureToolTip(bool oei); void setToolStartProgress(const QString& toolName); void setToolProgress(int progress); void setToolStopProgress(); void setToolInfoMessage(const QString& txt); bool startingSaveVersion(const QUrl& url, bool subversion, bool saveAs, const QString& format); void setPreviewModeMask(int mask); PreviewToolBar::PreviewMode previewMode() const; bool showFileSaveDialog(const QUrl& initialUrl, QUrl& newURL); /** * Sets up a temp file to save image contents to and updates the saving * context to use this file * * @param url file to save the image to */ void setupTempSaveFile(const QUrl& url); /** * Sets the format to use in the saving context. Therefore multiple sources * are used starting with the extension found in the save dialog. * * @param filter filter selected in the dialog * @param targetUrl target url selected for the file to save * @return The valid extension which could be found, or a null string */ QString selectValidSavingFormat(const QUrl& targetUrl); void addAction2ContextMenu(const QString& actionName, bool addDisabled = false); private: class Private; Private* const d; friend class EditorToolIface; }; } // namespace Digikam #endif // DIGIKAM_IMAGE_EDITOR_WINDOW_H diff --git a/core/utilities/imageeditor/editor/editorwindow_p.h b/core/utilities/imageeditor/editor/editorwindow_p.h index 4a66da15b7..12dcbccaa3 100644 --- a/core/utilities/imageeditor/editor/editorwindow_p.h +++ b/core/utilities/imageeditor/editor/editorwindow_p.h @@ -1,276 +1,361 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2006-01-20 * Description : core image editor GUI implementation private data. * * Copyright (C) 2006-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #ifndef DIGIKAM_IMAGE_EDITOR_WINDOW_PRIVATE_H #define DIGIKAM_IMAGE_EDITOR_WINDOW_PRIVATE_H +#include "editorwindow.h" + +// C++ includes + +#include + // Qt includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include // KDE includes +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include +#ifdef HAVE_KIO +# include +#endif + // Local includes +#include "digikam_config.h" #include "digikam_debug.h" #include "digikam_globals.h" +#include "dmessagebox.h" +#include "applicationsettings.h" +#include "actioncategorizedview.h" +#include "canvas.h" +#include "categorizeditemmodel.h" +#include "colorcorrectiondlg.h" +#include "editorcore.h" +#include "dlogoaction.h" +#include "dmetadata.h" +#include "dzoombar.h" +#include "drawdecoderwidget.h" +#include "editorstackview.h" +#include "editortool.h" +#include "editortoolsettings.h" +#include "editortooliface.h" +#include "exposurecontainer.h" +#include "dfileoperations.h" +#include "filereadwritelock.h" +#include "filesaveoptionsbox.h" +#include "filesaveoptionsdlg.h" +#include "iccpostloadingmanager.h" +#include "iccsettings.h" +#include "iccsettingscontainer.h" +#include "icctransform.h" +#include "imagedialog.h" +#include "iofilesettings.h" +#include "metaenginesettings.h" +#include "libsinfodlg.h" +#include "loadingcacheinterface.h" +#include "jpegsettings.h" +#include "pngsettings.h" +#include "savingcontext.h" +#include "sidebar.h" +#include "slideshowsettings.h" +#include "softproofdialog.h" +#include "statusprogressbar.h" +#include "thememanager.h" +#include "thumbnailsize.h" +#include "thumbnailloadthread.h" +#include "versioningpromptusersavedlg.h" +#include "undostate.h" +#include "versionmanager.h" +#include "dfiledialog.h" +#include "dexpanderbox.h" +#include "imageiface.h" #include "editorwindow.h" #include "versionmanager.h" #include "dnotificationpopup.h" -class QAction; -class QDialog; -class QEventLoop; -class QLabel; -class QToolButton; -class QWidgetAction; - namespace Digikam { -class ActionCategorizedView; -class DZoomBar; -class EditorToolIface; -class ExposureSettingsContainer; -class ICCSettingsContainer; -class PreviewToolBar; -class DAdjustableLabel; -class IccProfilesMenuAction; - class Q_DECL_HIDDEN EditorWindow::Private { public: Private() : cmViewIndicator(nullptr), underExposureIndicator(nullptr), overExposureIndicator(nullptr), infoLabel(nullptr), copyAction(nullptr), cropAction(nullptr), flipHorizAction(nullptr), flipVertAction(nullptr), rotateLeftAction(nullptr), rotateRightAction(nullptr), selectAllAction(nullptr), selectNoneAction(nullptr), slideShowAction(nullptr), softProofOptionsAction(nullptr), zoomFitToSelectAction(nullptr), zoomMinusAction(nullptr), zoomPlusAction(nullptr), zoomTo100percents(nullptr), openWithAction(nullptr), waitingLoop(nullptr), currentWindowModalDialog(nullptr), zoomFitToWindowAction(nullptr), viewCMViewAction(nullptr), viewSoftProofAction(nullptr), viewUnderExpoAction(nullptr), viewOverExpoAction(nullptr), selectToolsActionView(nullptr), ICCSettings(nullptr), zoomBar(nullptr), previewToolBar(nullptr), exposureSettings(nullptr), toolIface(nullptr) { } ~Private() { } void legacyUpdateSplitterState(KConfigGroup& group); void plugNewVersionInFormatAction(EditorWindow* const q, QMenu* const menuAction, const QString& text, const QString& format); public: static const QString configAutoZoomEntry; static const QString configBackgroundColorEntry; static const QString configJpeg2000CompressionEntry; static const QString configJpeg2000LossLessEntry; static const QString configJpegCompressionEntry; static const QString configJpegSubSamplingEntry; static const QString configPgfCompressionEntry; static const QString configPgfLossLessEntry; static const QString configPngCompressionEntry; static const QString configSplitterStateEntry; static const QString configTiffCompressionEntry; static const QString configUnderExposureColorEntry; static const QString configUnderExposureIndicatorEntry; static const QString configUnderExposurePercentsEntry; static const QString configOverExposureColorEntry; static const QString configOverExposureIndicatorEntry; static const QString configOverExposurePercentsEntry; static const QString configExpoIndicatorModeEntry; static const QString configUseRawImportToolEntry; static const QString configRawImportToolIidEntry; static const QString configUseThemeBackgroundColorEntry; static const QString configVerticalSplitterSizesEntry; static const QString configVerticalSplitterStateEntry; QToolButton* cmViewIndicator; QToolButton* underExposureIndicator; QToolButton* overExposureIndicator; DAdjustableLabel* infoLabel; QAction* copyAction; QAction* cropAction; QAction* flipHorizAction; QAction* flipVertAction; QAction* rotateLeftAction; QAction* rotateRightAction; QAction* selectAllAction; QAction* selectNoneAction; QAction* slideShowAction; QAction* softProofOptionsAction; QAction* zoomFitToSelectAction; QAction* zoomMinusAction; QAction* zoomPlusAction; QAction* zoomTo100percents; QAction* openWithAction; QEventLoop* waitingLoop; QDialog* currentWindowModalDialog; QAction* zoomFitToWindowAction; QAction* viewCMViewAction; QAction* viewSoftProofAction; QAction* viewUnderExpoAction; QAction* viewOverExpoAction; ActionCategorizedView* selectToolsActionView; ICCSettingsContainer* ICCSettings; DZoomBar* zoomBar; PreviewToolBar* previewToolBar; ExposureSettingsContainer* exposureSettings; EditorToolIface* toolIface; VersionManager defaultVersionManager; QList fullscreenSizeBackup; QMap servicesMap; }; const QString EditorWindow::Private::configAutoZoomEntry(QLatin1String("AutoZoom")); const QString EditorWindow::Private::configBackgroundColorEntry(QLatin1String("BackgroundColor")); const QString EditorWindow::Private::configJpeg2000CompressionEntry(QLatin1String("JPEG2000Compression")); const QString EditorWindow::Private::configJpeg2000LossLessEntry(QLatin1String("JPEG2000LossLess")); const QString EditorWindow::Private::configJpegCompressionEntry(QLatin1String("JPEGCompression")); const QString EditorWindow::Private::configJpegSubSamplingEntry(QLatin1String("JPEGSubSampling")); const QString EditorWindow::Private::configPgfCompressionEntry(QLatin1String("PGFCompression")); const QString EditorWindow::Private::configPgfLossLessEntry(QLatin1String("PGFLossLess")); const QString EditorWindow::Private::configPngCompressionEntry(QLatin1String("PNGCompression")); const QString EditorWindow::Private::configSplitterStateEntry(QLatin1String("SplitterState")); const QString EditorWindow::Private::configTiffCompressionEntry(QLatin1String("TIFFCompression")); const QString EditorWindow::Private::configUnderExposureColorEntry(QLatin1String("UnderExposureColor")); const QString EditorWindow::Private::configUnderExposureIndicatorEntry(QLatin1String("UnderExposureIndicator")); const QString EditorWindow::Private::configUnderExposurePercentsEntry(QLatin1String("UnderExposurePercentsEntry")); const QString EditorWindow::Private::configOverExposureColorEntry(QLatin1String("OverExposureColor")); const QString EditorWindow::Private::configOverExposureIndicatorEntry(QLatin1String("OverExposureIndicator")); const QString EditorWindow::Private::configOverExposurePercentsEntry(QLatin1String("OverExposurePercentsEntry")); const QString EditorWindow::Private::configExpoIndicatorModeEntry(QLatin1String("ExpoIndicatorMode")); const QString EditorWindow::Private::configUseRawImportToolEntry(QLatin1String("UseRawImportTool")); const QString EditorWindow::Private::configRawImportToolIidEntry(QLatin1String("RawImportToolIid")); const QString EditorWindow::Private::configUseThemeBackgroundColorEntry(QLatin1String("UseThemeBackgroundColor")); const QString EditorWindow::Private::configVerticalSplitterSizesEntry(QLatin1String("Vertical Splitter Sizes")); const QString EditorWindow::Private::configVerticalSplitterStateEntry(QLatin1String("Vertical Splitter State")); void EditorWindow::Private::legacyUpdateSplitterState(KConfigGroup& group) { // Check if the thumbnail size in the config file is splitter based (the // old method), and convert to dock based if needed. + if (group.hasKey(configSplitterStateEntry)) { // Read splitter state from config file + QByteArray state; state = QByteArray::fromBase64(group.readEntry(configSplitterStateEntry, state)); // Do a cheap check: a splitter state with 3 windows is always 34 bytes. + if (state.count() == 34) { // Read the state in streamwise fashion. + QDataStream stream(state); // The first 8 bytes are resp. the magic number and the version // (which should be 0, otherwise it's not saved with an older // digiKam version). Then follows the list of window sizes. + qint32 marker; qint32 version = -1; QList sizesList; stream >> marker; stream >> version; if (version == 0) { stream >> sizesList; if (sizesList.count() == 3) { qCDebug(DIGIKAM_GENERAL_LOG) << "Found splitter based config, converting to dockbar"; + // Remove the first entry (the thumbbar) and write the rest // back. Then it should be fine. + sizesList.removeFirst(); QByteArray newData; QDataStream newStream(&newData, QIODevice::WriteOnly); newStream << marker; newStream << version; newStream << sizesList; char s[24]; int numBytes = stream.readRawData(s, 24); newStream.writeRawData(s, numBytes); group.writeEntry(configSplitterStateEntry, newData.toBase64()); } } } } } void EditorWindow::Private::plugNewVersionInFormatAction(EditorWindow* const q, QMenu* const menuAction, const QString& text, const QString& format) { QAction* const action = new QAction(text, q); connect(action, &QAction::triggered, q, [q, format]() { q->saveNewVersionInFormat(format); }); menuAction->addAction(action); } } // namespace Digikam #endif // DIGIKAM_IMAGE_EDITOR_WINDOW_PRIVATE_H diff --git a/core/utilities/imageeditor/editor/imageiface.cpp b/core/utilities/imageeditor/editor/imageiface.cpp index d57199da2a..459c1ed21b 100644 --- a/core/utilities/imageeditor/editor/imageiface.cpp +++ b/core/utilities/imageeditor/editor/imageiface.cpp @@ -1,478 +1,489 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2004-02-14 * Description : image data interface for image tools * * Copyright (C) 2004-2005 by Renchi Raju * Copyright (C) 2004-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #include "imageiface.h" // Qt includes #include #include #include #include #include // Local includes #include "digikam_debug.h" #include "exposurecontainer.h" #include "iccmanager.h" #include "iccsettingscontainer.h" #include "icctransform.h" #include "editorcore.h" #include "dmetadata.h" #include "digikam_globals.h" namespace Digikam { class Q_DECL_HIDDEN ImageIface::Private { public: explicit Private() : previewType(FullImage), originalWidth(0), originalHeight(0), originalBytesDepth(0), constrainWidth(0), constrainHeight(0), previewWidth(0), previewHeight(0), core(EditorCore::defaultInstance()) { } QPixmap checkPixmap(); uchar* previewImageData(); public: ImageIface::PreviewType previewType; int originalWidth; int originalHeight; int originalBytesDepth; int constrainWidth; int constrainHeight; int previewWidth; int previewHeight; QPixmap qcheck; DImg previewImage; DImg targetPreviewImage; EditorCore* const core; }; QPixmap ImageIface::Private::checkPixmap() { if (qcheck.isNull()) { qcheck = QPixmap(8, 8); QPainter p; p.begin(&qcheck); p.fillRect(0, 0, 4, 4, QColor(144, 144, 144)); p.fillRect(4, 4, 4, 4, QColor(144, 144, 144)); p.fillRect(0, 4, 4, 4, QColor(100, 100, 100)); p.fillRect(4, 0, 4, 4, QColor(100, 100, 100)); p.end(); } return qcheck; } uchar* ImageIface::Private::previewImageData() { if (previewImage.isNull()) { DImg* im = nullptr; if (previewType == FullImage) { im = core->getImg(); if (!im || im->isNull()) { return nullptr; } } else // ImageSelection { im = new DImg(core->getImgSelection()); if (!im) { return nullptr; } if (im->isNull()) { delete im; return nullptr; } im->setIccProfile(core->getEmbeddedICC()); } QSize sz(im->width(), im->height()); sz.scale(constrainWidth, constrainHeight, Qt::KeepAspectRatio); previewImage = im->smoothScale(sz.width(), sz.height()); previewWidth = previewImage.width(); previewHeight = previewImage.height(); // only create another copy if needed, in setPreviewImage + targetPreviewImage = previewImage; if (previewType == ImageSelection) { delete im; } } DImg previewData = previewImage.copyImageData(); + return previewData.stripImageData(); } // ------------------------------------------------------------------------------------------------------ ImageIface::ImageIface(const QSize& size) : d(new Private) { d->constrainWidth = size.width(); d->constrainHeight = size.height(); d->originalWidth = d->core->origWidth(); d->originalHeight = d->core->origHeight(); d->originalBytesDepth = d->core->bytesDepth(); } ImageIface::~ImageIface() { delete d; } void ImageIface::setPreviewType(PreviewType type) { d->previewType = type; } ImageIface::PreviewType ImageIface::previewType() const { return d->previewType; } DImg *ImageIface::previewReference() { return &(d->previewImage); } DColor ImageIface::colorInfoFromOriginal(const QPoint& point) const { if (!original() || original()->isNull()) { qCWarning(DIGIKAM_GENERAL_LOG) << "No image data available!"; return DColor(); } - if (point.x() > originalSize().width() || point.y() > originalSize().height()) + if ((point.x() > originalSize().width()) || (point.y() > originalSize().height())) { qCWarning(DIGIKAM_GENERAL_LOG) << "Coordinate out of range!"; + return DColor(); } return original()->getPixelColor(point.x(), point.y()); } DColor ImageIface::colorInfoFromPreview(const QPoint& point) const { - if (d->previewImage.isNull() || point.x() > d->previewWidth || point.y() > d->previewHeight) + if (d->previewImage.isNull() || (point.x() > d->previewWidth) || (point.y() > d->previewHeight)) { qCWarning(DIGIKAM_GENERAL_LOG) << "Coordinate out of range or no image data available!"; + return DColor(); } return d->previewImage.getPixelColor(point.x(), point.y()); } DColor ImageIface::colorInfoFromTargetPreview(const QPoint& point) const { - if (d->targetPreviewImage.isNull() || point.x() > d->previewWidth || point.y() > d->previewHeight) + if (d->targetPreviewImage.isNull() || (point.x() > d->previewWidth) || (point.y() > d->previewHeight)) { qCWarning(DIGIKAM_GENERAL_LOG) << "Coordinate out of range or no image data available!"; + return DColor(); } return d->targetPreviewImage.getPixelColor(point.x(), point.y()); } DImg ImageIface::setPreviewSize(const QSize& size) const { d->previewImage.reset(); d->targetPreviewImage.reset(); d->constrainWidth = size.width(); d->constrainHeight = size.height(); return preview(); } DImg ImageIface::preview() const { // NOTE: corrects the values for width and height of the preview image from the image data interface // See Bug #320382 for details. + uchar* const data = d->previewImageData(); + return DImg(d->previewWidth, d->previewHeight, previewSixteenBit(), previewHasAlpha(), data, false); } DImg* ImageIface::original() const { return d->core->getImg(); } DImg ImageIface::selection() const { return d->core->getImgSelection(); } void ImageIface::setPreviewIccProfile(const IccProfile& profile) { d->targetPreviewImage.detach(); d->targetPreviewImage.setIccProfile(profile); } void ImageIface::crop(const QRect& region) { d->core->crop(region); } void ImageIface::setOriginalIccProfile(const IccProfile& profile) { d->core->putIccProfile(profile); } QSize ImageIface::previewSize() const { return QSize(d->previewWidth, d->previewHeight); } bool ImageIface::previewSixteenBit() const { return originalSixteenBit(); } bool ImageIface::previewHasAlpha() const { return originalHasAlpha(); } QSize ImageIface::originalSize() const { return QSize(d->core->origWidth(), d->core->origHeight()); } bool ImageIface::originalSixteenBit() const { return d->core->sixteenBit(); } bool ImageIface::originalHasAlpha() const { return d->core->hasAlpha(); } QRect ImageIface::selectionRect() const { return (d->core->getSelectedArea()); } void ImageIface::convertOriginalColorDepth(int depth) { d->core->convertDepth(depth); } QPixmap ImageIface::convertToPixmap(DImg& img) const { return d->core->convertToPixmap(img); } IccProfile ImageIface::originalIccProfile() const { return d->core->getEmbeddedICC(); } MetaEngineData ImageIface::originalMetadata() const { DImg* const img = original(); if (img) + { return (img->getMetadata()); + } return MetaEngineData(); } void ImageIface::setOriginalMetadata(const MetaEngineData& meta) { DImg* const img = original(); if (img) + { img->setMetadata(meta); + } } PhotoInfoContainer ImageIface::originalPhotoInfo() const { return (DMetadata(originalMetadata()).getPhotographInformation()); } void ImageIface::paint(QPaintDevice* const device, const QRect& rect, QPainter* const painter) { int x = rect.x(); int y = rect.y(); int w = rect.width(); int h = rect.height(); QPainter* p = nullptr; QPainter localPainter; if (painter) { p = painter; } else { p = &localPainter; p->begin(device); } int width = w > 0 ? qMin(d->previewWidth, w) : d->previewWidth; int height = h > 0 ? qMin(d->previewHeight, h) : d->previewHeight; if (!d->targetPreviewImage.isNull()) { if (d->targetPreviewImage.hasAlpha()) { p->drawTiledPixmap(x, y, width, height, d->checkPixmap()); } QPixmap pixImage; bool doSoftProofing = d->core->softProofingEnabled(); ICCSettingsContainer iccSettings = d->core->getICCSettings(); if (iccSettings.enableCM && (iccSettings.useManagedView || doSoftProofing)) { IccManager manager(d->targetPreviewImage); IccTransform monitorICCtrans; if (doSoftProofing) { monitorICCtrans = manager.displaySoftProofingTransform(IccProfile(iccSettings.defaultProofProfile)); } else { monitorICCtrans = manager.displayTransform(); } pixImage = d->targetPreviewImage.convertToPixmap(monitorICCtrans); } else { pixImage = d->targetPreviewImage.convertToPixmap(); } p->drawPixmap(x, y, pixImage, 0, 0, width, height); // Show the Over/Under exposure pixels indicators ExposureSettingsContainer* const expoSettings = d->core->getExposureSettings(); if (expoSettings && (expoSettings->underExposureIndicator || expoSettings->overExposureIndicator)) { QImage pureColorMask = d->targetPreviewImage.pureColorMask(expoSettings); QPixmap pixMask = QPixmap::fromImage(pureColorMask); p->drawPixmap(x, y, pixMask, 0, 0, width, height); } } if (!painter) { p->end(); } } void ImageIface::setSelection(const QString& caller, const FilterAction& action, const DImg& img) { - if (img.hasAlpha() != originalHasAlpha() || - img.sixteenBit() != originalSixteenBit() || - img.size() != selectionRect().size() + if ((img.hasAlpha() != originalHasAlpha()) || + (img.sixteenBit() != originalSixteenBit()) || + (img.size() != selectionRect().size()) ) { qCDebug(DIGIKAM_GENERAL_LOG) << "Properties of image to overwrite selection differs than original image"; return; } if (img.isNull()) { qCDebug(DIGIKAM_GENERAL_LOG) << "No image data to handle"; return; } d->core->putImgSelection(caller, action, img); } void ImageIface::setPreview(const DImg& img) { - if (img.hasAlpha() != previewHasAlpha() || - img.sixteenBit() != previewSixteenBit() + if ((img.hasAlpha() != previewHasAlpha()) || + (img.sixteenBit() != previewSixteenBit()) ) { qCDebug(DIGIKAM_GENERAL_LOG) << "Properties of image differs than preview"; return; } uchar* const data = img.bits(); if (!data) { qCDebug(DIGIKAM_GENERAL_LOG) << "No preview image data to handle"; return; } d->targetPreviewImage.detach(); d->targetPreviewImage.putImageData(data); } void ImageIface::setOriginal(const QString& caller, const FilterAction& action, const DImg& img) { if (img.isNull()) { qCDebug(DIGIKAM_GENERAL_LOG) << "No image data to handle"; return; } d->core->putImg(caller, action, img); } } // namespace Digikam diff --git a/core/utilities/imageeditor/editor/imageiface.h b/core/utilities/imageeditor/editor/imageiface.h index 73bcb02c07..343b0c6337 100644 --- a/core/utilities/imageeditor/editor/imageiface.h +++ b/core/utilities/imageeditor/editor/imageiface.h @@ -1,187 +1,208 @@ /* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2004-02-14 * Description : image data interface for image tools * * Copyright (C) 2004-2005 by Renchi Raju * Copyright (C) 2004-2020 by Gilles Caulier * * 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, 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. * * ============================================================ */ #ifndef DIGIKAM_IMAGE_IFACE_H #define DIGIKAM_IMAGE_IFACE_H // Qt includes #include #include // Local includes #include "dimg.h" #include "dcolor.h" #include "filteraction.h" #include "photoinfocontainer.h" #include "digikam_export.h" class QPaintDevice; namespace Digikam { class DIGIKAM_EXPORT ImageIface { public: enum PreviewType { - FullImage, /// Preview will be rendered using full image. - ImageSelection /// Preview will be rendered using current selection from editor canvas. + FullImage, ///< Preview will be rendered using full image. + ImageSelection ///< Preview will be rendered using current selection from editor canvas. }; public: - /** Standard constructor. Size is the constrain dimension of preview. This can be null size. + /** + * Standard constructor. Size is the constrain dimension of preview. This can be null size. */ explicit ImageIface(const QSize& size = QSize(0, 0)); ~ImageIface(); - /** If useSelection is true, preview will be rendered using current selection in editor instead the full - * image. Default preview is FullImage. + /** + * If useSelection is true, preview will be rendered using current selection in editor instead the full + * image. Default preview is FullImage. */ void setPreviewType(PreviewType type = FullImage); - /** Sets preview size and returns new preview as with getPreview. - * The parameters are only hints, previewSize() may differ from size. + /** + * Sets preview size and returns new preview as with getPreview. + * The parameters are only hints, previewSize() may differ from size. */ DImg setPreviewSize(const QSize& size) const; - /** Methods to get/set preview image information. + /** + * Methods to get/set preview image information. */ QSize previewSize() const; bool previewHasAlpha() const; bool previewSixteenBit() const; PreviewType previewType() const; - /** Return a pointer to the DImg object representing the preview image. + /** + * Return a pointer to the DImg object representing the preview image. * This function is a backdoor for preview editing. */ DImg* previewReference(); - /** Return a DImg object representing the preview image. + /** + * Return a DImg object representing the preview image. */ DImg preview() const; - /** Return current image selection position and size into original image coordinates. + /** + * Return current image selection position and size into original image coordinates. */ QRect selectionRect() const; - /** Return a DImg object representing the current original image selection. + /** + * Return a DImg object representing the current original image selection. */ DImg selection() const; - /** Crop the original image currently hosted by editor to the region. + /** + * Crop the original image currently hosted by editor to the region. */ void crop(const QRect& region); - /** Get colors from original, (unchanged) preview - * or target preview (set by setPreviewImage) image. + /** + * Get colors from original, (unchanged) preview + * or target preview (set by setPreviewImage) image. */ DColor colorInfoFromOriginal(const QPoint& point) const; DColor colorInfoFromPreview(const QPoint& point) const; DColor colorInfoFromTargetPreview(const QPoint& point) const; - /** Methods to get/set original image information. + /** + * Methods to get/set original image information. */ QSize originalSize() const; bool originalHasAlpha() const; bool originalSixteenBit() const; - /** Original image meta-data management methods. + /** + * Original image meta-data management methods. */ IccProfile originalIccProfile() const; PhotoInfoContainer originalPhotoInfo() const; MetaEngineData originalMetadata() const; void setOriginalMetadata(const MetaEngineData& meta); - /** Return a pointer to the DImg object representing the original image. - * This object may not be modified or stored. Make copies if you need. + /** + * Return a pointer to the DImg object representing the original image. + * This object may not be modified or stored. Make copies if you need. */ DImg* original() const; - /** Convert depth of original image. + /** + * Convert depth of original image. */ void convertOriginalColorDepth(int depth); - /** Convert a DImg image to a pixmap for screen using color - * managed view if necessary. + /** + * Convert a DImg image to a pixmap for screen using color + * managed view if necessary. */ QPixmap convertToPixmap(DImg& img) const; - /** Paint the current target preview image (or the preview image, - * if setPreview has not been called) on the given paint device. - * at x|y, with given maximum width and height taken from rectangle rect. + /** + * Paint the current target preview image (or the preview image, + * if setPreview has not been called) on the given paint device. + * at x|y, with given maximum width and height taken from rectangle rect. */ void paint(QPaintDevice* const device, const QRect& rect, QPainter* const painter = nullptr); - /** Set the color profile of the original image. + /** + * Set the color profile of the original image. */ void setOriginalIccProfile(const IccProfile& profile); - /** Set the color profile of the preview image. + /** + * Set the color profile of the preview image. */ void setPreviewIccProfile(const IccProfile& profile); - /** Replace the data of the current original image selection with the given data. - * The characteristics of the data must match the characteristics of the current - * selection as returned by the selectionWidth(), selectionHeight(), - * originalSixteenBit() and originalHasAlpha() methods. - * Caller is an i18n'ed string that will be shown as the undo/redo action name. + /** + * Replace the data of the current original image selection with the given data. + * The characteristics of the data must match the characteristics of the current + * selection as returned by the selectionWidth(), selectionHeight(), + * originalSixteenBit() and originalHasAlpha() methods. + * Caller is an i18n'ed string that will be shown as the undo/redo action name. */ void setSelection(const QString& caller, const FilterAction& action, const DImg& img); - /** Replace the stored target preview with the given image. - * The characteristics of the data must match the characteristics of the current - * as returned by the preview...() methods. - * The target preview image is used by the paint() and - * colorInfoFromTargetPreview() methods. - * The image returned by getPreview() is unaffected. + /** + * Replace the stored target preview with the given image. + * The characteristics of the data must match the characteristics of the current + * as returned by the preview...() methods. + * The target preview image is used by the paint() and + * colorInfoFromTargetPreview() methods. + * The image returned by getPreview() is unaffected. */ void setPreview(const DImg& img); - /** Replace the data of the original with the given image. - * The characteristics of the data must match the characteristics of - * the original image as returned by the original...() methods, - * The size of image can be changed. - * Caller is an i18n'ed string that will be shown as the undo/redo action name. + /** + * Replace the data of the original with the given image. + * The characteristics of the data must match the characteristics of + * the original image as returned by the original...() methods, + * The size of image can be changed. + * Caller is an i18n'ed string that will be shown as the undo/redo action name. */ void setOriginal(const QString& caller, const FilterAction& action, const DImg& img); private: // Hidden copy constructor and assignment operator. ImageIface(const ImageIface&); ImageIface& operator=(const ImageIface&); class Private; Private* const d; }; } // namespace Digikam #endif // DIGIKAM_IMAGE_IFACE_H