forked from aseprite/aseprite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc.cpp
720 lines (590 loc) · 17.5 KB
/
doc.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// Aseprite
// Copyright (C) 2018-2024 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/doc.h"
#include "app/app.h"
#include "app/color_target.h"
#include "app/color_utils.h"
#include "app/context.h"
#include "app/context.h"
#include "app/doc_api.h"
#include "app/doc_event.h"
#include "app/doc_observer.h"
#include "app/doc_undo.h"
#include "app/file/format_options.h"
#include "app/flatten.h"
#include "app/pref/preferences.h"
#include "app/util/cel_ops.h"
#include "base/memory.h"
#include "doc/cel.h"
#include "doc/layer.h"
#include "doc/layer_tilemap.h"
#include "doc/mask.h"
#include "doc/mask_boundaries.h"
#include "doc/palette.h"
#include "doc/slice.h"
#include "doc/sprite.h"
#include "doc/tag.h"
#include "os/system.h"
#include "os/window.h"
#include "ui/system.h"
#include <limits>
#include <map>
#define DOC_TRACE(...) // TRACEARGS(__VA_ARGS__)
namespace app {
using namespace base;
using namespace doc;
Doc::Doc(Sprite* sprite)
: m_ctx(nullptr)
, m_flags(kMaskVisible)
, m_undo(new DocUndo)
, m_transaction(nullptr)
// Information about the file format used to load/save this document
, m_format_options(nullptr)
// Mask
, m_mask(new Mask())
, m_lastDrawingPoint(Doc::NoLastDrawingPoint())
{
setFilename("Sprite");
if (sprite)
sprites().add(sprite);
updateOSColorSpace(false);
DOC_TRACE("DOC: New", this);
}
Doc::~Doc()
{
DOC_TRACE("DOC: Deleting", this);
removeFromContext();
}
void Doc::setContext(Context* ctx)
{
if (ctx == m_ctx)
return;
removeFromContext();
m_ctx = ctx;
if (ctx) {
DOC_TRACE("DOC: Removing as fully backed up", this);
// Remove the flag that indicates that this doc is fully backed
// up, because now we are inside a context, so the user can change
// it again and the backup will be outdated.
if (m_flags & kFullyBackedUp)
m_flags ^= kFullyBackedUp;
ctx->documents().add(this);
}
onContextChanged();
}
bool Doc::canWriteLockFromRead() const
{
return m_rwLock.canWriteLockFromRead();
}
Doc::LockResult Doc::readLock(int timeout)
{
auto res = m_rwLock.lock(base::RWLock::ReadLock, timeout);
DOC_TRACE("DOC: readLock", this, (int)res);
return res;
}
Doc::LockResult Doc::writeLock(int timeout)
{
auto res = m_rwLock.lock(base::RWLock::WriteLock, timeout);
DOC_TRACE("DOC: writeLock", this, (int)res);
return res;
}
Doc::LockResult Doc::upgradeToWrite(int timeout)
{
auto res = m_rwLock.upgradeToWrite(timeout);
DOC_TRACE("DOC: upgradeToWrite", this, (int)res);
return res;
}
void Doc::downgradeToRead(LockResult lockResult)
{
DOC_TRACE("DOC: downgradeToRead", this, (int)lockResult);
m_rwLock.downgradeToRead(lockResult);
}
void Doc::unlock(LockResult lockResult)
{
ASSERT(lockResult != base::RWLock::LockResult::Fail);
DOC_TRACE("DOC: unlock", this, (int)lockResult);
m_rwLock.unlock(lockResult);
}
bool Doc::weakLock(std::atomic<base::RWLock::WeakLock>* weak_lock_flag)
{
bool res = m_rwLock.weakLock(weak_lock_flag);
DOC_TRACE("DOC: weakLock", this, (int)res);
return res;
}
void Doc::weakUnlock()
{
DOC_TRACE("DOC: weakUnlock", this);
m_rwLock.weakUnlock();
}
void Doc::setTransaction(Transaction* transaction)
{
if (transaction) {
ASSERT(!m_transaction);
m_transaction = transaction;
}
else {
ASSERT(m_transaction);
m_transaction = nullptr;
}
}
DocApi Doc::getApi(Transaction& transaction)
{
return DocApi(this, transaction);
}
//////////////////////////////////////////////////////////////////////
// Main properties
bool Doc::isUndoing() const
{
return m_undo->isUndoing();
}
color_t Doc::bgColor() const
{
return color_utils::color_for_target(
Preferences::instance().colorBar.bgColor(),
ColorTarget(ColorTarget::BackgroundLayer,
sprite()->pixelFormat(),
sprite()->transparentColor()));
}
color_t Doc::bgColor(Layer* layer) const
{
if (layer->isBackground())
return color_utils::color_for_layer(
Preferences::instance().colorBar.bgColor(),
layer);
else
return layer->sprite()->transparentColor();
}
//////////////////////////////////////////////////////////////////////
// Modifications with notifications
void Doc::setLayerVisibilityWithNotifications(Layer* layer, const bool visible)
{
notifyBeforeLayerVisibilityChange(layer, visible);
layer->setVisible(visible);
notifyAfterLayerVisibilityChange(layer);
}
//////////////////////////////////////////////////////////////////////
// Notifications
void Doc::notifyGeneralUpdate()
{
DocEvent ev(this);
notify_observers<DocEvent&>(&DocObserver::onGeneralUpdate, ev);
}
void Doc::notifyColorSpaceChanged()
{
updateOSColorSpace(true);
DocEvent ev(this);
ev.sprite(sprite());
notify_observers<DocEvent&>(&DocObserver::onColorSpaceChanged, ev);
}
void Doc::notifyPaletteChanged()
{
DocEvent ev(this);
ev.sprite(sprite());
notify_observers<DocEvent&>(&DocObserver::onPaletteChanged, ev);
}
void Doc::notifySpritePixelsModified(Sprite* sprite, const gfx::Region& region, frame_t frame)
{
DocEvent ev(this);
ev.sprite(sprite);
ev.region(region);
ev.frame(frame);
notify_observers<DocEvent&>(&DocObserver::onSpritePixelsModified, ev);
}
void Doc::notifyExposeSpritePixels(Sprite* sprite, const gfx::Region& region)
{
DocEvent ev(this);
ev.sprite(sprite);
ev.region(region);
notify_observers<DocEvent&>(&DocObserver::onExposeSpritePixels, ev);
}
void Doc::notifyLayerMergedDown(Layer* srcLayer, Layer* targetLayer)
{
DocEvent ev(this);
ev.sprite(srcLayer->sprite());
ev.layer(srcLayer);
ev.targetLayer(targetLayer);
notify_observers<DocEvent&>(&DocObserver::onLayerMergedDown, ev);
}
void Doc::notifyBeforeLayerVisibilityChange(Layer* layer, bool newState)
{
DocEvent ev(this);
ev.layer(layer);
notify_observers<DocEvent&, bool>(&DocObserver::onBeforeLayerVisibilityChange, ev, newState);
}
void Doc::notifyAfterLayerVisibilityChange(Layer* layer)
{
DocEvent ev(this);
ev.layer(layer);
notify_observers<DocEvent&>(&DocObserver::onAfterLayerVisibilityChange, ev);
}
void Doc::notifyCelMoved(Layer* fromLayer, frame_t fromFrame, Layer* toLayer, frame_t toFrame)
{
DocEvent ev(this);
ev.sprite(toLayer->sprite());
ev.layer(fromLayer);
ev.frame(fromFrame);
ev.targetLayer(toLayer);
ev.targetFrame(toFrame);
notify_observers<DocEvent&>(&DocObserver::onCelMoved, ev);
}
void Doc::notifyCelCopied(Layer* fromLayer, frame_t fromFrame, Layer* toLayer, frame_t toFrame)
{
DocEvent ev(this);
ev.sprite(toLayer->sprite());
ev.layer(fromLayer); // From layer can be nullptr
ev.frame(fromFrame);
ev.targetLayer(toLayer);
ev.targetFrame(toFrame);
notify_observers<DocEvent&>(&DocObserver::onCelCopied, ev);
}
void Doc::notifySelectionChanged()
{
DocEvent ev(this);
notify_observers<DocEvent&>(&DocObserver::onSelectionChanged, ev);
}
void Doc::notifySelectionBoundariesChanged()
{
DocEvent ev(this);
notify_observers<DocEvent&>(&DocObserver::onSelectionBoundariesChanged, ev);
}
void Doc::notifyTilesetChanged(Tileset* tileset)
{
DocEvent ev(this);
ev.tileset(tileset);
notify_observers<DocEvent&>(&DocObserver::onTilesetChanged, ev);
}
void Doc::notifyLayerGroupCollapseChange(Layer* layer)
{
DocEvent ev(this);
ev.layer(layer);
notify_observers<DocEvent&>(&DocObserver::onLayerCollapsedChanged, ev);
}
void Doc::notifyAfterAddTile(LayerTilemap* layer, frame_t frame, tile_index ti)
{
DocEvent ev(this);
ev.sprite(layer->sprite());
ev.layer(layer);
ev.frame(frame);
ev.tileset(layer->tileset());
ev.tileIndex(ti);
notify_observers<DocEvent&>(&DocObserver::onAfterAddTile, ev);
}
bool Doc::isModified() const
{
return !m_undo->isInSavedStateOrSimilar();
}
bool Doc::isAssociatedToFile() const
{
return (m_flags & kAssociatedToFile) == kAssociatedToFile;
}
void Doc::markAsSaved()
{
m_flags |= kAssociatedToFile;
m_undo->markSavedState();
}
void Doc::impossibleToBackToSavedState()
{
m_undo->impossibleToBackToSavedState();
}
bool Doc::needsBackup() const
{
// If the undo history isn't empty, the user has modified the
// document, so we need to backup those changes.
return m_undo->canUndo() || m_undo->canRedo();
}
bool Doc::inhibitBackup() const
{
return (m_flags & kInhibitBackup) == kInhibitBackup;
}
void Doc::setInhibitBackup(const bool inhibitBackup)
{
if (inhibitBackup)
m_flags |= kInhibitBackup;
else
m_flags &= ~kInhibitBackup;
}
void Doc::markAsBackedUp()
{
DOC_TRACE("DOC: Mark as fully backed up", this);
m_flags |= kFullyBackedUp;
}
bool Doc::isFullyBackedUp() const
{
return (m_flags & kFullyBackedUp ? true: false);
}
void Doc::markAsReadOnly()
{
DOC_TRACE("DOC: Mark as read-only", this);
m_flags |= kReadOnly;
}
bool Doc::isReadOnly() const
{
return (m_flags & kReadOnly ? true: false);
}
void Doc::removeReadOnlyMark()
{
DOC_TRACE("DOC: Read-only mark removed", this);
m_flags &= ~kReadOnly;
}
//////////////////////////////////////////////////////////////////////
// Loaded options from file
void Doc::setFormatOptions(const FormatOptionsPtr& format_options)
{
m_format_options = format_options;
}
//////////////////////////////////////////////////////////////////////
// Boundaries
void Doc::destroyMaskBoundaries()
{
m_maskBoundaries.reset();
notifySelectionBoundariesChanged();
}
void Doc::generateMaskBoundaries(const Mask* mask)
{
m_maskBoundaries.reset();
// No mask specified? Use the current one in the document
if (!mask) {
if (!isMaskVisible()) // The mask is hidden
return; // Done, without boundaries
else
mask = this->mask(); // Use the document mask
}
ASSERT(mask);
if (!mask->isEmpty()) {
m_maskBoundaries.regen(mask->bitmap());
m_maskBoundaries.offset(mask->bounds().x,
mask->bounds().y);
}
notifySelectionBoundariesChanged();
}
//////////////////////////////////////////////////////////////////////
// Mask
void Doc::setMask(const Mask* mask)
{
ASSERT(mask);
m_mask->copyFrom(mask);
m_flags |= kMaskVisible;
resetTransformation();
}
bool Doc::isMaskVisible() const
{
return
(m_flags & kMaskVisible) && // The mask was not hidden by the user explicitly
!m_mask->isEmpty(); // The mask is not empty
}
void Doc::setMaskVisible(bool visible)
{
if (visible)
m_flags |= kMaskVisible;
else
m_flags &= ~kMaskVisible;
}
//////////////////////////////////////////////////////////////////////
// Transformation
Transformation Doc::getTransformation() const
{
return m_transformation;
}
void Doc::setTransformation(const Transformation& transform)
{
m_transformation = transform;
}
void Doc::resetTransformation()
{
m_transformation = Transformation(gfx::RectF(m_mask->bounds()), m_transformation.cornerThick());
}
//////////////////////////////////////////////////////////////////////
// Copying
void Doc::copyLayerContent(const Layer* sourceLayer0, Doc* destDoc, Layer* destLayer0) const
{
LayerFlags dstFlags = sourceLayer0->flags();
// Remove the "background" flag if the destDoc already has a background layer.
if (((int)dstFlags & (int)LayerFlags::Background) == (int)LayerFlags::Background &&
(destDoc->sprite()->backgroundLayer())) {
dstFlags = (LayerFlags)((int)dstFlags & ~(int)(LayerFlags::BackgroundLayerFlags));
}
// Copy the layer name/flags/user data
destLayer0->setName(sourceLayer0->name());
destLayer0->setFlags(dstFlags);
destLayer0->setUserData(sourceLayer0->userData());
if (sourceLayer0->isImage() && destLayer0->isImage()) {
const LayerImage* sourceLayer = static_cast<const LayerImage*>(sourceLayer0);
LayerImage* destLayer = static_cast<LayerImage*>(destLayer0);
// Copy blend mode and opacity
destLayer->setBlendMode(sourceLayer->blendMode());
destLayer->setOpacity(sourceLayer->opacity());
// Copy cels
CelConstIterator it = sourceLayer->getCelBegin();
CelConstIterator end = sourceLayer->getCelEnd();
std::map<ObjectId, Cel*> linked;
for (; it != end; ++it) {
const Cel* sourceCel = *it;
if (sourceCel->frame() > destLayer->sprite()->lastFrame())
break;
std::unique_ptr<Cel> newCel(nullptr);
auto it = linked.find(sourceCel->data()->id());
if (it != linked.end()) {
newCel.reset(Cel::MakeLink(sourceCel->frame(),
it->second));
newCel->copyNonsharedPropertiesFrom(sourceCel);
}
else {
newCel.reset(create_cel_copy(nullptr, // TODO add undo information?
sourceCel,
destLayer->sprite(),
destLayer,
sourceCel->frame()));
linked.insert(std::make_pair(sourceCel->data()->id(), newCel.get()));
}
destLayer->addCel(newCel.get());
newCel.release();
}
}
else if (sourceLayer0->isGroup() && destLayer0->isGroup()) {
const LayerGroup* sourceLayer = static_cast<const LayerGroup*>(sourceLayer0);
LayerGroup* destLayer = static_cast<LayerGroup*>(destLayer0);
for (Layer* sourceChild : sourceLayer->layers()) {
std::unique_ptr<Layer> destChild(nullptr);
if (sourceChild->isImage()) {
destChild.reset(new LayerImage(destLayer->sprite()));
copyLayerContent(sourceChild, destDoc, destChild.get());
}
else if (sourceChild->isGroup()) {
destChild.reset(new LayerGroup(destLayer->sprite()));
copyLayerContent(sourceChild, destDoc, destChild.get());
}
else {
ASSERT(false);
}
ASSERT(destChild != NULL);
// Add the new layer in the sprite.
Layer* newLayer = destChild.release();
Layer* afterThis = destLayer->lastLayer();
destLayer->addLayer(newLayer);
destChild.release();
destLayer->stackLayer(newLayer, afterThis);
}
}
else {
ASSERT(false && "Trying to copy two incompatible layers");
}
}
Doc* Doc::duplicate(DuplicateType type) const
{
const Sprite* sourceSprite = sprite();
std::unique_ptr<Sprite> spriteCopyPtr(new Sprite(
sourceSprite->spec(),
sourceSprite->palette(frame_t(0))->size()));
std::unique_ptr<Doc> documentCopy(new Doc(spriteCopyPtr.get()));
Sprite* spriteCopy = spriteCopyPtr.release();
spriteCopy->setTotalFrames(sourceSprite->totalFrames());
// Copy frames duration
for (frame_t i(0); i < sourceSprite->totalFrames(); ++i)
spriteCopy->setFrameDuration(i, sourceSprite->frameDuration(i));
// Copy frame tags
for (const Tag* tag : sourceSprite->tags())
spriteCopy->tags().add(new Tag(*tag));
// Copy slices
for (const Slice *slice : sourceSprite->slices()) {
auto sliceCopy = new Slice(*slice);
spriteCopy->slices().add(sliceCopy);
ASSERT(sliceCopy->owner() == &spriteCopy->slices());
}
// Copy color palettes
{
PalettesList::const_iterator it = sourceSprite->getPalettes().begin();
PalettesList::const_iterator end = sourceSprite->getPalettes().end();
for (; it != end; ++it) {
const Palette* pal = *it;
spriteCopy->setPalette(pal, true);
}
}
switch (type) {
case DuplicateExactCopy:
// Copy the layer group
copyLayerContent(sourceSprite->root(),
documentCopy.get(),
spriteCopy->root());
ASSERT((spriteCopy->backgroundLayer() && sourceSprite->backgroundLayer()) ||
(!spriteCopy->backgroundLayer() && !sourceSprite->backgroundLayer()));
break;
case DuplicateWithFlattenLayers:
{
// Flatten layers
ASSERT(sourceSprite->root() != NULL);
LayerImage* flatLayer = create_flatten_layer_copy
(spriteCopy,
sourceSprite->root(),
gfx::Rect(0, 0, sourceSprite->width(), sourceSprite->height()),
frame_t(0), sourceSprite->lastFrame(),
Preferences::instance().experimental.newBlend());
// Add and select the new flat layer
spriteCopy->root()->addLayer(flatLayer);
// Configure the layer as background only if the original
// sprite has a background layer.
if (sourceSprite->backgroundLayer() != NULL)
flatLayer->configureAsBackground();
}
break;
}
// Copy only some flags
documentCopy->m_flags = (m_flags & kMaskVisible);
documentCopy->setFilename(filename());
documentCopy->setMask(mask());
documentCopy->generateMaskBoundaries();
return documentCopy.release();
}
void Doc::close()
{
try {
notify_observers<Doc*>(&DocObserver::onCloseDocument, this);
}
catch (...) {
LOG(ERROR, "DOC: Exception on DocObserver::onCloseDocument()\n");
}
removeFromContext();
}
void Doc::onFileNameChange()
{
notify_observers(&DocObserver::onFileNameChanged, this);
}
void Doc::onContextChanged()
{
m_undo->setContext(context());
}
void Doc::removeFromContext()
{
if (m_ctx) {
m_ctx->documents().remove(this);
m_ctx = nullptr;
onContextChanged();
}
}
void Doc::updateOSColorSpace(bool appWideSignal)
{
auto system = os::instance();
if (system) {
m_osColorSpace = system->makeColorSpace(sprite()->colorSpace());
if (!m_osColorSpace && system->defaultWindow())
m_osColorSpace = system->defaultWindow()->colorSpace();
}
if (appWideSignal &&
context() &&
context()->activeDocument() == this) {
App::instance()->ColorSpaceChange();
}
}
// static
gfx::Point Doc::NoLastDrawingPoint()
{
return gfx::Point(std::numeric_limits<int>::min(),
std::numeric_limits<int>::min());
}
} // namespace app