- update X3D and FBX testing checksums
[blender.git] / release / scripts / startup / bl_operators / image.py
1 # ##### BEGIN GPL LICENSE BLOCK #####
2 #
3 #  This program is free software; you can redistribute it and/or
4 #  modify it under the terms of the GNU General Public License
5 #  as published by the Free Software Foundation; either version 2
6 #  of the License, or (at your option) any later version.
7 #
8 #  This program is distributed in the hope that it will be useful,
9 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 #  GNU General Public License for more details.
12 #
13 #  You should have received a copy of the GNU General Public License
14 #  along with this program; if not, write to the Free Software Foundation,
15 #  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 #
17 # ##### END GPL LICENSE BLOCK #####
18
19 # <pep8-80 compliant>
20
21 import bpy
22 from bpy.props import StringProperty
23
24
25 class EditExternally(bpy.types.Operator):
26     '''Edit image in an external application'''
27     bl_idname = "image.external_edit"
28     bl_label = "Image Edit Externally"
29     bl_options = {'REGISTER'}
30
31     filepath = StringProperty(
32             name="File Path",
33             description="Path to an image file",
34             maxlen=1024,
35             )
36
37     def _editor_guess(self, context):
38         import sys
39
40         image_editor = context.user_preferences.filepaths.image_editor
41
42         # use image editor in the preferences when available.
43         if not image_editor:
44             if sys.platform[:3] == "win":
45                 image_editor = ["start"]  # not tested!
46             elif sys.platform == "darwin":
47                 image_editor = ["open"]
48             else:
49                 image_editor = ["gimp"]
50         else:
51             if sys.platform == "darwin":
52                 # blender file selector treats .app as a folder
53                 # and will include a trailing backslash, so we strip it.
54                 image_editor.rstrip('\\')
55                 image_editor = ["open", "-a", image_editor]
56             else:
57                 image_editor = [image_editor]
58
59         return image_editor
60
61     def execute(self, context):
62         import os
63         import subprocess
64
65         filepath = self.filepath
66
67         if not filepath:
68             self.report({'ERROR'}, "Image path not set")
69             return {'CANCELLED'}
70
71         filepath = os.path.normpath(bpy.path.abspath(filepath))
72
73         if not os.path.exists(filepath):
74             self.report({'ERROR'},
75                         "Image path %r not found, image may be packed or "
76                         "unsaved." % filepath)
77             return {'CANCELLED'}
78
79         cmd = self._editor_guess(context) + [filepath]
80
81         try:
82             subprocess.Popen(cmd)
83         except:
84             import traceback
85             traceback.print_exc()
86             self.report({'ERROR'},
87                         "Image editor not found, "
88                         "please specify in User Preferences > File")
89
90             return {'CANCELLED'}
91
92         return {'FINISHED'}
93
94     def invoke(self, context, event):
95         try:
96             filepath = context.space_data.image.filepath
97         except:
98             import traceback
99             traceback.print_exc()
100             self.report({'ERROR'}, "Image not found on disk")
101             return {'CANCELLED'}
102
103         self.filepath = filepath
104         self.execute(context)
105
106         return {'FINISHED'}
107
108
109 class SaveDirty(bpy.types.Operator):
110     """Save all modified textures"""
111     bl_idname = "image.save_dirty"
112     bl_label = "Save Dirty"
113     bl_options = {'REGISTER', 'UNDO'}
114
115     def execute(self, context):
116         unique_paths = set()
117         for image in bpy.data.images:
118             if image.is_dirty:
119                 filepath = bpy.path.abspath(image.filepath)
120                 if "\\" not in filepath and "/" not in filepath:
121                     self.report({'WARNING'}, "Invalid path: " + filepath)
122                 elif filepath in unique_paths:
123                     self.report({'WARNING'},
124                                 "Path used by more then one image: %r" %
125                                 filepath)
126                 else:
127                     unique_paths.add(filepath)
128                     image.save()
129         return {'FINISHED'}
130
131
132 class ProjectEdit(bpy.types.Operator):
133     """Edit a snapshot of the viewport in an external image editor"""
134     bl_idname = "image.project_edit"
135     bl_label = "Project Edit"
136     bl_options = {'REGISTER'}
137
138     _proj_hack = [""]
139
140     def execute(self, context):
141         import os
142
143         EXT = "png"  # could be made an option but for now ok
144
145         for image in bpy.data.images:
146             image.tag = True
147
148         if 'FINISHED' not in bpy.ops.paint.image_from_view():
149             return {'CANCELLED'}
150
151         image_new = None
152         for image in bpy.data.images:
153             if not image.tag:
154                 image_new = image
155                 break
156
157         if not image_new:
158             self.report({'ERROR'}, "Could not make new image")
159             return {'CANCELLED'}
160
161         filepath = os.path.basename(bpy.data.filepath)
162         filepath = os.path.splitext(filepath)[0]
163         # fixes <memory> rubbish, needs checking
164         # filepath = bpy.path.clean_name(filepath)
165
166         if bpy.data.is_saved:
167             filepath = "//" + filepath
168         else:
169             tmpdir = context.user_preferences.filepaths.temporary_directory
170             filepath = os.path.join(tmpdir, "project_edit")
171
172         obj = context.object
173
174         if obj:
175             filepath += "_" + bpy.path.clean_name(obj.name)
176
177         filepath_final = filepath + "." + EXT
178         i = 0
179
180         while os.path.exists(bpy.path.abspath(filepath_final)):
181             filepath_final = filepath + ("%.3d.%s" % (i, EXT))
182             i += 1
183
184         image_new.name = bpy.path.basename(filepath_final)
185         ProjectEdit._proj_hack[0] = image_new.name
186
187         image_new.filepath_raw = filepath_final  # TODO, filepath raw is crummy
188         image_new.file_format = 'PNG'
189         image_new.save()
190
191         try:
192             bpy.ops.image.external_edit(filepath=filepath_final)
193         except RuntimeError as re:
194             self.report({'ERROR'}, str(re))
195
196         return {'FINISHED'}
197
198
199 class ProjectApply(bpy.types.Operator):
200     """Project edited image back onto the object"""
201     bl_idname = "image.project_apply"
202     bl_label = "Project Apply"
203     bl_options = {'REGISTER'}
204
205     def execute(self, context):
206         image_name = ProjectEdit._proj_hack[0]  # TODO, deal with this nicer
207
208         try:
209             image = bpy.data.images[image_name]
210         except KeyError:
211             import traceback
212             traceback.print_exc()
213             self.report({'ERROR'}, "Could not find image '%s'" % image_name)
214             return {'CANCELLED'}
215
216         image.reload()
217         bpy.ops.paint.project_image(image=image_name)
218
219         return {'FINISHED'}