5a9a308a098951040411cd26688c0ad504f6a0e9
[blender-addons-contrib.git] / text_editor_pasteall.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 bl_info = {
20     "name": "PasteAll",
21     "author": "Dalai Felinto (dfelinto)",
22     "version": (0,5),
23     "blender": (2, 5, 6),
24     "api": 34529,
25     "location": "Text editor > Properties panel",
26     "description": "Send your selection or text to www.pasteall.org",
27     "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\
28         "Scripts/Text_Editor/PasteAll",
29     "tracker_url": "https://projects.blender.org/tracker/index.php?"\
30         "func=detail&aid=23493",
31     "category": "Text Editor"}
32
33 # ########################################################
34 # PasteAll.org Text Sender Script
35 #
36 # Dalai Felinto (dfelinto)
37 # blenderecia.orgfree.com
38 #
39 # Rio de Janeiro - Brasil
40 # Vancouver - Canada
41 #
42 # Original code: 23rd August 2010 (Blender 2.5.3 rev. 31525)
43 #
44 # Important Note:
45 # This script is not official. I did it for fun and for my own usage.
46 # And please do not abuse of their generosity - use it wisely (a.k.a no flood).
47 #
48 # ########################################################
49
50
51 import bpy
52 import urllib
53 import urllib.request
54 import webbrowser
55
56 class TEXT_PT_pasteall(bpy.types.Panel):
57     bl_space_type = 'TEXT_EDITOR'
58     bl_region_type = 'UI'
59     bl_label = "PasteAll.org"
60
61     def draw(self, context):
62         layout = self.layout        
63         layout.operator("text.pasteall", icon='URL')
64         layout.prop(context.scene, "use_webbrowser")
65
66 class TEXT_OT_pasteall(bpy.types.Operator):
67     ''''''
68     bl_idname = "text.pasteall"
69     bl_label = "PasteAll.org"
70     bl_description = "Send the current text or selection to www.pasteall.org"
71
72     @classmethod
73     def poll(cls, context):
74         if context.area.type != 'TEXT_EDITOR':
75             return False
76         else:
77             return context.space_data.text != None
78
79     def invoke(self, context, event):
80         import webbrowser
81         st = context.space_data
82
83         # get the selected text
84         text = self.get_selected_text(st.text)
85         # if no text is selected send the whole file
86         if text is None: text = st.text.as_string()
87
88         # get the file type based on the extension
89         format = self.get_file_format(st.text)
90
91         # send the text and receive the returned page
92         html = self.send_text(text, format)
93
94         if html is None:
95             self.report('ERROR', "Error in sending the text to the server.")
96             return {'CANCELLED'}
97
98         # get the link of the posted page
99         page = self.get_page(str(html))
100         
101         if page is None or page == "":
102             self.report('ERROR', "Error in retrieving the page.")
103             return {'CANCELLED'}
104         else:
105             self.report('INFO', page)
106
107         # store the link in the clipboard
108         bpy.context.window_manager.clipboard = page
109
110         if context.scene.use_webbrowser:
111             try:
112                 webbrowser.open_new_tab(page)
113             except:
114                 self.report('WARNING', "Error in opening the page %s." % (page))
115
116         return {'FINISHED'}
117             
118     def send_text(self, text, format):
119         ''''''
120         import urllib
121         url = "http://www.pasteall.org/index.php"
122         values = {  'action' : 'savepaste',
123                     'parent_id' : '0',
124                     'language_id': format,
125                     'code' : text }
126
127         try:
128             data = urllib.parse.urlencode(values)
129             req = urllib.request.Request(url, data)
130             response = urllib.request.urlopen(req)
131             page_source = response.read()
132         except:
133             return None
134         else:
135             return page_source
136
137     def get_page(self, html):
138         ''''''
139         id = html.find('directlink')
140         id_begin = id + 12 # hardcoded: directlink">
141         id_end = html[id_begin:].find("</a>")
142
143         if id != -1 and id_end != -1:
144             return html[id_begin:id_begin + id_end]
145         else:
146             return None
147
148     def get_selected_text(self, text):
149         ''''''
150         current_line = text.current_line
151         select_end_line = text.select_end_line
152         
153         current_character = text.current_character
154         select_end_character = text.select_end_character
155         
156         # if there is no selected text return None
157         if current_line == select_end_line:
158             if current_character == select_end_character:
159                 return None
160             else:
161                 return current_line.body[min(current_character,select_end_character):max(current_character,select_end_character)]
162
163         text_return = None
164         writing = False
165         normal_order = True # selection from top to bottom
166
167         for line in text.lines:
168             if not writing:
169                 if line == current_line:
170                     text_return = current_line.body[current_character:] + "\n"
171                     writing = True
172                     continue
173                 elif line == select_end_line:
174                     text_return =  select_end_line.body[select_end_character:] + "\n"
175                     writing = True
176                     normal_order = False
177                     continue
178             else:
179                 if normal_order:
180                     if line == select_end_line:
181                         text_return += select_end_line.body[:select_end_character]
182                         break
183                     else:
184                         text_return += line.body + "\n"
185                         continue
186                 else:
187                     if line == current_line:
188                         text_return += current_line.body[:current_character]
189                         break
190                     else:
191                         text_return += line.body + "\n"
192                         continue
193
194         return text_return
195     
196     def get_file_format(self, text):
197         '''Try to guess what is the format based on the file extension'''
198         extensions =   {'diff':'24',
199                         'patch':'24',
200                         'py':'62',
201                         'c':'12',
202                         'cpp':'18'}
203
204         type = text.name.split(".")[-1]
205         return extensions.get(type, '0')
206
207 def register():
208     bpy.types.Scene.use_webbrowser = bpy.props.BoolProperty(
209         name='Launch Browser',
210         description='Opens the page with the submitted text.',
211         default=True)
212
213 def unregister():
214     del bpy.types.Scene.use_webbrowser
215
216 if __name__ == "__main__":
217     register()