OSDN Git Service

OpenRaster: don't manipulate layer attributes directly
[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, traceback
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.effective_opacity)
195
196         mypaintlib.tile_convert_rgb16_to_rgb8(dst, dst_8bit)
197
198     def add_layer(self, insert_idx=None, after=None, name=''):
199         self.do(command.AddLayer(self, insert_idx, after, name))
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_visibility(self, visible, layer=None):
219         cmd = self.get_last_command()
220         if isinstance(cmd, command.SetLayerVisibility):
221             self.undo()
222         self.do(command.SetLayerVisibility(self, visible, layer))
223
224     def set_layer_opacity(self, opacity, layer=None):
225         """Sets the opacity of a layer. If layer=None, works on the current layer"""
226         cmd = self.get_last_command()
227         if isinstance(cmd, command.SetLayerOpacity):
228             self.undo()
229         self.do(command.SetLayerOpacity(self, opacity, layer))
230
231     def set_background(self, obj):
232         # This is not an undoable action. One reason is that dragging
233         # on the color chooser would get tons of undo steps.
234
235         if not isinstance(obj, backgroundsurface.Background):
236             obj = backgroundsurface.Background(obj)
237         self.background = obj
238
239         self.invalidate_all()
240
241     def load_from_pixbuf(self, pixbuf):
242         self.clear()
243         self.load_layer_from_pixbuf(pixbuf)
244
245     def is_layered(self):
246         count = 0
247         for l in self.layers:
248             if not l.surface.is_empty():
249                 count += 1
250         return count > 1
251
252     def is_empty(self):
253         return len(self.layers) == 1 and self.layer.surface.is_empty()
254
255     def save(self, filename, **kwargs):
256         self.split_stroke()
257         trash, ext = os.path.splitext(filename)
258         ext = ext.lower().replace('.', '')
259         save = getattr(self, 'save_' + ext, self.unsupported)
260         try:        
261             save(filename, **kwargs)
262         except gobject.GError, e:
263             traceback.print_exc()
264             if e.code == 5:
265                 #add a hint due to a very consfusing error message when there is no space left on device
266                 raise SaveLoadError, _('Unable to save: %s\nDo you have enough space left on the device?') % e.message
267             else:
268                 raise SaveLoadError, _('Unable to save: %s') % e.message
269         except IOError, e:
270             traceback.print_exc()
271             raise SaveLoadError, _('Unable to save: %s') % e.strerror
272         self.unsaved_painting_time = 0.0
273
274     def load(self, filename):
275         if not os.path.isfile(filename):
276             raise SaveLoadError, _('File does not exist: %s') % repr(filename)
277         if not os.access(filename,os.R_OK):
278             raise SaveLoadError, _('You do not have the necessary permissions to open file: %s') % repr(filename)
279         trash, ext = os.path.splitext(filename)
280         ext = ext.lower().replace('.', '')
281         load = getattr(self, 'load_' + ext, self.unsupported)
282         try:
283             load(filename)
284         except gobject.GError, e:
285             traceback.print_exc()
286             raise SaveLoadError, _('Error while loading: GError %s') % e
287         except IOError, e:
288             traceback.print_exc()
289             raise SaveLoadError, _('Error while loading: IOError %s') % e
290         self.command_stack.clear()
291         self.unsaved_painting_time = 0.0
292         self.call_doc_observers()
293
294     def unsupported(self, filename):
295         raise SaveLoadError, _('Unknown file format extension: %s') % repr(filename)
296
297     def render_as_pixbuf(self, *args):
298         return pixbufsurface.render_as_pixbuf(self, *args)
299
300     def save_png(self, filename, compression=2, alpha=False, multifile=False):
301         if multifile:
302             self.save_multifile_png(filename, compression)
303         else:
304             if alpha:
305                 tmp_layer = layer.Layer()
306                 for l in self.layers:
307                     l.merge_into(tmp_layer)
308                 pixbuf = tmp_layer.surface.render_as_pixbuf()
309             else:
310                 pixbuf = self.render_as_pixbuf()
311             pixbuf.save(filename, 'png', {'compression':str(compression)})
312
313     def save_multifile_png(self, filename, compression=2, alpha=False):
314         prefix, ext = os.path.splitext(filename)
315         # if we have a number already, strip it
316         l = prefix.rsplit('.', 1)
317         if l[-1].isdigit():
318             prefix = l[0]
319         doc_bbox = self.get_bbox()
320         for i, l in enumerate(self.layers):
321             filename = '%s.%03d%s' % (prefix, i+1, ext)
322             l.surface.save(filename, *doc_bbox)
323
324     def load_png(self, filename):
325         self.load_from_pixbuf(gdk.pixbuf_new_from_file(filename))
326
327     def load_jpg(self, filename):
328         self.load_from_pixbuf(gdk.pixbuf_new_from_file(filename))
329     load_jpeg = load_jpg
330
331     def save_jpg(self, filename, quality=90):
332         pixbuf = self.render_as_pixbuf()
333         pixbuf.save(filename, 'jpeg', options={'quality':str(quality)})
334     save_jpeg = save_jpg
335
336     def save_ora(self, filename, options=None):
337         print 'save_ora:'
338         t0 = time.time()
339         tempdir = tempfile.mkdtemp('mypaint')
340         # use .tmp extension, so we don't overwrite a valid file if there is an exception
341         z = zipfile.ZipFile(filename + '.tmpsave', 'w', compression=zipfile.ZIP_STORED)
342         # work around a permission bug in the zipfile library: http://bugs.python.org/issue3394
343         def write_file_str(filename, data):
344             zi = zipfile.ZipInfo(filename)
345             zi.external_attr = 0100644 << 16
346             z.writestr(zi, data)
347         write_file_str('mimetype', 'image/openraster') # must be the first file
348         image = ET.Element('image')
349         stack = ET.SubElement(image, 'stack')
350         x0, y0, w0, h0 = self.get_bbox()
351         a = image.attrib
352         a['w'] = str(w0)
353         a['h'] = str(h0)
354
355         def store_pixbuf(pixbuf, name):
356             tmp = join(tempdir, 'tmp.png')
357             t1 = time.time()
358             pixbuf.save(tmp, 'png', {'compression':'2'})
359             print '  %.3fs saving %s compression 2' % (time.time() - t1, name)
360             z.write(tmp, name)
361             os.remove(tmp)
362
363         def add_layer(x, y, opac, pixbuf, name, layer_name, visible=True):
364             layer = ET.Element('layer')
365             stack.append(layer)
366             store_pixbuf(pixbuf, name)
367             a = layer.attrib
368             if layer_name:
369                 a['name'] = layer_name
370             a['src'] = name
371             a['x'] = str(x)
372             a['y'] = str(y)
373             a['opacity'] = str(opac)
374             if visible:
375                 a['visibility'] = 'visible'
376             else:
377                 a['visibility'] = 'hidden'
378             return layer
379
380         for idx, l in enumerate(reversed(self.layers)):
381             if l.surface.is_empty():
382                 continue
383             opac = l.opacity
384             x, y, w, h = l.surface.get_bbox()
385             pixbuf = l.surface.render_as_pixbuf()
386             el = add_layer(x-x0, y-y0, opac, pixbuf, 'data/layer%03d.png' % idx, l.name, l.visible)
387             # strokemap
388             data = l.save_strokemap_to_string(-x, -y)
389             name = 'data/layer%03d_strokemap.dat' % idx
390             el.attrib['mypaint_strokemap'] = name
391             write_file_str(name, data)
392
393         # save background as layer (solid color or tiled)
394         s = pixbufsurface.Surface(x0, y0, w0, h0)
395         s.fill(self.background)
396         l = add_layer(0, 0, 1.0, s.pixbuf, 'data/background.png', 'background')
397         bg = self.background
398         x, y, w, h = bg.get_pattern_bbox()
399         pixbuf = pixbufsurface.render_as_pixbuf(bg, x+x0, y+y0, w, h, alpha=False)
400         store_pixbuf(pixbuf, 'data/background_tile.png')
401         l.attrib['background_tile'] = 'data/background_tile.png'
402
403         # preview
404         t2 = time.time()
405         print '  starting to render image for thumbnail...'
406         pixbuf = self.render_as_pixbuf()
407         w, h = pixbuf.get_width(), pixbuf.get_height()
408         if w > h:
409             w, h = 256, max(h*256/w, 1)
410         else:
411             w, h = max(w*256/h, 1), 256
412         t1 = time.time()
413         pixbuf = pixbuf.scale_simple(w, h, gdk.INTERP_BILINEAR)
414         print '  %.3fs scaling thumbnail' % (time.time() - t1)
415         store_pixbuf(pixbuf, 'Thumbnails/thumbnail.png')
416         print '  total %.3fs spent on thumbnail' % (time.time() - t2)
417
418         helpers.indent_etree(image)
419         xml = ET.tostring(image, encoding='UTF-8')
420
421         write_file_str('stack.xml', xml)
422         z.close()
423         os.rmdir(tempdir)
424         if os.path.exists(filename):
425             os.remove(filename) # windows needs that
426         os.rename(filename + '.tmpsave', filename)
427
428         print '%.3fs save_ora total' % (time.time() - t0)
429
430     def load_ora(self, filename):
431         """Loads from an OpenRaster file"""
432         print 'load_ora:'
433         t0 = time.time()
434         tempdir = tempfile.mkdtemp('mypaint')
435         z = zipfile.ZipFile(filename)
436         print 'mimetype:', z.read('mimetype').strip()
437         xml = z.read('stack.xml')
438         image = ET.fromstring(xml)
439         stack = image.find('stack')
440
441         def get_pixbuf(filename):
442             t1 = time.time()
443             tmp = join(tempdir, 'tmp.png')
444             f = open(tmp, 'wb')
445             f.write(z.read(filename))
446             f.close()
447             res = gdk.pixbuf_new_from_file(tmp)
448             os.remove(tmp)
449             print '  %.3fs loading %s' % (time.time() - t1, filename)
450             return res
451
452         def get_layers_list(root, x=0,y=0):
453             res = []
454             for item in root:
455                 if item.tag == 'layer':
456                     if 'x' in item.attrib:
457                         item.attrib['x'] = int(item.attrib['x']) + x
458                     if 'y' in item.attrib:
459                         item.attrib['y'] = int(item.attrib['y']) + y
460                     res.append(item)
461                 elif item.tag == 'stack':
462                     stack_x = int( item.attrib.get('x', 0) )
463                     stack_y = int( item.attrib.get('y', 0) )
464                     res += get_layers_list(item, stack_x, stack_y)
465                 else:
466                     print 'Warning: ignoring unsupported tag:', item.tag
467             return res
468
469         self.clear() # this leaves one empty layer
470         no_background = True
471         for layer in get_layers_list(stack):
472             a = layer.attrib
473
474             if 'background_tile' in a:
475                 assert no_background
476                 try:
477                     print a['background_tile']
478                     self.set_background(get_pixbuf(a['background_tile']))
479                     no_background = False
480                     continue
481                 except backgroundsurface.BackgroundError, e:
482                     print 'ORA background tile not usable:', e
483
484             src = a.get('src', '')
485             if not src.lower().endswith('.png'):
486                 print 'Warning: ignoring non-png layer'
487                 continue
488             pixbuf = get_pixbuf(src)
489             name = a.get('name', '')
490             x = int(a.get('x', '0'))
491             y = int(a.get('y', '0'))
492             opac = float(a.get('opacity', '1.0'))
493             visible = not 'hidden' in a.get('visibility', 'visible')
494             self.add_layer(insert_idx=0, name=name)
495             last_pixbuf = pixbuf
496             t1 = time.time()
497             self.load_layer_from_pixbuf(pixbuf, x, y)
498             layer = self.layers[0]
499
500             self.set_layer_opacity(helpers.clamp(opac, 0.0, 1.0), layer)
501             self.set_layer_visibility(visible, layer)
502             print '  %.3fs converting pixbuf to layer format' % (time.time() - t1)
503             # strokemap
504             fname = a.get('mypaint_strokemap', None)
505             if fname:
506                 if x % N or y % N:
507                     print 'Warning: dropping non-aligned strokemap'
508                 else:
509                     data = z.read(fname)
510                     layer.load_strokemap_from_string(data, x, y)
511
512         os.rmdir(tempdir)
513
514         if len(self.layers) == 1:
515             raise ValueError, 'Could not load any layer.'
516
517         if no_background:
518             # recognize solid or tiled background layers, at least those that mypaint <= 0.7.1 saves
519             t1 = time.time()
520             p = last_pixbuf
521             if not p.get_has_alpha() and p.get_width() % N == 0 and p.get_height() % N == 0:
522                 tiles = self.layers[0].surface.tiledict.values()
523                 if len(tiles) > 1:
524                     all_equal = True
525                     for tile in tiles[1:]:
526                         if (tile.rgba != tiles[0].rgba).any():
527                             all_equal = False
528                             break
529                     if all_equal:
530                         arr = helpers.gdkpixbuf2numpy(p)
531                         tile = arr[0:N,0:N,:]
532                         self.set_background(tile.copy())
533                         self.select_layer(0)
534                         self.remove_layer()
535             print '  %.3fs recognizing tiled background' % (time.time() - t1)
536
537         if len(self.layers) > 1:
538             # remove the still present initial empty top layer
539             self.select_layer(len(self.layers)-1)
540             self.remove_layer()
541             # this leaves the topmost layer selected
542
543         print '%.3fs load_ora total' % (time.time() - t0)