# encoding: utf-8 # vi:si:et:sw=4:sts=4:ts=4 import sys import os try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject use_Gtk = True except: from tkinter import Tk, PhotoImage import tkinter.filedialog use_Gtk = False DEBUG = False def short_home(path): home = os.path.expanduser('~') if path and path.startswith(home): path = path.replace(home, '~') return path class GtkUI: def selectFolder(self, data): dialog = Gtk.FileChooserDialog(title=data.get("title", "Select Folder"), action=Gtk.FileChooserAction.SELECT_FOLDER) dialog.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK) dialog.set_default_response(Gtk.ResponseType.OK) response = dialog.run() if response == Gtk.ResponseType.OK: filename = dialog.get_filename() if DEBUG: print(filename, 'selected') elif response == Gtk.ResponseType.CANCEL: if DEBUG: print('Closed, no files selected') filename = None else: filename = None dialog.destroy() while Gtk.events_pending(): Gtk.main_iteration() if DEBUG: print("done") return short_home(filename) def selectFile(self, data): dialog = Gtk.FileChooserDialog(title=data.get("title", "Select File"), action=Gtk.FileChooserAction.OPEN) dialog.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK) dialog.set_default_response(Gtk.ResponseType.OK) response = dialog.run() if response == Gtk.ResponseType.OK: filename = dialog.get_filename() if DEBUG: print(filename, 'selected') elif response == Gtk.ResponseType.CANCEL: if DEBUG: print('Closed, no files selected') filename = None else: filename = None dialog.destroy() while Gtk.events_pending(): Gtk.main_iteration() if DEBUG: print("done") return short_home(filename) class TkUI: def __init__(self): self.root = Tk(className="Open Media Library") png = os.path.join(os.path.dirname(os.path.abspath('__file__')), 'static', 'png', 'oml.png') icon = PhotoImage(file=png) self.root.tk.call('wm', 'iconphoto', self.root._w, icon) self.root.withdraw() # hiding tkinter window if sys.platform == 'darwin': self.root.lift() self.root.call('wm', 'attributes', '.', '-topmost', True) self.root.update() self.root.after_idle(self.root.call, 'wm', 'attributes', '.', '-topmost', False) def selectFolder(self, data): folder = tkinter.filedialog.askdirectory(parent=self.root, title=data.get("title", "Select Folder")) return short_home(folder) def selectFile(self, data): filename = tkinter.filedialog.askopenfilename(parent=self.root, title=data.get("title", "Select File")) return short_home(filename) if use_Gtk: ui = GtkUI() else: ui = TkUI() if __name__ == '__main__': base = '~' if len(sys.argv) >= 3: base = sys.argv[2] base = os.path.expanduser(base) os.chdir(base) if len(sys.argv) >= 2 and sys.argv[1] == 'folder': print(ui.selectFolder({})) else: print(ui.selectFile({}))