-
Notifications
You must be signed in to change notification settings - Fork 384
/
document.py
2199 lines (1890 loc) · 78.4 KB
/
document.py
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# This file is part of MyPaint.
# Copyright (C) 2010-2019 by the MyPaint Development Team
# Copyright (C) 2007-2013 by Martin Renold <martinxyz@gmx.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
## Imports
from __future__ import absolute_import, division, print_function
import os
import sys
import zipfile
import tempfile
import time
from os.path import join
import xml.etree.ElementTree as ET
from warnings import warn
import shutil
from datetime import datetime
from collections import namedtuple
import json
import logging
from lib.fileutils import safename
from lib.naming import make_unique_name
from lib.gibindings import GObject
from lib.gibindings import GLib
import lib.meta
import lib.helpers as helpers
import lib.fileutils as fileutils
import lib.tiledsurface as tiledsurface
import lib.command as command
import lib.layer as layer
import lib.brush as brush
from lib.observable import event
from lib.observable import ObservableDict
import lib.pixbuf
from lib.cache import DEFAULT_CACHE_SIZE
from lib.errors import FileHandlingError
from lib.errors import AllocationError
import lib.idletask
from lib.gettext import C_
import lib.xml
import lib.glib
import lib.feedback
import lib.layervis
from lib.pycompat import unicode
logger = logging.getLogger(__name__)
## Module constants
DEFAULT_RESOLUTION = 72
DEFAULT_UNDO_STACK_SIZE = 40
N = tiledsurface.N
CACHE_APP_SUBDIR_NAME = u"mypaint"
CACHE_DOC_SUBDIR_PREFIX = u"doc."
CACHE_DOC_AUTOSAVE_SUBDIR = u"autosave"
CACHE_ACTIVITY_FILE = u"active"
CACHE_UPDATE_INTERVAL = 10 # seconds
# Logging and error reporting strings
_LOAD_FAILED_COMMON_TEMPLATE_LINE = C_(
"Document IO: common error strings: {error_loading_common}",
u"Error loading “{basename}”."
)
_ERROR_SEE_LOGS_LINE = C_(
"Document IO: common error strings: {see_logs}",
u"The logs may have more detail "
u"about this error."
)
# OpenRaster dialect consts
_ORA_MYPAINT_VERSION \
= "{%s}version" % (lib.xml.OPENRASTER_MYPAINT_NS,)
_ORA_FRAME_ACTIVE_ATTR \
= "{%s}frame-active" % (lib.xml.OPENRASTER_MYPAINT_NS,)
_ORA_UNSAVED_PAINTING_TIME_ATTR \
= "{%s}unsaved-painting-time" % (lib.xml.OPENRASTER_MYPAINT_NS,)
_ORA_JSON_SETTINGS_ATTR \
= "{%s}json-settings" % (lib.xml.OPENRASTER_MYPAINT_NS,)
_ORA_EOTF_ATTR \
= "{%s}eotf" % (lib.xml.OPENRASTER_MYPAINT_NS,)
_ORA_JSON_SETTINGS_ZIP_PATH = "data/mypaint-settings.json"
## Class defs
_AUTOSAVE_INFO_FIELDS = (
"path",
"last_modified",
"thumbnail",
"num_layers",
"unsaved_painting_time",
"width", "height",
"valid",
"cache_in_use",
)
class AutosaveInfo (namedtuple("AutosaveInfo", _AUTOSAVE_INFO_FIELDS)):
"""Information about an autosave dir.
:ivar unicode path: Full path to the autosave directory itself
:ivar datetime.datetime last_modified: When its data was last changed
:ivar GdkPixbuf.Pixbuf thumbnail: 256x256 pixel thumbnail, or None
:ivar int num_layers: how many data layers exist in the doc
:ivar float unsaved_painting_time: seconds of unsaved painting
:ivar int width: Width of the document
:ivar int height: Height of the document
:ivar bool valid: True if the directory looks structurally valid
:ivar bool cache_in_use: True if the directory is possibly in use
"""
@classmethod
def new_for_path(cls, path):
if not isinstance(path, unicode):
raise ValueError("path argument must be unicode")
if not os.path.isdir(path):
raise ValueError("Autosave folder %r does not exist", path)
has_data = os.path.isdir(os.path.join(path, "data"))
valid = has_data
stackxml_path = os.path.join(path, "stack.xml")
thumbnail_path = os.path.join(path, "Thumbnails", "thumbnail.png")
has_stackxml = os.path.isfile(stackxml_path)
if has_stackxml:
last_modified = _get_path_mtime(stackxml_path)
else:
last_modified = _get_path_mtime(path)
valid = False
unsaved_painting_time = 0
num_layers = 0
width = 0
height = 0
if has_stackxml:
try:
doc = ET.parse(stackxml_path)
except (ET.ParseError, IOError, OSError) as ex:
valid = False
else:
image_elem = doc.getroot()
unsaved_painting_time = max(0.0, float(
image_elem.attrib.get(
"mypaint_unsaved_painting_time",
0.0,
)
))
width = max(0, int(image_elem.attrib.get('w', 0)))
height = max(0, int(image_elem.attrib.get('h', 0)))
num_layers = max(0, len(image_elem.findall(".//layer")) - 1)
thumbnail = None
if os.path.exists(thumbnail_path):
thumbnail = lib.pixbuf.load_from_file(thumbnail_path)
cache_in_use = False
cache_dir_path = os.path.dirname(path)
activity_file_path = os.path.join(cache_dir_path, CACHE_ACTIVITY_FILE)
if os.path.exists(activity_file_path):
cache_activity_time = _get_path_mtime(activity_file_path)
cache_activity_dt = (datetime.now() - cache_activity_time).seconds
if cache_activity_dt <= CACHE_UPDATE_INTERVAL + 3:
cache_in_use = True
return cls(
path = path,
last_modified = last_modified,
valid = valid,
num_layers = num_layers,
unsaved_painting_time = unsaved_painting_time,
width = width,
height = height,
thumbnail = thumbnail,
cache_in_use = cache_in_use,
)
def get_description(self):
"""Human-readable description of the autosave
:rtype: unicode
"""
fmt_time = lib.helpers.fmt_time_period_abbr
unsaved_time_str = fmt_time(self.unsaved_painting_time)
last_modif_dt = (datetime.now() - self.last_modified).seconds
# TODO: Look into whether breaking out these strings causes problems
if last_modif_dt < 0:
last_modif_ago_str = C_(
"Document autosave descriptions: the {ago} string: future",
# TRANSLATORS: string used in e.g. "3h42m from now"
u"from now"
)
else:
last_modif_ago_str = C_(
"Document autosave descriptions: the {ago} string: past",
# TRANSLATORS: string used in e.g. "8s ago"
u"ago"
)
last_modif_str = fmt_time(abs(last_modif_dt))
if self.cache_in_use:
template = C_(
"Document autosave descriptions",
# TRANSLATORS: String descriptions for an autosaved backup.
# TRANSLATORS: Time strings are localized: e.g. "3h42m" or "8s"
u"Cache folder still may be in use.\n"
u"Are you running more than once instance of MyPaint?\n"
u"Close app and wait {cache_update_interval}s to retry."
)
elif not self.valid:
template = C_(
"Document autosave descriptions",
u"Incomplete backup updated {last_modified_time} {ago}"
)
else:
template = C_(
"Document autosave descriptions",
# TRANSLATORS: The {ago} variable is a translated string.
# TRANSLATORS: Look for the msgids "from now" and "ago"
# TRANSLATORS: (with context starting w. "Document autosave")
# TRANSLATORS: to make sure their translations match this one.
u"Backup updated {last_modified_time} {ago}\n"
u"Size: {autosave.width}×{autosave.height} pixels, "
u"Layers: {autosave.num_layers}\n"
u"Contains {unsaved_time} of unsaved painting."
)
return template.format(
autosave = self,
unsaved_time = unsaved_time_str,
last_modified_time = last_modif_str,
ago = last_modif_ago_str,
cache_update_interval = CACHE_UPDATE_INTERVAL,
)
class Document (object):
"""In-memory representation of everything to be worked on & saved
This is the "model" in the Model-View-Controller design for the
drawing canvas. The View mostly resides in `gui.tileddrawwidget`,
and the Controller is mostly in `gui.document` and `gui.mode`.
The model contains everything that the user would want to save. It
is possible to use the model without any GUI attached (see
``../tests/``).
Please note the following difficulty with the command stack: many
uses of the working Document model rely on altering the model
directly, then writing an undoable record of the changes to the
command stack when asked. There may be more than one concurrent
source of these pending changes. See `sync_pending_changes()` for
details of how sources of pending changes are asked to synchronize
their state with the model and its command stack.
"""
## Class constants
#: Debugging toggle. If True, New and Load and Remove Layer will create a
#: new blank painting layer if they empty out the document.
CREATE_PAINTING_LAYER_IF_EMPTY = True
## Initialization and cleanup
def __init__(self, brushinfo=None, painting_only=False,
cache_dir=None, cache_size=DEFAULT_CACHE_SIZE,
max_undo_stack_size=DEFAULT_UNDO_STACK_SIZE):
"""Initialize
:param brushinfo: the lib.brush.BrushInfo instance to use
:param painting_only: only use painting layers
:param cache_dir: use an existing cache dir
:param cache_size: size of the layer render cache
If painting_only is true, then no tempdir will be created by the
document when it is initialized or cleared.
If an existing cache dir is requested, it will not be created, and
it won't be managed. Autosave and cleanup will be turned off if
this is set; it's assumed that you're importing into a parent
document.
"""
object.__init__(self)
if not brushinfo:
brushinfo = brush.BrushInfo()
brushinfo.load_defaults()
self._layers = layer.RootLayerStack(self, cache_size=cache_size)
self._layers.layer_content_changed += self._canvas_modified_cb
self.brush = brush.Brush(brushinfo)
self.brush.brushinfo.observers.append(self.brushsettings_changed_cb)
self.stroke = None
self.command_stack = command.CommandStack(max_undo_stack_size)
# Cache and auto-saving to the cache
self._painting_only = painting_only
self._cache_dir = cache_dir
if cache_dir is not None:
if painting_only:
raise ValueError(
"painting_only and cache_dir arguments "
"are mutually exclusive",
)
if not os.path.isdir(cache_dir):
raise ValueError(
"cache_dir argument must be the path "
"to an existing directory",
)
self._owns_cache_dir = False
else:
self._owns_cache_dir = True
self._cache_updater_id = None
self._autosave_backups = False
self.autosave_interval = 10
self._autosave_processor = None
self._autosave_countdown_id = None
self._autosave_dirty = False
if (not painting_only) and self._owns_cache_dir:
self._autosave_processor = lib.idletask.Processor()
self.command_stack.stack_updated += self._command_stack_updated_cb
self.effective_bbox_changed += self._effective_bbox_changed_cb
# Optional page area and resolution information
self._frame = [0, 0, 0, 0]
self._frame_enabled = False
self._xres = None
self._yres = None
#: Document-specific settings, serialized as JSON when saving ORA.
self._settings = ObservableDict()
self.sync_pending_changes += self._settings_sync_pending_changes_cb
#: Sets of layer-views, identified by name.
self._layer_view_manager = lib.layervis.LayerViewManager(self)
# And begin in a known state
self.clear()
def __repr__(self):
bbox = self.get_bbox()
nlayers = len(list(self.layer_stack.walk()))
return ("<Document nlayers=%d bbox=%r paintonly=%r>" %
(nlayers, bbox, self._painting_only))
## Layer stack access
@property
def layer_stack(self):
"""The root of the layer stack tree
See also `lib.layer.RootLayerStack`.
"""
# TODO: rename or alias this to just "layers" one day.
return self._layers
## Working document's cache directory
@property
def tempdir(self):
"""The working doc's cache dir (read-only, deprecated name)"""
warn("Use cache_dir instead", DeprecationWarning, stacklevel=2)
return self._cache_dir
@property
def cache_dir(self):
"""The working document's cache dir"""
return self._cache_dir
def _create_cache_dir(self):
"""Internal: creates the working-document cache dir if needed."""
if self._painting_only or not self._owns_cache_dir:
return
assert self._cache_dir is None
app_cache_root = get_app_cache_root()
doc_cache_dir = tempfile.mkdtemp(
prefix=CACHE_DOC_SUBDIR_PREFIX,
dir=app_cache_root,
)
if not isinstance(doc_cache_dir, unicode):
doc_cache_dir = doc_cache_dir.decode(sys.getfilesystemencoding())
logger.debug("Created working-doc cache dir %r", doc_cache_dir)
self._cache_dir = doc_cache_dir
# Start the cache updater, which kicks off background autosaves,
# and updates an activity canary file.
# Not a perfect solution, but maybe a better cross-platform one
# than file locking, pidfiles or other horrors.
activity_file_path = os.path.join(doc_cache_dir, CACHE_ACTIVITY_FILE)
with open(activity_file_path, "w") as fp:
fp.write(
"A recent timestamp on this file indicates that\n"
"its containing cache subfolder is active.\n"
)
self._start_cache_updater()
def _cleanup_cache_dir(self):
"""Internal: recursively delete the working-document cache_dir if OK.
Also stops any background tasks which update it.
"""
if self._painting_only or not self._owns_cache_dir:
return
if self._cache_dir is None:
return
self._stop_cache_updater()
self._stop_autosave_writes()
shutil.rmtree(self._cache_dir, ignore_errors=True)
if os.path.exists(self._cache_dir):
logger.error(
"Failed to remove working-doc cache dir %r",
self._cache_dir,
)
else:
logger.debug(
"Successfully removed working-doc cache dir %r",
self._cache_dir,
)
self._cache_dir = None
def cleanup(self):
"""Cleans up any persistent state belonging to the document.
This method is called by the main app's exit routine
after confirmation.
"""
self._cleanup_cache_dir()
## Document-specific settings dict.
@property
def settings(self):
"""The document-specific settings dict.
:returns: dict-like object that can be monitored for simple changes.
:rtype: lib.observable.ObservableDict
The settings dict is conserved when saving and loading
OpenRaster files. Note however that a round-trip converts
strings and dict keys to unicode objects.
>>> import tempfile, shutil, os.path
>>> tmpdir = tempfile.mkdtemp()
>>> doc1 = Document(painting_only=True)
>>> doc1.settings[u"T.1"] = [1, 2]
>>> doc1.settings[u"T.2"] = u"simple"
>>> doc1.settings[u"T.3"] = {u"4": 5}
>>> expected = [
... (u'T.1', [1, 2]),
... (u'T.2', u'simple'),
... (u'T.3', {u'4': 5}),
... ]
>>> sorted([i for i in doc1.settings.items()
... if i[0].startswith("T.")]) == expected
True
>>> file1 = os.path.join(tmpdir, "file1.ora")
>>> thumb1 = doc1.save(file1)
>>> doc1.cleanup()
>>> doc2 = Document(painting_only=True)
>>> doc2.load(file1)
True
>>> sorted([i for i in doc1.settings.items()
... if i[0].startswith("T.")]) == expected
True
>>> doc2.settings == doc1.settings
True
>>> doc2.cleanup()
>>> shutil.rmtree(tmpdir)
See also: ``json``.
"""
return self._settings
## Periodic cache updater
def _start_cache_updater(self):
"""Start the cache updater if it isn't running."""
assert not self._painting_only
assert self._owns_cache_dir
if self._cache_updater_id:
return
logger.debug("cache_updater started")
self._cache_updater_id = GLib.timeout_add_seconds(
interval = CACHE_UPDATE_INTERVAL,
function = self._cache_updater_cb,
)
def _stop_cache_updater(self):
"""Stop the cache updater."""
assert not self._painting_only
assert self._owns_cache_dir
if not self._cache_updater_id:
return
logger.debug("cache_updater: stopped")
GLib.source_remove(self._cache_updater_id)
self._cache_updater_id = None
def _cache_updater_cb(self):
"""Payload: update canary file, start autosave countdown if dirty"""
assert not self._painting_only
assert self._owns_cache_dir
activity_file_path = os.path.join(self.cache_dir, CACHE_ACTIVITY_FILE)
os.utime(activity_file_path, None)
if self._autosave_dirty:
self._start_autosave_countdown()
return True
## Autosave flag
@property
def autosave_backups(self):
return self._autosave_backups
@autosave_backups.setter
def autosave_backups(self, newval):
newval = bool(newval)
oldval = bool(self._autosave_backups)
self._autosave_backups = newval
if self._painting_only or not self._owns_cache_dir:
return
if oldval and not newval:
self._stop_autosave_writes()
self._stop_autosave_countdown()
## Autosave countdown, restarted by activity.
def _restart_autosave_countdown(self):
"""Stop and then start the countdown to an automatic backup
Should be called in response to any user activity which might
have changed the document's data or its structure.
"""
assert not self._painting_only
self._stop_autosave_countdown()
self._start_autosave_countdown()
def _start_autosave_countdown(self):
"""Start the countdown to an automatic backup, if it isn't already.
This does nothing if the countdown has already been started, or
if the autosave writes are in progress.
"""
assert not self._painting_only
if not self._autosave_dirty:
return
if self._autosave_processor.has_work():
return
if self._autosave_countdown_id:
return
if not self._autosave_backups:
return
interval = lib.helpers.clamp(self.autosave_interval, 5, 300)
self._autosave_countdown_id = GLib.timeout_add_seconds(
interval = interval,
function = self._autosave_countdown_cb,
)
logger.debug(
"autosave_countdown: autosave will run in %ds",
self.autosave_interval,
)
def _stop_autosave_countdown(self):
"""Stop any existing countdown to an automatic backup"""
assert not self._painting_only
if not self._autosave_countdown_id:
return
GLib.source_remove(self._autosave_countdown_id)
self._autosave_countdown_id = None
def _autosave_countdown_cb(self):
"""Payload: start autosave writes and terminate"""
assert not self._painting_only
# Sync settings so they get saved, but not the whole doc.
# See https://github.com/mypaint/mypaint/issues/893
self._settings.sync_pending_changes(flush=True)
self._queue_autosave_writes()
self._autosave_countdown_id = None
return False
## Queued autosave writes: low priority & chunked
def _queue_autosave_writes(self):
"""Add autosaved backup tasks to the background processor
These tasks consist of nicely chunked writes for all layers
whose data has changed, plus a few extra structural and
bookkeeping ones.
"""
if not self._cache_dir:
logger.warning("autosave start abandoned: _cache_dir not set")
# sometimes happens on exit
return
logger.debug("autosave starting: queueing save tasks")
assert not self._painting_only
assert not self._autosave_processor.has_work()
assert self._autosave_dirty
oradir = os.path.join(self._cache_dir, CACHE_DOC_AUTOSAVE_SUBDIR)
datadir = os.path.join(oradir, "data")
if not os.path.exists(datadir):
logger.debug("autosave: creating %r...", datadir)
os.makedirs(datadir)
# Mimetype entry
manifest = set()
with open(os.path.join(oradir, 'mimetype'), 'w') as fp:
fp.write(lib.xml.OPENRASTER_MEDIA_TYPE)
manifest.add("mimetype")
# Dimensions
image_bbox = tuple(self.get_bbox())
if self.frame_enabled:
image_bbox = tuple(self.get_frame())
# Get root stack element and files that will be needed,
# queue writes for those files
taskproc = self._autosave_processor
root_elem = self.layer_stack.queue_autosave(
oradir, taskproc, manifest,
save_srgb_chunks = True, # internal-only, so sure.
bbox = image_bbox,
)
# Build the image element
x0, y0, w0, h0 = image_bbox
image_elem = ET.Element('image')
image_elem.attrib['w'] = str(w0)
image_elem.attrib['h'] = str(h0)
image_elem.attrib[_ORA_EOTF_ATTR] = str(lib.eotf.eotf())
frame_active_value = ("true" if self.frame_enabled else "false")
image_elem.attrib[_ORA_FRAME_ACTIVE_ATTR] = frame_active_value
image_elem.append(root_elem)
# Store the unsaved painting time too, since recovery needs it.
# This is a (very) local extension to the format.
t_str = "{:3f}".format(self.unsaved_painting_time)
image_elem.attrib[_ORA_UNSAVED_PAINTING_TIME_ATTR] = t_str
# Doc-specific settings
settings_file_rel = _ORA_JSON_SETTINGS_ZIP_PATH
if self._settings is not None:
taskproc.add_work(
self._autosave_settings_cb,
dict(self._settings),
os.path.join(oradir, settings_file_rel),
)
image_elem.attrib[_ORA_JSON_SETTINGS_ATTR] = settings_file_rel
manifest.add(settings_file_rel)
# Store version of MyPaint the file was saved with
image_elem.attrib[_ORA_MYPAINT_VERSION] = lib.meta.MYPAINT_VERSION
# Thumbnail generation.
rootstack_sshot = self.layer_stack.save_snapshot()
rootstack_clone = layer.RootLayerStack(doc=None)
rootstack_clone.load_snapshot(rootstack_sshot)
thumbdir_rel = "Thumbnails"
thumbdir = os.path.join(oradir, thumbdir_rel)
if not os.path.exists(thumbdir):
os.makedirs(thumbdir)
thumbfile_basename = "thumbnail.png"
thumbfile_rel = os.path.join(thumbdir_rel, thumbfile_basename)
taskproc.add_work(
self._autosave_thumbnail_cb,
rootstack_clone,
image_bbox,
os.path.join(thumbdir, thumbfile_basename)
)
manifest.add(thumbfile_rel)
# Final write
stackfile_rel = "stack.xml"
taskproc.add_work(
self._autosave_stackxml_cb,
image_elem,
os.path.join(oradir, stackfile_rel),
)
manifest.add(stackfile_rel)
# Cleanup
taskproc.add_work(
self._autosave_cleanup_cb,
oradir = oradir,
manifest = manifest,
)
def _autosave_thumbnail_cb(self, rootstack, bbox, filename):
"""Autosaved backup task: write Thumbnails/thumbnail.png
This runs every time currently for the same reason we rewrite
stack.xml each time. It would be a big win if we didn't have to
do this though.
"""
assert not self._painting_only
thumbnail = rootstack.render_thumbnail(bbox)
tmpname = filename + u".TMP"
lib.pixbuf.save(thumbnail, tmpname)
lib.fileutils.replace(tmpname, filename)
return False
def _autosave_stackxml_cb(self, image_elem, filename):
"""Autosaved backup task: write stack.xml
This runs every time because the document's layer structure can
change without data layers being aware of it.
"""
assert not self._painting_only
lib.xml.indent_etree(image_elem)
tmpname = filename + u".TMP"
with open(tmpname, 'wb') as xml_fp:
xml = ET.tostring(image_elem, encoding='UTF-8')
xml_fp.write(xml)
lib.fileutils.replace(tmpname, filename)
return False
def _autosave_settings_cb(self, settings, filename):
"""Autosaved backup task: save the doc-specific settings dict"""
assert not self._painting_only
# Py2/Py3: always feed print() a UTF-8 encoded byte string.
json_data = json.dumps(settings, indent=2)
if isinstance(json_data, unicode):
json_data = json_data.encode("utf-8")
assert isinstance(json_data, bytes)
tmpname = filename + u".TMP"
with open(tmpname, 'wb') as fp:
fp.write(json_data)
lib.fileutils.replace(tmpname, filename)
def _autosave_cleanup_cb(self, oradir, manifest):
"""Autosaved backup task: final cleanup task"""
assert not self._painting_only
surplus_files = []
for dirpath, dirnames, filenames in os.walk(oradir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
filerel = os.path.relpath(filepath, oradir)
if filerel not in manifest:
surplus_files.append(filepath)
# Remove surplus files.
# This is fairly normal: it happens when layers are deleted.
for path in surplus_files:
logger.debug(
"autosave: removing %r (not listed in manifest)",
path,
)
os.unlink(path)
# Also check for files listed in the manifest that aren't
# present on the disk. That's more of a concern,
# because it means the index will be inconsistent
for path in [os.path.join(oradir, p) for p in manifest]:
if os.path.exists(path):
continue
logger.error(
"autosave: missing %r (listed in the manifest)",
path,
)
self._autosave_dirty = False
logger.debug("autosave: all done, doc marked autosave-clean")
return False
def _stop_autosave_writes(self):
assert not self._painting_only
logger.debug("autosave stopped: clearing task queue")
self._autosave_processor.stop()
def _command_stack_updated_cb(self, cmdstack):
assert not self._painting_only
if not self.autosave_backups:
return
self._autosave_dirty = True
self._restart_autosave_countdown()
logger.debug("autosave: updates detected, doc marked autosave-dirty")
## Document frame
def get_resolution(self):
"""Returns the document model's nominal resolution
The OpenRaster format saves resolution information in both vertical and
horizontal resolutions, but MyPaint does not support this at present.
This method returns the a unidirectional document resolution in pixels
per inch; this is the user-chosen factor that UI controls should use
when converting real-world measurements in frames, fonts, and other
objects to document pixels.
Note that the document resolution has no direct relation to screen
pixels or printed dots.
"""
if self._xres and self._yres:
return max(1, max(self._xres, self._yres))
else:
return DEFAULT_RESOLUTION
def set_resolution(self, res):
"""Sets the document model's nominal resolution
The OpenRaster format saves resolution information in both vertical and
horizontal resolutions, but MyPaint does not support this at present.
This method sets the document resolution in pixels per inch in both
directions.
Note that the document resolution has no direct relation to screen
pixels or printed dots.
"""
if res is not None:
res = int(res)
res = max(1, res)
self._xres = res
self._yres = res
def get_frame(self):
return self._frame
def set_frame(self, frame, user_initiated=False):
x, y, w, h = frame
self.update_frame(x=x, y=y, width=w, height=h,
user_initiated=user_initiated)
frame = property(get_frame, set_frame)
def update_frame(self, x=None, y=None, width=None, height=None,
user_initiated=False):
"""Update parts of the frame"""
frame = [x, y, width, height]
if user_initiated:
if isinstance(self.get_last_command(), command.UpdateFrame):
self.update_last_command(frame=frame)
else:
self.do(command.UpdateFrame(self, frame))
else:
new_frame = list(self._frame[:])
for i, var in enumerate([x, y, width, height]):
if var is not None:
new_frame[i] = int(var)
if new_frame != self._frame:
old_frame = tuple(self._frame)
self._frame[:] = new_frame
new_frame = tuple(new_frame)
self.frame_updated(old_frame, new_frame)
self.effective_bbox_changed()
@event
def frame_updated(self, old_frame, new_frame):
"""Event: the frame's dimensions were updated
:param tuple frame: the new frame extents (x, y, w, h)
"""
def get_frame_enabled(self):
return self._frame_enabled
def set_frame_enabled(self, enabled, user_initiated=False):
enabled = bool(enabled)
if self._frame_enabled == enabled:
return
if user_initiated:
self.do(command.SetFrameEnabled(self, enabled))
else:
self._frame_enabled = enabled
self.frame_enabled_changed(enabled)
self.effective_bbox_changed()
frame_enabled = property(get_frame_enabled)
@event
def frame_enabled_changed(self, enabled):
"""Event: the frame_enabled field changed value"""
def set_frame_to_current_layer(self, user_initiated=False):
current = self.layer_stack.current
x, y, w, h = current.get_bbox()
self.update_frame(x, y, w, h, user_initiated=user_initiated)
def set_frame_to_document(self, user_initiated=False):
x, y, w, h = self.get_bbox()
self.update_frame(x, y, w, h, user_initiated=user_initiated)
def trim_current_layer(self):
"""Trim the current layer to the extent of the document frame
This has no effect if the frame is not currently enabled.
"""
if not self._frame_enabled:
return
self.do(command.TrimLayer(self))
def uniq_current_layer(self, pixels=False):
"""Udoably remove non-unique tiles or pixels from the current layer."""
self.do(command.UniqLayer(self, pixels=pixels))
def refactor_current_layer_group(self, pixels=False):
"""Undoably factor out common parts of child layers to a new child."""
self.do(command.RefactorGroup(self, pixels=pixels))
@event
def effective_bbox_changed(self):
"""Event: the effective bounding box was changed"""
def _effective_bbox_changed_cb(self, *_ignored):
# Background layer's autosaved data files depend on the
# frame's position and size. No other layers need this.
assert not self._painting_only
self.layer_stack.background_layer.autosave_dirty = True
## Misc actions
def clear(self, new_cache=True):
"""Clears everything, and resets the command stack
:param bool new_cache: False to *not* create a new cache dir
This results in a document consisting of
one newly created blank drawing layer,
an empty undo history, and unless `new_cache` is False,
a new empty working-document temp directory.
Clearing the document also generates a full redraw,
and resets the frame, the stored resolution,
and the document-specific settings.
"""
self.sync_pending_changes()
self.layer_view_manager.clear()
self._layers.symmetry_unset = True
self._layers.set_symmetry_state(
False, (0, 0), lib.mypaintlib.SymmetryVertical, 2, 0)
prev_area = self.get_full_redraw_bbox()
if self._owns_cache_dir:
if self._cache_dir is not None:
self._cleanup_cache_dir()
if new_cache:
self._create_cache_dir()
self.command_stack.clear()
self._layers.clear()
if self.CREATE_PAINTING_LAYER_IF_EMPTY:
self.add_layer((-1,))
self._layers.current_path = (0,)
self.command_stack.clear()
else:
self._layers.current_path = None
self.unsaved_painting_time = 0.0
self.set_frame([0, 0, 0, 0])
self.set_frame_enabled(False)
self._xres = None
self._yres = None
self._settings.clear()
self.canvas_area_modified(*prev_area)
def brushsettings_changed_cb(self, settings):
self.sync_pending_changes(flush=False)
def select_layer(self, index=None, path=None, layer=None):
"""Selects a layer undoably"""
layers = self.layer_stack
sel_path = layers.canonpath(index=index, path=path, layer=layer,
usecurrent=False, usefirst=True)
self.do(command.SelectLayer(self, path=sel_path))
## Layer stack (z-order and grouping)
def restack_layer(self, src_path, targ_path):
"""Moves a layer within the layer stack by path, undoably
:param tuple src_path: path of the layer to be moved
:param tuple targ_path: target insert path
The source path must identify an existing layer. The target
path must be a valid insertion path at the time this method is
called.
"""
logger.debug("Restack layer at %r to %r", src_path, targ_path)
cmd = command.RestackLayer(self, src_path, targ_path)
self.do(cmd)
def bubble_current_layer_up(self):
"""Moves the current layer up in the stack (undoable)"""
cmd = command.BubbleLayerUp(self)
self.do(cmd)
def bubble_current_layer_down(self):
"""Moves the current layer down in the stack (undoable)"""
cmd = command.BubbleLayerDown(self)
self.do(cmd)
## Misc layer command frontends
def duplicate_current_layer(self):
"""Makes an exact copy of the current layer (undoable)"""
self.do(command.DuplicateLayer(self))
def clear_current_layer(self):
"""Clears the current layer (undoable)"""