| 1 |
#!/usr/bin/python3 |
| 2 |
""" Allows you to open a Gtk file dialog from and get the selected file in return |
| 3 |
|
| 4 |
Used by a couple of Cinnamon spices via Javascript |
| 5 |
|
| 6 |
Usage: |
| 7 |
cinnamon-file-dialog {0|1|2} -{p|n|d|f} [path] ... |
| 8 |
""" |
| 9 |
|
| 10 |
import sys |
| 11 |
from setproctitle import setproctitle |
| 12 |
setproctitle("cinnamon-file-dialog") |
| 13 |
|
| 14 |
import gi |
| 15 |
gi.require_version('Gtk', '3.0') |
| 16 |
from gi.repository import Gtk |
| 17 |
|
| 18 |
cancelButton = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) |
| 19 |
typeArg = int(sys.argv[1]) |
| 20 |
fdType = typeArg % 3 |
| 21 |
if fdType == 0: |
| 22 |
msg = "Open" |
| 23 |
action = Gtk.FileChooserAction.OPEN |
| 24 |
okButton = (Gtk.STOCK_OPEN, Gtk.ResponseType.OK) |
| 25 |
elif fdType == 1: |
| 26 |
msg = "Select Folder" |
| 27 |
action = Gtk.FileChooserAction.SELECT_FOLDER |
| 28 |
okButton = (Gtk.STOCK_OPEN, Gtk.ResponseType.OK) |
| 29 |
elif fdType == 2: |
| 30 |
msg = "Save" |
| 31 |
action = Gtk.FileChooserAction.SAVE |
| 32 |
okButton = (Gtk.STOCK_SAVE, Gtk.ResponseType.OK) |
| 33 |
|
| 34 |
buttons = cancelButton + okButton |
| 35 |
filechooserdialog = Gtk.FileChooserDialog(title=msg, action=action, buttons=buttons) |
| 36 |
|
| 37 |
for i in range(2, len(sys.argv)): |
| 38 |
if sys.argv[i] == "-p": |
| 39 |
filechooserdialog.set_filename(sys.argv[i + 1]) |
| 40 |
elif sys.argv[i] == "-n": |
| 41 |
filechooserdialog.set_current_name(sys.argv[i + 1]) |
| 42 |
elif sys.argv[i] == "-d": |
| 43 |
filechooserdialog.set_current_folder(sys.argv[i + 1]) |
| 44 |
elif sys.argv[i] == "-f": |
| 45 |
filterList = sys.argv[i + 1].split(",") |
| 46 |
for filterInfo in filterList: |
| 47 |
[name, filters] = filterInfo.split(";") |
| 48 |
filterObj = Gtk.FileFilter() |
| 49 |
filterObj.set_name(name) |
| 50 |
rules = filters.split(":") |
| 51 |
for rule in rules: |
| 52 |
[ftype, value] = rule.split("=") |
| 53 |
if ftype == "m": |
| 54 |
filterObj.add_mime_type(value) |
| 55 |
elif ftype == "p": |
| 56 |
filterObj.add_pattern(value) |
| 57 |
filechooserdialog.add_filter(filterObj) |
| 58 |
|
| 59 |
if fdType == 2: |
| 60 |
filechooserdialog.set_do_overwrite_confirmation(True) |
| 61 |
|
| 62 |
if typeArg > 2: |
| 63 |
filechooserdialog.set_select_multiple(True) |
| 64 |
|
| 65 |
response = filechooserdialog.run() |
| 66 |
if response == Gtk.ResponseType.OK: |
| 67 |
if typeArg > 2: |
| 68 |
print(filechooserdialog.get_filenames()) |
| 69 |
else: |
| 70 |
print(filechooserdialog.get_filename()) |
| 71 |
|
| 72 |
filechooserdialog.destroy() |