1 # This file is part of MyPaint.
2 # Copyright (C) 2007-2008 by Martin Renold <martinxyz@gmx.ch>
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.
9 import os, zipfile, tempfile, time, traceback
11 import xml.etree.ElementTree as ET
14 from gettext import gettext as _
16 import helpers, tiledsurface, pixbufsurface, backgroundsurface, mypaintlib
17 import command, stroke, layer
21 class SaveLoadError(Exception):
22 """Expected errors on loading or saving, like missing permissions or non-existing files."""
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.
32 The "controller" mostly in drawwindow.py.
33 It is possible to use it without any GUI attached (see ../tests/)
35 # Please note the following difficulty with the undo stack:
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.
43 self.brush = brush.Brush()
45 self.canvas_observers = []
46 self.stroke_observers = [] # callback arguments: stroke, brush (brush is a temporary read-only convenience object)
47 self.doc_observers = []
50 def call_doc_observers(self):
51 for f in self.doc_observers:
55 def clear(self, init=False):
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))
65 # disallow undo of the first layer
66 self.command_stack.clear()
67 self.unsaved_painting_time = 0.0
70 for f in self.canvas_observers:
73 self.call_doc_observers()
75 def get_current_layer(self):
76 return self.layers[self.layer_idx]
77 layer = property(get_current_layer)
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)
90 def select_layer(self, idx):
91 self.do(command.SelectLayer(self, idx))
93 def move_layer(self, was_idx, new_idx):
94 self.do(command.MoveLayer(self, was_idx, new_idx))
96 def clear_layer(self):
97 if not self.layer.surface.is_empty():
98 self.do(command.ClearLayer(self))
100 def stroke_to(self, dtime, x, y, pressure):
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)
108 l.surface.begin_atomic()
109 split = self.brush.stroke_to (l.surface, x, y, pressure, dtime)
110 l.surface.end_atomic()
115 def straight_line(self, src, dst):
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)
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)
132 self.stroke_to(duration/N, x[i], y[i], pressure)
134 self.brush = real_brush
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:
142 def invalidate_all(self):
143 for f in self.canvas_observers:
149 cmd = self.command_stack.undo()
150 if not cmd or not cmd.automatic_undo:
156 cmd = self.command_stack.redo()
157 if not cmd or not cmd.automatic_undo:
162 self.command_stack.do(cmd)
164 def get_last_command(self):
166 return self.command_stack.get_last_command()
168 def set_brush(self, brush):
170 self.brush.copy_settings_from(brush)
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)
181 def blit_tile_into(self, dst_8bit, tx, ty, mipmap=0, layers=None, background=None):
184 if background is None:
185 background = self.background
187 assert dst_8bit.dtype == 'uint8'
188 dst = numpy.empty((N, N, 3), dtype='uint16')
190 background.blit_tile_into(dst, tx, ty, mipmap)
193 surface = layer.surface
194 surface.composite_tile_over(dst, tx, ty, mipmap_level=mipmap, opacity=layer.effective_opacity)
196 mypaintlib.tile_convert_rgb16_to_rgb8(dst, dst_8bit)
198 def add_layer(self, insert_idx=None, after=None, name=''):
199 self.do(command.AddLayer(self, insert_idx, after, name))
201 def remove_layer(self,layer=None):
202 if len(self.layers) > 1:
203 self.do(command.RemoveLayer(self,layer))
207 def merge_layer_down(self):
208 dst_idx = self.layer_idx - 1
211 self.do(command.MergeLayer(self, dst_idx))
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))
218 def set_layer_visibility(self, visible, layer=None):
219 cmd = self.get_last_command()
220 if isinstance(cmd, command.SetLayerVisibility):
222 self.do(command.SetLayerVisibility(self, visible, layer))
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):
229 self.do(command.SetLayerOpacity(self, opacity, layer))
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.
235 if not isinstance(obj, backgroundsurface.Background):
236 obj = backgroundsurface.Background(obj)
237 self.background = obj
239 self.invalidate_all()
241 def load_from_pixbuf(self, pixbuf):
243 self.load_layer_from_pixbuf(pixbuf)
245 def is_layered(self):
247 for l in self.layers:
248 if not l.surface.is_empty():
253 return len(self.layers) == 1 and self.layer.surface.is_empty()
255 def save(self, filename, **kwargs):
257 trash, ext = os.path.splitext(filename)
258 ext = ext.lower().replace('.', '')
259 save = getattr(self, 'save_' + ext, self.unsupported)
261 save(filename, **kwargs)
262 except gobject.GError, e:
263 traceback.print_exc()
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
268 raise SaveLoadError, _('Unable to save: %s') % e.message
270 traceback.print_exc()
271 raise SaveLoadError, _('Unable to save: %s') % e.strerror
272 self.unsaved_painting_time = 0.0
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)
284 except gobject.GError, e:
285 traceback.print_exc()
286 raise SaveLoadError, _('Error while loading: GError %s') % 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()
294 def unsupported(self, filename):
295 raise SaveLoadError, _('Unknown file format extension: %s') % repr(filename)
297 def render_as_pixbuf(self, *args):
298 return pixbufsurface.render_as_pixbuf(self, *args)
300 def save_png(self, filename, compression=2, alpha=False, multifile=False):
302 self.save_multifile_png(filename, compression)
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()
310 pixbuf = self.render_as_pixbuf()
311 pixbuf.save(filename, 'png', {'compression':str(compression)})
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)
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)
324 def load_png(self, filename):
325 self.load_from_pixbuf(gdk.pixbuf_new_from_file(filename))
327 def load_jpg(self, filename):
328 self.load_from_pixbuf(gdk.pixbuf_new_from_file(filename))
331 def save_jpg(self, filename, quality=90):
332 pixbuf = self.render_as_pixbuf()
333 pixbuf.save(filename, 'jpeg', options={'quality':str(quality)})
336 def save_ora(self, filename, options=None):
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
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()
355 def store_pixbuf(pixbuf, name):
356 tmp = join(tempdir, 'tmp.png')
358 pixbuf.save(tmp, 'png', {'compression':'2'})
359 print ' %.3fs saving %s compression 2' % (time.time() - t1, name)
363 def add_layer(x, y, opac, pixbuf, name, layer_name, visible=True):
364 layer = ET.Element('layer')
366 store_pixbuf(pixbuf, name)
369 a['name'] = layer_name
373 a['opacity'] = str(opac)
375 a['visibility'] = 'visible'
377 a['visibility'] = 'hidden'
380 for idx, l in enumerate(reversed(self.layers)):
381 if l.surface.is_empty():
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)
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)
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')
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'
405 print ' starting to render image for thumbnail...'
406 pixbuf = self.render_as_pixbuf()
407 w, h = pixbuf.get_width(), pixbuf.get_height()
409 w, h = 256, max(h*256/w, 1)
411 w, h = max(w*256/h, 1), 256
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)
418 helpers.indent_etree(image)
419 xml = ET.tostring(image, encoding='UTF-8')
421 write_file_str('stack.xml', xml)
424 if os.path.exists(filename):
425 os.remove(filename) # windows needs that
426 os.rename(filename + '.tmpsave', filename)
428 print '%.3fs save_ora total' % (time.time() - t0)
430 def load_ora(self, filename):
431 """Loads from an OpenRaster file"""
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')
441 def get_pixbuf(filename):
443 tmp = join(tempdir, 'tmp.png')
445 f.write(z.read(filename))
447 res = gdk.pixbuf_new_from_file(tmp)
449 print ' %.3fs loading %s' % (time.time() - t1, filename)
452 def get_layers_list(root, x=0,y=0):
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
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)
466 print 'Warning: ignoring unsupported tag:', item.tag
469 self.clear() # this leaves one empty layer
471 for layer in get_layers_list(stack):
474 if 'background_tile' in a:
477 print a['background_tile']
478 self.set_background(get_pixbuf(a['background_tile']))
479 no_background = False
481 except backgroundsurface.BackgroundError, e:
482 print 'ORA background tile not usable:', e
484 src = a.get('src', '')
485 if not src.lower().endswith('.png'):
486 print 'Warning: ignoring non-png layer'
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)
497 self.load_layer_from_pixbuf(pixbuf, x, y)
498 layer = self.layers[0]
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)
504 fname = a.get('mypaint_strokemap', None)
507 print 'Warning: dropping non-aligned strokemap'
510 layer.load_strokemap_from_string(data, x, y)
514 if len(self.layers) == 1:
515 raise ValueError, 'Could not load any layer.'
518 # recognize solid or tiled background layers, at least those that mypaint <= 0.7.1 saves
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()
525 for tile in tiles[1:]:
526 if (tile.rgba != tiles[0].rgba).any():
530 arr = helpers.gdkpixbuf2numpy(p)
531 tile = arr[0:N,0:N,:]
532 self.set_background(tile.copy())
535 print ' %.3fs recognizing tiled background' % (time.time() - t1)
537 if len(self.layers) > 1:
538 # remove the still present initial empty top layer
539 self.select_layer(len(self.layers)-1)
541 # this leaves the topmost layer selected
543 print '%.3fs load_ora total' % (time.time() - t0)