blob: 07b7277190f01934cbbe287fd4678f3a3ae27046 [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 Rossum40144012002-02-04 12:52:44 +000020if hasattr(Win, "FrontNonFloatingWindow"):
21 MyFrontWindow = Win.FrontNonFloatingWindow
22else:
23 MyFrontWindow = Win.FrontWindow
24
25
Just van Rossum73efed22000-04-09 19:45:22 +000026try:
Just van Rossum0f2fd162000-10-20 06:36:30 +000027 import Wthreading
Just van Rossum73efed22000-04-09 19:45:22 +000028except ImportError:
Just van Rossum0f2fd162000-10-20 06:36:30 +000029 haveThreading = 0
30else:
31 haveThreading = Wthreading.haveThreading
Just van Rossum73efed22000-04-09 19:45:22 +000032
Just van Rossum40f9b7b1999-01-30 22:39:17 +000033_scriptuntitledcounter = 1
Fred Drake79e75e12001-07-20 19:05:50 +000034_wordchars = string.ascii_letters + string.digits + "_"
Just van Rossum40f9b7b1999-01-30 22:39:17 +000035
36
Just van Rossum73efed22000-04-09 19:45:22 +000037runButtonLabels = ["Run all", "Stop!"]
38runSelButtonLabels = ["Run selection", "Pause!", "Resume"]
39
40
Just van Rossum40f9b7b1999-01-30 22:39:17 +000041class Editor(W.Window):
42
43 def __init__(self, path = "", title = ""):
44 defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs()
45 global _scriptuntitledcounter
46 if not path:
47 if title:
48 self.title = title
49 else:
50 self.title = "Untitled Script " + `_scriptuntitledcounter`
51 _scriptuntitledcounter = _scriptuntitledcounter + 1
52 text = ""
53 self._creator = W._signature
Jack Jansen9a389472002-03-29 21:26:04 +000054 self._eoln = os.linesep
Just van Rossum40f9b7b1999-01-30 22:39:17 +000055 elif os.path.exists(path):
56 path = resolvealiases(path)
57 dir, name = os.path.split(path)
58 self.title = name
59 f = open(path, "rb")
60 text = f.read()
61 f.close()
62 fss = macfs.FSSpec(path)
63 self._creator, filetype = fss.GetCreatorType()
64 else:
65 raise IOError, "file '%s' does not exist" % path
66 self.path = path
67
Just van Rossumc7ba0801999-05-21 21:42:27 +000068 if '\n' in text:
69 import EasyDialogs
70 if string.find(text, '\r\n') >= 0:
Jack Jansen9a389472002-03-29 21:26:04 +000071 self._eoln = '\r\n'
Just van Rossumc7ba0801999-05-21 21:42:27 +000072 else:
Jack Jansen9a389472002-03-29 21:26:04 +000073 self._eoln = '\n'
74 text = string.replace(text, self._eoln, '\r')
75 change = 0
Just van Rossumc7ba0801999-05-21 21:42:27 +000076 else:
77 change = 0
Jack Jansen9a389472002-03-29 21:26:04 +000078 self._eoln = '\r'
Just van Rossumc7ba0801999-05-21 21:42:27 +000079
Just van Rossum40f9b7b1999-01-30 22:39:17 +000080 self.settings = {}
81 if self.path:
82 self.readwindowsettings()
83 if self.settings.has_key("windowbounds"):
84 bounds = self.settings["windowbounds"]
85 else:
86 bounds = defaultwindowsize
87 if self.settings.has_key("fontsettings"):
88 self.fontsettings = self.settings["fontsettings"]
89 else:
90 self.fontsettings = defaultfontsettings
91 if self.settings.has_key("tabsize"):
92 try:
93 self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"]
94 except:
95 self.tabsettings = defaulttabsettings
96 else:
97 self.tabsettings = defaulttabsettings
Just van Rossum40f9b7b1999-01-30 22:39:17 +000098
Just van Rossumc7ba0801999-05-21 21:42:27 +000099 W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000100 self.setupwidgets(text)
Just van Rossumc7ba0801999-05-21 21:42:27 +0000101 if change > 0:
Just van Rossumf7f93882001-11-02 19:24:41 +0000102 self.editgroup.editor.textchanged()
Just van Rossumc7ba0801999-05-21 21:42:27 +0000103
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000104 if self.settings.has_key("selection"):
105 selstart, selend = self.settings["selection"]
106 self.setselection(selstart, selend)
107 self.open()
108 self.setinfotext()
109 self.globals = {}
110 self._buf = "" # for write method
111 self.debugging = 0
112 self.profiling = 0
113 if self.settings.has_key("run_as_main"):
114 self.run_as_main = self.settings["run_as_main"]
115 else:
116 self.run_as_main = 0
Just van Rossum0f2fd162000-10-20 06:36:30 +0000117 if self.settings.has_key("run_with_interpreter"):
118 self.run_with_interpreter = self.settings["run_with_interpreter"]
119 else:
120 self.run_with_interpreter = 0
Just van Rossum73efed22000-04-09 19:45:22 +0000121 self._threadstate = (0, 0)
122 self._thread = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000123
124 def readwindowsettings(self):
125 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000126 resref = Res.FSpOpenResFile(self.path, 1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000127 except Res.Error:
128 return
129 try:
130 Res.UseResFile(resref)
131 data = Res.Get1Resource('PyWS', 128)
132 self.settings = marshal.loads(data.data)
133 except:
134 pass
135 Res.CloseResFile(resref)
136
137 def writewindowsettings(self):
138 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000139 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000140 except Res.Error:
Jack Jansen64aa1e22001-01-29 15:19:17 +0000141 Res.FSpCreateResFile(self.path, self._creator, 'TEXT', MACFS.smAllScripts)
Jack Jansend13c3852000-06-20 21:59:25 +0000142 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000143 try:
144 data = Res.Resource(marshal.dumps(self.settings))
145 Res.UseResFile(resref)
146 try:
147 temp = Res.Get1Resource('PyWS', 128)
148 temp.RemoveResource()
149 except Res.Error:
150 pass
151 data.AddResource('PyWS', 128, "window settings")
152 finally:
153 Res.UpdateResFile(resref)
154 Res.CloseResFile(resref)
155
156 def getsettings(self):
157 self.settings = {}
158 self.settings["windowbounds"] = self.getbounds()
159 self.settings["selection"] = self.getselection()
160 self.settings["fontsettings"] = self.editgroup.editor.getfontsettings()
161 self.settings["tabsize"] = self.editgroup.editor.gettabsettings()
162 self.settings["run_as_main"] = self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000163 self.settings["run_with_interpreter"] = self.run_with_interpreter
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000164
165 def get(self):
166 return self.editgroup.editor.get()
167
168 def getselection(self):
169 return self.editgroup.editor.ted.WEGetSelection()
170
171 def setselection(self, selstart, selend):
172 self.editgroup.editor.setselection(selstart, selend)
173
174 def getfilename(self):
175 if self.path:
176 return self.path
177 return '<%s>' % self.title
178
179 def setupwidgets(self, text):
Just van Rossumf376ef02001-11-18 14:12:43 +0000180 topbarheight = 24
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000181 popfieldwidth = 80
182 self.lastlineno = None
183
184 # make an editor
185 self.editgroup = W.Group((0, topbarheight + 1, 0, 0))
186 editor = W.PyEditor((0, 0, -15,-15), text,
187 fontsettings = self.fontsettings,
188 tabsettings = self.tabsettings,
189 file = self.getfilename())
190
191 # make the widgets
192 self.popfield = ClassFinder((popfieldwidth - 17, -15, 16, 16), [], self.popselectline)
193 self.linefield = W.EditText((-1, -15, popfieldwidth - 15, 16), inset = (6, 1))
194 self.editgroup._barx = W.Scrollbar((popfieldwidth - 2, -15, -14, 16), editor.hscroll, max = 32767)
195 self.editgroup._bary = W.Scrollbar((-15, 14, 16, -14), editor.vscroll, max = 32767)
196 self.editgroup.editor = editor # add editor *after* scrollbars
197
198 self.editgroup.optionsmenu = W.PopupMenu((-15, -1, 16, 16), [])
199 self.editgroup.optionsmenu.bind('<click>', self.makeoptionsmenu)
200
201 self.bevelbox = W.BevelBox((0, 0, 0, topbarheight))
202 self.hline = W.HorizontalLine((0, topbarheight, 0, 0))
Just van Rossumf376ef02001-11-18 14:12:43 +0000203 self.infotext = W.TextBox((175, 6, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000))
204 self.runbutton = W.BevelButton((6, 4, 80, 16), runButtonLabels[0], self.run)
205 self.runselbutton = W.BevelButton((90, 4, 80, 16), runSelButtonLabels[0], self.runselection)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000206
207 # bind some keys
208 editor.bind("cmdr", self.runbutton.push)
209 editor.bind("enter", self.runselbutton.push)
210 editor.bind("cmdj", self.domenu_gotoline)
211 editor.bind("cmdd", self.domenu_toggledebugger)
212 editor.bind("<idle>", self.updateselection)
213
214 editor.bind("cmde", searchengine.setfindstring)
215 editor.bind("cmdf", searchengine.show)
216 editor.bind("cmdg", searchengine.findnext)
217 editor.bind("cmdshiftr", searchengine.replace)
218 editor.bind("cmdt", searchengine.replacefind)
219
220 self.linefield.bind("return", self.dolinefield)
221 self.linefield.bind("enter", self.dolinefield)
222 self.linefield.bind("tab", self.dolinefield)
223
224 # intercept clicks
225 editor.bind("<click>", self.clickeditor)
226 self.linefield.bind("<click>", self.clicklinefield)
227
228 def makeoptionsmenu(self):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000229 menuitems = [('Font settings\xc9', self.domenu_fontsettings),
230 ("Save options\xc9", self.domenu_options),
Just van Rossum12710051999-02-27 17:18:30 +0000231 '-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000232 ('\0' + chr(self.run_as_main) + 'Run as __main__', self.domenu_toggle_run_as_main),
Just van Rossum0f2fd162000-10-20 06:36:30 +0000233 #('\0' + chr(self.run_with_interpreter) + 'Run with Interpreter', self.domenu_toggle_run_with_interpreter),
234 #'-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000235 ('Modularize', self.domenu_modularize),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000236 ('Browse namespace\xc9', self.domenu_browsenamespace),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000237 '-']
238 if self.profiling:
239 menuitems = menuitems + [('Disable profiler', self.domenu_toggleprofiler)]
240 else:
241 menuitems = menuitems + [('Enable profiler', self.domenu_toggleprofiler)]
242 if self.editgroup.editor._debugger:
243 menuitems = menuitems + [('Disable debugger', self.domenu_toggledebugger),
244 ('Clear breakpoints', self.domenu_clearbreakpoints),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000245 ('Edit breakpoints\xc9', self.domenu_editbreakpoints)]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000246 else:
247 menuitems = menuitems + [('Enable debugger', self.domenu_toggledebugger)]
248 self.editgroup.optionsmenu.set(menuitems)
249
250 def domenu_toggle_run_as_main(self):
251 self.run_as_main = not self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000252 self.run_with_interpreter = 0
Just van Rossumf7f93882001-11-02 19:24:41 +0000253 self.editgroup.editor.selectionchanged()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000254
255 def domenu_toggle_run_with_interpreter(self):
256 self.run_with_interpreter = not self.run_with_interpreter
257 self.run_as_main = 0
Just van Rossumf7f93882001-11-02 19:24:41 +0000258 self.editgroup.editor.selectionchanged()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000259
260 def showbreakpoints(self, onoff):
261 self.editgroup.editor.showbreakpoints(onoff)
262 self.debugging = onoff
263
264 def domenu_clearbreakpoints(self, *args):
265 self.editgroup.editor.clearbreakpoints()
266
267 def domenu_editbreakpoints(self, *args):
268 self.editgroup.editor.editbreakpoints()
269
270 def domenu_toggledebugger(self, *args):
271 if not self.debugging:
272 W.SetCursor('watch')
273 self.debugging = not self.debugging
274 self.editgroup.editor.togglebreakpoints()
275
276 def domenu_toggleprofiler(self, *args):
277 self.profiling = not self.profiling
278
279 def domenu_browsenamespace(self, *args):
280 import PyBrowser, W
281 W.SetCursor('watch')
282 globals, file, modname = self.getenvironment()
283 if not modname:
284 modname = self.title
285 PyBrowser.Browser(globals, "Object browser: " + modname)
286
287 def domenu_modularize(self, *args):
288 modname = _filename_as_modname(self.title)
289 if not modname:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000290 raise W.AlertError, "Can't modularize \"%s\"" % self.title
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000291 run_as_main = self.run_as_main
292 self.run_as_main = 0
293 self.run()
294 self.run_as_main = run_as_main
295 if self.path:
296 file = self.path
297 else:
298 file = self.title
299
300 if self.globals and not sys.modules.has_key(modname):
301 module = imp.new_module(modname)
302 for attr in self.globals.keys():
303 setattr(module,attr,self.globals[attr])
304 sys.modules[modname] = module
305 self.globals = {}
306
307 def domenu_fontsettings(self, *args):
308 import FontSettings
309 fontsettings = self.editgroup.editor.getfontsettings()
310 tabsettings = self.editgroup.editor.gettabsettings()
311 settings = FontSettings.FontDialog(fontsettings, tabsettings)
312 if settings:
313 fontsettings, tabsettings = settings
314 self.editgroup.editor.setfontsettings(fontsettings)
315 self.editgroup.editor.settabsettings(tabsettings)
316
Just van Rossum12710051999-02-27 17:18:30 +0000317 def domenu_options(self, *args):
Jack Jansen9a389472002-03-29 21:26:04 +0000318 rvcreator, rveoln = SaveOptions(self._creator, self._eoln)
319 if rvcreator != self._creator or rveoln != self._eoln:
Just van Rossumf7f93882001-11-02 19:24:41 +0000320 self.editgroup.editor.selectionchanged() # ouch...
Jack Jansen9a389472002-03-29 21:26:04 +0000321 self._creator = rvcreator
322 self._eoln = rveoln
Just van Rossum12710051999-02-27 17:18:30 +0000323
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000324 def clicklinefield(self):
325 if self._currentwidget <> self.linefield:
326 self.linefield.select(1)
327 self.linefield.selectall()
328 return 1
329
330 def clickeditor(self):
331 if self._currentwidget <> self.editgroup.editor:
332 self.dolinefield()
333 return 1
334
335 def updateselection(self, force = 0):
336 sel = min(self.editgroup.editor.getselection())
337 lineno = self.editgroup.editor.offsettoline(sel)
338 if lineno <> self.lastlineno or force:
339 self.lastlineno = lineno
340 self.linefield.set(str(lineno + 1))
341 self.linefield.selview()
342
343 def dolinefield(self):
344 try:
345 lineno = string.atoi(self.linefield.get()) - 1
346 if lineno <> self.lastlineno:
347 self.editgroup.editor.selectline(lineno)
348 self.updateselection(1)
349 except:
350 self.updateselection(1)
351 self.editgroup.editor.select(1)
352
353 def setinfotext(self):
354 if not hasattr(self, 'infotext'):
355 return
356 if self.path:
357 self.infotext.set(self.path)
358 else:
359 self.infotext.set("")
360
361 def close(self):
362 if self.editgroup.editor.changed:
363 import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +0000364 from Carbon import Qd
Just van Rossum25ddc632001-07-05 07:06:26 +0000365 Qd.InitCursor()
366 save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title,
367 default=1, no="Don\xd5t save")
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000368 if save > 0:
369 if self.domenu_save():
370 return 1
371 elif save < 0:
372 return 1
Just van Rossum25ddc632001-07-05 07:06:26 +0000373 self.globals = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000374 W.Window.close(self)
375
376 def domenu_close(self, *args):
377 return self.close()
378
379 def domenu_save(self, *args):
380 if not self.path:
381 # Will call us recursively
382 return self.domenu_save_as()
383 data = self.editgroup.editor.get()
Jack Jansen9a389472002-03-29 21:26:04 +0000384 if self._eoln != '\r':
385 data = string.replace(data, '\r', self._eoln)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000386 fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings
387 fp.write(data)
388 fp.close()
389 fss = macfs.FSSpec(self.path)
390 fss.SetCreatorType(self._creator, 'TEXT')
391 self.getsettings()
392 self.writewindowsettings()
393 self.editgroup.editor.changed = 0
394 self.editgroup.editor.selchanged = 0
395 import linecache
396 if linecache.cache.has_key(self.path):
397 del linecache.cache[self.path]
398 import macostools
399 macostools.touched(self.path)
400
401 def can_save(self, menuitem):
402 return self.editgroup.editor.changed or self.editgroup.editor.selchanged
403
404 def domenu_save_as(self, *args):
405 fss, ok = macfs.StandardPutFile('Save as:', self.title)
406 if not ok:
407 return 1
408 self.showbreakpoints(0)
409 self.path = fss.as_pathname()
410 self.setinfotext()
411 self.title = os.path.split(self.path)[-1]
412 self.wid.SetWTitle(self.title)
413 self.domenu_save()
414 self.editgroup.editor.setfile(self.getfilename())
415 app = W.getapplication()
416 app.makeopenwindowsmenu()
417 if hasattr(app, 'makescriptsmenu'):
418 app = W.getapplication()
419 fss, fss_changed = app.scriptsfolder.Resolve()
420 path = fss.as_pathname()
421 if path == self.path[:len(path)]:
422 W.getapplication().makescriptsmenu()
423
424 def domenu_save_as_applet(self, *args):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000425 import buildtools
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000426
427 buildtools.DEBUG = 0 # ouch.
428
429 if self.title[-3:] == ".py":
430 destname = self.title[:-3]
431 else:
432 destname = self.title + ".applet"
433 fss, ok = macfs.StandardPutFile('Save as Applet:', destname)
434 if not ok:
435 return 1
436 W.SetCursor("watch")
437 destname = fss.as_pathname()
438 if self.path:
439 filename = self.path
440 if filename[-3:] == ".py":
441 rsrcname = filename[:-3] + '.rsrc'
442 else:
443 rsrcname = filename + '.rsrc'
444 else:
445 filename = self.title
446 rsrcname = ""
447
448 pytext = self.editgroup.editor.get()
449 pytext = string.split(pytext, '\r')
450 pytext = string.join(pytext, '\n') + '\n'
451 try:
452 code = compile(pytext, filename, "exec")
453 except (SyntaxError, EOFError):
454 raise buildtools.BuildError, "Syntax error in script %s" % `filename`
455
456 # Try removing the output file
457 try:
458 os.remove(destname)
459 except os.error:
460 pass
461 template = buildtools.findtemplate()
462 buildtools.process_common(template, None, code, rsrcname, destname, 0, 1)
463
464 def domenu_gotoline(self, *args):
465 self.linefield.selectall()
466 self.linefield.select(1)
467 self.linefield.selectall()
468
469 def domenu_selectline(self, *args):
470 self.editgroup.editor.expandselection()
471
472 def domenu_find(self, *args):
473 searchengine.show()
474
475 def domenu_entersearchstring(self, *args):
476 searchengine.setfindstring()
477
478 def domenu_replace(self, *args):
479 searchengine.replace()
480
481 def domenu_findnext(self, *args):
482 searchengine.findnext()
483
484 def domenu_replacefind(self, *args):
485 searchengine.replacefind()
486
487 def domenu_run(self, *args):
488 self.runbutton.push()
489
490 def domenu_runselection(self, *args):
491 self.runselbutton.push()
492
493 def run(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000494 if self._threadstate == (0, 0):
495 self._run()
496 else:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000497 lock = Wthreading.Lock()
498 lock.acquire()
499 self._thread.postException(KeyboardInterrupt)
500 if self._thread.isBlocked():
Just van Rossum73efed22000-04-09 19:45:22 +0000501 self._thread.start()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000502 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000503
504 def _run(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000505 if self.run_with_interpreter:
506 if self.editgroup.editor.changed:
507 import EasyDialogs
508 import Qd; Qd.InitCursor()
Just van Rossumdc3c6172001-06-19 21:37:33 +0000509 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
Just van Rossum0f2fd162000-10-20 06:36:30 +0000510 if save > 0:
511 if self.domenu_save():
512 return
513 elif save < 0:
514 return
515 if not self.path:
516 raise W.AlertError, "Can't run unsaved file"
517 self._run_with_interpreter()
518 else:
519 pytext = self.editgroup.editor.get()
520 globals, file, modname = self.getenvironment()
521 self.execstring(pytext, globals, globals, file, modname)
522
523 def _run_with_interpreter(self):
524 interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter")
525 if not os.path.exists(interp_path):
526 raise W.AlertError, "Can't find interpreter"
527 import findertools
528 XXX
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000529
530 def runselection(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000531 if self._threadstate == (0, 0):
532 self._runselection()
533 elif self._threadstate == (1, 1):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000534 self._thread.block()
Just van Rossum73efed22000-04-09 19:45:22 +0000535 self.setthreadstate((1, 2))
536 elif self._threadstate == (1, 2):
537 self._thread.start()
538 self.setthreadstate((1, 1))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000539
540 def _runselection(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000541 if self.run_with_interpreter:
542 raise W.AlertError, "Can't run selection with Interpreter"
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000543 globals, file, modname = self.getenvironment()
544 locals = globals
545 # select whole lines
546 self.editgroup.editor.expandselection()
547
548 # get lineno of first selected line
549 selstart, selend = self.editgroup.editor.getselection()
550 selstart, selend = min(selstart, selend), max(selstart, selend)
551 selfirstline = self.editgroup.editor.offsettoline(selstart)
552 alltext = self.editgroup.editor.get()
553 pytext = alltext[selstart:selend]
554 lines = string.split(pytext, '\r')
555 indent = getminindent(lines)
556 if indent == 1:
557 classname = ''
558 alllines = string.split(alltext, '\r')
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000559 for i in range(selfirstline - 1, -1, -1):
560 line = alllines[i]
561 if line[:6] == 'class ':
562 classname = string.split(string.strip(line[6:]))[0]
563 classend = identifieRE_match(classname)
564 if classend < 1:
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 classname = classname[:classend]
567 break
568 elif line and line[0] not in '\t#':
Just van Rossumdc3c6172001-06-19 21:37:33 +0000569 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000570 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000571 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000572 if globals.has_key(classname):
Just van Rossum25ddc632001-07-05 07:06:26 +0000573 klass = globals[classname]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000574 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000575 raise W.AlertError, "Can't find class \"%s\"." % classname
Just van Rossum25ddc632001-07-05 07:06:26 +0000576 # add class def
577 pytext = ("class %s:\n" % classname) + pytext
578 selfirstline = selfirstline - 1
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000579 elif indent > 0:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000580 raise W.AlertError, "Can't run indented code."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000581
582 # add "newlines" to fool compile/exec:
583 # now a traceback will give the right line number
584 pytext = selfirstline * '\r' + pytext
585 self.execstring(pytext, globals, locals, file, modname)
Just van Rossum25ddc632001-07-05 07:06:26 +0000586 if indent == 1 and globals[classname] is not klass:
587 # update the class in place
588 klass.__dict__.update(globals[classname].__dict__)
589 globals[classname] = klass
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000590
Just van Rossum73efed22000-04-09 19:45:22 +0000591 def setthreadstate(self, state):
592 oldstate = self._threadstate
593 if oldstate[0] <> state[0]:
594 self.runbutton.settitle(runButtonLabels[state[0]])
595 if oldstate[1] <> state[1]:
596 self.runselbutton.settitle(runSelButtonLabels[state[1]])
597 self._threadstate = state
598
599 def _exec_threadwrapper(self, *args, **kwargs):
600 apply(execstring, args, kwargs)
601 self.setthreadstate((0, 0))
602 self._thread = None
603
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000604 def execstring(self, pytext, globals, locals, file, modname):
605 tracebackwindow.hide()
606 # update windows
607 W.getapplication().refreshwindows()
608 if self.run_as_main:
609 modname = "__main__"
610 if self.path:
611 dir = os.path.dirname(self.path)
612 savedir = os.getcwd()
613 os.chdir(dir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000614 sys.path.insert(0, dir)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000615 else:
616 cwdindex = None
617 try:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000618 if haveThreading:
619 self._thread = Wthreading.Thread(os.path.basename(file),
Just van Rossum73efed22000-04-09 19:45:22 +0000620 self._exec_threadwrapper, pytext, globals, locals, file, self.debugging,
621 modname, self.profiling)
622 self.setthreadstate((1, 1))
623 self._thread.start()
624 else:
625 execstring(pytext, globals, locals, file, self.debugging,
626 modname, self.profiling)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000627 finally:
628 if self.path:
629 os.chdir(savedir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000630 del sys.path[0]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000631
632 def getenvironment(self):
633 if self.path:
634 file = self.path
635 dir = os.path.dirname(file)
636 # check if we're part of a package
637 modname = ""
638 while os.path.exists(os.path.join(dir, "__init__.py")):
639 dir, dirname = os.path.split(dir)
Just van Rossum2aaeb521999-02-05 21:58:25 +0000640 modname = dirname + '.' + modname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000641 subname = _filename_as_modname(self.title)
Just van Rossumf7f93882001-11-02 19:24:41 +0000642 if subname is None:
643 return self.globals, file, None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000644 if modname:
645 if subname == "__init__":
Just van Rossum2aaeb521999-02-05 21:58:25 +0000646 # strip trailing period
647 modname = modname[:-1]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000648 else:
Just van Rossum2aaeb521999-02-05 21:58:25 +0000649 modname = modname + subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000650 else:
651 modname = subname
652 if sys.modules.has_key(modname):
653 globals = sys.modules[modname].__dict__
654 self.globals = {}
655 else:
656 globals = self.globals
Just van Rossum73efed22000-04-09 19:45:22 +0000657 modname = subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000658 else:
659 file = '<%s>' % self.title
660 globals = self.globals
661 modname = file
662 return globals, file, modname
663
664 def write(self, stuff):
665 """for use as stdout"""
666 self._buf = self._buf + stuff
667 if '\n' in self._buf:
668 self.flush()
669
670 def flush(self):
671 stuff = string.split(self._buf, '\n')
672 stuff = string.join(stuff, '\r')
673 end = self.editgroup.editor.ted.WEGetTextLength()
674 self.editgroup.editor.ted.WESetSelection(end, end)
675 self.editgroup.editor.ted.WEInsert(stuff, None, None)
676 self.editgroup.editor.updatescrollbars()
677 self._buf = ""
678 # ? optional:
679 #self.wid.SelectWindow()
680
681 def getclasslist(self):
682 from string import find, strip
Just van Rossum24073ea1999-12-23 15:46:57 +0000683 methodRE = re.compile(r"\r[ \t]+def ")
684 findMethod = methodRE.search
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000685 editor = self.editgroup.editor
686 text = editor.get()
687 list = []
688 append = list.append
689 functag = "func"
690 classtag = "class"
691 methodtag = "method"
692 pos = -1
693 if text[:4] == 'def ':
694 append((pos + 4, functag))
695 pos = 4
696 while 1:
697 pos = find(text, '\rdef ', pos + 1)
698 if pos < 0:
699 break
700 append((pos + 5, functag))
701 pos = -1
702 if text[:6] == 'class ':
703 append((pos + 6, classtag))
704 pos = 6
705 while 1:
706 pos = find(text, '\rclass ', pos + 1)
707 if pos < 0:
708 break
709 append((pos + 7, classtag))
710 pos = 0
711 while 1:
Just van Rossum24073ea1999-12-23 15:46:57 +0000712 m = findMethod(text, pos + 1)
713 if m is None:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000714 break
Just van Rossum24073ea1999-12-23 15:46:57 +0000715 pos = m.regs[0][0]
716 #pos = find(text, '\r\tdef ', pos + 1)
717 append((m.regs[0][1], methodtag))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000718 list.sort()
719 classlist = []
720 methodlistappend = None
721 offsetToLine = editor.ted.WEOffsetToLine
722 getLineRange = editor.ted.WEGetLineRange
723 append = classlist.append
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000724 for pos, tag in list:
725 lineno = offsetToLine(pos)
726 lineStart, lineEnd = getLineRange(lineno)
727 line = strip(text[pos:lineEnd])
728 line = line[:identifieRE_match(line)]
729 if tag is functag:
730 append(("def " + line, lineno + 1))
731 methodlistappend = None
732 elif tag is classtag:
733 append(["class " + line])
734 methodlistappend = classlist[-1].append
735 elif methodlistappend and tag is methodtag:
736 methodlistappend(("def " + line, lineno + 1))
737 return classlist
738
739 def popselectline(self, lineno):
740 self.editgroup.editor.selectline(lineno - 1)
741
742 def selectline(self, lineno, charoffset = 0):
743 self.editgroup.editor.selectline(lineno - 1, charoffset)
744
Just van Rossum12710051999-02-27 17:18:30 +0000745class _saveoptions:
746
Jack Jansen9a389472002-03-29 21:26:04 +0000747 def __init__(self, creator, eoln):
Just van Rossum12710051999-02-27 17:18:30 +0000748 self.rv = None
Jack Jansen9a389472002-03-29 21:26:04 +0000749 self.eoln = eoln
750 self.w = w = W.ModalDialog((260, 160), 'Save options')
Just van Rossum12710051999-02-27 17:18:30 +0000751 radiobuttons = []
752 w.label = W.TextBox((8, 8, 80, 18), "File creator:")
Just van Rossum3af507d1999-04-22 22:23:46 +0000753 w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit)
Jack Jansen9a389472002-03-29 21:26:04 +0000754 w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython Interpreter", radiobuttons, self.interp_hit)
755 w.interpx_radio = W.RadioButton((8, 62, 160, 18), "OSX PythonW Interpreter", radiobuttons, self.interpx_hit)
756 w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons)
757 w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect)
758 w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit)
Just van Rossum12710051999-02-27 17:18:30 +0000759 w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit)
760 w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit)
761 w.setdefaultbutton(w.okbutton)
762 if creator == 'Pyth':
763 w.interp_radio.set(1)
Just van Rossum3af507d1999-04-22 22:23:46 +0000764 elif creator == W._signature:
Just van Rossum12710051999-02-27 17:18:30 +0000765 w.ide_radio.set(1)
Jack Jansen9a389472002-03-29 21:26:04 +0000766 elif creator == 'PytX':
767 w.interpx_radio.set(1)
768 elif creator == '\0\0\0\0':
769 w.none_radio.set(1)
Just van Rossum12710051999-02-27 17:18:30 +0000770 else:
771 w.other_radio.set(1)
Jack Jansen9a389472002-03-29 21:26:04 +0000772
773 w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:")
774 radiobuttons = []
775 w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit)
776 w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit)
777 w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit)
778 if self.eoln == '\n':
779 w.unix_radio.set(1)
780 elif self.eoln == '\r\n':
781 w.win_radio.set(1)
782 else:
783 w.mac_radio.set(1)
784
Just van Rossum12710051999-02-27 17:18:30 +0000785 w.bind("cmd.", w.cancelbutton.push)
786 w.open()
787
788 def ide_hit(self):
Just van Rossum3af507d1999-04-22 22:23:46 +0000789 self.w.other_creator.set(W._signature)
Just van Rossum12710051999-02-27 17:18:30 +0000790
791 def interp_hit(self):
792 self.w.other_creator.set("Pyth")
793
Jack Jansen9a389472002-03-29 21:26:04 +0000794 def interpx_hit(self):
795 self.w.other_creator.set("PytX")
796
797 def none_hit(self):
798 self.w.other_creator.set("\0\0\0\0")
799
Just van Rossum12710051999-02-27 17:18:30 +0000800 def otherselect(self, *args):
801 sel_from, sel_to = self.w.other_creator.getselection()
802 creator = self.w.other_creator.get()[:4]
803 creator = creator + " " * (4 - len(creator))
804 self.w.other_creator.set(creator)
805 self.w.other_creator.setselection(sel_from, sel_to)
806 self.w.other_radio.set(1)
807
Jack Jansen9a389472002-03-29 21:26:04 +0000808 def mac_hit(self):
809 self.eoln = '\r'
810
811 def unix_hit(self):
812 self.eoln = '\n'
813
814 def win_hit(self):
815 self.eoln = '\r\n'
816
Just van Rossum12710051999-02-27 17:18:30 +0000817 def cancelbuttonhit(self):
818 self.w.close()
819
820 def okbuttonhit(self):
Jack Jansen9a389472002-03-29 21:26:04 +0000821 self.rv = (self.w.other_creator.get()[:4], self.eoln)
Just van Rossum12710051999-02-27 17:18:30 +0000822 self.w.close()
823
824
Jack Jansen9a389472002-03-29 21:26:04 +0000825def SaveOptions(creator, eoln):
826 s = _saveoptions(creator, eoln)
Just van Rossum12710051999-02-27 17:18:30 +0000827 return s.rv
828
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000829
830def _escape(where, what) :
831 return string.join(string.split(where, what), '\\' + what)
832
833def _makewholewordpattern(word):
834 # first, escape special regex chars
Just van Rossum3eec7622001-07-10 19:25:40 +0000835 for esc in "\\[]()|.*^+$?":
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000836 word = _escape(word, esc)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000837 notwordcharspat = '[^' + _wordchars + ']'
Jack Jansen9ad27522001-02-21 13:54:31 +0000838 pattern = '(' + word + ')'
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000839 if word[0] in _wordchars:
840 pattern = notwordcharspat + pattern
841 if word[-1] in _wordchars:
842 pattern = pattern + notwordcharspat
Jack Jansen9ad27522001-02-21 13:54:31 +0000843 return re.compile(pattern)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000844
Just van Rossumf376ef02001-11-18 14:12:43 +0000845
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000846class SearchEngine:
847
848 def __init__(self):
849 self.visible = 0
850 self.w = None
851 self.parms = { "find": "",
852 "replace": "",
853 "wrap": 1,
854 "casesens": 1,
855 "wholeword": 1
856 }
857 import MacPrefs
858 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
859 if prefs.searchengine:
860 self.parms["casesens"] = prefs.searchengine.casesens
861 self.parms["wrap"] = prefs.searchengine.wrap
862 self.parms["wholeword"] = prefs.searchengine.wholeword
863
864 def show(self):
865 self.visible = 1
866 if self.w:
867 self.w.wid.ShowWindow()
868 self.w.wid.SelectWindow()
869 self.w.find.edit.select(1)
870 self.w.find.edit.selectall()
871 return
872 self.w = W.Dialog((420, 150), "Find")
873
874 self.w.find = TitledEditText((10, 4, 300, 36), "Search for:")
875 self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:")
876
877 self.w.boxes = W.Group((10, 50, 300, 40))
878 self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive")
879 self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word")
880 self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around")
881
882 self.buttons = [ ("Find", "cmdf", self.find),
883 ("Replace", "cmdr", self.replace),
884 ("Replace all", None, self.replaceall),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000885 ("Don't find", "cmdd", self.dont),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000886 ("Cancel", "cmd.", self.cancel)
887 ]
888 for i in range(len(self.buttons)):
889 bounds = -90, 22 + i * 24, 80, 16
890 title, shortcut, callback = self.buttons[i]
891 self.w[title] = W.Button(bounds, title, callback)
892 if shortcut:
893 self.w.bind(shortcut, self.w[title].push)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000894 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000895 self.w.find.edit.bind("<key>", self.key)
896 self.w.bind("<activate>", self.activate)
897 self.w.bind("<close>", self.close)
898 self.w.open()
899 self.setparms()
900 self.w.find.edit.select(1)
901 self.w.find.edit.selectall()
902 self.checkbuttons()
903
904 def close(self):
905 self.hide()
906 return -1
907
908 def key(self, char, modifiers):
909 self.w.find.edit.key(char, modifiers)
910 self.checkbuttons()
911 return 1
912
913 def activate(self, onoff):
914 if onoff:
915 self.checkbuttons()
916
917 def checkbuttons(self):
918 editor = findeditor(self)
919 if editor:
920 if self.w.find.get():
921 for title, cmd, call in self.buttons[:-2]:
922 self.w[title].enable(1)
923 self.w.setdefaultbutton(self.w["Find"])
924 else:
925 for title, cmd, call in self.buttons[:-2]:
926 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000927 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000928 else:
929 for title, cmd, call in self.buttons[:-2]:
930 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000931 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000932
933 def find(self):
934 self.getparmsfromwindow()
935 if self.findnext():
936 self.hide()
937
938 def replace(self):
939 editor = findeditor(self)
940 if not editor:
941 return
942 if self.visible:
943 self.getparmsfromwindow()
944 text = editor.getselectedtext()
945 find = self.parms["find"]
946 if not self.parms["casesens"]:
947 find = string.lower(find)
948 text = string.lower(text)
949 if text == find:
950 self.hide()
951 editor.insert(self.parms["replace"])
952
953 def replaceall(self):
954 editor = findeditor(self)
955 if not editor:
956 return
957 if self.visible:
958 self.getparmsfromwindow()
959 W.SetCursor("watch")
960 find = self.parms["find"]
961 if not find:
962 return
963 findlen = len(find)
964 replace = self.parms["replace"]
965 replacelen = len(replace)
966 Text = editor.get()
967 if not self.parms["casesens"]:
968 find = string.lower(find)
969 text = string.lower(Text)
970 else:
971 text = Text
972 newtext = ""
973 pos = 0
974 counter = 0
975 while 1:
976 if self.parms["wholeword"]:
977 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +0000978 match = wholewordRE.search(text, pos)
979 if match:
980 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000981 else:
982 pos = -1
983 else:
984 pos = string.find(text, find, pos)
985 if pos < 0:
986 break
987 counter = counter + 1
988 text = text[:pos] + replace + text[pos + findlen:]
989 Text = Text[:pos] + replace + Text[pos + findlen:]
990 pos = pos + replacelen
991 W.SetCursor("arrow")
992 if counter:
993 self.hide()
994 import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +0000995 from Carbon import Res
Just van Rossumf7f93882001-11-02 19:24:41 +0000996 editor.textchanged()
997 editor.selectionchanged()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000998 editor.ted.WEUseText(Res.Resource(Text))
999 editor.ted.WECalText()
1000 editor.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +00001001 editor.GetWindow().InvalWindowRect(editor._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001002 #editor.ted.WEUpdate(self.w.wid.GetWindowPort().visRgn)
1003 EasyDialogs.Message("Replaced %d occurrences" % counter)
1004
1005 def dont(self):
1006 self.getparmsfromwindow()
1007 self.hide()
1008
1009 def replacefind(self):
1010 self.replace()
1011 self.findnext()
1012
1013 def setfindstring(self):
1014 editor = findeditor(self)
1015 if not editor:
1016 return
1017 find = editor.getselectedtext()
1018 if not find:
1019 return
1020 self.parms["find"] = find
1021 if self.w:
1022 self.w.find.edit.set(self.parms["find"])
1023 self.w.find.edit.selectall()
1024
1025 def findnext(self):
1026 editor = findeditor(self)
1027 if not editor:
1028 return
1029 find = self.parms["find"]
1030 if not find:
1031 return
1032 text = editor.get()
1033 if not self.parms["casesens"]:
1034 find = string.lower(find)
1035 text = string.lower(text)
1036 selstart, selend = editor.getselection()
1037 selstart, selend = min(selstart, selend), max(selstart, selend)
1038 if self.parms["wholeword"]:
1039 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +00001040 match = wholewordRE.search(text, selend)
1041 if match:
1042 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001043 else:
1044 pos = -1
1045 else:
1046 pos = string.find(text, find, selend)
1047 if pos >= 0:
1048 editor.setselection(pos, pos + len(find))
1049 return 1
1050 elif self.parms["wrap"]:
1051 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001052 match = wholewordRE.search(text, 0)
1053 if match:
1054 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001055 else:
1056 pos = -1
1057 else:
1058 pos = string.find(text, find)
1059 if selstart > pos >= 0:
1060 editor.setselection(pos, pos + len(find))
1061 return 1
1062
1063 def setparms(self):
1064 for key, value in self.parms.items():
1065 try:
1066 self.w[key].set(value)
1067 except KeyError:
1068 self.w.boxes[key].set(value)
1069
1070 def getparmsfromwindow(self):
1071 if not self.w:
1072 return
1073 for key, value in self.parms.items():
1074 try:
1075 value = self.w[key].get()
1076 except KeyError:
1077 value = self.w.boxes[key].get()
1078 self.parms[key] = value
1079
1080 def cancel(self):
1081 self.hide()
1082 self.setparms()
1083
1084 def hide(self):
1085 if self.w:
1086 self.w.wid.HideWindow()
1087 self.visible = 0
1088
1089 def writeprefs(self):
1090 import MacPrefs
1091 self.getparmsfromwindow()
1092 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1093 prefs.searchengine.casesens = self.parms["casesens"]
1094 prefs.searchengine.wrap = self.parms["wrap"]
1095 prefs.searchengine.wholeword = self.parms["wholeword"]
1096 prefs.save()
1097
1098
1099class TitledEditText(W.Group):
1100
1101 def __init__(self, possize, title, text = ""):
1102 W.Group.__init__(self, possize)
1103 self.title = W.TextBox((0, 0, 0, 16), title)
1104 self.edit = W.EditText((0, 16, 0, 0), text)
1105
1106 def set(self, value):
1107 self.edit.set(value)
1108
1109 def get(self):
1110 return self.edit.get()
1111
1112
1113class ClassFinder(W.PopupWidget):
1114
1115 def click(self, point, modifiers):
1116 W.SetCursor("watch")
1117 self.set(self._parentwindow.getclasslist())
1118 W.PopupWidget.click(self, point, modifiers)
1119
1120
1121def getminindent(lines):
1122 indent = -1
1123 for line in lines:
1124 stripped = string.strip(line)
1125 if not stripped or stripped[0] == '#':
1126 continue
1127 if indent < 0 or line[:indent] <> indent * '\t':
1128 indent = 0
1129 for c in line:
1130 if c <> '\t':
1131 break
1132 indent = indent + 1
1133 return indent
1134
1135
1136def getoptionkey():
1137 return not not ord(Evt.GetKeys()[7]) & 0x04
1138
1139
1140def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1141 modname="__main__", profiling=0):
1142 if debugging:
1143 import PyDebugger, bdb
1144 BdbQuit = bdb.BdbQuit
1145 else:
1146 BdbQuit = 'BdbQuitDummyException'
1147 pytext = string.split(pytext, '\r')
1148 pytext = string.join(pytext, '\n') + '\n'
1149 W.SetCursor("watch")
1150 globals['__name__'] = modname
1151 globals['__file__'] = filename
1152 sys.argv = [filename]
1153 try:
1154 code = compile(pytext, filename, "exec")
1155 except:
1156 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1157 # special. That's wrong because THIS case is special (could be literal
1158 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1159 # in imported module!!!
1160 tracebackwindow.traceback(1, filename)
1161 return
1162 try:
1163 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001164 if haveThreading:
1165 lock = Wthreading.Lock()
1166 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001167 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001168 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001169 else:
1170 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001171 elif not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001172 if hasattr(MacOS, 'EnableAppswitch'):
1173 MacOS.EnableAppswitch(0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001174 try:
1175 if profiling:
1176 import profile, ProfileBrowser
1177 p = profile.Profile()
1178 p.set_cmd(filename)
1179 try:
1180 p.runctx(code, globals, locals)
1181 finally:
1182 import pstats
1183
1184 stats = pstats.Stats(p)
1185 ProfileBrowser.ProfileBrowser(stats)
1186 else:
1187 exec code in globals, locals
1188 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001189 if not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001190 if hasattr(MacOS, 'EnableAppswitch'):
1191 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001192 except W.AlertError, detail:
1193 raise W.AlertError, detail
1194 except (KeyboardInterrupt, BdbQuit):
1195 pass
Just van Rossumf7f93882001-11-02 19:24:41 +00001196 except SystemExit, arg:
1197 if arg.code:
1198 sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001199 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001200 if haveThreading:
1201 import continuation
1202 lock = Wthreading.Lock()
1203 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001204 if debugging:
1205 sys.settrace(None)
1206 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1207 return
1208 else:
1209 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001210 if haveThreading:
1211 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001212 if debugging:
1213 sys.settrace(None)
1214 PyDebugger.stop()
1215
1216
Just van Rossum3eec7622001-07-10 19:25:40 +00001217_identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
Jack Jansen9ad27522001-02-21 13:54:31 +00001218
1219def identifieRE_match(str):
1220 match = _identifieRE.match(str)
1221 if not match:
1222 return -1
1223 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001224
1225def _filename_as_modname(fname):
1226 if fname[-3:] == '.py':
1227 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001228 match = _identifieRE.match(modname)
1229 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001230 return string.join(string.split(modname, '.'), '_')
1231
1232def findeditor(topwindow, fromtop = 0):
Just van Rossum40144012002-02-04 12:52:44 +00001233 wid = MyFrontWindow()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001234 if not fromtop:
1235 if topwindow.w and wid == topwindow.w.wid:
1236 wid = topwindow.w.wid.GetNextWindow()
1237 if not wid:
1238 return
1239 app = W.getapplication()
1240 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1241 window = W.getapplication()._windows[wid]
1242 else:
1243 return
1244 if not isinstance(window, Editor):
1245 return
1246 return window.editgroup.editor
1247
1248
1249class _EditorDefaultSettings:
1250
1251 def __init__(self):
1252 self.template = "%s, %d point"
1253 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1254 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001255 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001256 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1257
1258 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1259 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1260 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1261 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1262 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1263
1264 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1265 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1266 self.w.setdefaultbutton(self.w.okbutton)
1267 self.w.bind('cmd.', self.w.cancelbutton.push)
1268 self.w.open()
1269
1270 def picksize(self):
1271 app = W.getapplication()
1272 editor = findeditor(self)
1273 if editor is not None:
1274 width, height = editor._parentwindow._bounds[2:]
1275 self.w.xsize.set(`width`)
1276 self.w.ysize.set(`height`)
1277 else:
1278 raise W.AlertError, "No edit window found"
1279
1280 def dofont(self):
1281 import FontSettings
1282 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1283 if settings:
1284 self.fontsettings, self.tabsettings = settings
1285 sys.exc_traceback = None
1286 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1287
1288 def close(self):
1289 self.w.close()
1290 del self.w
1291
1292 def cancel(self):
1293 self.close()
1294
1295 def ok(self):
1296 try:
1297 width = string.atoi(self.w.xsize.get())
1298 except:
1299 self.w.xsize.select(1)
1300 self.w.xsize.selectall()
1301 raise W.AlertError, "Bad number for window width"
1302 try:
1303 height = string.atoi(self.w.ysize.get())
1304 except:
1305 self.w.ysize.select(1)
1306 self.w.ysize.selectall()
1307 raise W.AlertError, "Bad number for window height"
1308 self.windowsize = width, height
1309 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1310 self.close()
1311
1312def geteditorprefs():
1313 import MacPrefs
1314 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1315 try:
1316 fontsettings = prefs.pyedit.fontsettings
1317 tabsettings = prefs.pyedit.tabsettings
1318 windowsize = prefs.pyedit.windowsize
1319 except:
Just van Rossumf7f93882001-11-02 19:24:41 +00001320 fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001321 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1322 windowsize = prefs.pyedit.windowsize = (500, 250)
1323 sys.exc_traceback = None
1324 return fontsettings, tabsettings, windowsize
1325
1326def seteditorprefs(fontsettings, tabsettings, windowsize):
1327 import MacPrefs
1328 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1329 prefs.pyedit.fontsettings = fontsettings
1330 prefs.pyedit.tabsettings = tabsettings
1331 prefs.pyedit.windowsize = windowsize
1332 prefs.save()
1333
1334_defaultSettingsEditor = None
1335
1336def EditorDefaultSettings():
1337 global _defaultSettingsEditor
1338 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1339 _defaultSettingsEditor = _EditorDefaultSettings()
1340 else:
1341 _defaultSettingsEditor.w.select()
1342
1343def resolvealiases(path):
1344 try:
1345 return macfs.ResolveAliasFile(path)[0].as_pathname()
1346 except (macfs.error, ValueError), (error, str):
1347 if error <> -120:
1348 raise
1349 dir, file = os.path.split(path)
1350 return os.path.join(resolvealiases(dir), file)
1351
1352searchengine = SearchEngine()
1353tracebackwindow = Wtraceback.TraceBack()