blob: 1bebe6ee90e8aabcde30548c927b2ec93e633152 [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
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000010from Carbon import Win
11from Carbon import Res
12from Carbon import Evt
Just van Rossum40f9b7b1999-01-30 22:39:17 +000013import 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
Fred Drake79e75e12001-07-20 19:05:50 +000028_wordchars = string.ascii_letters + string.digits + "_"
Just van Rossum40f9b7b1999-01-30 22:39:17 +000029
30
Just van Rossum73efed22000-04-09 19:45:22 +000031runButtonLabels = ["Run all", "Stop!"]
32runSelButtonLabels = ["Run selection", "Pause!", "Resume"]
33
34
Just van Rossum40f9b7b1999-01-30 22:39:17 +000035class Editor(W.Window):
36
37 def __init__(self, path = "", title = ""):
38 defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs()
39 global _scriptuntitledcounter
40 if not path:
41 if title:
42 self.title = title
43 else:
44 self.title = "Untitled Script " + `_scriptuntitledcounter`
45 _scriptuntitledcounter = _scriptuntitledcounter + 1
46 text = ""
47 self._creator = W._signature
48 elif os.path.exists(path):
49 path = resolvealiases(path)
50 dir, name = os.path.split(path)
51 self.title = name
52 f = open(path, "rb")
53 text = f.read()
54 f.close()
55 fss = macfs.FSSpec(path)
56 self._creator, filetype = fss.GetCreatorType()
57 else:
58 raise IOError, "file '%s' does not exist" % path
59 self.path = path
60
Just van Rossumc7ba0801999-05-21 21:42:27 +000061 if '\n' in text:
62 import EasyDialogs
63 if string.find(text, '\r\n') >= 0:
64 sourceOS = 'DOS'
65 searchString = '\r\n'
66 else:
67 sourceOS = 'UNIX'
68 searchString = '\n'
Just van Rossumdc3c6172001-06-19 21:37:33 +000069 change = EasyDialogs.AskYesNoCancel('"%s" contains %s-style line feeds. '
Just van Rossum73efed22000-04-09 19:45:22 +000070 'Change them to MacOS carriage returns?' % (self.title, sourceOS), 1)
Just van Rossumc7ba0801999-05-21 21:42:27 +000071 # bug: Cancel is treated as No
72 if change > 0:
73 text = string.replace(text, searchString, '\r')
74 else:
75 change = 0
76
Just van Rossum40f9b7b1999-01-30 22:39:17 +000077 self.settings = {}
78 if self.path:
79 self.readwindowsettings()
80 if self.settings.has_key("windowbounds"):
81 bounds = self.settings["windowbounds"]
82 else:
83 bounds = defaultwindowsize
84 if self.settings.has_key("fontsettings"):
85 self.fontsettings = self.settings["fontsettings"]
86 else:
87 self.fontsettings = defaultfontsettings
88 if self.settings.has_key("tabsize"):
89 try:
90 self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"]
91 except:
92 self.tabsettings = defaulttabsettings
93 else:
94 self.tabsettings = defaulttabsettings
Just van Rossum40f9b7b1999-01-30 22:39:17 +000095
Just van Rossumc7ba0801999-05-21 21:42:27 +000096 W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +000097 self.setupwidgets(text)
Just van Rossumc7ba0801999-05-21 21:42:27 +000098 if change > 0:
Just van Rossumf7f93882001-11-02 19:24:41 +000099 self.editgroup.editor.textchanged()
Just van Rossumc7ba0801999-05-21 21:42:27 +0000100
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000101 if self.settings.has_key("selection"):
102 selstart, selend = self.settings["selection"]
103 self.setselection(selstart, selend)
104 self.open()
105 self.setinfotext()
106 self.globals = {}
107 self._buf = "" # for write method
108 self.debugging = 0
109 self.profiling = 0
110 if self.settings.has_key("run_as_main"):
111 self.run_as_main = self.settings["run_as_main"]
112 else:
113 self.run_as_main = 0
Just van Rossum0f2fd162000-10-20 06:36:30 +0000114 if self.settings.has_key("run_with_interpreter"):
115 self.run_with_interpreter = self.settings["run_with_interpreter"]
116 else:
117 self.run_with_interpreter = 0
Just van Rossum73efed22000-04-09 19:45:22 +0000118 self._threadstate = (0, 0)
119 self._thread = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000120
121 def readwindowsettings(self):
122 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000123 resref = Res.FSpOpenResFile(self.path, 1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000124 except Res.Error:
125 return
126 try:
127 Res.UseResFile(resref)
128 data = Res.Get1Resource('PyWS', 128)
129 self.settings = marshal.loads(data.data)
130 except:
131 pass
132 Res.CloseResFile(resref)
133
134 def writewindowsettings(self):
135 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000136 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000137 except Res.Error:
Jack Jansen64aa1e22001-01-29 15:19:17 +0000138 Res.FSpCreateResFile(self.path, self._creator, 'TEXT', MACFS.smAllScripts)
Jack Jansend13c3852000-06-20 21:59:25 +0000139 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000140 try:
141 data = Res.Resource(marshal.dumps(self.settings))
142 Res.UseResFile(resref)
143 try:
144 temp = Res.Get1Resource('PyWS', 128)
145 temp.RemoveResource()
146 except Res.Error:
147 pass
148 data.AddResource('PyWS', 128, "window settings")
149 finally:
150 Res.UpdateResFile(resref)
151 Res.CloseResFile(resref)
152
153 def getsettings(self):
154 self.settings = {}
155 self.settings["windowbounds"] = self.getbounds()
156 self.settings["selection"] = self.getselection()
157 self.settings["fontsettings"] = self.editgroup.editor.getfontsettings()
158 self.settings["tabsize"] = self.editgroup.editor.gettabsettings()
159 self.settings["run_as_main"] = self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000160 self.settings["run_with_interpreter"] = self.run_with_interpreter
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000161
162 def get(self):
163 return self.editgroup.editor.get()
164
165 def getselection(self):
166 return self.editgroup.editor.ted.WEGetSelection()
167
168 def setselection(self, selstart, selend):
169 self.editgroup.editor.setselection(selstart, selend)
170
171 def getfilename(self):
172 if self.path:
173 return self.path
174 return '<%s>' % self.title
175
176 def setupwidgets(self, text):
Just van Rossum6b45b1e2001-11-02 22:55:15 +0000177 topbarheight = 28
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000178 popfieldwidth = 80
179 self.lastlineno = None
180
181 # make an editor
182 self.editgroup = W.Group((0, topbarheight + 1, 0, 0))
183 editor = W.PyEditor((0, 0, -15,-15), text,
184 fontsettings = self.fontsettings,
185 tabsettings = self.tabsettings,
186 file = self.getfilename())
187
188 # make the widgets
189 self.popfield = ClassFinder((popfieldwidth - 17, -15, 16, 16), [], self.popselectline)
190 self.linefield = W.EditText((-1, -15, popfieldwidth - 15, 16), inset = (6, 1))
191 self.editgroup._barx = W.Scrollbar((popfieldwidth - 2, -15, -14, 16), editor.hscroll, max = 32767)
192 self.editgroup._bary = W.Scrollbar((-15, 14, 16, -14), editor.vscroll, max = 32767)
193 self.editgroup.editor = editor # add editor *after* scrollbars
194
195 self.editgroup.optionsmenu = W.PopupMenu((-15, -1, 16, 16), [])
196 self.editgroup.optionsmenu.bind('<click>', self.makeoptionsmenu)
197
198 self.bevelbox = W.BevelBox((0, 0, 0, topbarheight))
199 self.hline = W.HorizontalLine((0, topbarheight, 0, 0))
Just van Rossum6b45b1e2001-11-02 22:55:15 +0000200 self.infotext = W.TextBox((175, 7, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000))
201 self.runbutton = W.Button((6, 5, 60, 16), runButtonLabels[0], self.run)
202 self.runselbutton = W.Button((78, 5, 90, 16), runSelButtonLabels[0], self.runselection)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000203
204 # bind some keys
205 editor.bind("cmdr", self.runbutton.push)
206 editor.bind("enter", self.runselbutton.push)
207 editor.bind("cmdj", self.domenu_gotoline)
208 editor.bind("cmdd", self.domenu_toggledebugger)
209 editor.bind("<idle>", self.updateselection)
210
211 editor.bind("cmde", searchengine.setfindstring)
212 editor.bind("cmdf", searchengine.show)
213 editor.bind("cmdg", searchengine.findnext)
214 editor.bind("cmdshiftr", searchengine.replace)
215 editor.bind("cmdt", searchengine.replacefind)
216
217 self.linefield.bind("return", self.dolinefield)
218 self.linefield.bind("enter", self.dolinefield)
219 self.linefield.bind("tab", self.dolinefield)
220
221 # intercept clicks
222 editor.bind("<click>", self.clickeditor)
223 self.linefield.bind("<click>", self.clicklinefield)
224
225 def makeoptionsmenu(self):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000226 menuitems = [('Font settings\xc9', self.domenu_fontsettings),
227 ("Save options\xc9", self.domenu_options),
Just van Rossum12710051999-02-27 17:18:30 +0000228 '-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000229 ('\0' + chr(self.run_as_main) + 'Run as __main__', self.domenu_toggle_run_as_main),
Just van Rossum0f2fd162000-10-20 06:36:30 +0000230 #('\0' + chr(self.run_with_interpreter) + 'Run with Interpreter', self.domenu_toggle_run_with_interpreter),
231 #'-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000232 ('Modularize', self.domenu_modularize),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000233 ('Browse namespace\xc9', self.domenu_browsenamespace),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000234 '-']
235 if self.profiling:
236 menuitems = menuitems + [('Disable profiler', self.domenu_toggleprofiler)]
237 else:
238 menuitems = menuitems + [('Enable profiler', self.domenu_toggleprofiler)]
239 if self.editgroup.editor._debugger:
240 menuitems = menuitems + [('Disable debugger', self.domenu_toggledebugger),
241 ('Clear breakpoints', self.domenu_clearbreakpoints),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000242 ('Edit breakpoints\xc9', self.domenu_editbreakpoints)]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000243 else:
244 menuitems = menuitems + [('Enable debugger', self.domenu_toggledebugger)]
245 self.editgroup.optionsmenu.set(menuitems)
246
247 def domenu_toggle_run_as_main(self):
248 self.run_as_main = not self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000249 self.run_with_interpreter = 0
Just van Rossumf7f93882001-11-02 19:24:41 +0000250 self.editgroup.editor.selectionchanged()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000251
252 def domenu_toggle_run_with_interpreter(self):
253 self.run_with_interpreter = not self.run_with_interpreter
254 self.run_as_main = 0
Just van Rossumf7f93882001-11-02 19:24:41 +0000255 self.editgroup.editor.selectionchanged()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000256
257 def showbreakpoints(self, onoff):
258 self.editgroup.editor.showbreakpoints(onoff)
259 self.debugging = onoff
260
261 def domenu_clearbreakpoints(self, *args):
262 self.editgroup.editor.clearbreakpoints()
263
264 def domenu_editbreakpoints(self, *args):
265 self.editgroup.editor.editbreakpoints()
266
267 def domenu_toggledebugger(self, *args):
268 if not self.debugging:
269 W.SetCursor('watch')
270 self.debugging = not self.debugging
271 self.editgroup.editor.togglebreakpoints()
272
273 def domenu_toggleprofiler(self, *args):
274 self.profiling = not self.profiling
275
276 def domenu_browsenamespace(self, *args):
277 import PyBrowser, W
278 W.SetCursor('watch')
279 globals, file, modname = self.getenvironment()
280 if not modname:
281 modname = self.title
282 PyBrowser.Browser(globals, "Object browser: " + modname)
283
284 def domenu_modularize(self, *args):
285 modname = _filename_as_modname(self.title)
286 if not modname:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000287 raise W.AlertError, "Can't modularize \"%s\"" % self.title
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000288 run_as_main = self.run_as_main
289 self.run_as_main = 0
290 self.run()
291 self.run_as_main = run_as_main
292 if self.path:
293 file = self.path
294 else:
295 file = self.title
296
297 if self.globals and not sys.modules.has_key(modname):
298 module = imp.new_module(modname)
299 for attr in self.globals.keys():
300 setattr(module,attr,self.globals[attr])
301 sys.modules[modname] = module
302 self.globals = {}
303
304 def domenu_fontsettings(self, *args):
305 import FontSettings
306 fontsettings = self.editgroup.editor.getfontsettings()
307 tabsettings = self.editgroup.editor.gettabsettings()
308 settings = FontSettings.FontDialog(fontsettings, tabsettings)
309 if settings:
310 fontsettings, tabsettings = settings
311 self.editgroup.editor.setfontsettings(fontsettings)
312 self.editgroup.editor.settabsettings(tabsettings)
313
Just van Rossum12710051999-02-27 17:18:30 +0000314 def domenu_options(self, *args):
315 rv = SaveOptions(self._creator)
316 if rv:
Just van Rossumf7f93882001-11-02 19:24:41 +0000317 self.editgroup.editor.selectionchanged() # ouch...
Just van Rossum12710051999-02-27 17:18:30 +0000318 self._creator = rv
319
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000320 def clicklinefield(self):
321 if self._currentwidget <> self.linefield:
322 self.linefield.select(1)
323 self.linefield.selectall()
324 return 1
325
326 def clickeditor(self):
327 if self._currentwidget <> self.editgroup.editor:
328 self.dolinefield()
329 return 1
330
331 def updateselection(self, force = 0):
332 sel = min(self.editgroup.editor.getselection())
333 lineno = self.editgroup.editor.offsettoline(sel)
334 if lineno <> self.lastlineno or force:
335 self.lastlineno = lineno
336 self.linefield.set(str(lineno + 1))
337 self.linefield.selview()
338
339 def dolinefield(self):
340 try:
341 lineno = string.atoi(self.linefield.get()) - 1
342 if lineno <> self.lastlineno:
343 self.editgroup.editor.selectline(lineno)
344 self.updateselection(1)
345 except:
346 self.updateselection(1)
347 self.editgroup.editor.select(1)
348
349 def setinfotext(self):
350 if not hasattr(self, 'infotext'):
351 return
352 if self.path:
353 self.infotext.set(self.path)
354 else:
355 self.infotext.set("")
356
357 def close(self):
358 if self.editgroup.editor.changed:
359 import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +0000360 from Carbon import Qd
Just van Rossum25ddc632001-07-05 07:06:26 +0000361 Qd.InitCursor()
362 save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title,
363 default=1, no="Don\xd5t save")
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 Rossum25ddc632001-07-05 07:06:26 +0000369 self.globals = None
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):
Just van Rossum25ddc632001-07-05 07:06:26 +0000567 klass = globals[classname]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000568 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000569 raise W.AlertError, "Can't find class \"%s\"." % classname
Just van Rossum25ddc632001-07-05 07:06:26 +0000570 # add class def
571 pytext = ("class %s:\n" % classname) + pytext
572 selfirstline = selfirstline - 1
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000573 elif indent > 0:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000574 raise W.AlertError, "Can't run indented code."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000575
576 # add "newlines" to fool compile/exec:
577 # now a traceback will give the right line number
578 pytext = selfirstline * '\r' + pytext
579 self.execstring(pytext, globals, locals, file, modname)
Just van Rossum25ddc632001-07-05 07:06:26 +0000580 if indent == 1 and globals[classname] is not klass:
581 # update the class in place
582 klass.__dict__.update(globals[classname].__dict__)
583 globals[classname] = klass
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000584
Just van Rossum73efed22000-04-09 19:45:22 +0000585 def setthreadstate(self, state):
586 oldstate = self._threadstate
587 if oldstate[0] <> state[0]:
588 self.runbutton.settitle(runButtonLabels[state[0]])
589 if oldstate[1] <> state[1]:
590 self.runselbutton.settitle(runSelButtonLabels[state[1]])
591 self._threadstate = state
592
593 def _exec_threadwrapper(self, *args, **kwargs):
594 apply(execstring, args, kwargs)
595 self.setthreadstate((0, 0))
596 self._thread = None
597
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000598 def execstring(self, pytext, globals, locals, file, modname):
599 tracebackwindow.hide()
600 # update windows
601 W.getapplication().refreshwindows()
602 if self.run_as_main:
603 modname = "__main__"
604 if self.path:
605 dir = os.path.dirname(self.path)
606 savedir = os.getcwd()
607 os.chdir(dir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000608 sys.path.insert(0, dir)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000609 else:
610 cwdindex = None
611 try:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000612 if haveThreading:
613 self._thread = Wthreading.Thread(os.path.basename(file),
Just van Rossum73efed22000-04-09 19:45:22 +0000614 self._exec_threadwrapper, pytext, globals, locals, file, self.debugging,
615 modname, self.profiling)
616 self.setthreadstate((1, 1))
617 self._thread.start()
618 else:
619 execstring(pytext, globals, locals, file, self.debugging,
620 modname, self.profiling)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000621 finally:
622 if self.path:
623 os.chdir(savedir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000624 del sys.path[0]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000625
626 def getenvironment(self):
627 if self.path:
628 file = self.path
629 dir = os.path.dirname(file)
630 # check if we're part of a package
631 modname = ""
632 while os.path.exists(os.path.join(dir, "__init__.py")):
633 dir, dirname = os.path.split(dir)
Just van Rossum2aaeb521999-02-05 21:58:25 +0000634 modname = dirname + '.' + modname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000635 subname = _filename_as_modname(self.title)
Just van Rossumf7f93882001-11-02 19:24:41 +0000636 if subname is None:
637 return self.globals, file, None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000638 if modname:
639 if subname == "__init__":
Just van Rossum2aaeb521999-02-05 21:58:25 +0000640 # strip trailing period
641 modname = modname[:-1]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000642 else:
Just van Rossum2aaeb521999-02-05 21:58:25 +0000643 modname = modname + subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000644 else:
645 modname = subname
646 if sys.modules.has_key(modname):
647 globals = sys.modules[modname].__dict__
648 self.globals = {}
649 else:
650 globals = self.globals
Just van Rossum73efed22000-04-09 19:45:22 +0000651 modname = subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000652 else:
653 file = '<%s>' % self.title
654 globals = self.globals
655 modname = file
656 return globals, file, modname
657
658 def write(self, stuff):
659 """for use as stdout"""
660 self._buf = self._buf + stuff
661 if '\n' in self._buf:
662 self.flush()
663
664 def flush(self):
665 stuff = string.split(self._buf, '\n')
666 stuff = string.join(stuff, '\r')
667 end = self.editgroup.editor.ted.WEGetTextLength()
668 self.editgroup.editor.ted.WESetSelection(end, end)
669 self.editgroup.editor.ted.WEInsert(stuff, None, None)
670 self.editgroup.editor.updatescrollbars()
671 self._buf = ""
672 # ? optional:
673 #self.wid.SelectWindow()
674
675 def getclasslist(self):
676 from string import find, strip
Just van Rossum24073ea1999-12-23 15:46:57 +0000677 methodRE = re.compile(r"\r[ \t]+def ")
678 findMethod = methodRE.search
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000679 editor = self.editgroup.editor
680 text = editor.get()
681 list = []
682 append = list.append
683 functag = "func"
684 classtag = "class"
685 methodtag = "method"
686 pos = -1
687 if text[:4] == 'def ':
688 append((pos + 4, functag))
689 pos = 4
690 while 1:
691 pos = find(text, '\rdef ', pos + 1)
692 if pos < 0:
693 break
694 append((pos + 5, functag))
695 pos = -1
696 if text[:6] == 'class ':
697 append((pos + 6, classtag))
698 pos = 6
699 while 1:
700 pos = find(text, '\rclass ', pos + 1)
701 if pos < 0:
702 break
703 append((pos + 7, classtag))
704 pos = 0
705 while 1:
Just van Rossum24073ea1999-12-23 15:46:57 +0000706 m = findMethod(text, pos + 1)
707 if m is None:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000708 break
Just van Rossum24073ea1999-12-23 15:46:57 +0000709 pos = m.regs[0][0]
710 #pos = find(text, '\r\tdef ', pos + 1)
711 append((m.regs[0][1], methodtag))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000712 list.sort()
713 classlist = []
714 methodlistappend = None
715 offsetToLine = editor.ted.WEOffsetToLine
716 getLineRange = editor.ted.WEGetLineRange
717 append = classlist.append
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000718 for pos, tag in list:
719 lineno = offsetToLine(pos)
720 lineStart, lineEnd = getLineRange(lineno)
721 line = strip(text[pos:lineEnd])
722 line = line[:identifieRE_match(line)]
723 if tag is functag:
724 append(("def " + line, lineno + 1))
725 methodlistappend = None
726 elif tag is classtag:
727 append(["class " + line])
728 methodlistappend = classlist[-1].append
729 elif methodlistappend and tag is methodtag:
730 methodlistappend(("def " + line, lineno + 1))
731 return classlist
732
733 def popselectline(self, lineno):
734 self.editgroup.editor.selectline(lineno - 1)
735
736 def selectline(self, lineno, charoffset = 0):
737 self.editgroup.editor.selectline(lineno - 1, charoffset)
738
Just van Rossum12710051999-02-27 17:18:30 +0000739class _saveoptions:
740
741 def __init__(self, creator):
742 self.rv = None
743 self.w = w = W.ModalDialog((240, 140), 'Save options')
744 radiobuttons = []
745 w.label = W.TextBox((8, 8, 80, 18), "File creator:")
Just van Rossum3af507d1999-04-22 22:23:46 +0000746 w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit)
747 w.interp_radio = W.RadioButton((8, 42, 160, 18), "Python Interpreter", radiobuttons, self.interp_hit)
Just van Rossum12710051999-02-27 17:18:30 +0000748 w.other_radio = W.RadioButton((8, 62, 50, 18), "Other:", radiobuttons)
749 w.other_creator = W.EditText((62, 62, 40, 20), creator, self.otherselect)
750 w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit)
751 w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit)
752 w.setdefaultbutton(w.okbutton)
753 if creator == 'Pyth':
754 w.interp_radio.set(1)
Just van Rossum3af507d1999-04-22 22:23:46 +0000755 elif creator == W._signature:
Just van Rossum12710051999-02-27 17:18:30 +0000756 w.ide_radio.set(1)
757 else:
758 w.other_radio.set(1)
759 w.bind("cmd.", w.cancelbutton.push)
760 w.open()
761
762 def ide_hit(self):
Just van Rossum3af507d1999-04-22 22:23:46 +0000763 self.w.other_creator.set(W._signature)
Just van Rossum12710051999-02-27 17:18:30 +0000764
765 def interp_hit(self):
766 self.w.other_creator.set("Pyth")
767
768 def otherselect(self, *args):
769 sel_from, sel_to = self.w.other_creator.getselection()
770 creator = self.w.other_creator.get()[:4]
771 creator = creator + " " * (4 - len(creator))
772 self.w.other_creator.set(creator)
773 self.w.other_creator.setselection(sel_from, sel_to)
774 self.w.other_radio.set(1)
775
776 def cancelbuttonhit(self):
777 self.w.close()
778
779 def okbuttonhit(self):
780 self.rv = self.w.other_creator.get()[:4]
781 self.w.close()
782
783
784def SaveOptions(creator):
785 s = _saveoptions(creator)
786 return s.rv
787
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000788
789def _escape(where, what) :
790 return string.join(string.split(where, what), '\\' + what)
791
792def _makewholewordpattern(word):
793 # first, escape special regex chars
Just van Rossum3eec7622001-07-10 19:25:40 +0000794 for esc in "\\[]()|.*^+$?":
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000795 word = _escape(word, esc)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000796 notwordcharspat = '[^' + _wordchars + ']'
Jack Jansen9ad27522001-02-21 13:54:31 +0000797 pattern = '(' + word + ')'
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000798 if word[0] in _wordchars:
799 pattern = notwordcharspat + pattern
800 if word[-1] in _wordchars:
801 pattern = pattern + notwordcharspat
Jack Jansen9ad27522001-02-21 13:54:31 +0000802 return re.compile(pattern)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000803
804class SearchEngine:
805
806 def __init__(self):
807 self.visible = 0
808 self.w = None
809 self.parms = { "find": "",
810 "replace": "",
811 "wrap": 1,
812 "casesens": 1,
813 "wholeword": 1
814 }
815 import MacPrefs
816 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
817 if prefs.searchengine:
818 self.parms["casesens"] = prefs.searchengine.casesens
819 self.parms["wrap"] = prefs.searchengine.wrap
820 self.parms["wholeword"] = prefs.searchengine.wholeword
821
822 def show(self):
823 self.visible = 1
824 if self.w:
825 self.w.wid.ShowWindow()
826 self.w.wid.SelectWindow()
827 self.w.find.edit.select(1)
828 self.w.find.edit.selectall()
829 return
830 self.w = W.Dialog((420, 150), "Find")
831
832 self.w.find = TitledEditText((10, 4, 300, 36), "Search for:")
833 self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:")
834
835 self.w.boxes = W.Group((10, 50, 300, 40))
836 self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive")
837 self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word")
838 self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around")
839
840 self.buttons = [ ("Find", "cmdf", self.find),
841 ("Replace", "cmdr", self.replace),
842 ("Replace all", None, self.replaceall),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000843 ("Don't find", "cmdd", self.dont),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000844 ("Cancel", "cmd.", self.cancel)
845 ]
846 for i in range(len(self.buttons)):
847 bounds = -90, 22 + i * 24, 80, 16
848 title, shortcut, callback = self.buttons[i]
849 self.w[title] = W.Button(bounds, title, callback)
850 if shortcut:
851 self.w.bind(shortcut, self.w[title].push)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000852 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000853 self.w.find.edit.bind("<key>", self.key)
854 self.w.bind("<activate>", self.activate)
855 self.w.bind("<close>", self.close)
856 self.w.open()
857 self.setparms()
858 self.w.find.edit.select(1)
859 self.w.find.edit.selectall()
860 self.checkbuttons()
861
862 def close(self):
863 self.hide()
864 return -1
865
866 def key(self, char, modifiers):
867 self.w.find.edit.key(char, modifiers)
868 self.checkbuttons()
869 return 1
870
871 def activate(self, onoff):
872 if onoff:
873 self.checkbuttons()
874
875 def checkbuttons(self):
876 editor = findeditor(self)
877 if editor:
878 if self.w.find.get():
879 for title, cmd, call in self.buttons[:-2]:
880 self.w[title].enable(1)
881 self.w.setdefaultbutton(self.w["Find"])
882 else:
883 for title, cmd, call in self.buttons[:-2]:
884 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000885 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000886 else:
887 for title, cmd, call in self.buttons[:-2]:
888 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000889 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000890
891 def find(self):
892 self.getparmsfromwindow()
893 if self.findnext():
894 self.hide()
895
896 def replace(self):
897 editor = findeditor(self)
898 if not editor:
899 return
900 if self.visible:
901 self.getparmsfromwindow()
902 text = editor.getselectedtext()
903 find = self.parms["find"]
904 if not self.parms["casesens"]:
905 find = string.lower(find)
906 text = string.lower(text)
907 if text == find:
908 self.hide()
909 editor.insert(self.parms["replace"])
910
911 def replaceall(self):
912 editor = findeditor(self)
913 if not editor:
914 return
915 if self.visible:
916 self.getparmsfromwindow()
917 W.SetCursor("watch")
918 find = self.parms["find"]
919 if not find:
920 return
921 findlen = len(find)
922 replace = self.parms["replace"]
923 replacelen = len(replace)
924 Text = editor.get()
925 if not self.parms["casesens"]:
926 find = string.lower(find)
927 text = string.lower(Text)
928 else:
929 text = Text
930 newtext = ""
931 pos = 0
932 counter = 0
933 while 1:
934 if self.parms["wholeword"]:
935 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000936 match = wholewordRE.search(text, pos)
937 if match:
938 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000939 else:
940 pos = -1
941 else:
942 pos = string.find(text, find, pos)
943 if pos < 0:
944 break
945 counter = counter + 1
946 text = text[:pos] + replace + text[pos + findlen:]
947 Text = Text[:pos] + replace + Text[pos + findlen:]
948 pos = pos + replacelen
949 W.SetCursor("arrow")
950 if counter:
951 self.hide()
952 import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +0000953 from Carbon import Res
Just van Rossumf7f93882001-11-02 19:24:41 +0000954 editor.textchanged()
955 editor.selectionchanged()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000956 editor.ted.WEUseText(Res.Resource(Text))
957 editor.ted.WECalText()
958 editor.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +0000959 editor.GetWindow().InvalWindowRect(editor._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000960 #editor.ted.WEUpdate(self.w.wid.GetWindowPort().visRgn)
961 EasyDialogs.Message("Replaced %d occurrences" % counter)
962
963 def dont(self):
964 self.getparmsfromwindow()
965 self.hide()
966
967 def replacefind(self):
968 self.replace()
969 self.findnext()
970
971 def setfindstring(self):
972 editor = findeditor(self)
973 if not editor:
974 return
975 find = editor.getselectedtext()
976 if not find:
977 return
978 self.parms["find"] = find
979 if self.w:
980 self.w.find.edit.set(self.parms["find"])
981 self.w.find.edit.selectall()
982
983 def findnext(self):
984 editor = findeditor(self)
985 if not editor:
986 return
987 find = self.parms["find"]
988 if not find:
989 return
990 text = editor.get()
991 if not self.parms["casesens"]:
992 find = string.lower(find)
993 text = string.lower(text)
994 selstart, selend = editor.getselection()
995 selstart, selend = min(selstart, selend), max(selstart, selend)
996 if self.parms["wholeword"]:
997 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000998 match = wholewordRE.search(text, selend)
999 if match:
1000 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001001 else:
1002 pos = -1
1003 else:
1004 pos = string.find(text, find, selend)
1005 if pos >= 0:
1006 editor.setselection(pos, pos + len(find))
1007 return 1
1008 elif self.parms["wrap"]:
1009 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001010 match = wholewordRE.search(text, 0)
1011 if match:
1012 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001013 else:
1014 pos = -1
1015 else:
1016 pos = string.find(text, find)
1017 if selstart > pos >= 0:
1018 editor.setselection(pos, pos + len(find))
1019 return 1
1020
1021 def setparms(self):
1022 for key, value in self.parms.items():
1023 try:
1024 self.w[key].set(value)
1025 except KeyError:
1026 self.w.boxes[key].set(value)
1027
1028 def getparmsfromwindow(self):
1029 if not self.w:
1030 return
1031 for key, value in self.parms.items():
1032 try:
1033 value = self.w[key].get()
1034 except KeyError:
1035 value = self.w.boxes[key].get()
1036 self.parms[key] = value
1037
1038 def cancel(self):
1039 self.hide()
1040 self.setparms()
1041
1042 def hide(self):
1043 if self.w:
1044 self.w.wid.HideWindow()
1045 self.visible = 0
1046
1047 def writeprefs(self):
1048 import MacPrefs
1049 self.getparmsfromwindow()
1050 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1051 prefs.searchengine.casesens = self.parms["casesens"]
1052 prefs.searchengine.wrap = self.parms["wrap"]
1053 prefs.searchengine.wholeword = self.parms["wholeword"]
1054 prefs.save()
1055
1056
1057class TitledEditText(W.Group):
1058
1059 def __init__(self, possize, title, text = ""):
1060 W.Group.__init__(self, possize)
1061 self.title = W.TextBox((0, 0, 0, 16), title)
1062 self.edit = W.EditText((0, 16, 0, 0), text)
1063
1064 def set(self, value):
1065 self.edit.set(value)
1066
1067 def get(self):
1068 return self.edit.get()
1069
1070
1071class ClassFinder(W.PopupWidget):
1072
1073 def click(self, point, modifiers):
1074 W.SetCursor("watch")
1075 self.set(self._parentwindow.getclasslist())
1076 W.PopupWidget.click(self, point, modifiers)
1077
1078
1079def getminindent(lines):
1080 indent = -1
1081 for line in lines:
1082 stripped = string.strip(line)
1083 if not stripped or stripped[0] == '#':
1084 continue
1085 if indent < 0 or line[:indent] <> indent * '\t':
1086 indent = 0
1087 for c in line:
1088 if c <> '\t':
1089 break
1090 indent = indent + 1
1091 return indent
1092
1093
1094def getoptionkey():
1095 return not not ord(Evt.GetKeys()[7]) & 0x04
1096
1097
1098def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1099 modname="__main__", profiling=0):
1100 if debugging:
1101 import PyDebugger, bdb
1102 BdbQuit = bdb.BdbQuit
1103 else:
1104 BdbQuit = 'BdbQuitDummyException'
1105 pytext = string.split(pytext, '\r')
1106 pytext = string.join(pytext, '\n') + '\n'
1107 W.SetCursor("watch")
1108 globals['__name__'] = modname
1109 globals['__file__'] = filename
1110 sys.argv = [filename]
1111 try:
1112 code = compile(pytext, filename, "exec")
1113 except:
1114 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1115 # special. That's wrong because THIS case is special (could be literal
1116 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1117 # in imported module!!!
1118 tracebackwindow.traceback(1, filename)
1119 return
1120 try:
1121 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001122 if haveThreading:
1123 lock = Wthreading.Lock()
1124 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001125 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001126 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001127 else:
1128 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001129 elif not haveThreading:
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001130 MacOS.EnableAppswitch(0)
1131 try:
1132 if profiling:
1133 import profile, ProfileBrowser
1134 p = profile.Profile()
1135 p.set_cmd(filename)
1136 try:
1137 p.runctx(code, globals, locals)
1138 finally:
1139 import pstats
1140
1141 stats = pstats.Stats(p)
1142 ProfileBrowser.ProfileBrowser(stats)
1143 else:
1144 exec code in globals, locals
1145 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001146 if not haveThreading:
Just van Rossum73efed22000-04-09 19:45:22 +00001147 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001148 except W.AlertError, detail:
1149 raise W.AlertError, detail
1150 except (KeyboardInterrupt, BdbQuit):
1151 pass
Just van Rossumf7f93882001-11-02 19:24:41 +00001152 except SystemExit, arg:
1153 if arg.code:
1154 sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001155 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001156 if haveThreading:
1157 import continuation
1158 lock = Wthreading.Lock()
1159 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001160 if debugging:
1161 sys.settrace(None)
1162 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1163 return
1164 else:
1165 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001166 if haveThreading:
1167 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001168 if debugging:
1169 sys.settrace(None)
1170 PyDebugger.stop()
1171
1172
Just van Rossum3eec7622001-07-10 19:25:40 +00001173_identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
Jack Jansen9ad27522001-02-21 13:54:31 +00001174
1175def identifieRE_match(str):
1176 match = _identifieRE.match(str)
1177 if not match:
1178 return -1
1179 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001180
1181def _filename_as_modname(fname):
1182 if fname[-3:] == '.py':
1183 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001184 match = _identifieRE.match(modname)
1185 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001186 return string.join(string.split(modname, '.'), '_')
1187
1188def findeditor(topwindow, fromtop = 0):
1189 wid = Win.FrontWindow()
1190 if not fromtop:
1191 if topwindow.w and wid == topwindow.w.wid:
1192 wid = topwindow.w.wid.GetNextWindow()
1193 if not wid:
1194 return
1195 app = W.getapplication()
1196 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1197 window = W.getapplication()._windows[wid]
1198 else:
1199 return
1200 if not isinstance(window, Editor):
1201 return
1202 return window.editgroup.editor
1203
1204
1205class _EditorDefaultSettings:
1206
1207 def __init__(self):
1208 self.template = "%s, %d point"
1209 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1210 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001211 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001212 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1213
1214 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1215 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1216 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1217 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1218 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1219
1220 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1221 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1222 self.w.setdefaultbutton(self.w.okbutton)
1223 self.w.bind('cmd.', self.w.cancelbutton.push)
1224 self.w.open()
1225
1226 def picksize(self):
1227 app = W.getapplication()
1228 editor = findeditor(self)
1229 if editor is not None:
1230 width, height = editor._parentwindow._bounds[2:]
1231 self.w.xsize.set(`width`)
1232 self.w.ysize.set(`height`)
1233 else:
1234 raise W.AlertError, "No edit window found"
1235
1236 def dofont(self):
1237 import FontSettings
1238 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1239 if settings:
1240 self.fontsettings, self.tabsettings = settings
1241 sys.exc_traceback = None
1242 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1243
1244 def close(self):
1245 self.w.close()
1246 del self.w
1247
1248 def cancel(self):
1249 self.close()
1250
1251 def ok(self):
1252 try:
1253 width = string.atoi(self.w.xsize.get())
1254 except:
1255 self.w.xsize.select(1)
1256 self.w.xsize.selectall()
1257 raise W.AlertError, "Bad number for window width"
1258 try:
1259 height = string.atoi(self.w.ysize.get())
1260 except:
1261 self.w.ysize.select(1)
1262 self.w.ysize.selectall()
1263 raise W.AlertError, "Bad number for window height"
1264 self.windowsize = width, height
1265 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1266 self.close()
1267
1268def geteditorprefs():
1269 import MacPrefs
1270 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1271 try:
1272 fontsettings = prefs.pyedit.fontsettings
1273 tabsettings = prefs.pyedit.tabsettings
1274 windowsize = prefs.pyedit.windowsize
1275 except:
Just van Rossumf7f93882001-11-02 19:24:41 +00001276 fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001277 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1278 windowsize = prefs.pyedit.windowsize = (500, 250)
1279 sys.exc_traceback = None
1280 return fontsettings, tabsettings, windowsize
1281
1282def seteditorprefs(fontsettings, tabsettings, windowsize):
1283 import MacPrefs
1284 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1285 prefs.pyedit.fontsettings = fontsettings
1286 prefs.pyedit.tabsettings = tabsettings
1287 prefs.pyedit.windowsize = windowsize
1288 prefs.save()
1289
1290_defaultSettingsEditor = None
1291
1292def EditorDefaultSettings():
1293 global _defaultSettingsEditor
1294 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1295 _defaultSettingsEditor = _EditorDefaultSettings()
1296 else:
1297 _defaultSettingsEditor.w.select()
1298
1299def resolvealiases(path):
1300 try:
1301 return macfs.ResolveAliasFile(path)[0].as_pathname()
1302 except (macfs.error, ValueError), (error, str):
1303 if error <> -120:
1304 raise
1305 dir, file = os.path.split(path)
1306 return os.path.join(resolvealiases(dir), file)
1307
1308searchengine = SearchEngine()
1309tracebackwindow = Wtraceback.TraceBack()