when checking for windows check sys.platform starts with "win" rather then '== "win32...
[blender.git] / release / scripts / op / 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 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(name="File Path", description="Path to an image file", maxlen=1024, default="")
32
33     def _editor_guess(self, context):
34         import sys
35
36         image_editor = context.user_preferences.filepaths.image_editor
37
38         # use image editor in the preferences when available.
39         if not image_editor:
40             if sys.platform[:3] == "win":
41                 image_editor = ["start"]  # not tested!
42             elif sys.platform == "darwin":
43                 image_editor = ["open"]
44             else:
45                 image_editor = ["gimp"]
46         else:
47             if sys.platform == "darwin":
48                 # blender file selector treats .app as a folder
49                 # and will include a trailing backslash, so we strip it.
50                 image_editor.rstrip('\\')
51                 image_editor = ["open", "-a", image_editor]
52             else:
53                 image_editor = [image_editor]
54
55         return image_editor
56
57     def execute(self, context):
58         import os
59         import subprocess
60         filepath = bpy.path.abspath(self.filepath)
61
62         if not os.path.exists(filepath):
63             self.report('ERROR', "Image path %r not found." % filepath)
64             return {'CANCELLED'}
65
66         cmd = self._editor_guess(context) + [filepath]
67
68         subprocess.Popen(cmd)
69
70         return {'FINISHED'}
71
72     def invoke(self, context, event):
73         try:
74             filepath = context.space_data.image.filepath
75         except:
76             self.report({'ERROR'}, "Image not found on disk")
77             return {'CANCELLED'}
78
79         self.filepath = filepath
80         self.execute(context)
81
82         return {'FINISHED'}
83
84
85 class SaveDirty(bpy.types.Operator):
86     """Save all modified textures"""
87     bl_idname = "image.save_dirty"
88     bl_label = "Save Dirty"
89     bl_options = {'REGISTER', 'UNDO'}
90
91     def execute(self, context):
92         unique_paths = set()
93         for image in bpy.data.images:
94             if image.is_dirty:
95                 filepath = bpy.path.abspath(image.filepath)
96                 if "\\" not in filepath and "/" not in filepath:
97                     self.report({'WARNING'}, "Invalid path: " + filepath)
98                 elif filepath in unique_paths:
99                     self.report({'WARNING'}, "Path used by more then one image: " + filepath)
100                 else:
101                     unique_paths.add(filepath)
102                     image.save()
103         return {'FINISHED'}
104
105
106 class ProjectEdit(bpy.types.Operator):
107     """Edit a snapshot if the viewport in an external image editor"""
108     bl_idname = "image.project_edit"
109     bl_label = "Project Edit"
110     bl_options = {'REGISTER'}
111
112     _proj_hack = [""]
113
114     def execute(self, context):
115         import os
116         import subprocess
117
118         EXT = "png"  # could be made an option but for now ok
119
120         for image in bpy.data.images:
121             image.tag = True
122
123         if 'FINISHED' not in bpy.ops.paint.image_from_view():
124             return {'CANCELLED'}
125
126         image_new = None
127         for image in bpy.data.images:
128             if not image.tag:
129                 image_new = image
130                 break
131
132         if not image_new:
133             self.report({'ERROR'}, "Could not make new image")
134             return {'CANCELLED'}
135
136         filepath = os.path.basename(bpy.data.filepath)
137         filepath = os.path.splitext(filepath)[0]
138         # filepath = bpy.path.clean_name(filepath) # fixes <memory> rubbish, needs checking
139
140         if filepath.startswith(".") or filepath == "":
141             # TODO, have a way to check if the file is saved, assume startup.blend
142             tmpdir = context.user_preferences.filepaths.temporary_directory
143             filepath = os.path.join(tmpdir, "project_edit")
144         else:
145             filepath = "//" + filepath
146
147         obj = context.object
148
149         if obj:
150             filepath += "_" + bpy.path.clean_name(obj.name)
151
152         filepath_final = filepath + "." + EXT
153         i = 0
154
155         while os.path.exists(bpy.path.abspath(filepath_final)):
156             filepath_final = filepath + ("%.3d.%s" % (i, EXT))
157             i += 1
158
159         image_new.name = os.path.basename(filepath_final)
160         ProjectEdit._proj_hack[0] = image_new.name
161
162         image_new.filepath_raw = filepath_final  # TODO, filepath raw is crummy
163         image_new.file_format = 'PNG'
164         image_new.save()
165
166         bpy.ops.image.external_edit(filepath=filepath_final)
167
168         return {'FINISHED'}
169
170
171 class ProjectApply(bpy.types.Operator):
172     """Project edited image back onto the object"""
173     bl_idname = "image.project_apply"
174     bl_label = "Project Apply"
175     bl_options = {'REGISTER'}
176
177     def execute(self, context):
178         image_name = ProjectEdit._proj_hack[0]  # TODO, deal with this nicer
179
180         try:
181             image = bpy.data.images[image_name]
182         except KeyError:
183             self.report({'ERROR'}, "Could not find image '%s'" % image_name)
184             return {'CANCELLED'}
185
186         image.reload()
187         bpy.ops.paint.project_image(image=image_name)
188
189         return {'FINISHED'}
190
191
192 def register():
193     bpy.utils.register_module(__name__)
194
195
196 def unregister():
197     bpy.utils.unregister_module(__name__)
198
199 if __name__ == "__main__":
200     register()