OSDN Git Service

layers: more robust remove/merge actions
[mypaint-anime/master.git] / lib / document.py
1 # This file is part of MyPaint.
2 # Copyright (C) 2007-2008 by Martin Renold <martinxyz@gmx.ch>
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8
9 import os, zipfile, tempfile, time
10 join = os.path.join
11 import xml.etree.ElementTree as ET
12 from gtk import gdk
13 import gobject, numpy
14 from gettext import gettext as _
15
16 import helpers, tiledsurface, pixbufsurface, backgroundsurface, mypaintlib
17 import command, stroke, layer
18 import brush
19 N = tiledsurface.N
20
21 class SaveLoadError(Exception):
22     """Expected errors on loading or saving, like missing permissions or non-existing files."""
23     pass
24
25 class Document():
26     """
27     This is the "model" in the Model-View-Controller design.
28     (The "view" would be ../gui/tileddrawwidget.py.)
29     It represents everything that the user would want to save.
30
31
32     The "controller" mostly in drawwindow.py.
33     It is possible to use it without any GUI attached (see ../tests/)
34     """
35     # Please note the following difficulty with the undo stack:
36     #
37     #   Most of the time there is an unfinished (but already rendered)
38     #   stroke pending, which has to be turned into a command.Action
39     #   or discarded as empty before any other action is possible.
40     #   (split_stroke)
41
42     def __init__(self):
43         self.brush = brush.Brush()
44         self.stroke = None
45         self.canvas_observers = []
46         self.stroke_observers = [] # callback arguments: stroke, brush (brush is a temporary read-only convenience object)
47         self.doc_observers = []
48         self.clear(True)
49
50     def call_doc_observers(self):
51         for f in self.doc_observers:
52             f(self)
53         return True
54
55     def clear(self, init=False):
56         self.split_stroke()
57         if not init:
58             bbox = self.get_bbox()
59         # throw everything away, including undo stack
60         self.command_stack = command.CommandStack()
61         self.set_background((255, 255, 255))
62         self.layers = []
63         self.layer_idx = None
64         self.add_layer(0)
65         # disallow undo of the first layer
66         self.command_stack.clear()
67         self.unsaved_painting_time = 0.0
68
69         if not init:
70             for f in self.canvas_observers:
71                 f(*bbox)
72
73         self.call_doc_observers()
74
75     def get_current_layer(self):
76         return self.layers[self.layer_idx]
77     layer = property(get_current_layer)
78
79     def split_stroke(self):
80         if not self.stroke: return
81         self.stroke.stop_recording()
82         if not self.stroke.empty:
83             self.command_stack.do(command.Stroke(self, self.stroke, self.snapshot_before_stroke))
84             del self.snapshot_before_stroke
85             self.unsaved_painting_time += self.stroke.total_painting_time
86             for f in self.stroke_observers:
87                 f(self.stroke, self.brush)
88         self.stroke = None
89
90     def select_layer(self, idx):
91         self.do(command.SelectLayer(self, idx))
92
93     def move_layer(self, was_idx, new_idx):
94         self.do(command.MoveLayer(self, was_idx, new_idx))
95
96     def clear_layer(self):
97         if not self.layer.surface.is_empty():
98             self.do(command.ClearLayer(self))
99
100     def stroke_to(self, dtime, x, y, pressure):
101         if not self.stroke:
102             self.stroke = stroke.Stroke()
103             self.stroke.start_recording(self.brush)
104             self.snapshot_before_stroke = self.layer.save_snapshot()
105         self.stroke.record_event(dtime, x, y, pressure)
106
107         l = self.layer
108         l.surface.begin_atomic()
109         split = self.brush.stroke_to (l.surface, x, y, pressure, dtime)
110         l.surface.end_atomic()
111
112         if split:
113             self.split_stroke()
114
115     def straight_line(self, src, dst):
116         self.split_stroke()
117         # TODO: undo last stroke if it was very short... (but not at document level?)
118         real_brush = self.brush
119         self.brush = brush.Brush()
120         self.brush.copy_settings_from(real_brush)
121
122         duration = 3.0
123         pressure = 0.3
124         N = 1000
125         x = numpy.linspace(src[0], dst[0], N)
126         y = numpy.linspace(src[1], dst[1], N)
127         # rest the brush in src for a minute, to avoid interpolation
128         # from the upper left corner (states are zero) (FIXME: the
129         # brush should handle this on its own, maybe?)
130         self.stroke_to(60.0, x[0], y[0], 0.0)
131         for i in xrange(N):
132             self.stroke_to(duration/N, x[i], y[i], pressure)
133         self.split_stroke()
134         self.brush = real_brush
135
136
137     def layer_modified_cb(self, *args):
138         # for now, any layer modification is assumed to be visible
139         for f in self.canvas_observers:
140             f(*args)
141
142     def invalidate_all(self):
143         for f in self.canvas_observers:
144             f(0, 0, 0, 0)
145
146     def undo(self):
147         self.split_stroke()
148         while 1:
149             cmd = self.command_stack.undo()
150             if not cmd or not cmd.automatic_undo:
151                 return cmd
152
153     def redo(self):
154         self.split_stroke()
155         while 1:
156             cmd = self.command_stack.redo()
157             if not cmd or not cmd.automatic_undo:
158                 return cmd
159
160     def do(self, cmd):
161         self.split_stroke()
162         self.command_stack.do(cmd)
163
164     def get_last_command(self):
165         self.split_stroke()
166         return self.command_stack.get_last_command()
167
168     def set_brush(self, brush):
169         self.split_stroke()
170         self.brush.copy_settings_from(brush)
171
172     def get_bbox(self):
173         res = helpers.Rect()
174         for layer in self.layers:
175             # OPTIMIZE: only visible layers...
176             # careful: currently saving assumes that all layers are included
177             bbox = layer.surface.get_bbox()
178             res.expandToIncludeRect(bbox)
179         return res
180
181     def blit_tile_into(self, dst_8bit, tx, ty, mipmap=0, layers=None, background=None):
182         if layers is None:
183             layers = self.layers
184         if background is None:
185             background = self.background
186
187         assert dst_8bit.dtype == 'uint8'
188         dst = numpy.empty((N, N, 3), dtype='uint16')
189
190         background.blit_tile_into(dst, tx, ty, mipmap)
191
192         for layer in layers:
193             surface = layer.surface
194             surface.composite_tile_over(dst, tx, ty, mipmap_level=mipmap, opacity=layer.opacity)
195
196         mypaintlib.tile_convert_rgb16_to_rgb8(dst, dst_8bit)
197
198     def add_layer(self, insert_idx=None, after=None):
199         self.do(command.AddLayer(self, insert_idx, after))
200
201     def remove_layer(self,layer=None):
202         if len(self.layers) > 1:
203             self.do(command.RemoveLayer(self,layer))
204         else:
205             self.clear_layer()
206
207     def merge_layer_down(self):
208         dst_idx = self.layer_idx - 1
209         if dst_idx < 0:
210             return False
211         self.do(command.MergeLayer(self, dst_idx))
212         return True
213
214     def load_layer_from_pixbuf(self, pixbuf, x=0, y=0):
215         arr = helpers.gdkpixbuf2numpy(pixbuf)
216         self.do(command.LoadLayer(self, arr, x, y))
217
218     def set_layer_opacity(self, opacity):
219         cmd = self.get_last_command()
220         if isinstance(cmd, command.SetLayerOpacity):
221             self.undo()
222         self.do(command.SetLayerOpacity(self, opacity))
223
224     def set_background(self, obj):
225         # This is not an undoable action. One reason is that dragging
226         # on the color chooser would get tons of undo steps.
227
228         if not isinstance(obj, backgroundsurface.Background):
229             obj = backgroundsurface.Background(obj)
230         self.background = obj
231
232         self.invalidate_all()
233
234     def load_from_pixbuf(self, pixbuf):
235         self.clear()
236         self.load_layer_from_pixbuf(pixbuf)
237
238     def is_layered(self):
239         count = 0
240         for l in self.layers:
241             if not l.surface.is_empty():
242                 count += 1
243         return count > 1
244
245     def is_empty(self):
246         return len(self.layers) == 1 and self.layer.surface.is_empty()
247
248     def save(self, filename, **kwargs):
249         self.split_stroke()
250         trash, ext = os.path.splitext(filename)
251         ext = ext.lower().replace('.', '')
252         save = getattr(self, 'save_' + ext, self.unsupported)
253         try:        
254             save(filename, **kwargs)
255         except gobject.GError, e:
256             if e.code == 5:
257                 #add a hint due to a very consfusing error message when there is no space left on device
258                 raise SaveLoadError, _('Unable to save: %s\nDo you have enough space left on the device?') % e.message
259             else:
260                 raise SaveLoadError, _('Unable to save: %s') % e.message
261         except IOError, e:
262             raise SaveLoadError, _('Unable to save: %s') % e.strerror
263         self.unsaved_painting_time = 0.0
264
265     def load(self, filename):
266         if not os.path.isfile(filename):
267             raise SaveLoadError, _('File does not exist: %s') % repr(filename)
268         if not os.access(filename,os.R_OK):
269             raise SaveLoadError, _('You do not have the necessary permissions to open file: %s') % repr(filename)
270         trash, ext = os.path.splitext(filename)
271         ext = ext.lower().replace('.', '')
272         load = getattr(self, 'load_' + ext, self.unsupported)
273         load(filename)
274         self.command_stack.clear()
275         self.unsaved_painting_time = 0.0
276         self.call_doc_observers()
277
278     def unsupported(self, filename):
279         raise SaveLoadError, _('Unknown file format extension: %s') % repr(filename)
280
281     def render_as_pixbuf(self, *args):
282         return pixbufsurface.render_as_pixbuf(self, *args)
283
284     def save_png(self, filename, compression=2, alpha=False, multifile=False):
285         if multifile:
286             self.save_multifile_png(filename, compression)
287         else:
288             if alpha:
289                 tmp_layer = layer.Layer()
290                 for l in self.layers:
291                     l.merge_into(tmp_layer)
292                 pixbuf = tmp_layer.surface.render_as_pixbuf()
293             else:
294                 pixbuf = self.render_as_pixbuf()
295             pixbuf.save(filename, 'png', {'compression':str(compression)})
296
297     def save_multifile_png(self, filename, compression=2, alpha=False):
298         prefix, ext = os.path.splitext(filename)
299         # if we have a number already, strip it
300         l = prefix.rsplit('.', 1)
301         if l[-1].isdigit():
302             prefix = l[0]
303         doc_bbox = self.get_bbox()
304         for i, l in enumerate(self.layers):
305             filename = '%s.%03d%s' % (prefix, i+1, ext)
306             l.surface.save(filename, *doc_bbox)
307
308     def load_png(self, filename):
309         self.load_from_pixbuf(gdk.pixbuf_new_from_file(filename))
310
311     def load_jpg(self, filename):
312         self.load_from_pixbuf(gdk.pixbuf_new_from_file(filename))
313     load_jpeg = load_jpg
314
315     def save_jpg(self, filename, quality=90):
316         pixbuf = self.render_as_pixbuf()
317         pixbuf.save(filename, 'jpeg', options={'quality':str(quality)})
318     save_jpeg = save_jpg
319
320     def save_ora(self, filename, options=None):
321         print 'save_ora:'
322         t0 = time.time()
323         tempdir = tempfile.mkdtemp('mypaint')
324         # use .tmp extension, so we don't overwrite a valid file if there is an exception
325         z = zipfile.ZipFile(filename + '.tmpsave', 'w', compression=zipfile.ZIP_STORED)
326         # work around a permission bug in the zipfile library: http://bugs.python.org/issue3394
327         def write_file_str(filename, data):
328             zi = zipfile.ZipInfo(filename)
329             zi.external_attr = 0100644 << 16
330             z.writestr(zi, data)
331         write_file_str('mimetype', 'image/openraster') # must be the first file
332         image = ET.Element('image')
333         stack = ET.SubElement(image, 'stack')
334         x0, y0, w0, h0 = self.get_bbox()
335         a = image.attrib
336         a['w'] = str(w0)
337         a['h'] = str(h0)
338
339         def store_pixbuf(pixbuf, name):
340             tmp = join(tempdir, 'tmp.png')
341             t1 = time.time()
342             pixbuf.save(tmp, 'png', {'compression':'2'})
343             print '  %.3fs saving %s compression 2' % (time.time() - t1, name)
344             z.write(tmp, name)
345             os.remove(tmp)
346
347         def add_layer(x, y, opac, pixbuf, name, layer_name):
348             layer = ET.Element('layer')
349             stack.append(layer)
350             store_pixbuf(pixbuf, name)
351             a = layer.attrib
352             if layer_name:
353                 a['name'] = layer_name
354             a['src'] = name
355             a['x'] = str(x)
356             a['y'] = str(y)
357             a['opacity'] = str(opac)
358             return layer
359
360         for idx, l in enumerate(reversed(self.layers)):
361             if l.surface.is_empty():
362                 continue
363             opac = l.opacity
364             x, y, w, h = l.surface.get_bbox()
365             pixbuf = l.surface.render_as_pixbuf()
366             el = add_layer(x-x0, y-y0, opac, pixbuf, 'data/layer%03d.png' % idx, l.name)
367             # strokemap
368             data = l.save_strokemap_to_string(-x, -y)
369             name = 'data/layer%03d_strokemap.dat' % idx
370             el.attrib['mypaint_strokemap'] = name
371             write_file_str(name, data)
372
373         # save background as layer (solid color or tiled)
374         s = pixbufsurface.Surface(x0, y0, w0, h0)
375         s.fill(self.background)
376         l = add_layer(0, 0, 1.0, s.pixbuf, 'data/background.png', 'background')
377         bg = self.background
378         x, y, w, h = bg.get_pattern_bbox()
379         pixbuf = pixbufsurface.render_as_pixbuf(bg, x+x0, y+y0, w, h, alpha=False)
380         store_pixbuf(pixbuf, 'data/background_tile.png')
381         l.attrib['background_tile'] = 'data/background_tile.png'
382
383         # preview
384         t2 = time.time()
385         print '  starting to render image for thumbnail...'
386         pixbuf = self.render_as_pixbuf()
387         w, h = pixbuf.get_width(), pixbuf.get_height()
388         if w > h:
389             w, h = 256, max(h*256/w, 1)
390         else:
391             w, h = max(w*256/h, 1), 256
392         t1 = time.time()
393         pixbuf = pixbuf.scale_simple(w, h, gdk.INTERP_BILINEAR)
394         print '  %.3fs scaling thumbnail' % (time.time() - t1)
395         store_pixbuf(pixbuf, 'Thumbnails/thumbnail.png')
396         print '  total %.3fs spent on thumbnail' % (time.time() - t2)
397
398         helpers.indent_etree(image)
399         xml = ET.tostring(image, encoding='UTF-8')
400
401         write_file_str('stack.xml', xml)
402         z.close()
403         os.rmdir(tempdir)
404         if os.path.exists(filename):
405             os.remove(filename) # windows needs that
406         os.rename(filename + '.tmpsave', filename)
407
408         print '%.3fs save_ora total' % (time.time() - t0)
409
410     def load_ora(self, filename):
411         print 'load_ora:'
412         t0 = time.time()
413         tempdir = tempfile.mkdtemp('mypaint')
414         z = zipfile.ZipFile(filename)
415         print 'mimetype:', z.read('mimetype').strip()
416         xml = z.read('stack.xml')
417         image = ET.fromstring(xml)
418         stack = image.find('stack')
419
420         def get_pixbuf(filename):
421             t1 = time.time()
422             tmp = join(tempdir, 'tmp.png')
423             f = open(tmp, 'wb')
424             f.write(z.read(filename))
425             f.close()
426             res = gdk.pixbuf_new_from_file(tmp)
427             os.remove(tmp)
428             print '  %.3fs loading %s' % (time.time() - t1, filename)
429             return res
430
431         def get_layers_list(root, x=0,y=0):
432             res = []
433             for item in root:
434                 if item.tag == 'layer':
435                     if 'x' in item.attrib:
436                         item.attrib['x'] = int(item.attrib['x']) + x
437                     if 'y' in item.attrib:
438                         item.attrib['y'] = int(item.attrib['y']) + y
439                     res.append(item)
440                 elif item.tag == 'stack':
441                     stack_x = int( item.attrib.get('x', 0) )
442                     stack_y = int( item.attrib.get('y', 0) )
443                     res += get_layers_list(item, stack_x, stack_y)
444                 else:
445                     print 'Warning: ignoring unsupported tag:', item.tag
446             return res
447
448         self.clear() # this leaves one empty layer
449         no_background = True
450         for layer in get_layers_list(stack):
451             a = layer.attrib
452
453             if 'background_tile' in a:
454                 assert no_background
455                 try:
456                     print a['background_tile']
457                     self.set_background(get_pixbuf(a['background_tile']))
458                     no_background = False
459                     continue
460                 except backgroundsurface.BackgroundError, e:
461                     print 'ORA background tile not usable:', e
462
463             src = a.get('src', '')
464             if not src.lower().endswith('.png'):
465                 print 'Warning: ignoring non-png layer'
466                 continue
467             pixbuf = get_pixbuf(src)
468             name = a.get('name', '')
469
470             x = int(a.get('x', '0'))
471             y = int(a.get('y', '0'))
472             opac = float(a.get('opacity', '1.0'))
473             self.add_layer(insert_idx=0)
474             last_pixbuf = pixbuf
475             t1 = time.time()
476             self.load_layer_from_pixbuf(pixbuf, x, y)
477             layer = self.layers[0]
478             layer.name = name
479             layer.opacity = helpers.clamp(opac, 0.0, 1.0)
480             print '  %.3fs converting pixbuf to layer format' % (time.time() - t1)
481             # strokemap
482             fname = a.get('mypaint_strokemap', None)
483             if fname:
484                 if x % N or y % N:
485                     print 'Warning: dropping non-aligned strokemap'
486                 else:
487                     data = z.read(fname)
488                     self.layers[0].load_strokemap_from_string(data, x, y)
489
490         os.rmdir(tempdir)
491
492         if len(self.layers) == 1:
493             raise ValueError, 'Could not load any layer.'
494
495         if no_background:
496             # recognize solid or tiled background layers, at least those that mypaint <= 0.7.1 saves
497             t1 = time.time()
498             p = last_pixbuf
499             if not p.get_has_alpha() and p.get_width() % N == 0 and p.get_height() % N == 0:
500                 tiles = self.layers[0].surface.tiledict.values()
501                 if len(tiles) > 1:
502                     all_equal = True
503                     for tile in tiles[1:]:
504                         if (tile.rgba != tiles[0].rgba).any():
505                             all_equal = False
506                             break
507                     if all_equal:
508                         arr = helpers.gdkpixbuf2numpy(p)
509                         tile = arr[0:N,0:N,:]
510                         self.set_background(tile.copy())
511                         self.select_layer(0)
512                         self.remove_layer()
513             print '  %.3fs recognizing tiled background' % (time.time() - t1)
514
515         if len(self.layers) > 1:
516             # remove the still present initial empty top layer
517             self.select_layer(len(self.layers)-1)
518             self.remove_layer()
519             # this leaves the topmost layer selected
520
521         print '%.3fs load_ora total' % (time.time() - t0)