1 | n/a | """ |
---|
2 | n/a | Dialogs that query users and verify the answer before accepting. |
---|
3 | n/a | Use ttk widgets, limiting use to tcl/tk 8.5+, as in IDLE 3.6+. |
---|
4 | n/a | |
---|
5 | n/a | Query is the generic base class for a popup dialog. |
---|
6 | n/a | The user must either enter a valid answer or close the dialog. |
---|
7 | n/a | Entries are validated when <Return> is entered or [Ok] is clicked. |
---|
8 | n/a | Entries are ignored when [Cancel] or [X] are clicked. |
---|
9 | n/a | The 'return value' is .result set to either a valid answer or None. |
---|
10 | n/a | |
---|
11 | n/a | Subclass SectionName gets a name for a new config file section. |
---|
12 | n/a | Configdialog uses it for new highlight theme and keybinding set names. |
---|
13 | n/a | Subclass ModuleName gets a name for File => Open Module. |
---|
14 | n/a | Subclass HelpSource gets menu item and path for additions to Help menu. |
---|
15 | n/a | """ |
---|
16 | n/a | # Query and Section name result from splitting GetCfgSectionNameDialog |
---|
17 | n/a | # of configSectionNameDialog.py (temporarily config_sec.py) into |
---|
18 | n/a | # generic and specific parts. 3.6 only, July 2016. |
---|
19 | n/a | # ModuleName.entry_ok came from editor.EditorWindow.load_module. |
---|
20 | n/a | # HelpSource was extracted from configHelpSourceEdit.py (temporarily |
---|
21 | n/a | # config_help.py), with darwin code moved from ok to path_ok. |
---|
22 | n/a | |
---|
23 | n/a | import importlib |
---|
24 | n/a | import os |
---|
25 | n/a | from sys import executable, platform # Platform is set for one test. |
---|
26 | n/a | |
---|
27 | n/a | from tkinter import Toplevel, StringVar, W, E, N, S |
---|
28 | n/a | from tkinter.ttk import Frame, Button, Entry, Label |
---|
29 | n/a | from tkinter import filedialog |
---|
30 | n/a | from tkinter.font import Font |
---|
31 | n/a | |
---|
32 | n/a | class Query(Toplevel): |
---|
33 | n/a | """Base class for getting verified answer from a user. |
---|
34 | n/a | |
---|
35 | n/a | For this base class, accept any non-blank string. |
---|
36 | n/a | """ |
---|
37 | n/a | def __init__(self, parent, title, message, *, text0='', used_names={}, |
---|
38 | n/a | _htest=False, _utest=False): |
---|
39 | n/a | """Create popup, do not return until tk widget destroyed. |
---|
40 | n/a | |
---|
41 | n/a | Additional subclass init must be done before calling this |
---|
42 | n/a | unless _utest=True is passed to suppress wait_window(). |
---|
43 | n/a | |
---|
44 | n/a | title - string, title of popup dialog |
---|
45 | n/a | message - string, informational message to display |
---|
46 | n/a | text0 - initial value for entry |
---|
47 | n/a | used_names - names already in use |
---|
48 | n/a | _htest - bool, change box location when running htest |
---|
49 | n/a | _utest - bool, leave window hidden and not modal |
---|
50 | n/a | """ |
---|
51 | n/a | Toplevel.__init__(self, parent) |
---|
52 | n/a | self.withdraw() # Hide while configuring, especially geometry. |
---|
53 | n/a | self.parent = parent |
---|
54 | n/a | self.title(title) |
---|
55 | n/a | self.message = message |
---|
56 | n/a | self.text0 = text0 |
---|
57 | n/a | self.used_names = used_names |
---|
58 | n/a | self.transient(parent) |
---|
59 | n/a | self.grab_set() |
---|
60 | n/a | windowingsystem = self.tk.call('tk', 'windowingsystem') |
---|
61 | n/a | if windowingsystem == 'aqua': |
---|
62 | n/a | try: |
---|
63 | n/a | self.tk.call('::tk::unsupported::MacWindowStyle', 'style', |
---|
64 | n/a | self._w, 'moveableModal', '') |
---|
65 | n/a | except: |
---|
66 | n/a | pass |
---|
67 | n/a | self.bind("<Command-.>", self.cancel) |
---|
68 | n/a | self.bind('<Key-Escape>', self.cancel) |
---|
69 | n/a | self.protocol("WM_DELETE_WINDOW", self.cancel) |
---|
70 | n/a | self.bind('<Key-Return>', self.ok) |
---|
71 | n/a | self.bind("<KP_Enter>", self.ok) |
---|
72 | n/a | self.resizable(height=False, width=False) |
---|
73 | n/a | self.create_widgets() |
---|
74 | n/a | self.update_idletasks() # Needed here for winfo_reqwidth below. |
---|
75 | n/a | self.geometry( # Center dialog over parent (or below htest box). |
---|
76 | n/a | "+%d+%d" % ( |
---|
77 | n/a | parent.winfo_rootx() + |
---|
78 | n/a | (parent.winfo_width()/2 - self.winfo_reqwidth()/2), |
---|
79 | n/a | parent.winfo_rooty() + |
---|
80 | n/a | ((parent.winfo_height()/2 - self.winfo_reqheight()/2) |
---|
81 | n/a | if not _htest else 150) |
---|
82 | n/a | ) ) |
---|
83 | n/a | if not _utest: |
---|
84 | n/a | self.deiconify() # Unhide now that geometry set. |
---|
85 | n/a | self.wait_window() |
---|
86 | n/a | |
---|
87 | n/a | def create_widgets(self): # Call from override, if any. |
---|
88 | n/a | # Bind to self widgets needed for entry_ok or unittest. |
---|
89 | n/a | self.frame = frame = Frame(self, padding=10) |
---|
90 | n/a | frame.grid(column=0, row=0, sticky='news') |
---|
91 | n/a | frame.grid_columnconfigure(0, weight=1) |
---|
92 | n/a | |
---|
93 | n/a | entrylabel = Label(frame, anchor='w', justify='left', |
---|
94 | n/a | text=self.message) |
---|
95 | n/a | self.entryvar = StringVar(self, self.text0) |
---|
96 | n/a | self.entry = Entry(frame, width=30, textvariable=self.entryvar) |
---|
97 | n/a | self.entry.focus_set() |
---|
98 | n/a | self.error_font = Font(name='TkCaptionFont', |
---|
99 | n/a | exists=True, root=self.parent) |
---|
100 | n/a | self.entry_error = Label(frame, text=' ', foreground='red', |
---|
101 | n/a | font=self.error_font) |
---|
102 | n/a | self.button_ok = Button( |
---|
103 | n/a | frame, text='OK', default='active', command=self.ok) |
---|
104 | n/a | self.button_cancel = Button( |
---|
105 | n/a | frame, text='Cancel', command=self.cancel) |
---|
106 | n/a | |
---|
107 | n/a | entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) |
---|
108 | n/a | self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E, |
---|
109 | n/a | pady=[10,0]) |
---|
110 | n/a | self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, |
---|
111 | n/a | sticky=W+E) |
---|
112 | n/a | self.button_ok.grid(column=1, row=99, padx=5) |
---|
113 | n/a | self.button_cancel.grid(column=2, row=99, padx=5) |
---|
114 | n/a | |
---|
115 | n/a | def showerror(self, message, widget=None): |
---|
116 | n/a | #self.bell(displayof=self) |
---|
117 | n/a | (widget or self.entry_error)['text'] = 'ERROR: ' + message |
---|
118 | n/a | |
---|
119 | n/a | def entry_ok(self): # Example: usually replace. |
---|
120 | n/a | "Return non-blank entry or None." |
---|
121 | n/a | self.entry_error['text'] = '' |
---|
122 | n/a | entry = self.entry.get().strip() |
---|
123 | n/a | if not entry: |
---|
124 | n/a | self.showerror('blank line.') |
---|
125 | n/a | return None |
---|
126 | n/a | return entry |
---|
127 | n/a | |
---|
128 | n/a | def ok(self, event=None): # Do not replace. |
---|
129 | n/a | '''If entry is valid, bind it to 'result' and destroy tk widget. |
---|
130 | n/a | |
---|
131 | n/a | Otherwise leave dialog open for user to correct entry or cancel. |
---|
132 | n/a | ''' |
---|
133 | n/a | entry = self.entry_ok() |
---|
134 | n/a | if entry is not None: |
---|
135 | n/a | self.result = entry |
---|
136 | n/a | self.destroy() |
---|
137 | n/a | else: |
---|
138 | n/a | # [Ok] moves focus. (<Return> does not.) Move it back. |
---|
139 | n/a | self.entry.focus_set() |
---|
140 | n/a | |
---|
141 | n/a | def cancel(self, event=None): # Do not replace. |
---|
142 | n/a | "Set dialog result to None and destroy tk widget." |
---|
143 | n/a | self.result = None |
---|
144 | n/a | self.destroy() |
---|
145 | n/a | |
---|
146 | n/a | |
---|
147 | n/a | class SectionName(Query): |
---|
148 | n/a | "Get a name for a config file section name." |
---|
149 | n/a | # Used in ConfigDialog.GetNewKeysName, .GetNewThemeName (837) |
---|
150 | n/a | |
---|
151 | n/a | def __init__(self, parent, title, message, used_names, |
---|
152 | n/a | *, _htest=False, _utest=False): |
---|
153 | n/a | super().__init__(parent, title, message, used_names=used_names, |
---|
154 | n/a | _htest=_htest, _utest=_utest) |
---|
155 | n/a | |
---|
156 | n/a | def entry_ok(self): |
---|
157 | n/a | "Return sensible ConfigParser section name or None." |
---|
158 | n/a | self.entry_error['text'] = '' |
---|
159 | n/a | name = self.entry.get().strip() |
---|
160 | n/a | if not name: |
---|
161 | n/a | self.showerror('no name specified.') |
---|
162 | n/a | return None |
---|
163 | n/a | elif len(name)>30: |
---|
164 | n/a | self.showerror('name is longer than 30 characters.') |
---|
165 | n/a | return None |
---|
166 | n/a | elif name in self.used_names: |
---|
167 | n/a | self.showerror('name is already in use.') |
---|
168 | n/a | return None |
---|
169 | n/a | return name |
---|
170 | n/a | |
---|
171 | n/a | |
---|
172 | n/a | class ModuleName(Query): |
---|
173 | n/a | "Get a module name for Open Module menu entry." |
---|
174 | n/a | # Used in open_module (editor.EditorWindow until move to iobinding). |
---|
175 | n/a | |
---|
176 | n/a | def __init__(self, parent, title, message, text0, |
---|
177 | n/a | *, _htest=False, _utest=False): |
---|
178 | n/a | super().__init__(parent, title, message, text0=text0, |
---|
179 | n/a | _htest=_htest, _utest=_utest) |
---|
180 | n/a | |
---|
181 | n/a | def entry_ok(self): |
---|
182 | n/a | "Return entered module name as file path or None." |
---|
183 | n/a | self.entry_error['text'] = '' |
---|
184 | n/a | name = self.entry.get().strip() |
---|
185 | n/a | if not name: |
---|
186 | n/a | self.showerror('no name specified.') |
---|
187 | n/a | return None |
---|
188 | n/a | # XXX Ought to insert current file's directory in front of path. |
---|
189 | n/a | try: |
---|
190 | n/a | spec = importlib.util.find_spec(name) |
---|
191 | n/a | except (ValueError, ImportError) as msg: |
---|
192 | n/a | self.showerror(str(msg)) |
---|
193 | n/a | return None |
---|
194 | n/a | if spec is None: |
---|
195 | n/a | self.showerror("module not found") |
---|
196 | n/a | return None |
---|
197 | n/a | if not isinstance(spec.loader, importlib.abc.SourceLoader): |
---|
198 | n/a | self.showerror("not a source-based module") |
---|
199 | n/a | return None |
---|
200 | n/a | try: |
---|
201 | n/a | file_path = spec.loader.get_filename(name) |
---|
202 | n/a | except AttributeError: |
---|
203 | n/a | self.showerror("loader does not support get_filename", |
---|
204 | n/a | parent=self) |
---|
205 | n/a | return None |
---|
206 | n/a | return file_path |
---|
207 | n/a | |
---|
208 | n/a | |
---|
209 | n/a | class HelpSource(Query): |
---|
210 | n/a | "Get menu name and help source for Help menu." |
---|
211 | n/a | # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9) |
---|
212 | n/a | |
---|
213 | n/a | def __init__(self, parent, title, *, menuitem='', filepath='', |
---|
214 | n/a | used_names={}, _htest=False, _utest=False): |
---|
215 | n/a | """Get menu entry and url/local file for Additional Help. |
---|
216 | n/a | |
---|
217 | n/a | User enters a name for the Help resource and a web url or file |
---|
218 | n/a | name. The user can browse for the file. |
---|
219 | n/a | """ |
---|
220 | n/a | self.filepath = filepath |
---|
221 | n/a | message = 'Name for item on Help menu:' |
---|
222 | n/a | super().__init__( |
---|
223 | n/a | parent, title, message, text0=menuitem, |
---|
224 | n/a | used_names=used_names, _htest=_htest, _utest=_utest) |
---|
225 | n/a | |
---|
226 | n/a | def create_widgets(self): |
---|
227 | n/a | super().create_widgets() |
---|
228 | n/a | frame = self.frame |
---|
229 | n/a | pathlabel = Label(frame, anchor='w', justify='left', |
---|
230 | n/a | text='Help File Path: Enter URL or browse for file') |
---|
231 | n/a | self.pathvar = StringVar(self, self.filepath) |
---|
232 | n/a | self.path = Entry(frame, textvariable=self.pathvar, width=40) |
---|
233 | n/a | browse = Button(frame, text='Browse', width=8, |
---|
234 | n/a | command=self.browse_file) |
---|
235 | n/a | self.path_error = Label(frame, text=' ', foreground='red', |
---|
236 | n/a | font=self.error_font) |
---|
237 | n/a | |
---|
238 | n/a | pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0], |
---|
239 | n/a | sticky=W) |
---|
240 | n/a | self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E, |
---|
241 | n/a | pady=[10,0]) |
---|
242 | n/a | browse.grid(column=2, row=11, padx=5, sticky=W+S) |
---|
243 | n/a | self.path_error.grid(column=0, row=12, columnspan=3, padx=5, |
---|
244 | n/a | sticky=W+E) |
---|
245 | n/a | |
---|
246 | n/a | def askfilename(self, filetypes, initdir, initfile): # htest # |
---|
247 | n/a | # Extracted from browse_file so can mock for unittests. |
---|
248 | n/a | # Cannot unittest as cannot simulate button clicks. |
---|
249 | n/a | # Test by running htest, such as by running this file. |
---|
250 | n/a | return filedialog.Open(parent=self, filetypes=filetypes)\ |
---|
251 | n/a | .show(initialdir=initdir, initialfile=initfile) |
---|
252 | n/a | |
---|
253 | n/a | def browse_file(self): |
---|
254 | n/a | filetypes = [ |
---|
255 | n/a | ("HTML Files", "*.htm *.html", "TEXT"), |
---|
256 | n/a | ("PDF Files", "*.pdf", "TEXT"), |
---|
257 | n/a | ("Windows Help Files", "*.chm"), |
---|
258 | n/a | ("Text Files", "*.txt", "TEXT"), |
---|
259 | n/a | ("All Files", "*")] |
---|
260 | n/a | path = self.pathvar.get() |
---|
261 | n/a | if path: |
---|
262 | n/a | dir, base = os.path.split(path) |
---|
263 | n/a | else: |
---|
264 | n/a | base = None |
---|
265 | n/a | if platform[:3] == 'win': |
---|
266 | n/a | dir = os.path.join(os.path.dirname(executable), 'Doc') |
---|
267 | n/a | if not os.path.isdir(dir): |
---|
268 | n/a | dir = os.getcwd() |
---|
269 | n/a | else: |
---|
270 | n/a | dir = os.getcwd() |
---|
271 | n/a | file = self.askfilename(filetypes, dir, base) |
---|
272 | n/a | if file: |
---|
273 | n/a | self.pathvar.set(file) |
---|
274 | n/a | |
---|
275 | n/a | item_ok = SectionName.entry_ok # localize for test override |
---|
276 | n/a | |
---|
277 | n/a | def path_ok(self): |
---|
278 | n/a | "Simple validity check for menu file path" |
---|
279 | n/a | path = self.path.get().strip() |
---|
280 | n/a | if not path: #no path specified |
---|
281 | n/a | self.showerror('no help file path specified.', self.path_error) |
---|
282 | n/a | return None |
---|
283 | n/a | elif not path.startswith(('www.', 'http')): |
---|
284 | n/a | if path[:5] == 'file:': |
---|
285 | n/a | path = path[5:] |
---|
286 | n/a | if not os.path.exists(path): |
---|
287 | n/a | self.showerror('help file path does not exist.', |
---|
288 | n/a | self.path_error) |
---|
289 | n/a | return None |
---|
290 | n/a | if platform == 'darwin': # for Mac Safari |
---|
291 | n/a | path = "file://" + path |
---|
292 | n/a | return path |
---|
293 | n/a | |
---|
294 | n/a | def entry_ok(self): |
---|
295 | n/a | "Return apparently valid (name, path) or None" |
---|
296 | n/a | self.entry_error['text'] = '' |
---|
297 | n/a | self.path_error['text'] = '' |
---|
298 | n/a | name = self.item_ok() |
---|
299 | n/a | path = self.path_ok() |
---|
300 | n/a | return None if name is None or path is None else (name, path) |
---|
301 | n/a | |
---|
302 | n/a | |
---|
303 | n/a | if __name__ == '__main__': |
---|
304 | n/a | import unittest |
---|
305 | n/a | unittest.main('idlelib.idle_test.test_query', verbosity=2, exit=False) |
---|
306 | n/a | |
---|
307 | n/a | from idlelib.idle_test.htest import run |
---|
308 | n/a | run(Query, HelpSource) |
---|