forked from aseprite/aseprite
/
cmd_save_file.cpp
488 lines (418 loc) · 12.9 KB
/
cmd_save_file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Aseprite
// Copyright (C) 2019 Igara Studio S.A.
// Copyright (C) 2001-2018 David Capello
//
// This program is distributed under the terms of
// the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "app/commands/cmd_save_file.h"
#include "app/app.h"
#include "app/commands/command.h"
#include "app/commands/commands.h"
#include "app/commands/params.h"
#include "app/console.h"
#include "app/context_access.h"
#include "app/doc.h"
#include "app/doc_undo.h"
#include "app/file/file.h"
#include "app/file/gif_format.h"
#include "app/file/png_format.h"
#include "app/file_selector.h"
#include "app/i18n/strings.h"
#include "app/job.h"
#include "app/modules/gui.h"
#include "app/pref/preferences.h"
#include "app/recent_files.h"
#include "app/restore_visible_layers.h"
#include "app/ui/export_file_window.h"
#include "app/ui/layer_frame_comboboxes.h"
#include "app/ui/optional_alert.h"
#include "app/ui/status_bar.h"
#include "base/bind.h"
#include "base/convert_to.h"
#include "base/fs.h"
#include "base/scoped_value.h"
#include "base/thread.h"
#include "doc/frame_tag.h"
#include "doc/sprite.h"
#include "fmt/format.h"
#include "ui/ui.h"
#include "undo/undo_state.h"
namespace app {
class SaveFileJob : public Job, public IFileOpProgress {
public:
SaveFileJob(FileOp* fop)
: Job("Saving file")
, m_fop(fop)
{
}
void showProgressWindow() {
startJob();
if (isCanceled()) {
m_fop->stop();
}
waitJob();
}
private:
// Thread to do the hard work: save the file to the disk.
virtual void onJob() override {
try {
m_fop->operate(this);
}
catch (const std::exception& e) {
m_fop->setError("Error saving file:\n%s", e.what());
}
m_fop->done();
}
virtual void ackFileOpProgress(double progress) override {
jobProgress(progress);
}
FileOp* m_fop;
};
//////////////////////////////////////////////////////////////////////
SaveFileBaseCommand::SaveFileBaseCommand(const char* id, CommandFlags flags)
: Command(id, flags)
{
m_useUI = true;
m_ignoreEmpty = false;
}
void SaveFileBaseCommand::onLoadParams(const Params& params)
{
m_filename = params.get("filename");
m_filenameFormat = params.get("filename-format");
m_frameTag = params.get("frame-tag");
m_aniDir = params.get("ani-dir");
m_slice = params.get("slice");
if (params.has_param("from-frame") ||
params.has_param("to-frame")) {
doc::frame_t fromFrame = params.get_as<doc::frame_t>("from-frame");
doc::frame_t toFrame = params.get_as<doc::frame_t>("to-frame");
m_selFrames.insert(fromFrame, toFrame);
m_adjustFramesByFrameTag = true;
}
else {
m_selFrames.clear();
m_adjustFramesByFrameTag = false;
}
std::string useUI = params.get("useUI");
m_useUI = (useUI.empty() || (useUI == "true"));
std::string ignoreEmpty = params.get("ignoreEmpty");
m_ignoreEmpty = (ignoreEmpty == "true");
}
// Returns true if there is a current sprite to save.
// [main thread]
bool SaveFileBaseCommand::onEnabled(Context* context)
{
return context->checkFlags(ContextFlags::ActiveDocumentIsWritable);
}
std::string SaveFileBaseCommand::saveAsDialog(
Context* context,
const std::string& dlgTitle,
const std::string& initialFilename,
const bool markAsSaved,
const bool saveInBackground,
const std::string& forbiddenFilename)
{
Doc* document = context->activeDocument();
Preferences::instance().save();
std::string filename;
if (!m_filename.empty()) {
filename = m_filename;
}
else {
base::paths exts = get_writable_extensions();
filename = initialFilename;
#ifdef ENABLE_UI
again:;
base::paths newfilename;
if (!m_useUI ||
!app::show_file_selector(
dlgTitle, filename, exts,
FileSelectorType::Save,
newfilename))
return std::string();
filename = newfilename.front();
if (!forbiddenFilename.empty() &&
base::normalize_path(forbiddenFilename) ==
base::normalize_path(filename)) {
ui::Alert::show(Strings::alerts_cannot_file_overwrite_on_export());
goto again;
}
#endif // ENABLE_UI
}
if (saveInBackground) {
saveDocumentInBackground(
context, document,
filename, markAsSaved);
Preferences::instance().document(document).saveCopy.filename("");
Preferences::instance().document(document).saveCopy.aniDir(doc::AniDir::FORWARD);
Preferences::instance().document(document).saveCopy.applyPixelRatio(false);
Preferences::instance().document(document).saveCopy.layer("");
Preferences::instance().document(document).saveCopy.forTwitter(false);
Preferences::instance().document(document).saveCopy.resizeScale(1);
Preferences::instance().save();
}
return filename;
}
void SaveFileBaseCommand::saveDocumentInBackground(
const Context* context,
Doc* document,
const std::string& filename,
const bool markAsSaved)
{
if (!m_aniDir.empty()) {
switch (convert_string_to_anidir(m_aniDir)) {
case AniDir::REVERSE:
m_selFrames = m_selFrames.makeReverse();
break;
case AniDir::PING_PONG:
m_selFrames = m_selFrames.makePingPong();
break;
}
}
FileOpROI roi(document, m_slice, m_frameTag,
m_selFrames, m_adjustFramesByFrameTag);
std::unique_ptr<FileOp> fop(
FileOp::createSaveDocumentOperation(
context,
roi,
filename,
m_filenameFormat,
m_ignoreEmpty));
if (!fop)
return;
SaveFileJob job(fop.get());
job.showProgressWindow();
if (fop->hasError()) {
Console console;
console.printf(fop->error().c_str());
// We don't know if the file was saved correctly or not. So mark
// it as it should be saved again.
document->impossibleToBackToSavedState();
}
// If the job was cancelled, mark the document as modified.
else if (fop->isStop()) {
document->impossibleToBackToSavedState();
}
else if (context->isUIAvailable()) {
App::instance()->recentFiles()->addRecentFile(filename);
if (markAsSaved) {
document->markAsSaved();
document->setFilename(filename);
document->incrementVersion();
}
#ifdef ENABLE_UI
StatusBar::instance()
->setStatusText(2000, "File <%s> saved.",
base::get_file_name(filename).c_str());
#endif
}
}
//////////////////////////////////////////////////////////////////////
class SaveFileCommand : public SaveFileBaseCommand {
public:
SaveFileCommand();
protected:
void onExecute(Context* context) override;
};
SaveFileCommand::SaveFileCommand()
: SaveFileBaseCommand(CommandId::SaveFile(), CmdRecordableFlag)
{
}
// Saves the active document in a file.
// [main thread]
void SaveFileCommand::onExecute(Context* context)
{
Doc* document = context->activeDocument();
// If the document is associated to a file in the file-system, we can
// save it directly without user interaction.
if (document->isAssociatedToFile()) {
const ContextReader reader(context);
const Doc* documentReader = reader.document();
saveDocumentInBackground(
context, document,
documentReader->filename(), true);
}
// If the document isn't associated to a file, we must to show the
// save-as dialog to the user to select for first time the file-name
// for this document.
else {
saveAsDialog(context, "Save File",
document->filename(), true);
}
}
class SaveFileAsCommand : public SaveFileBaseCommand {
public:
SaveFileAsCommand();
protected:
void onExecute(Context* context) override;
};
SaveFileAsCommand::SaveFileAsCommand()
: SaveFileBaseCommand(CommandId::SaveFileAs(), CmdRecordableFlag)
{
}
void SaveFileAsCommand::onExecute(Context* context)
{
Doc* document = context->activeDocument();
saveAsDialog(context, "Save As",
document->filename(), true);
}
class SaveFileCopyAsCommand : public SaveFileBaseCommand {
public:
SaveFileCopyAsCommand();
protected:
void onExecute(Context* context) override;
private:
void moveToUndoState(Doc* doc,
const undo::UndoState* state);
};
SaveFileCopyAsCommand::SaveFileCopyAsCommand()
: SaveFileBaseCommand(CommandId::SaveFileCopyAs(), CmdRecordableFlag)
{
}
void SaveFileCopyAsCommand::onExecute(Context* context)
{
Doc* doc = context->activeDocument();
std::string outputFilename = m_filename;
std::string layers = kAllLayers;
std::string frames = kAllFrames;
double xscale = 1.0;
double yscale = 1.0;
bool applyPixelRatio = false;
doc::AniDir aniDirValue = convert_string_to_anidir(m_aniDir);
bool isForTwitter = false;
#if ENABLE_UI
if (m_useUI && context->isUIAvailable()) {
ExportFileWindow win(doc);
bool askOverwrite = true;
win.SelectOutputFile.connect(
[this, &win, &askOverwrite, context, doc]() -> std::string {
std::string result =
saveAsDialog(
context, "Export",
win.outputFilenameValue(), false, false,
(doc->isAssociatedToFile() ? doc->filename():
std::string()));
if (!result.empty())
askOverwrite = false; // Already asked in the file selector dialog
return result;
});
again:;
if (!win.show())
return;
outputFilename = win.outputFilenameValue();
if (askOverwrite &&
base::is_file(outputFilename)) {
int ret = OptionalAlert::show(
Preferences::instance().exportFile.showOverwriteFilesAlert,
1, // Yes is the default option when the alert dialog is disabled
fmt::format(Strings::alerts_overwrite_files_on_export(),
outputFilename));
if (ret != 1)
goto again;
}
// Save the preferences used to export the file, so if we open the
// window again, we will have the same options.
win.savePref();
layers = win.layersValue();
frames = win.framesValue();
xscale = yscale = win.resizeValue();
applyPixelRatio = win.applyPixelRatio();
aniDirValue = win.aniDirValue();
isForTwitter = win.isForTwitter();
}
#endif
// Pixel ratio
if (applyPixelRatio) {
doc::PixelRatio pr = doc->sprite()->pixelRatio();
xscale *= pr.w;
yscale *= pr.h;
}
// Apply scale
const undo::UndoState* undoState = nullptr;
bool undoResize = false;
if (xscale != 1.0 || yscale != 1.0) {
Command* resizeCmd = Commands::instance()->byId(CommandId::SpriteSize());
ASSERT(resizeCmd);
if (resizeCmd) {
int width = doc->sprite()->width();
int height = doc->sprite()->height();
int newWidth = int(double(width) * xscale);
int newHeight = int(double(height) * yscale);
if (newWidth < 1) newWidth = 1;
if (newHeight < 1) newHeight = 1;
if (width != newWidth || height != newHeight) {
doc->setInhibitBackup(true);
undoState = doc->undoHistory()->currentState();
undoResize = true;
Params params;
params.set("use-ui", "false");
params.set("width", base::convert_to<std::string>(newWidth).c_str());
params.set("height", base::convert_to<std::string>(newHeight).c_str());
params.set("resize-method", "nearest-neighbor"); // TODO add algorithm in the UI?
context->executeCommand(resizeCmd, params);
}
}
}
{
RestoreVisibleLayers layersVisibility;
if (context->isUIAvailable()) {
Site site = context->activeSite();
// Selected layers to export
calculate_visible_layers(site,
layers,
layersVisibility);
// Selected frames to export
SelectedFrames selFrames;
FrameTag* frameTag = calculate_selected_frames(
site, frames, selFrames);
if (frameTag)
m_frameTag = frameTag->name();
m_selFrames = selFrames;
m_adjustFramesByFrameTag = false;
}
base::ScopedValue<std::string> restoreAniDir(
m_aniDir,
convert_anidir_to_string(aniDirValue), // New value
m_aniDir); // Restore old value
// TODO This should be set as options for the specific encoder
GifEncoderDurationFix fixGif(isForTwitter);
PngEncoderOneAlphaPixel fixPng(isForTwitter);
saveDocumentInBackground(
context, doc, outputFilename, false);
}
// Undo resize
if (undoResize &&
undoState != doc->undoHistory()->currentState()) {
moveToUndoState(doc, undoState);
doc->setInhibitBackup(false);
}
}
void SaveFileCopyAsCommand::moveToUndoState(Doc* doc,
const undo::UndoState* state)
{
try {
DocWriter writer(doc, 100);
doc->undoHistory()->moveToState(state);
doc->generateMaskBoundaries();
doc->notifyGeneralUpdate();
}
catch (const std::exception& ex) {
Console::showException(ex);
}
}
Command* CommandFactory::createSaveFileCommand()
{
return new SaveFileCommand;
}
Command* CommandFactory::createSaveFileAsCommand()
{
return new SaveFileAsCommand;
}
Command* CommandFactory::createSaveFileCopyAsCommand()
{
return new SaveFileCopyAsCommand;
}
} // namespace app