-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathnative_file_chooser.py
95 lines (79 loc) · 2.94 KB
/
native_file_chooser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
try:
import wx
wx_available = True
except Exception:
wx_available = False
import threading
import os.path
import subprocess as sp
import time
from kivy.clock import mainthread
from message_box import MessageBox
class NativeFileChooser():
type_name = 'wx'
def __init__(self, **kwargs):
super(NativeFileChooser, self).__init__(**kwargs)
self.use_wx = False
self.use_zenity = False
self.use_kdialog = False
self.failed = False
if NativeFileChooser.type_name == 'wx' and wx_available:
self.use_wx = True
elif NativeFileChooser.type_name == 'zenity':
self.use_zenity = True
elif NativeFileChooser.type_name == 'kdialog':
self.use_kdialog = True
else:
raise "Unknown chooser"
def _run_command(self, cmd):
self._process = sp.Popen(cmd, stdout=sp.PIPE)
while True:
ret = self._process.poll()
if ret is not None:
if ret == 0:
out = self._process.communicate()[0].strip().decode('utf8')
self.selection = out
return self.selection
else:
return None
time.sleep(0.1)
def _wx_get_path(self):
app = wx.App(None)
style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
dialog = wx.FileDialog(None, self.title, defaultDir=self.start_dir, wildcard='GCode files|*.g;*.gcode;*.nc;*.gc;*.ngc|All Files|*', style=style)
if dialog.ShowModal() == wx.ID_OK:
path = dialog.GetPath()
else:
path = None
dialog.Destroy()
return path
def open(self, start_dir="", title="", cb=None):
self.cb = cb
self.title = title
self.start_dir = start_dir
threading.Thread(target=self._open_dialog).start()
def _open_dialog(self):
path = None
try:
if self.use_wx:
path = self._wx_get_path()
elif self.use_zenity:
os.unsetenv('WINDOWID') # needed so dialog pops up infront of my window
path = self._run_command(['zenity', '--title', self.title, '--file-selection', '--filename', self.start_dir + '/', '--file-filter', 'GCode files | *.g *.gcode *.nc *.gc *.ngc'])
elif self.use_kdialog:
path = self._run_command(['kdialog', '--title', self.title, '--getopenfilename', self.start_dir, 'GCode Files (*.g *.gcode *.nc *.gc *.ngc)'])
else:
self.failed = True
except Exception:
self.failed = True
self._loaded(path)
@mainthread
def _loaded(self, path):
if self.failed:
mb = MessageBox(text='File Chooser {} failed - try a different one'.format(NativeFileChooser.type_name))
mb.open()
return
if path:
dr = os.path.dirname(path)
if self.cb:
self.cb(path, dr)