blob: 7740dfec296190632fd02ddf2027266cb7717bb1 [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 Rossum5f740071999-10-30 11:44:25 +000099 self.editgroup.editor.changed = 1
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):
177 topbarheight = 24
178 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))
200 self.infotext = W.TextBox((175, 6, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000))
Just van Rossum73efed22000-04-09 19:45:22 +0000201 self.runbutton = W.Button((5, 4, 80, 16), runButtonLabels[0], self.run)
202 self.runselbutton = W.Button((90, 4, 80, 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
250 self.editgroup.editor.selchanged = 1
251
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 Rossum40f9b7b1999-01-30 22:39:17 +0000255 self.editgroup.editor.selchanged = 1
256
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 Rossum3af507d1999-04-22 22:23:46 +0000317 self.editgroup.editor.selchanged = 1 # 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)
636 if modname:
637 if subname == "__init__":
Just van Rossum2aaeb521999-02-05 21:58:25 +0000638 # strip trailing period
639 modname = modname[:-1]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000640 else:
Just van Rossum2aaeb521999-02-05 21:58:25 +0000641 modname = modname + subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000642 else:
643 modname = subname
644 if sys.modules.has_key(modname):
645 globals = sys.modules[modname].__dict__
646 self.globals = {}
647 else:
648 globals = self.globals
Just van Rossum73efed22000-04-09 19:45:22 +0000649 modname = subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000650 else:
651 file = '<%s>' % self.title
652 globals = self.globals
653 modname = file
654 return globals, file, modname
655
656 def write(self, stuff):
657 """for use as stdout"""
658 self._buf = self._buf + stuff
659 if '\n' in self._buf:
660 self.flush()
661
662 def flush(self):
663 stuff = string.split(self._buf, '\n')
664 stuff = string.join(stuff, '\r')
665 end = self.editgroup.editor.ted.WEGetTextLength()
666 self.editgroup.editor.ted.WESetSelection(end, end)
667 self.editgroup.editor.ted.WEInsert(stuff, None, None)
668 self.editgroup.editor.updatescrollbars()
669 self._buf = ""
670 # ? optional:
671 #self.wid.SelectWindow()
672
673 def getclasslist(self):
674 from string import find, strip
Just van Rossum24073ea1999-12-23 15:46:57 +0000675 methodRE = re.compile(r"\r[ \t]+def ")
676 findMethod = methodRE.search
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000677 editor = self.editgroup.editor
678 text = editor.get()
679 list = []
680 append = list.append
681 functag = "func"
682 classtag = "class"
683 methodtag = "method"
684 pos = -1
685 if text[:4] == 'def ':
686 append((pos + 4, functag))
687 pos = 4
688 while 1:
689 pos = find(text, '\rdef ', pos + 1)
690 if pos < 0:
691 break
692 append((pos + 5, functag))
693 pos = -1
694 if text[:6] == 'class ':
695 append((pos + 6, classtag))
696 pos = 6
697 while 1:
698 pos = find(text, '\rclass ', pos + 1)
699 if pos < 0:
700 break
701 append((pos + 7, classtag))
702 pos = 0
703 while 1:
Just van Rossum24073ea1999-12-23 15:46:57 +0000704 m = findMethod(text, pos + 1)
705 if m is None:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000706 break
Just van Rossum24073ea1999-12-23 15:46:57 +0000707 pos = m.regs[0][0]
708 #pos = find(text, '\r\tdef ', pos + 1)
709 append((m.regs[0][1], methodtag))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000710 list.sort()
711 classlist = []
712 methodlistappend = None
713 offsetToLine = editor.ted.WEOffsetToLine
714 getLineRange = editor.ted.WEGetLineRange
715 append = classlist.append
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000716 for pos, tag in list:
717 lineno = offsetToLine(pos)
718 lineStart, lineEnd = getLineRange(lineno)
719 line = strip(text[pos:lineEnd])
720 line = line[:identifieRE_match(line)]
721 if tag is functag:
722 append(("def " + line, lineno + 1))
723 methodlistappend = None
724 elif tag is classtag:
725 append(["class " + line])
726 methodlistappend = classlist[-1].append
727 elif methodlistappend and tag is methodtag:
728 methodlistappend(("def " + line, lineno + 1))
729 return classlist
730
731 def popselectline(self, lineno):
732 self.editgroup.editor.selectline(lineno - 1)
733
734 def selectline(self, lineno, charoffset = 0):
735 self.editgroup.editor.selectline(lineno - 1, charoffset)
736
Just van Rossum12710051999-02-27 17:18:30 +0000737class _saveoptions:
738
739 def __init__(self, creator):
740 self.rv = None
741 self.w = w = W.ModalDialog((240, 140), 'Save options')
742 radiobuttons = []
743 w.label = W.TextBox((8, 8, 80, 18), "File creator:")
Just van Rossum3af507d1999-04-22 22:23:46 +0000744 w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit)
745 w.interp_radio = W.RadioButton((8, 42, 160, 18), "Python Interpreter", radiobuttons, self.interp_hit)
Just van Rossum12710051999-02-27 17:18:30 +0000746 w.other_radio = W.RadioButton((8, 62, 50, 18), "Other:", radiobuttons)
747 w.other_creator = W.EditText((62, 62, 40, 20), creator, self.otherselect)
748 w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit)
749 w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit)
750 w.setdefaultbutton(w.okbutton)
751 if creator == 'Pyth':
752 w.interp_radio.set(1)
Just van Rossum3af507d1999-04-22 22:23:46 +0000753 elif creator == W._signature:
Just van Rossum12710051999-02-27 17:18:30 +0000754 w.ide_radio.set(1)
755 else:
756 w.other_radio.set(1)
757 w.bind("cmd.", w.cancelbutton.push)
758 w.open()
759
760 def ide_hit(self):
Just van Rossum3af507d1999-04-22 22:23:46 +0000761 self.w.other_creator.set(W._signature)
Just van Rossum12710051999-02-27 17:18:30 +0000762
763 def interp_hit(self):
764 self.w.other_creator.set("Pyth")
765
766 def otherselect(self, *args):
767 sel_from, sel_to = self.w.other_creator.getselection()
768 creator = self.w.other_creator.get()[:4]
769 creator = creator + " " * (4 - len(creator))
770 self.w.other_creator.set(creator)
771 self.w.other_creator.setselection(sel_from, sel_to)
772 self.w.other_radio.set(1)
773
774 def cancelbuttonhit(self):
775 self.w.close()
776
777 def okbuttonhit(self):
778 self.rv = self.w.other_creator.get()[:4]
779 self.w.close()
780
781
782def SaveOptions(creator):
783 s = _saveoptions(creator)
784 return s.rv
785
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000786
787def _escape(where, what) :
788 return string.join(string.split(where, what), '\\' + what)
789
790def _makewholewordpattern(word):
791 # first, escape special regex chars
Just van Rossum3eec7622001-07-10 19:25:40 +0000792 for esc in "\\[]()|.*^+$?":
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000793 word = _escape(word, esc)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000794 notwordcharspat = '[^' + _wordchars + ']'
Jack Jansen9ad27522001-02-21 13:54:31 +0000795 pattern = '(' + word + ')'
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000796 if word[0] in _wordchars:
797 pattern = notwordcharspat + pattern
798 if word[-1] in _wordchars:
799 pattern = pattern + notwordcharspat
Jack Jansen9ad27522001-02-21 13:54:31 +0000800 return re.compile(pattern)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000801
802class SearchEngine:
803
804 def __init__(self):
805 self.visible = 0
806 self.w = None
807 self.parms = { "find": "",
808 "replace": "",
809 "wrap": 1,
810 "casesens": 1,
811 "wholeword": 1
812 }
813 import MacPrefs
814 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
815 if prefs.searchengine:
816 self.parms["casesens"] = prefs.searchengine.casesens
817 self.parms["wrap"] = prefs.searchengine.wrap
818 self.parms["wholeword"] = prefs.searchengine.wholeword
819
820 def show(self):
821 self.visible = 1
822 if self.w:
823 self.w.wid.ShowWindow()
824 self.w.wid.SelectWindow()
825 self.w.find.edit.select(1)
826 self.w.find.edit.selectall()
827 return
828 self.w = W.Dialog((420, 150), "Find")
829
830 self.w.find = TitledEditText((10, 4, 300, 36), "Search for:")
831 self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:")
832
833 self.w.boxes = W.Group((10, 50, 300, 40))
834 self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive")
835 self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word")
836 self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around")
837
838 self.buttons = [ ("Find", "cmdf", self.find),
839 ("Replace", "cmdr", self.replace),
840 ("Replace all", None, self.replaceall),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000841 ("Don't find", "cmdd", self.dont),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000842 ("Cancel", "cmd.", self.cancel)
843 ]
844 for i in range(len(self.buttons)):
845 bounds = -90, 22 + i * 24, 80, 16
846 title, shortcut, callback = self.buttons[i]
847 self.w[title] = W.Button(bounds, title, callback)
848 if shortcut:
849 self.w.bind(shortcut, self.w[title].push)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000850 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000851 self.w.find.edit.bind("<key>", self.key)
852 self.w.bind("<activate>", self.activate)
853 self.w.bind("<close>", self.close)
854 self.w.open()
855 self.setparms()
856 self.w.find.edit.select(1)
857 self.w.find.edit.selectall()
858 self.checkbuttons()
859
860 def close(self):
861 self.hide()
862 return -1
863
864 def key(self, char, modifiers):
865 self.w.find.edit.key(char, modifiers)
866 self.checkbuttons()
867 return 1
868
869 def activate(self, onoff):
870 if onoff:
871 self.checkbuttons()
872
873 def checkbuttons(self):
874 editor = findeditor(self)
875 if editor:
876 if self.w.find.get():
877 for title, cmd, call in self.buttons[:-2]:
878 self.w[title].enable(1)
879 self.w.setdefaultbutton(self.w["Find"])
880 else:
881 for title, cmd, call in self.buttons[:-2]:
882 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000883 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000884 else:
885 for title, cmd, call in self.buttons[:-2]:
886 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000887 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000888
889 def find(self):
890 self.getparmsfromwindow()
891 if self.findnext():
892 self.hide()
893
894 def replace(self):
895 editor = findeditor(self)
896 if not editor:
897 return
898 if self.visible:
899 self.getparmsfromwindow()
900 text = editor.getselectedtext()
901 find = self.parms["find"]
902 if not self.parms["casesens"]:
903 find = string.lower(find)
904 text = string.lower(text)
905 if text == find:
906 self.hide()
907 editor.insert(self.parms["replace"])
908
909 def replaceall(self):
910 editor = findeditor(self)
911 if not editor:
912 return
913 if self.visible:
914 self.getparmsfromwindow()
915 W.SetCursor("watch")
916 find = self.parms["find"]
917 if not find:
918 return
919 findlen = len(find)
920 replace = self.parms["replace"]
921 replacelen = len(replace)
922 Text = editor.get()
923 if not self.parms["casesens"]:
924 find = string.lower(find)
925 text = string.lower(Text)
926 else:
927 text = Text
928 newtext = ""
929 pos = 0
930 counter = 0
931 while 1:
932 if self.parms["wholeword"]:
933 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000934 match = wholewordRE.search(text, pos)
935 if match:
936 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000937 else:
938 pos = -1
939 else:
940 pos = string.find(text, find, pos)
941 if pos < 0:
942 break
943 counter = counter + 1
944 text = text[:pos] + replace + text[pos + findlen:]
945 Text = Text[:pos] + replace + Text[pos + findlen:]
946 pos = pos + replacelen
947 W.SetCursor("arrow")
948 if counter:
949 self.hide()
950 import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +0000951 from Carbon import Res
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000952 editor.changed = 1
953 editor.selchanged = 1
954 editor.ted.WEUseText(Res.Resource(Text))
955 editor.ted.WECalText()
956 editor.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +0000957 editor.GetWindow().InvalWindowRect(editor._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000958 #editor.ted.WEUpdate(self.w.wid.GetWindowPort().visRgn)
959 EasyDialogs.Message("Replaced %d occurrences" % counter)
960
961 def dont(self):
962 self.getparmsfromwindow()
963 self.hide()
964
965 def replacefind(self):
966 self.replace()
967 self.findnext()
968
969 def setfindstring(self):
970 editor = findeditor(self)
971 if not editor:
972 return
973 find = editor.getselectedtext()
974 if not find:
975 return
976 self.parms["find"] = find
977 if self.w:
978 self.w.find.edit.set(self.parms["find"])
979 self.w.find.edit.selectall()
980
981 def findnext(self):
982 editor = findeditor(self)
983 if not editor:
984 return
985 find = self.parms["find"]
986 if not find:
987 return
988 text = editor.get()
989 if not self.parms["casesens"]:
990 find = string.lower(find)
991 text = string.lower(text)
992 selstart, selend = editor.getselection()
993 selstart, selend = min(selstart, selend), max(selstart, selend)
994 if self.parms["wholeword"]:
995 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000996 match = wholewordRE.search(text, selend)
997 if match:
998 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000999 else:
1000 pos = -1
1001 else:
1002 pos = string.find(text, find, selend)
1003 if pos >= 0:
1004 editor.setselection(pos, pos + len(find))
1005 return 1
1006 elif self.parms["wrap"]:
1007 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001008 match = wholewordRE.search(text, 0)
1009 if match:
1010 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001011 else:
1012 pos = -1
1013 else:
1014 pos = string.find(text, find)
1015 if selstart > pos >= 0:
1016 editor.setselection(pos, pos + len(find))
1017 return 1
1018
1019 def setparms(self):
1020 for key, value in self.parms.items():
1021 try:
1022 self.w[key].set(value)
1023 except KeyError:
1024 self.w.boxes[key].set(value)
1025
1026 def getparmsfromwindow(self):
1027 if not self.w:
1028 return
1029 for key, value in self.parms.items():
1030 try:
1031 value = self.w[key].get()
1032 except KeyError:
1033 value = self.w.boxes[key].get()
1034 self.parms[key] = value
1035
1036 def cancel(self):
1037 self.hide()
1038 self.setparms()
1039
1040 def hide(self):
1041 if self.w:
1042 self.w.wid.HideWindow()
1043 self.visible = 0
1044
1045 def writeprefs(self):
1046 import MacPrefs
1047 self.getparmsfromwindow()
1048 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1049 prefs.searchengine.casesens = self.parms["casesens"]
1050 prefs.searchengine.wrap = self.parms["wrap"]
1051 prefs.searchengine.wholeword = self.parms["wholeword"]
1052 prefs.save()
1053
1054
1055class TitledEditText(W.Group):
1056
1057 def __init__(self, possize, title, text = ""):
1058 W.Group.__init__(self, possize)
1059 self.title = W.TextBox((0, 0, 0, 16), title)
1060 self.edit = W.EditText((0, 16, 0, 0), text)
1061
1062 def set(self, value):
1063 self.edit.set(value)
1064
1065 def get(self):
1066 return self.edit.get()
1067
1068
1069class ClassFinder(W.PopupWidget):
1070
1071 def click(self, point, modifiers):
1072 W.SetCursor("watch")
1073 self.set(self._parentwindow.getclasslist())
1074 W.PopupWidget.click(self, point, modifiers)
1075
1076
1077def getminindent(lines):
1078 indent = -1
1079 for line in lines:
1080 stripped = string.strip(line)
1081 if not stripped or stripped[0] == '#':
1082 continue
1083 if indent < 0 or line[:indent] <> indent * '\t':
1084 indent = 0
1085 for c in line:
1086 if c <> '\t':
1087 break
1088 indent = indent + 1
1089 return indent
1090
1091
1092def getoptionkey():
1093 return not not ord(Evt.GetKeys()[7]) & 0x04
1094
1095
1096def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1097 modname="__main__", profiling=0):
1098 if debugging:
1099 import PyDebugger, bdb
1100 BdbQuit = bdb.BdbQuit
1101 else:
1102 BdbQuit = 'BdbQuitDummyException'
1103 pytext = string.split(pytext, '\r')
1104 pytext = string.join(pytext, '\n') + '\n'
1105 W.SetCursor("watch")
1106 globals['__name__'] = modname
1107 globals['__file__'] = filename
1108 sys.argv = [filename]
1109 try:
1110 code = compile(pytext, filename, "exec")
1111 except:
1112 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1113 # special. That's wrong because THIS case is special (could be literal
1114 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1115 # in imported module!!!
1116 tracebackwindow.traceback(1, filename)
1117 return
1118 try:
1119 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001120 if haveThreading:
1121 lock = Wthreading.Lock()
1122 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001123 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001124 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001125 else:
1126 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001127 elif not haveThreading:
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001128 MacOS.EnableAppswitch(0)
1129 try:
1130 if profiling:
1131 import profile, ProfileBrowser
1132 p = profile.Profile()
1133 p.set_cmd(filename)
1134 try:
1135 p.runctx(code, globals, locals)
1136 finally:
1137 import pstats
1138
1139 stats = pstats.Stats(p)
1140 ProfileBrowser.ProfileBrowser(stats)
1141 else:
1142 exec code in globals, locals
1143 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001144 if not haveThreading:
Just van Rossum73efed22000-04-09 19:45:22 +00001145 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001146 except W.AlertError, detail:
1147 raise W.AlertError, detail
1148 except (KeyboardInterrupt, BdbQuit):
1149 pass
1150 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001151 if haveThreading:
1152 import continuation
1153 lock = Wthreading.Lock()
1154 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001155 if debugging:
1156 sys.settrace(None)
1157 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1158 return
1159 else:
1160 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001161 if haveThreading:
1162 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001163 if debugging:
1164 sys.settrace(None)
1165 PyDebugger.stop()
1166
1167
Just van Rossum3eec7622001-07-10 19:25:40 +00001168_identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
Jack Jansen9ad27522001-02-21 13:54:31 +00001169
1170def identifieRE_match(str):
1171 match = _identifieRE.match(str)
1172 if not match:
1173 return -1
1174 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001175
1176def _filename_as_modname(fname):
1177 if fname[-3:] == '.py':
1178 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001179 match = _identifieRE.match(modname)
1180 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001181 return string.join(string.split(modname, '.'), '_')
1182
1183def findeditor(topwindow, fromtop = 0):
1184 wid = Win.FrontWindow()
1185 if not fromtop:
1186 if topwindow.w and wid == topwindow.w.wid:
1187 wid = topwindow.w.wid.GetNextWindow()
1188 if not wid:
1189 return
1190 app = W.getapplication()
1191 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1192 window = W.getapplication()._windows[wid]
1193 else:
1194 return
1195 if not isinstance(window, Editor):
1196 return
1197 return window.editgroup.editor
1198
1199
1200class _EditorDefaultSettings:
1201
1202 def __init__(self):
1203 self.template = "%s, %d point"
1204 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1205 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001206 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001207 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1208
1209 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1210 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1211 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1212 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1213 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1214
1215 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1216 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1217 self.w.setdefaultbutton(self.w.okbutton)
1218 self.w.bind('cmd.', self.w.cancelbutton.push)
1219 self.w.open()
1220
1221 def picksize(self):
1222 app = W.getapplication()
1223 editor = findeditor(self)
1224 if editor is not None:
1225 width, height = editor._parentwindow._bounds[2:]
1226 self.w.xsize.set(`width`)
1227 self.w.ysize.set(`height`)
1228 else:
1229 raise W.AlertError, "No edit window found"
1230
1231 def dofont(self):
1232 import FontSettings
1233 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1234 if settings:
1235 self.fontsettings, self.tabsettings = settings
1236 sys.exc_traceback = None
1237 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1238
1239 def close(self):
1240 self.w.close()
1241 del self.w
1242
1243 def cancel(self):
1244 self.close()
1245
1246 def ok(self):
1247 try:
1248 width = string.atoi(self.w.xsize.get())
1249 except:
1250 self.w.xsize.select(1)
1251 self.w.xsize.selectall()
1252 raise W.AlertError, "Bad number for window width"
1253 try:
1254 height = string.atoi(self.w.ysize.get())
1255 except:
1256 self.w.ysize.select(1)
1257 self.w.ysize.selectall()
1258 raise W.AlertError, "Bad number for window height"
1259 self.windowsize = width, height
1260 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1261 self.close()
1262
1263def geteditorprefs():
1264 import MacPrefs
1265 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1266 try:
1267 fontsettings = prefs.pyedit.fontsettings
1268 tabsettings = prefs.pyedit.tabsettings
1269 windowsize = prefs.pyedit.windowsize
1270 except:
1271 fontsettings = prefs.pyedit.fontsettings = ("Python-Sans", 0, 9, (0, 0, 0))
1272 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1273 windowsize = prefs.pyedit.windowsize = (500, 250)
1274 sys.exc_traceback = None
1275 return fontsettings, tabsettings, windowsize
1276
1277def seteditorprefs(fontsettings, tabsettings, windowsize):
1278 import MacPrefs
1279 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1280 prefs.pyedit.fontsettings = fontsettings
1281 prefs.pyedit.tabsettings = tabsettings
1282 prefs.pyedit.windowsize = windowsize
1283 prefs.save()
1284
1285_defaultSettingsEditor = None
1286
1287def EditorDefaultSettings():
1288 global _defaultSettingsEditor
1289 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1290 _defaultSettingsEditor = _EditorDefaultSettings()
1291 else:
1292 _defaultSettingsEditor.w.select()
1293
1294def resolvealiases(path):
1295 try:
1296 return macfs.ResolveAliasFile(path)[0].as_pathname()
1297 except (macfs.error, ValueError), (error, str):
1298 if error <> -120:
1299 raise
1300 dir, file = os.path.split(path)
1301 return os.path.join(resolvealiases(dir), file)
1302
1303searchengine = SearchEngine()
1304tracebackwindow = Wtraceback.TraceBack()