def open_dialog(title, window, filters): """Show a file chooser dialog. Filters should be a list of tuples: (filtertitle, globpattern). Returns a tuple of the form (fileformat, filename). Here "fileformat" is the index of the filter that matched filename, or None if there were no matches). "filename" is None if no file was selected. """ dialog = Gtk.FileChooserDialog(title, window, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) dialog.set_default_response(Gtk.ResponseType.OK) for filter_title, pattern in filters: f = Gtk.FileFilter() f.set_name(filter_title) f.add_pattern(pattern) dialog.add_filter(f) result = (None, None) if dialog.run() == Gtk.ResponseType.OK: filename = dialog.get_filename() if isinstance(filename, bytes): filename = filename.decode('utf-8') file_format = None for i, (_junk, pattern) in enumerate(filters): if fnmatch(filename, pattern): file_format = i break result = (file_format, filename) dialog.hide() return result
def save_dialog(title, window, filters, default_format=None): """Shows a file save dialog. "filters" should be a list of tuples: (filter title, glob pattern). "default_format" may be a pair (format id, suffix). That suffix will be added to filename if it does not match any of filters. Returns a tuple of the form (fileformat, filename). Here "fileformat" is index of filter that matches filename, or None if no matches). "filename" is None if no file was selected. """ dialog = Gtk.FileChooserDialog(title, window, Gtk.FileChooserAction.SAVE, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK)) dialog.set_default_response(Gtk.ResponseType.OK) dialog.set_do_overwrite_confirmation(True) for filter_title, pattern in filters: f = Gtk.FileFilter() f.set_name(filter_title) f.add_pattern(pattern) dialog.add_filter(f) result = (None, None) while dialog.run() == Gtk.ResponseType.OK: filename = dialog.get_filename() if isinstance(filename, bytes): filename = filename.decode('utf-8') file_format = None for i, (_junk, pattern) in enumerate(filters): if fnmatch(filename, pattern): file_format = i break if file_format is None and default_format is not None: file_format, suffix = default_format filename += suffix dialog.set_current_name(filename) dialog.response(Gtk.ResponseType.OK) else: result = (file_format, filename) break dialog.hide() return result