clang-format all files

This commit is contained in:
David Capello 2024-12-16 10:10:34 -03:00
parent 4b3ff3369e
commit b2e4f78b69
1511 changed files with 55829 additions and 61507 deletions

2
laf

@ -1 +1 @@
Subproject commit 10d96af44f5d64af3fb277f48fdc0dd8cc950ac6 Subproject commit c84b89b4826b64b05a176eb15725ba526495c6a1

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/active_site_handler.h" #include "app/active_site_handler.h"
@ -74,7 +74,7 @@ void ActiveSiteHandler::getActiveSiteForDoc(Doc* doc, Site* site)
void ActiveSiteHandler::setActiveLayerInDoc(Doc* doc, doc::Layer* layer) void ActiveSiteHandler::setActiveLayerInDoc(Doc* doc, doc::Layer* layer)
{ {
Data& data = getData(doc); Data& data = getData(doc);
data.layer = (layer ? layer->id(): 0); data.layer = (layer ? layer->id() : 0);
} }
void ActiveSiteHandler::setActiveFrameInDoc(Doc* doc, doc::frame_t frame) void ActiveSiteHandler::setActiveFrameInDoc(Doc* doc, doc::frame_t frame)
@ -133,8 +133,7 @@ void ActiveSiteHandler::onAddFrame(DocEvent& ev)
void ActiveSiteHandler::onBeforeRemoveLayer(DocEvent& ev) void ActiveSiteHandler::onBeforeRemoveLayer(DocEvent& ev)
{ {
Data& data = getData(ev.document()); Data& data = getData(ev.document());
doc::Layer* selectedLayer = (data.layer != doc::NullId ? doc::Layer* selectedLayer = (data.layer != doc::NullId ? doc::get<doc::Layer>(data.layer) :
doc::get<doc::Layer>(data.layer):
nullptr); nullptr);
if (!selectedLayer) if (!selectedLayer)
return; return;
@ -145,8 +144,7 @@ void ActiveSiteHandler::onBeforeRemoveLayer(DocEvent& ev)
// Select other layer as active // Select other layer as active
doc::Layer* layerToSelect = candidate_if_layer_is_deleted(selectedLayer, ev.layer()); doc::Layer* layerToSelect = candidate_if_layer_is_deleted(selectedLayer, ev.layer());
if (selectedLayer != layerToSelect) { if (selectedLayer != layerToSelect) {
data.layer = (layerToSelect ? layerToSelect->id(): data.layer = (layerToSelect ? layerToSelect->id() : doc::NullId);
doc::NullId);
} }
} }

View File

@ -17,20 +17,20 @@
#include <map> #include <map>
namespace doc { namespace doc {
class Layer; class Layer;
} }
namespace app { namespace app {
class Doc; class Doc;
class Site; class Site;
// Pseudo-DocViews to handle active layer/frame in a non-UI context // Pseudo-DocViews to handle active layer/frame in a non-UI context
// per Doc. // per Doc.
// //
// TODO we could move code to handle active frame/layer from // TODO we could move code to handle active frame/layer from
// Timeline to this class. // Timeline to this class.
class ActiveSiteHandler : public DocObserver { class ActiveSiteHandler : public DocObserver {
public: public:
ActiveSiteHandler(); ActiveSiteHandler();
virtual ~ActiveSiteHandler(); virtual ~ActiveSiteHandler();
@ -43,7 +43,7 @@ namespace app {
void setSelectedColorsInDoc(Doc* doc, const doc::PalettePicks& picks); void setSelectedColorsInDoc(Doc* doc, const doc::PalettePicks& picks);
void setSelectedTilesInDoc(Doc* doc, const doc::PalettePicks& picks); void setSelectedTilesInDoc(Doc* doc, const doc::PalettePicks& picks);
private: private:
// DocObserver impl // DocObserver impl
void onAddLayer(DocEvent& ev) override; void onAddLayer(DocEvent& ev) override;
void onAddFrame(DocEvent& ev) override; void onAddFrame(DocEvent& ev) override;
@ -62,7 +62,7 @@ namespace app {
Data& getData(Doc* doc); Data& getData(Doc* doc);
std::map<Doc*, Data> m_data; std::map<Doc*, Data> m_data;
}; };
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/app.h" #include "app/app.h"
@ -103,13 +103,10 @@ namespace {
class ConsoleEngineDelegate : public script::EngineDelegate { class ConsoleEngineDelegate : public script::EngineDelegate {
public: public:
ConsoleEngineDelegate(Console& console) : m_console(console) { } ConsoleEngineDelegate(Console& console) : m_console(console) {}
void onConsoleError(const char* text) override { void onConsoleError(const char* text) override { onConsolePrint(text); }
onConsolePrint(text); void onConsolePrint(const char* text) override { m_console.printf("%s\n", text); }
}
void onConsolePrint(const char* text) override {
m_console.printf("%s\n", text);
}
private: private:
Console& m_console; Console& m_console;
}; };
@ -126,10 +123,7 @@ public:
class App::LoadLanguage { class App::LoadLanguage {
public: public:
LoadLanguage(Preferences& pref, LoadLanguage(Preferences& pref, Extensions& exts) { Strings::createInstance(pref, exts); }
Extensions& exts) {
Strings::createInstance(pref, exts);
}
}; };
class App::Modules { class App::Modules {
@ -152,8 +146,7 @@ public:
std::unique_ptr<app::crash::DataRecovery> m_recovery; std::unique_ptr<app::crash::DataRecovery> m_recovery;
#endif #endif
Modules(const bool createLogInDesktop, Modules(const bool createLogInDesktop, Preferences& pref)
Preferences& pref)
: m_loggerModule(createLogInDesktop) : m_loggerModule(createLogInDesktop)
, m_loadLanguage(pref, m_extensions) , m_loadLanguage(pref, m_extensions)
, m_activeToolManager(&m_toolbox) , m_activeToolManager(&m_toolbox)
@ -164,14 +157,15 @@ public:
{ {
} }
~Modules() { ~Modules()
{
#ifdef ENABLE_DATA_RECOVERY #ifdef ENABLE_DATA_RECOVERY
ASSERT(m_recovery == nullptr || ASSERT(m_recovery == nullptr || ui::get_app_state() == ui::AppState::kClosingWithException);
ui::get_app_state() == ui::AppState::kClosingWithException);
#endif #endif
} }
app::crash::DataRecovery* recovery() { app::crash::DataRecovery* recovery()
{
#ifdef ENABLE_DATA_RECOVERY #ifdef ENABLE_DATA_RECOVERY
return m_recovery.get(); return m_recovery.get();
#else #else
@ -179,18 +173,19 @@ public:
#endif #endif
} }
void createDataRecovery(Context* ctx) { void createDataRecovery(Context* ctx)
{
#ifdef ENABLE_DATA_RECOVERY #ifdef ENABLE_DATA_RECOVERY
#ifdef ENABLE_TRIAL_MODE #ifdef ENABLE_TRIAL_MODE
DRM_INVALID{ DRM_INVALID
{
return; return;
} }
#endif #endif
m_recovery = std::make_unique<app::crash::DataRecovery>(ctx); m_recovery = std::make_unique<app::crash::DataRecovery>(ctx);
m_recovery->SessionsListIsReady.connect( m_recovery->SessionsListIsReady.connect([] {
[] {
ui::assert_ui_thread(); ui::assert_ui_thread();
auto app = App::instance(); auto app = App::instance();
if (app && app->mainWindow()) { if (app && app->mainWindow()) {
@ -201,14 +196,16 @@ public:
#endif #endif
} }
void searchDataRecoverySessions() { void searchDataRecoverySessions()
{
#ifdef ENABLE_DATA_RECOVERY #ifdef ENABLE_DATA_RECOVERY
#ifdef ENABLE_TRIAL_MODE #ifdef ENABLE_TRIAL_MODE
DRM_INVALID{ DRM_INVALID
{
return; return;
} }
#endif #endif
ASSERT(m_recovery); ASSERT(m_recovery);
if (m_recovery) if (m_recovery)
@ -216,19 +213,20 @@ public:
#endif #endif
} }
void deleteDataRecovery() { void deleteDataRecovery()
{
#ifdef ENABLE_DATA_RECOVERY #ifdef ENABLE_DATA_RECOVERY
#ifdef ENABLE_TRIAL_MODE #ifdef ENABLE_TRIAL_MODE
DRM_INVALID{ DRM_INVALID
{
return; return;
} }
#endif #endif
m_recovery.reset(); m_recovery.reset();
#endif #endif
} }
}; };
App* App::m_instance = nullptr; App* App::m_instance = nullptr;
@ -273,8 +271,7 @@ int App::initialize(const AppOptions& options)
#if LAF_WINDOWS #if LAF_WINDOWS
if (options.disableWintab() || if (options.disableWintab() || !pref.experimental.loadWintabDriver() ||
!pref.experimental.loadWintabDriver() ||
pref.tablet.api() == "pointer") { pref.tablet.api() == "pointer") {
tabletOptions.api = os::TabletAPI::WindowsPointerInput; tabletOptions.api = os::TabletAPI::WindowsPointerInput;
} }
@ -299,20 +296,15 @@ int App::initialize(const AppOptions& options)
system->setTabletOptions(tabletOptions); system->setTabletOptions(tabletOptions);
system->setAppName(get_app_name()); system->setAppName(get_app_name());
system->setAppMode(m_isGui ? os::AppMode::GUI: system->setAppMode(m_isGui ? os::AppMode::GUI : os::AppMode::CLI);
os::AppMode::CLI);
if (m_isGui) if (m_isGui)
m_uiSystem.reset(new ui::UISystem); m_uiSystem.reset(new ui::UISystem);
bool createLogInDesktop = false; bool createLogInDesktop = false;
switch (options.verboseLevel()) { switch (options.verboseLevel()) {
case AppOptions::kNoVerbose: case AppOptions::kNoVerbose: base::set_log_level(ERROR); break;
base::set_log_level(ERROR); case AppOptions::kVerbose: base::set_log_level(INFO); break;
break;
case AppOptions::kVerbose:
base::set_log_level(INFO);
break;
case AppOptions::kHighlyVerbose: case AppOptions::kHighlyVerbose:
base::set_log_level(VERBOSE); base::set_log_level(VERBOSE);
createLogInDesktop = true; createLogInDesktop = true;
@ -333,7 +325,7 @@ int App::initialize(const AppOptions& options)
// Load modules // Load modules
m_modules = std::make_unique<Modules>(createLogInDesktop, pref); m_modules = std::make_unique<Modules>(createLogInDesktop, pref);
m_legacy = std::make_unique<LegacyModules>(isGui() ? REQUIRE_INTERFACE: 0); m_legacy = std::make_unique<LegacyModules>(isGui() ? REQUIRE_INTERFACE : 0);
m_brushes = std::make_unique<AppBrushes>(); m_brushes = std::make_unique<AppBrushes>();
// Data recovery is enabled only in GUI mode // Data recovery is enabled only in GUI mode
@ -425,17 +417,18 @@ int App::initialize(const AppOptions& options)
namespace { namespace {
struct CloseMainWindow { struct CloseMainWindow {
std::unique_ptr<MainWindow>& m_win; std::unique_ptr<MainWindow>& m_win;
CloseMainWindow(std::unique_ptr<MainWindow>& win) : m_win(win) { } CloseMainWindow(std::unique_ptr<MainWindow>& win) : m_win(win) {}
~CloseMainWindow() { m_win.reset(nullptr); } ~CloseMainWindow() { m_win.reset(nullptr); }
}; };
// Deletes all docs. // Deletes all docs.
struct DeleteAllDocs { struct DeleteAllDocs {
Context* m_ctx; Context* m_ctx;
DeleteAllDocs(Context* ctx) : m_ctx(ctx) { } DeleteAllDocs(Context* ctx) : m_ctx(ctx) {}
~DeleteAllDocs() { ~DeleteAllDocs()
{
std::vector<Doc*> docs; std::vector<Doc*> docs;
// Add all documents that were closed in the past, these docs // Add all documents that were closed in the past, these docs
@ -465,7 +458,7 @@ namespace {
delete doc; delete doc;
} }
} }
}; };
} // anonymous namespace } // anonymous namespace
@ -479,8 +472,7 @@ void App::run()
auto manager = ui::Manager::getDefault(); auto manager = ui::Manager::getDefault();
#if LAF_WINDOWS #if LAF_WINDOWS
// How to interpret one finger on Windows tablets. // How to interpret one finger on Windows tablets.
manager->display()->nativeWindow() manager->display()->nativeWindow()->setInterpretOneFingerGestureAsMouseMovement(
->setInterpretOneFingerGestureAsMouseMovement(
preferences().experimental.oneFingerAsMouseMovement()); preferences().experimental.oneFingerAsMouseMovement());
#endif #endif
@ -535,8 +527,7 @@ void App::run()
#ifdef ENABLE_UPDATER #ifdef ENABLE_UPDATER
// Launch the thread to check for updates. // Launch the thread to check for updates.
app::CheckUpdateThreadLauncher checkUpdate( app::CheckUpdateThreadLauncher checkUpdate(m_mainWindow->getCheckUpdateDelegate());
m_mainWindow->getCheckUpdateDelegate());
checkUpdate.launch(); checkUpdate.launch();
#endif #endif
@ -672,10 +663,8 @@ bool App::isPortable()
{ {
static std::optional<bool> is_portable; static std::optional<bool> is_portable;
if (!is_portable) { if (!is_portable) {
is_portable = is_portable = base::is_file(
base::is_file(base::join_path( base::join_path(base::get_file_path(base::get_app_path()), "aseprite.ini"));
base::get_file_path(base::get_app_path()),
"aseprite.ini"));
} }
return *is_portable; return *is_portable;
} }
@ -870,14 +859,20 @@ int app_get_color_to_clear_layer(Layer* layer)
} }
#ifdef ENABLE_DRM #ifdef ENABLE_DRM
void app_configure_drm() { void app_configure_drm()
{
ResourceFinder userDirRf, dataDirRf; ResourceFinder userDirRf, dataDirRf;
userDirRf.includeUserDir(""); userDirRf.includeUserDir("");
dataDirRf.includeDataDir(""); dataDirRf.includeDataDir("");
std::map<std::string, std::string> config = { std::map<std::string, std::string> config = {
{"data", dataDirRf.getFirstOrCreateDefault()} { "data", dataDirRf.getFirstOrCreateDefault() }
}; };
DRM_CONFIGURE(get_app_url(), get_app_name(), get_app_version(), userDirRf.getFirstOrCreateDefault(), updater::getUserAgent(), config); DRM_CONFIGURE(get_app_url(),
get_app_name(),
get_app_version(),
userDirRf.getFirstOrCreateDefault(),
updater::getUserAgent(),
config);
} }
#endif #endif

View File

@ -19,52 +19,52 @@
#include <vector> #include <vector>
namespace doc { namespace doc {
class Layer; class Layer;
} }
namespace ui { namespace ui {
class UISystem; class UISystem;
} }
namespace app { namespace app {
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
namespace script { namespace script {
class Engine; class Engine;
} }
#endif #endif
class AppMod; class AppMod;
class AppOptions; class AppOptions;
class BackupIndicator; class BackupIndicator;
class Context; class Context;
class ContextBar; class ContextBar;
class Doc; class Doc;
class Extensions; class Extensions;
class INotificationDelegate; class INotificationDelegate;
class InputChain; class InputChain;
class LegacyModules; class LegacyModules;
class LoggerModule; class LoggerModule;
class MainWindow; class MainWindow;
class Preferences; class Preferences;
class RecentFiles; class RecentFiles;
class Timeline; class Timeline;
class Workspace; class Workspace;
namespace crash { namespace crash {
class DataRecovery; class DataRecovery;
} }
namespace tools { namespace tools {
class ActiveToolManager; class ActiveToolManager;
class Tool; class Tool;
class ToolBox; class ToolBox;
} } // namespace tools
using namespace doc; using namespace doc;
class App { class App {
public: public:
App(AppMod* mod = nullptr); App(AppMod* mod = nullptr);
~App(); ~App();
@ -98,7 +98,8 @@ namespace app {
Extensions& extensions() const; Extensions& extensions() const;
crash::DataRecovery* dataRecovery() const; crash::DataRecovery* dataRecovery() const;
AppBrushes& brushes() { AppBrushes& brushes()
{
ASSERT(m_brushes.get()); ASSERT(m_brushes.get());
return *m_brushes; return *m_brushes;
} }
@ -123,7 +124,7 @@ namespace app {
obs::signal<void()> ColorSpaceChange; obs::signal<void()> ColorSpaceChange;
obs::signal<void()> PalettePresetsChange; obs::signal<void()> PalettePresetsChange;
private: private:
class CoreModules; class CoreModules;
class LoadLanguage; class LoadLanguage;
class Modules; class Modules;
@ -151,13 +152,13 @@ namespace app {
// Set the memory dump filename to show in the Preferences dialog // Set the memory dump filename to show in the Preferences dialog
// or the "send crash" dialog. It's set by the SendCrash class. // or the "send crash" dialog. It's set by the SendCrash class.
std::string m_memoryDumpFilename; std::string m_memoryDumpFilename;
}; };
void app_refresh_screen(); void app_refresh_screen();
void app_rebuild_documents_tabs(); void app_rebuild_documents_tabs();
PixelFormat app_get_current_pixel_format(); PixelFormat app_get_current_pixel_format();
int app_get_color_to_clear_layer(doc::Layer* layer); int app_get_color_to_clear_layer(doc::Layer* layer);
void app_configure_drm(); void app_configure_drm();
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/app_brushes.h" #include "app/app_brushes.h"
@ -41,9 +41,8 @@ ImageRef load_xml_image(const XMLElement* imageElem)
ImageRef image; ImageRef image;
int w, h; int w, h;
if (imageElem->QueryIntAttribute("width", &w) != XML_SUCCESS || if (imageElem->QueryIntAttribute("width", &w) != XML_SUCCESS ||
imageElem->QueryIntAttribute("height", &h) != XML_SUCCESS || imageElem->QueryIntAttribute("height", &h) != XML_SUCCESS || w < 0 || w > 9999 || h < 0 ||
w < 0 || w > 9999 || h > 9999)
h < 0 || h > 9999)
return image; return image;
auto formatValue = imageElem->Attribute("format"); auto formatValue = imageElem->Attribute("format");
@ -66,10 +65,14 @@ ImageRef load_xml_image(const XMLElement* imageElem)
if ((end - it) < 4) if ((end - it) < 4)
break; break;
int r = *it; ++it; int r = *it;
int g = *it; ++it; ++it;
int b = *it; ++it; int g = *it;
int a = *it; ++it; ++it;
int b = *it;
++it;
int a = *it;
++it;
pixel = doc::rgba(r, g, b, a); pixel = doc::rgba(r, g, b, a);
} }
@ -81,8 +84,10 @@ ImageRef load_xml_image(const XMLElement* imageElem)
if ((end - it) < 2) if ((end - it) < 2)
break; break;
int v = *it; ++it; int v = *it;
int a = *it; ++it; ++it;
int a = *it;
++it;
pixel = doc::graya(v, a); pixel = doc::graya(v, a);
} }
@ -133,7 +138,7 @@ void save_xml_image(XMLElement* imageElem, const Image* image)
base::buffer data; base::buffer data;
data.reserve(h * image->widthBytes()); data.reserve(h * image->widthBytes());
switch (image->pixelFormat()) { switch (image->pixelFormat()) {
case IMAGE_RGB:{ case IMAGE_RGB: {
const LockImageBits<RgbTraits> pixels(image); const LockImageBits<RgbTraits> pixels(image);
for (const auto& pixel : pixels) { for (const auto& pixel : pixels) {
data.push_back(doc::rgba_getr(pixel)); data.push_back(doc::rgba_getr(pixel));
@ -143,7 +148,7 @@ void save_xml_image(XMLElement* imageElem, const Image* image)
} }
break; break;
} }
case IMAGE_GRAYSCALE:{ case IMAGE_GRAYSCALE: {
const LockImageBits<GrayscaleTraits> pixels(image); const LockImageBits<GrayscaleTraits> pixels(image);
for (const auto& pixel : pixels) { for (const auto& pixel : pixels) {
data.push_back(doc::graya_getv(pixel)); data.push_back(doc::graya_getv(pixel));
@ -187,8 +192,7 @@ AppBrushes::AppBrushes()
load(fn); load(fn);
} }
catch (const std::exception& ex) { catch (const std::exception& ex) {
LOG(ERROR, "BRSH: Error loading user brushes from '%s': %s\n", LOG(ERROR, "BRSH: Error loading user brushes from '%s': %s\n", fn.c_str(), ex.what());
fn.c_str(), ex.what());
} }
} }
m_userBrushesFilename = fn; m_userBrushesFilename = fn;
@ -202,8 +206,10 @@ AppBrushes::~AppBrushes()
} }
// We cannot throw exceptions from a destructor // We cannot throw exceptions from a destructor
catch (const std::exception& ex) { catch (const std::exception& ex) {
LOG(ERROR, "BRSH: Error saving user brushes to '%s': %s\n", LOG(ERROR,
m_userBrushesFilename.c_str(), ex.what()); "BRSH: Error saving user brushes to '%s': %s\n",
m_userBrushesFilename.c_str(),
ex.what());
} }
} }
} }
@ -211,10 +217,10 @@ AppBrushes::~AppBrushes()
AppBrushes::slot_id AppBrushes::addBrushSlot(const BrushSlot& brush) AppBrushes::slot_id AppBrushes::addBrushSlot(const BrushSlot& brush)
{ {
// Use an empty slot // Use an empty slot
for (size_t i=0; i<m_slots.size(); ++i) { for (size_t i = 0; i < m_slots.size(); ++i) {
if (!m_slots[i].locked() || m_slots[i].isEmpty()) { if (!m_slots[i].locked() || m_slots[i].isEmpty()) {
m_slots[i] = brush; m_slots[i] = brush;
return i+1; return i + 1;
} }
} }
@ -230,8 +236,7 @@ void AppBrushes::removeBrushSlot(slot_id slot)
m_slots[slot] = BrushSlot(); m_slots[slot] = BrushSlot();
// Erase empty trailing slots // Erase empty trailing slots
while (!m_slots.empty() && while (!m_slots.empty() && m_slots[m_slots.size() - 1].isEmpty())
m_slots[m_slots.size()-1].isEmpty())
m_slots.erase(--m_slots.end()); m_slots.erase(--m_slots.end());
ItemsChange(); ItemsChange();
@ -249,8 +254,7 @@ void AppBrushes::removeAllBrushSlots()
bool AppBrushes::hasBrushSlot(slot_id slot) const bool AppBrushes::hasBrushSlot(slot_id slot) const
{ {
--slot; --slot;
return (slot >= 0 && slot < (int)m_slots.size() && return (slot >= 0 && slot < (int)m_slots.size() && !m_slots[slot].isEmpty());
!m_slots[slot].isEmpty());
} }
BrushSlot AppBrushes::getBrushSlot(slot_id slot) const BrushSlot AppBrushes::getBrushSlot(slot_id slot) const
@ -274,8 +278,7 @@ void AppBrushes::setBrushSlot(slot_id slot, const BrushSlot& brush)
void AppBrushes::lockBrushSlot(slot_id slot) void AppBrushes::lockBrushSlot(slot_id slot)
{ {
--slot; --slot;
if (slot >= 0 && slot < (int)m_slots.size() && if (slot >= 0 && slot < (int)m_slots.size() && !m_slots[slot].isEmpty()) {
!m_slots[slot].isEmpty()) {
m_slots[slot].setLocked(true); m_slots[slot].setLocked(true);
} }
} }
@ -283,8 +286,7 @@ void AppBrushes::lockBrushSlot(slot_id slot)
void AppBrushes::unlockBrushSlot(slot_id slot) void AppBrushes::unlockBrushSlot(slot_id slot)
{ {
--slot; --slot;
if (slot >= 0 && slot < (int)m_slots.size() && if (slot >= 0 && slot < (int)m_slots.size() && !m_slots[slot].isEmpty()) {
!m_slots[slot].isEmpty()) {
m_slots[slot].setLocked(false); m_slots[slot].setLocked(false);
} }
} }
@ -292,26 +294,22 @@ void AppBrushes::unlockBrushSlot(slot_id slot)
bool AppBrushes::isBrushSlotLocked(slot_id slot) const bool AppBrushes::isBrushSlotLocked(slot_id slot) const
{ {
--slot; --slot;
if (slot >= 0 && slot < (int)m_slots.size() && if (slot >= 0 && slot < (int)m_slots.size() && !m_slots[slot].isEmpty()) {
!m_slots[slot].isEmpty()) {
return m_slots[slot].locked(); return m_slots[slot].locked();
} }
else else
return false; return false;
} }
static const int kBrushFlags = static const int kBrushFlags = int(BrushSlot::Flags::BrushType) | int(BrushSlot::Flags::BrushSize) |
int(BrushSlot::Flags::BrushType) |
int(BrushSlot::Flags::BrushSize) |
int(BrushSlot::Flags::BrushAngle); int(BrushSlot::Flags::BrushAngle);
void AppBrushes::load(const std::string& filename) void AppBrushes::load(const std::string& filename)
{ {
XMLDocumentRef doc = app::open_xml(filename); XMLDocumentRef doc = app::open_xml(filename);
XMLHandle handle(doc.get()); XMLHandle handle(doc.get());
XMLElement* brushElem = handle XMLElement* brushElem =
.FirstChildElement("brushes") handle.FirstChildElement("brushes").FirstChildElement("brush").ToElement();
.FirstChildElement("brush").ToElement();
while (brushElem) { while (brushElem) {
// flags // flags
@ -329,14 +327,15 @@ void AppBrushes::load(const std::string& filename)
const char* size = brushElem->Attribute("size"); const char* size = brushElem->Attribute("size");
const char* angle = brushElem->Attribute("angle"); const char* angle = brushElem->Attribute("angle");
if (type || size || angle) { if (type || size || angle) {
if (type) flags |= int(BrushSlot::Flags::BrushType); if (type)
if (size) flags |= int(BrushSlot::Flags::BrushSize); flags |= int(BrushSlot::Flags::BrushType);
if (angle) flags |= int(BrushSlot::Flags::BrushAngle); if (size)
brush.reset( flags |= int(BrushSlot::Flags::BrushSize);
new Brush( if (angle)
(type ? string_id_to_brush_type(type): kFirstBrushType), flags |= int(BrushSlot::Flags::BrushAngle);
(size ? base::convert_to<int>(std::string(size)): 1), brush.reset(new Brush((type ? string_id_to_brush_type(type) : kFirstBrushType),
(angle ? base::convert_to<int>(std::string(angle)): 0))); (size ? base::convert_to<int>(std::string(size)) : 1),
(angle ? base::convert_to<int>(std::string(angle)) : 0)));
} }
// Brush image // Brush image
@ -397,16 +396,19 @@ void AppBrushes::load(const std::string& filename)
} }
// Image color (enabled by default for backward compatibility) // Image color (enabled by default for backward compatibility)
if (!brushElem->Attribute("imagecolor") || if (!brushElem->Attribute("imagecolor") || bool_attr(brushElem, "imagecolor", false))
bool_attr(brushElem, "imagecolor", false))
flags |= int(BrushSlot::Flags::ImageColor); flags |= int(BrushSlot::Flags::ImageColor);
if (flags != 0) if (flags != 0)
flags |= int(BrushSlot::Flags::Locked); flags |= int(BrushSlot::Flags::Locked);
BrushSlot brushSlot(BrushSlot::Flags(flags), BrushSlot brushSlot(BrushSlot::Flags(flags),
brush, fgColor, bgColor, brush,
inkType, inkOpacity, shade, fgColor,
bgColor,
inkType,
inkOpacity,
shade,
pixelPerfect); pixelPerfect);
m_slots.push_back(brushSlot); m_slots.push_back(brushSlot);
@ -437,8 +439,7 @@ void AppBrushes::save(const std::string& filename) const
ASSERT(slot.brush()); ASSERT(slot.brush());
if (flags & int(BrushSlot::Flags::BrushType)) { if (flags & int(BrushSlot::Flags::BrushType)) {
brushElem->SetAttribute( brushElem->SetAttribute("type", brush_type_to_string_id(slot.brush()->type()).c_str());
"type", brush_type_to_string_id(slot.brush()->type()).c_str());
} }
if (flags & int(BrushSlot::Flags::BrushSize)) { if (flags & int(BrushSlot::Flags::BrushSize)) {
@ -449,8 +450,7 @@ void AppBrushes::save(const std::string& filename) const
brushElem->SetAttribute("angle", slot.brush()->angle()); brushElem->SetAttribute("angle", slot.brush()->angle());
} }
if (slot.brush()->type() == kImageBrushType && if (slot.brush()->type() == kImageBrushType && slot.brush()->originalImage()) {
slot.brush()->originalImage()) {
XMLElement* elem = brushElem->InsertNewChildElement("image"); XMLElement* elem = brushElem->InsertNewChildElement("image");
save_xml_image(elem, slot.brush()->originalImage()); save_xml_image(elem, slot.brush()->originalImage());
@ -460,9 +460,8 @@ void AppBrushes::save(const std::string& filename) const
} }
// Image color // Image color
brushElem->SetAttribute( brushElem->SetAttribute("imagecolor",
"imagecolor", (flags & int(BrushSlot::Flags::ImageColor)) ? "true" : "false");
(flags & int(BrushSlot::Flags::ImageColor)) ? "true": "false");
} }
} }
@ -480,8 +479,7 @@ void AppBrushes::save(const std::string& filename) const
// Ink // Ink
if (flags & int(BrushSlot::Flags::InkType)) { if (flags & int(BrushSlot::Flags::InkType)) {
XMLElement* elem = brushElem->InsertNewChildElement("inktype"); XMLElement* elem = brushElem->InsertNewChildElement("inktype");
elem->SetAttribute( elem->SetAttribute("value", app::tools::ink_type_to_string_id(slot.inkType()).c_str());
"value", app::tools::ink_type_to_string_id(slot.inkType()).c_str());
} }
if (flags & int(BrushSlot::Flags::InkOpacity)) { if (flags & int(BrushSlot::Flags::InkOpacity)) {
@ -498,7 +496,7 @@ void AppBrushes::save(const std::string& filename) const
// Pixel-perfect // Pixel-perfect
if (flags & int(BrushSlot::Flags::PixelPerfect)) { if (flags & int(BrushSlot::Flags::PixelPerfect)) {
XMLElement* elem = brushElem->InsertNewChildElement("pixelperfect"); XMLElement* elem = brushElem->InsertNewChildElement("pixelperfect");
elem->SetAttribute("value", slot.pixelPerfect() ? "true": "false"); elem->SetAttribute("value", slot.pixelPerfect() ? "true" : "false");
} }
} }
} }

View File

@ -18,8 +18,8 @@
namespace app { namespace app {
class AppBrushes { class AppBrushes {
public: public:
// Number of slot (a range from 1 to AppBrushes::size() inclusive) // Number of slot (a range from 1 to AppBrushes::size() inclusive)
typedef int slot_id; typedef int slot_id;
typedef std::vector<BrushSlot> BrushSlots; typedef std::vector<BrushSlot> BrushSlots;
@ -44,7 +44,7 @@ namespace app {
obs::signal<void()> ItemsChange; obs::signal<void()> ItemsChange;
private: private:
void load(const std::string& filename); void load(const std::string& filename);
void save(const std::string& filename) const; void save(const std::string& filename) const;
static std::string userBrushesFilename(); static std::string userBrushesFilename();
@ -52,7 +52,7 @@ namespace app {
doc::Brushes m_standard; doc::Brushes m_standard;
BrushSlots m_slots; BrushSlots m_slots;
std::string m_userBrushesFilename; std::string m_userBrushesFilename;
}; };
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/app_menus.h" #include "app/app_menus.h"
@ -37,11 +37,11 @@
#include "tinyxml2.h" #include "tinyxml2.h"
#include <algorithm>
#include <cctype> #include <cctype>
#include <cstdlib>
#include <cstring> #include <cstring>
#include <string> #include <string>
#include <algorithm>
#include <cstdlib>
#define MENUS_TRACE(...) // TRACEARGS #define MENUS_TRACE(...) // TRACEARGS
@ -80,22 +80,12 @@ bool is_text_entry_shortcut(const os::Shortcut& shortcut)
const int lchr = std::tolower(chr); const int lchr = std::tolower(chr);
bool result = bool result =
((mod == os::KeyModifiers::kKeyNoneModifier || ((mod == os::KeyModifiers::kKeyNoneModifier || mod == os::KeyModifiers::kKeyShiftModifier) &&
mod == os::KeyModifiers::kKeyShiftModifier) && chr >= 32 && chr < 0xF000) ||
chr >= 32 && chr < 0xF000) ((mod == os::KeyModifiers::kKeyCmdModifier || mod == os::KeyModifiers::kKeyCtrlModifier) &&
|| (lchr == 'a' || lchr == 'c' || lchr == 'v' || lchr == 'x')) ||
((mod == os::KeyModifiers::kKeyCmdModifier || (chr == kUnicodeInsert || chr == kUnicodeDel || chr == kUnicodeHome || chr == kUnicodeEnd ||
mod == os::KeyModifiers::kKeyCtrlModifier) && chr == kUnicodeLeft || chr == kUnicodeRight || chr == kUnicodeEsc || chr == kUnicodeEnter);
(lchr == 'a' || lchr == 'c' || lchr == 'v' || lchr == 'x'))
||
(chr == kUnicodeInsert ||
chr == kUnicodeDel ||
chr == kUnicodeHome ||
chr == kUnicodeEnd ||
chr == kUnicodeLeft ||
chr == kUnicodeRight ||
chr == kUnicodeEsc ||
chr == kUnicodeEnter);
return result; return result;
} }
@ -125,8 +115,7 @@ bool can_call_global_shortcut(const AppMenuItem::Native* native)
// prefer text input, so we cannot call shortcuts without // prefer text input, so we cannot call shortcuts without
// modifiers (e.g. F or T keystrokes) to trigger a global command // modifiers (e.g. F or T keystrokes) to trigger a global command
// in a text field. // in a text field.
(focus == nullptr || (focus == nullptr || focus->type() != ui::kEntryWidget ||
focus->type() != ui::kEntryWidget ||
!is_text_entry_shortcut(native->shortcut)) && !is_text_entry_shortcut(native->shortcut)) &&
(native->keyContext == KeyContext::Any || (native->keyContext == KeyContext::Any ||
native->keyContext == KeyboardShortcuts::instance()->getCurrentKeyContext()); native->keyContext == KeyboardShortcuts::instance()->getCurrentKeyContext());
@ -271,8 +260,7 @@ int from_scancode_to_unicode(KeyScancode scancode)
return 0; return 0;
} }
AppMenuItem::Native get_native_shortcut_for_command( AppMenuItem::Native get_native_shortcut_for_command(const char* commandId,
const char* commandId,
const Params& params = Params()) const Params& params = Params())
{ {
AppMenuItem::Native native; AppMenuItem::Native native;
@ -312,8 +300,7 @@ os::Shortcut get_os_shortcut_from_key(const Key* key)
#endif #endif
return os::Shortcut( return os::Shortcut(
(accel.unicodeChar() ? accel.unicodeChar(): (accel.unicodeChar() ? accel.unicodeChar() : from_scancode_to_unicode(accel.scancode())),
from_scancode_to_unicode(accel.scancode())),
accel.modifiers()); accel.modifiers());
} }
else else
@ -326,18 +313,15 @@ AppMenus* AppMenus::instance()
static AppMenus* instance = NULL; static AppMenus* instance = NULL;
if (!instance) { if (!instance) {
instance = new AppMenus; instance = new AppMenus;
App::instance()->Exit.connect([]{ destroy_instance(instance); }); App::instance()->Exit.connect([] { destroy_instance(instance); });
} }
return instance; return instance;
} }
AppMenus::AppMenus() AppMenus::AppMenus() : m_recentFilesPlaceholder(nullptr), m_osMenu(nullptr)
: m_recentFilesPlaceholder(nullptr)
, m_osMenu(nullptr)
{ {
m_recentFilesConn = m_recentFilesConn = App::instance()->recentFiles()->Changed.connect(
App::instance()->recentFiles()->Changed.connect( [this] { rebuildRecentList(); });
[this]{ rebuildRecentList(); });
} }
void AppMenus::reload() void AppMenus::reload()
@ -386,8 +370,7 @@ void AppMenus::reload()
// Add one menu item to run each script from the user scripts/ folder // Add one menu item to run each script from the user scripts/ folder
{ {
MenuItem* scriptsMenu = dynamic_cast<MenuItem*>( MenuItem* scriptsMenu = dynamic_cast<MenuItem*>(m_rootMenu->findItemById("scripts_menu"));
m_rootMenu->findItemById("scripts_menu"));
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
// Load scripts // Load scripts
ResourceFinder rf; ResourceFinder rf;
@ -455,9 +438,7 @@ void AppMenus::reload()
LOG("MENU: Loading commands keyboard shortcuts from %s\n", path); LOG("MENU: Loading commands keyboard shortcuts from %s\n", path);
XMLElement* xmlKey = handle XMLElement* xmlKey = handle.FirstChildElement("gui").FirstChildElement("keyboard").ToElement();
.FirstChildElement("gui")
.FirstChildElement("keyboard").ToElement();
// From a fresh start, load the default keys // From a fresh start, load the default keys
KeyboardShortcuts::instance()->clear(); KeyboardShortcuts::instance()->clear();
@ -465,11 +446,9 @@ void AppMenus::reload()
// Load extension-defined keys // Load extension-defined keys
for (const Extension* ext : App::instance()->extensions()) { for (const Extension* ext : App::instance()->extensions()) {
if (ext->isEnabled() && if (ext->isEnabled() && ext->hasKeys()) {
ext->hasKeys()) {
for (const auto& kv : ext->keys()) { for (const auto& kv : ext->keys()) {
KeyboardShortcuts::instance()->importFile( KeyboardShortcuts::instance()->importFile(kv.second, KeySource::ExtensionDefined);
kv.second, KeySource::ExtensionDefined);
} }
} }
} }
@ -489,13 +468,10 @@ void AppMenus::reload()
} }
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
void AppMenus::loadScriptsSubmenu(ui::Menu* menu, void AppMenus::loadScriptsSubmenu(ui::Menu* menu, const std::string& dir, const bool rootLevel)
const std::string& dir,
const bool rootLevel)
{ {
auto files = base::list_files(dir); auto files = base::list_files(dir);
std::sort(files.begin(), files.end(), std::sort(files.begin(), files.end(), [](const std::string& a, const std::string& b) {
[](const std::string& a, const std::string& b) {
return base::compare_filenames(a, b) < 0; return base::compare_filenames(a, b) < 0;
}); });
int insertPos = 0; int insertPos = 0;
@ -510,18 +486,15 @@ void AppMenus::loadScriptsSubmenu(ui::Menu* menu,
if (base::string_to_lower(base::get_file_extension(fn)) == "lua") { if (base::string_to_lower(base::get_file_extension(fn)) == "lua") {
Params params; Params params;
params.set("filename", fullFn.c_str()); params.set("filename", fullFn.c_str());
menuitem = new AppMenuItem( menuitem =
base::get_file_title(fn).c_str(), new AppMenuItem(base::get_file_title(fn).c_str(), CommandId::RunScript(), params);
CommandId::RunScript(),
params);
} }
} }
else if (base::is_directory(fullFn)) { else if (base::is_directory(fullFn)) {
Menu* submenu = new Menu(); Menu* submenu = new Menu();
loadScriptsSubmenu(submenu, fullFn, false); loadScriptsSubmenu(submenu, fullFn, false);
menuitem = new AppMenuItem( menuitem = new AppMenuItem(base::get_file_title(fn).c_str());
base::get_file_title(fn).c_str());
menuitem->setSubmenu(submenu); menuitem->setSubmenu(submenu);
} }
if (menuitem) { if (menuitem) {
@ -543,7 +516,8 @@ void AppMenus::initTheme()
bool AppMenus::rebuildRecentList() bool AppMenus::rebuildRecentList()
{ {
MENUS_TRACE("MENUS: AppMenus::rebuildRecentList m_recentFilesPlaceholder=", m_recentFilesPlaceholder); MENUS_TRACE("MENUS: AppMenus::rebuildRecentList m_recentFilesPlaceholder=",
m_recentFilesPlaceholder);
if (!m_recentFilesPlaceholder) if (!m_recentFilesPlaceholder)
return true; return true;
@ -563,21 +537,15 @@ bool AppMenus::rebuildRecentList()
auto recent = App::instance()->recentFiles(); auto recent = App::instance()->recentFiles();
base::paths files; base::paths files;
files.insert(files.end(), files.insert(files.end(), recent->pinnedFiles().begin(), recent->pinnedFiles().end());
recent->pinnedFiles().begin(), files.insert(files.end(), recent->recentFiles().begin(), recent->recentFiles().end());
recent->pinnedFiles().end());
files.insert(files.end(),
recent->recentFiles().begin(),
recent->recentFiles().end());
if (!files.empty()) { if (!files.empty()) {
Params params; Params params;
for (const auto& fn : files) { for (const auto& fn : files) {
params.set("filename", fn.c_str()); params.set("filename", fn.c_str());
std::unique_ptr<AppMenuItem> menuitem( std::unique_ptr<AppMenuItem> menuitem(
new AppMenuItem(base::get_file_name(fn).c_str(), new AppMenuItem(base::get_file_name(fn).c_str(), CommandId::OpenFile(), params));
CommandId::OpenFile(),
params));
menuitem->setIsRecentFileItem(true); menuitem->setIsRecentFileItem(true);
m_recentMenuItems.push_back(menuitem.get()); m_recentMenuItems.push_back(menuitem.get());
@ -586,8 +554,7 @@ bool AppMenus::rebuildRecentList()
} }
else { else {
std::unique_ptr<AppMenuItem> menuitem( std::unique_ptr<AppMenuItem> menuitem(
new AppMenuItem( new AppMenuItem(Strings::main_menu_file_no_recent_file()));
Strings::main_menu_file_no_recent_file()));
menuitem->setIsRecentFileItem(true); menuitem->setIsRecentFileItem(true);
menuitem->setEnabled(false); menuitem->setEnabled(false);
@ -596,10 +563,9 @@ bool AppMenus::rebuildRecentList()
} }
// Sync native menus // Sync native menus
if (owner->native() && if (owner->native() && owner->native()->menuItem) {
owner->native()->menuItem) {
auto menus = os::instance()->menus(); auto menus = os::instance()->menus();
os::MenuRef osMenu = (menus ? menus->makeMenu(): nullptr); os::MenuRef osMenu = (menus ? menus->makeMenu() : nullptr);
if (osMenu) { if (osMenu) {
createNativeSubmenus(osMenu.get(), menu); createNativeSubmenus(osMenu.get(), menu);
owner->native()->menuItem->setSubmenu(osMenu); owner->native()->menuItem->setSubmenu(osMenu);
@ -611,16 +577,14 @@ bool AppMenus::rebuildRecentList()
Menu* AppMenus::getAnimationMenu() Menu* AppMenus::getAnimationMenu()
{ {
auto menuItem = auto menuItem = dynamic_cast<MenuItem*>(m_rootMenu->findItemById("animation_menu"));
dynamic_cast<MenuItem*>(m_rootMenu->findItemById("animation_menu"));
if (menuItem) if (menuItem)
return menuItem->getSubmenu(); return menuItem->getSubmenu();
else else
return nullptr; return nullptr;
} }
void AppMenus::addMenuGroup(const std::string& groupId, void AppMenus::addMenuGroup(const std::string& groupId, MenuItem* menuItem)
MenuItem* menuItem)
{ {
GroupInfo& group = m_groups[groupId]; GroupInfo& group = m_groups[groupId];
ASSERT(group.menu == nullptr); ASSERT(group.menu == nullptr);
@ -639,22 +603,20 @@ void AppMenus::removeMenuGroup(const std::string& groupId)
if (group.menu->getOwnerMenuItem()) { if (group.menu->getOwnerMenuItem()) {
ui::MenuItem* item = group.menu->getOwnerMenuItem(); ui::MenuItem* item = group.menu->getOwnerMenuItem();
removeMenuItemFromGroup( removeMenuItemFromGroup([item](Widget* i) { return item == i; });
[item](Widget* i){
return item == i;
});
} }
m_groups.erase(it); m_groups.erase(it);
} }
} }
void AppMenus::addMenuItemIntoGroup(const std::string& groupId, void AppMenus::addMenuItemIntoGroup(const std::string& groupId, std::unique_ptr<Widget>&& menuItem)
std::unique_ptr<Widget>&& menuItem)
{ {
auto it = m_groups.find(groupId); auto it = m_groups.find(groupId);
if (it == m_groups.end()) { if (it == m_groups.end()) {
LOG(ERROR, "MENU: An extension tried to add a command (%s) in a non-existent group (%s)\n", LOG(ERROR,
menuItem->text().c_str(), groupId.c_str()); "MENU: An extension tried to add a command (%s) in a non-existent group (%s)\n",
menuItem->text().c_str(),
groupId.c_str());
menuItem.release(); menuItem.release();
return; return;
} }
@ -666,7 +628,7 @@ void AppMenus::addMenuItemIntoGroup(const std::string& groupId,
if (group.end) { if (group.end) {
int insertIndex = menu->getChildIndex(group.end); int insertIndex = menu->getChildIndex(group.end);
ASSERT(insertIndex >= 0); ASSERT(insertIndex >= 0);
menu->insertChild(insertIndex+1, menuItem.get()); menu->insertChild(insertIndex + 1, menuItem.get());
} }
else { else {
menu->addChild(menuItem.get()); menu->addChild(menuItem.get());
@ -683,7 +645,7 @@ void AppMenus::removeMenuItemFromGroup(Pred pred)
{ {
for (auto& it : m_groups) { for (auto& it : m_groups) {
GroupInfo& group = it.second; GroupInfo& group = it.second;
for (auto it=group.items.begin(); it != group.items.end(); ) { for (auto it = group.items.begin(); it != group.items.end();) {
auto& item = *it; auto& item = *it;
if (pred(item)) { if (pred(item)) {
if (item == group.end) if (item == group.end)
@ -702,8 +664,7 @@ void AppMenus::removeMenuItemFromGroup(Pred pred)
void AppMenus::removeMenuItemFromGroup(Command* cmd) void AppMenus::removeMenuItemFromGroup(Command* cmd)
{ {
removeMenuItemFromGroup( removeMenuItemFromGroup([cmd](Widget* item) {
[cmd](Widget* item){
auto appMenuItem = dynamic_cast<AppMenuItem*>(item); auto appMenuItem = dynamic_cast<AppMenuItem*>(item);
return (appMenuItem && appMenuItem->getCommand() == cmd); return (appMenuItem && appMenuItem->getCommand() == cmd);
}); });
@ -711,10 +672,7 @@ void AppMenus::removeMenuItemFromGroup(Command* cmd)
void AppMenus::removeMenuItemFromGroup(Widget* menuItem) void AppMenus::removeMenuItemFromGroup(Widget* menuItem)
{ {
removeMenuItemFromGroup( removeMenuItemFromGroup([menuItem](Widget* item) { return (item == menuItem); });
[menuItem](Widget* item){
return (item == menuItem);
});
} }
Menu* AppMenus::loadMenuById(XMLHandle& handle, const char* id) Menu* AppMenus::loadMenuById(XMLHandle& handle, const char* id)
@ -722,10 +680,8 @@ Menu* AppMenus::loadMenuById(XMLHandle& handle, const char* id)
ASSERT(id != NULL); ASSERT(id != NULL);
// <gui><menus><menu> // <gui><menus><menu>
XMLElement* xmlMenu = handle XMLElement* xmlMenu =
.FirstChildElement("gui") handle.FirstChildElement("gui").FirstChildElement("menus").FirstChildElement("menu").ToElement();
.FirstChildElement("menus")
.FirstChildElement("menu").ToElement();
while (xmlMenu) { while (xmlMenu) {
const char* menuId = xmlMenu->Attribute("id"); const char* menuId = xmlMenu->Attribute("id");
@ -785,9 +741,7 @@ Widget* AppMenus::convertXmlelemToMenuitem(XMLElement* elem, Menu* menu)
} }
const char* commandId = elem->Attribute("command"); const char* commandId = elem->Attribute("command");
Command* command = Command* command = (commandId ? Commands::instance()->byId(commandId) : nullptr);
(commandId ? Commands::instance()->byId(commandId):
nullptr);
// load params // load params
Params params; Params params;
@ -805,9 +759,8 @@ Widget* AppMenus::convertXmlelemToMenuitem(XMLElement* elem, Menu* menu)
} }
// Create the item // Create the item
AppMenuItem* menuitem = new AppMenuItem(m_xmlTranslator(elem, "text"), AppMenuItem* menuitem =
(command ? command->id(): ""), new AppMenuItem(m_xmlTranslator(elem, "text"), (command ? command->id() : ""), params);
params);
if (!menuitem) if (!menuitem)
return nullptr; return nullptr;
@ -821,7 +774,8 @@ Widget* AppMenus::convertXmlelemToMenuitem(XMLElement* elem, Menu* menu)
menuitem->processMnemonicFromText(); menuitem->processMnemonicFromText();
} }
if (id) menuitem->setId(id); if (id)
menuitem->setId(id);
if (group) { if (group) {
m_groups[group].menu = menu; m_groups[group].menu = menu;
m_groups[group].end = menuitem; m_groups[group].end = menuitem;
@ -874,8 +828,7 @@ void AppMenus::applyShortcutToMenuitemsWithCommand(Menu* menu,
const std::string& mi_commandId = menuitem->getCommandId(); const std::string& mi_commandId = menuitem->getCommandId();
const Params& mi_params = menuitem->getParams(); const Params& mi_params = menuitem->getParams();
if ((base::utf8_icmp(mi_commandId, command->id()) == 0) && if ((base::utf8_icmp(mi_commandId, command->id()) == 0) && (mi_params == params)) {
(mi_params == params)) {
// Set the keyboard shortcut to be shown in this menu-item // Set the keyboard shortcut to be shown in this menu-item
menuitem->setKey(key); menuitem->setKey(key);
} }
@ -938,26 +891,26 @@ void AppMenus::createNativeMenus()
os::MenuItemInfo about(fmt::format("About {}", get_app_name())); os::MenuItemInfo about(fmt::format("About {}", get_app_name()));
auto native = get_native_shortcut_for_command(CommandId::About()); auto native = get_native_shortcut_for_command(CommandId::About());
about.shortcut = native.shortcut; about.shortcut = native.shortcut;
about.execute = [native]{ about.execute = [native] {
if (can_call_global_shortcut(&native)) { if (can_call_global_shortcut(&native)) {
Command* cmd = Commands::instance()->byId(CommandId::About()); Command* cmd = Commands::instance()->byId(CommandId::About());
UIContext::instance()->executeCommandFromMenuOrShortcut(cmd); UIContext::instance()->executeCommandFromMenuOrShortcut(cmd);
} }
}; };
about.validate = [native](os::MenuItem* item){ about.validate = [native](os::MenuItem* item) {
item->setEnabled(can_call_global_shortcut(&native)); item->setEnabled(can_call_global_shortcut(&native));
}; };
os::MenuItemInfo preferences("Preferences..."); os::MenuItemInfo preferences("Preferences...");
native = get_native_shortcut_for_command(CommandId::Options()); native = get_native_shortcut_for_command(CommandId::Options());
preferences.shortcut = native.shortcut; preferences.shortcut = native.shortcut;
preferences.execute = [native]{ preferences.execute = [native] {
if (can_call_global_shortcut(&native)) { if (can_call_global_shortcut(&native)) {
Command* cmd = Commands::instance()->byId(CommandId::Options()); Command* cmd = Commands::instance()->byId(CommandId::Options());
UIContext::instance()->executeCommandFromMenuOrShortcut(cmd); UIContext::instance()->executeCommandFromMenuOrShortcut(cmd);
} }
}; };
preferences.validate = [native](os::MenuItem* item){ preferences.validate = [native](os::MenuItem* item) {
item->setEnabled(can_call_global_shortcut(&native)); item->setEnabled(can_call_global_shortcut(&native));
}; };
@ -973,7 +926,8 @@ void AppMenus::createNativeMenus()
appMenu->addItem(menus->makeMenuItem(preferences)); appMenu->addItem(menus->makeMenuItem(preferences));
appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo(os::MenuItemInfo::Separator))); appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo(os::MenuItemInfo::Separator)));
appMenu->addItem(menus->makeMenuItem(hide)); appMenu->addItem(menus->makeMenuItem(hide));
appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo("Hide Others", os::MenuItemInfo::HideOthers))); appMenu->addItem(
menus->makeMenuItem(os::MenuItemInfo("Hide Others", os::MenuItemInfo::HideOthers)));
appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo("Show All", os::MenuItemInfo::ShowAll))); appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo("Show All", os::MenuItemInfo::ShowAll)));
appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo(os::MenuItemInfo::Separator))); appMenu->addItem(menus->makeMenuItem(os::MenuItemInfo(os::MenuItemInfo::Separator)));
appMenu->addItem(menus->makeMenuItem(quit)); appMenu->addItem(menus->makeMenuItem(quit));
@ -1011,7 +965,7 @@ void AppMenus::createNativeMenus()
// We use helpIndex+1 because the first index in m_osMenu is the // We use helpIndex+1 because the first index in m_osMenu is the
// App menu. // App menu.
m_osMenu->insertItem(helpIndex+1, windowItem); m_osMenu->insertItem(helpIndex + 1, windowItem);
} }
#endif #endif
@ -1020,8 +974,7 @@ void AppMenus::createNativeMenus()
oldOSMenu.reset(); oldOSMenu.reset();
} }
void AppMenus::createNativeSubmenus(os::Menu* osMenu, void AppMenus::createNativeSubmenus(os::Menu* osMenu, const ui::Menu* uiMenu)
const ui::Menu* uiMenu)
{ {
os::Menus* menus = os::instance()->menus(); os::Menus* menus = os::instance()->menus();
@ -1034,17 +987,15 @@ void AppMenus::createNativeSubmenus(os::Menu* osMenu,
info.type = os::MenuItemInfo::Separator; info.type = os::MenuItemInfo::Separator;
} }
else if (child->type() == kMenuItemWidget) { else if (child->type() == kMenuItemWidget) {
if (appMenuItem && if (appMenuItem && appMenuItem->getCommand()) {
appMenuItem->getCommand()) { native = get_native_shortcut_for_command(appMenuItem->getCommandId().c_str(),
native = get_native_shortcut_for_command(
appMenuItem->getCommandId().c_str(),
appMenuItem->getParams()); appMenuItem->getParams());
} }
info.type = os::MenuItemInfo::Normal; info.type = os::MenuItemInfo::Normal;
info.text = child->text(); info.text = child->text();
info.shortcut = native.shortcut; info.shortcut = native.shortcut;
info.execute = [appMenuItem]{ info.execute = [appMenuItem] {
if (can_call_global_shortcut(appMenuItem->native())) if (can_call_global_shortcut(appMenuItem->native()))
appMenuItem->executeClick(); appMenuItem->executeClick();
}; };
@ -1077,8 +1028,7 @@ void AppMenus::createNativeSubmenus(os::Menu* osMenu,
osItem->setAsStandardEditMenuItem(); osItem->setAsStandardEditMenuItem();
} }
if (child->type() == ui::kMenuItemWidget && if (child->type() == ui::kMenuItemWidget && ((ui::MenuItem*)child)->hasSubmenu()) {
((ui::MenuItem*)child)->hasSubmenu()) {
os::MenuRef osSubmenu = menus->makeMenu(); os::MenuRef osSubmenu = menus->makeMenu();
createNativeSubmenus(osSubmenu.get(), ((ui::MenuItem*)child)->getSubmenu()); createNativeSubmenus(osSubmenu.get(), ((ui::MenuItem*)child)->getSubmenu());
osItem->setSubmenu(osSubmenu); osItem->setSubmenu(osSubmenu);

View File

@ -21,22 +21,22 @@
#include <memory> #include <memory>
namespace tinyxml2 { namespace tinyxml2 {
class XMLElement; class XMLElement;
class XMLHandle; class XMLHandle;
} } // namespace tinyxml2
namespace app { namespace app {
class Command; class Command;
class Params; class Params;
using namespace ui; using namespace ui;
// Class to handle/get/reload available menus in gui.xml file. // Class to handle/get/reload available menus in gui.xml file.
class AppMenus { class AppMenus {
AppMenus(); AppMenus();
DISABLE_COPYING(AppMenus); DISABLE_COPYING(AppMenus);
public: public:
static AppMenus* instance(); static AppMenus* instance();
void reload(); void reload();
@ -59,38 +59,36 @@ namespace app {
Menu* getAnimationMenu(); Menu* getAnimationMenu();
Menu* getNewFrameMenu() { return m_newFramePopupMenu.get(); } Menu* getNewFrameMenu() { return m_newFramePopupMenu.get(); }
void applyShortcutToMenuitemsWithCommand(Command* command, const Params& params, void applyShortcutToMenuitemsWithCommand(Command* command,
const Params& params,
const KeyPtr& key); const KeyPtr& key);
void syncNativeMenuItemKeyShortcuts(); void syncNativeMenuItemKeyShortcuts();
// Menu item handling in groups // Menu item handling in groups
void addMenuGroup(const std::string& groupId, void addMenuGroup(const std::string& groupId, MenuItem* menuItem);
MenuItem* menuItem);
void removeMenuGroup(const std::string& groupId); void removeMenuGroup(const std::string& groupId);
void addMenuItemIntoGroup(const std::string& groupId, void addMenuItemIntoGroup(const std::string& groupId, std::unique_ptr<Widget>&& menuItem);
std::unique_ptr<Widget>&& menuItem);
void removeMenuItemFromGroup(Command* cmd); void removeMenuItemFromGroup(Command* cmd);
void removeMenuItemFromGroup(Widget* menuItem); void removeMenuItemFromGroup(Widget* menuItem);
private: private:
template<typename Pred> template<typename Pred>
void removeMenuItemFromGroup(Pred pred); void removeMenuItemFromGroup(Pred pred);
Menu* loadMenuById(tinyxml2::XMLHandle& handle, const char *id); Menu* loadMenuById(tinyxml2::XMLHandle& handle, const char* id);
Menu* convertXmlelemToMenu(tinyxml2::XMLElement* elem); Menu* convertXmlelemToMenu(tinyxml2::XMLElement* elem);
Widget* convertXmlelemToMenuitem(tinyxml2::XMLElement* elem, Menu* menu); Widget* convertXmlelemToMenuitem(tinyxml2::XMLElement* elem, Menu* menu);
void applyShortcutToMenuitemsWithCommand(Menu* menu, Command* command, const Params& params, void applyShortcutToMenuitemsWithCommand(Menu* menu,
Command* command,
const Params& params,
const KeyPtr& key); const KeyPtr& key);
void syncNativeMenuItemKeyShortcuts(Menu* menu); void syncNativeMenuItemKeyShortcuts(Menu* menu);
void updateMenusList(); void updateMenusList();
void createNativeMenus(); void createNativeMenus();
void createNativeSubmenus(os::Menu* osMenu, void createNativeSubmenus(os::Menu* osMenu, const ui::Menu* uiMenu);
const ui::Menu* uiMenu);
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
void loadScriptsSubmenu(ui::Menu* menu, void loadScriptsSubmenu(ui::Menu* menu, const std::string& dir, const bool rootLevel);
const std::string& dir,
const bool rootLevel);
#endif #endif
struct GroupInfo { struct GroupInfo {
@ -124,9 +122,9 @@ namespace app {
// support native menus) // support native menus)
os::MenuRef m_osMenu; os::MenuRef m_osMenu;
XmlTranslator m_xmlTranslator; XmlTranslator m_xmlTranslator;
}; };
os::Shortcut get_os_shortcut_from_key(const Key* key); os::Shortcut get_os_shortcut_from_key(const Key* key);
} // namespace app } // namespace app

View File

@ -9,13 +9,13 @@
#pragma once #pragma once
namespace app { namespace app {
class MainWindow; class MainWindow;
class AppMod { class AppMod {
public: public:
virtual ~AppMod() { } virtual ~AppMod() {}
virtual void modMainWindow(MainWindow* mainWindow) = 0; virtual void modMainWindow(MainWindow* mainWindow) = 0;
}; };
} // namespace app } // namespace app

View File

@ -47,26 +47,21 @@ public:
, m_inkType(inkType) , m_inkType(inkType)
, m_inkOpacity(inkOpacity) , m_inkOpacity(inkOpacity)
, m_shade(shade) , m_shade(shade)
, m_pixelPerfect(pixelPerfect) { , m_pixelPerfect(pixelPerfect)
{
} }
Flags flags() const { return m_flags; } Flags flags() const { return m_flags; }
void setFlags(Flags flags) { m_flags = flags; } void setFlags(Flags flags) { m_flags = flags; }
bool isEmpty() const { bool isEmpty() const { return int(m_flags) == 0; }
return int(m_flags) == 0;
}
bool hasFlag(Flags flag) const { bool hasFlag(Flags flag) const { return ((int(m_flags) & int(flag)) == int(flag)); }
return ((int(m_flags) & int(flag)) == int(flag));
}
bool hasBrush() const { bool hasBrush() const
return {
(brush() && return (brush() &&
(hasFlag(Flags::BrushType) || (hasFlag(Flags::BrushType) || hasFlag(Flags::BrushSize) || hasFlag(Flags::BrushAngle)));
hasFlag(Flags::BrushSize) ||
hasFlag(Flags::BrushAngle)));
} }
// Can be null if the user deletes the brush. // Can be null if the user deletes the brush.
@ -80,11 +75,10 @@ public:
// True if the user locked the brush using the shortcut key to // True if the user locked the brush using the shortcut key to
// access it. // access it.
bool locked() const { bool locked() const { return hasFlag(Flags::Locked); }
return hasFlag(Flags::Locked);
}
void setLocked(bool locked) { void setLocked(bool locked)
{
if (locked) if (locked)
m_flags = static_cast<Flags>(int(m_flags) | int(Flags::Locked)); m_flags = static_cast<Flags>(int(m_flags) | int(Flags::Locked));
else else

View File

@ -6,28 +6,28 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#ifdef ENABLE_UPDATER #ifdef ENABLE_UPDATER
#include "app/check_update.h" #include "app/check_update.h"
#include "app/check_update_delegate.h" #include "app/check_update_delegate.h"
#include "app/pref/preferences.h" #include "app/pref/preferences.h"
#include "base/convert_to.h" #include "base/convert_to.h"
#include "base/launcher.h" #include "base/launcher.h"
#include "base/replace_string.h" #include "base/replace_string.h"
#include "base/thread.h" #include "base/thread.h"
#include "base/version.h" #include "base/version.h"
#include "ver/info.h" #include "ver/info.h"
#if ENABLE_SENTRY #if ENABLE_SENTRY
#include "app/sentry_wrapper.h" #include "app/sentry_wrapper.h"
#endif #endif
#include <ctime> #include <ctime>
#include <sstream> #include <sstream>
static const int kMonitoringPeriod = 100; static const int kMonitoringPeriod = 100;
@ -35,27 +35,22 @@ namespace app {
class CheckUpdateBackgroundJob : public updater::CheckUpdateDelegate { class CheckUpdateBackgroundJob : public updater::CheckUpdateDelegate {
public: public:
CheckUpdateBackgroundJob() CheckUpdateBackgroundJob() : m_received(false) {}
: m_received(false) { }
void abort() { void abort() { m_checker.abort(); }
m_checker.abort();
}
bool isReceived() const { bool isReceived() const { return m_received; }
return m_received;
}
void sendRequest(const updater::Uuid& uuid, const std::string& extraParams) { void sendRequest(const updater::Uuid& uuid, const std::string& extraParams)
{
m_checker.checkNewVersion(uuid, extraParams, this); m_checker.checkNewVersion(uuid, extraParams, this);
} }
const updater::CheckUpdateResponse& getResponse() const { const updater::CheckUpdateResponse& getResponse() const { return m_response; }
return m_response;
}
private: private:
void onResponse(updater::CheckUpdateResponse& data) override { void onResponse(updater::CheckUpdateResponse& data) override
{
m_response = data; m_response = data;
m_received = true; m_received = true;
} }
@ -72,11 +67,11 @@ CheckUpdateThreadLauncher::CheckUpdateThreadLauncher(CheckUpdateDelegate* delega
, m_received(false) , m_received(false)
, m_inits(m_preferences.updater.inits()) , m_inits(m_preferences.updater.inits())
, m_exits(m_preferences.updater.exits()) , m_exits(m_preferences.updater.exits())
#ifdef _DEBUG #ifdef _DEBUG
, m_isDeveloper(true) , m_isDeveloper(true)
#else #else
, m_isDeveloper(m_preferences.updater.isDeveloper()) , m_isDeveloper(m_preferences.updater.isDeveloper())
#endif #endif
, m_timer(kMonitoringPeriod, NULL) , m_timer(kMonitoringPeriod, NULL)
{ {
// Get how many days we have to wait for the next "check for update" // Get how many days we have to wait for the next "check for update"
@ -87,15 +82,16 @@ CheckUpdateThreadLauncher::CheckUpdateThreadLauncher(CheckUpdateDelegate* delega
time_t now = std::time(NULL); time_t now = std::time(NULL);
// Verify if we are in the "WaitDays" period... // Verify if we are in the "WaitDays" period...
if (now < lastCheck+int(double(60*60*24*waitDays)) && if (now < lastCheck + int(double(60 * 60 * 24 * waitDays)) && now > lastCheck) { // <- Avoid
now > lastCheck) { // <- Avoid broken clocks // broken
// clocks
// So we do not check for updates. // So we do not check for updates.
m_doCheck = false; m_doCheck = false;
} }
} }
// Minimal stats: number of initializations // Minimal stats: number of initializations
m_preferences.updater.inits(m_inits+1); m_preferences.updater.inits(m_inits + 1);
m_preferences.save(); m_preferences.save();
} }
@ -112,7 +108,7 @@ CheckUpdateThreadLauncher::~CheckUpdateThreadLauncher()
} }
// Minimal stats: number of exits // Minimal stats: number of exits
m_preferences.updater.exits(m_exits+1); m_preferences.updater.exits(m_exits + 1);
m_preferences.save(); m_preferences.save();
} }
@ -122,9 +118,9 @@ void CheckUpdateThreadLauncher::launch()
m_uuid = m_preferences.updater.uuid(); m_uuid = m_preferences.updater.uuid();
if (!m_uuid.empty()) { if (!m_uuid.empty()) {
#if ENABLE_SENTRY #if ENABLE_SENTRY
Sentry::setUserID(m_uuid); Sentry::setUserID(m_uuid);
#endif #endif
LOG(VERBOSE, "APP: Saved UUID %s\n", m_uuid.c_str()); LOG(VERBOSE, "APP: Saved UUID %s\n", m_uuid.c_str());
} }
@ -138,7 +134,7 @@ void CheckUpdateThreadLauncher::launch()
m_delegate->onCheckingUpdates(); m_delegate->onCheckingUpdates();
m_bgJob.reset(new CheckUpdateBackgroundJob); m_bgJob.reset(new CheckUpdateBackgroundJob);
m_thread.reset(new std::thread([this]{ checkForUpdates(); })); m_thread.reset(new std::thread([this] { checkForUpdates(); }));
// Start a timer to monitoring the progress of the background job // Start a timer to monitoring the progress of the background job
// executed in "m_thread". The "onMonitoringTick" method will be // executed in "m_thread". The "onMonitoringTick" method will be
@ -160,7 +156,6 @@ void CheckUpdateThreadLauncher::onMonitoringTick()
// Depending on the type of update received // Depending on the type of update received
switch (m_response.getUpdateType()) { switch (m_response.getUpdateType()) {
case updater::CheckUpdateResponse::NoUpdate: case updater::CheckUpdateResponse::NoUpdate:
// Clear // Clear
m_preferences.updater.newVersion(""); m_preferences.updater.newVersion("");
@ -182,9 +177,9 @@ void CheckUpdateThreadLauncher::onMonitoringTick()
m_preferences.updater.uuid(m_uuid); m_preferences.updater.uuid(m_uuid);
if (!m_uuid.empty()) { if (!m_uuid.empty()) {
#if ENABLE_SENTRY #if ENABLE_SENTRY
Sentry::setUserID(m_uuid); Sentry::setUserID(m_uuid);
#endif #endif
LOG(VERBOSE, "APP: New UUID %s\n", m_uuid.c_str()); LOG(VERBOSE, "APP: New UUID %s\n", m_uuid.c_str());
} }
} }
@ -207,8 +202,7 @@ void CheckUpdateThreadLauncher::checkForUpdates()
// Add mini-stats in the request // Add mini-stats in the request
std::stringstream extraParams; std::stringstream extraParams;
extraParams << "inits=" << m_inits extraParams << "inits=" << m_inits << "&exits=" << m_exits;
<< "&exits=" << m_exits;
if (m_isDeveloper) if (m_isDeveloper)
extraParams << "&dev=1"; extraParams << "&dev=1";
@ -235,8 +229,7 @@ void CheckUpdateThreadLauncher::showUI()
} }
if (newVer) { if (newVer) {
m_delegate->onNewUpdate(m_preferences.updater.newUrl(), m_delegate->onNewUpdate(m_preferences.updater.newUrl(), m_preferences.updater.newVersion());
m_preferences.updater.newVersion());
} }
else { else {
// If the program was updated, reset the "exits" counter // If the program was updated, reset the "exits" counter
@ -249,6 +242,6 @@ void CheckUpdateThreadLauncher::showUI()
} }
} }
} } // namespace app
#endif // ENABLE_UPDATER #endif // ENABLE_UPDATER

View File

@ -11,21 +11,21 @@
#ifdef ENABLE_UPDATER #ifdef ENABLE_UPDATER
#include "ui/timer.h" #include "ui/timer.h"
#include "updater/check_update.h" #include "updater/check_update.h"
#include <atomic> #include <atomic>
#include <memory> #include <memory>
#include <thread> #include <thread>
namespace app { namespace app {
class CheckUpdateDelegate; class CheckUpdateDelegate;
class CheckUpdateBackgroundJob; class CheckUpdateBackgroundJob;
class Preferences; class Preferences;
class CheckUpdateThreadLauncher { class CheckUpdateThreadLauncher {
public: public:
CheckUpdateThreadLauncher(CheckUpdateDelegate* delegate); CheckUpdateThreadLauncher(CheckUpdateDelegate* delegate);
~CheckUpdateThreadLauncher(); ~CheckUpdateThreadLauncher();
@ -33,12 +33,9 @@ namespace app {
bool isReceived() const; bool isReceived() const;
const updater::CheckUpdateResponse& getResponse() const const updater::CheckUpdateResponse& getResponse() const { return m_response; }
{
return m_response;
}
private: private:
void onMonitoringTick(); void onMonitoringTick();
void checkForUpdates(); void checkForUpdates();
void showUI(); void showUI();
@ -60,7 +57,7 @@ namespace app {
updater::CheckUpdateResponse m_response; updater::CheckUpdateResponse m_response;
ui::Timer m_timer; ui::Timer m_timer;
}; };
} // namespace app } // namespace app

View File

@ -10,17 +10,17 @@
#ifdef ENABLE_UPDATER #ifdef ENABLE_UPDATER
#include <string> #include <string>
namespace app { namespace app {
class CheckUpdateDelegate { class CheckUpdateDelegate {
public: public:
virtual ~CheckUpdateDelegate() { } virtual ~CheckUpdateDelegate() {}
virtual void onCheckingUpdates() = 0; virtual void onCheckingUpdates() = 0;
virtual void onUpToDate() = 0; virtual void onUpToDate() = 0;
virtual void onNewUpdate(const std::string& url, const std::string& version) = 0; virtual void onNewUpdate(const std::string& url, const std::string& version) = 0;
}; };
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cli/app_options.h" #include "app/cli/app_options.h"
@ -29,60 +29,145 @@ AppOptions::AppOptions(int argc, const char* argv[])
, m_shell(m_po.add("shell").description("Start an interactive console to execute scripts")) , m_shell(m_po.add("shell").description("Start an interactive console to execute scripts"))
#endif #endif
, m_batch(m_po.add("batch").mnemonic('b').description("Do not start the UI")) , m_batch(m_po.add("batch").mnemonic('b').description("Do not start the UI"))
, m_preview(m_po.add("preview").mnemonic('p').description("Do not execute actions, just print what will be\ndone")) , m_preview(m_po.add("preview").mnemonic('p').description(
, m_saveAs(m_po.add("save-as").requiresValue("<filename>").description("Save the last given sprite with other format")) "Do not execute actions, just print what will be\ndone"))
, m_palette(m_po.add("palette").requiresValue("<filename>").description("Change the palette of the last given sprite")) , m_saveAs(m_po.add("save-as")
, m_scale(m_po.add("scale").requiresValue("<factor>").description("Resize all previously opened sprites")) .requiresValue("<filename>")
, m_ditheringAlgorithm(m_po.add("dithering-algorithm").requiresValue("<algorithm>").description("Dithering algorithm used in --color-mode\nto convert images from RGB to Indexed\n none\n ordered\n old")) .description("Save the last given sprite with other format"))
, m_ditheringMatrix(m_po.add("dithering-matrix").requiresValue("<id>").description("Matrix used in ordered dithering algorithm\n bayer2x2\n bayer4x4\n bayer8x8\n filename.png")) , m_palette(m_po.add("palette")
, m_colorMode(m_po.add("color-mode").requiresValue("<mode>").description("Change color mode of all previously\nopened sprites:\n rgb\n grayscale\n indexed")) .requiresValue("<filename>")
, m_shrinkTo(m_po.add("shrink-to").requiresValue("width,height").description("Shrink each sprite if it is\nlarger than width or height")) .description("Change the palette of the last given sprite"))
, m_data(m_po.add("data").requiresValue("<filename.json>").description("File to store the sprite sheet metadata")) , m_scale(m_po.add("scale")
, m_format(m_po.add("format").requiresValue("<format>").description("Format to export the data file\n(json-hash, json-array)")) .requiresValue("<factor>")
, m_sheet(m_po.add("sheet").requiresValue("<filename.png>").description("Image file to save the texture")) .description("Resize all previously opened sprites"))
, m_sheetType(m_po.add("sheet-type").requiresValue("<type>").description("Algorithm to create the sprite sheet:\n horizontal\n vertical\n rows\n columns\n packed")) , m_ditheringAlgorithm(
m_po.add("dithering-algorithm")
.requiresValue("<algorithm>")
.description(
"Dithering algorithm used in --color-mode\nto convert images from RGB to Indexed\n none\n ordered\n old"))
, m_ditheringMatrix(
m_po.add("dithering-matrix")
.requiresValue("<id>")
.description(
"Matrix used in ordered dithering algorithm\n bayer2x2\n bayer4x4\n bayer8x8\n filename.png"))
, m_colorMode(
m_po.add("color-mode")
.requiresValue("<mode>")
.description(
"Change color mode of all previously\nopened sprites:\n rgb\n grayscale\n indexed"))
, m_shrinkTo(m_po.add("shrink-to")
.requiresValue("width,height")
.description("Shrink each sprite if it is\nlarger than width or height"))
, m_data(m_po.add("data")
.requiresValue("<filename.json>")
.description("File to store the sprite sheet metadata"))
, m_format(m_po.add("format")
.requiresValue("<format>")
.description("Format to export the data file\n(json-hash, json-array)"))
, m_sheet(m_po.add("sheet")
.requiresValue("<filename.png>")
.description("Image file to save the texture"))
, m_sheetType(
m_po.add("sheet-type")
.requiresValue("<type>")
.description(
"Algorithm to create the sprite sheet:\n horizontal\n vertical\n rows\n columns\n packed"))
, m_sheetPack(m_po.add("sheet-pack").description("Same as -sheet-type packed")) , m_sheetPack(m_po.add("sheet-pack").description("Same as -sheet-type packed"))
, m_sheetWidth(m_po.add("sheet-width").requiresValue("<pixels>").description("Sprite sheet width")) , m_sheetWidth(
, m_sheetHeight(m_po.add("sheet-height").requiresValue("<pixels>").description("Sprite sheet height")) m_po.add("sheet-width").requiresValue("<pixels>").description("Sprite sheet width"))
, m_sheetColumns(m_po.add("sheet-columns").requiresValue("<columns>").description("Fixed # of columns for -sheet-type rows")) , m_sheetHeight(
, m_sheetRows(m_po.add("sheet-rows").requiresValue("<rows>").description("Fixed # of rows for -sheet-type columns")) m_po.add("sheet-height").requiresValue("<pixels>").description("Sprite sheet height"))
, m_splitLayers(m_po.add("split-layers").description("Save each visible layer of sprites\nas separated images in the sheet\n")) , m_sheetColumns(m_po.add("sheet-columns")
.requiresValue("<columns>")
.description("Fixed # of columns for -sheet-type rows"))
, m_sheetRows(m_po.add("sheet-rows")
.requiresValue("<rows>")
.description("Fixed # of rows for -sheet-type columns"))
, m_splitLayers(
m_po.add("split-layers")
.description("Save each visible layer of sprites\nas separated images in the sheet\n"))
, m_splitTags(m_po.add("split-tags").description("Save each tag as a separated file")) , m_splitTags(m_po.add("split-tags").description("Save each tag as a separated file"))
, m_splitSlices(m_po.add("split-slices").description("Save each slice as a separated file")) , m_splitSlices(m_po.add("split-slices").description("Save each slice as a separated file"))
, m_splitGrid(m_po.add("split-grid").description("Save each grid tile as a separated file")) , m_splitGrid(m_po.add("split-grid").description("Save each grid tile as a separated file"))
, m_layer(m_po.add("layer").alias("import-layer").requiresValue("<name>").description("Include just the given layer in the sheet\nor save as operation")) , m_layer(m_po.add("layer")
, m_allLayers(m_po.add("all-layers").description("Make all layers visible\nBy default hidden layers will be ignored")) .alias("import-layer")
, m_ignoreLayer(m_po.add("ignore-layer").requiresValue("<name>").description("Exclude the given layer in the sheet\nor save as operation")) .requiresValue("<name>")
, m_tag(m_po.add("tag").alias("frame-tag").requiresValue("<name>").description("Include tagged frames in the sheet")) .description("Include just the given layer in the sheet\nor save as operation"))
, m_playSubtags(m_po.add("play-subtags").description("Play subtags and repeats when saving the frames of an animated sprite")) , m_allLayers(m_po.add("all-layers")
, m_frameRange(m_po.add("frame-range").requiresValue("from,to").description("Only export frames in the [from,to] range")) .description("Make all layers visible\nBy default hidden layers will be ignored"))
, m_ignoreLayer(m_po.add("ignore-layer")
.requiresValue("<name>")
.description("Exclude the given layer in the sheet\nor save as operation"))
, m_tag(m_po.add("tag")
.alias("frame-tag")
.requiresValue("<name>")
.description("Include tagged frames in the sheet"))
, m_playSubtags(
m_po.add("play-subtags")
.description("Play subtags and repeats when saving the frames of an animated sprite"))
, m_frameRange(m_po.add("frame-range")
.requiresValue("from,to")
.description("Only export frames in the [from,to] range"))
, m_ignoreEmpty(m_po.add("ignore-empty").description("Do not export empty frames/cels")) , m_ignoreEmpty(m_po.add("ignore-empty").description("Do not export empty frames/cels"))
, m_mergeDuplicates(m_po.add("merge-duplicates").description("Merge all duplicate frames into one in the sprite sheet")) , m_mergeDuplicates(m_po.add("merge-duplicates")
, m_borderPadding(m_po.add("border-padding").requiresValue("<value>").description("Add padding on the texture borders")) .description("Merge all duplicate frames into one in the sprite sheet"))
, m_shapePadding(m_po.add("shape-padding").requiresValue("<value>").description("Add padding between frames")) , m_borderPadding(m_po.add("border-padding")
, m_innerPadding(m_po.add("inner-padding").requiresValue("<value>").description("Add padding inside each frame")) .requiresValue("<value>")
, m_trim(m_po.add("trim").description("Trim whole sprite for --save-as\nor individual frames for --sheet")) .description("Add padding on the texture borders"))
, m_trimSprite(m_po.add("trim-sprite").description("Trim the whole sprite (for --save-as and --sheet)")) , m_shapePadding(
, m_trimByGrid(m_po.add("trim-by-grid").description("Trim all images by its correspondent grid boundaries before exporting")) m_po.add("shape-padding").requiresValue("<value>").description("Add padding between frames"))
, m_innerPadding(m_po.add("inner-padding")
.requiresValue("<value>")
.description("Add padding inside each frame"))
, m_trim(m_po.add("trim").description(
"Trim whole sprite for --save-as\nor individual frames for --sheet"))
, m_trimSprite(
m_po.add("trim-sprite").description("Trim the whole sprite (for --save-as and --sheet)"))
, m_trimByGrid(
m_po.add("trim-by-grid")
.description("Trim all images by its correspondent grid boundaries before exporting"))
, m_extrude(m_po.add("extrude").description("Extrude all images duplicating all edges one pixel")) , m_extrude(m_po.add("extrude").description("Extrude all images duplicating all edges one pixel"))
, m_crop(m_po.add("crop").requiresValue("x,y,width,height").description("Crop all the images to the given rectangle")) , m_crop(m_po.add("crop")
, m_slice(m_po.add("slice").requiresValue("<name>").description("Crop the sprite to the given slice area")) .requiresValue("x,y,width,height")
, m_filenameFormat(m_po.add("filename-format").requiresValue("<fmt>").description("Special format to generate filenames")) .description("Crop all the images to the given rectangle"))
, m_tagnameFormat(m_po.add("tagname-format").requiresValue("<fmt>").description("Special format to generate tagnames in JSON data")) , m_slice(m_po.add("slice").requiresValue("<name>").description(
"Crop the sprite to the given slice area"))
, m_filenameFormat(m_po.add("filename-format")
.requiresValue("<fmt>")
.description("Special format to generate filenames"))
, m_tagnameFormat(m_po.add("tagname-format")
.requiresValue("<fmt>")
.description("Special format to generate tagnames in JSON data"))
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
, m_script(m_po.add("script").requiresValue("<filename>").description("Execute a specific script")) , m_script(
, m_scriptParam(m_po.add("script-param").requiresValue("name=value").description("Parameter for a script executed from the\nCLI that you can access with app.params")) m_po.add("script").requiresValue("<filename>").description("Execute a specific script"))
, m_scriptParam(
m_po.add("script-param")
.requiresValue("name=value")
.description(
"Parameter for a script executed from the\nCLI that you can access with app.params"))
#endif #endif
, m_listLayers(m_po.add("list-layers").description("List layers of the next given sprite\nor include layers in JSON data")) , m_listLayers(
, m_listLayerHierarchy(m_po.add("list-layer-hierarchy").description("List layers with groups of the next given sprite\nor include layers hierarchy in JSON data")) m_po.add("list-layers")
, m_listTags(m_po.add("list-tags").description("List tags of the next given sprite\nor include frame tags in JSON data")) .description("List layers of the next given sprite\nor include layers in JSON data"))
, m_listSlices(m_po.add("list-slices").description("List slices of the next given sprite\nor include slices in JSON data")) , m_listLayerHierarchy(
m_po.add("list-layer-hierarchy")
.description(
"List layers with groups of the next given sprite\nor include layers hierarchy in JSON data"))
, m_listTags(
m_po.add("list-tags")
.description("List tags of the next given sprite\nor include frame tags in JSON data"))
, m_listSlices(
m_po.add("list-slices")
.description("List slices of the next given sprite\nor include slices in JSON data"))
, m_oneFrame(m_po.add("oneframe").description("Load just the first frame")) , m_oneFrame(m_po.add("oneframe").description("Load just the first frame"))
, m_exportTileset(m_po.add("export-tileset").description("Export only tilesets from visible tilemap layers")) , m_exportTileset(
m_po.add("export-tileset").description("Export only tilesets from visible tilemap layers"))
, m_verbose(m_po.add("verbose").mnemonic('v').description("Explain what is being done")) , m_verbose(m_po.add("verbose").mnemonic('v').description("Explain what is being done"))
, m_debug(m_po.add("debug").description("Extreme verbose mode and\ncopy log to desktop")) , m_debug(m_po.add("debug").description("Extreme verbose mode and\ncopy log to desktop"))
#ifdef ENABLE_STEAM #ifdef ENABLE_STEAM
, m_noInApp(m_po.add("noinapp").description("Disable \"in game\" visibility on Steam\nDoesn't count playtime")) , m_noInApp(m_po.add("noinapp").description(
"Disable \"in game\" visibility on Steam\nDoesn't count playtime"))
#endif #endif
#ifdef _WIN32 #ifdef _WIN32
, m_disableWintab(m_po.add("disable-wintab").description("Don't load wintab32.dll library")) , m_disableWintab(m_po.add("disable-wintab").description("Don't load wintab32.dll library"))
@ -105,10 +190,7 @@ AppOptions::AppOptions(int argc, const char* argv[])
m_showHelp = m_po.enabled(m_help); m_showHelp = m_po.enabled(m_help);
m_showVersion = m_po.enabled(m_version); m_showVersion = m_po.enabled(m_version);
if (m_startShell || if (m_startShell || m_showHelp || m_showVersion || m_po.enabled(m_batch)) {
m_showHelp ||
m_showVersion ||
m_po.enabled(m_batch)) {
m_startUI = false; m_startUI = false;
} }
} }
@ -121,9 +203,7 @@ AppOptions::AppOptions(int argc, const char* argv[])
bool AppOptions::hasExporterParams() const bool AppOptions::hasExporterParams() const
{ {
return return m_po.enabled(m_data) || m_po.enabled(m_sheet);
m_po.enabled(m_data) ||
m_po.enabled(m_sheet);
} }
#ifdef ENABLE_STEAM #ifdef ENABLE_STEAM
@ -140,4 +220,4 @@ bool AppOptions::disableWintab() const
} }
#endif #endif
} } // namespace app

View File

@ -41,9 +41,7 @@ public:
bool showVersion() const { return m_showVersion; } bool showVersion() const { return m_showVersion; }
VerboseLevel verboseLevel() const { return m_verboseLevel; } VerboseLevel verboseLevel() const { return m_verboseLevel; }
const ValueList& values() const { const ValueList& values() const { return m_po.values(); }
return m_po.values();
}
// Export options // Export options
const Option& saveAs() const { return m_saveAs; } const Option& saveAs() const { return m_saveAs; }
@ -181,7 +179,6 @@ private:
#endif #endif
Option& m_help; Option& m_help;
Option& m_version; Option& m_version;
}; };
} // namespace app } // namespace app

View File

@ -13,32 +13,29 @@
namespace app { namespace app {
class AppOptions; class AppOptions;
class Context; class Context;
class DocExporter; class DocExporter;
class Params; class Params;
struct CliOpenFile; struct CliOpenFile;
class CliDelegate { class CliDelegate {
public: public:
virtual ~CliDelegate() { } virtual ~CliDelegate() {}
virtual void showHelp(const AppOptions& options) { } virtual void showHelp(const AppOptions& options) {}
virtual void showVersion() { } virtual void showVersion() {}
virtual void uiMode() { } virtual void uiMode() {}
virtual void shellMode() { } virtual void shellMode() {}
virtual void batchMode() { } virtual void batchMode() {}
virtual void beforeOpenFile(const CliOpenFile& cof) { } virtual void beforeOpenFile(const CliOpenFile& cof) {}
virtual void afterOpenFile(const CliOpenFile& cof) { } virtual void afterOpenFile(const CliOpenFile& cof) {}
virtual void saveFile(Context* ctx, const CliOpenFile& cof) { } virtual void saveFile(Context* ctx, const CliOpenFile& cof) {}
virtual void loadPalette(Context* ctx, const std::string& filename) { } virtual void loadPalette(Context* ctx, const std::string& filename) {}
virtual void exportFiles(Context* ctx, DocExporter& exporter) { } virtual void exportFiles(Context* ctx, DocExporter& exporter) {}
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
virtual int execScript(const std::string& filename, virtual int execScript(const std::string& filename, const Params& params) { return 0; }
const Params& params) {
return 0;
}
#endif // ENABLE_SCRIPTING #endif // ENABLE_SCRIPTING
}; };
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cli/cli_open_file.h" #include "app/cli/cli_open_file.h"

View File

@ -17,10 +17,10 @@
namespace app { namespace app {
class Doc; class Doc;
class FileOpROI; class FileOpROI;
struct CliOpenFile { struct CliOpenFile {
Doc* document = nullptr; Doc* document = nullptr;
std::string filename; std::string filename;
std::string filenameFormat; std::string filenameFormat;
@ -48,25 +48,16 @@ namespace app {
bool playSubtags = false; bool playSubtags = false;
gfx::Rect crop; gfx::Rect crop;
bool hasTag() const { bool hasTag() const { return (!tag.empty()); }
return (!tag.empty());
}
bool hasSlice() const { bool hasSlice() const { return (!slice.empty()); }
return (!slice.empty());
}
bool hasFrameRange() const { bool hasFrameRange() const { return (fromFrame >= 0 && toFrame >= 0); }
return (fromFrame >= 0 && toFrame >= 0);
}
bool hasLayersFilter() const { bool hasLayersFilter() const { return (!includeLayers.empty() || !excludeLayers.empty()); }
return (!includeLayers.empty() ||
!excludeLayers.empty());
}
FileOpROI roi() const; FileOpROI roi() const;
}; };
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cli/cli_processor.h" #include "app/cli/cli_processor.h"
@ -44,9 +44,7 @@ namespace app {
namespace { namespace {
bool match_path(const std::string& filter, bool match_path(const std::string& filter, const std::string& layer_path, const bool exclude)
const std::string& layer_path,
const bool exclude)
{ {
if (filter == layer_path) if (filter == layer_path)
return true; return true;
@ -55,21 +53,18 @@ bool match_path(const std::string& filter,
base::split_string(filter, a, "/"); base::split_string(filter, a, "/");
base::split_string(layer_path, b, "/"); base::split_string(layer_path, b, "/");
for (std::size_t i=0; i<a.size() && i<b.size(); ++i) { for (std::size_t i = 0; i < a.size() && i < b.size(); ++i) {
if (a[i] != b[i] && a[i] != "*") if (a[i] != b[i] && a[i] != "*")
return false; return false;
} }
const bool wildcard = (!a.empty() && a[a.size()-1] == "*"); const bool wildcard = (!a.empty() && a[a.size() - 1] == "*");
// Exclude group itself when all children are excluded. This special // Exclude group itself when all children are excluded. This special
// case is only for exclusion because if we leave the group // case is only for exclusion because if we leave the group
// selected, the propagation of the selection will include all // selected, the propagation of the selection will include all
// visible children too (see SelectedLayers::propagateSelection()). // visible children too (see SelectedLayers::propagateSelection()).
if (exclude && if (exclude && a.size() > 1 && a.size() == b.size() + 1 && wildcard) {
a.size() > 1 &&
a.size() == b.size()+1 &&
wildcard) {
return true; return true;
} }
@ -95,8 +90,7 @@ bool filter_layer(const std::string& layer_path,
// If there is one layer with the given name "filter", we can convert // If there is one layer with the given name "filter", we can convert
// the filter to a full path to the layer (e.g. to match child layers // the filter to a full path to the layer (e.g. to match child layers
// of a group). // of a group).
std::string convert_filter_to_layer_path_if_possible( std::string convert_filter_to_layer_path_if_possible(const Sprite* sprite,
const Sprite* sprite,
const std::string& filter) const std::string& filter)
{ {
std::string fullName; std::string fullName;
@ -107,8 +101,7 @@ std::string convert_filter_to_layer_path_if_possible(
const Layer* layer = layers.front(); const Layer* layer = layers.front();
layers.pop(); layers.pop();
if (layer != sprite->root() && if (layer != sprite->root() && layer->name() == filter) {
layer->name() == filter) {
if (fullName.empty()) { if (fullName.empty()) {
fullName = get_layer_path(layer); fullName = get_layer_path(layer);
} }
@ -152,16 +145,14 @@ void CliProcessor::FilterLayers(const Sprite* sprite,
(!includes.empty() && !filter_layer(layer_path, includes, true))) (!includes.empty() && !filter_layer(layer_path, includes, true)))
continue; continue;
if (!excludes.empty() && if (!excludes.empty() && !filter_layer(layer_path, excludes, false))
!filter_layer(layer_path, excludes, false))
continue; continue;
filteredLayers.insert(layer); filteredLayers.insert(layer);
} }
} }
CliProcessor::CliProcessor(CliDelegate* delegate, CliProcessor::CliProcessor(CliDelegate* delegate, const AppOptions& options)
const AppOptions& options)
: m_delegate(delegate) : m_delegate(delegate)
, m_options(options) , m_options(options)
, m_exporter(nullptr) , m_exporter(nullptr)
@ -451,8 +442,7 @@ int CliProcessor::process(Context* ctx)
// Scale all sprites // Scale all sprites
for (auto doc : ctx->documents()) { for (auto doc : ctx->documents()) {
ctx->setActiveDocument(doc); ctx->setActiveDocument(doc);
ctx->executeCommand(Commands::instance()->byId(CommandId::SpriteSize()), ctx->executeCommand(Commands::instance()->byId(CommandId::SpriteSize()), params);
params);
} }
} }
// --dithering-algorithm <algorithm> // --dithering-algorithm <algorithm>
@ -466,7 +456,8 @@ int CliProcessor::process(Context* ctx)
else if (value.value() == "error-diffusion") else if (value.value() == "error-diffusion")
ditheringAlgorithm = render::DitheringAlgorithm::ErrorDiffusion; ditheringAlgorithm = render::DitheringAlgorithm::ErrorDiffusion;
else else
throw std::runtime_error("--dithering-algorithm needs a valid algorithm name\n" throw std::runtime_error(
"--dithering-algorithm needs a valid algorithm name\n"
"Usage: --dithering-algorithm <algorithm>\n" "Usage: --dithering-algorithm <algorithm>\n"
"Where <algorithm> can be none, ordered, old, or error-diffusion"); "Where <algorithm> can be none, ordered, old, or error-diffusion");
} }
@ -487,15 +478,9 @@ int CliProcessor::process(Context* ctx)
else if (value.value() == "indexed") { else if (value.value() == "indexed") {
params.set("format", "indexed"); params.set("format", "indexed");
switch (ditheringAlgorithm) { switch (ditheringAlgorithm) {
case render::DitheringAlgorithm::None: case render::DitheringAlgorithm::None: params.set("dithering", "none"); break;
params.set("dithering", "none"); case render::DitheringAlgorithm::Ordered: params.set("dithering", "ordered"); break;
break; case render::DitheringAlgorithm::Old: params.set("dithering", "old"); break;
case render::DitheringAlgorithm::Ordered:
params.set("dithering", "ordered");
break;
case render::DitheringAlgorithm::Old:
params.set("dithering", "old");
break;
case render::DitheringAlgorithm::ErrorDiffusion: case render::DitheringAlgorithm::ErrorDiffusion:
params.set("dithering", "error-diffusion"); params.set("dithering", "error-diffusion");
break; break;
@ -539,8 +524,7 @@ int CliProcessor::process(Context* ctx)
scale = std::min(scaleWidth, scaleHeight); scale = std::min(scaleWidth, scaleHeight);
Params params; Params params;
params.set("scale", base::convert_to<std::string>(scale).c_str()); params.set("scale", base::convert_to<std::string>(scale).c_str());
ctx->executeCommand(Commands::instance()->byId(CommandId::SpriteSize()), ctx->executeCommand(Commands::instance()->byId(CommandId::SpriteSize()), params);
params);
} }
} }
} }
@ -564,8 +548,7 @@ int CliProcessor::process(Context* ctx)
const std::string& v = value.value(); const std::string& v = value.value();
auto i = v.find('='); auto i = v.find('=');
if (i != std::string::npos) if (i != std::string::npos)
scriptParams.set(v.substr(0, i).c_str(), scriptParams.set(v.substr(0, i).c_str(), v.substr(i + 1).c_str());
v.substr(i+1).c_str());
else else
scriptParams.set(v.c_str(), "1"); scriptParams.set(v.c_str(), "1");
} }
@ -612,7 +595,7 @@ int CliProcessor::process(Context* ctx)
cof.document = nullptr; cof.document = nullptr;
cof.filename = base::normalize_path(value.value()); cof.filename = base::normalize_path(value.value());
if (// Check that the filename wasn't used loading a sequence if ( // Check that the filename wasn't used loading a sequence
// of images as one sprite // of images as one sprite
m_usedFiles.find(cof.filename) == m_usedFiles.end() && m_usedFiles.find(cof.filename) == m_usedFiles.end() &&
// Open sprite // Open sprite
@ -652,9 +635,7 @@ bool CliProcessor::openFile(Context* ctx, CliOpenFile& cof)
Doc* oldDoc = ctx->activeDocument(); Doc* oldDoc = ctx->activeDocument();
m_batch.open(ctx, m_batch.open(ctx, cof.filename, cof.oneFrame);
cof.filename,
cof.oneFrame);
// Mark used file names as "already processed" so we don't try to // Mark used file names as "already processed" so we don't try to
// open then again // open then again
@ -691,9 +672,8 @@ bool CliProcessor::openFile(Context* ctx, CliOpenFile& cof)
if (cof.hasFrameRange()) { if (cof.hasFrameRange()) {
// --frame-range with --frame-tag // --frame-range with --frame-tag
if (tag) { if (tag) {
selFrames.insert( selFrames.insert(tag->fromFrame() + std::clamp(cof.fromFrame, 0, tag->frames() - 1),
tag->fromFrame()+std::clamp(cof.fromFrame, 0, tag->frames()-1), tag->fromFrame() + std::clamp(cof.toFrame, 0, tag->frames() - 1));
tag->fromFrame()+std::clamp(cof.toFrame, 0, tag->frames()-1));
} }
// --frame-range without --frame-tag // --frame-range without --frame-tag
else { else {
@ -706,25 +686,23 @@ bool CliProcessor::openFile(Context* ctx, CliOpenFile& cof)
filterLayers(doc->sprite(), cof, filteredLayers); filterLayers(doc->sprite(), cof, filteredLayers);
if (cof.exportTileset) { if (cof.exportTileset) {
m_exporter->addTilesetsSamples( m_exporter->addTilesetsSamples(doc, (cof.hasLayersFilter() ? &filteredLayers : nullptr));
doc,
(cof.hasLayersFilter() ? &filteredLayers: nullptr));
} }
else { else {
m_exporter->addDocumentSamples( m_exporter->addDocumentSamples(doc,
doc, tag, tag,
cof.splitLayers, cof.splitLayers,
cof.splitTags, cof.splitTags,
cof.splitGrid, cof.splitGrid,
(cof.hasLayersFilter() ? &filteredLayers: nullptr), (cof.hasLayersFilter() ? &filteredLayers : nullptr),
(!selFrames.empty() ? &selFrames: nullptr)); (!selFrames.empty() ? &selFrames : nullptr));
} }
} }
} }
m_delegate->afterOpenFile(cof); m_delegate->afterOpenFile(cof);
return (doc ? true: false); return (doc ? true : false);
} }
void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof) void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof)
@ -742,17 +720,14 @@ void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof)
cropParams.set("y", base::convert_to<std::string>(cof.crop.y).c_str()); cropParams.set("y", base::convert_to<std::string>(cof.crop.y).c_str());
cropParams.set("width", base::convert_to<std::string>(cof.crop.w).c_str()); cropParams.set("width", base::convert_to<std::string>(cof.crop.w).c_str());
cropParams.set("height", base::convert_to<std::string>(cof.crop.h).c_str()); cropParams.set("height", base::convert_to<std::string>(cof.crop.h).c_str());
ctx->executeCommand( ctx->executeCommand(Commands::instance()->byId(CommandId::CropSprite()), cropParams);
Commands::instance()->byId(CommandId::CropSprite()),
cropParams);
} }
std::string fn = cof.filename; std::string fn = cof.filename;
std::string filenameFormat = cof.filenameFormat; std::string filenameFormat = cof.filenameFormat;
if (filenameFormat.empty()) { // Default format if (filenameFormat.empty()) { // Default format
bool hasFrames = (cof.roi().frames() > 1); bool hasFrames = (cof.roi().frames() > 1);
filenameFormat = get_default_filename_format( filenameFormat = get_default_filename_format(fn,
fn,
true, // With path true, // With path
hasFrames, // Has frames hasFrames, // Has frames
cof.splitLayers, // Has layer cof.splitLayers, // Has layer
@ -777,8 +752,7 @@ void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof)
std::vector<doc::Tag*> tags; std::vector<doc::Tag*> tags;
if (cof.hasTag()) { if (cof.hasTag()) {
tags.push_back( tags.push_back(doc->sprite()->tags().getByName(cof.tag));
doc->sprite()->tags().getByName(cof.tag));
} }
else { else {
doc::Tags& origTags = cof.document->sprite()->tags(); doc::Tags& origTags = cof.document->sprite()->tags();
@ -786,8 +760,7 @@ void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof)
for (doc::Tag* tag : origTags) { for (doc::Tag* tag : origTags) {
// In case the tag is outside the given --frame-range // In case the tag is outside the given --frame-range
if (cof.hasFrameRange()) { if (cof.hasFrameRange()) {
if (tag->toFrame() < cof.fromFrame || if (tag->toFrame() < cof.fromFrame || tag->fromFrame() > cof.toFrame)
tag->fromFrame() > cof.toFrame)
continue; continue;
} }
tags.push_back(tag); tags.push_back(tag);
@ -799,8 +772,7 @@ void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof)
std::vector<doc::Slice*> slices; std::vector<doc::Slice*> slices;
if (cof.hasSlice()) { if (cof.hasSlice()) {
slices.push_back( slices.push_back(doc->sprite()->slices().getByName(cof.slice));
doc->sprite()->slices().getByName(cof.slice));
} }
else { else {
doc::Slices& origSlices = cof.document->sprite()->slices(); doc::Slices& origSlices = cof.document->sprite()->slices();
@ -868,9 +840,7 @@ void CliProcessor::saveFile(Context* ctx, const CliOpenFile& cof)
itemCof.includeLayers.push_back(layer->name()); itemCof.includeLayers.push_back(layer->name());
} }
if (tag) { if (tag) {
fnInfo fnInfo.innerTagName(tag->name()).outerTagName(tag->name());
.innerTagName(tag->name())
.outerTagName(tag->name());
itemCof.tag = tag->name(); itemCof.tag = tag->name();
} }
if (slice) { if (slice) {

View File

@ -21,19 +21,18 @@
#include <vector> #include <vector>
namespace doc { namespace doc {
class Sprite; class Sprite;
} }
namespace app { namespace app {
class AppOptions; class AppOptions;
class Context; class Context;
class DocExporter; class DocExporter;
class CliProcessor { class CliProcessor {
public: public:
CliProcessor(CliDelegate* delegate, CliProcessor(CliDelegate* delegate, const AppOptions& options);
const AppOptions& options);
int process(Context* ctx); int process(Context* ctx);
// Public so it can be tested // Public so it can be tested
@ -43,18 +42,15 @@ namespace app {
std::vector<std::string> excludes, std::vector<std::string> excludes,
doc::SelectedLayers& filteredLayers); doc::SelectedLayers& filteredLayers);
private: private:
bool openFile(Context* ctx, CliOpenFile& cof); bool openFile(Context* ctx, CliOpenFile& cof);
void saveFile(Context* ctx, const CliOpenFile& cof); void saveFile(Context* ctx, const CliOpenFile& cof);
void filterLayers(const doc::Sprite* sprite, void filterLayers(const doc::Sprite* sprite,
const CliOpenFile& cof, const CliOpenFile& cof,
doc::SelectedLayers& filteredLayers) { doc::SelectedLayers& filteredLayers)
CliProcessor::FilterLayers( {
sprite, CliProcessor::FilterLayers(sprite, cof.includeLayers, cof.excludeLayers, filteredLayers);
cof.includeLayers,
cof.excludeLayers,
filteredLayers);
} }
CliDelegate* m_delegate; CliDelegate* m_delegate;
@ -65,7 +61,7 @@ namespace app {
// load a sequence of files) so we don't ask for them again. // load a sequence of files) so we don't ask for them again.
std::set<std::string> m_usedFiles; std::set<std::string> m_usedFiles;
OpenBatchOfFiles m_batch; OpenBatchOfFiles m_batch;
}; };
} // namespace app } // namespace app

View File

@ -17,7 +17,8 @@ using namespace app;
class CliTestDelegate : public CliDelegate { class CliTestDelegate : public CliDelegate {
public: public:
CliTestDelegate() { CliTestDelegate()
{
m_helpWasShown = false; m_helpWasShown = false;
m_versionWasShown = false; m_versionWasShown = false;
m_uiMode = false; m_uiMode = false;
@ -30,15 +31,12 @@ public:
void uiMode() override { m_uiMode = true; } void uiMode() override { m_uiMode = true; }
void shellMode() override { m_shellMode = true; } void shellMode() override { m_shellMode = true; }
void batchMode() override { m_batchMode = true; } void batchMode() override { m_batchMode = true; }
void beforeOpenFile(const CliOpenFile& cof) override { } void beforeOpenFile(const CliOpenFile& cof) override {}
void afterOpenFile(const CliOpenFile& cof) override { } void afterOpenFile(const CliOpenFile& cof) override {}
void saveFile(Context* ctx, const CliOpenFile& cof) override { } void saveFile(Context* ctx, const CliOpenFile& cof) override {}
void exportFiles(Context* ctx, DocExporter& exporter) override { } void exportFiles(Context* ctx, DocExporter& exporter) override {}
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
int execScript(const std::string& filename, int execScript(const std::string& filename, const Params& params) override { return 0; }
const Params& params) override {
return 0;
}
#endif #endif
bool helpWasShown() const { return m_helpWasShown; } bool helpWasShown() const { return m_helpWasShown; }
@ -52,12 +50,13 @@ private:
bool m_batchMode; bool m_batchMode;
}; };
std::unique_ptr<AppOptions> args(std::initializer_list<const char*> l) { std::unique_ptr<AppOptions> args(std::initializer_list<const char*> l)
int argc = l.size()+1; {
int argc = l.size() + 1;
const char** argv = new const char*[argc]; const char** argv = new const char*[argc];
argv[0] = "aseprite.exe"; argv[0] = "aseprite.exe";
auto it = l.begin(); auto it = l.begin();
for (int i=1; i<argc; ++i, ++it) { for (int i = 1; i < argc; ++i, ++it) {
argv[i] = *it; argv[i] = *it;
TRACE("argv[%d] = %s\n", i, argv[i]); TRACE("argv[%d] = %s\n", i, argv[i]);
} }
@ -69,7 +68,7 @@ std::unique_ptr<AppOptions> args(std::initializer_list<const char*> l) {
TEST(Cli, None) TEST(Cli, None)
{ {
CliTestDelegate d; CliTestDelegate d;
auto a = args({ }); auto a = args({});
CliProcessor p(&d, *a); CliProcessor p(&d, *a);
p.process(nullptr); p.process(nullptr);
EXPECT_TRUE(!d.helpWasShown()); EXPECT_TRUE(!d.helpWasShown());

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cli/default_cli_delegate.h" #include "app/cli/default_cli_delegate.h"
@ -42,15 +42,11 @@ namespace app {
void DefaultCliDelegate::showHelp(const AppOptions& options) void DefaultCliDelegate::showHelp(const AppOptions& options)
{ {
std::cout std::cout << get_app_name() << " v" << get_app_version() << " | A pixel art program\n"
<< get_app_name() << " v" << get_app_version() << get_app_copyright() << "\n\nUsage:\n"
<< " | A pixel art program\n"
<< get_app_copyright()
<< "\n\nUsage:\n"
<< " " << options.exeName() << " [OPTIONS] [FILES]...\n\n" << " " << options.exeName() << " [OPTIONS] [FILES]...\n\n"
<< "Options:\n" << "Options:\n"
<< options.programOptions() << options.programOptions() << "\nFind more information in " << get_app_name()
<< "\nFind more information in " << get_app_name()
<< " web site: " << get_app_url() << "\n\n"; << " web site: " << get_app_url() << "\n\n";
} }
@ -111,8 +107,7 @@ void DefaultCliDelegate::saveFile(Context* ctx, const CliOpenFile& cof)
ctx->executeCommand(saveAsCommand, params); ctx->executeCommand(saveAsCommand, params);
} }
void DefaultCliDelegate::loadPalette(Context* ctx, void DefaultCliDelegate::loadPalette(Context* ctx, const std::string& filename)
const std::string& filename)
{ {
std::unique_ptr<doc::Palette> palette(load_palette(filename.c_str())); std::unique_ptr<doc::Palette> palette(load_palette(filename.c_str()));
if (palette) { if (palette) {
@ -123,8 +118,7 @@ void DefaultCliDelegate::loadPalette(Context* ctx,
ctx->executeCommand(loadPalCommand, params); ctx->executeCommand(loadPalCommand, params);
} }
else { else {
Console().printf("Error loading palette in --palette '%s'\n", Console().printf("Error loading palette in --palette '%s'\n", filename.c_str());
filename.c_str());
} }
} }
@ -133,8 +127,7 @@ void DefaultCliDelegate::exportFiles(Context* ctx, DocExporter& exporter)
LOG("APP: Exporting sheet...\n"); LOG("APP: Exporting sheet...\n");
base::task_token token; base::task_token token;
std::unique_ptr<Doc> spriteSheet( std::unique_ptr<Doc> spriteSheet(exporter.exportSheet(ctx, token));
exporter.exportSheet(ctx, token));
// Sprite sheet isn't used, we just delete it. // Sprite sheet isn't used, we just delete it.
@ -142,8 +135,7 @@ void DefaultCliDelegate::exportFiles(Context* ctx, DocExporter& exporter)
} }
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
int DefaultCliDelegate::execScript(const std::string& filename, int DefaultCliDelegate::execScript(const std::string& filename, const Params& params)
const Params& params)
{ {
ScriptInputChain scriptInputChain; ScriptInputChain scriptInputChain;
if (!App::instance()->isGui()) { if (!App::instance()->isGui()) {

View File

@ -13,8 +13,8 @@
namespace app { namespace app {
class DefaultCliDelegate : public CliDelegate { class DefaultCliDelegate : public CliDelegate {
public: public:
void showHelp(const AppOptions& programOptions) override; void showHelp(const AppOptions& programOptions) override;
void showVersion() override; void showVersion() override;
void afterOpenFile(const CliOpenFile& cof) override; void afterOpenFile(const CliOpenFile& cof) override;
@ -22,10 +22,9 @@ namespace app {
void loadPalette(Context* ctx, const std::string& filename) override; void loadPalette(Context* ctx, const std::string& filename) override;
void exportFiles(Context* ctx, DocExporter& exporter) override; void exportFiles(Context* ctx, DocExporter& exporter) override;
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
int execScript(const std::string& filename, int execScript(const std::string& filename, const Params& params) override;
const Params& params) override;
#endif #endif
}; };
} // namespace app } // namespace app

View File

@ -15,8 +15,7 @@ using namespace doc;
class FilterLayers : public ::testing::Test { class FilterLayers : public ::testing::Test {
public: public:
FilterLayers() FilterLayers() : sprite(ImageSpec(ColorMode::RGB, 32, 32))
: sprite(ImageSpec(ColorMode::RGB, 32, 32))
{ {
a->setName("a"); a->setName("a");
b->setName("b"); b->setName("b");
@ -33,12 +32,9 @@ public:
b->addLayer(bb); b->addLayer(bb);
} }
void filter( void filter(std::vector<std::string> includes, std::vector<std::string> excludes)
std::vector<std::string> includes,
std::vector<std::string> excludes)
{ {
CliProcessor::FilterLayers( CliProcessor::FilterLayers(&sprite, std::move(includes), std::move(excludes), sel);
&sprite, std::move(includes), std::move(excludes), sel);
} }
Sprite sprite; Sprite sprite;

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cli/preview_cli_delegate.h" #include "app/cli/preview_cli_delegate.h"
@ -94,10 +94,7 @@ void PreviewCliDelegate::saveFile(Context* ctx, const CliOpenFile& cof)
<< " - Sprite: '" << cof.document->filename() << "'\n"; << " - Sprite: '" << cof.document->filename() << "'\n";
if (!cof.crop.isEmpty()) { if (!cof.crop.isEmpty()) {
std::cout << " - Crop: " std::cout << " - Crop: " << cof.crop.x << "," << cof.crop.y << " " << cof.crop.w << "x"
<< cof.crop.x << ","
<< cof.crop.y << " "
<< cof.crop.w << "x"
<< cof.crop.h << "\n"; << cof.crop.h << "\n";
} }
@ -112,8 +109,7 @@ void PreviewCliDelegate::saveFile(Context* ctx, const CliOpenFile& cof)
std::cout << " - Ignore empty frames\n"; std::cout << " - Ignore empty frames\n";
} }
std::cout << " - Size: " std::cout << " - Size: " << cof.document->sprite()->width() << "x"
<< cof.document->sprite()->width() << "x"
<< cof.document->sprite()->height() << "\n"; << cof.document->sprite()->height() << "\n";
showLayersFilter(cof); showLayersFilter(cof);
@ -136,8 +132,7 @@ void PreviewCliDelegate::saveFile(Context* ctx, const CliOpenFile& cof)
const auto& selFrames = cof.roi().framesSequence(); const auto& selFrames = cof.roi().framesSequence();
if (!selFrames.empty()) { if (!selFrames.empty()) {
if (selFrames.ranges() == 1) if (selFrames.ranges() == 1)
std::cout << " - Frame range from " std::cout << " - Frame range from " << selFrames.firstFrame() << " to "
<< selFrames.firstFrame() << " to "
<< selFrames.lastFrame() << "\n"; << selFrames.lastFrame() << "\n";
else { else {
std::cout << " - Specific frames:"; std::cout << " - Specific frames:";
@ -151,9 +146,7 @@ void PreviewCliDelegate::saveFile(Context* ctx, const CliOpenFile& cof)
if (!cof.filenameFormat.empty()) if (!cof.filenameFormat.empty())
std::cout << " - Filename format: '" << cof.filenameFormat << "'\n"; std::cout << " - Filename format: '" << cof.filenameFormat << "'\n";
std::unique_ptr<FileOp> fop( std::unique_ptr<FileOp> fop(FileOp::createSaveDocumentOperation(ctx,
FileOp::createSaveDocumentOperation(
ctx,
cof.roi(), cof.roi(),
cof.filename, cof.filename,
cof.filenameFormat, cof.filenameFormat,
@ -173,8 +166,7 @@ void PreviewCliDelegate::saveFile(Context* ctx, const CliOpenFile& cof)
std::cout << " - No output\n"; std::cout << " - No output\n";
} }
void PreviewCliDelegate::loadPalette(Context* ctx, void PreviewCliDelegate::loadPalette(Context* ctx, const std::string& filename)
const std::string& filename)
{ {
std::cout << "- Load palette:\n" std::cout << "- Load palette:\n"
<< " - Palette: '" << filename << "'\n"; << " - Palette: '" << filename << "'\n";
@ -197,8 +189,7 @@ void PreviewCliDelegate::exportFiles(Context* ctx, DocExporter& exporter)
<< " - Size: " << size.w << "x" << size.h << "\n"; << " - Size: " << size.w << "x" << size.h << "\n";
if (!exporter.textureFilename().empty()) { if (!exporter.textureFilename().empty()) {
std::cout << " - Save texture file: '" std::cout << " - Save texture file: '" << exporter.textureFilename() << "'\n";
<< exporter.textureFilename() << "'\n";
} }
if (!exporter.dataFilename().empty()) { if (!exporter.dataFilename().empty()) {
@ -211,15 +202,13 @@ void PreviewCliDelegate::exportFiles(Context* ctx, DocExporter& exporter)
<< " - Data format: " << format << "\n"; << " - Data format: " << format << "\n";
if (!exporter.filenameFormat().empty()) { if (!exporter.filenameFormat().empty()) {
std::cout << " - Filename format for JSON items: '" std::cout << " - Filename format for JSON items: '" << exporter.filenameFormat() << "'\n";
<< exporter.filenameFormat() << "'\n";
} }
} }
} }
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
int PreviewCliDelegate::execScript(const std::string& filename, int PreviewCliDelegate::execScript(const std::string& filename, const Params& params)
const Params& params)
{ {
std::cout << "- Run script: '" << filename << "'\n"; std::cout << "- Run script: '" << filename << "'\n";
if (!params.empty()) { if (!params.empty()) {
@ -257,8 +246,7 @@ void PreviewCliDelegate::showLayerVisibility(const doc::LayerGroup* group,
continue; continue;
std::cout << indent << "- " << layer->name() << "\n"; std::cout << indent << "- " << layer->name() << "\n";
if (layer->isGroup()) if (layer->isGroup())
showLayerVisibility(static_cast<const LayerGroup*>(layer), showLayerVisibility(static_cast<const LayerGroup*>(layer), indent + " ");
indent + " ");
} }
} }

View File

@ -14,13 +14,13 @@
#include <string> #include <string>
namespace doc { namespace doc {
class LayerGroup; class LayerGroup;
} }
namespace app { namespace app {
class PreviewCliDelegate : public CliDelegate { class PreviewCliDelegate : public CliDelegate {
public: public:
void showHelp(const AppOptions& programOptions) override; void showHelp(const AppOptions& programOptions) override;
void showVersion() override; void showVersion() override;
void uiMode() override; void uiMode() override;
@ -32,15 +32,13 @@ namespace app {
void loadPalette(Context* ctx, const std::string& filename) override; void loadPalette(Context* ctx, const std::string& filename) override;
void exportFiles(Context* ctx, DocExporter& exporter) override; void exportFiles(Context* ctx, DocExporter& exporter) override;
#ifdef ENABLE_SCRIPTING #ifdef ENABLE_SCRIPTING
int execScript(const std::string& filename, int execScript(const std::string& filename, const Params& params) override;
const Params& params) override;
#endif // ENABLE_SCRIPTING #endif // ENABLE_SCRIPTING
private: private:
void showLayersFilter(const CliOpenFile& cof); void showLayersFilter(const CliOpenFile& cof);
void showLayerVisibility(const doc::LayerGroup* group, void showLayerVisibility(const doc::LayerGroup* group, const std::string& indent);
const std::string& indent); };
};
} // namespace app } // namespace app

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/closed_docs.h" #include "app/closed_docs.h"
@ -20,22 +20,23 @@
namespace app { namespace app {
ClosedDocs::ClosedDocs(const Preferences& pref) ClosedDocs::ClosedDocs(const Preferences& pref) : m_done(false)
: m_done(false)
{ {
if (pref.general.dataRecovery()) if (pref.general.dataRecovery())
m_dataRecoveryPeriodMSecs = int(1000.0*60.0*pref.general.dataRecoveryPeriod()); m_dataRecoveryPeriodMSecs = int(1000.0 * 60.0 * pref.general.dataRecoveryPeriod());
else else
m_dataRecoveryPeriodMSecs = 0; m_dataRecoveryPeriodMSecs = 0;
if (pref.general.keepClosedSpriteOnMemory()) if (pref.general.keepClosedSpriteOnMemory())
m_keepClosedDocAliveForMSecs = int(1000.0*60.0*pref.general.keepClosedSpriteOnMemoryFor()); m_keepClosedDocAliveForMSecs = int(1000.0 * 60.0 * pref.general.keepClosedSpriteOnMemoryFor());
else else
m_keepClosedDocAliveForMSecs = 0; m_keepClosedDocAliveForMSecs = 0;
CLOSEDOC_TRACE("CLOSEDOC: Init", CLOSEDOC_TRACE("CLOSEDOC: Init",
"dataRecoveryPeriod", m_dataRecoveryPeriodMSecs, "dataRecoveryPeriod",
"keepClosedDocs", m_keepClosedDocAliveForMSecs); m_dataRecoveryPeriodMSecs,
"keepClosedDocs",
m_keepClosedDocAliveForMSecs);
} }
ClosedDocs::~ClosedDocs() ClosedDocs::~ClosedDocs()
@ -62,8 +63,7 @@ bool ClosedDocs::hasClosedDocs()
std::unique_lock<std::mutex> lock(m_mutex); std::unique_lock<std::mutex> lock(m_mutex);
result = !m_docs.empty(); result = !m_docs.empty();
} }
CLOSEDOC_TRACE("CLOSEDOC: Has closed docs?", CLOSEDOC_TRACE("CLOSEDOC: Has closed docs?", (result ? "true" : "false"));
(result ? "true": "false"));
return result; return result;
} }
@ -80,7 +80,7 @@ void ClosedDocs::addClosedDoc(Doc* doc)
m_docs.insert(m_docs.begin(), std::move(closedDoc)); m_docs.insert(m_docs.begin(), std::move(closedDoc));
if (!m_thread.joinable()) if (!m_thread.joinable())
m_thread = std::thread([this]{ backgroundThread(); }); m_thread = std::thread([this] { backgroundThread(); });
else else
m_cv.notify_one(); m_cv.notify_one();
} }
@ -126,13 +126,13 @@ void ClosedDocs::backgroundThread()
base::tick_t now = base::current_tick(); base::tick_t now = base::current_tick();
base::tick_t waitForMSecs = std::numeric_limits<base::tick_t>::max(); base::tick_t waitForMSecs = std::numeric_limits<base::tick_t>::max();
for (auto it=m_docs.begin(); it != m_docs.end(); ) { for (auto it = m_docs.begin(); it != m_docs.end();) {
const ClosedDoc& closedDoc = *it; const ClosedDoc& closedDoc = *it;
auto doc = closedDoc.doc; auto doc = closedDoc.doc;
base::tick_t diff = now - closedDoc.timestamp; base::tick_t diff = now - closedDoc.timestamp;
if (diff >= m_keepClosedDocAliveForMSecs) { if (diff >= m_keepClosedDocAliveForMSecs) {
if (// If we backup process is disabled if ( // If we backup process is disabled
m_dataRecoveryPeriodMSecs == 0 || m_dataRecoveryPeriodMSecs == 0 ||
// Or this document doesn't need a backup (e.g. an unmodified document) // Or this document doesn't need a backup (e.g. an unmodified document)
!doc->needsBackup() || !doc->needsBackup() ||
@ -150,7 +150,7 @@ void ClosedDocs::backgroundThread()
} }
} }
else { else {
waitForMSecs = std::min(waitForMSecs, m_keepClosedDocAliveForMSecs-diff); waitForMSecs = std::min(waitForMSecs, m_keepClosedDocAliveForMSecs - diff);
++it; ++it;
} }
} }

View File

@ -18,19 +18,19 @@
namespace app { namespace app {
class Doc; class Doc;
class Preferences; class Preferences;
// Handle the list of closed docs: // Handle the list of closed docs:
// * When a document is closed, we keep it for some time so the user // * When a document is closed, we keep it for some time so the user
// can undo the close command without losing the undo history. // can undo the close command without losing the undo history.
// * For the first closed document, a thread is launched to wait // * For the first closed document, a thread is launched to wait
// until we can definitely delete the doc after X minutes (like a // until we can definitely delete the doc after X minutes (like a
// garbage collector). // garbage collector).
// * If the document was not restore, we delete it from memory, if // * If the document was not restore, we delete it from memory, if
// the document was restore, we remove it from the m_docs. // the document was restore, we remove it from the m_docs.
class ClosedDocs { class ClosedDocs {
public: public:
ClosedDocs(const Preferences& pref); ClosedDocs(const Preferences& pref);
~ClosedDocs(); ~ClosedDocs();
@ -42,7 +42,7 @@ namespace app {
// the list of closed docs, and stop the thread. // the list of closed docs, and stop the thread.
std::vector<Doc*> getAndRemoveAllClosedDocs(); std::vector<Doc*> getAndRemoveAllClosedDocs();
private: private:
void backgroundThread(); void backgroundThread();
struct ClosedDoc { struct ClosedDoc {
@ -57,7 +57,7 @@ namespace app {
std::mutex m_mutex; std::mutex m_mutex;
std::condition_variable m_cv; std::condition_variable m_cv;
std::thread m_thread; std::thread m_thread;
}; };
} // namespace app } // namespace app

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd.h" #include "app/cmd.h"
@ -115,7 +115,8 @@ std::string Cmd::onLabel() const
return ""; return "";
} }
size_t Cmd::onMemSize() const { size_t Cmd::onMemSize() const
{
return sizeof(*this); return sizeof(*this);
} }

View File

@ -15,10 +15,10 @@
namespace app { namespace app {
class Context; class Context;
class Cmd : public undo::UndoCommand { class Cmd : public undo::UndoCommand {
public: public:
Cmd(); Cmd();
virtual ~Cmd(); virtual ~Cmd();
@ -34,7 +34,7 @@ namespace app {
Context* context() const { return m_ctx; } Context* context() const { return m_ctx; }
protected: protected:
virtual void onExecute(); virtual void onExecute();
virtual void onUndo(); virtual void onUndo();
virtual void onRedo(); virtual void onRedo();
@ -42,7 +42,7 @@ namespace app {
virtual std::string onLabel() const; virtual std::string onLabel() const;
virtual size_t onMemSize() const; virtual size_t onMemSize() const;
private: private:
Context* m_ctx; Context* m_ctx;
#if _DEBUG #if _DEBUG
enum class State { NotExecuted, Executed, Undone, Redone }; enum class State { NotExecuted, Executed, Undone, Redone };
@ -50,7 +50,7 @@ namespace app {
#endif #endif
DISABLE_COPYING(Cmd); DISABLE_COPYING(Cmd);
}; };
} // namespace app } // namespace app

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_cel.h" #include "app/cmd/add_cel.h"
@ -21,17 +21,13 @@
#include "doc/layer.h" #include "doc/layer.h"
#include "doc/subobjects_io.h" #include "doc/subobjects_io.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace base::serialization; using namespace base::serialization;
using namespace base::serialization::little_endian; using namespace base::serialization::little_endian;
using namespace doc; using namespace doc;
AddCel::AddCel(Layer* layer, Cel* cel) AddCel::AddCel(Layer* layer, Cel* cel) : WithLayer(layer), WithCel(cel), m_size(0)
: WithLayer(layer)
, WithCel(cel)
, m_size(0)
{ {
} }
@ -54,7 +50,7 @@ void AddCel::onUndo()
// Save the CelData only if the cel isn't linked // Save the CelData only if the cel isn't linked
bool has_data = (cel->links() == 0); bool has_data = (cel->links() == 0);
write8(m_stream, has_data ? 1: 0); write8(m_stream, has_data ? 1 : 0);
if (has_data) { if (has_data) {
write_image(m_stream, cel->image()); write_image(m_stream, cel->image());
write_celdata(m_stream, cel->data()); write_celdata(m_stream, cel->data());
@ -119,5 +115,4 @@ void AddCel::removeCel(Layer* layer, Cel* cel)
delete cel; delete cel;
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -15,37 +15,33 @@
#include <sstream> #include <sstream>
namespace doc { namespace doc {
class Cel; class Cel;
class Layer; class Layer;
} } // namespace doc
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class AddCel : public Cmd class AddCel : public Cmd,
, public WithLayer public WithLayer,
, public WithCel { public WithCel {
public: public:
AddCel(Layer* layer, Cel* cel); AddCel(Layer* layer, Cel* cel);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_size; }
return sizeof(*this) + m_size;
}
private: private:
void addCel(Layer* layer, Cel* cel); void addCel(Layer* layer, Cel* cel);
void removeCel(Layer* layer, Cel* cel); void removeCel(Layer* layer, Cel* cel);
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_frame.h" #include "app/cmd/add_frame.h"
@ -18,8 +18,7 @@
#include "doc/primitives.h" #include "doc/primitives.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -77,5 +76,4 @@ void AddFrame::onUndo()
doc->notify_observers<DocEvent&>(&DocObserver::onRemoveFrame, ev); doc->notify_observers<DocEvent&>(&DocObserver::onRemoveFrame, ev);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -16,34 +16,29 @@
#include <memory> #include <memory>
namespace doc { namespace doc {
class Sprite; class Sprite;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class AddFrame : public Cmd class AddFrame : public Cmd,
, public WithSprite { public WithSprite {
public: public:
AddFrame(Sprite* sprite, frame_t frame); AddFrame(Sprite* sprite, frame_t frame);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + (m_addCel ? m_addCel->memSize() : 0); }
return sizeof(*this) +
(m_addCel ? m_addCel->memSize() : 0);
}
private: private:
void moveFrames(Layer* layer, frame_t fromThis, frame_t delta); void moveFrames(Layer* layer, frame_t fromThis, frame_t delta);
frame_t m_newFrame; frame_t m_newFrame;
std::unique_ptr<AddCel> m_addCel; std::unique_ptr<AddCel> m_addCel;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_layer.h" #include "app/cmd/add_layer.h"
@ -16,8 +16,7 @@
#include "doc/layer_io.h" #include "doc/layer_io.h"
#include "doc/subobjects_io.h" #include "doc/subobjects_io.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -93,5 +92,4 @@ void AddLayer::removeLayer(Layer* group, Layer* layer)
delete layer; delete layer;
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,26 +14,23 @@
#include <sstream> #include <sstream>
namespace doc { namespace doc {
class Layer; class Layer;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class AddLayer : public Cmd { class AddLayer : public Cmd {
public: public:
AddLayer(Layer* group, Layer* newLayer, Layer* afterThis); AddLayer(Layer* group, Layer* newLayer, Layer* afterThis);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_size; }
return sizeof(*this) + m_size;
}
private: private:
void addLayer(Layer* group, Layer* newLayer, Layer* afterThis); void addLayer(Layer* group, Layer* newLayer, Layer* afterThis);
void removeLayer(Layer* group, Layer* layer); void removeLayer(Layer* group, Layer* layer);
@ -42,9 +39,8 @@ namespace cmd {
WithLayer m_afterThis; WithLayer m_afterThis;
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,17 +5,16 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_palette.h" #include "app/cmd/add_palette.h"
#include "doc/sprite.h"
#include "doc/palette.h" #include "doc/palette.h"
#include "doc/palette_io.h" #include "doc/palette_io.h"
#include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -47,5 +46,4 @@ void AddPalette::onUndo()
sprite->incrementVersion(); sprite->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -15,33 +15,29 @@
#include <sstream> #include <sstream>
namespace doc { namespace doc {
class Palette; class Palette;
class Sprite; class Sprite;
} } // namespace doc
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class AddPalette : public Cmd class AddPalette : public Cmd,
, public WithSprite { public WithSprite {
public: public:
AddPalette(Sprite* sprite, Palette* pal); AddPalette(Sprite* sprite, Palette* pal);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_size; }
return sizeof(*this) + m_size;
}
private: private:
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
frame_t m_frame; frame_t m_frame;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif // CMD_ADD_PALETTE_H_INCLUDED #endif // CMD_ADD_PALETTE_H_INCLUDED

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_slice.h" #include "app/cmd/add_slice.h"
@ -17,15 +17,11 @@
#include "doc/slice_io.h" #include "doc/slice_io.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
AddSlice::AddSlice(Sprite* sprite, Slice* slice) AddSlice::AddSlice(Sprite* sprite, Slice* slice) : WithSprite(sprite), WithSlice(slice), m_size(0)
: WithSprite(sprite)
, WithSlice(slice)
, m_size(0)
{ {
} }
@ -84,5 +80,4 @@ void AddSlice::removeSlice(Sprite* sprite, Slice* slice)
delete slice; delete slice;
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -15,33 +15,29 @@
#include <sstream> #include <sstream>
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class AddSlice : public Cmd class AddSlice : public Cmd,
, public WithSprite public WithSprite,
, public WithSlice { public WithSlice {
public: public:
AddSlice(Sprite* sprite, Slice* slice); AddSlice(Sprite* sprite, Slice* slice);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_size; }
return sizeof(*this) + m_size;
}
private: private:
void addSlice(Sprite* sprite, Slice* slice); void addSlice(Sprite* sprite, Slice* slice);
void removeSlice(Sprite* sprite, Slice* slice); void removeSlice(Sprite* sprite, Slice* slice);
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_tag.h" #include "app/cmd/add_tag.h"
@ -17,15 +17,11 @@
#include "doc/tag.h" #include "doc/tag.h"
#include "doc/tag_io.h" #include "doc/tag_io.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
AddTag::AddTag(Sprite* sprite, Tag* tag) AddTag::AddTag(Sprite* sprite, Tag* tag) : WithSprite(sprite), WithTag(tag), m_size(0)
: WithSprite(sprite)
, WithTag(tag)
, m_size(0)
{ {
} }
@ -86,5 +82,4 @@ void AddTag::onRedo()
doc->notify_observers<DocEvent&>(&DocObserver::onAddTag, ev); doc->notify_observers<DocEvent&>(&DocObserver::onAddTag, ev);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -10,35 +10,31 @@
#pragma once #pragma once
#include "app/cmd.h" #include "app/cmd.h"
#include "app/cmd/with_tag.h"
#include "app/cmd/with_sprite.h" #include "app/cmd/with_sprite.h"
#include "app/cmd/with_tag.h"
#include <sstream> #include <sstream>
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class AddTag : public Cmd class AddTag : public Cmd,
, public WithSprite public WithSprite,
, public WithTag { public WithTag {
public: public:
AddTag(Sprite* sprite, Tag* tag); AddTag(Sprite* sprite, Tag* tag);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_size; }
return sizeof(*this) + m_size;
}
private: private:
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_tile.h" #include "app/cmd/add_tile.h"
@ -16,12 +16,9 @@
#include "doc/tileset.h" #include "doc/tileset.h"
#include "doc/tilesets.h" #include "doc/tilesets.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
AddTile::AddTile(doc::Tileset* tileset, AddTile::AddTile(doc::Tileset* tileset, const doc::ImageRef& image, const doc::UserData& userData)
const doc::ImageRef& image,
const doc::UserData& userData)
: WithTileset(tileset) : WithTileset(tileset)
, WithImage(image.get()) , WithImage(image.get())
, m_size(0) , m_size(0)
@ -31,8 +28,7 @@ AddTile::AddTile(doc::Tileset* tileset,
{ {
} }
AddTile::AddTile(doc::Tileset* tileset, AddTile::AddTile(doc::Tileset* tileset, const doc::tile_index ti)
const doc::tile_index ti)
: WithTileset(tileset) : WithTileset(tileset)
, WithImage(tileset->get(ti).get()) , WithImage(tileset->get(ti).get())
, m_size(0) , m_size(0)
@ -94,8 +90,7 @@ void AddTile::onFireNotifications()
doc::Tileset* tileset = this->tileset(); doc::Tileset* tileset = this->tileset();
// Notify that the tileset's changed // Notify that the tileset's changed
static_cast<Doc*>(tileset->sprite()->document()) static_cast<Doc*>(tileset->sprite()->document())->notifyTilesetChanged(tileset);
->notifyTilesetChanged(tileset);
} }
void AddTile::addTile(doc::Tileset* tileset, void AddTile::addTile(doc::Tileset* tileset,
@ -111,5 +106,4 @@ void AddTile::addTile(doc::Tileset* tileset,
tileset->incrementVersion(); tileset->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -18,47 +18,43 @@
#include <sstream> #include <sstream>
namespace doc { namespace doc {
class Tileset; class Tileset;
} }
namespace app { namespace app { namespace cmd {
namespace cmd {
class AddTile : public Cmd class AddTile : public Cmd,
, public WithTileset public WithTileset,
, public WithImage { public WithImage {
public: public:
AddTile(doc::Tileset* tileset, AddTile(doc::Tileset* tileset,
const doc::ImageRef& image, const doc::ImageRef& image,
const doc::UserData& userData = UserData()); const doc::UserData& userData = UserData());
AddTile(doc::Tileset* tileset, AddTile(doc::Tileset* tileset, const doc::tile_index ti);
const doc::tile_index ti);
doc::tile_index tileIndex() const { return m_tileIndex; } doc::tile_index tileIndex() const { return m_tileIndex; }
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
void onFireNotifications() override; void onFireNotifications() override;
size_t onMemSize() const override { size_t onMemSize() const override
{
// TODO add m_userData size // TODO add m_userData size
return sizeof(*this) + m_size; return sizeof(*this) + m_size;
} }
private: private:
void addTile(doc::Tileset* tileset, void addTile(doc::Tileset* tileset, const doc::ImageRef& image, const doc::UserData& userData);
const doc::ImageRef& image,
const doc::UserData& userData);
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
doc::tile_index m_tileIndex; doc::tile_index m_tileIndex;
doc::ImageRef m_imageRef; doc::ImageRef m_imageRef;
doc::UserData m_userData; doc::UserData m_userData;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/add_tileset.h" #include "app/cmd/add_tileset.h"
@ -16,8 +16,7 @@
#include "doc/tileset_io.h" #include "doc/tileset_io.h"
#include "doc/tilesets.h" #include "doc/tilesets.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -84,5 +83,4 @@ void AddTileset::addTileset(doc::Tileset* tileset)
sprite->tilesets()->incrementVersion(); sprite->tilesets()->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -16,38 +16,34 @@
#include <sstream> #include <sstream>
namespace doc { namespace doc {
class Tileset; class Tileset;
} }
namespace app { namespace app { namespace cmd {
namespace cmd {
class AddTileset : public Cmd class AddTileset : public Cmd,
, public WithSprite public WithSprite,
, public WithTileset { public WithTileset {
public: public:
AddTileset(doc::Sprite* sprite, doc::Tileset* tileset); AddTileset(doc::Sprite* sprite, doc::Tileset* tileset);
AddTileset(doc::Sprite* sprite, const doc::tileset_index tsi); AddTileset(doc::Sprite* sprite, const doc::tileset_index tsi);
doc::tileset_index tilesetIndex() const { return m_tilesetIndex; } doc::tileset_index tilesetIndex() const { return m_tilesetIndex; }
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_size; }
return sizeof(*this) + m_size;
}
private: private:
void addTileset(doc::Tileset* tileset); void addTileset(doc::Tileset* tileset);
size_t m_size; size_t m_size;
std::stringstream m_stream; std::stringstream m_stream;
doc::tileset_index m_tilesetIndex; doc::tileset_index m_tilesetIndex;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/assign_color_profile.h" #include "app/cmd/assign_color_profile.h"
@ -14,8 +14,7 @@
#include "app/doc_event.h" #include "app/doc_event.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
AssignColorProfile::AssignColorProfile(doc::Sprite* sprite, const gfx::ColorSpaceRef& cs) AssignColorProfile::AssignColorProfile(doc::Sprite* sprite, const gfx::ColorSpaceRef& cs)
: WithSprite(sprite) : WithSprite(sprite)
@ -45,5 +44,4 @@ void AssignColorProfile::onFireNotifications()
doc->notifyColorSpaceChanged(); doc->notifyColorSpaceChanged();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -12,31 +12,27 @@
#include "app/cmd/with_sprite.h" #include "app/cmd/with_sprite.h"
#include "gfx/color_space.h" #include "gfx/color_space.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
class AssignColorProfile : public Cmd, class AssignColorProfile : public Cmd,
public WithSprite { public WithSprite {
public: public:
AssignColorProfile(doc::Sprite* sprite, const gfx::ColorSpaceRef& cs); AssignColorProfile(doc::Sprite* sprite, const gfx::ColorSpaceRef& cs);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onFireNotifications() override; void onFireNotifications() override;
size_t onMemSize() const override { size_t onMemSize() const override
return sizeof(*this) + {
2*sizeof(gfx::ColorSpace) + return sizeof(*this) + 2 * sizeof(gfx::ColorSpace) + m_oldCS->iccSize() + m_newCS->iccSize();
m_oldCS->iccSize() +
m_newCS->iccSize();
} }
private: private:
gfx::ColorSpaceRef m_oldCS; gfx::ColorSpaceRef m_oldCS;
gfx::ColorSpaceRef m_newCS; gfx::ColorSpaceRef m_newCS;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/background_from_layer.h" #include "app/cmd/background_from_layer.h"
@ -25,11 +25,9 @@
#include "doc/sprite.h" #include "doc/sprite.h"
#include "render/render.h" #include "render/render.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
BackgroundFromLayer::BackgroundFromLayer(Layer* layer) BackgroundFromLayer::BackgroundFromLayer(Layer* layer) : WithLayer(layer)
: WithLayer(layer)
{ {
ASSERT(layer); ASSERT(layer);
ASSERT(layer->isVisible()); ASSERT(layer->isVisible());
@ -60,10 +58,11 @@ void BackgroundFromLayer::onExecute()
ASSERT(cel_image->pixelFormat() != IMAGE_TILEMAP); ASSERT(cel_image->pixelFormat() != IMAGE_TILEMAP);
clear_image(bg_image.get(), bgcolor); clear_image(bg_image.get(), bgcolor);
render::composite_image( render::composite_image(bg_image.get(),
bg_image.get(), cel_image, cel_image,
sprite->palette(cel->frame()), sprite->palette(cel->frame()),
cel->x(), cel->y(), cel->x(),
cel->y(),
std::clamp(cel->opacity(), 0, 255), std::clamp(cel->opacity(), 0, 255),
static_cast<LayerImage*>(layer)->blendMode()); static_cast<LayerImage*>(layer)->blendMode());
@ -76,10 +75,8 @@ void BackgroundFromLayer::onExecute()
// Same size of cel image and background image, we can just // Same size of cel image and background image, we can just
// replace pixels. // replace pixels.
if (bg_image->width() == cel_image->width() && if (bg_image->width() == cel_image->width() && bg_image->height() == cel_image->height()) {
bg_image->height() == cel_image->height()) { executeAndAdd(new CopyRect(cel_image, bg_image.get(), gfx::Clip(0, 0, cel_image->bounds())));
executeAndAdd(new CopyRect(cel_image, bg_image.get(),
gfx::Clip(0, 0, cel_image->bounds())));
} }
// In other case we have to replace the whole image (this is the // In other case we have to replace the whole image (this is the
// most common case, a smaller transparent cel that is converted // most common case, a smaller transparent cel that is converted
@ -91,11 +88,10 @@ void BackgroundFromLayer::onExecute()
} }
// Fill all empty cels with a flat image filled with bgcolor // Fill all empty cels with a flat image filled with bgcolor
for (frame_t frame(0); frame<sprite->totalFrames(); ++frame) { for (frame_t frame(0); frame < sprite->totalFrames(); ++frame) {
Cel* cel = layer->cel(frame); Cel* cel = layer->cel(frame);
if (!cel) { if (!cel) {
ImageRef cel_image(Image::create(sprite->pixelFormat(), ImageRef cel_image(Image::create(sprite->pixelFormat(), sprite->width(), sprite->height()));
sprite->width(), sprite->height()));
clear_image(cel_image.get(), bgcolor); clear_image(cel_image.get(), bgcolor);
// Create the new cel and add it to the new background layer // Create the new cel and add it to the new background layer
@ -107,5 +103,4 @@ void BackgroundFromLayer::onExecute()
executeAndAdd(new cmd::ConfigureBackground(layer)); executeAndAdd(new cmd::ConfigureBackground(layer));
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -11,20 +11,18 @@
#include "app/cmd/with_layer.h" #include "app/cmd/with_layer.h"
#include "app/cmd_sequence.h" #include "app/cmd_sequence.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class BackgroundFromLayer : public CmdSequence class BackgroundFromLayer : public CmdSequence,
, public WithLayer { public WithLayer {
public: public:
BackgroundFromLayer(Layer* layer); BackgroundFromLayer(Layer* layer);
protected: protected:
void onExecute() override; void onExecute() override;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/clear_cel.h" #include "app/cmd/clear_cel.h"
@ -16,13 +16,11 @@
#include "doc/cel.h" #include "doc/cel.h"
#include "doc/layer.h" #include "doc/layer.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
ClearCel::ClearCel(Cel* cel) ClearCel::ClearCel(Cel* cel) : WithCel(cel)
: WithCel(cel)
{ {
Doc* doc = static_cast<Doc*>(cel->document()); Doc* doc = static_cast<Doc*>(cel->document());
@ -30,8 +28,7 @@ ClearCel::ClearCel(Cel* cel)
Image* image = cel->image(); Image* image = cel->image();
ASSERT(image); ASSERT(image);
if (image) if (image)
m_seq.add(new cmd::ClearImage(image, m_seq.add(new cmd::ClearImage(image, doc->bgColor(cel->layer())));
doc->bgColor(cel->layer())));
} }
else { else {
m_seq.add(new cmd::RemoveCel(cel)); m_seq.add(new cmd::RemoveCel(cel));
@ -53,5 +50,4 @@ void ClearCel::onRedo()
m_seq.redo(); m_seq.redo();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -12,28 +12,24 @@
#include "app/cmd/with_cel.h" #include "app/cmd/with_cel.h"
#include "app/cmd_sequence.h" #include "app/cmd_sequence.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class ClearCel : public Cmd class ClearCel : public Cmd,
, public WithCel { public WithCel {
public: public:
ClearCel(Cel* cel); ClearCel(Cel* cel);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_seq.memSize(); }
return sizeof(*this) + m_seq.memSize();
}
private: private:
CmdSequence m_seq; CmdSequence m_seq;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/clear_image.h" #include "app/cmd/clear_image.h"
@ -14,14 +14,11 @@
#include "doc/image.h" #include "doc/image.h"
#include "doc/primitives.h" #include "doc/primitives.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
ClearImage::ClearImage(Image* image, color_t color) ClearImage::ClearImage(Image* image, color_t color) : WithImage(image), m_color(color)
: WithImage(image)
, m_color(color)
{ {
} }
@ -46,5 +43,4 @@ void ClearImage::onUndo()
image->incrementVersion(); image->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -13,28 +13,24 @@
#include "doc/color.h" #include "doc/color.h"
#include "doc/image_ref.h" #include "doc/image_ref.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class ClearImage : public Cmd class ClearImage : public Cmd,
, public WithImage { public WithImage {
public: public:
ClearImage(Image* image, color_t color); ClearImage(Image* image, color_t color);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + (m_copy ? m_copy->getMemSize() : 0); }
return sizeof(*this) + (m_copy ? m_copy->getMemSize(): 0);
}
private: private:
ImageRef m_copy; ImageRef m_copy;
color_t m_color; color_t m_color;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/clear_mask.h" #include "app/cmd/clear_mask.h"
@ -21,13 +21,11 @@
#include "doc/mask.h" #include "doc/mask.h"
#include "doc/primitives.h" #include "doc/primitives.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
ClearMask::ClearMask(Cel* cel) ClearMask::ClearMask(Cel* cel) : WithCel(cel)
: WithCel(cel)
{ {
Doc* doc = static_cast<Doc*>(cel->document()); Doc* doc = static_cast<Doc*>(cel->document());
@ -51,8 +49,7 @@ ClearMask::ClearMask(Cel* cel)
gfx::Rect maskBounds; gfx::Rect maskBounds;
if (image->pixelFormat() == IMAGE_TILEMAP) { if (image->pixelFormat() == IMAGE_TILEMAP) {
auto grid = cel->grid(); auto grid = cel->grid();
imageBounds = gfx::Rect(grid.canvasToTile(cel->position()), imageBounds = gfx::Rect(grid.canvasToTile(cel->position()), cel->image()->size());
cel->image()->size());
maskBounds = grid.canvasToTile(mask->bounds()); maskBounds = grid.canvasToTile(mask->bounds());
m_bgcolor = doc::notile; // TODO configurable empty tile m_bgcolor = doc::notile; // TODO configurable empty tile
} }
@ -100,12 +97,11 @@ void ClearMask::clear()
Mask* mask = doc->mask(); Mask* mask = doc->mask();
Grid grid = cel->grid(); Grid grid = cel->grid();
doc::algorithm::fill_selection( doc::algorithm::fill_selection(cel->image(),
cel->image(),
cel->bounds(), cel->bounds(),
mask, mask,
m_bgcolor, m_bgcolor,
(cel->image()->isTilemap() ? &grid: nullptr)); (cel->image()->isTilemap() ? &grid : nullptr));
} }
void ClearMask::restore() void ClearMask::restore()
@ -114,11 +110,7 @@ void ClearMask::restore()
return; return;
Cel* cel = this->cel(); Cel* cel = this->cel();
copy_image(cel->image(), copy_image(cel->image(), m_copy.get(), m_cropPos.x, m_cropPos.y);
m_copy.get(),
m_cropPos.x,
m_cropPos.y);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -18,25 +18,24 @@
#include <memory> #include <memory>
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class ClearMask : public Cmd class ClearMask : public Cmd,
, public WithCel { public WithCel {
public: public:
ClearMask(Cel* cel); ClearMask(Cel* cel);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override
return sizeof(*this) + m_seq.memSize() + {
(m_copy ? m_copy->getMemSize(): 0); return sizeof(*this) + m_seq.memSize() + (m_copy ? m_copy->getMemSize() : 0);
} }
private: private:
void clear(); void clear();
void restore(); void restore();
@ -44,9 +43,8 @@ namespace cmd {
ImageRef m_copy; ImageRef m_copy;
gfx::Point m_cropPos; gfx::Point m_cropPos;
color_t m_bgcolor; color_t m_bgcolor;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/clear_rect.h" #include "app/cmd/clear_rect.h"
@ -16,8 +16,7 @@
#include "doc/layer.h" #include "doc/layer.h"
#include "doc/primitives.h" #include "doc/primitives.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -32,11 +31,8 @@ ClearRect::ClearRect(Cel* cel, const gfx::Rect& bounds)
m_offsetX = bounds.x - cel->x(); m_offsetX = bounds.x - cel->x();
m_offsetY = bounds.y - cel->y(); m_offsetY = bounds.y - cel->y();
gfx::Rect bounds2 = gfx::Rect bounds2 = image->bounds().createIntersection(
image->bounds().createIntersection( gfx::Rect(m_offsetX, m_offsetY, bounds.w, bounds.h));
gfx::Rect(
m_offsetX, m_offsetY,
bounds.w, bounds.h));
if (bounds.isEmpty()) if (bounds.isEmpty())
return; return;
@ -45,8 +41,7 @@ ClearRect::ClearRect(Cel* cel, const gfx::Rect& bounds)
Doc* doc = static_cast<Doc*>(cel->document()); Doc* doc = static_cast<Doc*>(cel->document());
m_bgcolor = doc->bgColor(cel->layer()); m_bgcolor = doc->bgColor(cel->layer());
m_copy.reset(crop_image(image, m_copy.reset(crop_image(image, bounds2.x, bounds2.y, bounds2.w, bounds2.h, m_bgcolor));
bounds2.x, bounds2.y, bounds2.w, bounds2.h, m_bgcolor));
} }
void ClearRect::onExecute() void ClearRect::onExecute()
@ -73,7 +68,8 @@ void ClearRect::onRedo()
void ClearRect::clear() void ClearRect::clear()
{ {
fill_rect(m_dstImage->image(), fill_rect(m_dstImage->image(),
m_offsetX, m_offsetY, m_offsetX,
m_offsetY,
m_offsetX + m_copy->width() - 1, m_offsetX + m_copy->width() - 1,
m_offsetY + m_copy->height() - 1, m_offsetY + m_copy->height() - 1,
m_bgcolor); m_bgcolor);
@ -84,5 +80,4 @@ void ClearRect::restore()
copy_image(m_dstImage->image(), m_copy.get(), m_offsetX, m_offsetY); copy_image(m_dstImage->image(), m_copy.get(), m_offsetX, m_offsetY);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -17,27 +17,26 @@
#include <memory> #include <memory>
namespace doc { namespace doc {
class Cel; class Cel;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class ClearRect : public Cmd { class ClearRect : public Cmd {
public: public:
ClearRect(Cel* cel, const gfx::Rect& bounds); ClearRect(Cel* cel, const gfx::Rect& bounds);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override
return sizeof(*this) + m_seq.memSize() + {
(m_copy ? m_copy->getMemSize(): 0); return sizeof(*this) + m_seq.memSize() + (m_copy ? m_copy->getMemSize() : 0);
} }
private: private:
void clear(); void clear();
void restore(); void restore();
@ -46,9 +45,8 @@ namespace cmd {
ImageRef m_copy; ImageRef m_copy;
int m_offsetX, m_offsetY; int m_offsetX, m_offsetY;
color_t m_bgcolor; color_t m_bgcolor;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/configure_background.h" #include "app/cmd/configure_background.h"
@ -16,25 +16,21 @@
#include "app/cmd/set_layer_opacity.h" #include "app/cmd/set_layer_opacity.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
ConfigureBackground::ConfigureBackground(Layer* layer) ConfigureBackground::ConfigureBackground(Layer* layer)
{ {
// Add "Background" and "LockMove" flags // Add "Background" and "LockMove" flags
LayerFlags newFlags = LayerFlags(int(layer->flags()) LayerFlags newFlags = LayerFlags(int(layer->flags()) | int(LayerFlags::BackgroundLayerFlags));
| int(LayerFlags::BackgroundLayerFlags));
add(new cmd::SetLayerFlags(layer, newFlags)); add(new cmd::SetLayerFlags(layer, newFlags));
add(new cmd::SetLayerName(layer, "Background")); add(new cmd::SetLayerName(layer, "Background"));
if (layer->isImage() && if (layer->isImage() && static_cast<LayerImage*>(layer)->opacity() < 255) {
static_cast<LayerImage*>(layer)->opacity() < 255) {
add(new cmd::SetLayerOpacity(static_cast<LayerImage*>(layer), 255)); add(new cmd::SetLayerOpacity(static_cast<LayerImage*>(layer), 255));
} }
add(new cmd::MoveLayer(layer, layer->sprite()->root(), nullptr)); add(new cmd::MoveLayer(layer, layer->sprite()->root(), nullptr));
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -11,19 +11,17 @@
#include "app/cmd_sequence.h" #include "app/cmd_sequence.h"
namespace doc { namespace doc {
class Layer; class Layer;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class ConfigureBackground : public CmdSequence { class ConfigureBackground : public CmdSequence {
public: public:
ConfigureBackground(Layer* layer); ConfigureBackground(Layer* layer);
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/convert_color_profile.h" #include "app/cmd/convert_color_profile.h"
@ -20,8 +20,7 @@
#include "os/color_space.h" #include "os/color_space.h"
#include "os/system.h" #include "os/system.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
static doc::ImageRef convert_image_color_space(const doc::Image* srcImage, static doc::ImageRef convert_image_color_space(const doc::Image* srcImage,
const gfx::ColorSpaceRef& newCS, const gfx::ColorSpaceRef& newCS,
@ -37,7 +36,7 @@ static doc::ImageRef convert_image_color_space(const doc::Image* srcImage,
} }
if (spec.colorMode() == doc::ColorMode::RGB) { if (spec.colorMode() == doc::ColorMode::RGB) {
for (int y=0; y<spec.height(); ++y) { for (int y = 0; y < spec.height(); ++y) {
conversion->convertRgba((uint32_t*)dstImage->getPixelAddress(0, y), conversion->convertRgba((uint32_t*)dstImage->getPixelAddress(0, y),
(const uint32_t*)srcImage->getPixelAddress(0, y), (const uint32_t*)srcImage->getPixelAddress(0, y),
spec.width()); spec.width());
@ -47,22 +46,22 @@ static doc::ImageRef convert_image_color_space(const doc::Image* srcImage,
// TODO create a set of functions to create pixel format // TODO create a set of functions to create pixel format
// conversions (this should be available when we add new kind of // conversions (this should be available when we add new kind of
// pixel formats). // pixel formats).
std::vector<uint8_t> buf(spec.width()*spec.height()); std::vector<uint8_t> buf(spec.width() * spec.height());
auto it = buf.begin(); auto it = buf.begin();
for (int y=0; y<spec.height(); ++y) { for (int y = 0; y < spec.height(); ++y) {
auto srcPtr = (const uint16_t*)srcImage->getPixelAddress(0, y); auto srcPtr = (const uint16_t*)srcImage->getPixelAddress(0, y);
for (int x=0; x<spec.width(); ++x, ++srcPtr, ++it) for (int x = 0; x < spec.width(); ++x, ++srcPtr, ++it)
*it = doc::graya_getv(*srcPtr); *it = doc::graya_getv(*srcPtr);
} }
conversion->convertGray(&buf[0], &buf[0], spec.width()*spec.height()); conversion->convertGray(&buf[0], &buf[0], spec.width() * spec.height());
it = buf.begin(); it = buf.begin();
for (int y=0; y<spec.height(); ++y) { for (int y = 0; y < spec.height(); ++y) {
auto srcPtr = (const uint16_t*)srcImage->getPixelAddress(0, y); auto srcPtr = (const uint16_t*)srcImage->getPixelAddress(0, y);
auto dstPtr = (uint16_t*)dstImage->getPixelAddress(0, y); auto dstPtr = (uint16_t*)dstImage->getPixelAddress(0, y);
for (int x=0; x<spec.width(); ++x, ++dstPtr, ++srcPtr, ++it) for (int x = 0; x < spec.width(); ++x, ++dstPtr, ++srcPtr, ++it)
*dstPtr = doc::graya(*it, doc::graya_geta(*srcPtr)); *dstPtr = doc::graya(*it, doc::graya_geta(*srcPtr));
} }
} }
@ -70,8 +69,7 @@ static doc::ImageRef convert_image_color_space(const doc::Image* srcImage,
return dstImage; return dstImage;
} }
void convert_color_profile(doc::Sprite* sprite, void convert_color_profile(doc::Sprite* sprite, const gfx::ColorSpaceRef& newCS)
const gfx::ColorSpaceRef& newCS)
{ {
ASSERT(sprite->colorSpace()); ASSERT(sprite->colorSpace());
ASSERT(newCS); ASSERT(newCS);
@ -89,8 +87,7 @@ void convert_color_profile(doc::Sprite* sprite,
for (Cel* cel : sprite->uniqueCels()) { for (Cel* cel : sprite->uniqueCels()) {
ImageRef old_image = cel->imageRef(); ImageRef old_image = cel->imageRef();
if (old_image.get()->pixelFormat() != IMAGE_TILEMAP) { if (old_image.get()->pixelFormat() != IMAGE_TILEMAP) {
ImageRef new_image = convert_image_color_space( ImageRef new_image = convert_image_color_space(old_image.get(), newCS, conversion.get());
old_image.get(), newCS, conversion.get());
sprite->replaceImage(old_image->id(), new_image); sprite->replaceImage(old_image->id(), new_image);
} }
@ -103,11 +100,10 @@ void convert_color_profile(doc::Sprite* sprite,
for (auto& pal : sprite->getPalettes()) { for (auto& pal : sprite->getPalettes()) {
Palette newPal(pal->frame(), pal->size()); Palette newPal(pal->frame(), pal->size());
for (int i=0; i<pal->size(); ++i) { for (int i = 0; i < pal->size(); ++i) {
color_t oldCol = pal->entry(i); color_t oldCol = pal->entry(i);
color_t newCol = pal->entry(i); color_t newCol = pal->entry(i);
conversion->convertRgba((uint32_t*)&newCol, conversion->convertRgba((uint32_t*)&newCol, (const uint32_t*)&oldCol, 1);
(const uint32_t*)&oldCol, 1);
newPal.setEntry(i, newCol); newPal.setEntry(i, newCol);
} }
@ -142,19 +138,17 @@ void convert_color_profile(doc::Image* image,
switch (image->pixelFormat()) { switch (image->pixelFormat()) {
case doc::IMAGE_RGB: case doc::IMAGE_RGB:
case doc::IMAGE_GRAYSCALE: { case doc::IMAGE_GRAYSCALE: {
ImageRef newImage = convert_image_color_space( ImageRef newImage = convert_image_color_space(image, newCS, conversion.get());
image, newCS, conversion.get());
image->copy(newImage.get(), gfx::Clip(image->bounds())); image->copy(newImage.get(), gfx::Clip(image->bounds()));
break; break;
} }
case doc::IMAGE_INDEXED: { case doc::IMAGE_INDEXED: {
for (int i=0; i<palette->size(); ++i) { for (int i = 0; i < palette->size(); ++i) {
color_t oldCol, newCol; color_t oldCol, newCol;
oldCol = newCol = palette->entry(i); oldCol = newCol = palette->entry(i);
conversion->convertRgba((uint32_t*)&newCol, conversion->convertRgba((uint32_t*)&newCol, (const uint32_t*)&oldCol, 1);
(const uint32_t*)&oldCol, 1);
palette->setEntry(i, newCol); palette->setEntry(i, newCol);
} }
break; break;
@ -184,8 +178,7 @@ ConvertColorProfile::ConvertColorProfile(doc::Sprite* sprite, const gfx::ColorSp
for (Cel* cel : sprite->uniqueCels()) { for (Cel* cel : sprite->uniqueCels()) {
ImageRef old_image = cel->imageRef(); ImageRef old_image = cel->imageRef();
if (old_image.get()->pixelFormat() != IMAGE_TILEMAP) { if (old_image.get()->pixelFormat() != IMAGE_TILEMAP) {
ImageRef new_image = convert_image_color_space( ImageRef new_image = convert_image_color_space(old_image.get(), newCS, conversion.get());
old_image.get(), newCS, conversion.get());
m_seq.add(new cmd::ReplaceImage(sprite, old_image, new_image)); m_seq.add(new cmd::ReplaceImage(sprite, old_image, new_image));
} }
@ -198,11 +191,10 @@ ConvertColorProfile::ConvertColorProfile(doc::Sprite* sprite, const gfx::ColorSp
for (auto& pal : sprite->getPalettes()) { for (auto& pal : sprite->getPalettes()) {
Palette newPal(pal->frame(), pal->size()); Palette newPal(pal->frame(), pal->size());
for (int i=0; i<pal->size(); ++i) { for (int i = 0; i < pal->size(); ++i) {
color_t oldCol = pal->entry(i); color_t oldCol = pal->entry(i);
color_t newCol = pal->entry(i); color_t newCol = pal->entry(i);
conversion->convertRgba((uint32_t*)&newCol, conversion->convertRgba((uint32_t*)&newCol, (const uint32_t*)&oldCol, 1);
(const uint32_t*)&oldCol, 1);
newPal.setEntry(i, newCol); newPal.setEntry(i, newCol);
} }
@ -230,5 +222,4 @@ void ConvertColorProfile::onRedo()
m_seq.redo(); m_seq.redo();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,45 +14,40 @@
#include "gfx/color_space.h" #include "gfx/color_space.h"
namespace gfx { namespace gfx {
class ColorSpace; class ColorSpace;
} }
namespace doc { namespace doc {
class Image; class Image;
class Palette; class Palette;
} } // namespace doc
namespace app { namespace app { namespace cmd {
namespace cmd {
class ConvertColorProfile : public Cmd, class ConvertColorProfile : public Cmd,
public WithSprite { public WithSprite {
public: public:
ConvertColorProfile(doc::Sprite* sprite, const gfx::ColorSpaceRef& newCS); ConvertColorProfile(doc::Sprite* sprite, const gfx::ColorSpaceRef& newCS);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_seq.memSize(); }
return sizeof(*this) + m_seq.memSize();
}
private: private:
CmdSequence m_seq; CmdSequence m_seq;
}; };
// Converts the sprite to the new color profile without undo information. // Converts the sprite to the new color profile without undo information.
// TODO how to merge this function with cmd::ConvertColorProfile // TODO how to merge this function with cmd::ConvertColorProfile
void convert_color_profile(doc::Sprite* sprite, void convert_color_profile(doc::Sprite* sprite, const gfx::ColorSpaceRef& newCS);
const gfx::ColorSpaceRef& newCS);
void convert_color_profile(doc::Image* image, void convert_color_profile(doc::Image* image,
doc::Palette* palette, doc::Palette* palette,
const gfx::ColorSpaceRef& oldCS, const gfx::ColorSpaceRef& oldCS,
const gfx::ColorSpaceRef& newCS); const gfx::ColorSpaceRef& newCS);
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/copy_cel.h" #include "app/cmd/copy_cel.h"
@ -27,14 +27,15 @@
#include "render/rasterize.h" #include "render/rasterize.h"
#include "render/render.h" #include "render/render.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
CopyCel::CopyCel( CopyCel::CopyCel(Layer* srcLayer,
Layer* srcLayer, frame_t srcFrame, frame_t srcFrame,
Layer* dstLayer, frame_t dstFrame, bool continuous) Layer* dstLayer,
frame_t dstFrame,
bool continuous)
: m_srcLayer(srcLayer) : m_srcLayer(srcLayer)
, m_dstLayer(dstLayer) , m_dstLayer(dstLayer)
, m_srcFrame(srcFrame) , m_srcFrame(srcFrame)
@ -73,21 +74,19 @@ void CopyCel::onExecute()
while (dstSprite->totalFrames() <= m_dstFrame) while (dstSprite->totalFrames() <= m_dstFrame)
executeAndAdd(new cmd::AddFrame(dstSprite, dstSprite->totalFrames())); executeAndAdd(new cmd::AddFrame(dstSprite, dstSprite->totalFrames()));
Image* srcImage = (srcCel ? srcCel->image(): NULL); Image* srcImage = (srcCel ? srcCel->image() : NULL);
ImageRef dstImage; ImageRef dstImage;
dstCel = dstLayer->cel(m_dstFrame); dstCel = dstLayer->cel(m_dstFrame);
if (dstCel) if (dstCel)
dstImage = dstCel->imageRef(); dstImage = dstCel->imageRef();
bool createLink = bool createLink = (srcLayer == dstLayer && m_continuous);
(srcLayer == dstLayer && m_continuous);
// For background layer // For background layer
if (dstLayer->isBackground()) { if (dstLayer->isBackground()) {
ASSERT(dstCel); ASSERT(dstCel);
ASSERT(dstImage); ASSERT(dstImage);
if (!dstCel || !dstImage || if (!dstCel || !dstImage || !srcCel || !srcImage)
!srcCel || !srcImage)
return; return;
ASSERT(!dstLayer->isTilemap()); // TODO support background tilemaps ASSERT(!dstLayer->isTilemap()); // TODO support background tilemaps
@ -102,15 +101,16 @@ void CopyCel::onExecute()
executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds()))); executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds())));
} }
else { else {
BlendMode blend = (srcLayer->isBackground() ? BlendMode blend = (srcLayer->isBackground() ? BlendMode::SRC : BlendMode::NORMAL);
BlendMode::SRC:
BlendMode::NORMAL);
ImageRef tmp(Image::createCopy(dstImage.get())); ImageRef tmp(Image::createCopy(dstImage.get()));
render::composite_image( render::composite_image(tmp.get(),
tmp.get(), srcImage, srcImage,
srcSprite->palette(m_srcFrame), srcSprite->palette(m_srcFrame),
srcCel->x(), srcCel->y(), 255, blend); srcCel->x(),
srcCel->y(),
255,
blend);
executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds()))); executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds())));
} }
} }
@ -137,15 +137,12 @@ void CopyCel::onFireNotifications()
// The m_srcLayer can be nullptr now because the layer from where we // The m_srcLayer can be nullptr now because the layer from where we
// copied this cel might not exist anymore (e.g. if we copied the // copied this cel might not exist anymore (e.g. if we copied the
// cel from another document that is already closed) // cel from another document that is already closed)
//ASSERT(m_srcLayer.layer()); // ASSERT(m_srcLayer.layer());
ASSERT(m_dstLayer.layer()); ASSERT(m_dstLayer.layer());
static_cast<Doc*>(m_dstLayer.layer()->sprite()->document()) static_cast<Doc*>(m_dstLayer.layer()->sprite()->document())
->notifyCelCopied( ->notifyCelCopied(m_srcLayer.layer(), m_srcFrame, m_dstLayer.layer(), m_dstFrame);
m_srcLayer.layer(), m_srcFrame,
m_dstLayer.layer(), m_dstFrame);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,27 +14,23 @@
#include "doc/color.h" #include "doc/color.h"
#include "doc/frame.h" #include "doc/frame.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class CopyCel : public CmdSequence { class CopyCel : public CmdSequence {
public: public:
CopyCel( CopyCel(Layer* srcLayer, frame_t srcFrame, Layer* dstLayer, frame_t dstFrame, bool continuous);
Layer* srcLayer, frame_t srcFrame,
Layer* dstLayer, frame_t dstFrame, bool continuous);
protected: protected:
void onExecute() override; void onExecute() override;
void onFireNotifications() override; void onFireNotifications() override;
private: private:
WithLayer m_srcLayer, m_dstLayer; WithLayer m_srcLayer, m_dstLayer;
frame_t m_srcFrame, m_dstFrame; frame_t m_srcFrame, m_dstFrame;
bool m_continuous; bool m_continuous;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/copy_frame.h" #include "app/cmd/copy_frame.h"
@ -14,11 +14,10 @@
#include "app/cmd/add_frame.h" #include "app/cmd/add_frame.h"
#include "app/cmd/copy_cel.h" #include "app/cmd/copy_cel.h"
#include "app/cmd/set_frame_duration.h" #include "app/cmd/set_frame_duration.h"
#include "doc/sprite.h"
#include "doc/layer.h" #include "doc/layer.h"
#include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -41,5 +40,4 @@ void CopyFrame::onExecute()
// Do not copy cels (cmd::CopyCel must be called from outside) // Do not copy cels (cmd::CopyCel must be called from outside)
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -8,32 +8,30 @@
#define APP_CMD_COPY_FRAME_H_INCLUDED #define APP_CMD_COPY_FRAME_H_INCLUDED
#pragma once #pragma once
#include "app/cmd_sequence.h"
#include "app/cmd/with_sprite.h" #include "app/cmd/with_sprite.h"
#include "app/cmd_sequence.h"
#include "doc/frame.h" #include "doc/frame.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class CopyFrame : public CmdSequence class CopyFrame : public CmdSequence,
, public WithSprite { public WithSprite {
public: public:
CopyFrame(Sprite* sprite, frame_t fromFrame, frame_t newFrame); CopyFrame(Sprite* sprite, frame_t fromFrame, frame_t newFrame);
protected: protected:
void onExecute() override; void onExecute() override;
size_t onMemSize() const override { size_t onMemSize() const override
return sizeof(*this) + {
CmdSequence::onMemSize() - sizeof(CmdSequence); return sizeof(*this) + CmdSequence::onMemSize() - sizeof(CmdSequence);
} }
private: private:
frame_t m_fromFrame; frame_t m_fromFrame;
frame_t m_newFrame; frame_t m_newFrame;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/copy_rect.h" #include "app/cmd/copy_rect.h"
@ -15,16 +15,13 @@
#include <algorithm> #include <algorithm>
namespace app { namespace app { namespace cmd {
namespace cmd {
CopyRect::CopyRect(Image* dst, const Image* src, const gfx::Clip& clip) CopyRect::CopyRect(Image* dst, const Image* src, const gfx::Clip& clip)
: WithImage(dst) : WithImage(dst)
, m_clip(clip) , m_clip(clip)
{ {
if (!m_clip.clip( if (!m_clip.clip(dst->width(), dst->height(), src->width(), src->height()))
dst->width(), dst->height(),
src->width(), src->height()))
return; return;
// Fill m_data with "src" data // Fill m_data with "src" data
@ -33,11 +30,10 @@ CopyRect::CopyRect(Image* dst, const Image* src, const gfx::Clip& clip)
m_data.resize(lineSize * m_clip.size.h); m_data.resize(lineSize * m_clip.size.h);
auto it = m_data.begin(); auto it = m_data.begin();
for (int v=0; v<m_clip.size.h; ++v) { for (int v = 0; v < m_clip.size.h; ++v) {
uint8_t* addr = src->getPixelAddress( uint8_t* addr = src->getPixelAddress(m_clip.dst.x, m_clip.dst.y + v);
m_clip.dst.x, m_clip.dst.y+v);
std::copy(addr, addr+lineSize, it); std::copy(addr, addr + lineSize, it);
it += lineSize; it += lineSize;
} }
} }
@ -67,12 +63,11 @@ void CopyRect::swap()
std::vector<uint8_t> tmp(lineSize); std::vector<uint8_t> tmp(lineSize);
auto it = m_data.begin(); auto it = m_data.begin();
for (int v=0; v<m_clip.size.h; ++v) { for (int v = 0; v < m_clip.size.h; ++v) {
uint8_t* addr = image->getPixelAddress( uint8_t* addr = image->getPixelAddress(m_clip.dst.x, m_clip.dst.y + v);
m_clip.dst.x, m_clip.dst.y+v);
std::copy(addr, addr+lineSize, tmp.begin()); std::copy(addr, addr + lineSize, tmp.begin());
std::copy(it, it+lineSize, addr); std::copy(it, it + lineSize, addr);
std::copy(tmp.begin(), tmp.end(), it); std::copy(tmp.begin(), tmp.end(), it);
it += lineSize; it += lineSize;
@ -86,5 +81,4 @@ int CopyRect::lineSize()
return image()->bytesPerPixel() * m_clip.size.w; return image()->bytesPerPixel() * m_clip.size.w;
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -15,35 +15,31 @@
#include <vector> #include <vector>
namespace doc { namespace doc {
class Image; class Image;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class CopyRect : public Cmd class CopyRect : public Cmd,
, public WithImage { public WithImage {
public: public:
CopyRect(Image* dst, const Image* src, const gfx::Clip& clip); CopyRect(Image* dst, const Image* src, const gfx::Clip& clip);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_data.size(); }
return sizeof(*this) + m_data.size();
}
private: private:
void swap(); void swap();
int lineSize(); int lineSize();
gfx::Clip m_clip; gfx::Clip m_clip;
std::vector<uint8_t> m_data; std::vector<uint8_t> m_data;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/copy_region.h" #include "app/cmd/copy_region.h"
@ -17,10 +17,10 @@
#include "doc/sprite.h" #include "doc/sprite.h"
#include "doc/tileset.h" #include "doc/tileset.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
CopyRegion::CopyRegion(Image* dst, const Image* src, CopyRegion::CopyRegion(Image* dst,
const Image* src,
const gfx::Region& region, const gfx::Region& region,
const gfx::Point& dstPos, const gfx::Point& dstPos,
bool alreadyCopied) bool alreadyCopied)
@ -30,12 +30,8 @@ CopyRegion::CopyRegion(Image* dst, const Image* src,
ASSERT(!region.isEmpty()); ASSERT(!region.isEmpty());
gfx::Rect rc = region.bounds(); gfx::Rect rc = region.bounds();
gfx::Clip clip( gfx::Clip clip(rc.x + dstPos.x, rc.y + dstPos.y, rc.x, rc.y, rc.w, rc.h);
rc.x+dstPos.x, rc.y+dstPos.y, if (clip.clip(dst->width(), dst->height(), src->width(), src->height())) {
rc.x, rc.y, rc.w, rc.h);
if (clip.clip(
dst->width(), dst->height(),
src->width(), src->height())) {
// Create region to save/swap later // Create region to save/swap later
m_region = region; m_region = region;
m_region.offset(dstPos); m_region.offset(dstPos);
@ -45,7 +41,8 @@ CopyRegion::CopyRegion(Image* dst, const Image* src,
save_image_region_in_buffer(m_region, src, dstPos, m_buffer); save_image_region_in_buffer(m_region, src, dstPos, m_buffer);
} }
CopyTileRegion::CopyTileRegion(Image* dst, const Image* src, CopyTileRegion::CopyTileRegion(Image* dst,
const Image* src,
const gfx::Region& region, const gfx::Region& region,
const gfx::Point& dstPos, const gfx::Point& dstPos,
bool alreadyCopied, bool alreadyCopied,
@ -53,7 +50,7 @@ CopyTileRegion::CopyTileRegion(Image* dst, const Image* src,
const doc::Tileset* tileset) const doc::Tileset* tileset)
: CopyRegion(dst, src, region, dstPos, alreadyCopied) : CopyRegion(dst, src, region, dstPos, alreadyCopied)
, m_tileIndex(tileIndex) , m_tileIndex(tileIndex)
, m_tilesetId(tileset ? tileset->id(): NullId) , m_tilesetId(tileset ? tileset->id() : NullId)
{ {
} }
@ -96,11 +93,9 @@ void CopyTileRegion::rehash()
tileset->notifyTileContentChange(m_tileIndex); tileset->notifyTileContentChange(m_tileIndex);
// Notify that the tileset changed // Notify that the tileset changed
static_cast<Doc*>(tileset->sprite()->document()) static_cast<Doc*>(tileset->sprite()->document())->notifyTilesetChanged(tileset);
->notifyTilesetChanged(tileset);
} }
} }
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -17,59 +17,57 @@
#include "gfx/region.h" #include "gfx/region.h"
namespace doc { namespace doc {
class Tileset; class Tileset;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class CopyRegion : public Cmd class CopyRegion : public Cmd,
, public WithImage { public WithImage {
public: public:
// If alreadyCopied is false, it means that onExecute() will copy // If alreadyCopied is false, it means that onExecute() will copy
// pixels from src to dst. If it's true, it means that "onExecute" // pixels from src to dst. If it's true, it means that "onExecute"
// should do nothing, because modified pixels are alreadt on "dst" // should do nothing, because modified pixels are alreadt on "dst"
// (so we use "src" as the original image). // (so we use "src" as the original image).
CopyRegion(Image* dst, const Image* src, CopyRegion(Image* dst,
const Image* src,
const gfx::Region& region, const gfx::Region& region,
const gfx::Point& dstPos, const gfx::Point& dstPos,
bool alreadyCopied = false); bool alreadyCopied = false);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_buffer.size(); }
return sizeof(*this) + m_buffer.size();
}
private: private:
void swap(); void swap();
virtual void rehash() { } virtual void rehash() {}
bool m_alreadyCopied; bool m_alreadyCopied;
gfx::Region m_region; gfx::Region m_region;
base::buffer m_buffer; base::buffer m_buffer;
}; };
class CopyTileRegion : public CopyRegion { class CopyTileRegion : public CopyRegion {
public: public:
CopyTileRegion(Image* dst, const Image* src, CopyTileRegion(Image* dst,
const Image* src,
const gfx::Region& region, const gfx::Region& region,
const gfx::Point& dstPos, const gfx::Point& dstPos,
bool alreadyCopied, bool alreadyCopied,
const doc::tile_index tileIndex, const doc::tile_index tileIndex,
const doc::Tileset* tileset); const doc::Tileset* tileset);
private: private:
void rehash() override; void rehash() override;
doc::tile_index m_tileIndex; doc::tile_index m_tileIndex;
doc::ObjectId m_tilesetId; doc::ObjectId m_tilesetId;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/crop_cel.h" #include "app/cmd/crop_cel.h"
@ -16,8 +16,7 @@
#include "doc/layer_tilemap.h" #include "doc/layer_tilemap.h"
#include "doc/primitives.h" #include "doc/primitives.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -45,8 +44,7 @@ void CropCel::onUndo()
} }
// Crops the cel image leaving the same ID in the image. // Crops the cel image leaving the same ID in the image.
void CropCel::cropImage(const gfx::Point& origin, void CropCel::cropImage(const gfx::Point& origin, const gfx::Rect& bounds)
const gfx::Rect& bounds)
{ {
Cel* cel = this->cel(); Cel* cel = this->cel();
@ -60,8 +58,10 @@ void CropCel::cropImage(const gfx::Point& origin,
} }
if (bounds != cel->image()->bounds()) { if (bounds != cel->image()->bounds()) {
ImageRef image(crop_image(cel->image(), ImageRef image(crop_image(cel->image(),
localBounds.x, localBounds.y, localBounds.x,
localBounds.w, localBounds.h, localBounds.y,
localBounds.w,
localBounds.h,
cel->image()->maskColor())); cel->image()->maskColor()));
ObjectId id = cel->image()->id(); ObjectId id = cel->image()->id();
ObjectVersion ver = cel->image()->version(); ObjectVersion ver = cel->image()->version();
@ -80,5 +80,4 @@ void CropCel::cropImage(const gfx::Point& origin,
} }
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,32 +14,27 @@
#include "gfx/point.h" #include "gfx/point.h"
#include "gfx/rect.h" #include "gfx/rect.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
class CropCel : public Cmd class CropCel : public Cmd,
, public WithCel { public WithCel {
public: public:
CropCel(doc::Cel* cel, const gfx::Rect& newBounds); CropCel(doc::Cel* cel, const gfx::Rect& newBounds);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this); }
return sizeof(*this);
}
private: private:
void cropImage(const gfx::Point& origin, void cropImage(const gfx::Point& origin, const gfx::Rect& bounds);
const gfx::Rect& bounds);
gfx::Point m_oldOrigin; gfx::Point m_oldOrigin;
gfx::Point m_newOrigin; gfx::Point m_newOrigin;
gfx::Rect m_oldBounds; gfx::Rect m_oldBounds;
gfx::Rect m_newBounds; gfx::Rect m_newBounds;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/deselect_mask.h" #include "app/cmd/deselect_mask.h"
@ -15,18 +15,16 @@
#include "app/doc.h" #include "app/doc.h"
#include "doc/mask.h" #include "doc/mask.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
DeselectMask::DeselectMask(Doc* doc) DeselectMask::DeselectMask(Doc* doc) : WithDocument(doc)
: WithDocument(doc)
{ {
} }
void DeselectMask::onExecute() void DeselectMask::onExecute()
{ {
Doc* doc = document(); Doc* doc = document();
m_oldMask.reset(doc->isMaskVisible() ? new Mask(*doc->mask()): nullptr); m_oldMask.reset(doc->isMaskVisible() ? new Mask(*doc->mask()) : nullptr);
doc->setMaskVisible(false); doc->setMaskVisible(false);
doc->notifySelectionChanged(); doc->notifySelectionChanged();
} }
@ -46,8 +44,7 @@ void DeselectMask::onUndo()
size_t DeselectMask::onMemSize() const size_t DeselectMask::onMemSize() const
{ {
return sizeof(*this) + (m_oldMask ? m_oldMask->getMemSize(): 0); return sizeof(*this) + (m_oldMask ? m_oldMask->getMemSize() : 0);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,28 +14,26 @@
#include <memory> #include <memory>
namespace doc { namespace doc {
class Mask; class Mask;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class DeselectMask : public Cmd class DeselectMask : public Cmd,
, public WithDocument { public WithDocument {
public: public:
DeselectMask(Doc* doc); DeselectMask(Doc* doc);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override; size_t onMemSize() const override;
private: private:
std::unique_ptr<Mask> m_oldMask; std::unique_ptr<Mask> m_oldMask;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,24 +6,24 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/flatten_layers.h" #include "app/cmd/flatten_layers.h"
#include "app/cmd/add_layer.h"
#include "app/cmd/add_cel.h" #include "app/cmd/add_cel.h"
#include "app/cmd/add_layer.h"
#include "app/cmd/configure_background.h" #include "app/cmd/configure_background.h"
#include "app/cmd/move_layer.h" #include "app/cmd/move_layer.h"
#include "app/cmd/remove_layer.h"
#include "app/cmd/remove_cel.h" #include "app/cmd/remove_cel.h"
#include "app/cmd/remove_layer.h"
#include "app/cmd/replace_image.h" #include "app/cmd/replace_image.h"
#include "app/cmd/set_cel_opacity.h"
#include "app/cmd/set_cel_position.h"
#include "app/cmd/set_cel_zindex.h"
#include "app/cmd/set_layer_blend_mode.h"
#include "app/cmd/set_layer_name.h" #include "app/cmd/set_layer_name.h"
#include "app/cmd/set_layer_opacity.h" #include "app/cmd/set_layer_opacity.h"
#include "app/cmd/set_layer_blend_mode.h"
#include "app/cmd/set_cel_opacity.h"
#include "app/cmd/set_cel_zindex.h"
#include "app/cmd/set_cel_position.h"
#include "app/cmd/unlink_cel.h" #include "app/cmd/unlink_cel.h"
#include "app/doc.h" #include "app/doc.h"
#include "app/i18n/strings.h" #include "app/i18n/strings.h"
@ -37,8 +37,7 @@
#include <algorithm> #include <algorithm>
namespace app { namespace app { namespace cmd {
namespace cmd {
FlattenLayers::FlattenLayers(doc::Sprite* sprite, FlattenLayers::FlattenLayers(doc::Sprite* sprite,
const doc::SelectedLayers& layers0, const doc::SelectedLayers& layers0,
@ -79,7 +78,7 @@ void FlattenLayers::onExecute()
ImageSpec spec = sprite->spec(); ImageSpec spec = sprite->spec();
gfx::Rect area; gfx::Rect area;
if (m_options.dynamicCanvas) { if (m_options.dynamicCanvas) {
for (frame_t frame(0); frame<sprite->totalFrames(); ++frame) { for (frame_t frame(0); frame < sprite->totalFrames(); ++frame) {
for (Layer* layer : layers) { for (Layer* layer : layers) {
Cel* cel = layer->cel(frame); Cel* cel = layer->cel(frame);
if (cel) if (cel)
@ -136,11 +135,10 @@ void FlattenLayers::onExecute()
const gfx::ClipF area_to_image(0, 0, area); const gfx::ClipF area_to_image(0, 0, area);
// Copy all frames to the background. // Copy all frames to the background.
for (frame_t frame(0); frame<sprite->totalFrames(); ++frame) { for (frame_t frame(0); frame < sprite->totalFrames(); ++frame) {
// If the flatLayer is the only cel in this frame, we can skip // If the flatLayer is the only cel in this frame, we can skip
// this frame to keep existing links in the flatLayer. // this frame to keep existing links in the flatLayer.
const bool anotherCelExists = const bool anotherCelExists = std::any_of(visibleLayers.begin(),
std::any_of(visibleLayers.begin(),
visibleLayers.end(), visibleLayers.end(),
[flatLayer, frame](const Layer* other) { [flatLayer, frame](const Layer* other) {
return (flatLayer != other && other->cel(frame)); return (flatLayer != other && other->cel(frame));
@ -154,9 +152,11 @@ void FlattenLayers::onExecute()
// Get exact bounds for rendered frame // Get exact bounds for rendered frame
gfx::Rect bounds = image->bounds(); gfx::Rect bounds = image->bounds();
const bool shrink = doc::algorithm::shrink_bounds( const bool shrink = doc::algorithm::shrink_bounds(image.get(),
image.get(), image->maskColor(), nullptr, image->maskColor(),
image->bounds(), bounds); nullptr,
image->bounds(),
bounds);
// Skip when fully transparent // Skip when fully transparent
Cel* cel = flatLayer->cel(frame); Cel* cel = flatLayer->cel(frame);
@ -168,12 +168,10 @@ void FlattenLayers::onExecute()
} }
// Apply shrunk bounds to new image // Apply shrunk bounds to new image
const ImageRef new_image(doc::crop_image( const ImageRef new_image(doc::crop_image(image.get(), bounds, image->maskColor()));
image.get(), bounds, image->maskColor()));
// Replace image on existing cel // Replace image on existing cel
if (cel) { if (cel) {
// TODO Keep cel links when possible // TODO Keep cel links when possible
if (cel->links()) if (cel->links())
@ -190,8 +188,7 @@ void FlattenLayers::onExecute()
if (cel->zIndex() != 0) if (cel->zIndex() != 0)
executeAndAdd(new cmd::SetCelZIndex(cel, 0)); executeAndAdd(new cmd::SetCelZIndex(cel, 0));
executeAndAdd(new cmd::SetCelPosition(cel, executeAndAdd(new cmd::SetCelPosition(cel, area.x + bounds.x, area.y + bounds.y));
area.x+bounds.x, area.y+bounds.y));
} }
// Modify destination cel // Modify destination cel
@ -200,7 +197,7 @@ void FlattenLayers::onExecute()
// Add new cel on null // Add new cel on null
else { else {
cel = new Cel(frame, new_image); cel = new Cel(frame, new_image);
cel->setPosition(area.x+bounds.x, area.y+bounds.y); cel->setPosition(area.x + bounds.x, area.y + bounds.y);
// No need to undo adding this cel when flattening onto // No need to undo adding this cel when flattening onto
// a new layer, as the layer itself would be destroyed, // a new layer, as the layer itself would be destroyed,
@ -221,9 +218,7 @@ void FlattenLayers::onExecute()
// Add new flatten layer // Add new flatten layer
if (newFlatLayer) { if (newFlatLayer) {
executeAndAdd(new cmd::AddLayer( executeAndAdd(new cmd::AddLayer(list.front()->parent(), flatLayer, list.front()));
list.front()->parent(), flatLayer, list.front()));
} }
// Reset layer properties when flattening in-place // Reset layer properties when flattening in-place
else { else {
@ -231,8 +226,7 @@ void FlattenLayers::onExecute()
executeAndAdd(new cmd::SetLayerOpacity(flatLayer, 255)); executeAndAdd(new cmd::SetLayerOpacity(flatLayer, 255));
if (flatLayer->blendMode() != doc::BlendMode::NORMAL) if (flatLayer->blendMode() != doc::BlendMode::NORMAL)
executeAndAdd(new cmd::SetLayerBlendMode( executeAndAdd(new cmd::SetLayerBlendMode(flatLayer, doc::BlendMode::NORMAL));
flatLayer, doc::BlendMode::NORMAL));
} }
// Delete flattened layers. // Delete flattened layers.
@ -245,5 +239,4 @@ void FlattenLayers::onExecute()
} }
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,40 +14,30 @@
#include "doc/object_ids.h" #include "doc/object_ids.h"
#include "doc/selected_layers.h" #include "doc/selected_layers.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
class FlattenLayers : public CmdSequence
, public WithSprite {
public:
class FlattenLayers : public CmdSequence,
public WithSprite {
public:
struct Options { struct Options {
bool newBlendMethod: 1; bool newBlendMethod : 1;
bool inplace: 1; bool inplace : 1;
bool mergeDown: 1; bool mergeDown : 1;
bool dynamicCanvas: 1; bool dynamicCanvas : 1;
Options(): Options() : newBlendMethod(false), inplace(false), mergeDown(false), dynamicCanvas(false) {}
newBlendMethod(false),
inplace(false),
mergeDown(false),
dynamicCanvas(false) {
}
}; };
FlattenLayers(doc::Sprite* sprite, FlattenLayers(doc::Sprite* sprite, const doc::SelectedLayers& layers, const Options options);
const doc::SelectedLayers& layers,
const Options options);
protected: protected:
void onExecute() override; void onExecute() override;
private: private:
doc::ObjectIds m_layerIds; doc::ObjectIds m_layerIds;
Options m_options; Options m_options;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,16 +5,15 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/flip_image.h" #include "app/cmd/flip_image.h"
#include "doc/image.h"
#include "doc/algorithm/flip_image.h" #include "doc/algorithm/flip_image.h"
#include "doc/image.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
FlipImage::FlipImage(Image* image, const gfx::Rect& bounds, doc::algorithm::FlipType flipType) FlipImage::FlipImage(Image* image, const gfx::Rect& bounds, doc::algorithm::FlipType flipType)
: WithImage(image) : WithImage(image)
@ -43,5 +42,4 @@ void FlipImage::swap()
image->incrementVersion(); image->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -16,34 +16,29 @@
#include <vector> #include <vector>
namespace doc { namespace doc {
class Image; class Image;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class FlipImage : public Cmd class FlipImage : public Cmd,
, public WithImage { public WithImage {
public: public:
FlipImage(Image* image, const gfx::Rect& bounds, FlipImage(Image* image, const gfx::Rect& bounds, doc::algorithm::FlipType flipType);
doc::algorithm::FlipType flipType);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this); }
return sizeof(*this);
}
private: private:
void swap(); void swap();
gfx::Rect m_bounds; gfx::Rect m_bounds;
doc::algorithm::FlipType m_flipType; doc::algorithm::FlipType m_flipType;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/flip_mask.h" #include "app/cmd/flip_mask.h"
@ -15,8 +15,7 @@
#include "doc/algorithm/flip_image.h" #include "doc/algorithm/flip_image.h"
#include "doc/mask.h" #include "doc/mask.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -46,12 +45,10 @@ void FlipMask::swap()
return; return;
mask->freeze(); mask->freeze();
doc::algorithm::flip_image(mask->bitmap(), doc::algorithm::flip_image(mask->bitmap(), mask->bitmap()->bounds(), m_flipType);
mask->bitmap()->bounds(), m_flipType);
mask->unfreeze(); mask->unfreeze();
doc->notifySelectionChanged(); doc->notifySelectionChanged();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -12,29 +12,25 @@
#include "app/cmd/with_document.h" #include "app/cmd/with_document.h"
#include "doc/algorithm/flip_type.h" #include "doc/algorithm/flip_type.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class FlipMask : public Cmd class FlipMask : public Cmd,
, public WithDocument { public WithDocument {
public: public:
FlipMask(Doc* doc, doc::algorithm::FlipType flipType); FlipMask(Doc* doc, doc::algorithm::FlipType flipType);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this); }
return sizeof(*this);
}
private: private:
void swap(); void swap();
doc::algorithm::FlipType m_flipType; doc::algorithm::FlipType m_flipType;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/flip_masked_cel.h" #include "app/cmd/flip_masked_cel.h"
@ -19,8 +19,7 @@
#include "doc/layer.h" #include "doc/layer.h"
#include "doc/mask.h" #include "doc/mask.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
FlipMaskedCel::FlipMaskedCel(Cel* cel, doc::algorithm::FlipType flipType) FlipMaskedCel::FlipMaskedCel(Cel* cel, doc::algorithm::FlipType flipType)
{ {
@ -36,16 +35,13 @@ FlipMaskedCel::FlipMaskedCel(Cel* cel, doc::algorithm::FlipType flipType)
int x = cel->x(); int x = cel->x();
int y = cel->y(); int y = cel->y();
mask->offsetOrigin(-x, -y); mask->offsetOrigin(-x, -y);
doc::algorithm::flip_image_with_mask( doc::algorithm::flip_image_with_mask(copy.get(), mask, flipType, bgcolor);
copy.get(), mask, flipType, bgcolor);
mask->offsetOrigin(x, y); mask->offsetOrigin(x, y);
int x1, y1, x2, y2; int x1, y1, x2, y2;
if (get_shrink_rect2(&x1, &y1, &x2, &y2, image, copy.get())) { if (get_shrink_rect2(&x1, &y1, &x2, &y2, image, copy.get())) {
add(new cmd::CopyRect(image, copy.get(), add(new cmd::CopyRect(image, copy.get(), gfx::Clip(x1, y1, x1, y1, x2 - x1 + 1, y2 - y1 + 1)));
gfx::Clip(x1, y1, x1, y1, x2-x1+1, y2-y1+1)));
} }
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -13,19 +13,17 @@
#include "doc/color.h" #include "doc/color.h"
namespace doc { namespace doc {
class Cel; class Cel;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class FlipMaskedCel : public CmdSequence { class FlipMaskedCel : public CmdSequence {
public: public:
FlipMaskedCel(Cel* cel, doc::algorithm::FlipType flipType); FlipMaskedCel(Cel* cel, doc::algorithm::FlipType flipType);
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/layer_from_background.h" #include "app/cmd/layer_from_background.h"
@ -15,8 +15,7 @@
#include "doc/layer.h" #include "doc/layer.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
LayerFromBackground::LayerFromBackground(Layer* layer) LayerFromBackground::LayerFromBackground(Layer* layer)
{ {
@ -29,12 +28,10 @@ LayerFromBackground::LayerFromBackground(Layer* layer)
ASSERT(layer->sprite()->backgroundLayer() != NULL); ASSERT(layer->sprite()->backgroundLayer() != NULL);
// Remove "Background" and "LockMove" flags // Remove "Background" and "LockMove" flags
LayerFlags newFlags = LayerFlags(int(layer->flags()) LayerFlags newFlags = LayerFlags(int(layer->flags()) & ~int(LayerFlags::BackgroundLayerFlags));
& ~int(LayerFlags::BackgroundLayerFlags));
add(new cmd::SetLayerFlags(layer, newFlags)); add(new cmd::SetLayerFlags(layer, newFlags));
add(new cmd::SetLayerName(layer, "Layer 0")); add(new cmd::SetLayerName(layer, "Layer 0"));
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -11,19 +11,17 @@
#include "app/cmd_sequence.h" #include "app/cmd_sequence.h"
namespace doc { namespace doc {
class Layer; class Layer;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class LayerFromBackground : public CmdSequence { class LayerFromBackground : public CmdSequence {
public: public:
LayerFromBackground(Layer* layer); LayerFromBackground(Layer* layer);
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/move_cel.h" #include "app/cmd/move_cel.h"
@ -29,14 +29,15 @@
#include "render/rasterize.h" #include "render/rasterize.h"
#include "render/render.h" #include "render/render.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
MoveCel::MoveCel( MoveCel::MoveCel(LayerImage* srcLayer,
LayerImage* srcLayer, frame_t srcFrame, frame_t srcFrame,
LayerImage* dstLayer, frame_t dstFrame, bool continuous) LayerImage* dstLayer,
frame_t dstFrame,
bool continuous)
: m_srcLayer(srcLayer) : m_srcLayer(srcLayer)
, m_dstLayer(dstLayer) , m_dstLayer(dstLayer)
, m_srcFrame(srcFrame) , m_srcFrame(srcFrame)
@ -75,21 +76,19 @@ void MoveCel::onExecute()
while (dstSprite->totalFrames() <= m_dstFrame) while (dstSprite->totalFrames() <= m_dstFrame)
executeAndAdd(new cmd::AddFrame(dstSprite, dstSprite->totalFrames())); executeAndAdd(new cmd::AddFrame(dstSprite, dstSprite->totalFrames()));
Image* srcImage = (srcCel ? srcCel->image(): NULL); Image* srcImage = (srcCel ? srcCel->image() : NULL);
ImageRef dstImage; ImageRef dstImage;
dstCel = dstLayer->cel(m_dstFrame); dstCel = dstLayer->cel(m_dstFrame);
if (dstCel) if (dstCel)
dstImage = dstCel->imageRef(); dstImage = dstCel->imageRef();
bool createLink = bool createLink = (srcLayer == dstLayer && m_continuous);
(srcLayer == dstLayer && m_continuous);
// For background layer // For background layer
if (dstLayer->isBackground()) { if (dstLayer->isBackground()) {
ASSERT(dstCel); ASSERT(dstCel);
ASSERT(dstImage); ASSERT(dstImage);
if (!dstCel || !dstImage || if (!dstCel || !dstImage || !srcCel || !srcImage)
!srcCel || !srcImage)
return; return;
ASSERT(!dstLayer->isTilemap()); // TODO support background tilemaps ASSERT(!dstLayer->isTilemap()); // TODO support background tilemaps
@ -105,15 +104,16 @@ void MoveCel::onExecute()
executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds()))); executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds())));
} }
else { else {
BlendMode blend = (srcLayer->isBackground() ? BlendMode blend = (srcLayer->isBackground() ? BlendMode::SRC : BlendMode::NORMAL);
BlendMode::SRC:
BlendMode::NORMAL);
ImageRef tmp(Image::createCopy(dstImage.get())); ImageRef tmp(Image::createCopy(dstImage.get()));
render::composite_image( render::composite_image(tmp.get(),
tmp.get(), srcImage, srcImage,
srcSprite->palette(m_srcFrame), srcSprite->palette(m_srcFrame),
srcCel->x(), srcCel->y(), 255, blend); srcCel->x(),
srcCel->y(),
255,
blend);
executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds()))); executeAndAdd(new cmd::CopyRect(dstImage.get(), tmp.get(), gfx::Clip(tmp->bounds())));
} }
executeAndAdd(new cmd::ClearCel(srcCel)); executeAndAdd(new cmd::ClearCel(srcCel));
@ -141,10 +141,7 @@ void MoveCel::onFireNotifications()
{ {
CmdSequence::onFireNotifications(); CmdSequence::onFireNotifications();
static_cast<Doc*>(m_dstLayer.layer()->sprite()->document()) static_cast<Doc*>(m_dstLayer.layer()->sprite()->document())
->notifyCelMoved( ->notifyCelMoved(m_srcLayer.layer(), m_srcFrame, m_dstLayer.layer(), m_dstFrame);
m_srcLayer.layer(), m_srcFrame,
m_dstLayer.layer(), m_dstFrame);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,30 +14,30 @@
#include "doc/frame.h" #include "doc/frame.h"
namespace doc { namespace doc {
class LayerImage; class LayerImage;
} }
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class MoveCel : public CmdSequence { class MoveCel : public CmdSequence {
public: public:
MoveCel( MoveCel(LayerImage* srcLayer,
LayerImage* srcLayer, frame_t srcFrame, frame_t srcFrame,
LayerImage* dstLayer, frame_t dstFrame, bool continuous); LayerImage* dstLayer,
frame_t dstFrame,
bool continuous);
protected: protected:
void onExecute() override; void onExecute() override;
void onFireNotifications() override; void onFireNotifications() override;
private: private:
WithLayer m_srcLayer, m_dstLayer; WithLayer m_srcLayer, m_dstLayer;
frame_t m_srcFrame, m_dstFrame; frame_t m_srcFrame, m_dstFrame;
bool m_continuous; bool m_continuous;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/move_layer.h" #include "app/cmd/move_layer.h"
@ -15,19 +15,16 @@
#include "doc/layer.h" #include "doc/layer.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
MoveLayer::MoveLayer(Layer* layer, MoveLayer::MoveLayer(Layer* layer, Layer* newParent, Layer* afterThis)
Layer* newParent,
Layer* afterThis)
: m_layer(layer) : m_layer(layer)
, m_oldParent(layer->parent()) , m_oldParent(layer->parent())
, m_oldAfterThis(layer->getPrevious()) , m_oldAfterThis(layer->getPrevious())
, m_newParent(newParent) , m_newParent(newParent)
, m_newAfterThis(afterThis == layer ? afterThis->getPrevious(): afterThis) , m_newAfterThis(afterThis == layer ? afterThis->getPrevious() : afterThis)
{ {
} }
@ -99,5 +96,4 @@ void MoveLayer::onFireNotifications()
doc->notify_observers<DocEvent&>(&DocObserver::onLayerRestacked, ev); doc->notify_observers<DocEvent&>(&DocObserver::onLayerRestacked, ev);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -11,31 +11,25 @@
#include "app/cmd.h" #include "app/cmd.h"
#include "app/cmd/with_layer.h" #include "app/cmd/with_layer.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class MoveLayer : public Cmd { class MoveLayer : public Cmd {
public: public:
MoveLayer(Layer* layer, MoveLayer(Layer* layer, Layer* newParent, Layer* afterThis);
Layer* newParent,
Layer* afterThis);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onFireNotifications() override; void onFireNotifications() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this); }
return sizeof(*this);
}
private: private:
WithLayer m_layer; WithLayer m_layer;
WithLayer m_oldParent, m_oldAfterThis; WithLayer m_oldParent, m_oldAfterThis;
WithLayer m_newParent, m_newAfterThis; WithLayer m_newParent, m_newAfterThis;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -6,7 +6,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/patch_cel.h" #include "app/cmd/patch_cel.h"
@ -17,8 +17,7 @@
#include "doc/cel.h" #include "doc/cel.h"
#include "doc/layer_tilemap.h" #include "doc/layer_tilemap.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -57,17 +56,10 @@ void PatchCel::onExecute()
if (cel->image()->pixelFormat() == IMAGE_TILEMAP) { if (cel->image()->pixelFormat() == IMAGE_TILEMAP) {
executeAndAdd( executeAndAdd(
new CopyRegion(cel->image(), new CopyRegion(cel->image(), m_patch, regionInTiles, -grid.canvasToTile(cel->position())));
m_patch,
regionInTiles,
-grid.canvasToTile(cel->position())));
} }
else { else {
executeAndAdd( executeAndAdd(new CopyRegion(cel->image(), m_patch, m_region, m_pos - cel->position()));
new CopyRegion(cel->image(),
m_patch,
m_region,
m_pos - cel->position()));
} }
executeAndAdd(new TrimCel(cel)); executeAndAdd(new TrimCel(cel));
@ -75,5 +67,4 @@ void PatchCel::onExecute()
m_patch = nullptr; m_patch = nullptr;
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -14,30 +14,28 @@
#include "gfx/point.h" #include "gfx/point.h"
namespace doc { namespace doc {
class Cel; class Cel;
class Image; class Image;
} } // namespace doc
namespace app { namespace app { namespace cmd {
namespace cmd {
class PatchCel : public CmdSequence class PatchCel : public CmdSequence,
, public WithCel { public WithCel {
public: public:
PatchCel(doc::Cel* dstCel, PatchCel(doc::Cel* dstCel,
const doc::Image* patch, const doc::Image* patch,
const gfx::Region& patchedRegion, const gfx::Region& patchedRegion,
const gfx::Point& patchPos); const gfx::Point& patchPos);
protected: protected:
void onExecute() override; void onExecute() override;
const doc::Image* m_patch; const doc::Image* m_patch;
const gfx::Region& m_region; const gfx::Region& m_region;
gfx::Point m_pos; gfx::Point m_pos;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/remap_colors.h" #include "app/cmd/remap_colors.h"
@ -16,14 +16,11 @@
#include "doc/remap.h" #include "doc/remap.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
RemapColors::RemapColors(Sprite* sprite, const Remap& remap) RemapColors::RemapColors(Sprite* sprite, const Remap& remap) : WithSprite(sprite), m_remap(remap)
: WithSprite(sprite)
, m_remap(remap)
{ {
} }
@ -51,5 +48,4 @@ void RemapColors::incrementVersions(Sprite* spr)
cel->image()->incrementVersion(); cel->image()->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -12,29 +12,25 @@
#include "app/cmd/with_sprite.h" #include "app/cmd/with_sprite.h"
#include "doc/remap.h" #include "doc/remap.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class RemapColors : public Cmd class RemapColors : public Cmd,
, public WithSprite { public WithSprite {
public: public:
RemapColors(Sprite* sprite, const Remap& remap); RemapColors(Sprite* sprite, const Remap& remap);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_remap.getMemSize(); }
return sizeof(*this) + m_remap.getMemSize();
}
private: private:
void incrementVersions(Sprite* spr); void incrementVersions(Sprite* spr);
Remap m_remap; Remap m_remap;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/remap_tilemaps.h" #include "app/cmd/remap_tilemaps.h"
@ -20,13 +20,11 @@
#include "doc/sprite.h" #include "doc/sprite.h"
#include "doc/tileset.h" #include "doc/tileset.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
RemapTilemaps::RemapTilemaps(Tileset* tileset, RemapTilemaps::RemapTilemaps(Tileset* tileset, const Remap& remap)
const Remap& remap)
: WithTileset(tileset) : WithTileset(tileset)
, m_remap(remap) , m_remap(remap)
{ {
@ -69,5 +67,4 @@ void RemapTilemaps::incrementVersions(Tileset* tileset)
} }
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -12,31 +12,26 @@
#include "app/cmd/with_tileset.h" #include "app/cmd/with_tileset.h"
#include "doc/remap.h" #include "doc/remap.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class RemapTilemaps : public Cmd class RemapTilemaps : public Cmd,
, public WithTileset { public WithTileset {
public: public:
RemapTilemaps(Tileset* tileset, RemapTilemaps(Tileset* tileset, const Remap& remap);
const Remap& remap);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_remap.getMemSize(); }
return sizeof(*this) + m_remap.getMemSize();
}
private: private:
void remapTileset(Tileset* tileset, const Remap& remap); void remapTileset(Tileset* tileset, const Remap& remap);
void incrementVersions(Tileset* tileset); void incrementVersions(Tileset* tileset);
Remap m_remap; Remap m_remap;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/remap_tileset.h" #include "app/cmd/remap_tileset.h"
@ -19,13 +19,11 @@
#include "doc/sprite.h" #include "doc/sprite.h"
#include "doc/tileset.h" #include "doc/tileset.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
RemapTileset::RemapTileset(Tileset* tileset, RemapTileset::RemapTileset(Tileset* tileset, const Remap& remap)
const Remap& remap)
: WithTileset(tileset) : WithTileset(tileset)
, m_remap(remap) , m_remap(remap)
{ {
@ -50,5 +48,4 @@ void RemapTileset::applyRemap(Tileset* tileset, const Remap& remap)
tileset->sprite()->incrementVersion(); tileset->sprite()->incrementVersion();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -12,30 +12,25 @@
#include "app/cmd/with_tileset.h" #include "app/cmd/with_tileset.h"
#include "doc/remap.h" #include "doc/remap.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class RemapTileset : public Cmd class RemapTileset : public Cmd,
, public WithTileset { public WithTileset {
public: public:
RemapTileset(Tileset* tileset, RemapTileset(Tileset* tileset, const Remap& remap);
const Remap& remap);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
size_t onMemSize() const override { size_t onMemSize() const override { return sizeof(*this) + m_remap.getMemSize(); }
return sizeof(*this) + m_remap.getMemSize();
}
private: private:
void applyRemap(Tileset* tileset, const Remap& remap); void applyRemap(Tileset* tileset, const Remap& remap);
Remap m_remap; Remap m_remap;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/remove_cel.h" #include "app/cmd/remove_cel.h"
@ -13,13 +13,11 @@
#include "doc/cel.h" #include "doc/cel.h"
#include "doc/layer.h" #include "doc/layer.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
RemoveCel::RemoveCel(Cel* cel) RemoveCel::RemoveCel(Cel* cel) : AddCel(cel->layer(), cel)
: AddCel(cel->layer(), cel)
{ {
} }
@ -38,5 +36,4 @@ void RemoveCel::onRedo()
AddCel::onUndo(); AddCel::onUndo();
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

View File

@ -10,21 +10,19 @@
#include "app/cmd/add_cel.h" #include "app/cmd/add_cel.h"
namespace app { namespace app { namespace cmd {
namespace cmd { using namespace doc;
using namespace doc;
class RemoveCel : public AddCel { class RemoveCel : public AddCel {
public: public:
RemoveCel(Cel* cel); RemoveCel(Cel* cel);
protected: protected:
void onExecute() override; void onExecute() override;
void onUndo() override; void onUndo() override;
void onRedo() override; void onRedo() override;
}; };
} // namespace cmd }} // namespace app::cmd
} // namespace app
#endif #endif

View File

@ -5,7 +5,7 @@
// the End-User License Agreement for Aseprite. // the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "app/cmd/remove_frame.h" #include "app/cmd/remove_frame.h"
@ -16,8 +16,7 @@
#include "doc/cels_range.h" #include "doc/cels_range.h"
#include "doc/sprite.h" #include "doc/sprite.h"
namespace app { namespace app { namespace cmd {
namespace cmd {
using namespace doc; using namespace doc;
@ -79,5 +78,4 @@ void RemoveFrame::onUndo()
doc->notify_observers<DocEvent&>(&DocObserver::onAddFrame, ev); doc->notify_observers<DocEvent&>(&DocObserver::onAddFrame, ev);
} }
} // namespace cmd }} // namespace app::cmd
} // namespace app

Some files were not shown because too many files have changed in this diff Show More