blob: a58de1b6f077d7aff3cf907cbb0fea83fd668b8b [file] [log] [blame]
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001"""A (less & less) simple Python editor"""
2
3import W
4import Wtraceback
5from Wkeys import *
6
7import macfs
Jack Jansen64aa1e22001-01-29 15:19:17 +00008import MACFS
Just van Rossum40f9b7b1999-01-30 22:39:17 +00009import MacOS
10import Win
11import Res
12import Evt
13import os
14import imp
15import sys
16import string
17import marshal
Jack Jansen9ad27522001-02-21 13:54:31 +000018import re
Just van Rossum40f9b7b1999-01-30 22:39:17 +000019
Just van Rossum73efed22000-04-09 19:45:22 +000020try:
Just van Rossum0f2fd162000-10-20 06:36:30 +000021 import Wthreading
Just van Rossum73efed22000-04-09 19:45:22 +000022except ImportError:
Just van Rossum0f2fd162000-10-20 06:36:30 +000023 haveThreading = 0
24else:
25 haveThreading = Wthreading.haveThreading
Just van Rossum73efed22000-04-09 19:45:22 +000026
Just van Rossum40f9b7b1999-01-30 22:39:17 +000027_scriptuntitledcounter = 1
Jack Jansen9ad27522001-02-21 13:54:31 +000028# _wordchars = string.letters + string.digits + "_"
29_wordchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
Just van Rossum40f9b7b1999-01-30 22:39:17 +000030
31
Just van Rossum73efed22000-04-09 19:45:22 +000032runButtonLabels = ["Run all", "Stop!"]
33runSelButtonLabels = ["Run selection", "Pause!", "Resume"]
34
35
Just van Rossum40f9b7b1999-01-30 22:39:17 +000036class Editor(W.Window):
37
38 def __init__(self, path = "", title = ""):
39 defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs()
40 global _scriptuntitledcounter
41 if not path:
42 if title:
43 self.title = title
44 else:
45 self.title = "Untitled Script " + `_scriptuntitledcounter`
46 _scriptuntitledcounter = _scriptuntitledcounter + 1
47 text = ""
48 self._creator = W._signature
49 elif os.path.exists(path):
50 path = resolvealiases(path)
51 dir, name = os.path.split(path)
52 self.title = name
53 f = open(path, "rb")
54 text = f.read()
55 f.close()
56 fss = macfs.FSSpec(path)
57 self._creator, filetype = fss.GetCreatorType()
58 else:
59 raise IOError, "file '%s' does not exist" % path
60 self.path = path
61
Just van Rossumc7ba0801999-05-21 21:42:27 +000062 if '\n' in text:
63 import EasyDialogs
64 if string.find(text, '\r\n') >= 0:
65 sourceOS = 'DOS'
66 searchString = '\r\n'
67 else:
68 sourceOS = 'UNIX'
69 searchString = '\n'
Just van Rossumdc3c6172001-06-19 21:37:33 +000070 change = EasyDialogs.AskYesNoCancel('"%s" contains %s-style line feeds. '
Just van Rossum73efed22000-04-09 19:45:22 +000071 'Change them to MacOS carriage returns?' % (self.title, sourceOS), 1)
Just van Rossumc7ba0801999-05-21 21:42:27 +000072 # bug: Cancel is treated as No
73 if change > 0:
74 text = string.replace(text, searchString, '\r')
75 else:
76 change = 0
77
Just van Rossum40f9b7b1999-01-30 22:39:17 +000078 self.settings = {}
79 if self.path:
80 self.readwindowsettings()
81 if self.settings.has_key("windowbounds"):
82 bounds = self.settings["windowbounds"]
83 else:
84 bounds = defaultwindowsize
85 if self.settings.has_key("fontsettings"):
86 self.fontsettings = self.settings["fontsettings"]
87 else:
88 self.fontsettings = defaultfontsettings
89 if self.settings.has_key("tabsize"):
90 try:
91 self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"]
92 except:
93 self.tabsettings = defaulttabsettings
94 else:
95 self.tabsettings = defaulttabsettings
Just van Rossum40f9b7b1999-01-30 22:39:17 +000096
Just van Rossumc7ba0801999-05-21 21:42:27 +000097 W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +000098 self.setupwidgets(text)
Just van Rossumc7ba0801999-05-21 21:42:27 +000099 if change > 0:
Just van Rossum5f740071999-10-30 11:44:25 +0000100 self.editgroup.editor.changed = 1
Just van Rossumc7ba0801999-05-21 21:42:27 +0000101
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000102 if self.settings.has_key("selection"):
103 selstart, selend = self.settings["selection"]
104 self.setselection(selstart, selend)
105 self.open()
106 self.setinfotext()
107 self.globals = {}
108 self._buf = "" # for write method
109 self.debugging = 0
110 self.profiling = 0
111 if self.settings.has_key("run_as_main"):
112 self.run_as_main = self.settings["run_as_main"]
113 else:
114 self.run_as_main = 0
Just van Rossum0f2fd162000-10-20 06:36:30 +0000115 if self.settings.has_key("run_with_interpreter"):
116 self.run_with_interpreter = self.settings["run_with_interpreter"]
117 else:
118 self.run_with_interpreter = 0
Just van Rossum73efed22000-04-09 19:45:22 +0000119 self._threadstate = (0, 0)
120 self._thread = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000121
122 def readwindowsettings(self):
123 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000124 resref = Res.FSpOpenResFile(self.path, 1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000125 except Res.Error:
126 return
127 try:
128 Res.UseResFile(resref)
129 data = Res.Get1Resource('PyWS', 128)
130 self.settings = marshal.loads(data.data)
131 except:
132 pass
133 Res.CloseResFile(resref)
134
135 def writewindowsettings(self):
136 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000137 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000138 except Res.Error:
Jack Jansen64aa1e22001-01-29 15:19:17 +0000139 Res.FSpCreateResFile(self.path, self._creator, 'TEXT', MACFS.smAllScripts)
Jack Jansend13c3852000-06-20 21:59:25 +0000140 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000141 try:
142 data = Res.Resource(marshal.dumps(self.settings))
143 Res.UseResFile(resref)
144 try:
145 temp = Res.Get1Resource('PyWS', 128)
146 temp.RemoveResource()
147 except Res.Error:
148 pass
149 data.AddResource('PyWS', 128, "window settings")
150 finally:
151 Res.UpdateResFile(resref)
152 Res.CloseResFile(resref)
153
154 def getsettings(self):
155 self.settings = {}
156 self.settings["windowbounds"] = self.getbounds()
157 self.settings["selection"] = self.getselection()
158 self.settings["fontsettings"] = self.editgroup.editor.getfontsettings()
159 self.settings["tabsize"] = self.editgroup.editor.gettabsettings()
160 self.settings["run_as_main"] = self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000161 self.settings["run_with_interpreter"] = self.run_with_interpreter
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000162
163 def get(self):
164 return self.editgroup.editor.get()
165
166 def getselection(self):
167 return self.editgroup.editor.ted.WEGetSelection()
168
169 def setselection(self, selstart, selend):
170 self.editgroup.editor.setselection(selstart, selend)
171
172 def getfilename(self):
173 if self.path:
174 return self.path
175 return '<%s>' % self.title
176
177 def setupwidgets(self, text):
178 topbarheight = 24
179 popfieldwidth = 80
180 self.lastlineno = None
181
182 # make an editor
183 self.editgroup = W.Group((0, topbarheight + 1, 0, 0))
184 editor = W.PyEditor((0, 0, -15,-15), text,
185 fontsettings = self.fontsettings,
186 tabsettings = self.tabsettings,
187 file = self.getfilename())
188
189 # make the widgets
190 self.popfield = ClassFinder((popfieldwidth - 17, -15, 16, 16), [], self.popselectline)
191 self.linefield = W.EditText((-1, -15, popfieldwidth - 15, 16), inset = (6, 1))
192 self.editgroup._barx = W.Scrollbar((popfieldwidth - 2, -15, -14, 16), editor.hscroll, max = 32767)
193 self.editgroup._bary = W.Scrollbar((-15, 14, 16, -14), editor.vscroll, max = 32767)
194 self.editgroup.editor = editor # add editor *after* scrollbars
195
196 self.editgroup.optionsmenu = W.PopupMenu((-15, -1, 16, 16), [])
197 self.editgroup.optionsmenu.bind('<click>', self.makeoptionsmenu)
198
199 self.bevelbox = W.BevelBox((0, 0, 0, topbarheight))
200 self.hline = W.HorizontalLine((0, topbarheight, 0, 0))
201 self.infotext = W.TextBox((175, 6, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000))
Just van Rossum73efed22000-04-09 19:45:22 +0000202 self.runbutton = W.Button((5, 4, 80, 16), runButtonLabels[0], self.run)
203 self.runselbutton = W.Button((90, 4, 80, 16), runSelButtonLabels[0], self.runselection)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000204
205 # bind some keys
206 editor.bind("cmdr", self.runbutton.push)
207 editor.bind("enter", self.runselbutton.push)
208 editor.bind("cmdj", self.domenu_gotoline)
209 editor.bind("cmdd", self.domenu_toggledebugger)
210 editor.bind("<idle>", self.updateselection)
211
212 editor.bind("cmde", searchengine.setfindstring)
213 editor.bind("cmdf", searchengine.show)
214 editor.bind("cmdg", searchengine.findnext)
215 editor.bind("cmdshiftr", searchengine.replace)
216 editor.bind("cmdt", searchengine.replacefind)
217
218 self.linefield.bind("return", self.dolinefield)
219 self.linefield.bind("enter", self.dolinefield)
220 self.linefield.bind("tab", self.dolinefield)
221
222 # intercept clicks
223 editor.bind("<click>", self.clickeditor)
224 self.linefield.bind("<click>", self.clicklinefield)
225
226 def makeoptionsmenu(self):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000227 menuitems = [('Font settings\xc9', self.domenu_fontsettings),
228 ("Save options\xc9", self.domenu_options),
Just van Rossum12710051999-02-27 17:18:30 +0000229 '-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000230 ('\0' + chr(self.run_as_main) + 'Run as __main__', self.domenu_toggle_run_as_main),
Just van Rossum0f2fd162000-10-20 06:36:30 +0000231 #('\0' + chr(self.run_with_interpreter) + 'Run with Interpreter', self.domenu_toggle_run_with_interpreter),
232 #'-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000233 ('Modularize', self.domenu_modularize),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000234 ('Browse namespace\xc9', self.domenu_browsenamespace),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000235 '-']
236 if self.profiling:
237 menuitems = menuitems + [('Disable profiler', self.domenu_toggleprofiler)]
238 else:
239 menuitems = menuitems + [('Enable profiler', self.domenu_toggleprofiler)]
240 if self.editgroup.editor._debugger:
241 menuitems = menuitems + [('Disable debugger', self.domenu_toggledebugger),
242 ('Clear breakpoints', self.domenu_clearbreakpoints),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000243 ('Edit breakpoints\xc9', self.domenu_editbreakpoints)]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000244 else:
245 menuitems = menuitems + [('Enable debugger', self.domenu_toggledebugger)]
246 self.editgroup.optionsmenu.set(menuitems)
247
248 def domenu_toggle_run_as_main(self):
249 self.run_as_main = not self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000250 self.run_with_interpreter = 0
251 self.editgroup.editor.selchanged = 1
252
253 def domenu_toggle_run_with_interpreter(self):
254 self.run_with_interpreter = not self.run_with_interpreter
255 self.run_as_main = 0
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000256 self.editgroup.editor.selchanged = 1
257
258 def showbreakpoints(self, onoff):
259 self.editgroup.editor.showbreakpoints(onoff)
260 self.debugging = onoff
261
262 def domenu_clearbreakpoints(self, *args):
263 self.editgroup.editor.clearbreakpoints()
264
265 def domenu_editbreakpoints(self, *args):
266 self.editgroup.editor.editbreakpoints()
267
268 def domenu_toggledebugger(self, *args):
269 if not self.debugging:
270 W.SetCursor('watch')
271 self.debugging = not self.debugging
272 self.editgroup.editor.togglebreakpoints()
273
274 def domenu_toggleprofiler(self, *args):
275 self.profiling = not self.profiling
276
277 def domenu_browsenamespace(self, *args):
278 import PyBrowser, W
279 W.SetCursor('watch')
280 globals, file, modname = self.getenvironment()
281 if not modname:
282 modname = self.title
283 PyBrowser.Browser(globals, "Object browser: " + modname)
284
285 def domenu_modularize(self, *args):
286 modname = _filename_as_modname(self.title)
287 if not modname:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000288 raise W.AlertError, "Can't modularize \"%s\"" % self.title
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000289 run_as_main = self.run_as_main
290 self.run_as_main = 0
291 self.run()
292 self.run_as_main = run_as_main
293 if self.path:
294 file = self.path
295 else:
296 file = self.title
297
298 if self.globals and not sys.modules.has_key(modname):
299 module = imp.new_module(modname)
300 for attr in self.globals.keys():
301 setattr(module,attr,self.globals[attr])
302 sys.modules[modname] = module
303 self.globals = {}
304
305 def domenu_fontsettings(self, *args):
306 import FontSettings
307 fontsettings = self.editgroup.editor.getfontsettings()
308 tabsettings = self.editgroup.editor.gettabsettings()
309 settings = FontSettings.FontDialog(fontsettings, tabsettings)
310 if settings:
311 fontsettings, tabsettings = settings
312 self.editgroup.editor.setfontsettings(fontsettings)
313 self.editgroup.editor.settabsettings(tabsettings)
314
Just van Rossum12710051999-02-27 17:18:30 +0000315 def domenu_options(self, *args):
316 rv = SaveOptions(self._creator)
317 if rv:
Just van Rossum3af507d1999-04-22 22:23:46 +0000318 self.editgroup.editor.selchanged = 1 # ouch...
Just van Rossum12710051999-02-27 17:18:30 +0000319 self._creator = rv
320
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000321 def clicklinefield(self):
322 if self._currentwidget <> self.linefield:
323 self.linefield.select(1)
324 self.linefield.selectall()
325 return 1
326
327 def clickeditor(self):
328 if self._currentwidget <> self.editgroup.editor:
329 self.dolinefield()
330 return 1
331
332 def updateselection(self, force = 0):
333 sel = min(self.editgroup.editor.getselection())
334 lineno = self.editgroup.editor.offsettoline(sel)
335 if lineno <> self.lastlineno or force:
336 self.lastlineno = lineno
337 self.linefield.set(str(lineno + 1))
338 self.linefield.selview()
339
340 def dolinefield(self):
341 try:
342 lineno = string.atoi(self.linefield.get()) - 1
343 if lineno <> self.lastlineno:
344 self.editgroup.editor.selectline(lineno)
345 self.updateselection(1)
346 except:
347 self.updateselection(1)
348 self.editgroup.editor.select(1)
349
350 def setinfotext(self):
351 if not hasattr(self, 'infotext'):
352 return
353 if self.path:
354 self.infotext.set(self.path)
355 else:
356 self.infotext.set("")
357
358 def close(self):
359 if self.editgroup.editor.changed:
360 import EasyDialogs
361 import Qd
362 Qd.InitCursor() # XXX should be done by dialog
Just van Rossumdc3c6172001-06-19 21:37:33 +0000363 save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title, 1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000364 if save > 0:
365 if self.domenu_save():
366 return 1
367 elif save < 0:
368 return 1
Just van Rossumc7ba0801999-05-21 21:42:27 +0000369 self.globals = None # XXX doesn't help... all globals leak :-(
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000370 W.Window.close(self)
371
372 def domenu_close(self, *args):
373 return self.close()
374
375 def domenu_save(self, *args):
376 if not self.path:
377 # Will call us recursively
378 return self.domenu_save_as()
379 data = self.editgroup.editor.get()
380 fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings
381 fp.write(data)
382 fp.close()
383 fss = macfs.FSSpec(self.path)
384 fss.SetCreatorType(self._creator, 'TEXT')
385 self.getsettings()
386 self.writewindowsettings()
387 self.editgroup.editor.changed = 0
388 self.editgroup.editor.selchanged = 0
389 import linecache
390 if linecache.cache.has_key(self.path):
391 del linecache.cache[self.path]
392 import macostools
393 macostools.touched(self.path)
394
395 def can_save(self, menuitem):
396 return self.editgroup.editor.changed or self.editgroup.editor.selchanged
397
398 def domenu_save_as(self, *args):
399 fss, ok = macfs.StandardPutFile('Save as:', self.title)
400 if not ok:
401 return 1
402 self.showbreakpoints(0)
403 self.path = fss.as_pathname()
404 self.setinfotext()
405 self.title = os.path.split(self.path)[-1]
406 self.wid.SetWTitle(self.title)
407 self.domenu_save()
408 self.editgroup.editor.setfile(self.getfilename())
409 app = W.getapplication()
410 app.makeopenwindowsmenu()
411 if hasattr(app, 'makescriptsmenu'):
412 app = W.getapplication()
413 fss, fss_changed = app.scriptsfolder.Resolve()
414 path = fss.as_pathname()
415 if path == self.path[:len(path)]:
416 W.getapplication().makescriptsmenu()
417
418 def domenu_save_as_applet(self, *args):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000419 import buildtools
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000420
421 buildtools.DEBUG = 0 # ouch.
422
423 if self.title[-3:] == ".py":
424 destname = self.title[:-3]
425 else:
426 destname = self.title + ".applet"
427 fss, ok = macfs.StandardPutFile('Save as Applet:', destname)
428 if not ok:
429 return 1
430 W.SetCursor("watch")
431 destname = fss.as_pathname()
432 if self.path:
433 filename = self.path
434 if filename[-3:] == ".py":
435 rsrcname = filename[:-3] + '.rsrc'
436 else:
437 rsrcname = filename + '.rsrc'
438 else:
439 filename = self.title
440 rsrcname = ""
441
442 pytext = self.editgroup.editor.get()
443 pytext = string.split(pytext, '\r')
444 pytext = string.join(pytext, '\n') + '\n'
445 try:
446 code = compile(pytext, filename, "exec")
447 except (SyntaxError, EOFError):
448 raise buildtools.BuildError, "Syntax error in script %s" % `filename`
449
450 # Try removing the output file
451 try:
452 os.remove(destname)
453 except os.error:
454 pass
455 template = buildtools.findtemplate()
456 buildtools.process_common(template, None, code, rsrcname, destname, 0, 1)
457
458 def domenu_gotoline(self, *args):
459 self.linefield.selectall()
460 self.linefield.select(1)
461 self.linefield.selectall()
462
463 def domenu_selectline(self, *args):
464 self.editgroup.editor.expandselection()
465
466 def domenu_find(self, *args):
467 searchengine.show()
468
469 def domenu_entersearchstring(self, *args):
470 searchengine.setfindstring()
471
472 def domenu_replace(self, *args):
473 searchengine.replace()
474
475 def domenu_findnext(self, *args):
476 searchengine.findnext()
477
478 def domenu_replacefind(self, *args):
479 searchengine.replacefind()
480
481 def domenu_run(self, *args):
482 self.runbutton.push()
483
484 def domenu_runselection(self, *args):
485 self.runselbutton.push()
486
487 def run(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000488 if self._threadstate == (0, 0):
489 self._run()
490 else:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000491 lock = Wthreading.Lock()
492 lock.acquire()
493 self._thread.postException(KeyboardInterrupt)
494 if self._thread.isBlocked():
Just van Rossum73efed22000-04-09 19:45:22 +0000495 self._thread.start()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000496 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000497
498 def _run(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000499 if self.run_with_interpreter:
500 if self.editgroup.editor.changed:
501 import EasyDialogs
502 import Qd; Qd.InitCursor()
Just van Rossumdc3c6172001-06-19 21:37:33 +0000503 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
Just van Rossum0f2fd162000-10-20 06:36:30 +0000504 if save > 0:
505 if self.domenu_save():
506 return
507 elif save < 0:
508 return
509 if not self.path:
510 raise W.AlertError, "Can't run unsaved file"
511 self._run_with_interpreter()
512 else:
513 pytext = self.editgroup.editor.get()
514 globals, file, modname = self.getenvironment()
515 self.execstring(pytext, globals, globals, file, modname)
516
517 def _run_with_interpreter(self):
518 interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter")
519 if not os.path.exists(interp_path):
520 raise W.AlertError, "Can't find interpreter"
521 import findertools
522 XXX
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000523
524 def runselection(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000525 if self._threadstate == (0, 0):
526 self._runselection()
527 elif self._threadstate == (1, 1):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000528 self._thread.block()
Just van Rossum73efed22000-04-09 19:45:22 +0000529 self.setthreadstate((1, 2))
530 elif self._threadstate == (1, 2):
531 self._thread.start()
532 self.setthreadstate((1, 1))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000533
534 def _runselection(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000535 if self.run_with_interpreter:
536 raise W.AlertError, "Can't run selection with Interpreter"
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000537 globals, file, modname = self.getenvironment()
538 locals = globals
539 # select whole lines
540 self.editgroup.editor.expandselection()
541
542 # get lineno of first selected line
543 selstart, selend = self.editgroup.editor.getselection()
544 selstart, selend = min(selstart, selend), max(selstart, selend)
545 selfirstline = self.editgroup.editor.offsettoline(selstart)
546 alltext = self.editgroup.editor.get()
547 pytext = alltext[selstart:selend]
548 lines = string.split(pytext, '\r')
549 indent = getminindent(lines)
550 if indent == 1:
551 classname = ''
552 alllines = string.split(alltext, '\r')
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000553 for i in range(selfirstline - 1, -1, -1):
554 line = alllines[i]
555 if line[:6] == 'class ':
556 classname = string.split(string.strip(line[6:]))[0]
557 classend = identifieRE_match(classname)
558 if classend < 1:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000559 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000560 classname = classname[:classend]
561 break
562 elif line and line[0] not in '\t#':
Just van Rossumdc3c6172001-06-19 21:37:33 +0000563 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000564 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000565 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000566 if globals.has_key(classname):
567 locals = globals[classname].__dict__
568 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000569 raise W.AlertError, "Can't find class \"%s\"." % classname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000570 # dedent to top level
571 for i in range(len(lines)):
572 lines[i] = lines[i][1:]
573 pytext = string.join(lines, '\r')
574 elif indent > 0:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000575 raise W.AlertError, "Can't run indented code."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000576
577 # add "newlines" to fool compile/exec:
578 # now a traceback will give the right line number
579 pytext = selfirstline * '\r' + pytext
580 self.execstring(pytext, globals, locals, file, modname)
581
Just van Rossum73efed22000-04-09 19:45:22 +0000582 def setthreadstate(self, state):
583 oldstate = self._threadstate
584 if oldstate[0] <> state[0]:
585 self.runbutton.settitle(runButtonLabels[state[0]])
586 if oldstate[1] <> state[1]:
587 self.runselbutton.settitle(runSelButtonLabels[state[1]])
588 self._threadstate = state
589
590 def _exec_threadwrapper(self, *args, **kwargs):
591 apply(execstring, args, kwargs)
592 self.setthreadstate((0, 0))
593 self._thread = None
594
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000595 def execstring(self, pytext, globals, locals, file, modname):
596 tracebackwindow.hide()
597 # update windows
598 W.getapplication().refreshwindows()
599 if self.run_as_main:
600 modname = "__main__"
601 if self.path:
602 dir = os.path.dirname(self.path)
603 savedir = os.getcwd()
604 os.chdir(dir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000605 sys.path.insert(0, dir)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000606 else:
607 cwdindex = None
608 try:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000609 if haveThreading:
610 self._thread = Wthreading.Thread(os.path.basename(file),
Just van Rossum73efed22000-04-09 19:45:22 +0000611 self._exec_threadwrapper, pytext, globals, locals, file, self.debugging,
612 modname, self.profiling)
613 self.setthreadstate((1, 1))
614 self._thread.start()
615 else:
616 execstring(pytext, globals, locals, file, self.debugging,
617 modname, self.profiling)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000618 finally:
619 if self.path:
620 os.chdir(savedir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000621 del sys.path[0]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000622
623 def getenvironment(self):
624 if self.path:
625 file = self.path
626 dir = os.path.dirname(file)
627 # check if we're part of a package
628 modname = ""
629 while os.path.exists(os.path.join(dir, "__init__.py")):
630 dir, dirname = os.path.split(dir)
Just van Rossum2aaeb521999-02-05 21:58:25 +0000631 modname = dirname + '.' + modname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000632 subname = _filename_as_modname(self.title)
633 if modname:
634 if subname == "__init__":
Just van Rossum2aaeb521999-02-05 21:58:25 +0000635 # strip trailing period
636 modname = modname[:-1]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000637 else:
Just van Rossum2aaeb521999-02-05 21:58:25 +0000638 modname = modname + subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000639 else:
640 modname = subname
641 if sys.modules.has_key(modname):
642 globals = sys.modules[modname].__dict__
643 self.globals = {}
644 else:
645 globals = self.globals
Just van Rossum73efed22000-04-09 19:45:22 +0000646 modname = subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000647 else:
648 file = '<%s>' % self.title
649 globals = self.globals
650 modname = file
651 return globals, file, modname
652
653 def write(self, stuff):
654 """for use as stdout"""
655 self._buf = self._buf + stuff
656 if '\n' in self._buf:
657 self.flush()
658
659 def flush(self):
660 stuff = string.split(self._buf, '\n')
661 stuff = string.join(stuff, '\r')
662 end = self.editgroup.editor.ted.WEGetTextLength()
663 self.editgroup.editor.ted.WESetSelection(end, end)
664 self.editgroup.editor.ted.WEInsert(stuff, None, None)
665 self.editgroup.editor.updatescrollbars()
666 self._buf = ""
667 # ? optional:
668 #self.wid.SelectWindow()
669
670 def getclasslist(self):
671 from string import find, strip
Just van Rossum24073ea1999-12-23 15:46:57 +0000672 methodRE = re.compile(r"\r[ \t]+def ")
673 findMethod = methodRE.search
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000674 editor = self.editgroup.editor
675 text = editor.get()
676 list = []
677 append = list.append
678 functag = "func"
679 classtag = "class"
680 methodtag = "method"
681 pos = -1
682 if text[:4] == 'def ':
683 append((pos + 4, functag))
684 pos = 4
685 while 1:
686 pos = find(text, '\rdef ', pos + 1)
687 if pos < 0:
688 break
689 append((pos + 5, functag))
690 pos = -1
691 if text[:6] == 'class ':
692 append((pos + 6, classtag))
693 pos = 6
694 while 1:
695 pos = find(text, '\rclass ', pos + 1)
696 if pos < 0:
697 break
698 append((pos + 7, classtag))
699 pos = 0
700 while 1:
Just van Rossum24073ea1999-12-23 15:46:57 +0000701 m = findMethod(text, pos + 1)
702 if m is None:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000703 break
Just van Rossum24073ea1999-12-23 15:46:57 +0000704 pos = m.regs[0][0]
705 #pos = find(text, '\r\tdef ', pos + 1)
706 append((m.regs[0][1], methodtag))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000707 list.sort()
708 classlist = []
709 methodlistappend = None
710 offsetToLine = editor.ted.WEOffsetToLine
711 getLineRange = editor.ted.WEGetLineRange
712 append = classlist.append
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000713 for pos, tag in list:
714 lineno = offsetToLine(pos)
715 lineStart, lineEnd = getLineRange(lineno)
716 line = strip(text[pos:lineEnd])
717 line = line[:identifieRE_match(line)]
718 if tag is functag:
719 append(("def " + line, lineno + 1))
720 methodlistappend = None
721 elif tag is classtag:
722 append(["class " + line])
723 methodlistappend = classlist[-1].append
724 elif methodlistappend and tag is methodtag:
725 methodlistappend(("def " + line, lineno + 1))
726 return classlist
727
728 def popselectline(self, lineno):
729 self.editgroup.editor.selectline(lineno - 1)
730
731 def selectline(self, lineno, charoffset = 0):
732 self.editgroup.editor.selectline(lineno - 1, charoffset)
733
Just van Rossum12710051999-02-27 17:18:30 +0000734class _saveoptions:
735
736 def __init__(self, creator):
737 self.rv = None
738 self.w = w = W.ModalDialog((240, 140), 'Save options')
739 radiobuttons = []
740 w.label = W.TextBox((8, 8, 80, 18), "File creator:")
Just van Rossum3af507d1999-04-22 22:23:46 +0000741 w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit)
742 w.interp_radio = W.RadioButton((8, 42, 160, 18), "Python Interpreter", radiobuttons, self.interp_hit)
Just van Rossum12710051999-02-27 17:18:30 +0000743 w.other_radio = W.RadioButton((8, 62, 50, 18), "Other:", radiobuttons)
744 w.other_creator = W.EditText((62, 62, 40, 20), creator, self.otherselect)
745 w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit)
746 w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit)
747 w.setdefaultbutton(w.okbutton)
748 if creator == 'Pyth':
749 w.interp_radio.set(1)
Just van Rossum3af507d1999-04-22 22:23:46 +0000750 elif creator == W._signature:
Just van Rossum12710051999-02-27 17:18:30 +0000751 w.ide_radio.set(1)
752 else:
753 w.other_radio.set(1)
754 w.bind("cmd.", w.cancelbutton.push)
755 w.open()
756
757 def ide_hit(self):
Just van Rossum3af507d1999-04-22 22:23:46 +0000758 self.w.other_creator.set(W._signature)
Just van Rossum12710051999-02-27 17:18:30 +0000759
760 def interp_hit(self):
761 self.w.other_creator.set("Pyth")
762
763 def otherselect(self, *args):
764 sel_from, sel_to = self.w.other_creator.getselection()
765 creator = self.w.other_creator.get()[:4]
766 creator = creator + " " * (4 - len(creator))
767 self.w.other_creator.set(creator)
768 self.w.other_creator.setselection(sel_from, sel_to)
769 self.w.other_radio.set(1)
770
771 def cancelbuttonhit(self):
772 self.w.close()
773
774 def okbuttonhit(self):
775 self.rv = self.w.other_creator.get()[:4]
776 self.w.close()
777
778
779def SaveOptions(creator):
780 s = _saveoptions(creator)
781 return s.rv
782
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000783
784def _escape(where, what) :
785 return string.join(string.split(where, what), '\\' + what)
786
787def _makewholewordpattern(word):
788 # first, escape special regex chars
789 for esc in "\\[].*^+$?":
790 word = _escape(word, esc)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000791 notwordcharspat = '[^' + _wordchars + ']'
Jack Jansen9ad27522001-02-21 13:54:31 +0000792 pattern = '(' + word + ')'
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000793 if word[0] in _wordchars:
794 pattern = notwordcharspat + pattern
795 if word[-1] in _wordchars:
796 pattern = pattern + notwordcharspat
Jack Jansen9ad27522001-02-21 13:54:31 +0000797 return re.compile(pattern)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000798
799class SearchEngine:
800
801 def __init__(self):
802 self.visible = 0
803 self.w = None
804 self.parms = { "find": "",
805 "replace": "",
806 "wrap": 1,
807 "casesens": 1,
808 "wholeword": 1
809 }
810 import MacPrefs
811 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
812 if prefs.searchengine:
813 self.parms["casesens"] = prefs.searchengine.casesens
814 self.parms["wrap"] = prefs.searchengine.wrap
815 self.parms["wholeword"] = prefs.searchengine.wholeword
816
817 def show(self):
818 self.visible = 1
819 if self.w:
820 self.w.wid.ShowWindow()
821 self.w.wid.SelectWindow()
822 self.w.find.edit.select(1)
823 self.w.find.edit.selectall()
824 return
825 self.w = W.Dialog((420, 150), "Find")
826
827 self.w.find = TitledEditText((10, 4, 300, 36), "Search for:")
828 self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:")
829
830 self.w.boxes = W.Group((10, 50, 300, 40))
831 self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive")
832 self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word")
833 self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around")
834
835 self.buttons = [ ("Find", "cmdf", self.find),
836 ("Replace", "cmdr", self.replace),
837 ("Replace all", None, self.replaceall),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000838 ("Don't find", "cmdd", self.dont),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000839 ("Cancel", "cmd.", self.cancel)
840 ]
841 for i in range(len(self.buttons)):
842 bounds = -90, 22 + i * 24, 80, 16
843 title, shortcut, callback = self.buttons[i]
844 self.w[title] = W.Button(bounds, title, callback)
845 if shortcut:
846 self.w.bind(shortcut, self.w[title].push)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000847 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000848 self.w.find.edit.bind("<key>", self.key)
849 self.w.bind("<activate>", self.activate)
850 self.w.bind("<close>", self.close)
851 self.w.open()
852 self.setparms()
853 self.w.find.edit.select(1)
854 self.w.find.edit.selectall()
855 self.checkbuttons()
856
857 def close(self):
858 self.hide()
859 return -1
860
861 def key(self, char, modifiers):
862 self.w.find.edit.key(char, modifiers)
863 self.checkbuttons()
864 return 1
865
866 def activate(self, onoff):
867 if onoff:
868 self.checkbuttons()
869
870 def checkbuttons(self):
871 editor = findeditor(self)
872 if editor:
873 if self.w.find.get():
874 for title, cmd, call in self.buttons[:-2]:
875 self.w[title].enable(1)
876 self.w.setdefaultbutton(self.w["Find"])
877 else:
878 for title, cmd, call in self.buttons[:-2]:
879 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000880 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000881 else:
882 for title, cmd, call in self.buttons[:-2]:
883 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000884 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000885
886 def find(self):
887 self.getparmsfromwindow()
888 if self.findnext():
889 self.hide()
890
891 def replace(self):
892 editor = findeditor(self)
893 if not editor:
894 return
895 if self.visible:
896 self.getparmsfromwindow()
897 text = editor.getselectedtext()
898 find = self.parms["find"]
899 if not self.parms["casesens"]:
900 find = string.lower(find)
901 text = string.lower(text)
902 if text == find:
903 self.hide()
904 editor.insert(self.parms["replace"])
905
906 def replaceall(self):
907 editor = findeditor(self)
908 if not editor:
909 return
910 if self.visible:
911 self.getparmsfromwindow()
912 W.SetCursor("watch")
913 find = self.parms["find"]
914 if not find:
915 return
916 findlen = len(find)
917 replace = self.parms["replace"]
918 replacelen = len(replace)
919 Text = editor.get()
920 if not self.parms["casesens"]:
921 find = string.lower(find)
922 text = string.lower(Text)
923 else:
924 text = Text
925 newtext = ""
926 pos = 0
927 counter = 0
928 while 1:
929 if self.parms["wholeword"]:
930 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000931 match = wholewordRE.search(text, pos)
932 if match:
933 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000934 else:
935 pos = -1
936 else:
937 pos = string.find(text, find, pos)
938 if pos < 0:
939 break
940 counter = counter + 1
941 text = text[:pos] + replace + text[pos + findlen:]
942 Text = Text[:pos] + replace + Text[pos + findlen:]
943 pos = pos + replacelen
944 W.SetCursor("arrow")
945 if counter:
946 self.hide()
947 import EasyDialogs
948 import Res
949 editor.changed = 1
950 editor.selchanged = 1
951 editor.ted.WEUseText(Res.Resource(Text))
952 editor.ted.WECalText()
953 editor.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +0000954 editor.GetWindow().InvalWindowRect(editor._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000955 #editor.ted.WEUpdate(self.w.wid.GetWindowPort().visRgn)
956 EasyDialogs.Message("Replaced %d occurrences" % counter)
957
958 def dont(self):
959 self.getparmsfromwindow()
960 self.hide()
961
962 def replacefind(self):
963 self.replace()
964 self.findnext()
965
966 def setfindstring(self):
967 editor = findeditor(self)
968 if not editor:
969 return
970 find = editor.getselectedtext()
971 if not find:
972 return
973 self.parms["find"] = find
974 if self.w:
975 self.w.find.edit.set(self.parms["find"])
976 self.w.find.edit.selectall()
977
978 def findnext(self):
979 editor = findeditor(self)
980 if not editor:
981 return
982 find = self.parms["find"]
983 if not find:
984 return
985 text = editor.get()
986 if not self.parms["casesens"]:
987 find = string.lower(find)
988 text = string.lower(text)
989 selstart, selend = editor.getselection()
990 selstart, selend = min(selstart, selend), max(selstart, selend)
991 if self.parms["wholeword"]:
992 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000993 match = wholewordRE.search(text, selend)
994 if match:
995 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000996 else:
997 pos = -1
998 else:
999 pos = string.find(text, find, selend)
1000 if pos >= 0:
1001 editor.setselection(pos, pos + len(find))
1002 return 1
1003 elif self.parms["wrap"]:
1004 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001005 match = wholewordRE.search(text, 0)
1006 if match:
1007 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001008 else:
1009 pos = -1
1010 else:
1011 pos = string.find(text, find)
1012 if selstart > pos >= 0:
1013 editor.setselection(pos, pos + len(find))
1014 return 1
1015
1016 def setparms(self):
1017 for key, value in self.parms.items():
1018 try:
1019 self.w[key].set(value)
1020 except KeyError:
1021 self.w.boxes[key].set(value)
1022
1023 def getparmsfromwindow(self):
1024 if not self.w:
1025 return
1026 for key, value in self.parms.items():
1027 try:
1028 value = self.w[key].get()
1029 except KeyError:
1030 value = self.w.boxes[key].get()
1031 self.parms[key] = value
1032
1033 def cancel(self):
1034 self.hide()
1035 self.setparms()
1036
1037 def hide(self):
1038 if self.w:
1039 self.w.wid.HideWindow()
1040 self.visible = 0
1041
1042 def writeprefs(self):
1043 import MacPrefs
1044 self.getparmsfromwindow()
1045 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1046 prefs.searchengine.casesens = self.parms["casesens"]
1047 prefs.searchengine.wrap = self.parms["wrap"]
1048 prefs.searchengine.wholeword = self.parms["wholeword"]
1049 prefs.save()
1050
1051
1052class TitledEditText(W.Group):
1053
1054 def __init__(self, possize, title, text = ""):
1055 W.Group.__init__(self, possize)
1056 self.title = W.TextBox((0, 0, 0, 16), title)
1057 self.edit = W.EditText((0, 16, 0, 0), text)
1058
1059 def set(self, value):
1060 self.edit.set(value)
1061
1062 def get(self):
1063 return self.edit.get()
1064
1065
1066class ClassFinder(W.PopupWidget):
1067
1068 def click(self, point, modifiers):
1069 W.SetCursor("watch")
1070 self.set(self._parentwindow.getclasslist())
1071 W.PopupWidget.click(self, point, modifiers)
1072
1073
1074def getminindent(lines):
1075 indent = -1
1076 for line in lines:
1077 stripped = string.strip(line)
1078 if not stripped or stripped[0] == '#':
1079 continue
1080 if indent < 0 or line[:indent] <> indent * '\t':
1081 indent = 0
1082 for c in line:
1083 if c <> '\t':
1084 break
1085 indent = indent + 1
1086 return indent
1087
1088
1089def getoptionkey():
1090 return not not ord(Evt.GetKeys()[7]) & 0x04
1091
1092
1093def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1094 modname="__main__", profiling=0):
1095 if debugging:
1096 import PyDebugger, bdb
1097 BdbQuit = bdb.BdbQuit
1098 else:
1099 BdbQuit = 'BdbQuitDummyException'
1100 pytext = string.split(pytext, '\r')
1101 pytext = string.join(pytext, '\n') + '\n'
1102 W.SetCursor("watch")
1103 globals['__name__'] = modname
1104 globals['__file__'] = filename
1105 sys.argv = [filename]
1106 try:
1107 code = compile(pytext, filename, "exec")
1108 except:
1109 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1110 # special. That's wrong because THIS case is special (could be literal
1111 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1112 # in imported module!!!
1113 tracebackwindow.traceback(1, filename)
1114 return
1115 try:
1116 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001117 if haveThreading:
1118 lock = Wthreading.Lock()
1119 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001120 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001121 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001122 else:
1123 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001124 elif not haveThreading:
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001125 MacOS.EnableAppswitch(0)
1126 try:
1127 if profiling:
1128 import profile, ProfileBrowser
1129 p = profile.Profile()
1130 p.set_cmd(filename)
1131 try:
1132 p.runctx(code, globals, locals)
1133 finally:
1134 import pstats
1135
1136 stats = pstats.Stats(p)
1137 ProfileBrowser.ProfileBrowser(stats)
1138 else:
1139 exec code in globals, locals
1140 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001141 if not haveThreading:
Just van Rossum73efed22000-04-09 19:45:22 +00001142 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001143 except W.AlertError, detail:
1144 raise W.AlertError, detail
1145 except (KeyboardInterrupt, BdbQuit):
1146 pass
1147 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001148 if haveThreading:
1149 import continuation
1150 lock = Wthreading.Lock()
1151 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001152 if debugging:
1153 sys.settrace(None)
1154 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1155 return
1156 else:
1157 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001158 if haveThreading:
1159 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001160 if debugging:
1161 sys.settrace(None)
1162 PyDebugger.stop()
1163
1164
Jack Jansen9ad27522001-02-21 13:54:31 +00001165_identifieRE = re.compile("[A-Za-z_][A-Za-z_0-9]*")
1166
1167def identifieRE_match(str):
1168 match = _identifieRE.match(str)
1169 if not match:
1170 return -1
1171 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001172
1173def _filename_as_modname(fname):
1174 if fname[-3:] == '.py':
1175 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001176 match = _identifieRE.match(modname)
1177 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001178 return string.join(string.split(modname, '.'), '_')
1179
1180def findeditor(topwindow, fromtop = 0):
1181 wid = Win.FrontWindow()
1182 if not fromtop:
1183 if topwindow.w and wid == topwindow.w.wid:
1184 wid = topwindow.w.wid.GetNextWindow()
1185 if not wid:
1186 return
1187 app = W.getapplication()
1188 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1189 window = W.getapplication()._windows[wid]
1190 else:
1191 return
1192 if not isinstance(window, Editor):
1193 return
1194 return window.editgroup.editor
1195
1196
1197class _EditorDefaultSettings:
1198
1199 def __init__(self):
1200 self.template = "%s, %d point"
1201 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1202 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001203 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001204 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1205
1206 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1207 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1208 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1209 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1210 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1211
1212 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1213 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1214 self.w.setdefaultbutton(self.w.okbutton)
1215 self.w.bind('cmd.', self.w.cancelbutton.push)
1216 self.w.open()
1217
1218 def picksize(self):
1219 app = W.getapplication()
1220 editor = findeditor(self)
1221 if editor is not None:
1222 width, height = editor._parentwindow._bounds[2:]
1223 self.w.xsize.set(`width`)
1224 self.w.ysize.set(`height`)
1225 else:
1226 raise W.AlertError, "No edit window found"
1227
1228 def dofont(self):
1229 import FontSettings
1230 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1231 if settings:
1232 self.fontsettings, self.tabsettings = settings
1233 sys.exc_traceback = None
1234 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1235
1236 def close(self):
1237 self.w.close()
1238 del self.w
1239
1240 def cancel(self):
1241 self.close()
1242
1243 def ok(self):
1244 try:
1245 width = string.atoi(self.w.xsize.get())
1246 except:
1247 self.w.xsize.select(1)
1248 self.w.xsize.selectall()
1249 raise W.AlertError, "Bad number for window width"
1250 try:
1251 height = string.atoi(self.w.ysize.get())
1252 except:
1253 self.w.ysize.select(1)
1254 self.w.ysize.selectall()
1255 raise W.AlertError, "Bad number for window height"
1256 self.windowsize = width, height
1257 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1258 self.close()
1259
1260def geteditorprefs():
1261 import MacPrefs
1262 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1263 try:
1264 fontsettings = prefs.pyedit.fontsettings
1265 tabsettings = prefs.pyedit.tabsettings
1266 windowsize = prefs.pyedit.windowsize
1267 except:
1268 fontsettings = prefs.pyedit.fontsettings = ("Python-Sans", 0, 9, (0, 0, 0))
1269 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1270 windowsize = prefs.pyedit.windowsize = (500, 250)
1271 sys.exc_traceback = None
1272 return fontsettings, tabsettings, windowsize
1273
1274def seteditorprefs(fontsettings, tabsettings, windowsize):
1275 import MacPrefs
1276 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1277 prefs.pyedit.fontsettings = fontsettings
1278 prefs.pyedit.tabsettings = tabsettings
1279 prefs.pyedit.windowsize = windowsize
1280 prefs.save()
1281
1282_defaultSettingsEditor = None
1283
1284def EditorDefaultSettings():
1285 global _defaultSettingsEditor
1286 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1287 _defaultSettingsEditor = _EditorDefaultSettings()
1288 else:
1289 _defaultSettingsEditor.w.select()
1290
1291def resolvealiases(path):
1292 try:
1293 return macfs.ResolveAliasFile(path)[0].as_pathname()
1294 except (macfs.error, ValueError), (error, str):
1295 if error <> -120:
1296 raise
1297 dir, file = os.path.split(path)
1298 return os.path.join(resolvealiases(dir), file)
1299
1300searchengine = SearchEngine()
1301tracebackwindow = Wtraceback.TraceBack()