diff --git a/krita/image/CMakeLists.txt b/krita/image/CMakeLists.txt index ce0b7b69f6..352e38d640 100644 --- a/krita/image/CMakeLists.txt +++ b/krita/image/CMakeLists.txt @@ -1,388 +1,389 @@ add_subdirectory( tests ) ########### next target ############### add_definitions(${KDE4_ENABLE_EXCEPTIONS}) # Chose a tiles backend # 1 - image/tiles # 3 - image/tiles3 set(USE_TILESYSTEM 3) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config-tiles.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/../config-tiles.h) ### WRONG PLACE??? if(USE_TILESYSTEM EQUAL 3) set(libkritatile_SRCS ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_tile.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_tile_data.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_tile_data_store.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_tile_data_pooler.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_tiled_data_manager.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_memento_manager.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_hline_iterator.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_vline_iterator.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/kis_random_accessor.cc ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_abstract_compression.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_lzf_compression.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_abstract_tile_compressor.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_legacy_tile_compressor.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_tile_compressor_2.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_chunk_allocator.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_memory_window.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_swapped_data_store.cpp ${CMAKE_SOURCE_DIR}/krita/image/tiles3/swap/kis_tile_data_swapper.cpp ) add_subdirectory( tiles3 ) endif() option(HAVE_MEMORY_LEAK_TRACKER "Enable memory leak tracker (always disabled in release build)" OFF) option(HAVE_BACKTRACE_SUPPORT "Enable recording of backtrace in memory leak tracker" OFF) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config-memory-leak-tracker.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-memory-leak-tracker.h) ### WRONG PLACE??? include_directories( ${CMAKE_SOURCE_DIR}/krita/image/metadata 3rdparty ) if(FFTW3_FOUND) include_directories(${FFTW3_INCLUDE_DIRS}) endif() if(HAVE_VC) include_directories(${Vc_INCLUDE_DIR}) ko_compile_for_all_implementations(__per_arch_circle_mask_generator_objs kis_brush_mask_applicator_factories.cpp) else() set(__per_arch_circle_mask_generator_objs kis_brush_mask_applicator_factories.cpp) endif() set(kritaimage_LIB_SRCS ${libkritatile_SRCS} kis_debug.cpp kis_distance_information.cpp kis_painter.cc kis_progress_updater.cpp brushengine/kis_paint_information.cc brushengine/kis_paintop.cc brushengine/kis_paintop_factory.cpp brushengine/kis_paintop_preset.cpp brushengine/kis_paintop_registry.cc brushengine/kis_paintop_settings.cpp brushengine/kis_locked_properties.cc brushengine/kis_locked_properties_proxy.cpp brushengine/kis_locked_properties_server.cpp commands/kis_deselect_global_selection_command.cpp commands/kis_image_change_layers_command.cpp commands/kis_image_command.cpp commands/kis_image_set_projection_color_space_command.cpp commands/kis_image_layer_add_command.cpp commands/kis_image_layer_move_command.cpp commands/kis_image_layer_remove_command.cpp commands/kis_image_layer_remove_command_impl.cpp commands/kis_image_node_lower_command.cpp commands/kis_image_node_raise_command.cpp commands/kis_image_node_to_bottom_command.cpp commands/kis_image_node_to_top_command.cpp commands/kis_image_lock_command.cpp commands/kis_layer_command.cpp commands/kis_layer_props_command.cpp commands/kis_node_command.cpp commands/kis_node_compositeop_command.cpp commands/kis_node_opacity_command.cpp commands/kis_node_property_list_command.cpp commands/kis_reselect_global_selection_command.cpp commands/kis_set_global_selection_command.cpp commands_new/kis_saved_commands.cpp commands_new/kis_processing_command.cpp commands_new/kis_image_resize_command.cpp commands_new/kis_image_set_resolution_command.cpp commands_new/kis_node_move_command2.cpp commands_new/kis_set_layer_style_command.cpp commands_new/kis_selection_move_command2.cpp commands_new/kis_update_command.cpp processing/kis_do_nothing_processing_visitor.cpp processing/kis_simple_processing_visitor.cpp processing/kis_crop_processing_visitor.cpp processing/kis_crop_selections_processing_visitor.cpp processing/kis_transform_processing_visitor.cpp processing/kis_mirror_processing_visitor.cpp filter/kis_filter.cc filter/kis_filter_configuration.cc filter/kis_filter_registry.cc filter/kis_color_transformation_filter.cc generator/kis_generator.cpp generator/kis_generator_layer.cpp generator/kis_generator_registry.cpp floodfill/kis_fill_interval_map.cpp floodfill/kis_scanline_fill.cpp kis_adjustment_layer.cc kis_selection_based_layer.cpp kis_node_filter_interface.cpp kis_base_accessor.cpp kis_base_node.cpp kis_base_processor.cpp kis_basic_math_toolbox.cpp kis_bookmarked_configuration_manager.cc kis_clone_info.cpp kis_clone_layer.cpp kis_colorspace_convert_visitor.cpp kis_config_widget.cpp kis_convolution_kernel.cc kis_convolution_painter.cc kis_gaussian_kernel.cpp kis_cubic_curve.cpp kis_default_bounds.cpp kis_default_bounds_base.cpp kis_effect_mask.cc kis_fast_math.cpp kis_fill_painter.cc kis_filter_mask.cpp kis_filter_strategy.cc kis_transform_mask.cpp kis_transform_mask_params_interface.cpp kis_recalculate_transform_mask_job.cpp kis_recalculate_generator_layer_job.cpp kis_transform_mask_params_factory_registry.cpp kis_safe_transform.cpp kis_gradient_painter.cc kis_gradient_shape_strategy.cpp kis_cached_gradient_shape_strategy.cpp kis_polygonal_gradient_shape_strategy.cpp kis_iterator_ng.cpp kis_async_merger.cpp kis_merge_walker.cc kis_updater_context.cpp kis_update_job_item.cpp kis_stroke_strategy_undo_command_based.cpp kis_simple_stroke_strategy.cpp kis_stroke_job_strategy.cpp kis_stroke_strategy.cpp kis_stroke.cpp kis_strokes_queue.cpp kis_simple_update_queue.cpp kis_update_scheduler.cpp kis_queues_progress_updater.cpp kis_composite_progress_proxy.cpp kis_update_time_monitor.cpp kis_group_layer.cc kis_count_visitor.cpp kis_histogram.cc kis_image_interfaces.cpp kis_node_graph_listener.cpp kis_image.cc kis_image_signal_router.cpp kis_image_config.cpp + kis_crop_saved_extra_data.cpp kis_signal_compressor.cpp kis_signal_compressor_with_param.cpp kis_thread_safe_signal_compressor.cpp kis_acyclic_signal_connector.cpp kis_layer.cc kis_indirect_painting_support.cpp kis_abstract_projection_plane.cpp kis_layer_projection_plane.cpp kis_mask_projection_plane.cpp kis_projection_leaf.cpp kis_mask.cc kis_base_mask_generator.cpp kis_rect_mask_generator.cpp kis_circle_mask_generator.cpp kis_gauss_circle_mask_generator.cpp kis_gauss_rect_mask_generator.cpp ${__per_arch_circle_mask_generator_objs} kis_curve_circle_mask_generator.cpp kis_curve_rect_mask_generator.cpp kis_math_toolbox.cpp kis_memory_leak_tracker.cpp kis_memory_statistics_server.cpp kis_name_server.cpp kis_node.cpp kis_node_facade.cpp kis_node_progress_proxy.cpp kis_busy_progress_indicator.cpp kis_node_visitor.cpp kis_paint_device.cc kis_fixed_paint_device.cpp kis_paint_layer.cc kis_perspective_grid.cpp kis_perspective_math.cpp kis_pixel_selection.cpp kis_processing_information.cpp kis_properties_configuration.cc kis_random_accessor_ng.cpp kis_random_generator.cc kis_random_sub_accessor.cpp kis_wrapped_random_accessor.cpp kis_selection.cc kis_selection_mask.cpp kis_update_outline_job.cpp kis_update_selection_job.cpp kis_serializable_configuration.cc kis_shared.cc kis_transaction_data.cpp kis_transform_worker.cc kis_perspectivetransform_worker.cpp bsplines/kis_bspline_1d.cpp bsplines/kis_bspline_2d.cpp bsplines/kis_nu_bspline_2d.cpp kis_warptransform_worker.cc kis_cage_transform_worker.cpp kis_liquify_transform_worker.cpp kis_green_coordinates_math.cpp kis_algebra_2d.cpp kis_dom_utils.cpp kis_transparency_mask.cc kis_undo_store.cpp kis_undo_stores.cpp kis_undo_adapter.cpp kis_surrogate_undo_adapter.cpp kis_legacy_undo_adapter.cpp kis_post_execution_undo_adapter.cpp kis_processing_visitor.cpp kis_processing_applicator.cpp krita_utils.cpp kis_outline_generator.cpp kis_layer_composition.cpp kis_selection_filters.cpp metadata/kis_meta_data_entry.cc metadata/kis_meta_data_filter.cc metadata/kis_meta_data_filter_p.cc metadata/kis_meta_data_filter_registry.cc metadata/kis_meta_data_filter_registry_model.cc metadata/kis_meta_data_io_backend.cc metadata/kis_meta_data_merge_strategy.cc metadata/kis_meta_data_merge_strategy_p.cc metadata/kis_meta_data_merge_strategy_registry.cc metadata/kis_meta_data_parser.cc metadata/kis_meta_data_schema.cc metadata/kis_meta_data_schema_registry.cc metadata/kis_meta_data_store.cc metadata/kis_meta_data_type_info.cc metadata/kis_meta_data_validator.cc metadata/kis_meta_data_value.cc recorder/kis_action_recorder.cc recorder/kis_macro.cc recorder/kis_macro_player.cc recorder/kis_node_query_path.cc recorder/kis_play_info.cc recorder/kis_recorded_action.cc recorder/kis_recorded_action_factory_registry.cc recorder/kis_recorded_action_load_context.cpp recorder/kis_recorded_action_save_context.cpp recorder/kis_recorded_filter_action.cpp recorder/kis_recorded_fill_paint_action.cpp recorder/kis_recorded_node_action.cc recorder/kis_recorded_paint_action.cpp recorder/kis_recorded_path_paint_action.cpp recorder/kis_recorded_shape_paint_action.cpp kis_psd_layer_style.cpp layerstyles/kis_layer_style_filter.cpp layerstyles/kis_layer_style_filter_environment.cpp layerstyles/kis_layer_style_filter_projection_plane.cpp layerstyles/kis_layer_style_projection_plane.cpp layerstyles/kis_ls_drop_shadow_filter.cpp layerstyles/kis_ls_satin_filter.cpp layerstyles/kis_ls_stroke_filter.cpp layerstyles/kis_ls_bevel_emboss_filter.cpp layerstyles/kis_ls_overlay_filter.cpp layerstyles/kis_ls_utils.cpp layerstyles/gimp_bump_map.cpp ) set(einspline_SRCS 3rdparty/einspline/bspline_create.cpp 3rdparty/einspline/bspline_data.cpp 3rdparty/einspline/multi_bspline_create.cpp 3rdparty/einspline/nubasis.cpp 3rdparty/einspline/nubspline_create.cpp 3rdparty/einspline/nugrid.cpp ) kde4_add_library(kritaimage SHARED ${kritaimage_LIB_SRCS} ${einspline_SRCS}) target_link_libraries(kritaimage ${KDE4_KDEUI_LIBS} kritaglobal kritapsd koodf pigmentcms kundo2 kowidgetutils) target_link_libraries(kritaimage LINK_INTERFACE_LIBRARIES kritaglobal kritapsd koodf pigmentcms kundo2 kowidgetutils) target_link_libraries(kritaimage ${Boost_SYSTEM_LIBRARY}) message("DEBUG_BOOST_LIBRARIES = " ${Boost_LIBRARIES}) message("DEBUG_BOOST_SYSTEM_FOUND = " ${Boost_SYSTEM_FOUND}) message("DEBUG_BOOST_SYSTEM_LIBRARY = " ${Boost_SYSTEM_LIBRARY}) if(OPENEXR_FOUND) target_link_libraries(kritaimage ${OPENEXR_LIBRARIES}) endif() if(FFTW3_FOUND) target_link_libraries(kritaimage ${FFTW3_LIBRARIES}) endif() if(HAVE_VC) target_link_libraries(kritaimage ${Vc_LIBRARIES}) endif() if (NOT GSL_FOUND) message (WARNING "KRITA WARNING! No GNU Scientific Library was found! Krita's Shaped Gradients might be non-normalized! Please install GSL library.") else () target_link_libraries(kritaimage ${GSL_LIBRARIES} ${GSL_CBLAS_LIBRARIES}) endif () set_target_properties(kritaimage PROPERTIES VERSION ${GENERIC_CALLIGRA_LIB_VERSION} SOVERSION ${GENERIC_CALLIGRA_LIB_SOVERSION} ) install(TARGETS kritaimage ${INSTALL_TARGETS_DEFAULT_ARGS}) ########### install schemas ############# install( FILES metadata/schemas/dc.schema metadata/schemas/exif.schema metadata/schemas/tiff.schema metadata/schemas/mkn.schema metadata/schemas/xmp.schema metadata/schemas/xmpmm.schema metadata/schemas/xmprights.schema DESTINATION ${DATA_INSTALL_DIR}/krita/metadata/schemas) ########### install files ############### install( FILES kis_base_node.h kis_base_processor.h kis_config_widget.h kis_convolution_kernel.h kis_convolution_painter.h kis_convolution_worker.h kis_cubic_curve.h kis_debug.h kis_default_bounds.h kis_distance_information.h filter/kis_filter.h filter/kis_filter_registry.h kis_filter_strategy.h kis_global.h kis_image.h kis_mask.h kis_node.h kis_node_facade.h kis_node_graph_listener.h kis_painter.h kis_paint_device.h kis_properties_configuration.h kis_processing_information.h kis_transform_worker.h kis_perspectivetransform_worker.h kis_warptransform_worker.h kis_serializable_configuration.h kis_selection.h kis_shared.h kis_shared_ptr.h kis_transaction.h kis_types.h krita_export.h filter/kis_filter_configuration.h generator/kis_generator.h generator/kis_generator_registry.h brushengine/kis_locked_properties.h brushengine/kis_locked_properties_proxy.h brushengine/kis_locked_properties_server.h DESTINATION ${INCLUDE_INSTALL_DIR}/krita) diff --git a/krita/image/kis_crop_saved_extra_data.cpp b/krita/image/kis_crop_saved_extra_data.cpp new file mode 100644 index 0000000000..d820c93579 --- /dev/null +++ b/krita/image/kis_crop_saved_extra_data.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015 Dmitry Kazakov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "kis_crop_saved_extra_data.h" + +#include "kis_node.h" + + +KisCropSavedExtraData::KisCropSavedExtraData(Type type, + QRect cropRect, + KisNodeSP cropNode) + : m_type(type), + m_cropRect(cropRect), + m_cropNode(cropNode) +{ +} + +KisCropSavedExtraData::~KisCropSavedExtraData() +{ +} diff --git a/krita/image/kis_crop_saved_extra_data.h b/krita/image/kis_crop_saved_extra_data.h new file mode 100644 index 0000000000..54cbd57591 --- /dev/null +++ b/krita/image/kis_crop_saved_extra_data.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2015 Dmitry Kazakov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#ifndef __KIS_CROP_SAVED_EXTRA_DATA_H +#define __KIS_CROP_SAVED_EXTRA_DATA_H + +#include + +#include "kundo2commandextradata.h" +#include "kis_types.h" +#include "krita_export.h" + + +class KRITAIMAGE_EXPORT KisCropSavedExtraData : public KUndo2CommandExtraData +{ +public: + enum Type { + CROP_IMAGE, + RESIZE_IMAGE, + CROP_LAYER + }; + +public: + + KisCropSavedExtraData(Type type, QRect cropRect, KisNodeSP cropNode = 0); + ~KisCropSavedExtraData(); + + inline Type type() const { + return m_type; + } + + inline QRect cropRect() const { + return m_cropRect; + } + + inline KisNodeSP cropNode() const { + return m_cropNode; + } + +private: + Type m_type; + QRect m_cropRect; + KisNodeSP m_cropNode; +}; + +#endif /* __KIS_CROP_SAVED_EXTRA_DATA_H */ diff --git a/krita/image/kis_image.cc b/krita/image/kis_image.cc index 5c7868769d..72e9b37048 100644 --- a/krita/image/kis_image.cc +++ b/krita/image/kis_image.cc @@ -1,1630 +1,1641 @@ /* * Copyright (c) 2002 Patrick Julien * Copyright (c) 2007 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_image.h" #include // WORDS_BIGENDIAN #include #include #include #include #include #include #include #include #include #include "KoColorSpaceRegistry.h" #include "KoColor.h" #include "KoColorConversionTransformation.h" #include "KoColorProfile.h" #include #include "recorder/kis_action_recorder.h" #include "kis_adjustment_layer.h" #include "kis_annotation.h" #include "kis_change_profile_visitor.h" #include "kis_colorspace_convert_visitor.h" #include "kis_count_visitor.h" #include "kis_filter_strategy.h" #include "kis_group_layer.h" #include "commands/kis_image_commands.h" #include "kis_layer.h" #include "kis_meta_data_merge_strategy_registry.h" #include "kis_name_server.h" #include "kis_paint_device.h" #include "kis_paint_layer.h" #include "kis_painter.h" #include "kis_perspective_grid.h" #include "kis_selection.h" #include "kis_transaction.h" #include "kis_types.h" #include "kis_meta_data_merge_strategy.h" #include "kis_memory_statistics_server.h" #include "kis_image_config.h" #include "kis_update_scheduler.h" #include "kis_image_signal_router.h" #include "kis_stroke_strategy.h" #include "kis_undo_stores.h" #include "kis_legacy_undo_adapter.h" #include "kis_post_execution_undo_adapter.h" #include "kis_transform_worker.h" #include "kis_processing_applicator.h" #include "processing/kis_crop_processing_visitor.h" #include "processing/kis_crop_selections_processing_visitor.h" #include "processing/kis_transform_processing_visitor.h" #include "commands_new/kis_image_resize_command.h" #include "commands_new/kis_image_set_resolution_command.h" #include "kis_composite_progress_proxy.h" #include "kis_layer_composition.h" #include "kis_wrapped_rect.h" +#include "kis_crop_saved_extra_data.h" #include "kis_layer_projection_plane.h" #include "kis_update_time_monitor.h" // #define SANITY_CHECKS #ifdef SANITY_CHECKS #define SANITY_CHECK_LOCKED(name) \ if (!locked()) warnKrita() << "Locking policy failed:" << name \ << "has been called without the image" \ "being locked"; #else #define SANITY_CHECK_LOCKED(name) #endif class KisImage::KisImagePrivate { public: quint32 lockCount; KisPerspectiveGrid* perspectiveGrid; qint32 width; qint32 height; double xres; double yres; const KoColorSpace * colorSpace; KisSelectionSP deselectedGlobalSelection; KisGroupLayerSP rootLayer; // The layers are contained in here QList dirtyLayers; // for thumbnails QList compositions; KisNodeSP isolatedRootNode; bool wrapAroundModePermitted; KisNameServer *nserver; KisUndoStore *undoStore; KisUndoAdapter *legacyUndoAdapter; KisPostExecutionUndoAdapter *postExecutionUndoAdapter; KisActionRecorder *recorder; vKisAnnotationSP annotations; QAtomicInt disableUIUpdateSignals; QAtomicInt disableDirtyRequests; KisImageSignalRouter *signalRouter; KisUpdateScheduler *scheduler; KisCompositeProgressProxy *compositeProgressProxy; bool startProjection; bool tryCancelCurrentStrokeAsync(); }; KisImage::KisImage(KisUndoStore *undoStore, qint32 width, qint32 height, const KoColorSpace * colorSpace, const QString& name, bool startProjection) : QObject(0) , KisShared() , m_d(new KisImagePrivate()) { setObjectName(name); dbgImage << "creating" << name; m_d->startProjection = startProjection; if (colorSpace == 0) { colorSpace = KoColorSpaceRegistry::instance()->rgb8(); } m_d->lockCount = 0; m_d->perspectiveGrid = 0; m_d->scheduler = 0; m_d->wrapAroundModePermitted = false; m_d->signalRouter = new KisImageSignalRouter(this); if (!undoStore) { undoStore = new KisDumbUndoStore(); } m_d->undoStore = undoStore; m_d->legacyUndoAdapter = new KisLegacyUndoAdapter(m_d->undoStore, this); m_d->postExecutionUndoAdapter = new KisPostExecutionUndoAdapter(m_d->undoStore, this); m_d->nserver = new KisNameServer(1); m_d->colorSpace = colorSpace; setRootLayer(new KisGroupLayer(this, "root", OPACITY_OPAQUE_U8)); m_d->xres = 1.0; m_d->yres = 1.0; m_d->width = width; m_d->height = height; m_d->recorder = new KisActionRecorder(this); m_d->compositeProgressProxy = new KisCompositeProgressProxy(); if (m_d->startProjection) { m_d->scheduler = new KisUpdateScheduler(this); m_d->scheduler->setProgressProxy(m_d->compositeProgressProxy); } connect(this, SIGNAL(sigImageModified()), KisMemoryStatisticsServer::instance(), SLOT(notifyImageChanged())); } KisImage::~KisImage() { dbgImage << "deleting kisimage" << objectName(); /** * Request the tools to end currently running strokes */ waitForDone(); /** * First delete the nodes, while strokes * and undo are still alive */ m_d->rootLayer = 0; KisUpdateScheduler *scheduler = m_d->scheduler; m_d->scheduler = 0; delete scheduler; delete m_d->postExecutionUndoAdapter; delete m_d->legacyUndoAdapter; delete m_d->undoStore; delete m_d->compositeProgressProxy; delete m_d->signalRouter; delete m_d->perspectiveGrid; delete m_d->nserver; delete m_d; disconnect(); // in case Qt gets confused } void KisImage::aboutToAddANode(KisNode *parent, int index) { KisNodeGraphListener::aboutToAddANode(parent, index); SANITY_CHECK_LOCKED("aboutToAddANode"); } void KisImage::nodeHasBeenAdded(KisNode *parent, int index) { KisNodeGraphListener::nodeHasBeenAdded(parent, index); SANITY_CHECK_LOCKED("nodeHasBeenAdded"); m_d->signalRouter->emitNodeHasBeenAdded(parent, index); KisNodeSP newNode = parent->at(index); if (!dynamic_cast(newNode.data())) { stopIsolatedMode(); } } void KisImage::aboutToRemoveANode(KisNode *parent, int index) { KisNodeSP deletedNode = parent->at(index); if (!dynamic_cast(deletedNode.data())) { stopIsolatedMode(); } KisNodeGraphListener::aboutToRemoveANode(parent, index); SANITY_CHECK_LOCKED("aboutToRemoveANode"); m_d->signalRouter->emitAboutToRemoveANode(parent, index); } void KisImage::nodeChanged(KisNode* node) { KisNodeGraphListener::nodeChanged(node); requestStrokeEnd(); m_d->signalRouter->emitNodeChanged(node); } KisSelectionSP KisImage::globalSelection() const { KisSelectionMaskSP selectionMask = m_d->rootLayer->selectionMask(); if (selectionMask) { return selectionMask->selection(); } else { return 0; } } void KisImage::setGlobalSelection(KisSelectionSP globalSelection) { KisSelectionMaskSP selectionMask = m_d->rootLayer->selectionMask(); if (!globalSelection) { if (selectionMask) { removeNode(selectionMask); } } else { if (!selectionMask) { selectionMask = new KisSelectionMask(this); selectionMask->initSelection(m_d->rootLayer); addNode(selectionMask); // If we do not set the selection now, the setActive call coming next // can be very, very expensive, depending on the size of the image. selectionMask->setSelection(globalSelection); selectionMask->setActive(true); } else { selectionMask->setSelection(globalSelection); } Q_ASSERT(m_d->rootLayer->childCount() > 0); Q_ASSERT(m_d->rootLayer->selectionMask()); } m_d->deselectedGlobalSelection = 0; m_d->legacyUndoAdapter->emitSelectionChanged(); } void KisImage::deselectGlobalSelection() { KisSelectionSP savedSelection = globalSelection(); setGlobalSelection(0); m_d->deselectedGlobalSelection = savedSelection; } bool KisImage::canReselectGlobalSelection() { return m_d->deselectedGlobalSelection; } void KisImage::reselectGlobalSelection() { if(m_d->deselectedGlobalSelection) { setGlobalSelection(m_d->deselectedGlobalSelection); } } QString KisImage::nextLayerName() const { if (m_d->nserver->currentSeed() == 0) { m_d->nserver->number(); return i18n("background"); } return i18n("Layer %1", m_d->nserver->number()); } void KisImage::rollBackLayerName() { m_d->nserver->rollback(); } KisCompositeProgressProxy* KisImage::compositeProgressProxy() { return m_d->compositeProgressProxy; } bool KisImage::locked() const { return m_d->lockCount != 0; } void KisImage::barrierLock() { if (!locked()) { requestStrokeEnd(); if (m_d->scheduler) { m_d->scheduler->barrierLock(); } } m_d->lockCount++; } bool KisImage::tryBarrierLock() { bool result = true; if (!locked()) { if (m_d->scheduler) { result = m_d->scheduler->tryBarrierLock(); } } if (result) { m_d->lockCount++; } return result; } void KisImage::lock() { if (!locked()) { requestStrokeEnd(); if (m_d->scheduler) { m_d->scheduler->lock(); } } m_d->lockCount++; } void KisImage::unlock() { Q_ASSERT(locked()); if (locked()) { m_d->lockCount--; if (m_d->lockCount == 0) { if (m_d->scheduler) { m_d->scheduler->unlock(); } } } } void KisImage::blockUpdates() { m_d->scheduler->blockUpdates(); } void KisImage::unblockUpdates() { m_d->scheduler->unblockUpdates(); } void KisImage::setSize(const QSize& size) { m_d->width = size.width(); m_d->height = size.height(); } void KisImage::resizeImageImpl(const QRect& newRect, bool cropLayers) { if (newRect == bounds() && !cropLayers) return; KUndo2MagicString actionName = cropLayers ? kundo2_i18n("Crop Image") : kundo2_i18n("Resize Image"); KisImageSignalVector emitSignals; emitSignals << ComplexSizeChangedSignal(newRect, newRect.size()); emitSignals << ModifiedSignal; + KisCropSavedExtraData *extraData = + new KisCropSavedExtraData(cropLayers ? + KisCropSavedExtraData::CROP_IMAGE : + KisCropSavedExtraData::RESIZE_IMAGE, + newRect); + KisProcessingApplicator applicator(this, m_d->rootLayer, KisProcessingApplicator::RECURSIVE | KisProcessingApplicator::NO_UI_UPDATES, - emitSignals, actionName); + emitSignals, actionName, extraData); if (cropLayers || !newRect.topLeft().isNull()) { KisProcessingVisitorSP visitor = new KisCropProcessingVisitor(newRect, cropLayers, true); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); } applicator.applyCommand(new KisImageResizeCommand(this, newRect.size())); applicator.end(); } void KisImage::resizeImage(const QRect& newRect) { resizeImageImpl(newRect, false); } void KisImage::cropImage(const QRect& newRect) { resizeImageImpl(newRect, true); } void KisImage::cropNode(KisNodeSP node, const QRect& newRect) { bool isLayer = dynamic_cast(node.data()); KUndo2MagicString actionName = isLayer ? kundo2_i18n("Crop Layer") : kundo2_i18n("Crop Mask"); KisImageSignalVector emitSignals; emitSignals << ModifiedSignal; + KisCropSavedExtraData *extraData = + new KisCropSavedExtraData(KisCropSavedExtraData::CROP_LAYER, + newRect, node); + KisProcessingApplicator applicator(this, node, KisProcessingApplicator::RECURSIVE, - emitSignals, actionName); + emitSignals, actionName, extraData); KisProcessingVisitorSP visitor = new KisCropProcessingVisitor(newRect, true, false); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); applicator.end(); } void KisImage::scaleImage(const QSize &size, qreal xres, qreal yres, KisFilterStrategy *filterStrategy) { bool resolutionChanged = xres != xRes() && yres != yRes(); bool sizeChanged = size != this->size(); if (!resolutionChanged && !sizeChanged) return; KisImageSignalVector emitSignals; if (resolutionChanged) emitSignals << ResolutionChangedSignal; if (sizeChanged) emitSignals << ComplexSizeChangedSignal(bounds(), size); emitSignals << ModifiedSignal; KUndo2MagicString actionName = sizeChanged ? kundo2_i18n("Scale Image") : kundo2_i18n("Change Image Resolution"); KisProcessingApplicator::ProcessingFlags signalFlags = (resolutionChanged || sizeChanged) ? KisProcessingApplicator::NO_UI_UPDATES : KisProcessingApplicator::NONE; KisProcessingApplicator applicator(this, m_d->rootLayer, KisProcessingApplicator::RECURSIVE | signalFlags, emitSignals, actionName); qreal sx = qreal(size.width()) / this->size().width(); qreal sy = qreal(size.height()) / this->size().height(); QTransform shapesCorrection; if (resolutionChanged) { shapesCorrection = QTransform::fromScale(xRes() / xres, yRes() / yres); } KisProcessingVisitorSP visitor = new KisTransformProcessingVisitor(sx, sy, 0, 0, QPointF(), 0, 0, 0, filterStrategy, shapesCorrection); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); if (resolutionChanged) { KUndo2Command *parent = new KisResetShapesCommand(m_d->rootLayer); new KisImageSetResolutionCommand(this, xres, yres, parent); applicator.applyCommand(parent); } if (sizeChanged) { applicator.applyCommand(new KisImageResizeCommand(this, size)); } applicator.end(); } void KisImage::scaleNode(KisNodeSP node, qreal sx, qreal sy, KisFilterStrategy *filterStrategy) { KUndo2MagicString actionName(kundo2_i18n("Scale Layer")); KisImageSignalVector emitSignals; emitSignals << ModifiedSignal; KisProcessingApplicator applicator(this, node, KisProcessingApplicator::RECURSIVE, emitSignals, actionName); KisProcessingVisitorSP visitor = new KisTransformProcessingVisitor(sx, sy, 0, 0, QPointF(), 0, 0, 0, filterStrategy); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); applicator.end(); } void KisImage::rotateImpl(const KUndo2MagicString &actionName, KisNodeSP rootNode, bool resizeImage, double radians) { QPointF offset; QSize newSize; { KisTransformWorker worker(0, 1.0, 1.0, 0, 0, 0, 0, radians, 0, 0, 0, 0); QTransform transform = worker.transform(); if (resizeImage) { QRect newRect = transform.mapRect(bounds()); newSize = newRect.size(); offset = -newRect.topLeft(); } else { QPointF origin = QRectF(rootNode->exactBounds()).center(); newSize = size(); offset = -(transform.map(origin) - origin); } } bool sizeChanged = resizeImage && (newSize.width() != width() || newSize.height() != height()); // These signals will be emitted after processing is done KisImageSignalVector emitSignals; if (sizeChanged) emitSignals << ComplexSizeChangedSignal(bounds(), newSize); emitSignals << ModifiedSignal; // These flags determine whether updates are transferred to the UI during processing KisProcessingApplicator::ProcessingFlags signalFlags = sizeChanged ? KisProcessingApplicator::NO_UI_UPDATES : KisProcessingApplicator::NONE; KisProcessingApplicator applicator(this, rootNode, KisProcessingApplicator::RECURSIVE | signalFlags, emitSignals, actionName); KisFilterStrategy *filter = KisFilterStrategyRegistry::instance()->value("Bicubic"); KisProcessingVisitorSP visitor = new KisTransformProcessingVisitor(1.0, 1.0, 0.0, 0.0, QPointF(), radians, offset.x(), offset.y(), filter); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); if (sizeChanged) { applicator.applyCommand(new KisImageResizeCommand(this, newSize)); } applicator.end(); } void KisImage::rotateImage(double radians) { rotateImpl(kundo2_i18n("Rotate Image"), root(), true, radians); } void KisImage::rotateNode(KisNodeSP node, double radians) { rotateImpl(kundo2_i18n("Rotate Layer"), node, false, radians); } void KisImage::shearImpl(const KUndo2MagicString &actionName, KisNodeSP rootNode, bool resizeImage, double angleX, double angleY, const QPointF &origin) { //angleX, angleY are in degrees const qreal pi = 3.1415926535897932385; const qreal deg2rad = pi / 180.0; qreal tanX = tan(angleX * deg2rad); qreal tanY = tan(angleY * deg2rad); QPointF offset; QSize newSize; { KisTransformWorker worker(0, 1.0, 1.0, tanX, tanY, origin.x(), origin.y(), 0, 0, 0, 0, 0); QRect newRect = worker.transform().mapRect(bounds()); newSize = newRect.size(); if (resizeImage) offset = -newRect.topLeft(); } if (newSize == size()) return; KisImageSignalVector emitSignals; if (resizeImage) emitSignals << ComplexSizeChangedSignal(bounds(), newSize); emitSignals << ModifiedSignal; KisProcessingApplicator::ProcessingFlags signalFlags = KisProcessingApplicator::RECURSIVE; if (resizeImage) signalFlags |= KisProcessingApplicator::NO_UI_UPDATES; KisProcessingApplicator applicator(this, rootNode, signalFlags, emitSignals, actionName); KisFilterStrategy *filter = KisFilterStrategyRegistry::instance()->value("Bilinear"); KisProcessingVisitorSP visitor = new KisTransformProcessingVisitor(1.0, 1.0, tanX, tanY, origin, 0, offset.x(), offset.y(), filter); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); if (resizeImage) { applicator.applyCommand(new KisImageResizeCommand(this, newSize)); } applicator.end(); } void KisImage::shearNode(KisNodeSP node, double angleX, double angleY) { QPointF shearOrigin = QRectF(bounds()).center(); shearImpl(kundo2_i18n("Shear layer"), node, false, angleX, angleY, shearOrigin); } void KisImage::shear(double angleX, double angleY) { shearImpl(kundo2_i18n("Shear Image"), m_d->rootLayer, true, angleX, angleY, QPointF()); } void KisImage::convertImageColorSpace(const KoColorSpace *dstColorSpace, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) { if (!dstColorSpace) return; const KoColorSpace *srcColorSpace = m_d->colorSpace; undoAdapter()->beginMacro(kundo2_i18n("Convert Image Color Space")); undoAdapter()->addCommand(new KisImageLockCommand(KisImageWSP(this), true)); undoAdapter()->addCommand(new KisImageSetProjectionColorSpaceCommand(KisImageWSP(this), dstColorSpace)); KisColorSpaceConvertVisitor visitor(this, srcColorSpace, dstColorSpace, renderingIntent, conversionFlags); m_d->rootLayer->accept(visitor); undoAdapter()->addCommand(new KisImageLockCommand(KisImageWSP(this), false)); undoAdapter()->endMacro(); setModified(); } bool KisImage::assignImageProfile(const KoColorProfile *profile) { if (!profile) return false; const KoColorSpace *dstCs = KoColorSpaceRegistry::instance()->colorSpace(colorSpace()->colorModelId().id(), colorSpace()->colorDepthId().id(), profile); const KoColorSpace *srcCs = colorSpace(); if (!dstCs) return false; m_d->colorSpace = dstCs; KisChangeProfileVisitor visitor(srcCs, dstCs); return m_d->rootLayer->accept(visitor); } void KisImage::convertProjectionColorSpace(const KoColorSpace *dstColorSpace) { if (*m_d->colorSpace == *dstColorSpace) return; undoAdapter()->beginMacro(kundo2_i18n("Convert Projection Color Space")); undoAdapter()->addCommand(new KisImageLockCommand(KisImageWSP(this), true)); undoAdapter()->addCommand(new KisImageSetProjectionColorSpaceCommand(KisImageWSP(this), dstColorSpace)); undoAdapter()->addCommand(new KisImageLockCommand(KisImageWSP(this), false)); undoAdapter()->endMacro(); setModified(); } void KisImage::setProjectionColorSpace(const KoColorSpace * colorSpace) { m_d->colorSpace = colorSpace; m_d->rootLayer->resetCache(); m_d->signalRouter->emitNotification(ColorSpaceChangedSignal); } const KoColorSpace * KisImage::colorSpace() const { return m_d->colorSpace; } const KoColorProfile * KisImage::profile() const { return colorSpace()->profile(); } double KisImage::xRes() const { return m_d->xres; } double KisImage::yRes() const { return m_d->yres; } void KisImage::setResolution(double xres, double yres) { m_d->xres = xres; m_d->yres = yres; m_d->signalRouter->emitNotification(ResolutionChangedSignal); } QPointF KisImage::documentToPixel(const QPointF &documentCoord) const { return QPointF(documentCoord.x() * xRes(), documentCoord.y() * yRes()); } QPoint KisImage::documentToIntPixel(const QPointF &documentCoord) const { QPointF pixelCoord = documentToPixel(documentCoord); return QPoint((int)pixelCoord.x(), (int)pixelCoord.y()); } QRectF KisImage::documentToPixel(const QRectF &documentRect) const { return QRectF(documentToPixel(documentRect.topLeft()), documentToPixel(documentRect.bottomRight())); } QRect KisImage::documentToIntPixel(const QRectF &documentRect) const { return documentToPixel(documentRect).toAlignedRect(); } QPointF KisImage::pixelToDocument(const QPointF &pixelCoord) const { return QPointF(pixelCoord.x() / xRes(), pixelCoord.y() / yRes()); } QPointF KisImage::pixelToDocument(const QPoint &pixelCoord) const { return QPointF((pixelCoord.x() + 0.5) / xRes(), (pixelCoord.y() + 0.5) / yRes()); } QRectF KisImage::pixelToDocument(const QRectF &pixelCoord) const { return QRectF(pixelToDocument(pixelCoord.topLeft()), pixelToDocument(pixelCoord.bottomRight())); } qint32 KisImage::width() const { return m_d->width; } qint32 KisImage::height() const { return m_d->height; } KisGroupLayerSP KisImage::rootLayer() const { Q_ASSERT(m_d->rootLayer); return m_d->rootLayer; } KisPaintDeviceSP KisImage::projection() const { if (m_d->isolatedRootNode) { return m_d->isolatedRootNode->projection(); } Q_ASSERT(m_d->rootLayer); KisPaintDeviceSP projection = m_d->rootLayer->projection(); Q_ASSERT(projection); return projection; } qint32 KisImage::nlayers() const { QStringList list; list << "KisLayer"; KisCountVisitor visitor(list, KoProperties()); m_d->rootLayer->accept(visitor); return visitor.count(); } qint32 KisImage::nHiddenLayers() const { QStringList list; list << "KisLayer"; KoProperties properties; properties.setProperty("visible", false); KisCountVisitor visitor(list, properties); m_d->rootLayer->accept(visitor); return visitor.count(); } QRect KisImage::realNodeExtent(KisNodeSP rootNode, QRect currentRect) { KisNodeSP node = rootNode->firstChild(); while(node) { currentRect |= realNodeExtent(node, currentRect); node = node->nextSibling(); } // TODO: it would be better to count up changeRect inside // node's extent() method currentRect |= rootNode->projectionPlane()->changeRect(rootNode->extent()); return currentRect; } void KisImage::refreshHiddenArea(KisNodeSP rootNode, const QRect &preparedArea) { QRect realNodeRect = realNodeExtent(rootNode); if (!preparedArea.contains(realNodeRect)) { QRegion dirtyRegion = realNodeRect; dirtyRegion -= preparedArea; foreach(const QRect &rc, dirtyRegion.rects()) { refreshGraph(rootNode, rc, realNodeRect); } } } void KisImage::flatten() { KisGroupLayerSP oldRootLayer = m_d->rootLayer; KisGroupLayerSP newRootLayer = new KisGroupLayer(this, "root", OPACITY_OPAQUE_U8); refreshHiddenArea(oldRootLayer, bounds()); lock(); KisPaintDeviceSP projectionCopy = new KisPaintDevice(*oldRootLayer->projection()); unlock(); KisPaintLayerSP flattenLayer = new KisPaintLayer(this, nextLayerName(), OPACITY_OPAQUE_U8, projectionCopy); Q_CHECK_PTR(flattenLayer); addNode(flattenLayer, newRootLayer, 0); undoAdapter()->beginMacro(kundo2_i18n("Flatten Image")); // NOTE: KisImageChangeLayersCommand performs all the locking for us undoAdapter()->addCommand(new KisImageChangeLayersCommand(KisImageWSP(this), oldRootLayer, newRootLayer)); undoAdapter()->endMacro(); setModified(); } KisLayerSP KisImage::mergeDown(KisLayerSP layer, const KisMetaData::MergeStrategy* strategy) { if (!layer->prevSibling()) return 0; // XXX: this breaks if we allow free mixing of masks and layers KisLayerSP prevLayer = dynamic_cast(layer->prevSibling().data()); if (!prevLayer) return 0; refreshHiddenArea(layer, bounds()); refreshHiddenArea(prevLayer, bounds()); bool prevAlphaDisabled = prevLayer->alphaChannelDisabled(); QRect layerProjectionExtent = this->projection()->extent(); QRect prevLayerProjectionExtent = prevLayer->projection()->extent(); // actual merging done by KisLayer::createMergedLayer (or specialized decendant) KisLayerSP mergedLayer = layer->createMergedLayer(prevLayer); Q_CHECK_PTR(mergedLayer); mergedLayer->setCompositeOp(COMPOSITE_OVER); mergedLayer->setChannelFlags(layer->channelFlags()); mergedLayer->disableAlphaChannel(prevAlphaDisabled); // Merge meta data QList srcs; srcs.append(prevLayer->metaData()); srcs.append(layer->metaData()); QList scores; int prevLayerArea = prevLayerProjectionExtent.width() * prevLayerProjectionExtent.height(); int layerArea = layerProjectionExtent.width() * layerProjectionExtent.height(); double norm = qMax(prevLayerArea, layerArea); scores.append(prevLayerArea / norm); scores.append(layerArea / norm); strategy->merge(mergedLayer->metaData(), srcs, scores); KisNodeSP parent = layer->parent(); // parent is set to null when the layer is removed from the node dbgImage << ppVar(parent); // FIXME: "Merge Down"? undoAdapter()->beginMacro(kundo2_i18n("Merge with Layer Below")); undoAdapter()->addCommand(new KisImageLayerAddCommand(this, mergedLayer, parent, layer)); safeRemoveTwoNodes(layer, prevLayer); undoAdapter()->endMacro(); return mergedLayer; } /** * The removal of two nodes in one go may be a bit tricky, because one * of them may be the clone of another. If we remove the source of a * clone layer, it will reincarnate into a paint layer. In this case * the pointer to the second layer will be lost. * * That's why we need to care about the order of the nodes removal: * the clone --- first, the source --- last. */ void KisImage::safeRemoveTwoNodes(KisNodeSP node1, KisNodeSP node2) { KisCloneLayer *clone1 = dynamic_cast(node1.data()); if (clone1 && KisNodeSP(clone1->copyFrom()) == node2) { undoAdapter()->addCommand(new KisImageLayerRemoveCommand(this, node1)); undoAdapter()->addCommand(new KisImageLayerRemoveCommand(this, node2)); } else { undoAdapter()->addCommand(new KisImageLayerRemoveCommand(this, node2)); undoAdapter()->addCommand(new KisImageLayerRemoveCommand(this, node1)); } } KisLayerSP KisImage::flattenLayer(KisLayerSP layer) { if (!layer->firstChild()) return layer; refreshHiddenArea(layer, bounds()); lock(); KisPaintDeviceSP mergedDevice = new KisPaintDevice(*layer->projection()); unlock(); KisPaintLayerSP newLayer = new KisPaintLayer(this, layer->name(), layer->opacity(), mergedDevice); newLayer->setCompositeOp(layer->compositeOp()->id()); undoAdapter()->beginMacro(kundo2_i18n("Flatten Layer")); undoAdapter()->addCommand(new KisImageLayerAddCommand(this, newLayer, layer->parent(), layer)); undoAdapter()->addCommand(new KisImageLayerRemoveCommand(this, layer)); QList srcs; srcs.append(layer->metaData()); const KisMetaData::MergeStrategy* strategy = KisMetaData::MergeStrategyRegistry::instance()->get("Smart"); QList scores; scores.append(1.0); //Just give some score, there only is one layer strategy->merge(newLayer->metaData(), srcs, scores); undoAdapter()->endMacro(); return newLayer; } void KisImage::setModified() { m_d->signalRouter->emitNotification(ModifiedSignal); } QImage KisImage::convertToQImage(QRect imageRect, const KoColorProfile * profile) { qint32 x; qint32 y; qint32 w; qint32 h; imageRect.getRect(&x, &y, &w, &h); return convertToQImage(x, y, w, h, profile); } QImage KisImage::convertToQImage(qint32 x, qint32 y, qint32 w, qint32 h, const KoColorProfile * profile) { KisPaintDeviceSP dev = projection(); if (!dev) return QImage(); QImage image = dev->convertToQImage(const_cast(profile), x, y, w, h, KoColorConversionTransformation::InternalRenderingIntent, KoColorConversionTransformation::InternalConversionFlags); return image; } QImage KisImage::convertToQImage(const QRect& scaledRect, const QSize& scaledImageSize, const KoColorProfile *profile) { if (scaledRect.isEmpty() || scaledImageSize.isEmpty()) { return QImage(); } try { qint32 imageWidth = width(); qint32 imageHeight = height(); quint32 pixelSize = colorSpace()->pixelSize(); double xScale = static_cast(imageWidth) / scaledImageSize.width(); double yScale = static_cast(imageHeight) / scaledImageSize.height(); QRect srcRect; srcRect.setLeft(static_cast(scaledRect.left() * xScale)); srcRect.setRight(static_cast(ceil((scaledRect.right() + 1) * xScale)) - 1); srcRect.setTop(static_cast(scaledRect.top() * yScale)); srcRect.setBottom(static_cast(ceil((scaledRect.bottom() + 1) * yScale)) - 1); KisPaintDeviceSP mergedImage = projection(); quint8 *scaledImageData = new quint8[scaledRect.width() * scaledRect.height() * pixelSize]; quint8 *imageRow = new quint8[srcRect.width() * pixelSize]; const qint32 imageRowX = srcRect.x(); for (qint32 y = 0; y < scaledRect.height(); ++y) { qint32 dstY = scaledRect.y() + y; qint32 dstX = scaledRect.x(); qint32 srcY = (dstY * imageHeight) / scaledImageSize.height(); mergedImage->readBytes(imageRow, imageRowX, srcY, srcRect.width(), 1); quint8 *dstPixel = scaledImageData + (y * scaledRect.width() * pixelSize); quint32 columnsRemaining = scaledRect.width(); while (columnsRemaining > 0) { qint32 srcX = (dstX * imageWidth) / scaledImageSize.width(); memcpy(dstPixel, imageRow + ((srcX - imageRowX) * pixelSize), pixelSize); ++dstX; dstPixel += pixelSize; --columnsRemaining; } } delete [] imageRow; QImage image = colorSpace()->convertToQImage(scaledImageData, scaledRect.width(), scaledRect.height(), const_cast(profile), KoColorConversionTransformation::InternalRenderingIntent, KoColorConversionTransformation::InternalConversionFlags); delete [] scaledImageData; return image; } catch (std::bad_alloc) { warnKrita << "KisImage::convertToQImage ran out of memory"; return QImage(); } } void KisImage::notifyLayersChanged() { m_d->signalRouter->emitNotification(LayersChangedSignal); } QRect KisImage::bounds() const { return QRect(0, 0, width(), height()); } KisPostExecutionUndoAdapter* KisImage::postExecutionUndoAdapter() const { return m_d->postExecutionUndoAdapter; } void KisImage::setUndoStore(KisUndoStore *undoStore) { m_d->legacyUndoAdapter->setUndoStore(undoStore); m_d->postExecutionUndoAdapter->setUndoStore(undoStore); delete m_d->undoStore; m_d->undoStore = undoStore; } KisUndoStore* KisImage::undoStore() { return m_d->undoStore; } KisUndoAdapter* KisImage::undoAdapter() const { return m_d->legacyUndoAdapter; } KisActionRecorder* KisImage::actionRecorder() const { return m_d->recorder; } void KisImage::setDefaultProjectionColor(const KoColor &color) { KIS_ASSERT_RECOVER_RETURN(m_d->rootLayer); m_d->rootLayer->setDefaultProjectionColor(color); } KoColor KisImage::defaultProjectionColor() const { KIS_ASSERT_RECOVER(m_d->rootLayer) { return KoColor(Qt::transparent, m_d->colorSpace); } return m_d->rootLayer->defaultProjectionColor(); } void KisImage::setRootLayer(KisGroupLayerSP rootLayer) { stopIsolatedMode(); KoColor defaultProjectionColor(Qt::transparent, m_d->colorSpace); if (m_d->rootLayer) { m_d->rootLayer->setGraphListener(0); m_d->rootLayer->disconnect(); KisPaintDeviceSP original = m_d->rootLayer->original(); defaultProjectionColor.setColor(original->defaultPixel(), original->colorSpace()); } m_d->rootLayer = rootLayer; m_d->rootLayer->disconnect(); m_d->rootLayer->setGraphListener(this); KisPaintDeviceSP newOriginal = m_d->rootLayer->original(); defaultProjectionColor.convertTo(newOriginal->colorSpace()); newOriginal->setDefaultPixel(defaultProjectionColor.data()); setRoot(m_d->rootLayer.data()); } void KisImage::addAnnotation(KisAnnotationSP annotation) { // Find the icc annotation, if there is one vKisAnnotationSP_it it = m_d->annotations.begin(); while (it != m_d->annotations.end()) { if ((*it)->type() == annotation->type()) { *it = annotation; return; } ++it; } m_d->annotations.push_back(annotation); } KisAnnotationSP KisImage::annotation(const QString& type) { vKisAnnotationSP_it it = m_d->annotations.begin(); while (it != m_d->annotations.end()) { if ((*it)->type() == type) { return *it; } ++it; } return KisAnnotationSP(0); } void KisImage::removeAnnotation(const QString& type) { vKisAnnotationSP_it it = m_d->annotations.begin(); while (it != m_d->annotations.end()) { if ((*it)->type() == type) { m_d->annotations.erase(it); return; } ++it; } } vKisAnnotationSP_it KisImage::beginAnnotations() { return m_d->annotations.begin(); } vKisAnnotationSP_it KisImage::endAnnotations() { return m_d->annotations.end(); } void KisImage::notifyAboutToBeDeleted() { emit sigAboutToBeDeleted(); } KisPerspectiveGrid* KisImage::perspectiveGrid() { if (m_d->perspectiveGrid == 0) m_d->perspectiveGrid = new KisPerspectiveGrid(); return m_d->perspectiveGrid; } KisImageSignalRouter* KisImage::signalRouter() { return m_d->signalRouter; } void KisImage::waitForDone() { requestStrokeEnd(); if (m_d->scheduler) { m_d->scheduler->waitForDone(); } } KisStrokeId KisImage::startStroke(KisStrokeStrategy *strokeStrategy) { /** * Ask open strokes to end gracefully. All the strokes clients * (including the one calling this method right now) will get * a notification that they should probably end their strokes. * However this is purely their choice whether to end a stroke * or not. */ requestStrokeEnd(); /** * Some of the strokes can cancel their work with undoing all the * changes they did to the paint devices. The problem is that undo * stack will know nothing about it. Therefore, just notify it * explicitly */ if (strokeStrategy->clearsRedoOnStart()) { m_d->undoStore->purgeRedoState(); } KisStrokeId id; if (m_d->scheduler) { id = m_d->scheduler->startStroke(strokeStrategy); } return id; } void KisImage::startIsolatedMode(KisNodeSP node) { barrierLock(); unlock(); m_d->isolatedRootNode = node; emit sigIsolatedModeChanged(); notifyProjectionUpdated(bounds()); } void KisImage::stopIsolatedMode() { if (!m_d->isolatedRootNode) return; KisNodeSP oldRootNode = m_d->isolatedRootNode; m_d->isolatedRootNode = 0; emit sigIsolatedModeChanged(); notifyProjectionUpdated(bounds()); // TODO: Substitute notifyProjectionUpdated() with this code // when update optimization is implemented // // QRect updateRect = bounds() | oldRootNode->extent(); // oldRootNode->setDirty(updateRect); } KisNodeSP KisImage::isolatedModeRoot() const { return m_d->isolatedRootNode; } void KisImage::addJob(KisStrokeId id, KisStrokeJobData *data) { KisUpdateTimeMonitor::instance()->reportJobStarted(data); if (m_d->scheduler) { m_d->scheduler->addJob(id, data); } } void KisImage::endStroke(KisStrokeId id) { if (m_d->scheduler) { m_d->scheduler->endStroke(id); } } bool KisImage::cancelStroke(KisStrokeId id) { bool result = false; if (m_d->scheduler) { result = m_d->scheduler->cancelStroke(id); } return result; } bool KisImage::KisImagePrivate::tryCancelCurrentStrokeAsync() { bool result = false; if (scheduler) { result = scheduler->tryCancelCurrentStrokeAsync(); } return result; } void KisImage::requestUndoDuringStroke() { emit sigUndoDuringStrokeRequested(); } void KisImage::requestStrokeCancellation() { if (!m_d->tryCancelCurrentStrokeAsync()) { emit sigStrokeCancellationRequested(); } } void KisImage::requestStrokeEnd() { emit sigStrokeEndRequested(); } void KisImage::refreshGraph(KisNodeSP root) { refreshGraph(root, bounds(), bounds()); } void KisImage::refreshGraph(KisNodeSP root, const QRect &rc, const QRect &cropRect) { if (!root) root = m_d->rootLayer; if (m_d->scheduler) { m_d->scheduler->fullRefresh(root, rc, cropRect); } } void KisImage::initialRefreshGraph() { /** * NOTE: Tricky part. We set crop rect to null, so the clones * will not rely on precalculated projections of their sources */ refreshGraphAsync(0, bounds(), QRect()); waitForDone(); } void KisImage::refreshGraphAsync(KisNodeSP root) { refreshGraphAsync(root, bounds(), bounds()); } void KisImage::refreshGraphAsync(KisNodeSP root, const QRect &rc) { refreshGraphAsync(root, rc, bounds()); } void KisImage::refreshGraphAsync(KisNodeSP root, const QRect &rc, const QRect &cropRect) { if (!root) root = m_d->rootLayer; if (m_d->scheduler) { m_d->scheduler->fullRefreshAsync(root, rc, cropRect); } } void KisImage::requestProjectionUpdateNoFilthy(KisNodeSP pseudoFilthy, const QRect &rc, const QRect &cropRect) { KIS_ASSERT_RECOVER_RETURN(pseudoFilthy); if (m_d->scheduler) { m_d->scheduler->updateProjectionNoFilthy(pseudoFilthy, rc, cropRect); } } void KisImage::addSpontaneousJob(KisSpontaneousJob *spontaneousJob) { if (m_d->scheduler) { m_d->scheduler->addSpontaneousJob(spontaneousJob); } } void KisImage::disableDirtyRequests() { m_d->disableDirtyRequests.ref(); } void KisImage::enableDirtyRequests() { m_d->disableDirtyRequests.deref(); } void KisImage::disableUIUpdates() { m_d->disableUIUpdateSignals.ref(); } void KisImage::enableUIUpdates() { m_d->disableUIUpdateSignals.deref(); } void KisImage::notifyProjectionUpdated(const QRect &rc) { KisUpdateTimeMonitor::instance()->reportUpdateFinished(rc); if (!m_d->disableUIUpdateSignals) { emit sigImageUpdated(rc); } } void KisImage::notifySelectionChanged() { /** * The selection is calculated asynchromously, so it is not * handled by disableUIUpdates() and other special signals of * KisImageSignalRouter */ m_d->legacyUndoAdapter->emitSelectionChanged(); /** * Editing of selection masks doesn't necessary produce a * setDirty() call, so in the end of the stroke we need to request * direct update of the UI's cache. */ if (m_d->isolatedRootNode && dynamic_cast(m_d->isolatedRootNode.data())) { notifyProjectionUpdated(bounds()); } } void KisImage::requestProjectionUpdateImpl(KisNode *node, const QRect &rect, const QRect &cropRect) { KisNodeGraphListener::requestProjectionUpdate(node, rect); if (m_d->scheduler) { m_d->scheduler->updateProjection(node, rect, cropRect); } } void KisImage::requestProjectionUpdate(KisNode *node, const QRect& rect) { if (m_d->disableDirtyRequests) return; /** * Here we use 'permitted' instead of 'active' intentively, * because the updates may come after the actual stroke has been * finished. And having some more updates for the stroke not * supporting the wrap-around mode will not make much harm. */ if (m_d->wrapAroundModePermitted) { QRect boundRect = bounds(); KisWrappedRect splitRect(rect, boundRect); foreach (const QRect &rc, splitRect) { requestProjectionUpdateImpl(node, rc, boundRect); } } else { requestProjectionUpdateImpl(node, rect, bounds()); } } QList KisImage::compositions() { return m_d->compositions; } void KisImage::addComposition(KisLayerComposition* composition) { m_d->compositions.append(composition); } void KisImage::removeComposition(KisLayerComposition* composition) { m_d->compositions.removeAll(composition); delete composition; } bool checkMasksNeedConversion(KisNodeSP root, const QRect &bounds) { KisSelectionMask *mask = dynamic_cast(root.data()); if (mask && (!bounds.contains(mask->paintDevice()->exactBounds()) || mask->selection()->hasShapeSelection())) { return true; } KisNodeSP node = root->firstChild(); while (node) { if (checkMasksNeedConversion(node, bounds)) { return true; } node = node->nextSibling(); } return false; } void KisImage::setWrapAroundModePermitted(bool value) { m_d->wrapAroundModePermitted = value; if (m_d->wrapAroundModePermitted && checkMasksNeedConversion(root(), bounds())) { KisProcessingApplicator applicator(this, root(), KisProcessingApplicator::RECURSIVE, KisImageSignalVector() << ModifiedSignal, kundo2_i18n("Crop Selections")); KisProcessingVisitorSP visitor = new KisCropSelectionsProcessingVisitor(bounds()); applicator.applyVisitor(visitor, KisStrokeJobData::CONCURRENT); applicator.end(); } } bool KisImage::wrapAroundModePermitted() const { return m_d->wrapAroundModePermitted; } bool KisImage::wrapAroundModeActive() const { return m_d->wrapAroundModePermitted && m_d->scheduler && m_d->scheduler->wrapAroundModeSupported(); } void KisImage::notifyNodeCollpasedChanged() { emit sigNodeCollapsedChanged(); } #include "kis_image.moc" diff --git a/krita/image/kis_processing_applicator.cpp b/krita/image/kis_processing_applicator.cpp index 3f8cf00917..8a42a40b17 100644 --- a/krita/image/kis_processing_applicator.cpp +++ b/krita/image/kis_processing_applicator.cpp @@ -1,296 +1,301 @@ /* * Copyright (c) 2011 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_processing_applicator.h" #include "kis_image.h" #include "kis_image_signal_router.h" #include "kis_node.h" #include "kis_clone_layer.h" #include "kis_processing_visitor.h" #include "commands_new/kis_processing_command.h" #include "kis_stroke_strategy_undo_command_based.h" class DisableUIUpdatesCommand : public KUndo2Command { public: DisableUIUpdatesCommand(KisImageWSP image, bool finalUpdate) : m_image(image), m_finalUpdate(finalUpdate) { } void redo() { if(m_finalUpdate) m_image->enableUIUpdates(); else m_image->disableUIUpdates(); } void undo() { if(!m_finalUpdate) m_image->enableUIUpdates(); else m_image->disableUIUpdates(); } private: KisImageWSP m_image; bool m_finalUpdate; }; class UpdateCommand : public KUndo2Command { public: UpdateCommand(KisImageWSP image, KisNodeSP node, KisProcessingApplicator::ProcessingFlags flags, bool finalUpdate) : m_image(image), m_node(node), m_flags(flags), m_finalUpdate(finalUpdate) { } void redo() { if(!m_finalUpdate) initialize(); else finalize(); } void undo() { if(m_finalUpdate) initialize(); else finalize(); } private: void initialize() { /** * We disable all non-centralized updates here. Everything * should be done by this command's explicit updates. * * If you still need third-party updates work, please add a * flag to the applicator. */ m_image->disableDirtyRequests(); } void finalize() { m_image->enableDirtyRequests(); if(m_flags.testFlag(KisProcessingApplicator::RECURSIVE)) { m_image->refreshGraphAsync(m_node); } m_node->setDirty(m_image->bounds()); updateClones(m_node); } void updateClones(KisNodeSP node) { // simple tail-recursive iteration KisNodeSP prevNode = node->lastChild(); while(prevNode) { updateClones(prevNode); prevNode = prevNode->prevSibling(); } KisLayer *layer = dynamic_cast(m_node.data()); if(layer && layer->hasClones()) { foreach(KisCloneLayerSP clone, layer->registeredClones()) { if(!clone) continue; QPoint offset(clone->x(), clone->y()); QRegion dirtyRegion(m_image->bounds()); dirtyRegion -= m_image->bounds().translated(offset); clone->setDirty(dirtyRegion); } } } private: KisImageWSP m_image; KisNodeSP m_node; KisProcessingApplicator::ProcessingFlags m_flags; bool m_finalUpdate; }; class EmitImageSignalsCommand : public KUndo2Command { public: EmitImageSignalsCommand(KisImageWSP image, KisImageSignalVector emitSignals, bool finalUpdate) : m_image(image), m_emitSignals(emitSignals), m_finalUpdate(finalUpdate) { } void redo() { if(m_finalUpdate) doUpdate(m_emitSignals); } void undo() { if(!m_finalUpdate) { KisImageSignalVector reverseSignals; KisImageSignalVector::iterator i = m_emitSignals.end(); while (i != m_emitSignals.begin()) { --i; reverseSignals.append(i->inverted()); } doUpdate(reverseSignals); } } private: void doUpdate(KisImageSignalVector emitSignals) { foreach(KisImageSignalType type, emitSignals) { m_image->signalRouter()->emitNotification(type); } } private: KisImageWSP m_image; KisImageSignalVector m_emitSignals; bool m_finalUpdate; }; KisProcessingApplicator::KisProcessingApplicator(KisImageWSP image, KisNodeSP node, ProcessingFlags flags, KisImageSignalVector emitSignals, - const KUndo2MagicString &name) + const KUndo2MagicString &name, + KUndo2CommandExtraData *extraData) : m_image(image), m_node(node), m_flags(flags), m_emitSignals(emitSignals), m_finalSignalsEmitted(false) { KisStrokeStrategyUndoCommandBased *strategy = new KisStrokeStrategyUndoCommandBased(name, false, m_image->postExecutionUndoAdapter()); if (m_flags.testFlag(SUPPORTS_WRAPAROUND_MODE)) { strategy->setSupportsWrapAroundMode(true); } + if (extraData) { + strategy->setCommandExtraData(extraData); + } + m_strokeId = m_image->startStroke(strategy); if(!m_emitSignals.isEmpty()) { applyCommand(new EmitImageSignalsCommand(m_image, m_emitSignals, false), KisStrokeJobData::BARRIER); } if(m_flags.testFlag(NO_UI_UPDATES)) { applyCommand(new DisableUIUpdatesCommand(m_image, false), KisStrokeJobData::BARRIER); } if (m_node) { applyCommand(new UpdateCommand(m_image, m_node, m_flags, false)); } } KisProcessingApplicator::~KisProcessingApplicator() { } void KisProcessingApplicator::applyVisitor(KisProcessingVisitorSP visitor, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity) { if(!m_flags.testFlag(RECURSIVE)) { applyCommand(new KisProcessingCommand(visitor, m_node), sequentiality, exclusivity); } else { visitRecursively(m_node, visitor, sequentiality, exclusivity); } } void KisProcessingApplicator::visitRecursively(KisNodeSP node, KisProcessingVisitorSP visitor, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity) { // simple tail-recursive iteration KisNodeSP prevNode = node->lastChild(); while(prevNode) { visitRecursively(prevNode, visitor, sequentiality, exclusivity); prevNode = prevNode->prevSibling(); } applyCommand(new KisProcessingCommand(visitor, node), sequentiality, exclusivity); } void KisProcessingApplicator::applyCommand(KUndo2Command *command, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity) { /* * One should not add commands after the final signals have been * emitted, only end or cancel the stroke */ KIS_ASSERT_RECOVER_RETURN(!m_finalSignalsEmitted); m_image->addJob(m_strokeId, new KisStrokeStrategyUndoCommandBased::Data(KUndo2CommandSP(command), false, sequentiality, exclusivity)); } void KisProcessingApplicator::explicitlyEmitFinalSignals() { KIS_ASSERT_RECOVER_RETURN(!m_finalSignalsEmitted); if (m_node) { applyCommand(new UpdateCommand(m_image, m_node, m_flags, true)); } if(m_flags.testFlag(NO_UI_UPDATES)) { applyCommand(new DisableUIUpdatesCommand(m_image, true), KisStrokeJobData::BARRIER); } if(!m_emitSignals.isEmpty()) { applyCommand(new EmitImageSignalsCommand(m_image, m_emitSignals, true), KisStrokeJobData::BARRIER); } // simple consistency check m_finalSignalsEmitted = true; } void KisProcessingApplicator::end() { if (!m_finalSignalsEmitted) { explicitlyEmitFinalSignals(); } m_image->endStroke(m_strokeId); } void KisProcessingApplicator::cancel() { m_image->cancelStroke(m_strokeId); } diff --git a/krita/image/kis_processing_applicator.h b/krita/image/kis_processing_applicator.h index 931921020b..be3c27d67a 100644 --- a/krita/image/kis_processing_applicator.h +++ b/krita/image/kis_processing_applicator.h @@ -1,92 +1,94 @@ /* * Copyright (c) 2011 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KIS_PROCESSING_APPLICATOR_H #define __KIS_PROCESSING_APPLICATOR_H #include "krita_export.h" #include "kis_types.h" #include "kis_stroke_job_strategy.h" #include "kis_image_signal_router.h" #include "kundo2magicstring.h" +#include "kundo2commandextradata.h" class KRITAIMAGE_EXPORT KisProcessingApplicator { public: enum ProcessingFlag { NONE = 0x0, RECURSIVE = 0x1, NO_UI_UPDATES = 0x2, SUPPORTS_WRAPAROUND_MODE = 0x4 }; Q_DECLARE_FLAGS(ProcessingFlags, ProcessingFlag) public: KisProcessingApplicator(KisImageWSP image, KisNodeSP node, ProcessingFlags flags = NONE, KisImageSignalVector emitSignals = KisImageSignalVector(), - const KUndo2MagicString &name = KUndo2MagicString()); + const KUndo2MagicString &name = KUndo2MagicString(), + KUndo2CommandExtraData *extraData = 0); ~KisProcessingApplicator(); void applyVisitor(KisProcessingVisitorSP visitor, KisStrokeJobData::Sequentiality sequentiality = KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::Exclusivity exclusivity = KisStrokeJobData::NORMAL); void applyCommand(KUndo2Command *command, KisStrokeJobData::Sequentiality sequentiality = KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::Exclusivity exclusivity = KisStrokeJobData::NORMAL); /** * This method emits all the final update signals of the stroke * without actually ending the stroke. This can be used for * long-running strokes which are kept open to implement preview * of the actions. * * WARNING: you cannot add new commands/processings after the * final signals has been emitted. You should either call end() or * cancel(). */ void explicitlyEmitFinalSignals(); void end(); void cancel(); private: void visitRecursively(KisNodeSP node, KisProcessingVisitorSP visitor, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity); private: KisImageWSP m_image; KisNodeSP m_node; ProcessingFlags m_flags; KisImageSignalVector m_emitSignals; KisStrokeId m_strokeId; bool m_finalSignalsEmitted; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KisProcessingApplicator::ProcessingFlags) #endif /* __KIS_PROCESSING_APPLICATOR_H */ diff --git a/krita/image/kis_stroke_strategy_undo_command_based.cpp b/krita/image/kis_stroke_strategy_undo_command_based.cpp index d6a982e06e..e8335654eb 100644 --- a/krita/image/kis_stroke_strategy_undo_command_based.cpp +++ b/krita/image/kis_stroke_strategy_undo_command_based.cpp @@ -1,131 +1,144 @@ /* * Copyright (c) 2011 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_stroke_strategy_undo_command_based.h" #include #include "kis_post_execution_undo_adapter.h" #include "commands_new/kis_saved_commands.h" KisStrokeStrategyUndoCommandBased:: KisStrokeStrategyUndoCommandBased(const KUndo2MagicString &name, bool undo, KisPostExecutionUndoAdapter *undoAdapter, KUndo2CommandSP initCommand, KUndo2CommandSP finishCommand) : KisSimpleStrokeStrategy("STROKE_UNDO_COMMAND_BASED", name), m_undo(undo), m_initCommand(initCommand), m_finishCommand(finishCommand), m_undoAdapter(undoAdapter), m_macroCommand(0) { enableJob(KisSimpleStrokeStrategy::JOB_INIT); enableJob(KisSimpleStrokeStrategy::JOB_FINISH); enableJob(KisSimpleStrokeStrategy::JOB_CANCEL); enableJob(KisSimpleStrokeStrategy::JOB_DOSTROKE); } void KisStrokeStrategyUndoCommandBased::setUsedWhileUndoRedo(bool value) { setClearsRedoOnStart(!value); } void KisStrokeStrategyUndoCommandBased::executeCommand(KUndo2CommandSP command, bool undo) { if(!command) return; if(undo) { command->undo(); } else { command->redo(); } } void KisStrokeStrategyUndoCommandBased::initStrokeCallback() { if(m_undoAdapter) { m_macroCommand = m_undoAdapter->createMacro(name()); } executeCommand(m_initCommand, m_undo); notifyCommandDone(m_initCommand, KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::NORMAL); } void KisStrokeStrategyUndoCommandBased::finishStrokeCallback() { executeCommand(m_finishCommand, m_undo); notifyCommandDone(m_finishCommand, KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::NORMAL); QMutexLocker locker(&m_mutex); if(m_macroCommand) { Q_ASSERT(m_undoAdapter); postProcessToplevelCommand(m_macroCommand); m_undoAdapter->addMacro(m_macroCommand); m_macroCommand = 0; } } void KisStrokeStrategyUndoCommandBased::cancelStrokeCallback() { QMutexLocker locker(&m_mutex); if(m_macroCommand) { m_macroCommand->performCancel(cancelStrokeId(), m_undo); delete m_macroCommand; m_macroCommand = 0; } } void KisStrokeStrategyUndoCommandBased::doStrokeCallback(KisStrokeJobData *data) { Data *d = dynamic_cast(data); executeCommand(d->command, d->undo); notifyCommandDone(d->command, d->sequentiality(), d->exclusivity()); } void KisStrokeStrategyUndoCommandBased::runAndSaveCommand(KUndo2CommandSP command, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity) { if (!command) return; command->redo(); notifyCommandDone(command, sequentiality, exclusivity); } void KisStrokeStrategyUndoCommandBased::notifyCommandDone(KUndo2CommandSP command, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity) { if(!command) return; QMutexLocker locker(&m_mutex); if(m_macroCommand) { m_macroCommand->addCommand(command, sequentiality, exclusivity); } } +void KisStrokeStrategyUndoCommandBased::setCommandExtraData(KUndo2CommandExtraData *data) +{ + if (m_undoAdapter && m_macroCommand) { + qWarning() << "WARNING: KisStrokeStrategyUndoCommandBased::setCommandExtraData():" + << "the extra data is set while the stroke has already been started!" + << "The result is undefined, continued actions may not work!"; + } + + m_commandExtraData.reset(data); +} + void KisStrokeStrategyUndoCommandBased::postProcessToplevelCommand(KUndo2Command *command) { - Q_UNUSED(command); + if (m_commandExtraData) { + command->setExtraData(m_commandExtraData.take()); + } } diff --git a/krita/image/kis_stroke_strategy_undo_command_based.h b/krita/image/kis_stroke_strategy_undo_command_based.h index 37f23871af..ed7c828880 100644 --- a/krita/image/kis_stroke_strategy_undo_command_based.h +++ b/krita/image/kis_stroke_strategy_undo_command_based.h @@ -1,114 +1,129 @@ /* * Copyright (c) 2011 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KIS_STROKE_STRATEGY_UNDO_COMMAND_BASED_H #define __KIS_STROKE_STRATEGY_UNDO_COMMAND_BASED_H #include #include #include #include "kis_types.h" #include "kis_simple_stroke_strategy.h" #include "commands_new/kis_saved_commands.h" - class KisStrokeJob; class KisPostExecutionUndoAdapter; class KRITAIMAGE_EXPORT KisStrokeStrategyUndoCommandBased : public KisSimpleStrokeStrategy { public: class Data : public KisStrokeJobData { public: Data(KUndo2CommandSP _command, bool _undo = false, Sequentiality _sequentiality = SEQUENTIAL, Exclusivity _exclusivity = NORMAL) : KisStrokeJobData(_sequentiality, _exclusivity), command(_command), undo(_undo) { } Data(KUndo2Command *_command, bool _undo = false, Sequentiality _sequentiality = SEQUENTIAL, Exclusivity _exclusivity = NORMAL) : KisStrokeJobData(_sequentiality, _exclusivity), command(_command), undo(_undo) { } KUndo2CommandSP command; bool undo; }; public: KisStrokeStrategyUndoCommandBased(const KUndo2MagicString &name, bool undo, KisPostExecutionUndoAdapter *undoAdapter, KUndo2CommandSP initCommand = KUndo2CommandSP(0), KUndo2CommandSP finishCommand = KUndo2CommandSP(0)); using KisSimpleStrokeStrategy::setExclusive; void initStrokeCallback(); void finishStrokeCallback(); void cancelStrokeCallback(); void doStrokeCallback(KisStrokeJobData *data); + /** + * Set extra data that will be assigned to the command + * represecting this action. Using extra data has the following + * restrictions: + * + * 1) The \p data must be set *before* the stroke has been started. + * Setting the \p data after the stroke has been started with + * image->startStroke(strokeId) leads to an undefined behaviour. + * + * 2) \p data becomes owned by the strategy/command right after + * setting it. Don't try to change it afterwards. + */ + void setCommandExtraData(KUndo2CommandExtraData *data); + /** * The undo-command-based is a low-level strategy, so it allows * changing its wraparound mode status. * * WARNING: the switch must be called *before* the stroke has been * started! Otherwise the mode will not be activated. */ using KisStrokeStrategy::setSupportsWrapAroundMode; void setUsedWhileUndoRedo(bool value); protected: void runAndSaveCommand(KUndo2CommandSP command, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity); void notifyCommandDone(KUndo2CommandSP command, KisStrokeJobData::Sequentiality sequentiality, KisStrokeJobData::Exclusivity exclusivity); virtual void postProcessToplevelCommand(KUndo2Command *command); private: void executeCommand(KUndo2CommandSP command, bool undo); private: bool m_undo; KUndo2CommandSP m_initCommand; KUndo2CommandSP m_finishCommand; KisPostExecutionUndoAdapter *m_undoAdapter; + QScopedPointer m_commandExtraData; + // protects done commands only QMutex m_mutex; KisSavedMacroCommand *m_macroCommand; }; #endif /* __KIS_STROKE_STRATEGY_UNDO_COMMAND_BASED_H */ diff --git a/krita/plugins/tools/tool_crop/kis_tool_crop.cc b/krita/plugins/tools/tool_crop/kis_tool_crop.cc index 2744dc50ce..3306435dfd 100644 --- a/krita/plugins/tools/tool_crop/kis_tool_crop.cc +++ b/krita/plugins/tools/tool_crop/kis_tool_crop.cc @@ -1,823 +1,863 @@ /* * kis_tool_crop.cc -- part of Krita * * Copyright (c) 2004 Boudewijn Rempt * Copyright (c) 2005 Michael Thaler * Copyright (c) 2006 Cyrille Berger * Copyright (C) 2007 Adrian Page * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_tool_crop.h" #include "kistoolcropconfigwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include +#include + struct DecorationLine { QPointF start; QPointF end; enum Relation { Width, Height, Smallest, Largest }; Relation startXRelation; Relation startYRelation; Relation endXRelation; Relation endYRelation; }; DecorationLine decors[20] = { //thirds {QPointF(0.0, 0.3333),QPointF(1.0, 0.3333), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.0, 0.6666),QPointF(1.0, 0.6666), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.3333, 0.0),QPointF(0.3333, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.6666, 0.0),QPointF(0.6666, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, //fifths {QPointF(0.0, 0.2),QPointF(1.0, 0.2), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.0, 0.4),QPointF(1.0, 0.4), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.0, 0.6),QPointF(1.0, 0.6), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.0, 0.8),QPointF(1.0, 0.8), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.2, 0.0),QPointF(0.2, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.4, 0.0),QPointF(0.4, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.6, 0.0),QPointF(0.6, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.8, 0.0),QPointF(0.8, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, // Passport photo {QPointF(0.0, 0.45/0.35),QPointF(1.0, 0.45/0.35), DecorationLine::Width, DecorationLine::Width, DecorationLine::Width, DecorationLine::Width}, {QPointF(0.2, 0.05/0.35),QPointF(0.8, 0.05/0.35), DecorationLine::Width, DecorationLine::Width, DecorationLine::Width, DecorationLine::Width}, {QPointF(0.2, 0.40/0.35),QPointF(0.8, 0.40/0.35), DecorationLine::Width, DecorationLine::Width, DecorationLine::Width, DecorationLine::Width}, {QPointF(0.25, 0.07/0.35),QPointF(0.75, 0.07/0.35), DecorationLine::Width, DecorationLine::Width, DecorationLine::Width, DecorationLine::Width}, {QPointF(0.25, 0.38/0.35),QPointF(0.75, 0.38/0.35), DecorationLine::Width, DecorationLine::Width, DecorationLine::Width, DecorationLine::Width}, {QPointF(0.35/0.45, 0.0),QPointF(0.35/0.45, 1.0), DecorationLine::Height, DecorationLine::Height, DecorationLine::Height, DecorationLine::Height}, //Crosshair {QPointF(0.0, 0.5),QPointF(1.0, 0.5), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height}, {QPointF(0.5, 0.0),QPointF(0.5, 1.0), DecorationLine::Width, DecorationLine::Height, DecorationLine::Width, DecorationLine::Height} }; #define DECORATION_COUNT 5 const int decorsIndex[DECORATION_COUNT] = {0,4,12,18,20}; KisToolCrop::KisToolCrop(KoCanvasBase * canvas) : KisTool(canvas, KisCursor::load("tool_crop_cursor.png", 6, 6)) { setObjectName("tool_crop"); m_handleSize = 13; m_haveCropSelection = false; m_cropTypeSelectable = false; m_cropType = ImageCropType; m_decoration = 1; connect(&m_finalRect, SIGNAL(sigValuesChanged()), SLOT(slotRectChanged())); connect(&m_finalRect, SIGNAL(sigLockValuesChanged()), SLOT(slotRectChanged())); } KisToolCrop::~KisToolCrop() { } void KisToolCrop::activate(ToolActivation toolActivation, const QSet &shapes) { KisTool::activate(toolActivation, shapes); configGroup = KGlobal::config()->group(toolId()); // save settings to kritarc KisResourcesSnapshotSP resources = new KisResourcesSnapshot(image(), currentNode(), 0, this->canvas()->resourceManager()); // load settings from configuration setGrowCenter(configGroup.readEntry("growCenter", false)); setAllowGrow(configGroup.readEntry("allowGrow", false)); // Default: thirds decoration setDecoration(configGroup.readEntry("decoration", 1)); // Default: crop the entire image setCropType(configGroup.readEntry("cropType", 1) == 0 ? LayerCropType : ImageCropType); m_finalRect.setCropRect(image()->bounds()); KisSelectionSP sel = resources->activeSelection(); if (sel) { m_haveCropSelection = true; m_finalRect.setRectInitial(sel->selectedExactRect()); } useCursor(cursor()); //pixel layer if(resources->currentNode() && resources->currentNode()->paintDevice()) { setCropTypeSelectable(true); } //vector layer else { setCropTypeSelectable(false); } } void KisToolCrop::cancelStroke() { m_haveCropSelection = false; doCanvasUpdate(image()->bounds()); } void KisToolCrop::deactivate() { cancelStroke(); KisTool::deactivate(); } void KisToolCrop::requestStrokeEnd() { if (m_haveCropSelection) crop(); } void KisToolCrop::requestStrokeCancellation() { cancelStroke(); } void KisToolCrop::canvasResourceChanged(int key, const QVariant &res) { KisTool::canvasResourceChanged(key, res); //pixel layer if(currentNode() && currentNode()->paintDevice()) { setCropTypeSelectable(true); } //vector layer else { setCropType(ImageCropType); setCropTypeSelectable(false); } } void KisToolCrop::paint(QPainter &painter, const KoViewConverter &converter) { Q_UNUSED(converter); paintOutlineWithHandles(painter); } void KisToolCrop::beginPrimaryAction(KoPointerEvent *event) { setMode(KisTool::PAINT_MODE); QPoint pos = convertToPixelCoord(event).toPoint(); m_dragStart = pos; m_resettingStroke = false; m_mouseOnHandleType = mouseOnHandle(pixelToView(convertToPixelCoord(event))); if (!m_haveCropSelection || m_mouseOnHandleType == None) { m_lastCanvasUpdateRect = image()->bounds(); const int initialWidth = m_finalRect.widthLocked() ? m_finalRect.rect().width() : 1; const int initialHeight = m_finalRect.heightLocked() ? m_finalRect.rect().height() : 1; const QRect initialRect = QRect(m_dragStart, QSize(initialWidth, initialHeight)); m_finalRect.setRectInitial(initialRect); m_initialDragRect = initialRect; m_mouseOnHandleType = KisConstrainedRect::Creation; m_resettingStroke = true; } else { m_initialDragRect = m_finalRect.rect(); } } void KisToolCrop::continuePrimaryAction(KoPointerEvent *event) { CHECK_MODE_SANITY_OR_RETURN(KisTool::PAINT_MODE); QPoint pos = convertToPixelCoord(event).toPoint(); QPoint drag = pos - m_dragStart; m_finalRect.moveHandle(KisConstrainedRect::HandleType(m_mouseOnHandleType), drag, m_initialDragRect); } +bool KisToolCrop::tryContinueLastCropAction() +{ + bool result = false; + + const KUndo2Command *lastCommand = image()->undoAdapter()->presentCommand(); + const KisCropSavedExtraData *data; + + if ((lastCommand = image()->undoAdapter()->presentCommand()) && + (data = dynamic_cast(lastCommand->extraData()))) { + + bool cropImageConsistent = + m_cropType == ImageCropType && + (data->type() == KisCropSavedExtraData::CROP_IMAGE || + data->type() == KisCropSavedExtraData::RESIZE_IMAGE); + + bool cropLayerConsistent = + m_cropType == LayerCropType && + data->type() == KisCropSavedExtraData::CROP_LAYER && + currentNode() == data->cropNode(); + + + if (cropImageConsistent || cropLayerConsistent) { + image()->undoAdapter()->undoLastCommand(); + image()->waitForDone(); + + m_finalRect.setRectInitial(data->cropRect()); + m_haveCropSelection = true; + + result = true; + } + } + + return result; +} + void KisToolCrop::endPrimaryAction(KoPointerEvent *event) { CHECK_MODE_SANITY_OR_RETURN(KisTool::PAINT_MODE); setMode(KisTool::HOVER_MODE); QRectF viewCropRect = pixelToView(m_finalRect.rect()); const bool haveValidRect = viewCropRect.width() > m_handleSize && viewCropRect.height() > m_handleSize; if (!m_haveCropSelection && !haveValidRect) { - m_finalRect.setRectInitial(image()->bounds()); - m_haveCropSelection = true; + if (!tryContinueLastCropAction()) { + m_finalRect.setRectInitial(image()->bounds()); + m_haveCropSelection = true; + } } else if (m_resettingStroke && !haveValidRect) { m_lastCanvasUpdateRect = image()->bounds(); m_haveCropSelection = false; } else { m_haveCropSelection = true; } m_finalRect.normalize(); qint32 type = mouseOnHandle(pixelToView(convertToPixelCoord(event))); setMoveResizeCursor(type); } void KisToolCrop::mouseMoveEvent(KoPointerEvent *event) { QPointF pos = convertToPixelCoord(event); if (m_haveCropSelection) { //if the crop selection is set //set resize cursor if we are on one of the handles if(mode() == KisTool::PAINT_MODE) { //keep the same cursor as the one we clicked with setMoveResizeCursor(m_mouseOnHandleType); }else{ //hovering qint32 type = mouseOnHandle(pixelToView(pos)); setMoveResizeCursor(type); } } } void KisToolCrop::beginPrimaryDoubleClickAction(KoPointerEvent *event) { if (m_haveCropSelection) crop(); // this action will have no continuation event->ignore(); } #define BORDER_LINE_WIDTH 0 #define HALF_BORDER_LINE_WIDTH 0 #define HANDLE_BORDER_LINE_WIDTH 1 QRectF KisToolCrop::borderLineRect() { QRectF borderRect = pixelToView(m_finalRect.rect()); // Draw the border line right next to the crop rectangle perimeter. borderRect.adjust(-HALF_BORDER_LINE_WIDTH, -HALF_BORDER_LINE_WIDTH, HALF_BORDER_LINE_WIDTH, HALF_BORDER_LINE_WIDTH); return borderRect; } #define OUTSIDE_CROP_ALPHA 200 void KisToolCrop::paintOutlineWithHandles(QPainter& gc) { if (canvas() && (mode() == KisTool::PAINT_MODE || m_haveCropSelection)) { gc.save(); QRectF wholeImageRect = pixelToView(image()->bounds()); QRectF borderRect = borderLineRect(); QPainterPath path; path.addRect(wholeImageRect); path.addRect(borderRect); gc.setPen(Qt::NoPen); gc.setBrush(QColor(0, 0, 0, OUTSIDE_CROP_ALPHA)); gc.drawPath(path); // Handles QPen pen(Qt::SolidLine); pen.setWidth(HANDLE_BORDER_LINE_WIDTH); pen.setColor(Qt::black); gc.setPen(pen); gc.setBrush(QColor(200, 200, 200, OUTSIDE_CROP_ALPHA)); gc.drawPath(handlesPath()); gc.setClipRect(borderRect, Qt::IntersectClip); if (m_decoration > 0) { for (int i = decorsIndex[m_decoration-1]; ipaintDevice()) { currentImage()->cropNode(currentNode(), cropRect); } else { currentImage()->cropImage(cropRect); } m_finalRect.setCropRect(image()->bounds()); } void KisToolCrop::setCropTypeLegacy(int cropType) { setCropType(cropType == 0 ? LayerCropType : ImageCropType); } void KisToolCrop::setCropType(KisToolCrop::CropToolType cropType) { if(m_cropType == cropType) return; m_cropType = cropType; // can't save LayerCropType, so have to convert it to int for saving configGroup.writeEntry("cropType", cropType == LayerCropType ? 0 : 1); emit cropTypeChanged(m_cropType); } KisToolCrop::CropToolType KisToolCrop::cropType() const { return m_cropType; } void KisToolCrop::setCropTypeSelectable(bool selectable) { if(selectable == m_cropTypeSelectable) return; m_cropTypeSelectable = selectable; emit cropTypeSelectableChanged(); } bool KisToolCrop::cropTypeSelectable() const { return m_cropTypeSelectable; } int KisToolCrop::decoration() const { return m_decoration; } void KisToolCrop::setDecoration(int i) { // This shouldn't happen, but safety first if(i < 0 || i > DECORATION_COUNT) return; m_decoration = i; emit decorationChanged(decoration()); updateCanvasViewRect(boundingRect()); configGroup.writeEntry("decoration", i); } void KisToolCrop::doCanvasUpdate(const QRect &updateRect) { updateCanvasViewRect(updateRect | m_lastCanvasUpdateRect); m_lastCanvasUpdateRect = updateRect; } void KisToolCrop::slotRectChanged() { emit cropHeightChanged(cropHeight()); emit cropWidthChanged(cropWidth()); emit cropXChanged(cropX()); emit cropYChanged(cropY()); emit ratioChanged(ratio()); emit forceHeightChanged(forceHeight()); emit forceWidthChanged(forceWidth()); emit forceRatioChanged(forceRatio()); emit canGrowChanged(allowGrow()); emit isCenteredChanged(growCenter()); doCanvasUpdate(boundingRect().toAlignedRect()); } void KisToolCrop::setCropX(int x) { if(x == m_finalRect.rect().x()) return; if (!m_haveCropSelection) { m_haveCropSelection = true; m_finalRect.setRectInitial(image()->bounds()); } QPoint offset = m_finalRect.rect().topLeft(); offset.setX(x); m_finalRect.setOffset(offset); } int KisToolCrop::cropX() const { return m_finalRect.rect().x(); } void KisToolCrop::setCropY(int y) { if(y == m_finalRect.rect().y()) return; if (!m_haveCropSelection) { m_haveCropSelection = true; m_finalRect.setRectInitial(image()->bounds()); } QPoint offset = m_finalRect.rect().topLeft(); offset.setY(y); m_finalRect.setOffset(offset); } int KisToolCrop::cropY() const { return m_finalRect.rect().y(); } void KisToolCrop::setCropWidth(int w) { if(w == m_finalRect.rect().width()) return; if (!m_haveCropSelection) { m_haveCropSelection = true; m_finalRect.setRectInitial(image()->bounds()); } m_finalRect.setWidth(w); } int KisToolCrop::cropWidth() const { return m_finalRect.rect().width(); } void KisToolCrop::setForceWidth(bool force) { m_finalRect.setWidthLocked(force); } bool KisToolCrop::forceWidth() const { return m_finalRect.widthLocked(); } void KisToolCrop::setCropHeight(int h) { if(h == m_finalRect.rect().height()) return; if (!m_haveCropSelection) { m_haveCropSelection = true; m_finalRect.setRectInitial(image()->bounds()); } m_finalRect.setHeight(h); } int KisToolCrop::cropHeight() const { return m_finalRect.rect().height(); } void KisToolCrop::setForceHeight(bool force) { m_finalRect.setHeightLocked(force); } bool KisToolCrop::forceHeight() const { return m_finalRect.heightLocked(); } void KisToolCrop::setAllowGrow(bool g) { m_finalRect.setCanGrow(g); m_finalRect.setCropRect(image()->bounds()); configGroup.writeEntry("allowGrow", g); } bool KisToolCrop::allowGrow() const { return m_finalRect.canGrow(); } void KisToolCrop::setGrowCenter(bool value) { m_finalRect.setCentered(value); configGroup.writeEntry("growCenter", value); } bool KisToolCrop::growCenter() const { return m_finalRect.centered(); } void KisToolCrop::setRatio(double ratio) { if(ratio == m_finalRect.ratio()) return; if (!m_haveCropSelection) { m_haveCropSelection = true; m_finalRect.setRectInitial(image()->bounds()); } m_finalRect.setRatio(ratio); } double KisToolCrop::ratio() const { return m_finalRect.ratio(); } void KisToolCrop::setForceRatio(bool force) { m_finalRect.setRatioLocked(force); } bool KisToolCrop::forceRatio() const { return m_finalRect.ratioLocked(); } QWidget* KisToolCrop::createOptionWidget() { KisToolCropConfigWidget* optionsWidget = new KisToolCropConfigWidget(0, this); // See https://bugs.kde.org/show_bug.cgi?id=316896 QWidget *specialSpacer = new QWidget(optionsWidget); specialSpacer->setObjectName("SpecialSpacer"); specialSpacer->setFixedSize(0, 0); optionsWidget->layout()->addWidget(specialSpacer); Q_CHECK_PTR(optionsWidget); optionsWidget->setObjectName(toolId() + " option widget"); connect(optionsWidget->bnCrop, SIGNAL(clicked()), this, SLOT(crop())); connect(optionsWidget, SIGNAL(cropTypeChanged(int)), this, SLOT(setCropTypeLegacy(int))); connect(optionsWidget, SIGNAL(cropXChanged(int)), this, SLOT(setCropX(int))); connect(optionsWidget, SIGNAL(cropYChanged(int)), this, SLOT(setCropY(int))); connect(optionsWidget, SIGNAL(cropHeightChanged(int)), this, SLOT(setCropHeight(int))); connect(optionsWidget, SIGNAL(forceHeightChanged(bool)), this, SLOT(setForceHeight(bool))); connect(optionsWidget, SIGNAL(cropWidthChanged(int)), this, SLOT(setCropWidth(int))); connect(optionsWidget, SIGNAL(forceWidthChanged(bool)), this, SLOT(setForceWidth(bool))); connect(optionsWidget, SIGNAL(ratioChanged(double)), this, SLOT(setRatio(double))); connect(optionsWidget, SIGNAL(forceRatioChanged(bool)), this, SLOT(setForceRatio(bool))); connect(optionsWidget, SIGNAL(decorationChanged(int)), this, SLOT(setDecoration(int))); connect(optionsWidget, SIGNAL(allowGrowChanged(bool)), this, SLOT(setAllowGrow(bool))); connect(optionsWidget, SIGNAL(growCenterChanged(bool)), this, SLOT(setGrowCenter(bool))); optionsWidget->setFixedHeight(optionsWidget->sizeHint().height()); return optionsWidget; } QRectF KisToolCrop::lowerRightHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.right() - m_handleSize / 2.0, cropBorderRect.bottom() - m_handleSize / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::upperRightHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.right() - m_handleSize / 2.0 , cropBorderRect.top() - m_handleSize / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::lowerLeftHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.left() - m_handleSize / 2.0 , cropBorderRect.bottom() - m_handleSize / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::upperLeftHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.left() - m_handleSize / 2.0, cropBorderRect.top() - m_handleSize / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::lowerHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.left() + (cropBorderRect.width() - m_handleSize) / 2.0 , cropBorderRect.bottom() - m_handleSize / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::rightHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.right() - m_handleSize / 2.0 , cropBorderRect.top() + (cropBorderRect.height() - m_handleSize) / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::upperHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.left() + (cropBorderRect.width() - m_handleSize) / 2.0 , cropBorderRect.top() - m_handleSize / 2.0, m_handleSize, m_handleSize); } QRectF KisToolCrop::leftHandleRect(QRectF cropBorderRect) { return QRectF(cropBorderRect.left() - m_handleSize / 2.0, cropBorderRect.top() + (cropBorderRect.height() - m_handleSize) / 2.0, m_handleSize, m_handleSize); } QPainterPath KisToolCrop::handlesPath() { QRectF cropBorderRect = borderLineRect(); QPainterPath path; path.addRect(upperLeftHandleRect(cropBorderRect)); path.addRect(upperRightHandleRect(cropBorderRect)); path.addRect(lowerLeftHandleRect(cropBorderRect)); path.addRect(lowerRightHandleRect(cropBorderRect)); path.addRect(upperHandleRect(cropBorderRect)); path.addRect(lowerHandleRect(cropBorderRect)); path.addRect(leftHandleRect(cropBorderRect)); path.addRect(rightHandleRect(cropBorderRect)); return path; } qint32 KisToolCrop::mouseOnHandle(QPointF currentViewPoint) { QRectF borderRect = borderLineRect(); qint32 handleType = None; if (!m_haveCropSelection) { return None; } if (upperLeftHandleRect(borderRect).contains(currentViewPoint)) { handleType = UpperLeft; } else if (lowerLeftHandleRect(borderRect).contains(currentViewPoint)) { handleType = LowerLeft; } else if (upperRightHandleRect(borderRect).contains(currentViewPoint)) { handleType = UpperRight; } else if (lowerRightHandleRect(borderRect).contains(currentViewPoint)) { handleType = LowerRight; } else if (upperHandleRect(borderRect).contains(currentViewPoint)) { handleType = Upper; } else if (lowerHandleRect(borderRect).contains(currentViewPoint)) { handleType = Lower; } else if (leftHandleRect(borderRect).contains(currentViewPoint)) { handleType = Left; } else if (rightHandleRect(borderRect).contains(currentViewPoint)) { handleType = Right; } else if (borderRect.contains(currentViewPoint)) { handleType = Inside; } return handleType; } void KisToolCrop::setMoveResizeCursor(qint32 handle) { QCursor cursor; switch (handle) { case(UpperLeft): case(LowerRight): cursor = KisCursor::sizeFDiagCursor(); break; case(LowerLeft): case(UpperRight): cursor = KisCursor::sizeBDiagCursor(); break; case(Upper): case(Lower): cursor = KisCursor::sizeVerCursor(); break; case(Left): case(Right): cursor = KisCursor::sizeHorCursor(); break; case(Inside): cursor = KisCursor::sizeAllCursor(); break; default: cursor = KisCursor::arrowCursor(); break; } useCursor(cursor); } QRectF KisToolCrop::boundingRect() { QRectF rect = handlesPath().boundingRect(); rect.adjust(-HANDLE_BORDER_LINE_WIDTH, -HANDLE_BORDER_LINE_WIDTH, HANDLE_BORDER_LINE_WIDTH, HANDLE_BORDER_LINE_WIDTH); return rect; } void KisToolCrop::drawDecorationLine(QPainter *p, DecorationLine *decorLine, const QRectF rect) { QPointF start = rect.topLeft(); QPointF end = rect.topLeft(); qreal small = qMin(rect.width(), rect.height()); qreal large = qMax(rect.width(), rect.height()); switch (decorLine->startXRelation) { case DecorationLine::Width: start.setX(start.x() + decorLine->start.x() * rect.width()); break; case DecorationLine::Height: start.setX(start.x() + decorLine->start.x() * rect.height()); break; case DecorationLine::Smallest: start.setX(start.x() + decorLine->start.x() * small); break; case DecorationLine::Largest: start.setX(start.x() + decorLine->start.x() * large); break; } switch (decorLine->startYRelation) { case DecorationLine::Width: start.setY(start.y() + decorLine->start.y() * rect.width()); break; case DecorationLine::Height: start.setY(start.y() + decorLine->start.y() * rect.height()); break; case DecorationLine::Smallest: start.setY(start.y() + decorLine->start.y() * small); break; case DecorationLine::Largest: start.setY(start.y() + decorLine->start.y() * large); break; } switch (decorLine->endXRelation) { case DecorationLine::Width: end.setX(end.x() + decorLine->end.x() * rect.width()); break; case DecorationLine::Height: end.setX(end.x() + decorLine->end.x() * rect.height()); break; case DecorationLine::Smallest: end.setX(end.x() + decorLine->end.x() * small); break; case DecorationLine::Largest: end.setX(end.x() + decorLine->end.x() * large); break; } switch (decorLine->endYRelation) { case DecorationLine::Width: end.setY(end.y() + decorLine->end.y() * rect.width()); break; case DecorationLine::Height: end.setY(end.y() + decorLine->end.y() * rect.height()); break; case DecorationLine::Smallest: end.setY(end.y() + decorLine->end.y() * small); break; case DecorationLine::Largest: end.setY(end.y() + decorLine->end.y() * large); break; } p->drawLine(start, end); } #include "kis_tool_crop.moc" diff --git a/krita/plugins/tools/tool_crop/kis_tool_crop.h b/krita/plugins/tools/tool_crop/kis_tool_crop.h index 398bf17576..453b6838ae 100644 --- a/krita/plugins/tools/tool_crop/kis_tool_crop.h +++ b/krita/plugins/tools/tool_crop/kis_tool_crop.h @@ -1,229 +1,231 @@ /* * kis_tool_crop.h - part of Krita * * Copyright (c) 2004 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_TOOL_CROP_H_ #define KIS_TOOL_CROP_H_ #include #include #include #include #include #include #include #include "kis_tool.h" #include "flake/kis_node_shape.h" #include "ui_wdg_tool_crop.h" #include "kis_constrained_rect.h" class QRect; struct DecorationLine; /** * Crop tool * * TODO: - crop from selection -- i.e, set crop outline to the exact bounds of the selection. * - (when moving to Qt 4: replace rectangle with darker, dimmer overlay layer * like we have for selections right now) */ class KisToolCrop : public KisTool { Q_OBJECT Q_ENUMS(CropToolType); Q_PROPERTY(CropToolType cropType READ cropType WRITE setCropType NOTIFY cropTypeChanged); Q_PROPERTY(bool cropTypeSelectable READ cropTypeSelectable WRITE setCropTypeSelectable NOTIFY cropTypeSelectableChanged); Q_PROPERTY(int cropX READ cropX WRITE setCropX NOTIFY cropXChanged); Q_PROPERTY(int cropY READ cropY WRITE setCropY NOTIFY cropYChanged); Q_PROPERTY(int cropWidth READ cropWidth WRITE setCropWidth NOTIFY cropWidthChanged); Q_PROPERTY(bool forceWidth READ forceWidth WRITE setForceWidth NOTIFY forceWidthChanged); Q_PROPERTY(int cropHeight READ cropHeight WRITE setCropHeight NOTIFY cropHeightChanged); Q_PROPERTY(bool forceHeight READ forceHeight WRITE setForceHeight NOTIFY forceHeightChanged); Q_PROPERTY(double ratio READ ratio WRITE setRatio NOTIFY ratioChanged); Q_PROPERTY(bool forceRatio READ forceRatio WRITE setForceRatio NOTIFY forceRatioChanged); Q_PROPERTY(int decoration READ decoration WRITE setDecoration NOTIFY decorationChanged); public: enum CropToolType { LayerCropType, ImageCropType }; KisToolCrop(KoCanvasBase * canvas); virtual ~KisToolCrop(); virtual QWidget* createOptionWidget(); void beginPrimaryAction(KoPointerEvent *event); void continuePrimaryAction(KoPointerEvent *event); void endPrimaryAction(KoPointerEvent *event); void beginPrimaryDoubleClickAction(KoPointerEvent *event); virtual void mouseMoveEvent(KoPointerEvent *e); virtual void canvasResourceChanged(int key, const QVariant &res); virtual void paint(QPainter &painter, const KoViewConverter &converter); CropToolType cropType() const; bool cropTypeSelectable() const; int cropX() const; int cropY() const; int cropWidth() const; bool forceWidth() const; int cropHeight() const; bool forceHeight() const; double ratio() const; bool forceRatio() const; int decoration() const; bool growCenter() const; bool allowGrow() const; Q_SIGNALS: void cropTypeSelectableChanged(); void cropTypeChanged(int value); void decorationChanged(int value); void cropXChanged(int value); void cropYChanged(int value); void cropWidthChanged(int value); void cropHeightChanged(int value); void ratioChanged(double value); void forceWidthChanged(bool value); void forceHeightChanged(bool value); void forceRatioChanged(bool value); void canGrowChanged(bool value); void isCenteredChanged(bool value); public Q_SLOTS: virtual void activate(ToolActivation toolActivation, const QSet &shapes); virtual void deactivate(); void requestStrokeEnd(); void requestStrokeCancellation(); void crop(); void setCropTypeLegacy(int cropType); void setCropType(CropToolType cropType); void setCropTypeSelectable(bool selectable); void setCropX(int x); void setCropY(int y); void setCropWidth(int x); void setForceWidth(bool force); void setCropHeight(int y); void setForceHeight(bool force); void setRatio(double ratio); void setForceRatio(bool force); void setDecoration(int i); void setAllowGrow(bool g); void setGrowCenter(bool g); void slotRectChanged(); private: void doCanvasUpdate(const QRect &updateRect); private: void cancelStroke(); QRectF boundingRect(); QRectF borderLineRect(); QPainterPath handlesPath(); void paintOutlineWithHandles(QPainter& gc); qint32 mouseOnHandle(const QPointF currentViewPoint); void setMoveResizeCursor(qint32 handle); QRectF lowerRightHandleRect(QRectF cropBorderRect); QRectF upperRightHandleRect(QRectF cropBorderRect); QRectF lowerLeftHandleRect(QRectF cropBorderRect); QRectF upperLeftHandleRect(QRectF cropBorderRect); QRectF lowerHandleRect(QRectF cropBorderRect); QRectF rightHandleRect(QRectF cropBorderRect); QRectF upperHandleRect(QRectF cropBorderRect); QRectF leftHandleRect(QRectF cropBorderRect); void drawDecorationLine(QPainter *p, DecorationLine *decorLine, QRectF rect); + bool tryContinueLastCropAction(); + private: QPoint m_dragStart; qint32 m_handleSize; bool m_haveCropSelection; qint32 m_mouseOnHandleType; CropToolType m_cropType; bool m_cropTypeSelectable; int m_decoration; bool m_resettingStroke; QRect m_lastCanvasUpdateRect; KConfigGroup configGroup; enum handleType { None = 0, UpperLeft = 1, UpperRight = 2, LowerLeft = 3, LowerRight = 4, Upper = 5, Lower = 6, Left = 7, Right = 8, Inside = 9 }; QList m_decorations; KisConstrainedRect m_finalRect; QRect m_initialDragRect; }; class KisToolCropFactory : public KoToolFactoryBase { public: KisToolCropFactory(const QStringList&) : KoToolFactoryBase("KisToolCrop") { setToolTip(i18n("Crop the image to an area")); setToolType(TOOL_TYPE_TRANSFORM); setActivationShapeId(KRITA_TOOL_ACTIVATION_ID); setPriority(10); setIconName(koIconNameCStr("tool_crop")); setShortcut(KShortcut("C")); } virtual ~KisToolCropFactory() {} virtual KoToolBase * createTool(KoCanvasBase *canvas) { return new KisToolCrop(canvas); } }; #endif // KIS_TOOL_CROP_H_ diff --git a/krita/plugins/tools/tool_transform2/strokes/transform_stroke_strategy.cpp b/krita/plugins/tools/tool_transform2/strokes/transform_stroke_strategy.cpp index 40ac0e2f03..cd63e5f715 100644 --- a/krita/plugins/tools/tool_transform2/strokes/transform_stroke_strategy.cpp +++ b/krita/plugins/tools/tool_transform2/strokes/transform_stroke_strategy.cpp @@ -1,358 +1,358 @@ /* * Copyright (c) 2013 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "transform_stroke_strategy.h" #include +#include "kundo2commandextradata.h" #include "kis_node_progress_proxy.h" #include #include #include #include #include #include #include #include "kis_transform_mask_adapter.h" #include "kis_transform_utils.h" - class ModifyTransformMaskCommand : public KUndo2Command { public: ModifyTransformMaskCommand(KisTransformMaskSP mask, KisTransformMaskParamsInterfaceSP params) : m_mask(mask), m_params(params), m_oldParams(m_mask->transformParams()) { } void redo() { m_mask->setTransformParams(m_params); /** * NOTE: this code "duplicates" the functionality provided * by KisRecalculateTransformMaskJob, but there is not much * reason for starting a separate stroke when a transformation * has happened */ m_mask->recaclulateStaticImage(); updateMask(); } void undo() { m_mask->setTransformParams(m_oldParams); m_mask->recaclulateStaticImage(); updateMask(); } private: void updateMask() { QRect updateRect = m_mask->extent(); KisNodeSP parent = m_mask->parent(); if (parent && parent->original()) { updateRect |= parent->original()->defaultBounds()->bounds(); } m_mask->setDirty(updateRect); } private: KisTransformMaskSP m_mask; KisTransformMaskParamsInterfaceSP m_params; KisTransformMaskParamsInterfaceSP m_oldParams; }; TransformStrokeStrategy::TransformStrokeStrategy(KisNodeSP rootNode, KisSelectionSP selection, KisPostExecutionUndoAdapter *undoAdapter) : KisStrokeStrategyUndoCommandBased(kundo2_i18n("Transform"), false, undoAdapter), m_selection(selection) { if (rootNode->childCount() || !rootNode->paintDevice()) { KisPaintDeviceSP device; if (KisTransformMask* tmask = dynamic_cast(rootNode.data())) { device = tmask->buildPreviewDevice(); /** * When working with transform mask, selections are not * taken into account. */ m_selection = 0; } else { device = rootNode->projection(); } m_previewDevice = createDeviceCache(device); } else { m_previewDevice = createDeviceCache(rootNode->paintDevice()); putDeviceCache(rootNode->paintDevice(), m_previewDevice); } Q_ASSERT(m_previewDevice); } TransformStrokeStrategy::~TransformStrokeStrategy() { } KisPaintDeviceSP TransformStrokeStrategy::previewDevice() const { return m_previewDevice; } KisSelectionSP TransformStrokeStrategy::realSelection() const { return m_selection; } KisPaintDeviceSP TransformStrokeStrategy::createDeviceCache(KisPaintDeviceSP dev) { KisPaintDeviceSP cache; if (m_selection) { QRect srcRect = m_selection->selectedExactRect(); cache = dev->createCompositionSourceDevice(); KisPainter gc(cache); gc.setSelection(m_selection); gc.bitBlt(srcRect.topLeft(), dev, srcRect); } else { cache = dev->createCompositionSourceDevice(dev); } return cache; } bool TransformStrokeStrategy::haveDeviceInCache(KisPaintDeviceSP src) { QMutexLocker l(&m_devicesCacheMutex); return m_devicesCacheHash.contains(src.data()); } void TransformStrokeStrategy::putDeviceCache(KisPaintDeviceSP src, KisPaintDeviceSP cache) { QMutexLocker l(&m_devicesCacheMutex); m_devicesCacheHash.insert(src.data(), cache); } KisPaintDeviceSP TransformStrokeStrategy::getDeviceCache(KisPaintDeviceSP src) { QMutexLocker l(&m_devicesCacheMutex); KisPaintDeviceSP cache = m_devicesCacheHash.value(src.data()); if (!cache) { qWarning() << "WARNING: Transform Stroke: the device is absent in cache!"; } return cache; } bool TransformStrokeStrategy::checkBelongsToSelection(KisPaintDeviceSP device) const { return m_selection && (device == m_selection->pixelSelection().data() || device == m_selection->projection().data()); } void TransformStrokeStrategy::doStrokeCallback(KisStrokeJobData *data) { TransformData *td = dynamic_cast(data); ClearSelectionData *csd = dynamic_cast(data); if(td) { m_savedTransformArgs = td->config; if (td->destination == TransformData::PAINT_DEVICE) { QRect oldExtent = td->node->extent(); KisPaintDeviceSP device = td->node->paintDevice(); if (device && !checkBelongsToSelection(device)) { KisPaintDeviceSP cachedPortion = getDeviceCache(device); Q_ASSERT(cachedPortion); KisTransaction transaction(device); KisProcessingVisitor::ProgressHelper helper(td->node); transformAndMergeDevice(td->config, cachedPortion, device, &helper); runAndSaveCommand(KUndo2CommandSP(transaction.endAndTake()), KisStrokeJobData::CONCURRENT, KisStrokeJobData::NORMAL); td->node->setDirty(oldExtent | td->node->extent()); } if (KisExternalLayer *extLayer = dynamic_cast(td->node.data())) { if (td->config.mode() == ToolTransformArgs::FREE_TRANSFORM || td->config.mode() == ToolTransformArgs::PERSPECTIVE_4POINT) { if (td->config.aX() || td->config.aY()) { qWarning() << "Perspective transform of an external layer is not supported:" << extLayer->name(); } QVector3D transformedCenter; KisTransformWorker w = KisTransformUtils::createTransformWorker(td->config, 0, 0, &transformedCenter); QTransform t = w.transform(); runAndSaveCommand(KUndo2CommandSP(extLayer->transform(t)), KisStrokeJobData::CONCURRENT, KisStrokeJobData::NORMAL); } } else if (KisTransformMask *transformMask = dynamic_cast(td->node.data())) { runAndSaveCommand(KUndo2CommandSP( new ModifyTransformMaskCommand(transformMask, KisTransformMaskParamsInterfaceSP( new KisTransformMaskAdapter(td->config)))), KisStrokeJobData::CONCURRENT, KisStrokeJobData::NORMAL); } } else if (m_selection) { /** * We use usual transaction here, because we cannot calsulate * transformation for perspective and warp workers. */ KisTransaction transaction(m_selection->pixelSelection()); KisProcessingVisitor::ProgressHelper helper(td->node); KisTransformUtils::transformDevice(td->config, m_selection->pixelSelection(), &helper); runAndSaveCommand(KUndo2CommandSP(transaction.endAndTake()), KisStrokeJobData::CONCURRENT, KisStrokeJobData::NORMAL); } } else if (csd) { KisPaintDeviceSP device = csd->node->paintDevice(); if (device && !checkBelongsToSelection(device)) { if (!haveDeviceInCache(device)) { putDeviceCache(device, createDeviceCache(device)); } clearSelection(device); } else if (KisTransformMask *transformMask = dynamic_cast(csd->node.data())) { runAndSaveCommand(KUndo2CommandSP( new ModifyTransformMaskCommand(transformMask, KisTransformMaskParamsInterfaceSP( new KisDumbTransformMaskParams(true)))), KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::NORMAL); } } else { KisStrokeStrategyUndoCommandBased::doStrokeCallback(data); } } void TransformStrokeStrategy::clearSelection(KisPaintDeviceSP device) { KisTransaction transaction(device); if (m_selection) { device->clearSelection(m_selection); } else { QRect oldExtent = device->extent(); device->clear(); device->setDirty(oldExtent); } runAndSaveCommand(KUndo2CommandSP(transaction.endAndTake()), KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::NORMAL); } void TransformStrokeStrategy::transformAndMergeDevice(const ToolTransformArgs &config, KisPaintDeviceSP src, KisPaintDeviceSP dst, KisProcessingVisitor::ProgressHelper *helper) { KoUpdaterPtr mergeUpdater = src != dst ? helper->updater() : 0; KisTransformUtils::transformDevice(config, src, helper); if (src != dst) { QRect mergeRect = src->extent(); KisPainter painter(dst); painter.setProgress(mergeUpdater); painter.bitBlt(mergeRect.topLeft(), src, mergeRect); painter.end(); } } -struct TransformExtraData : public KUndo2Command::ExtraData +struct TransformExtraData : public KUndo2CommandExtraData { ToolTransformArgs savedTransformArgs; }; void TransformStrokeStrategy::postProcessToplevelCommand(KUndo2Command *command) { TransformExtraData *data = new TransformExtraData(); data->savedTransformArgs = m_savedTransformArgs; command->setExtraData(data); } bool TransformStrokeStrategy::fetchArgsFromCommand(const KUndo2Command *command, ToolTransformArgs *args) { const TransformExtraData *data = dynamic_cast(command->extraData()); if (data) { *args = data->savedTransformArgs; } return bool(data); } void TransformStrokeStrategy::initStrokeCallback() { KisStrokeStrategyUndoCommandBased::initStrokeCallback(); if (m_selection) { m_selection->setVisible(false); } } void TransformStrokeStrategy::finishStrokeCallback() { if (m_selection) { m_selection->setVisible(true); } KisStrokeStrategyUndoCommandBased::finishStrokeCallback(); } void TransformStrokeStrategy::cancelStrokeCallback() { KisStrokeStrategyUndoCommandBased::cancelStrokeCallback(); if (m_selection) { m_selection->setVisible(true); } } diff --git a/libs/kundo2/CMakeLists.txt b/libs/kundo2/CMakeLists.txt index b2c8803892..bf056323a5 100644 --- a/libs/kundo2/CMakeLists.txt +++ b/libs/kundo2/CMakeLists.txt @@ -1,31 +1,31 @@ include_directories(${QT_INCLUDES} ${KDE4_INCLUDES}) set(kundo2_LIB_SRCS kundo2stack.cpp kundo2group.cpp kundo2view.cpp kundo2model.cpp kundo2magicstring.cpp - + kundo2commandextradata.cpp ) kde4_add_library(kundo2 SHARED ${kundo2_LIB_SRCS}) target_link_libraries(kundo2 ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY} ${KDE4_KDECORE_LIBS} ${KDE4_KDEUI_LIBS}) set_target_properties(kundo2 PROPERTIES VERSION ${GENERIC_CALLIGRA_LIB_VERSION} SOVERSION ${GENERIC_CALLIGRA_LIB_SOVERSION} ) install(TARGETS kundo2 ${INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES kundo2_export.h kundo2stack.h kundo2qstack.h kundo2group.h kundo2view.h kundo2model.h kundo2command.h kundo2magicstring.h DESTINATION ${INCLUDE_INSTALL_DIR}/calligra COMPONENT Devel ) diff --git a/libs/kundo2/kundo2commandextradata.cpp b/libs/kundo2/kundo2commandextradata.cpp new file mode 100644 index 0000000000..5a4fbcd5ae --- /dev/null +++ b/libs/kundo2/kundo2commandextradata.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2015 Dmitry Kazakov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "kundo2commandextradata.h" + + +KUndo2CommandExtraData::~KUndo2CommandExtraData() +{ +} diff --git a/libs/kundo2/kundo2commandextradata.h b/libs/kundo2/kundo2commandextradata.h new file mode 100644 index 0000000000..248c3b6e1b --- /dev/null +++ b/libs/kundo2/kundo2commandextradata.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2015 Dmitry Kazakov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#ifndef __KUNDO2COMMANDEXTRADATA_H +#define __KUNDO2COMMANDEXTRADATA_H + +#include "kundo2_export.h" + + +class KUNDO2_EXPORT KUndo2CommandExtraData +{ +public: + virtual ~KUndo2CommandExtraData(); +}; + +#endif /* __KUNDO2COMMANDEXTRADATA_H */ diff --git a/libs/kundo2/kundo2stack.cpp b/libs/kundo2/kundo2stack.cpp index 395cb9787e..066de6a36c 100644 --- a/libs/kundo2/kundo2stack.cpp +++ b/libs/kundo2/kundo2stack.cpp @@ -1,1431 +1,1427 @@ /* * Copyright (c) 2014 Dmitry Kazakov * Copyright (c) 2014 Mohit Goyal * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include #include #include #include #include "kundo2stack.h" #include "kundo2stack_p.h" #include "kundo2group.h" #include #include #ifndef QT_NO_UNDOCOMMAND /*! \class KUndo2Command \brief The KUndo2Command class is the base class of all commands stored on a KUndo2QStack. \since 4.2 For an overview of Qt's Undo Framework, see the \l{Overview of Qt's Undo Framework}{overview document}. A KUndo2Command represents a single editing action on a document; for example, inserting or deleting a block of text in a text editor. KUndo2Command can apply a change to the document with redo() and undo the change with undo(). The implementations for these functions must be provided in a derived class. \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 0 A KUndo2Command has an associated text(). This is a short string describing what the command does. It is used to update the text properties of the stack's undo and redo actions; see KUndo2QStack::createUndoAction() and KUndo2QStack::createRedoAction(). KUndo2Command objects are owned by the stack they were pushed on. KUndo2QStack deletes a command if it has been undone and a new command is pushed. For example: \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 1 In effect, when a command is pushed, it becomes the top-most command on the stack. To support command compression, KUndo2Command has an id() and the virtual function mergeWith(). These functions are used by KUndo2QStack::push(). To support command macros, a KUndo2Command object can have any number of child commands. Undoing or redoing the parent command will cause the child commands to be undone or redone. A command can be assigned to a parent explicitly in the constructor. In this case, the command will be owned by the parent. The parent in this case is usually an empty command, in that it doesn't provide its own implementation of undo() and redo(). Instead, it uses the base implementations of these functions, which simply call undo() or redo() on all its children. The parent should, however, have a meaningful text(). \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 2 Another way to create macros is to use the convenience functions KUndo2QStack::beginMacro() and KUndo2QStack::endMacro(). \sa KUndo2QStack */ /*! Constructs a KUndo2Command object with the given \a parent and \a text. If \a parent is not 0, this command is appended to parent's child list. The parent command then owns this command and will delete it in its destructor. \sa ~KUndo2Command() */ KUndo2Command::KUndo2Command(const KUndo2MagicString &text, KUndo2Command *parent): m_hasParent(parent != 0), m_timedID(0), m_endOfCommand(QTime::currentTime()) { d = new KUndo2CommandPrivate; if (parent != 0) { parent->d->child_list.append(this); } setText(text); setTime(); } /*! Constructs a KUndo2Command object with parent \a parent. If \a parent is not 0, this command is appended to parent's child list. The parent command then owns this command and will delete it in its destructor. \sa ~KUndo2Command() */ KUndo2Command::KUndo2Command(KUndo2Command *parent): m_hasParent(parent != 0),m_timedID(0) { d = new KUndo2CommandPrivate; if (parent != 0) parent->d->child_list.append(this); setTime(); } /*! Destroys the KUndo2Command object and all child commands. \sa KUndo2Command() */ KUndo2Command::~KUndo2Command() { qDeleteAll(d->child_list); delete d; } /*! Returns the ID of this command. A command ID is used in command compression. It must be an integer unique to this command's class, or -1 if the command doesn't support compression. If the command supports compression this function must be overridden in the derived class to return the correct ID. The base implementation returns -1. KUndo2QStack::push() will only try to merge two commands if they have the same ID, and the ID is not -1. \sa mergeWith(), KUndo2QStack::push() */ int KUndo2Command::id() const { return -1; } /*! Attempts to merge this command with \a command. Returns true on success; otherwise returns false. If this function returns true, calling this command's redo() must have the same effect as redoing both this command and \a command. Similarly, calling this command's undo() must have the same effect as undoing \a command and this command. KUndo2QStack will only try to merge two commands if they have the same id, and the id is not -1. The default implementation returns false. \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 3 \sa id() KUndo2QStack::push() */ bool KUndo2Command::mergeWith(const KUndo2Command *command) { Q_UNUSED(command); return false; } /*! Applies a change to the document. This function must be implemented in the derived class. Calling KUndo2QStack::push(), KUndo2QStack::undo() or KUndo2QStack::redo() from this function leads to undefined beahavior. The default implementation calls redo() on all child commands. \sa undo() */ void KUndo2Command::redo() { for (int i = 0; i < d->child_list.size(); ++i) d->child_list.at(i)->redo(); } /*! Reverts a change to the document. After undo() is called, the state of the document should be the same as before redo() was called. This function must be implemented in the derived class. Calling KUndo2QStack::push(), KUndo2QStack::undo() or KUndo2QStack::redo() from this function leads to undefined beahavior. The default implementation calls undo() on all child commands in reverse order. \sa redo() */ void KUndo2Command::undo() { for (int i = d->child_list.size() - 1; i >= 0; --i) d->child_list.at(i)->undo(); } /*! Returns a short text string describing what this command does; for example, "insert text". The text is used when the text properties of the stack's undo and redo actions are updated. \sa setText(), KUndo2QStack::createUndoAction(), KUndo2QStack::createRedoAction() */ QString KUndo2Command::actionText() const { if(d->actionText!=NULL) return d->actionText; else return QString(); } /*! Returns a short text string describing what this command does; for example, "insert text". The text is used when the text properties of the stack's undo and redo actions are updated. \sa setText(), KUndo2QStack::createUndoAction(), KUndo2QStack::createRedoAction() */ KUndo2MagicString KUndo2Command::text() const { return d->text; } /*! Sets the command's text to be the \a text specified. The specified text should be a short user-readable string describing what this command does. \sa text() KUndo2QStack::createUndoAction() KUndo2QStack::createRedoAction() */ void KUndo2Command::setText(const KUndo2MagicString &undoText) { d->text = undoText; d->actionText = undoText.toSecondaryString(); } /*! \since 4.4 Returns the number of child commands in this command. \sa child() */ int KUndo2Command::childCount() const { return d->child_list.count(); } /*! \since 4.4 Returns the child command at \a index. \sa childCount(), KUndo2QStack::command() */ const KUndo2Command *KUndo2Command::child(int index) const { if (index < 0 || index >= d->child_list.count()) return 0; return d->child_list.at(index); } bool KUndo2Command::hasParent() { return m_hasParent; } int KUndo2Command::timedId() { return m_timedID; } void KUndo2Command::setTimedID(int value) { m_timedID = value; } bool KUndo2Command::timedMergeWith(KUndo2Command *other) { if(other->timedId() == this->timedId() && other->timedId()!=-1 ) m_mergeCommandsVector.append(other); else return false; return true; } void KUndo2Command::setTime() { m_timeOfCreation = QTime::currentTime(); } QTime KUndo2Command::time() { return m_timeOfCreation; } void KUndo2Command::setEndTime() { m_endOfCommand = QTime::currentTime(); } QTime KUndo2Command::endTime() { return m_endOfCommand; } void KUndo2Command::undoMergedCommands() { undo(); if (!mergeCommandsVector().isEmpty()) { QVectorIterator it(mergeCommandsVector()); it.toFront(); while (it.hasNext()) { KUndo2Command* cmd = dynamic_cast(it.next()); cmd->undoMergedCommands(); } } } void KUndo2Command::redoMergedCommands() { if (!mergeCommandsVector().isEmpty()) { QVectorIterator it(mergeCommandsVector()); it.toBack(); while (it.hasPrevious()) { KUndo2Command* cmd = dynamic_cast(it.previous()); cmd->redoMergedCommands(); } } redo(); } QVector KUndo2Command::mergeCommandsVector() { return m_mergeCommandsVector; } bool KUndo2Command::isMerged() { return !m_mergeCommandsVector.isEmpty(); } -KUndo2Command::ExtraData::~ExtraData() -{ -} - -KUndo2Command::ExtraData* KUndo2Command::extraData() const +KUndo2CommandExtraData* KUndo2Command::extraData() const { return d->extraData.data(); } -void KUndo2Command::setExtraData(ExtraData *data) +void KUndo2Command::setExtraData(KUndo2CommandExtraData *data) { d->extraData.reset(data); } #endif // QT_NO_UNDOCOMMAND #ifndef QT_NO_UNDOSTACK /*! \class KUndo2QStack \brief The KUndo2QStack class is a stack of KUndo2Command objects. \since 4.2 For an overview of Qt's Undo Framework, see the \l{Overview of Qt's Undo Framework}{overview document}. An undo stack maintains a stack of commands that have been applied to a document. New commands are pushed on the stack using push(). Commands can be undone and redone using undo() and redo(), or by triggering the actions returned by createUndoAction() and createRedoAction(). KUndo2QStack keeps track of the \a current command. This is the command which will be executed by the next call to redo(). The index of this command is returned by index(). The state of the edited object can be rolled forward or back using setIndex(). If the top-most command on the stack has already been redone, index() is equal to count(). KUndo2QStack provides support for undo and redo actions, command compression, command macros, and supports the concept of a \e{clean state}. \section1 Undo and Redo Actions KUndo2QStack provides convenient undo and redo QAction objects, which can be inserted into a menu or a toolbar. When commands are undone or redone, KUndo2QStack updates the text properties of these actions to reflect what change they will trigger. The actions are also disabled when no command is available for undo or redo. These actions are returned by KUndo2QStack::createUndoAction() and KUndo2QStack::createRedoAction(). \section1 Command Compression and Macros Command compression is useful when several commands can be compressed into a single command that can be undone and redone in a single operation. For example, when a user types a character in a text editor, a new command is created. This command inserts the character into the document at the cursor position. However, it is more convenient for the user to be able to undo or redo typing of whole words, sentences, or paragraphs. Command compression allows these single-character commands to be merged into a single command which inserts or deletes sections of text. For more information, see KUndo2Command::mergeWith() and push(). A command macro is a sequence of commands, all of which are undone and redone in one go. Command macros are created by giving a command a list of child commands. Undoing or redoing the parent command will cause the child commands to be undone or redone. Command macros may be created explicitly by specifying a parent in the KUndo2Command constructor, or by using the convenience functions beginMacro() and endMacro(). Although command compression and macros appear to have the same effect to the user, they often have different uses in an application. Commands that perform small changes to a document may be usefully compressed if there is no need to individually record them, and if only larger changes are relevant to the user. However, for commands that need to be recorded individually, or those that cannot be compressed, it is useful to use macros to provide a more convenient user experience while maintaining a record of each command. \section1 Clean State KUndo2QStack supports the concept of a clean state. When the document is saved to disk, the stack can be marked as clean using setClean(). Whenever the stack returns to this state through undoing and redoing commands, it emits the signal cleanChanged(). This signal is also emitted when the stack leaves the clean state. This signal is usually used to enable and disable the save actions in the application, and to update the document's title to reflect that it contains unsaved changes. \sa KUndo2Command, KUndo2View */ #ifndef QT_NO_ACTION KUndo2Action::KUndo2Action(const QString &textTemplate, const QString &defaultText, QObject *parent) : QAction(parent) { m_textTemplate = textTemplate; m_defaultText = defaultText; } void KUndo2Action::setPrefixedText(const QString &text) { if (text.isEmpty()) setText(m_defaultText); else setText(m_textTemplate.arg(text)); } #endif // QT_NO_ACTION /*! \internal Sets the current index to \a idx, emitting appropriate signals. If \a clean is true, makes \a idx the clean index as well. */ void KUndo2QStack::setIndex(int idx, bool clean) { bool was_clean = m_index == m_clean_index; if (m_lastMergedIndex <= idx) { m_lastMergedSetCount = idx - m_lastMergedIndex; } else { m_lastMergedSetCount = 1; m_lastMergedIndex = idx-1; } if(idx == 0){ m_lastMergedSetCount = 0; m_lastMergedIndex = 0; } if (idx != m_index) { m_index = idx; emit indexChanged(m_index); emit canUndoChanged(canUndo()); emit undoTextChanged(undoText()); emit canRedoChanged(canRedo()); emit redoTextChanged(redoText()); } if (clean) m_clean_index = m_index; bool is_clean = m_index == m_clean_index; if (is_clean != was_clean) emit cleanChanged(is_clean); } void KUndo2QStack::purgeRedoState() { bool macro = !m_macro_stack.isEmpty(); if (macro) return; bool redoStateChanged = false; bool cleanStateChanged = false; while (m_index < m_command_list.size()) { delete m_command_list.takeLast(); redoStateChanged = true; } if (m_clean_index > m_index) { m_clean_index = -1; // we've deleted the clean state cleanStateChanged = true; } if (redoStateChanged) { emit canRedoChanged(canRedo()); emit redoTextChanged(redoText()); } if (cleanStateChanged) { emit cleanChanged(isClean()); } } /*! \internal If the number of commands on the stack exceedes the undo limit, deletes commands from the bottom of the stack. Returns true if commands were deleted. */ bool KUndo2QStack::checkUndoLimit() { if (m_undo_limit <= 0 || !m_macro_stack.isEmpty() || m_undo_limit >= m_command_list.count()) return false; int del_count = m_command_list.count() - m_undo_limit; for (int i = 0; i < del_count; ++i) delete m_command_list.takeFirst(); m_index -= del_count; if (m_clean_index != -1) { if (m_clean_index < del_count) m_clean_index = -1; // we've deleted the clean command else m_clean_index -= del_count; } return true; } /*! Constructs an empty undo stack with the parent \a parent. The stack will initially be in the clean state. If \a parent is a KUndo2Group object, the stack is automatically added to the group. \sa push() */ KUndo2QStack::KUndo2QStack(QObject *parent) : QObject(parent), m_index(0), m_clean_index(0), m_group(0), m_undo_limit(0), m_useCumulativeUndoRedo(false), m_lastMergedSetCount(0), m_lastMergedIndex(0) { setTimeT1(5); setTimeT2(1); setStrokesN(2); #ifndef QT_NO_UNDOGROUP if (KUndo2Group *group = qobject_cast(parent)) group->addStack(this); #endif } /*! Destroys the undo stack, deleting any commands that are on it. If the stack is in a KUndo2Group, the stack is automatically removed from the group. \sa KUndo2QStack()The number of last strokes which Krita should store separately */ KUndo2QStack::~KUndo2QStack() { #ifndef QT_NO_UNDOGROUP if (m_group != 0) m_group->removeStack(this); #endif clear(); } /*! Clears the command stack by deleting all commands on it, and returns the stack to the clean state.{ } Commands are not undone or redone; the state of the edited object remains unchanged. This function is usually used when the contents of the document are abandoned. \sa KUndo2QStack() */ void KUndo2QStack::clear() { if (m_command_list.isEmpty()) return; bool was_clean = isClean(); m_macro_stack.clear(); qDeleteAll(m_command_list); m_command_list.clear(); m_index = 0; m_clean_index = 0; emit indexChanged(0); emit canUndoChanged(false); emit undoTextChanged(QString()); emit canRedoChanged(false); emit redoTextChanged(QString()); if (!was_clean) emit cleanChanged(true); } /*! Pushes \a cmd on the stack or merges it with the most recently executed command. In either case, executes \a cmd by calling its redo() function. If \a cmd's id is not -1, and if the id is the same as that of the most recently executed command, KUndo2QStack will attempt to merge the two commands by calling KUndo2Command::mergeWith() on the most recently executed command. If KUndo2Command::mergeWith() returns true, \a cmd is deleted. In all other cases \a cmd is simply pushed on the stack. If commands were undone before \a cmd was pushed, the current command and all commands above it are deleted. Hence \a cmd always ends up being the top-most on the stack. Once a command is pushed, the stack takes ownership of it. There are no getters to return the command, since modifying it after it has been executed will almost always lead to corruption of the document's state. \sa KUndo2Command::id() KUndo2Command::mergeWith() */ void KUndo2QStack::push(KUndo2Command *cmd) { cmd->redoMergedCommands(); cmd->setEndTime(); bool macro = !m_macro_stack.isEmpty(); KUndo2Command *cur = 0; if (macro) { KUndo2Command *macro_cmd = m_macro_stack.last(); if (!macro_cmd->d->child_list.isEmpty()) cur = macro_cmd->d->child_list.last(); } else { if (m_index > 0) cur = m_command_list.at(m_index - 1); while (m_index < m_command_list.size()) delete m_command_list.takeLast(); if (m_clean_index > m_index) m_clean_index = -1; // we've deleted the clean state } bool try_merge = cur != 0 && cur->id() != -1 && cur->id() == cmd->id() && (macro || m_index != m_clean_index); /*! *Here we are going to try to merge several commands together using the QVector field in the commands using *3 parameters. N : Number of commands that should remain individual at the top of the stack. T1 : Time lapsed between current command and previously merged command -- signal to *merge throughout the stack. T2 : Time lapsed between two commands signalling both commands belong to the same set *Whenever a KUndo2Command is initialized -- it consists of a start-time and when it is pushed --an end time. *Every time a command is pushed -- it checks whether the command pushed was pushed after T1 seconds of the last merged command *Then the merging begins with each group depending on the time in between each command (T2). * *@TODO : Currently it is not able to merge two merged commands together. */ if (!macro && m_command_list.size() > 1 && cmd->timedId() != -1 && m_useCumulativeUndoRedo) { KUndo2Command* lastcmd = m_command_list.last(); if (qAbs(cmd->time().msecsTo(lastcmd->endTime())) < m_timeT2 * 1000) { m_lastMergedSetCount++; } else { m_lastMergedSetCount = 0; m_lastMergedIndex = m_index-1; } if(lastcmd->timedId()==-1){ m_lastMergedSetCount = 0; m_lastMergedIndex = m_index; } if (m_lastMergedSetCount > m_strokesN) { KUndo2Command* toMerge = m_command_list.at(m_lastMergedIndex); if (toMerge && m_command_list.at(m_lastMergedIndex + 1)) { if(toMerge->timedMergeWith(m_command_list.at(m_lastMergedIndex + 1))){ m_command_list.removeAt(m_lastMergedIndex + 1); } m_lastMergedSetCount--; m_lastMergedIndex = m_command_list.indexOf(toMerge); } } m_index = m_command_list.size(); if(m_lastMergedIndextime().msecsTo(m_command_list.at(m_lastMergedIndex)->endTime()) < -m_timeT1 * 1000) { //T1 time elapsed QListIterator it(m_command_list); it.toBack(); m_lastMergedSetCount = 1; while (it.hasPrevious()) { KUndo2Command* curr = it.previous(); KUndo2Command* lastCmdInCurrent = curr; if (!lastcmd->mergeCommandsVector().isEmpty()) { if (qAbs(lastcmd->mergeCommandsVector().last()->time().msecsTo(lastCmdInCurrent->endTime())) < int(m_timeT2 * 1000) && lastcmd != lastCmdInCurrent && lastcmd != curr) { if(lastcmd->timedMergeWith(curr)){ if (m_command_list.contains(curr)) { m_command_list.removeOne(curr); } } } else { lastcmd = curr; //end of a merge set } } else { if (qAbs(lastcmd->time().msecsTo(lastCmdInCurrent->endTime())) < int(m_timeT2 * 1000) && lastcmd != lastCmdInCurrent &&lastcmd!=curr) { if(lastcmd->timedMergeWith(curr)){ if (m_command_list.contains(curr)){ m_command_list.removeOne(curr); } } } else { lastcmd = curr; //end of a merge set } } } m_lastMergedIndex = m_command_list.size()-1; } } m_index = m_command_list.size(); } if (try_merge && cur->mergeWith(cmd)) { delete cmd; if (!macro) { emit indexChanged(m_index); emit canUndoChanged(canUndo()); emit undoTextChanged(undoText()); emit canRedoChanged(canRedo()); emit redoTextChanged(redoText()); } } else { if (macro) { m_macro_stack.last()->d->child_list.append(cmd); } else { m_command_list.append(cmd); if(checkUndoLimit()) { m_lastMergedIndex = m_index - m_strokesN; } setIndex(m_index + 1, false); } } } /*! Marks the stack as clean and emits cleanChanged() if the stack was not already clean. Whenever the stack returns to this state through the use of undo/redo commands, it emits the signal cleanChanged(). This signal is also emitted when the stack leaves the clean state. \sa isClean(), cleanIndex() */ void KUndo2QStack::setClean() { if (!m_macro_stack.isEmpty()) { qWarning("KUndo2QStack::setClean(): cannot set clean in the middle of a macro"); return; } setIndex(m_index, true); } /*! If the stack is in the clean state, returns true; otherwise returns false. \sa setClean() cleanIndex() */ bool KUndo2QStack::isClean() const { if (!m_macro_stack.isEmpty()) return false; return m_clean_index == m_index; } /*! Returns the clean index. This is the index at which setClean() was called. A stack may not have a clean index. This happens if a document is saved, some commands are undone, then a new command is pushed. Since push() deletes all the undone commands before pushing the new command, the stack can't return to the clean state again. In this case, this function returns -1. \sa isClean() setClean() */ int KUndo2QStack::cleanIndex() const { return m_clean_index; } /*! Undoes the command below the current command by calling KUndo2Command::undo(). Decrements the current command index. If the stack is empty, or if the bottom command on the stack has already been undone, this function does nothing. \sa redo() index() */ void KUndo2QStack::undo() { if (m_index == 0) return; if (!m_macro_stack.isEmpty()) { qWarning("KUndo2QStack::undo(): cannot undo in the middle of a macro"); return; } int idx = m_index - 1; m_command_list.at(idx)->undoMergedCommands(); setIndex(idx, false); } /*! Redoes the current command by calling KUndo2Command::redo(). Increments the current command index. If the stack is empty, or if the top command on the stack has already been redone, this function does nothing. \sa undo() index() */ void KUndo2QStack::redo() { if (m_index == m_command_list.size()) return; if (!m_macro_stack.isEmpty()) { qWarning("KUndo2QStack::redo(): cannot redo in the middle of a macro"); return; } m_command_list.at(m_index)->redoMergedCommands(); setIndex(m_index + 1, false); } /*! Returns the number of commands on the stack. Macro commands are counted as one command. \sa index() setIndex() command() */ int KUndo2QStack::count() const { return m_command_list.size(); } /*! Returns the index of the current command. This is the command that will be executed on the next call to redo(). It is not always the top-most command on the stack, since a number of commands may have been undone. \sa undo() redo() count() */ int KUndo2QStack::index() const { return m_index; } /*! Repeatedly calls undo() or redo() until the current command index reaches \a idx. This function can be used to roll the state of the document forwards of backwards. indexChanged() is emitted only once. \sa index() count() undo() redo() */ void KUndo2QStack::setIndex(int idx) { if (!m_macro_stack.isEmpty()) { qWarning("KUndo2QStack::setIndex(): cannot set index in the middle of a macro"); return; } if (idx < 0) idx = 0; else if (idx > m_command_list.size()) idx = m_command_list.size(); int i = m_index; while (i < idx) { m_command_list.at(i++)->redoMergedCommands(); } while (i > idx) { m_command_list.at(--i)->undoMergedCommands(); } setIndex(idx, false); } /*! Returns true if there is a command available for undo; otherwise returns false. This function returns false if the stack is empty, or if the bottom command on the stack has already been undone. Synonymous with index() == 0. \sa index() canRedo() */ bool KUndo2QStack::canUndo() const { if (!m_macro_stack.isEmpty()) return false; return m_index > 0; } /*! Returns true if there is a command available for redo; otherwise returns false. This function returns false if the stack is empty or if the top command on the stack has already been redone. Synonymous with index() == count(). \sa index() canUndo() */ bool KUndo2QStack::canRedo() const { if (!m_macro_stack.isEmpty()) return false; return m_index < m_command_list.size(); } /*! Returns the text of the command which will be undone in the next call to undo(). \sa KUndo2Command::text() redoActionText() undoItemText() */ QString KUndo2QStack::undoText() const { if (!m_macro_stack.isEmpty()) return QString(); if (m_index > 0 && m_command_list.at(m_index-1)!=NULL) return m_command_list.at(m_index - 1)->actionText(); return QString(); } /*! Returns the text of the command which will be redone in the next call to redo(). \sa KUndo2Command::text() undoActionText() redoItemText() */ QString KUndo2QStack::redoText() const { if (!m_macro_stack.isEmpty()) return QString(); if (m_index < m_command_list.size()) return m_command_list.at(m_index)->actionText(); return QString(); } #ifndef QT_NO_ACTION /*! Creates an undo QAction object with the given \a parent. Triggering this action will cause a call to undo(). The text of this action is the text of the command which will be undone in the next call to undo(), prefixed by the specified \a prefix. If there is no command available for undo, this action will be disabled. If \a prefix is empty, the default prefix "Undo" is used. \sa createRedoAction(), canUndo(), KUndo2Command::text() */ QAction *KUndo2QStack::createUndoAction(QObject *parent) const { KUndo2Action *result = new KUndo2Action(i18n("Undo %1"), i18nc("Default text for undo action", "Undo"), parent); result->setEnabled(canUndo()); result->setPrefixedText(undoText()); connect(this, SIGNAL(canUndoChanged(bool)), result, SLOT(setEnabled(bool))); connect(this, SIGNAL(undoTextChanged(QString)), result, SLOT(setPrefixedText(QString))); connect(result, SIGNAL(triggered()), this, SLOT(undo())); return result; } /*! Creates an redo QAction object with the given \a parent. Triggering this action will cause a call to redo(). The text of this action is the text of the command which will be redone in the next call to redo(), prefixed by the specified \a prefix. If there is no command available for redo, this action will be disabled. If \a prefix is empty, the default prefix "Redo" is used. \sa createUndoAction(), canRedo(), KUndo2Command::text() */ QAction *KUndo2QStack::createRedoAction(QObject *parent) const { KUndo2Action *result = new KUndo2Action(i18n("Redo %1"), i18nc("Default text for redo action", "Redo"), parent); result->setEnabled(canRedo()); result->setPrefixedText(redoText()); connect(this, SIGNAL(canRedoChanged(bool)), result, SLOT(setEnabled(bool))); connect(this, SIGNAL(redoTextChanged(QString)), result, SLOT(setPrefixedText(QString))); connect(result, SIGNAL(triggered()), this, SLOT(redo())); return result; } #endif // QT_NO_ACTION /*! Begins composition of a macro command with the given \a text description. An empty command described by the specified \a text is pushed on the stack. Any subsequent commands pushed on the stack will be appended to the empty command's children until endMacro() is called. Calls to beginMacro() and endMacro() may be nested, but every call to beginMacro() must have a matching call to endMacro(). While a macro is composed, the stack is disabled. This means that: \list \i indexChanged() and cleanChanged() are not emitted, \i canUndo() and canRedo() return false, \i calling undo() or redo() has no effect, \i the undo/redo actions are disabled. \endlist The stack becomes enabled and appropriate signals are emitted when endMacro() is called for the outermost macro. \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 4 This code is equivalent to: \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 5 \sa endMacro() */ void KUndo2QStack::beginMacro(const KUndo2MagicString &text) { KUndo2Command *cmd = new KUndo2Command(); cmd->setText(text); if (m_macro_stack.isEmpty()) { while (m_index < m_command_list.size()) delete m_command_list.takeLast(); if (m_clean_index > m_index) m_clean_index = -1; // we've deleted the clean state m_command_list.append(cmd); } else { m_macro_stack.last()->d->child_list.append(cmd); } m_macro_stack.append(cmd); if (m_macro_stack.count() == 1) { emit canUndoChanged(false); emit undoTextChanged(QString()); emit canRedoChanged(false); emit redoTextChanged(QString()); } } /*! Ends composition of a macro command. If this is the outermost macro in a set nested macros, this function emits indexChanged() once for the entire macro command. \sa beginMacro() */ void KUndo2QStack::endMacro() { if (m_macro_stack.isEmpty()) { qWarning("KUndo2QStack::endMacro(): no matching beginMacro()"); return; } m_macro_stack.removeLast(); if (m_macro_stack.isEmpty()) { checkUndoLimit(); setIndex(m_index + 1, false); } } /*! \since 4.4 Returns a const pointer to the command at \a index. This function returns a const pointer, because modifying a command, once it has been pushed onto the stack and executed, almost always causes corruption of the state of the document, if the command is later undone or redone. \sa KUndo2Command::child() */ const KUndo2Command *KUndo2QStack::command(int index) const { if (index < 0 || index >= m_command_list.count()) return 0; return m_command_list.at(index); } /*! Returns the text of the command at index \a idx. \sa beginMacro() */ QString KUndo2QStack::text(int idx) const { if (idx < 0 || idx >= m_command_list.size()) return QString(); return m_command_list.at(idx)->text().toString(); } /*! \property KUndo2QStack::undoLimit \brief the maximum number of commands on this stack. \since 4.3 When the number of commands on a stack exceedes the stack's undoLimit, commands are deleted from the bottom of the stack. Macro commands (commands with child commands) are treated as one command. The default value is 0, which means that there is no limit. This property may only be set when the undo stack is empty, since setting it on a non-empty stack might delete the command at the current index. Calling setUndoLimit() on a non-empty stack prints a warning and does nothing. */ void KUndo2QStack::setUndoLimit(int limit) { if (!m_command_list.isEmpty()) { qWarning("KUndo2QStack::setUndoLimit(): an undo limit can only be set when the stack is empty"); return; } if (limit == m_undo_limit) return; m_undo_limit = limit; checkUndoLimit(); } int KUndo2QStack::undoLimit() const { return m_undo_limit; } /*! \property KUndo2QStack::active \brief the active status of this stack. An application often has multiple undo stacks, one for each opened document. The active stack is the one associated with the currently active document. If the stack belongs to a KUndo2Group, calls to KUndo2Group::undo() or KUndo2Group::redo() will be forwarded to this stack when it is active. If the KUndo2Group is watched by a KUndo2View, the view will display the contents of this stack when it is active. If the stack does not belong to a KUndo2Group, making it active has no effect. It is the programmer's responsibility to specify which stack is active by calling setActive(), usually when the associated document window receives focus. \sa KUndo2Group */ void KUndo2QStack::setActive(bool active) { #ifdef QT_NO_UNDOGROUP Q_UNUSED(active); #else if (m_group != 0) { if (active) m_group->setActiveStack(this); else if (m_group->activeStack() == this) m_group->setActiveStack(0); } #endif } bool KUndo2QStack::isActive() const { #ifdef QT_NO_UNDOGROUP return true; #else return m_group == 0 || m_group->activeStack() == this; #endif } void KUndo2QStack::setUseCumulativeUndoRedo(bool value) { m_useCumulativeUndoRedo = value; } bool KUndo2QStack::useCumulativeUndoRedo() { return m_useCumulativeUndoRedo; } void KUndo2QStack::setTimeT1(double value) { m_timeT1 = value; } double KUndo2QStack::timeT1() { return m_timeT1; } void KUndo2QStack::setTimeT2(double value) { m_timeT2 = value; } double KUndo2QStack::timeT2() { return m_timeT2; } int KUndo2QStack::strokesN() { return m_strokesN; } void KUndo2QStack::setStrokesN(int value) { m_strokesN = value; } QAction* KUndo2Stack::createRedoAction(KActionCollection* actionCollection, const QString& actionName) { QAction* action = KUndo2QStack::createRedoAction(actionCollection); if (actionName.isEmpty()) { action->setObjectName(KStandardAction::name(KStandardAction::Redo)); } else { action->setObjectName(actionName); } action->setIcon(koIcon("edit-redo")); action->setIconText(i18n("Redo")); action->setShortcuts(KStandardShortcut::redo()); actionCollection->addAction(action->objectName(), action); return action; } QAction* KUndo2Stack::createUndoAction(KActionCollection* actionCollection, const QString& actionName) { QAction* action = KUndo2QStack::createUndoAction(actionCollection); if (actionName.isEmpty()) { action->setObjectName(KStandardAction::name(KStandardAction::Undo)); } else { action->setObjectName(actionName); } action->setIcon(koIcon("edit-undo")); action->setIconText(i18n("Undo")); action->setShortcuts(KStandardShortcut::undo()); actionCollection->addAction(action->objectName(), action); return action; } /*! \fn void KUndo2QStack::indexChanged(int idx) This signal is emitted whenever a command modifies the state of the document. This happens when a command is undone or redone. When a macro command is undone or redone, or setIndex() is called, this signal is emitted only once. \a idx specifies the index of the current command, ie. the command which will be executed on the next call to redo(). \sa index() setIndex() */ /*! \fn void KUndo2QStack::cleanChanged(bool clean) This signal is emitted whenever the stack enters or leaves the clean state. If \a clean is true, the stack is in a clean state; otherwise this signal indicates that it has left the clean state. \sa isClean() setClean() */ /*! \fn void KUndo2QStack::undoTextChanged(const QString &undoText) This signal is emitted whenever the value of undoText() changes. It is used to update the text property of the undo action returned by createUndoAction(). \a undoText specifies the new text. */ /*! \fn void KUndo2QStack::canUndoChanged(bool canUndo) This signal is emitted whenever the value of canUndo() changes. It is used to enable or disable the undo action returned by createUndoAction(). \a canUndo specifies the new value. */ /*! \fn void KUndo2QStack::redoTextChanged(const QString &redoText) This signal is emitted whenever the value of redoText() changes. It is used to update the text property of the redo action returned by createRedoAction(). \a redoText specifies the new text. */ /*! \fn void KUndo2QStack::canRedoChanged(bool canRedo) This signal is emitted whenever the value of canRedo() changes. It is used to enable or disable the redo action returned by createRedoAction(). \a canRedo specifies the new value. */ KUndo2Stack::KUndo2Stack(QObject *parent): KUndo2QStack(parent) { } #endif // QT_NO_UNDOSTACK diff --git a/libs/kundo2/kundo2stack.h b/libs/kundo2/kundo2stack.h index 47186cfde9..c8e6a84014 100644 --- a/libs/kundo2/kundo2stack.h +++ b/libs/kundo2/kundo2stack.h @@ -1,257 +1,255 @@ /* * Copyright (c) 2014 Dmitry Kazakov * Copyright (c) 2014 Mohit Goyal * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef KUNDO2STACK_H #define KUNDO2STACK_H #include #include #include #include #include #include #include "kundo2_export.h" class QAction; class KUndo2CommandPrivate; class KUndo2Group; class KActionCollection; #ifndef QT_NO_UNDOCOMMAND #include "kundo2magicstring.h" +#include "kundo2commandextradata.h" + class KUNDO2_EXPORT KUndo2Command { KUndo2CommandPrivate *d; int timedID; public: explicit KUndo2Command(KUndo2Command *parent = 0); explicit KUndo2Command(const KUndo2MagicString &text, KUndo2Command *parent = 0); virtual ~KUndo2Command(); virtual void undo(); virtual void redo(); QString actionText() const; KUndo2MagicString text() const; void setText(const KUndo2MagicString &text); virtual int id() const; virtual int timedId(); virtual void setTimedID(int timedID); virtual bool mergeWith(const KUndo2Command *other); virtual bool timedMergeWith(KUndo2Command *other); int childCount() const; const KUndo2Command *child(int index) const; bool hasParent(); virtual void setTime(); virtual QTime time(); virtual void setEndTime(); virtual QTime endTime(); virtual QVector mergeCommandsVector(); virtual bool isMerged(); virtual void undoMergedCommands(); virtual void redoMergedCommands(); - struct ExtraData { - virtual ~ExtraData(); - }; - /** * \return user-defined object associated with the command * * \see setExtraData() */ - ExtraData* extraData() const; + KUndo2CommandExtraData* extraData() const; /** * The user can assign an arbitrary object associated with the * command. The \p data object is owned by the command. If you assign * the object twice, the first one will be destroyed. */ - void setExtraData(ExtraData *data); + void setExtraData(KUndo2CommandExtraData *data); private: Q_DISABLE_COPY(KUndo2Command) friend class KUndo2QStack; bool m_hasParent; int m_timedID; QTime m_timeOfCreation; QTime m_endOfCommand; QVector m_mergeCommandsVector; }; #endif // QT_NO_UNDOCOMMAND #ifndef QT_NO_UNDOSTACK class KUNDO2_EXPORT KUndo2QStack : public QObject { Q_OBJECT // Q_DECLARE_PRIVATE(KUndo2QStack) Q_PROPERTY(bool active READ isActive WRITE setActive) Q_PROPERTY(int undoLimit READ undoLimit WRITE setUndoLimit) public: explicit KUndo2QStack(QObject *parent = 0); virtual ~KUndo2QStack(); void clear(); void push(KUndo2Command *cmd); bool canUndo() const; bool canRedo() const; QString undoText() const; QString redoText() const; int count() const; int index() const; QString actionText(int idx) const; QString text(int idx) const; #ifndef QT_NO_ACTION QAction *createUndoAction(QObject *parent) const; QAction *createRedoAction(QObject *parent) const; #endif // QT_NO_ACTION bool isActive() const; bool isClean() const; int cleanIndex() const; void beginMacro(const KUndo2MagicString &text); void endMacro(); void setUndoLimit(int limit); int undoLimit() const; const KUndo2Command *command(int index) const; void setUseCumulativeUndoRedo(bool value); bool useCumulativeUndoRedo(); void setTimeT1(double value); double timeT1(); void setTimeT2(double value); double timeT2(); int strokesN(); void setStrokesN(int value); public Q_SLOTS: void setClean(); virtual void setIndex(int idx); virtual void undo(); virtual void redo(); void setActive(bool active = true); void purgeRedoState(); Q_SIGNALS: void indexChanged(int idx); void cleanChanged(bool clean); void canUndoChanged(bool canUndo); void canRedoChanged(bool canRedo); void undoTextChanged(const QString &undoActionText); void redoTextChanged(const QString &redoActionText); private: // from QUndoStackPrivate QList m_command_list; QList m_macro_stack; int m_index; int m_clean_index; KUndo2Group *m_group; int m_undo_limit; bool m_useCumulativeUndoRedo; double m_timeT1; double m_timeT2; int m_strokesN; int m_lastMergedSetCount; int m_lastMergedIndex; // also from QUndoStackPrivate void setIndex(int idx, bool clean); bool checkUndoLimit(); Q_DISABLE_COPY(KUndo2QStack) friend class KUndo2Group; }; class KUNDO2_EXPORT KUndo2Stack : public KUndo2QStack { public: explicit KUndo2Stack(QObject *parent = 0); // functions from KUndoStack QAction* createRedoAction(KActionCollection* actionCollection, const QString& actionName = QString()); QAction* createUndoAction(KActionCollection* actionCollection, const QString& actionName = QString()); }; #endif // QT_NO_UNDOSTACK #endif // KUNDO2STACK_H diff --git a/libs/kundo2/kundo2stack_p.h b/libs/kundo2/kundo2stack_p.h index 56382a9617..bc122fd612 100644 --- a/libs/kundo2/kundo2stack_p.h +++ b/libs/kundo2/kundo2stack_p.h @@ -1,93 +1,93 @@ /**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef KUNDO2STACK_P_H #define KUNDO2STACK_P_H #include #include #include #include "kundo2stack.h" class KUndo2Command; // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp. This header // file may change from version to version without notice, or even be removed. // // We mean it. // class KUndo2CommandPrivate { public: KUndo2CommandPrivate() : id(-1) {} QList child_list; QString actionText; KUndo2MagicString text; int id; - QScopedPointer extraData; + QScopedPointer extraData; }; #ifndef QT_NO_UNDOSTACK #ifndef QT_NO_ACTION class KUndo2Action : public QAction { Q_OBJECT public: KUndo2Action(const QString &textTemplate, const QString &defaultText, QObject *parent = 0); public Q_SLOTS: void setPrefixedText(const QString &text); private: QString m_textTemplate; QString m_defaultText; }; #endif // QT_NO_ACTION #endif // QT_NO_UNDOSTACK #endif // KUNDO2STACK_P_H