1 """All ROX applications that can save documents should use drag-and-drop saving.
2 The document itself should use the Saveable mix-in class and override some of the
3 methods to actually do the save.
5 If you want to save a selection then you can create a new object specially for
6 the purpose and pass that to the SaveBox."""
10 from rox
import alert
, info
, g
, _
, filer
11 from rox
import choices
, get_local_path
, TRUE
, FALSE
12 from icon_theme
import rox_theme
19 def _write_xds_property(context
, value
):
20 win
= context
.source_window
22 win
.property_change('XdndDirectSave0', 'text/plain', 8,
23 gdk
.PROP_MODE_REPLACE
,
26 win
.property_delete('XdndDirectSave0')
28 def _read_xds_property(context
, delete
):
29 win
= context
.source_window
30 retval
= win
.property_get('XdndDirectSave0', 'text/plain', delete
)
35 def image_for_type(type):
36 'Search <Choices> for a suitable icon. Returns a pixbuf, or None.'
37 media
, subtype
= type.split('/', 1)
38 path
= choices
.load('MIME-icons', media
+ '_' + subtype
+ '.png')
40 icon
= 'mime-%s:%s' % (media
, subtype
)
42 path
= rox_theme
.lookup_icon(icon
, 48)
44 icon
= 'mime-%s' % media
45 path
= rox_theme
.lookup_icon(icon
, 48)
47 print "Error loading MIME icon"
49 path
= choices
.load('MIME-icons', media
+ '.png')
51 return gdk
.pixbuf_new_from_file(path
)
55 def _report_save_error():
56 "Report a SaveAbort nicely, otherwise use report_exception()"
57 type, value
= sys
.exc_info()[:2]
58 if isinstance(value
, AbortSave
):
61 rox
.report_exception()
63 class AbortSave(Exception):
64 """Raise this to cancel a save. If a message is given, it is displayed
65 in a normal alert box (not in the report_exception style). If the
66 message is None, no message is shown (you should have already shown
68 def __init__(self
, message
):
69 self
.message
= message
73 rox
.alert(self
.message
)
76 """This class describes the interface that an object must provide
77 to work with the SaveBox/SaveArea widgets. Inherit from it if you
78 want to save. All methods can be overridden, but normally only
79 save_to_stream() needs to be."""
81 def set_uri(self
, uri
):
82 """When the data is safely saved somewhere this is called
83 with its new name. Mark your data as unmodified and update
84 the filename for next time. Saving to another application
85 won't call this method. Default method does nothing."""
88 def save_to_stream(self
, stream
):
89 """Write the data to save to the stream. When saving to a
90 local file, stream will be the actual file, otherwise it is a
92 raise Exception('You forgot to write the save_to_stream() method...'
95 def save_to_file(self
, path
):
96 """Write data to file. Raise an exception on error.
97 The default creates a temporary file, uses save_to_stream() to
98 write to it, then renames it over the original. If the temporary file
99 can't be created, it writes directly over the original."""
101 # Ensure the directory exists...
102 dir = os
.path
.dirname(path
)
103 if not os
.path
.isdir(dir):
104 from rox
import fileutils
106 fileutils
.makedirs(dir)
108 raise AbortSave(None) # (message already shown)
111 tmp
= 'tmp-' + `random
.randrange(1000000)`
112 tmp
= os
.path
.join(dir, tmp
)
115 return os
.fdopen(os
.open(path
, os
.O_CREAT | os
.O_WRONLY
, 0600), 'wb')
120 # Can't create backup... try a direct write
125 self
.save_to_stream(file)
132 if tmp
and os
.path
.exists(tmp
):
133 if os
.path
.getsize(tmp
) == 0 or \
134 rox
.confirm(_("Delete temporary file '%s'?") % tmp
,
137 raise AbortSave(None)
138 self
.save_set_permissions(path
)
141 def save_to_selection(self
, selection_data
):
142 """Write data to the selection. The default method uses save_to_stream()."""
143 from cStringIO
import StringIO
145 self
.save_to_stream(stream
)
146 selection_data
.set(selection_data
.target
, 8, stream
.getvalue())
149 def save_set_permissions(self
, path
):
150 """The default save_to_file() creates files with the mode 0600
151 (user read/write only). After saving has finished, it calls this
152 method to set the final permissions. The save_set_permissions():
153 - sets it to 0666 masked with the umask (if save_mode is None), or
154 - sets it to save_mode (not masked) otherwise."""
155 if self
.save_mode
is not None:
156 os
.chmod(path
, self
.save_mode
)
158 mask
= os
.umask(0077) # Get the current umask
159 os
.umask(mask
) # Set it back how it was
160 os
.chmod(path
, 0666 & ~mask
)
163 """Time to close the savebox. Default method does nothing."""
167 """Discard button clicked, or document safely saved. Only called if a SaveBox
168 was created with discard=1.
169 The user doesn't want the document any more, even if it's modified and unsaved.
171 raise Exception("Sorry... my programmer forgot to tell me how to handle Discard!")
173 save_to_stream
._rox
_default
= 1
174 save_to_file
._rox
_default
= 1
175 save_to_selection
._rox
_default
= 1
176 def can_save_to_file(self
):
177 """Indicates whether we have a working save_to_stream or save_to_file
178 method (ie, whether we can save to files). Default method checks that
179 one of these two methods has been overridden."""
180 if not hasattr(self
.save_to_stream
, '_rox_default'):
181 return 1 # Have user-provided save_to_stream
182 if not hasattr(self
.save_to_file
, '_rox_default'):
183 return 1 # Have user-provided save_to_file
185 def can_save_to_selection(self
):
186 """Indicates whether we have a working save_to_stream or save_to_selection
187 method (ie, whether we can save to selections). Default methods checks that
188 one of these two methods has been overridden."""
189 if not hasattr(self
.save_to_stream
, '_rox_default'):
190 return 1 # Have user-provided save_to_stream
191 if not hasattr(self
.save_to_selection
, '_rox_default'):
192 return 1 # Have user-provided save_to_file
195 def save_cancelled(self
):
196 """If you multitask during a save (using a recursive mainloop) then the
197 user may click on the Cancel button. This function gets called if so, and
198 should cause the recursive mainloop to return."""
199 raise Exception("Lazy programmer error: can't abort save!")
201 class SaveArea(g
.VBox
):
202 """A SaveArea contains the widgets used in a save box. You can use
203 this to put a savebox area in a larger window."""
204 def __init__(self
, document
, uri
, type):
205 """'document' must be a subclass of Saveable.
206 'uri' is the file's current location, or a simple name (eg 'TextFile')
207 if it has never been saved.
208 'type' is the MIME-type to use (eg 'text/plain').
210 g
.VBox
.__init
__(self
, FALSE
, 0)
212 self
.document
= document
213 self
.initial_uri
= uri
215 drag_area
= self
._create
_drag
_area
(type)
216 self
.pack_start(drag_area
, TRUE
, TRUE
, 0)
220 entry
.connect('activate', lambda w
: self
.save_to_file_in_entry())
222 self
.pack_start(entry
, FALSE
, TRUE
, 4)
227 def _set_icon(self
, type):
228 pixbuf
= image_for_type(type)
230 self
.icon
.set_from_pixbuf(pixbuf
)
232 self
.icon
.set_from_stock(g
.STOCK_MISSING_IMAGE
, g
.ICON_SIZE_DND
)
234 def _create_drag_area(self
, type):
235 align
= g
.Alignment()
236 align
.set(.5, .5, 0, 0)
238 self
.drag_box
= g
.EventBox()
239 self
.drag_box
.set_border_width(4)
240 self
.drag_box
.add_events(gdk
.BUTTON_PRESS_MASK
)
241 align
.add(self
.drag_box
)
243 self
.icon
= g
.Image()
246 self
._set
_drag
_source
(type)
247 self
.drag_box
.connect('drag_begin', self
.drag_begin
)
248 self
.drag_box
.connect('drag_end', self
.drag_end
)
249 self
.drag_box
.connect('drag_data_get', self
.drag_data_get
)
250 self
.drag_in_progress
= 0
252 self
.drag_box
.add(self
.icon
)
256 def set_type(self
, type, icon
= None):
257 """Change the icon and drag target to 'type'.
258 If 'icon' is given (as a GtkImage) then that icon is used,
259 otherwise an appropriate icon for the type is used."""
261 self
.icon
.set_from_pixbuf(icon
.get_pixbuf())
264 self
._set
_drag
_source
(type)
266 def _set_drag_source(self
, type):
267 if self
.document
.can_save_to_file():
268 targets
= [('XdndDirectSave0', 0, TARGET_XDS
)]
271 if self
.document
.can_save_to_selection():
272 targets
= targets
+ [(type, 0, TARGET_RAW
),
273 ('application/octet-stream', 0, TARGET_RAW
)]
276 raise Exception("Document %s can't save!" % self
.document
)
277 self
.drag_box
.drag_source_set(gdk
.BUTTON1_MASK | gdk
.BUTTON3_MASK
,
279 gdk
.ACTION_COPY | gdk
.ACTION_MOVE
)
281 def save_to_file_in_entry(self
):
282 """Call this when the user clicks on an OK button you provide."""
283 uri
= self
.entry
.get_text()
284 path
= get_local_path(uri
)
287 if not self
.confirm_new_path(path
):
290 self
.set_sensitive(FALSE
)
292 self
.document
.save_to_file(path
)
294 self
.set_sensitive(TRUE
)
300 rox
.info(_("Drag the icon to a directory viewer\n"
301 "(or enter a full pathname)"))
303 def drag_begin(self
, drag_box
, context
):
304 self
.drag_in_progress
= 1
305 self
.destroy_on_drag_end
= 0
309 pixbuf
= self
.icon
.get_pixbuf()
311 drag_box
.drag_source_set_icon_pixbuf(pixbuf
)
313 uri
= self
.entry
.get_text()
322 _write_xds_property(context
, leaf
)
324 def drag_data_get(self
, widget
, context
, selection_data
, info
, time
):
325 if info
== TARGET_RAW
:
327 self
.set_sensitive(FALSE
)
329 self
.document
.save_to_selection(selection_data
)
331 self
.set_sensitive(TRUE
)
334 _write_xds_property(context
, None)
338 _write_xds_property(context
, None)
340 if self
.drag_in_progress
:
341 self
.destroy_on_drag_end
= 1
345 elif info
!= TARGET_XDS
:
346 _write_xds_property(context
, None)
347 alert("Bad target requested!")
352 # Get the path that the destination app wants us to save to.
353 # If it's local, save and return Success
354 # (or Error if save fails)
355 # If it's remote, return Failure (remote may try another method)
356 # If no URI is given, return Error
358 uri
= _read_xds_property(context
, FALSE
)
360 path
= get_local_path(uri
)
362 if not self
.confirm_new_path(path
):
366 self
.set_sensitive(FALSE
)
368 self
.document
.save_to_file(path
)
370 self
.set_sensitive(TRUE
)
371 self
.data_sent
= TRUE
374 self
.data_sent
= FALSE
379 to_send
= 'F' # Non-local transfer
381 alert("Remote application wants to use " +
382 "Direct Save, but I can't read the " +
383 "XdndDirectSave0 (type text/plain) " +
386 selection_data
.set(selection_data
.target
, 8, to_send
)
389 _write_xds_property(context
, None)
390 path
= get_local_path(uri
)
398 def confirm_new_path(self
, path
):
399 """Use wants to save to this path. If it's different to the original path,
400 check that it doesn't exist and ask for confirmation if it does. Returns true
401 to go ahead with the save."""
402 if path
== self
.initial_uri
:
404 if not os
.path
.exists(path
):
406 return rox
.confirm(_("File '%s' already exists -- overwrite it?") % path
,
407 g
.STOCK_DELETE
, _('_Overwrite'))
409 def set_uri(self
, uri
):
410 "Data is safely saved somewhere. Update the document's URI. Internal."
411 self
.document
.set_uri(uri
)
413 def drag_end(self
, widget
, context
):
414 self
.drag_in_progress
= 0
415 if self
.destroy_on_drag_end
:
419 self
.document
.save_done()
421 class SaveBox(g
.Dialog
):
422 """A SaveBox is a GtkDialog that contains a SaveArea and, optionally, a Discard button.
423 Calls rox.toplevel_(un)ref automatically.
426 def __init__(self
, document
, uri
, type = 'text/plain', discard
= FALSE
):
427 """See SaveArea.__init__.
428 If discard is TRUE then an extra discard button is added to the dialog."""
429 g
.Dialog
.__init
__(self
)
430 self
.set_has_separator(FALSE
)
432 self
.add_button(g
.STOCK_CANCEL
, g
.RESPONSE_CANCEL
)
433 self
.add_button(g
.STOCK_SAVE
, g
.RESPONSE_OK
)
434 self
.set_default_response(g
.RESPONSE_OK
)
437 discard_area
= g
.HButtonBox()
439 def discard_clicked(event
):
442 button
= rox
.ButtonMixed(g
.STOCK_DELETE
, _('_Discard'))
443 discard_area
.pack_start(button
, FALSE
, TRUE
, 2)
444 button
.connect('clicked', discard_clicked
)
445 button
.unset_flags(g
.CAN_FOCUS
)
446 button
.set_flags(g
.CAN_DEFAULT
)
447 self
.vbox
.pack_end(discard_area
, FALSE
, TRUE
, 0)
448 self
.vbox
.reorder_child(discard_area
, 0)
450 discard_area
.show_all()
452 self
.set_title(_('Save As:'))
453 self
.set_position(g
.WIN_POS_MOUSE
)
454 self
.set_wmclass('savebox', 'Savebox')
455 self
.set_border_width(1)
457 # Might as well make use of the new nested scopes ;-)
458 self
.set_save_in_progress(0)
459 class BoxedArea(SaveArea
):
460 def set_uri(area
, uri
):
461 document
.set_uri(uri
)
468 def set_sensitive(area
, sensitive
):
470 # Might have been destroyed by now...
471 self
.set_save_in_progress(not sensitive
)
472 SaveArea
.set_sensitive(area
, sensitive
)
473 save_area
= BoxedArea(document
, uri
, type)
474 self
.save_area
= save_area
477 self
.build_main_area()
481 # Have to do this here, or the selection gets messed up
482 save_area
.entry
.grab_focus()
483 g
.Editable
.select_region(save_area
.entry
, i
, -1) # PyGtk bug
484 #save_area.entry.select_region(i, -1)
486 def got_response(widget
, response
):
487 if self
.save_in_progress
:
489 document
.save_cancelled()
491 rox
.report_exception()
493 if response
== g
.RESPONSE_CANCEL
:
495 elif response
== g
.RESPONSE_OK
:
496 self
.save_area
.save_to_file_in_entry()
497 elif response
== g
.RESPONSE_DELETE_EVENT
:
500 raise Exception('Unknown response!')
501 self
.connect('response', got_response
)
504 self
.connect('destroy', lambda w
: rox
.toplevel_unref())
506 def set_type(self
, type, icon
= None):
507 """See SaveArea's method of the same name."""
508 self
.save_area
.set_type(type, icon
)
510 def build_main_area(self
):
511 """Place self.save_area somewhere in self.vbox. Override this
512 for more complicated layouts."""
513 self
.vbox
.add(self
.save_area
)
515 def set_save_in_progress(self
, in_progress
):
516 """Called when saving starts and ends. Shade/unshade any widgets as
517 required. Make sure you call the default method too!
518 Not called if box is destroyed from a recursive mainloop inside
519 a save_to_* function."""
520 self
.set_response_sensitive(g
.RESPONSE_OK
, not in_progress
)
521 self
.save_in_progress
= in_progress
523 class StringSaver(SaveBox
, Saveable
):
524 """A very simple SaveBox which saves the string passed to its constructor."""
525 def __init__(self
, string
, name
):
526 """'string' is the string to save. 'name' is the default filename"""
527 SaveBox
.__init
__(self
, self
, name
, 'text/plain')
530 def save_to_stream(self
, stream
):
531 stream
.write(self
.string
)
533 class SaveFilter(Saveable
):
534 """This Saveable runs a process in the background to generate the
535 save data. Any python streams can be used as the input to and
536 output from the process.
538 The output from the subprocess is saved to the output stream (either
539 directly, for fileno() streams, or via another temporary file).
541 If the process returns a non-zero exit status or writes to stderr,
542 the save fails (messages written to stderr are displayed).
547 def set_stdin(self
, stream
):
548 """Use 'stream' as stdin for the process. If stream is not a
549 seekable fileno() stream then it is copied to a temporary file
550 at this point. If None, the child process will get /dev/null on
552 if stream
is not None:
553 if hasattr(stream
, 'fileno') and hasattr(stream
, 'seek'):
558 self
.stdin
= tempfile
.TemporaryFile()
559 shutil
.copyfileobj(stream
, self
.stdin
)
563 def save_to_stream(self
, stream
):
564 from processes
import Process
565 from cStringIO
import StringIO
569 # Get the FD for the output, creating a tmp file if needed
570 if hasattr(stream
, 'fileno'):
571 stdout_fileno
= stream
.fileno()
575 tmp
= tempfile
.TemporaryFile()
576 stdout_fileno
= tmp
.fileno()
578 # Get the FD for the input
580 stdin_fileno
= self
.stdin
.fileno()
583 stdin_fileno
= os
.open('/dev/null', os
.O_RDONLY
)
585 class FilterProcess(Process
):
586 def child_post_fork(self
):
587 if stdout_fileno
!= 1:
588 os
.dup2(stdout_fileno
, 1)
589 os
.close(stdout_fileno
)
590 if stdin_fileno
is not None and stdin_fileno
!= 0:
591 os
.dup2(stdin_fileno
, 0)
592 os
.close(stdin_fileno
)
593 def got_error_output(self
, data
):
595 def child_died(self
, status
):
600 self
.process
= FilterProcess()
608 print >> errors
, '\nProcess terminated at user request'
609 error
= errors
.getvalue().strip()
611 raise AbortSave(error
)
613 raise AbortSave('child_run() returned an error code, but no error message!')
615 # Data went to a temp file
617 stream
.write(tmp
.read())
620 """This is run in the child process. The default method runs 'self.command'
621 using os.system() and prints a message to stderr if the exit code is non-zero.
622 DO NOT call gtk functions here!
624 Be careful to escape shell special characters when inserting filenames!
626 command
= self
.command
627 if os
.system(command
):
628 print >>sys
.stderr
, "Command:\n%s\nreturned an error code" % command
629 os
._exit
(0) # Writing to stderr indicates error...
631 def save_cancelled(self
):
632 """Send SIGTERM to the child processes."""