# -*- coding: utf-8 -*-
#@+leo-ver=4
#@+node:@file __wx_gui.py
#@@first

"""A plugin to use wxPython as Leo's gui."""

from leoPlugins import *
from leoGlobals import *

#@<< imports for wx plugin >>
#@+node:<< imports for wx plugin >>
import leoCommands,leoFind,leoFrame,leoGui,leoNodes,leoTree
import os,sys,traceback

try:    from wxPython import wx
except: wx = None
#@nonl
#@-node:<< imports for wx plugin >>
#@nl
#@<< constants for wx plugin >>
#@+node:<< constants for wx plugin >>
cSplitterWidth = 600

const_dict = {}
const_lastVal = 100 # Starting wx id.

def const(name):
	
	"""Return the wx id associated with name"""
	
	# Should this canonicalize the label?  Just remove '&' ??
	
	id = const_dict.get(name)
	if id != None:
		return id
	else:
		global const_lastVal
		const_lastVal += 1
		const_dict[name] = const_lastVal
		# trace(name,const_lastVal)
		return const_lastVal
#@nonl
#@-node:<< constants for wx plugin >>
#@nl

#@+others
#@+node:wxGui class
class wxGui(leoGui.leoGui):
	
	#@	@+others
	#@+node:wxGui.__init__
	def __init__ (self):
		
		trace("wxGui")
		
		# Initialize the base class.
		if 1: # in plugin
			leoGui.leoGui.__init__(self,"wxPython")
		else:
			leoGui.__init__(self,"wxPython")
			
		self.bitmap_name = None
		self.bitmap = None
	#@nonl
	#@-node:wxGui.__init__
	#@+node:createRootWindow & allies
	def createRootWindow(self):
	
		trace("wxGui")
		self.wxApp = wxLeoApp(None) # This redirects stdout & stderr to stupid console.
		self.wxFrame = None
		
		if 0: # Not ready yet.
			self.setDefaultIcon()
			self.getDefaultConfigFont(app.config)
			self.setEncoding()
			self.createGlobalWindows()
	
		return self.wxFrame
	#@nonl
	#@-node:createRootWindow & allies
	#@+node:setDefaultIcon
	def setDefaultIcon(self):
		
		"""Set the icon to be used in all Leo windows.
		
		This code does nothing for Tk versions before 8.4.3."""
		
		gui = self
	
		try:
			version = gui.root.getvar("tk_patchLevel")
			if CheckVersion(version,"8.4.3"):
				# tk 8.4.3 or greater: load a 16 by 16 icon.
				path = os.path.join(app.loadDir,"..","Icons")
				if os.path.exists(path):
					file = os.path.join(path,"LeoApp16.ico")
					if os.path.exists(path):
						self.bitmap = Tkinter.BitmapImage(file)
					else:
						es("LeoApp16.ico not in Icons directory", color="red")
				else:
					es("Icons directory not found: "+path, color="red")
		except:
			print "exception setting bitmap"
			traceback.print_exc()
	#@nonl
	#@-node:setDefaultIcon
	#@+node:setEncoding
	#@+at 
	#@nonl
	# According to Martin v. Löwis, getdefaultlocale() is broken, and cannot 
	# be fixed. The workaround is to copy the getpreferredencoding() function 
	# from locale.py in Python 2.3a2.  This function is now in leoGlobals.py.
	#@-at
	#@@c
	
	def setEncoding (self):
	
		for (encoding,src) in (
			(app.config.tkEncoding,"config"),
			#(locale.getdefaultlocale()[1],"locale"),
			(getpreferredencoding(),"locale"),
			(sys.getdefaultencoding(),"sys"),
			("utf-8","default")):
		
			if isValidEncoding (encoding): # 3/22/03
				app.tkEncoding = encoding
				# trace(app.tkEncoding,src)
				break
			elif encoding and len(encoding) > 0:
				trace("ignoring invalid " + src + " encoding: " + `encoding`)
				
		# trace(app.tkEncoding)
	#@nonl
	#@-node:setEncoding
	#@+node:getDefaultConfigFont
	def getDefaultConfigFont(self,config):
		
		"""Get the default font from a new text widget."""
	
		t = Tkinter.Text()
		fn = t.cget("font")
		font = tkFont.Font(font=fn)
		config.defaultFont = font
		config.defaultFontFamily = font.cget("family")
	#@nonl
	#@-node:getDefaultConfigFont
	#@+node:createGlobalWindows
	def createGlobalWindows (self):
		
		"""Create the global windows for the application."""
		
		app.findFrame = leoFind.leoFind()
		app.findFrame.top.withdraw()
		app.globalWindows.append(app.findFrame)
	#@nonl
	#@-node:createGlobalWindows
	#@+node:destroy
	def destroy(self,widget):
		
		pass # wx code not ready yet.
	#@nonl
	#@-node:destroy
	#@+node:finishCreate
	def finishCreate (self):
	
		pass
		
	#@-node:finishCreate
	#@+node:killGui (not used)
	def killGui(self,exitFlag=true):
		
		"""Destroy a gui and terminate Leo if exitFlag is true."""
	
		pass # Not ready yet.
	
	#@-node:killGui (not used)
	#@+node:recreateRootWindow (not used)
	def recreateRootWindow(self):
		"""A do-nothing base class to create the hidden root window of a gui
	
		after a previous gui has terminated with killGui(false)."""
		pass
	
	#@-node:recreateRootWindow (not used)
	#@+node:runMainLoop
	def runMainLoop(self):
	
		"""Run tkinter's main loop."""
		
		trace("wxGui")
		self.wxApp.MainLoop()
		trace("done")
	#@nonl
	#@-node:runMainLoop
	#@+node:getFontFromParams
	def getFontFromParams(self,family,size,slant,weight):
		
		trace(app.config.defaultFont)
		
		return app.config.defaultFont ##
		
		family_name = family
		
		try:
			font = tkFont.Font(family=family,size=size,slant=slant,weight=weight)
			#print family_name,family,size,slant,weight
			#print "actual_name:",font.cget("family")
			return font
		except:
			es("exception setting font from " + `family_name`)
			es("family,size,slant,weight:"+
				`family`+':'+`size`+':'+`slant`+':'+`weight`)
			es_exception()
			return app.config.defaultFont
	#@nonl
	#@-node:getFontFromParams
	#@+node:Dialogs
	def newAboutLeoDialog(self,commander):
		"""A do-nothing base class to create an About Leo dialog."""
		pass
	
	def newAskOkDialog(self,commander):
		"""A do-nothing base class to create an askOK dialog ."""
		pass
	
	def newAskOkCancelDialog(self,commander):
		"""A do-nothing base class to create an askOkCancel dialog."""
		pass
	
	def newAskOkCancelNumberDialog(self,commander):
		"""A do-nothing base class to create an askOkCancelNumber dialog ."""
		pass
	
	def newAskYesNoDialog(self,commander):
		"""A do-nothing base class to create an askYesNo dialog."""
		pass
	
	def newAskYesNoCancelDialg(self,commander):
		"""A do-nothing base class to create an askYesNoCancel dialog ."""
		pass
	#@nonl
	#@-node:Dialogs
	#@+node:newLeoFrame
	def newLeoFrame(self,title):
		
		"""Create a view frame for the Leo main window."""
		
		trace()
		self.wxFrame = wxLeoFrame(title)
		self.wxApp.SetTopWindow(self.wxFrame)
		self.wxFrame.Show(true)
		if not app.root:
			app.root = self.wxFrame
		return self.wxFrame
	#@nonl
	#@-node:newLeoFrame
	#@+node:other frames...
	def newColorFrame(self,commander):
		"""Create a colorFrame."""
		pass # To do
	
	def newColorNameFrame(self,commander):
		"""Create a colorNameFrame."""
		pass # To do
	
	def newCompareFrame(self,commander):
		"""Create a compareFrame."""
		pass # To do
	
	def newFindFrame(self,commander):
		"""Create a findFrame."""
		pass # To do
	
	def newFontFrame(self,commander):
		"""Create a fontFrame."""
		pass # To do
	
	def newPrefsFrame(self,commander):
		"""Create a prefsFrame."""
		pass # To do
	#@nonl
	#@-node:other frames...
	#@+node:destroyLeoFrame
	def destroyLeoFrame (self,frame):
	
		trace(frame.title)
		frame.Close()
	#@nonl
	#@-node:destroyLeoFrame
	#@+node:destroy
	def destroy (self,widget):
		
		trace()
	#@nonl
	#@-node:destroy
	#@+node:get_focus
	def get_focus(self,top):
		
		"""Returns the widget that has focus, or body if None."""
	
		pass # wx code not ready yet.
	#@nonl
	#@-node:get_focus
	#@+node:set_focus
	def set_focus(self,commands,widget):
		
		"""Set the focus of the widget in the given commander if it needs to be changed."""
		
		pass # wx code not ready yet.
	#@nonl
	#@-node:set_focus
	#@+node:force_focus
	def force_focus(self,commands,widget):
		
		"""Set the focus of the widget in the given commander if it needs to be changed."""
		
		pass # wx code not ready yet.
	#@nonl
	#@-node:force_focus
	#@+node:attachLeoIcon & createLeoIcon
	def attachLeoIcon (self,w):
		
		"""Try to attach a Leo icon to the Leo Window.
		
		Use tk's wm_iconbitmap function if available (tk 8.3.4 or greater).
		Otherwise, try to use the Python Imaging Library and the tkIcon package."""
	
		if self.bitmap != None:
			# We don't need PIL or tkicon: this is tk 8.3.4 or greater.
			try:
				w.wm_iconbitmap(self.bitmap)
			except:
				self.bitmap = None
		
		if self.bitmap == None:
			try:
				#@			<< try to use the PIL and tkIcon packages to draw the icon >>
				#@+node:<< try to use the PIL and tkIcon packages to draw the icon >>
				#@+at 
				#@nonl
				# This code requires Fredrik Lundh's PIL and tkIcon packages:
				# 
				# Download PIL    from 
				# http://www.pythonware.com/downloads/index.htm#pil
				# Download tkIcon from http://www.effbot.org/downloads/#tkIcon
				# 
				# Many thanks to Jonathan M. Gilligan for suggesting this 
				# code.
				#@-at
				#@@c
				
				import Image,tkIcon,_tkicon
				
				# Wait until the window has been drawn once before attaching the icon in OnVisiblity.
				def visibilityCallback(event,self=self,w=w):
					try: self.leoIcon.attach(w.winfo_id())
					except: pass
				w.bind("<Visibility>",visibilityCallback)
				if not self.leoIcon:
					# Load a 16 by 16 gif.  Using .gif rather than an .ico allows us to specify transparency.
					icon_file_name = os.path.join(app.loadDir,'..','Icons','LeoWin.gif')
					icon_file_name = os.path.normpath(icon_file_name)
					icon_image = Image.open(icon_file_name)
					if 1: # Doesn't resize.
						self.leoIcon = self.createLeoIcon(icon_image)
					else: # Assumes 64x64
						self.leoIcon = tkIcon.Icon(icon_image)
				#@nonl
				#@-node:<< try to use the PIL and tkIcon packages to draw the icon >>
				#@nl
			except:
				# traceback.print_exc()
				self.leoIcon = None
	#@nonl
	#@-node:attachLeoIcon & createLeoIcon
	#@+node:createLeoIcon
	# This code is adapted from tkIcon.__init__
	# Unlike the tkIcon code, this code does _not_ resize the icon file.
	
	def createLeoIcon (self,icon):
		
		try:
			import Image,tkIcon,_tkicon
			
			i = icon ; m = None
			# create transparency mask
			if i.mode == "P":
				try:
					t = i.info["transparency"]
					m = i.point(lambda i, t=t: i==t, "1")
				except KeyError: pass
			elif i.mode == "RGBA":
				# get transparency layer
				m = i.split()[3].point(lambda i: i == 0, "1")
			if not m:
				m = Image.new("1", i.size, 0) # opaque
			# clear unused parts of the original image
			i = i.convert("RGB")
			i.paste((0, 0, 0), (0, 0), m)
			# create icon
			m = m.tostring("raw", ("1", 0, 1))
			c = i.tostring("raw", ("BGRX", 0, -1))
			return _tkicon.new(i.size, c, m)
		except:
			return None
	#@nonl
	#@-node:createLeoIcon
	#@+node:get_window_info
	# WARNING: Call this routine _after_ creating a dialog.
	# (This routine inhibits the grid and pack geometry managers.)
	
	def get_window_info (self,top):
		
		top.update_idletasks() # Required to get proper info.
	
		# Get the information about top and the screen.
		geom = top.geometry() # geom = "WidthxHeight+XOffset+YOffset"
		dim,x,y = string.split(geom,'+')
		w,h = string.split(dim,'x')
		w,h,x,y = int(w),int(h),int(x),int(y)
		
		return w,h,x,y
	#@nonl
	#@-node:get_window_info
	#@+node:center_dialog
	# Center the dialog on the screen.
	# WARNING: Call this routine _after_ creating a dialog.
	# (This routine inhibits the grid and pack geometry managers.)
	
	def center_dialog(self,top):
	
		sw = top.winfo_screenwidth()
		sh = top.winfo_screenheight()
		w,h,x,y = get_window_info(top)
		
		# Set the new window coordinates, leaving w and h unchanged.
		x = (sw - w)/2
		y = (sh - h)/2
		top.geometry("%dx%d%+d%+d" % (w,h,x,y))
		
		return w,h,x,y
	#@nonl
	#@-node:center_dialog
	#@+node:create_labeled_frame
	# Returns frames w and f.
	# Typically the caller would pack w into other frames, and pack content into f.
	
	def create_labeled_frame (self,parent,
		caption=None,relief="groove",bd=2,padx=0,pady=0):
		
		Tk = Tkinter
		# Create w, the master frame.
		w = Tk.Frame(parent)
		w.grid(sticky="news")
		
		# Configure w as a grid with 5 rows and columns.
		# The middle of this grid will contain f, the expandable content area.
		w.columnconfigure(1,minsize=bd)
		w.columnconfigure(2,minsize=padx)
		w.columnconfigure(3,weight=1)
		w.columnconfigure(4,minsize=padx)
		w.columnconfigure(5,minsize=bd)
		
		w.rowconfigure(1,minsize=bd)
		w.rowconfigure(2,minsize=pady)
		w.rowconfigure(3,weight=1)
		w.rowconfigure(4,minsize=pady)
		w.rowconfigure(5,minsize=bd)
	
		# Create the border spanning all rows and columns.
		border = Tk.Frame(w,bd=bd,relief=relief) # padx=padx,pady=pady)
		border.grid(row=1,column=1,rowspan=5,columnspan=5,sticky="news")
		
		# Create the content frame, f, in the center of the grid.
		f = Tk.Frame(w,bd=bd)
		f.grid(row=3,column=3,sticky="news")
		
		# Add the caption.
		if caption and len(caption) > 0:
			caption = Tk.Label(parent,text=caption,highlightthickness=0,bd=0)
			caption.tkraise(w)
			caption.grid(in_=w,row=0,column=2,rowspan=2,columnspan=3,padx=4,sticky="w")
	
		return w,f
	#@nonl
	#@-node:create_labeled_frame
	#@-others
#@nonl
#@-node:wxGui class
#@+node:wxLeoApp class
class wxLeoApp (wx.wxApp):
	
	#@	@+others
	#@+node:OnInit
	def OnInit(self):
		
		self.SetAppName("Leo")
		trace("wx.wxPlatform",wx.wxPlatform)
		app.findFrame = wxFindFrame()
		app.globalWindows.append(app.findFrame)
		return true
	#@nonl
	#@-node:OnInit
	#@+node:OnExit
	def OnExit(self):
		
		trace()
		return true
	#@-node:OnExit
	#@-others
#@-node:wxLeoApp class
#@+node:wxLeoFrame class
class wxLeoFrame(wx.wxFrame):
	#@	@+others
	#@+node:__init__
	def __init__ (self,title):
		
		# trace("wxLeoFrame",title)
		self.title = title
		self.ratio = None
		self.secondary_ratio = None
		self.activeFrame = None
		self.c = None # set in finishCreate.
		self.quitting = false
		self.updateCount = 0
		self.treeIniting = false
		self.drawing = false # Lockout recursive draws.
		self.root_id = None
		self.menuIdDict = {}
		self.menuBar = None
		
		# These vars have corresponding getters/setters.
		self.mDragging = false
		self.mRootVnode = None
		self.mTopVnode = None
		self.mCurrentVnode = None
	
		wx.wxFrame.__init__(self, None, -1, title) # wx.wxNO_3D # hangs.
		
		#self.outerPanel = wx.wxPanel(self,-1)
		#self.iconPanel = wx.wxPanel(self.outerPanel, -1, "iconPanel")
		
		self.CreateStatusBar()
		self.createMenuBar()
		
		#@	<< create the splitters >>
		#@+node:<< create the splitters >>
		self.splitter1 = wx.wxSplitterWindow(self,
			const("cSplitterWindow"),
			wx.wxDefaultPosition, wx.wxDefaultSize,
			wx.wxSP_NOBORDER)
		
		# No effect, except to create a red flash.
		if 0:
			self.splitter1.SetForegroundColour(wx.wxRED)
			self.splitter1.SetBackgroundColour(wx.wxRED)
		
		self.splitter2 = wx.wxSplitterWindow(self.splitter1, -1,
			wx.wxDefaultPosition, wx.wxDefaultSize,
			wx.wxSP_NOBORDER)
			# wx.wxSP_BORDER | wx.wxSP_3D, "splitterWindow");
		
		self.splitter1.SetMinimumPaneSize(4)
		self.splitter2.SetMinimumPaneSize(4)
		#@nonl
		#@-node:<< create the splitters >>
		#@nl
		#@	<< create the tree >>
		#@+node:<< create the tree >>
		self.tree = wx.wxTreeCtrl(self.splitter2,
			const("cTreeCtrl"),
			wx.wxDefaultPosition, wx.wxDefaultSize,
			wx.wxTR_HAS_BUTTONS | wx.wxTR_EDIT_LABELS, wx.wxDefaultValidator,
			"treeCtrl")
			
		trace(const("cTreeCtrl"))
		#@nonl
		#@-node:<< create the tree >>
		#@nl
		#@	<< create the body pane >>
		#@+node:<< create the body pane >>
		self.body = wx.wxTextCtrl(self.splitter1,
			const("cBodyCtrl"), "",
			wx.wxDefaultPosition, wx.wxDefaultSize,
			wx.wxTE_MULTILINE)
		#@-node:<< create the body pane >>
		#@nl
		#@	<< create the log pane >>
		#@+node:<< create the log pane >>
		self.log = wx.wxTextCtrl(self.splitter2,
			const("cLogCtrl"), "",
			wx.wxDefaultPosition, wx.wxDefaultSize,
			wx.wxTE_MULTILINE )
		#@-node:<< create the log pane >>
		#@nl
		#@	<< set the window icon >>
		#@+node:<< set the window icon >>
		if wx.wxPlatform == "__WXMSW__":
		
			path = os.path.join(app.loadDir,"..","Icons","LeoApp16.ico")
			icon = wx.wxIcon(path,wx.wxBITMAP_TYPE_ICO,16,16)
			self.SetIcon(icon)
		#@-node:<< set the window icon >>
		#@nl
		#@	<< declare event handlers for frame >>
		#@+node:<< declare event handlers for frame >>
		if wx.wxPlatform == "__WXMSW__": # Activate events exist only on Windows.
			wx.EVT_ACTIVATE(self,self.onActivate)
		else:
			wx.EVT_SET_FOCUS(self,self.OnSetFocus)
		
		wx.EVT_CLOSE(self,self.onCloseLeoFrame)
		
		wx.EVT_MENU_OPEN(self,self.updateAllMenus) 
		
		if 0: # Causes problems at present.  The screen isn't drawn properly.
			wx.EVT_SIZE(self,self.onResize)
		#@nonl
		#@-node:<< declare event handlers for frame >>
		#@nl
		#@	<< declare event handlers for body & tree >>
		#@+node:<< declare event handlers for body & tree >>
		# in self.body
		wx.EVT_TEXT(self,const("cBodyCtrl"),self.onBodyTextUpdated) # Fires whenever text changes.
		
		# in self.tree
		id = const("cTreeCtrl")
		trace(id,self.tree)
		
		wx.EVT_TREE_KEY_DOWN        (self,id,self.onTreeKeyDown) # Control keys do not fire this event.
		wx.EVT_TREE_SEL_CHANGED     (self,id,self.onTreeChanged)
		wx.EVT_TREE_SEL_CHANGING    (self,id,self.onTreeChanging)
		wx.EVT_TREE_BEGIN_DRAG      (self,id,self.onTreeBeginDrag)
		wx.EVT_TREE_END_DRAG        (self,id,self.onTreeEndDrag)
		wx.EVT_TREE_BEGIN_LABEL_EDIT(self,id,self.onTreeBeginLabelEdit)
		wx.EVT_TREE_END_LABEL_EDIT  (self,id,self.onTreeEndLabelEdit)
		
		 
		wx.EVT_TREE_ITEM_COLLAPSED  (self,id,self.onTreeCollapsed)
		wx.EVT_TREE_ITEM_EXPANDED   (self,id,self.onTreeExpanded)
		
		wx.EVT_TREE_ITEM_COLLAPSING (self,id,self.onTreeCollapsing)
		wx.EVT_TREE_ITEM_EXPANDING  (self,id,self.onTreeExpanding)
		#@nonl
		#@-node:<< declare event handlers for body & tree >>
		#@nl
		
		# Attach the controls to the splitter.
		self.splitter1.SplitHorizontally(self.splitter2, self.body, 0)
		self.splitter2.SplitVertically(self.tree, self.log, cSplitterWidth/2)
		
	#@nonl
	#@-node:__init__
	#@+node:__repr__
	def __repr__ (self):
		
		return "wxLeoFrame: " + self.title
	#@nonl
	#@-node:__repr__
	#@+node:finishCreate
	def finishCreate (self,commander):
		
		self.c = self.commands = commander
		trace(commander)
		
		# Kludge.
		self.c.body = self.body
		self.c.frame = self
		
		# Add the frame to the global window list.
		app.windowList.append(self)
		self.redraw()
	#@nonl
	#@-node:finishCreate
	#@+node:createMenuBar
	def createMenuBar(self):
		
		self.menuBar = menuBar = wx.wxMenuBar()
		self.menuShortcuts = []
		
		#@	<< create the file menu >>
		#@+node:<< create the file menu >>
		fileMenu = wx.wxMenu()
		
		#@<< create the top-level file entries >>
		#@+node:<< create the top-level file entries >>
		#@+at 
		#@nonl
		# leo.py will probably never have a Print command.  Instead, export 
		# text files that may be formatted and printed as desired.
		#@-at
		#@@c
		
		table = (
			("&New","Ctrl+N",self.OnNew),
			("&Open...","Ctrl+O",self.OnOpen))
		self.createMenuEntries(fileMenu,table)
		
		# Create a new menu rather than call OnOpenWith.
		openWithMenu = wx.wxMenu()
		
		table = (
			("-",None,None),
			("&Close","Ctrl+W",self.OnClose),
			("&Save","Ctrl+S",self.OnSave),
			("Save &As","Shift+Ctrl+S",self.OnSaveAs),
			("Save To",None,self.OnSaveTo),
			("Re&vert To Saved",None,self.OnRevert,self.OnUpdateRevert))
		
		self.createMenuEntries(fileMenu,table)
		#@nonl
		#@-node:<< create the top-level file entries >>
		#@nl
		#@<< create the recent files submenu >>
		#@+node:<< create the recent files submenu >>
		recentFilesMenu = wx.wxMenu()
		
		self.recentFiles = app().config.getRecentFiles()
		
		if 0: # Not ready yet.
			self.createRecentFilesMenuItems()
			
		lab = "Recent &Files..."
		fileMenu.AppendMenu(const(lab),lab,recentFilesMenu)
		#@nonl
		#@-node:<< create the recent files submenu >>
		#@nl
		fileMenu.AppendSeparator()
		#@<< create the read/write submenu >>
		#@+node:<< create the read/write submenu >>
		readWriteMenu = wx.wxMenu()
		
		table = [
				("&Read Outline Only","Shift+Ctrl+R",self.OnReadOutlineOnly),
				("Read @file &Nodes",None,self.OnReadAtFileNodes),
				("-",None,None),
				#("Write &Dirty @file Nodes","Shift+Ctrl+Q",self.OnWriteDirtyAtFileNodes),
				#("Write &Missing @file Nodes",None,self.OnWriteMissingAtFileNodes),
				("Write &Outline Only",None,self.OnWriteOutlineOnly),
				("&Write @file Nodes","Shift+Ctrl+W",self.OnWriteAtFileNodes)]
		
		self.createMenuEntries(readWriteMenu,table)
		
		lab = "&Read/Write..."
		fileMenu.AppendMenu(const(lab),lab,readWriteMenu)
		#@nonl
		#@-node:<< create the read/write submenu >>
		#@nl
		#@<< create the tangle submenu >>
		#@+node:<< create the tangle submenu >>
		tangleMenu = wx.wxMenu()
		
		table = (
			("Tangle &All","Shift+Ctrl+A",self.OnTangleAll),
			("Tangle &Marked","Shift+Ctrl+M",self.OnTangleMarked),
			("&Tangle","Shift+Ctrl+T",self.OnTangle))
		
		self.createMenuEntries(tangleMenu,table)
		
		lab = "&Tangle..."
		fileMenu.AppendMenu(const(lab),lab,tangleMenu)
		#@nonl
		#@-node:<< create the tangle submenu >>
		#@nl
		#@<< create the untangle submenu >>
		#@+node:<< create the untangle submenu >>
		untangleMenu = wx.wxMenu()
		
		table = (
			("Untangle &All",None,self.OnUntangleAll),
			("Untangle &Marked",None,self.OnUntangleMarked),
			("&Untangle","Shift+Ctrl+U",self.OnUntangle))
			
		self.createMenuEntries(untangleMenu,table)
		
		lab = "&Untangle..."
		fileMenu.AppendMenu(const(lab),lab,untangleMenu)
		#@nonl
		#@-node:<< create the untangle submenu >>
		#@nl
		#@<< create the import submenu >>
		#@+node:<< create the import submenu >>
		importMenu = wx.wxMenu()
		
		table = (
			#("Import To @&file","Shift+Ctrl+F",self.OnImportAtFile),
			#("Import To @&root",None,self.OnImportAtRoot),
			("Import &CWEB Files",None,self.OnImportCWEBFiles),
			("Import &noweb Files",None,self.OnImportNowebFiles))
			#("Import Flattened &Outline",None,self.OnImportFlattenedOutline))
		
		self.createMenuEntries(importMenu,table)
		
		lab = "&Import..."
		fileMenu.AppendMenu(const(lab),lab,importMenu)
		#@nonl
		#@-node:<< create the import submenu >>
		#@nl
		#@<< create the export submenu >>
		#@+node:<< create the export submenu >>
		exportMenu = wx.wxMenu()
		
		table = (
			#("Export &Headlines",None,self.OnExportHeadlines),
			#("Outline To &CWEB",None,self.OnOutlineToCWEB),
			#("Outline To &Noweb",None,self.OnOutlineToNoweb),
			("&Flatten Outline",None,self.OnFlattenOutline),)
			#("&Remove Sentinels",None,self.OnRemoveSentinels),
			#("&Weave",None,self.OnWeave)]
		
		self.createMenuEntries(exportMenu,table)
		
		lab = "&Export..."
		fileMenu.AppendMenu(const(lab),lab,exportMenu)
		#@nonl
		#@-node:<< create the export submenu >>
		#@nl
		fileMenu.AppendSeparator()
		
		# Create the last entries.
		exitTable = (("E&xit","Ctrl-Q",self.OnQuit),)
		self.createMenuEntries(fileMenu,exitTable)
		#@nonl
		#@-node:<< create the file menu >>
		#@nl
		#@	<< create the edit menu >>
		#@+node:<< create the edit menu >>
		editMenu = wx.wxMenu()
		
		#@<< create the first top-level edit entries >>
		#@+node:<< create the first top-level edit entries >>
		table = (
			("Can't Undo","Ctrl+Z",self.OnUndo,self.OnUpdateUndo), # &U reserved for Undo
			("Can't Redo","Shift+Ctrl+Z",self.OnRedo,self.OnUpdateRedo), # &R reserved for Redo
			("-",None,None),
			#("Cu&t","Ctrl+X",self.OnCutFromMenu,self.OnUpdateCut), 
			#("Cop&y","Ctrl+C",self.OnCopyFromMenu,self.OnUpdateCopy),
			#("&Paste","Ctrl+V",self.OnPasteFromMenu,self.OnUpdatePaste),
			#("&Delete",None,self.OnDelete,self.OnUpdateDelete),
			("Select &All","Ctrl+A",self.OnSelectAll,self.OnUpdateSelectAll),
			("-",None,None))
		
		self.createMenuEntries(editMenu,table)
		#@nonl
		#@-node:<< create the first top-level edit entries >>
		#@nl
		#@<< create the edit body submenu >>
		#@+node:<< create the edit body submenu >>
		editBodyMenu = wx.wxMenu()
		
		table = (
			("Extract &Section","Shift+Ctrl+E",self.OnExtractSection,self.OnUpdateExtractSection),
			("Extract &Names","Shift+Ctrl+N",self.OnExtractNames,self.OnUpdateExtractNames),
			("&Extract","Shift+Ctrl+D",self.OnExtract,self.OnUpdateExtract))
		
			#("-",None,None),
			#("Convert All B&lanks",None,self.OnConvertAllBlanks),
			#("Convert All T&abs",None,self.OnConvertAllTabs),
			#("Convert &Blanks","Shift+Ctrl+B",self.OnConvertBlanks),
			#("Convert &Tabs","Shift+Ctrl+J",self.OnConvertTabs),
			#("Insert Body Time/&Date","Shift+Ctrl+G",self.OnInsertBodyTime),
			#("&Reformat Paragraph","Shift+Ctrl+P",self.OnReformatParagraph),
			#("-",None,None),
			#("&Indent","Ctrl+]",self.OnIndent),
			#("&Unindent","Ctrl+[",self.OnDedent),
			#("&Match Brackets","Ctrl+K",self.OnFindMatchingBracket))
			
		self.createMenuEntries(editBodyMenu,table)
		
		lab = "Edit &Body..."
		editMenu.AppendMenu(const(lab),lab,editBodyMenu)
		#@nonl
		#@-node:<< create the edit body submenu >>
		#@nl
		#@<< create the edit headline submenu >>
		#@+node:<< create the edit headline submenu >>
		editHeadlineMenu = wx.wxMenu()
		
		table = (
			("Edit &Headline","Ctrl+H",self.OnEditHeadline),)
		
			#("&End Edit Headline","Escape",self.OnEndEditHeadline),
			#("&Abort Edit Headline","Shift-Escape",self.OnAbortEditHeadline),
			#("Insert Headline Time/&Date","Shift+Ctrl+H",self.OnInsertHeadlineTime))
			
			# 5/16/03 EKR: I dislike this command.
			#("Toggle Angle Brackets","Ctrl+B",self.OnToggleAngleBrackets)
			
		self.createMenuEntries(editHeadlineMenu,table)
		
		lab = "Edit &Headline..."
		editMenu.AppendMenu(const(lab),lab,editHeadlineMenu)
		
		
		#@-node:<< create the edit headline submenu >>
		#@nl
		#@<< create the find submenu >>
		#@+node:<< create the find submenu >>
		findMenu = wx.wxMenu()
		
		table = (
			("&Find Panel","Ctrl+F",self.OnFindPanel),
			("-",None,None),
			("Find &Next","F3",self.OnFindNext,self.OnUpdateFind),
			("Find &Previous","F4",self.OnFindPrevious,self.OnUpdateFind),
			("&Replace","Ctrl+=",self.OnReplace,self.OnUpdateReplace),
			("Replace, &Then Find","Ctrl+-",self.OnReplaceThenFind,self.OnUpdateReplace))
		
		self.createMenuEntries(findMenu,table)
		
		lab = "&Find..."
		editMenu.AppendMenu(const(lab),lab,findMenu)
		#@nonl
		#@-node:<< create the find submenu >>
		#@nl
		#@<< create the last top-level edit entries >>
		#@+node:<< create the last top-level edit entries >>
		if 1:
			label = "Toggle Invisibles"
		else:
			label = choose(c.tree.colorizer.showInvisibles,"Hide In&visibles","Show In&visibles")
		
		table = (
			#("&Go To Line Number","Alt+G",self.OnGoToLineNumber),
			#("&Execute Script","Alt+Shift+E",self.OnExecuteScript),
			("Set Fon&t...","Shift+Alt+T",self.OnFontPanel),
			#("Set &Colors...","Shift+Alt+C",self.OnColorPanel),
			#(label,"Alt+V",self.OnViewAllCharacters),
			#("-",None,None),
			("Prefere&nces","Ctrl+Y",self.OnPreferences))
		
		self.createMenuEntries(editMenu,table)
		#@nonl
		#@-node:<< create the last top-level edit entries >>
		#@nl
		#@nonl
		#@-node:<< create the edit menu >>
		#@nl
		#@	<< create the outline menu >>
		#@+node:<< create the outline menu >>
		outlineMenu = wx.wxMenu()
		
		#@<< create top-level outline menu >>
		#@+node:<< create top-level outline menu >>
		table = (
			("C&ut Node","Shift+Ctrl+X",self.OnCutNode,self.OnUpdateCutNode),
			("C&opy Node","Shift+Ctrl+C",self.OnCopyNode),
			("&Paste Node","Shift+Ctrl+V",self.OnPasteNode,self.OnUpdatePasteNode),
			("&Delete Node","Shift+Ctrl+BkSp",self.OnDeleteNode,self.OnUpdateDeleteNode),
			("-",None,None),
			("&Insert Node","Ctrl+I",self.OnInsertNode),
			("&Clone Node","Ctrl+`",self.OnCloneNode))
		
			# ("Sort Node",None,self.OnSortChildren,self.OnUpdateSortNode)
			# ("Sort C&hildren",None,self.OnSortChildren),
			#("&Sort Siblings","Alt-A",self.OnSortSiblings),
			#("-",None,None))
		
		self.createMenuEntries(outlineMenu,table)
		#@nonl
		#@-node:<< create top-level outline menu >>
		#@nl
		#@<< create expand/contract submenu >>
		#@+node:<< create expand/contract submenu >>
		expandMenu = wx.wxMenu()
		
		table = (
			("&Contract All","Alt+-",self.OnContractAll,self.OnUpdateContractAll),
			# ("Contract &Node","Alt+[",self.OnContractNode),
			# ("Contract &Parent","Alt+0",self.OnContractParent),
			("-",None,None),
			# ("Expand P&rev Level","Alt+.",self.OnExpandPrevLevel),
			# ("Expand N&ext Level","Alt+=",self.OnExpandNextLevel),
			# ("-",None,None),
			("Expand To Level &1","Alt+1",self.OnExpandToLevel1),
			("Expand To Level &2","Alt+2",self.OnExpandToLevel2),
			("Expand To Level &3","Alt+3",self.OnExpandToLevel3),
			("Expand To Level &4","Alt+4",self.OnExpandToLevel4),
			("Expand To Level &5","Alt+5",self.OnExpandToLevel5),
			("Expand To Level &6","Alt+6",self.OnExpandToLevel6),
			("Expand To Level &7","Alt+7",self.OnExpandToLevel7),
			("Expand To Level &8","Alt+8",self.OnExpandToLevel8),
			# ("Expand To Level &9","Alt+9",self.OnExpandToLevel9),
			("-",None,None),
			("Expand &All","Alt+9",self.OnExpandAll,self.OnUpdateExpandAll))
			#("Expand N&ode","Alt+]",self.OnExpandNode))
		
		self.createMenuEntries(expandMenu,table)
		
		lab = "&Expand/Contract..."
		outlineMenu.AppendMenu(const(lab),lab,expandMenu)
		
		if 0: # not used yet.  Maybe never.
			wx.EVT_UPDATE_UI(cExpandAllChildrenMenuItem,self.OnUpdateExpandAllChildren)
			wx.EVT_UPDATE_UI(cExpandChilrenMenuItem,self.OnUpdateExpandChildren)
			wx.EVT_UPDATE_UI(cContractAllChildrenMenuItem,self.OnUpdateContractAllChildren)
			wx.EVT_UPDATE_UI(cContractChilrenMenuItem,self.OnUpdateContractChildren)
		#@nonl
		#@-node:<< create expand/contract submenu >>
		#@nl
		#@<< create move submenu >>
		#@+node:<< create move submenu >>
		moveSelectMenu = wx.wxMenu()
		
		table = (
			("Move &Down", "Ctrl+D",self.OnMoveDown,self.OnUpdateMoveDown),
			("Move &Left", "Ctrl+L",self.OnMoveLeft,self.OnUpdateMoveLeft),
			("Move &Right","Ctrl+R",self.OnMoveRight,self.OnUpdateMoveRight),
			("Move &Up",   "Ctrl+U",self.OnMoveUp,self.OnUpdateMoveUp),
			("-",None,None),
			("&Promote","Ctrl+{",self.OnPromote,self.OnUpdatePromote),
			("&Demote", "Ctrl+}",self.OnDemote,self.OnUpdateDemote))
			
		self.createMenuEntries(moveSelectMenu,table)
		
		lab = "&Move..."
		outlineMenu.AppendMenu(const(lab),lab,moveSelectMenu)
		#@nonl
		#@-node:<< create move submenu >>
		#@nl
		#@<< create mark submenu >>
		#@+node:<< create mark submenu >>
		markMenu = wx.wxMenu()
		
		table = (
			("&Mark","Ctrl-M",self.OnMark,self.OnUpdateMark),
			("Mark &Subheads","Alt+S",self.OnMarkSubheads,self.OnUpdateMarkSubheads),
			("Mark Changed &Items","Alt+C",self.OnMarkChangedItems,self.OnUpdateMarkChangedItems),
			("Mark Changed &Roots","Alt+R",self.OnMarkChangedRoots,self.OnUpdateMarkChangedRoots),
			# ("Mark &Clones","Alt+K",self.OnMarkClones),
			("&Unmark All","Alt+U",self.OnUnmarkAll))
			
		self.createMenuEntries(markMenu,table)
		
		lab = "M&ark/Unmark..."
		outlineMenu.AppendMenu(const(lab),lab,markMenu)
		#@nonl
		#@-node:<< create mark submenu >>
		#@nl
		#@<< create goto submenu >>
		#@+node:<< create goto submenu >>
		gotoMenu = wx.wxMenu()
		
		table = (
			#("Go Back",None,self.OnGoPrevVisitedNode), # Usually use buttons for this.
			#("Go Forward",None,self.OnGoNextVisitedNode),
			#("-",None,None),
			("Go To Next &Marked","Alt+M",self.OnGoToNextMarked,self.OnUpdateGoToNextMarked),
			("Go To Next C&hanged","Alt+D",self.OnGoToNextChanged,self.OnUpdateGoToNextChanged),
			# ("Go To Next &Clone","Alt+N",self.OnGoToNextClone),
			("-",None,None),
			#("Go To &First Node","Alt+Shift+G",self.OnGoToFirstNode),
			#("Go To &Last Node","Alt+Shift+H",self.OnGoToLastNode),
			#("Go To &Parent","Alt+Shift+P",self.OnGoToParent),
			#("Go To P&rev Sibling","Alt+Shift+R",self.OnGoToPrevSibling),
			#("Go To Next &Sibling","Alt+Shift+S",self.OnGoToNextSibling),
			#("-",None,None),
			("Go To Prev V&isible","Alt-UpArrow",self.OnGoPrevVisible,self.OnUpdateGoPrevVisible),
			("Go To Next &Visible","Alt-DnArrow",self.OnGoNextVisible,self.OnUpdateGoNextVisible),
			("Go To Prev Node","Alt-Shift+UpArrow",self.OnGoBack,self.OnUpdateGoBack),
			("Go To Next Node","Alt-Shift-DnArrow",self.OnGoNext,self.OnUpdateGoNext))
			
		self.createMenuEntries(gotoMenu,table)
		
		lab = "&Go To..."
		outlineMenu.AppendMenu(const(lab),lab,gotoMenu)
		#@nonl
		#@-node:<< create goto submenu >>
		#@nl
		#@nonl
		#@-node:<< create the outline menu >>
		#@nl
		if 0: # c not created yet.
			doHook("create-optional-menus",c=c)
		#@	<< create the window menu >>
		#@+node:<< create the window menu >>
		windowMenu = wx.wxMenu()
		
		table = (
			("&Equal Sized Panes","Ctrl-E",self.OnEqualSizedPanes),
			("Toggle &Active Pane","Ctrl-T",self.OnToggleActivePane),
			# ("Toggle &Split Direction",None,self.OnToggleSplitDirection),
			("-",None,None),
			("Casca&de",None,self.OnCascade),
			("&Minimize All",None,self.OnMinimizeAll))
			
			#("-",None,None),
			#("Open &Compare Window",None,self.OnOpenCompareWindow))
		
		self.createMenuEntries(windowMenu,table)
		#@nonl
		#@-node:<< create the window menu >>
		#@nl
		#@	<< create the help menu >>
		#@+node:<< create the help menu >>
		helpMenu = wx.wxMenu()
		
		table = (
			("&About Leo...",None,self.OnAbout),)
			#("Online &Home Page",None,self.OnLeoHome),
			#("-",None,None),
			#("Open Online &Tutorial",None,self.OnLeoTutorial))
		
		self.createMenuEntries(helpMenu,table)
		
		if 0: # not ready yet.
		
			if wx.wxPlatform == '__WXMSW__':
				table = (("Open &Offline Tutorial",None,self.OnLeoHelp),)
				self.createMenuEntries(helpMenu,table)
			
			table = (
				("Open Leo&Docs.leo",None,self.OnLeoDocumentation),
				("-",None,None),
				("Open Leo&Config.leo",None,self.OnLeoConfig),
				("Apply &Settings",None,self.OnApplyConfig))
		
			self.createMenuEntries(helpMenu,table)
		#@nonl
		#@-node:<< create the help menu >>
		#@nl
		
		for menu,name in (
			(fileMenu, "&File"),
			(editMenu, "&Edit"),
			(outlineMenu, "&Outline"),
			(windowMenu, "&Window"),
			(helpMenu, "&Help")):
		
			menuBar.Append(menu,name)
			
		self.SetMenuBar(menuBar)  # attach the menu bar to the frame
		
		# app().menuWarningsGiven = true
	#@nonl
	#@-node:createMenuBar
	#@+node:createMenuEntries
	#@+at 
	#@nonl
	# The old, non-user-configurable code bound shortcuts in createMenuBar.  
	# The new user-configurable code binds shortcuts here.
	# 
	# Centralized tables of shortscuts no longer exist as they did in 
	# createAccelerators.  To check for duplicates, (possibly arising from 
	# leoConfig.txt) we add entries to a central dictionary here, and report 
	# duplicates if an entry for a canonicalized shortcut already exists.
	#@-at
	#@@c
	
	def createMenuEntries (self,menu,table,openWith=0):
		
		for data in table:
			if len(data) == 3:
				label,accel,command = data ; update_command = None
			else:
				label,accel,command,update_command = data
	
			if label == '-':
				menu.AppendSeparator()
			else:
				def callback(event,command=command):
					try: command(event)
					except: print traceback.print_exc()
		
				id = const(label)
				menu.Append(id,label,label)
				wx.EVT_MENU(self,id,callback)
				if update_command:
					self.menuIdDict[label] = id,label,update_command
					# We no longer pollute idle-time with this garbage
					# wx.EVT_UPDATE_UI(self,id,update_command)
	#@nonl
	#@-node:createMenuEntries
	#@+node:onActivate & OnSetFocus
	if wx.wxPlatform == '__WXMSW__':
		
		def onActivate(self,event):
			if event.GetActive():
				self.activeFrame = self
				if self.c:
					pass ## self.c.checkAllFileDates()
	else:
		
		def OnSetFocus(self,event):
			self.activeFrame = self
			if self.c:
				self.c.checkAllFileDates()
	#@-node:onActivate & OnSetFocus
	#@+node:onCloseLeoFrame
	def destroyAllPanels (self):
		trace() # Not used yet.  Later, this might be called from the app class.
		self.Destroy()
	
	def onCloseLeoFrame(self,event):
	
		frame = self
	
		if 1: # works.  It should be improved later...
	
			# To do: use app.closeLeoWindow so we can use app's logic.
			# We can't do this now because app.destroyWindow stupidly references frame.top.
			# And there are subtle problems that must be resolved in app.destroyWindow.
			app.windowList.remove(frame)
			if not app.windowList:
				if app.findFrame:
					app.findFrame.Destroy()
					app.findFrame = None
			
			if 0: # app should probably call a new frame.destroySelfAndIvars routine.
	
				# Can't do this before self.Destroy because the menu updaters need the ivars.
				# Can't do this after  self.Destroy because frame.clearAllIvars is gone.
				# We need to disable window updaters before destroying ivars.
				app.destroyAllWindowObjects(frame)
				
			self.Destroy() # Should be very last statement!
	
		return ## not finished yet.
	
		# Veto the close if the Frame has been changed and the user cancels.
		if  self.c.isChanged():
			veto = false
			if not mReverting:
				#@			<< Prompt for change.  Set veto if the user cancels >>
				#@+node:<< Prompt for change.  Set veto if the user cancels >>
				# Use the window title:  mFileName may not exist.
				title = self.GetTitle()
				if title and title[0] == '*':
					title = title.Mid(1)
					
				quitType = choose(self.quitting,"quitting","closing")
				message = 'Save changes to "%s" before %s?' % (title,quitType)
				dialog = wxMessageDialog(self,message,"LeoWX",wxYES_NO|wxCANCEL)
				answer = dialog.ShowModal()
				if answer == wx.wxID_YES:
					# The user want's to save the file before closing.
					if mFileName == "":
						d = wxFileDialog(
							None,"Save",
							"",# default directory
							title + ".leo",# default file
							"*.leo",# wildcard
							wxSAVE | wxOVERWRITE_PROMPT, # style of dialog.
							wxDefaultPosition)
				
						if d.ShowModal()== wxID_OK:
							paths = d.GetPaths()
							if paths.Count()== 1:
								path = paths.Item(0)
								mFileName = path
								self.SetTitle(path)
								self.c.save(path)
							else: veto = true
						else: veto = true
					else: self.c.save(mFileName)
				elif answer == wx.wxID_NO:
					pass # The user does not want to save the frame.
				elif answer == wx.wxID_CANCEL:
					pass # The user want's to cancel the close.
				else:
					veto = true
				#@nonl
				#@-node:<< Prompt for change.  Set veto if the user cancels >>
				#@nl
			if veto and event.CanVeto():
				event.Veto()# veto the close.
				return
	
		app.windowList.remove(self)
		if not app.windowList:
			#@		<< Close the permanent frames >>
			#@+node:<< Close the permanent frames >>
			if  gPrefsFrame:
				gPrefsFrame.Destroy()
				gPrefsFrame = None
			
			if app.findFrame:
				app.findFrame.Destroy()
				app.findFrame = None
				
			if wx.wxPlatform == "__WXMSW__":
				wxPythonFrame.destroy()
			#@nonl
			#@-node:<< Close the permanent frames >>
			#@nl
		# Clear the active form.  It will be set on the next activate event.
		self.activeFrame = None
		gCommands = None
		# Set all vnodes to NULL so they are not destroyed.
		if 0: #/// why shouldn't they be destroyed ??
			tree = self.tree
			v = self.c.rootVnode()
			while v:
				next = v.threadNext()
				id = v.treeID()
				assert(id)
				tree.SetItemData(id,None)
				v = next
		self.Destroy()
	#@nonl
	#@-node:onCloseLeoFrame
	#@+node:onResize
	def onResize(self,event):
	
		if mIniting:
			return # Can be called during initialization.
	
		# Resize splitter1 with equal sized panes.
		size = self.splitter1.GetClientSize()
		self.splitter1.SetClientSize(size)
		w = size.GetWidth() ; h = size.GetHeight()
		if self.splitter1.GetSplitMode()== wx.wxSPLIT_VERTICAL:
			self.splitter1.SetSashPosition(w/2,true)
		else:
			self.splitter1.SetSashPosition(h/2,true)
	
		# Resize splitter2 with equal sized panes.
		size = self.splitter2.GetClientSize()
		w = size.GetWidth() ; h = size.GetHeight()
		if self.splitter2.GetSplitMode()== wx.wxSPLIT_VERTICAL:
			self.splitter2.SetSashPosition((3*w)/5,true)
		else:
			self.splitter2.SetSashPosition((3*h)/5,true)
	#@-node:onResize
	#@+node:onBodyTextUpdated
	def onBodyTextUpdated(self,event):
	
		if self.c == None:  return
		v = self.c.currentVnode()
		if v == None: return
		
		s = self.body.GetValue()
		trace(s)
	
		return ## Not yet: sevaral calls below use tkinter or frame.top.
		
		# not yet: c.setChanged uses frame.top
		#@	<< Set the dirty bit and/or the file-changed mark if the text has changed >>
		#@+node:<< Set the dirty bit and/or the file-changed mark if the text has changed >>
		if not v.isDirty() and s != v.bodyString():
		
			v.initDirtyBit()# Avoid calling setIcon.
			if not self.c.isChanged():
				self.c.setChanged(true)
		#@nonl
		#@-node:<< Set the dirty bit and/or the file-changed mark if the text has changed >>
		#@nl
		# not yet: ses tkinter...
		v.setBodyStringOrPane(self,s)
		v.setAncestorAtFileNodeDirty()
		# Update the syntax colorer if needed.
		self.c.updateSyntaxColorer(v)
		#@	<< Update icons >>
		#@+node:<< Update icons >>
		# It is very important to eliminate flicker here.
		val = v.computeIcon()
		repaint = false
		
		if not self.c.isChanged():
			self.c.setChanged(true)
			repaint = true
		
		if val >= 0 and val != v.iconVal():
			repaint = true
			v.setIconWithVal(val)
			# Update all joined nodes.
			v2 = v.joinList()
			while v2 and v2 != v:
				v2.setIconWithVal(val)
				v2 = v2.joinList()
		
		if repaint:
			self.tree.Refresh()
		#@nonl
		#@-node:<< Update icons >>
		#@nl
	#@nonl
	#@-node:onBodyTextUpdated
	#@+node:onTreeCollapsed & onTreeExpanded
	def onTreeCollapsed(self,event):
		
		"""Prepare to collapse the tree."""
		
		# trace()
		pass # No need to redraw the tree.
	
	def onTreeExpanded (self,event):
		
		"""Redraw the tree when a tree collapses."""
	
		if not self.drawing:
			# trace()
			self.redraw()
	#@nonl
	#@-node:onTreeCollapsed & onTreeExpanded
	#@+node:onTreeCollapsing & onTreeExpanding
	def onTreeCollapsing(self,event):
		
		"""Call v.contract for a later redraw."""
	
		tree = self.tree
		id = event.GetItem()
		if id.IsOk:
			v = tree.GetItemData(id).GetData()
			if v:
				#trace(v)
				v.contract()
		
	def onTreeExpanding (self,event):
		
		"""Call v.expand for a later redraw."""
		
		tree = self.tree
		id = event.GetItem()
		if id.IsOk:
			v = tree.GetItemData(id).GetData()
			if v:
				#trace(v)
				v.expand()
	#@nonl
	#@-node:onTreeCollapsing & onTreeExpanding
	#@+node:onTreeChanged
	def onTreeChanged(self,event):
	
		c = self.c ; tree = self.tree
	 	new_id = event.GetItem()
		if new_id.IsOk():
			v = tree.GetItemData(new_id).GetData()
			# trace(v) ; es(v)
			c.selectVnode(v)
		return
		
		if self.c.mInhibitOnTreeChanged: return
		
		# N.B. Either new_id or old_id might be 0, depending on circumstances.
		new_id = event.GetItem()
		trace("new item: ", new_id)
		if not new_id.IsOk(): return
		new_v =(self.tree.GetItemData(new_id))
		if new_v == None: return
		if 0: # no longer used
			# old_id may not exist if we are activating the first node.
			old_id = event.GetOldItem()
			trace("old item: ", old_id)
			old_v = None
			if old_id.IsOk():
				old_v =(self.tree.GetItemData(old_id))
				if wx.wxPlatform == "__WXMSW__":
					assert(old_v)
	
		# Apparently in wxWindows this does _not_ fire the text changed event! But in wxGTK it does.
		# We must prevent the update event handler from messing with the old text!
		sDisableTextUpdates += 1
		if 1:
			# Clear the old text.
			self.body.Clear()
			# Put the text of the new node into the body pane.
			new_v.t().loadBodyPaneFromTnode(self.body)
			# Clear the undo stack.
			self.body.DiscardEdits()
		sDisableTextUpdates -= 1
		# Update the Commander's idea of the current node.
		self.c.mCurrentVnode = new_v
		# Update the syntax colorer if needed.
		self.c.updateSyntaxColorer(new_v)
	
	#@-node:onTreeChanged
	#@+node:onTreeChanging
	def onTreeChanging(self,event):
		
		"""Event handler gets called whenever a new node gets selected"""
	
		# trace()
		pass
	#@nonl
	#@-node:onTreeChanging
	#@+node:onTreeBeginLabelEdit
	# Editing is allowed only if this routine exists.
	
	def onTreeBeginLabelEdit(self,event):
	
		# Disallow editing of the dummy root node.
		id = event.GetItem()
		if id == self.root_id:
			event.Veto()
	#@nonl
	#@-node:onTreeBeginLabelEdit
	#@+node:onTreeEndLabelEdit
	# Editing will be allowed only if this routine exists.
	
	def onTreeEndLabelEdit(self,event):
	
		tree = self.tree
		s = event.GetLabel()
		id = event.GetItem()
		v = tree.GetItemData(id).GetData()
		trace(id,s)
	
		return # Not yet: c.setChanged uses frame.top.
	
		# Set the dirty bit and the file-changed mark if the headline has changed.
		if not v.isDirty()and s != v.headString():
			v.setDirty()
			if not self.c.isChanged():
				self.c.setChanged(true)
	
		# Update all joined headlines.
		j = v.joinList()
		while j != v:
			j.setHeadString(s)
			j = j.joinList()
	#@nonl
	#@-node:onTreeEndLabelEdit
	#@+node:onTreeKeyDown
	def onTreeKeyDown(self,event):
		
		trace()
		pass # Probably we don't need to do anything until the end-edit event.
	#@nonl
	#@-node:onTreeKeyDown
	#@+node:onTreeBeginDrag
	def onTreeBeginDrag(self,event):
	
		trace() ; return
	
		if event.GetItem()!= self.tree.GetRootItem():
			mDraggedItem = event.GetItem()
			event.Allow()
	#@-node:onTreeBeginDrag
	#@+node:onTreeEndDrag
	def onTreeEndDrag(self,event):
		
		trace() ; return
	
		#@	<< Define onTreeEndDrag vars >>
		#@+node:<< Define onTreeEndDrag vars >>
		assert(self.tree)
		assert(self.c)
		
		dst = event.GetItem()
		src = mDraggedItem
		mDraggedItem = 0
		
		if not dst.IsOk() or not src.IsOk():
			return
		
		src_v = self.tree.GetItemData(src)
		if src_v == None:
			return
		
		dst_v =self.tree.GetItemData(dst)
		if dst_v == None:
			return
		
		parent = self.tree.GetParent(dst)
		parent_v = None
		#@nonl
		#@-node:<< Define onTreeEndDrag vars >>
		#@nl
		if  src == 0 or dst == 0:  return
		cookie = None
		if (
			# dst is the root
			not parent.IsOk()or
			# dst has visible children and dst isn't the first child.
			self.tree.ItemHasChildren(dst)and self.tree.IsExpanded(dst)and
			self.tree.GetFirstChild(dst,cookie) != src or
			# back(src)== dst(would otherwise be a do-nothing)
			self.tree.GetPrevSibling(src) == dst):
			#@		<< Insert src as the first child of dst >>
			#@+node:<< Insert src as the first child of dst >>
			# Make sure the drag will be valid.
			parent_v = self.tree.GetItemData(dst)
			
			if not self.c.checkMoveWithParentWithWarning(src_v,parent_v,true):
				return
			
			src_v.moveToNthChildOf(dst_v,0)
			#@nonl
			#@-node:<< Insert src as the first child of dst >>
			#@nl
		else:
			# Not the root and no visible children.
			#@		<< Insert src after dst >>
			#@+node:<< Insert src after dst >>
			# Do nothing if dst is a child of src.
			p = parent
			while p.IsOk():
				if p == src:
					return
				p = self.tree.GetParent(p)
			
			# Do nothing if dst is joined to src.
			if dst_v.isJoinedTo(src_v):
				return
			
			# Make sure the drag will be valid.
			parent_v = self.tree.GetItemData(parent)
			if not self.c.checkMoveWithParentWithWarning(src_v,parent_v,true):
				return
			
			src_v.moveAfter(dst_v)
			#@nonl
			#@-node:<< Insert src after dst >>
			#@nl
		self.c.selectVnode(src_v)
		self.c.setChanged(true)
	#@-node:onTreeEndDrag
	#@+node:Notifications: probably will never be called
	if 0:# Notifications... We probably will never see these.
		def onBodyChanged(self,*args,**keys): trace() #  return self.tree.onBodyChanged(*args,**keys)
		def onHeadChanged(self,*args,**keys): trace() #  return self.tree.onHeadChanged(*args,**keys)
		def OnHeadlineKey(self,v,event):      trace(v) #  return self.tree.OnHeadlineKey(v,event)
		def idle_head_key(self,v):            trace(v) #  return self.tree.idle_head_key(v)
		
	# Editing... These can remain do-nothings.
	def editLabel(self,v):           pass
	def editVnode(self):             pass
	def endEditLabel(self):          pass
	def setEditVnode(self,v):        trace() #  self.tree.editVnode = v
	def setNormalLabelState(self,v): pass
	#@nonl
	#@-node:Notifications: probably will never be called
	#@+node:Vnode callbacks: probably will never be called
	# vnode callbacks: to be removed.
	if 0: # These will never be called, because the events are never generated.
		def OnBoxClick(self,v):              trace() #  return self.tree.OnBoxClick(v)
		def OnIconClick(self,v,event):       trace() #  return self.tree.OnIconClick(v,event)
		def OnIconDoubleClick(self,v,event): trace() #  return self.tree.OnIconDoubleClick(v,event)
		def OnIconRightClick(self,v,event):  trace() #  return self.tree.OnIconRightClick(v,event)
		def OnDrag(self,v,event):            trace() #  return self.tree.OnDrag(v,event)
		def OnEndDrag(self,v,event):         trace() #  return self.tree.OnEndDrag(v,event)
		def OnPopup(self,v,event):           trace() #  return self.tree.OnPopup(v,event)
	#@nonl
	#@-node:Vnode callbacks: probably will never be called
	#@+node: dummy routines: not ready yet
	def after_idle(*args): trace()
	
	def createOpenWithMenuFromTable (self,table): trace()
	def getMenu (self,name): trace(name)
	def resizePanesToRatio(self,ratio1,ratio2): trace(ratio1,ratio2)
	def setInitialWindowGeometry (self): trace()
	def setTopGeometry(self,geom): trace(geom)
	def updateRecentFiles(self,fileName): trace(fileName)
	
	# Wrappers for tk calls...
	
	def lift (self):   trace()
	def update (self): trace()
	
	def FindFocus(self): return self.body # Kludge.
	#@nonl
	#@-node: dummy routines: not ready yet
	#@+node:deiconify
	def deiconify (self):
		self.Iconize(false)
	#@nonl
	#@-node:deiconify
	#@+node:getTitle
	def getTitle (self):
		
		return self.title
	#@-node:getTitle
	#@+node:put & putnl
	def put (self,s,color=None):
		if self.log:
			self.log.AppendText(s)
		print s
	
	def putnl (self):
		print
		if self.log:
			self.log.AppendText('\n')
	#@nonl
	#@-node:put & putnl
	#@+node:select
	def select(self,v,updateBeadList=true):
		
		if v:
			self.mCurrentVnode = v
			#### What to do about updateBeadList ????
			trace("wxLeoFrame",v) #  return self.tree.select(v,updateBeadList)
	#@-node:select
	#@+node:Interface with the tree class
	if 1: # Most important...
	
		def drawIcon(self,v,x,y): trace(v) #  return self.tree.drawIcon(v,x,y)
		
		def setTreeIniting(self,flag):
			self.treeIniting = flag
	
		# Scrolling... 
		def scrollTo(self,v):  trace() #  return self.tree.scrollTo(v)
		def idle_scrollTo(self,v):  trace(v) #  return self.tree.idle_scrollTo(v)
	
	# Coloring...
	def getColorizer(self):           trace() # return self.tree.colorizer
	def recolor_now(self,v):          trace() # return self.tree.recolor_now(v)
	def recolor_range(self,v,leading,trailing):  trace() #  return self.tree.recolor_range(v,leading,trailing)
	def recolor(self,v):              trace() #  return self.tree.recolor(v)
	def updateSyntaxColorer(self,v):  trace() #  return self.tree.colorizer.updateSyntaxColorer(v)
	
	# Focus...
	def focus_get(self): trace() #  return self.tree.canvas.focus_get()
	
	# Fonts...
	def getFont(self):      return self.tree.getFont()
	def setFont(self,font): return self.tree.setFont(font)
	
	# OnHeadlineClick
	# OnHeadlineRightClick
	def OnActivateHeadline(self,v): trace() #  return self.tree.OnActivate(v)
	
	# Others...
	def expandAllAncestors(self,v): trace() #  return self.tree.expandAllAncestors(v)
	def getEditTextDict(self,v):    trace() #  return self.tree.edit_text_dict.get(v)
	#@nonl
	#@-node:Interface with the tree class
	#@+node:beginUpdate
	def beginUpdate (self):
	
		self.updateCount += 1
	#@nonl
	#@-node:beginUpdate
	#@+node:endUpdate
	def endUpdate (self,flag=true):
	
		assert(self.updateCount > 0)
	
		self.updateCount -= 1
		if flag and self.updateCount == 0:
			self.redraw()
	#@nonl
	#@-node:endUpdate
	#@+node:Getters
	def currentVnode(self):
		return self.mCurrentVnode
	
	def dragging(self):
		return self.mDragging
		
	def rootVnode(self):
		return self.mRootVnode
	
	def topVnode(self):
		return self.mTopVnode
	#@nonl
	#@-node:Getters
	#@+node:redraw & redraw_now
	def redraw (self):
	
		# trace(self.drawing)
		self.drawing = true # Tell event handlers not to call us.
	
		c = self.c ; tree = self.tree
		if c is None: return
		v = c.rootVnode()
		if v is None: return
	
		tree.DeleteAllItems()
		self.root_id = root_id = tree.AddRoot("Leo Outline Pane")
		while v:
			self.redraw_subtree(root_id,v)
			v = v.next()
		tree.Expand(root_id)
		
		self.drawing = false
			
	def redraw_now(self):
		trace()
		self.redraw()
	#@nonl
	#@-node:redraw & redraw_now
	#@+node:redraw_node
	def redraw_node(self,parent_id,v):
		
		# trace(v)
		tree = self.tree
		data = wx.wxTreeItemData(v)
		id = tree.AppendItem(parent_id,v.headString(),data=data)
		v.wxTreeId = id # Inject the ivar into the vnode.
		assert (v == tree.GetItemData(id).GetData())
		return id
		
	#@nonl
	#@-node:redraw_node
	#@+node:redraw_subtree
	def redraw_subtree(self,parent_id,v):
		
		# trace(v)
		tree = self.tree
		id = self.redraw_node(parent_id,v)
		child = v.firstChild()
		
		if v.isExpanded():
			while child:
				self.redraw_subtree(id,child)
				child = child.next()
			tree.Expand(id)
		else:
			if 1: # tree.SetItemHasChildren changes the event handler logic.  So this is good enough.
				while child:
					self.redraw_node(id,child)
					child = child.next()
			else:
				if child:
					tree.SetItemHasChildren(id)
			tree.Collapse(id)
	#@nonl
	#@-node:redraw_subtree
	#@+node:Setters
	def setRootVnode(self,v):
		
		# trace(v)
		if v:
			self.mRootVnode = v
		
	def setCurrentVnode(self,v):
		
		# trace(v)
		if v:
			self.mCurrentVnode = v
	#@nonl
	#@-node:Setters
	#@+node:updateAllMenus
	def updateAllMenus(self,event):
		
		"""Called whenever any menu is pulled down."""
		
		for id,label,update_command in self.menuIdDict.values():
	
			item = self.menuBar.FindItemById(id)
			try:
				self.updateMenuItem = item # optional param
				val = update_command()
				val = choose(val,1,0)
				item.Enable(val)
				# trace(id,bool(val),item.GetLabel())
			except:
				traceback.print_exc()
				val = true
	#@nonl
	#@-node:updateAllMenus
	#@+node:OnUpdateRevert
	def OnUpdateRevert(self):
		
		return self.c.canRevert()
	#@-node:OnUpdateRevert
	#@+node:OnUpdateCopy
	def OnUpdateCopy(self):
	
		w = self.FindFocus()
		if w and w == self.body:
			return self.body.CanCopy()
		elif w and w == self.log:
			return self.log.CanCopy()
		else:
			return false
	#@nonl
	#@-node:OnUpdateCopy
	#@+node:OnUpdateCut
	def OnUpdateCut(self):
	
		w = self.FindFocus()
		if w and w == self.body:
			return self.body.CanCut()
		elif w and w == mLogCtrl:
			return self.log.CanCut()
		else:
			return false
	#@-node:OnUpdateCut
	#@+node:OnUpdateDelete
	def OnUpdateDelete(self):
		
		return self.body.CanCut()
	#@nonl
	#@-node:OnUpdateDelete
	#@+node:OnUpdateExtract
	def OnUpdateExtract(self):
		
		return true
		
		# c.canExtract calls tk routines.
		# return self.c.canExtract()
	#@-node:OnUpdateExtract
	#@+node:OnUpdateExtractNames
	def OnUpdateExtractNames(self):
		
		return true
		
		# c.canExtractSectionNames calls tk routines.
		# return self.c.canExtractSectionNames()
	#@nonl
	#@-node:OnUpdateExtractNames
	#@+node:OnUpdateExtractSection
	def OnUpdateExtractSection(self):
		
		return true
		
		# c.canExtractSection calls tk routines.
		# return self.c.canExtractSection()
	
	#@-node:OnUpdateExtractSection
	#@+node:OnUpdateFind
	def OnUpdateFind(self):
	
		return true
	
		# return find_text.Length()> 0
	#@-node:OnUpdateFind
	#@+node:OnUpdatePaste
	def OnUpdatePaste(self):
	
		if wx.wxPlatform == "__WXMSW__": # apparent bug.
			return true
		else:
			w = self.FindFocus()
			if w and w == self.body:
				return self.body.CanPaste()
			elif w and w == mLogCtrl:
				return self.log.CanPaste()
			else:
				return false
	#@nonl
	#@-node:OnUpdatePaste
	#@+node:OnUpdateRedo
	def OnUpdateRedo(self):
	
		# The Tree view does not support redo.
		if wx.wxPlatform == "__WXGTK__": # text control does not support undo/redo on wxGTK
			return false
		else:
			return self.body.CanRedo()
		
	#@-node:OnUpdateRedo
	#@+node:OnUpdateReplace
	def OnUpdateReplace(self):
		
		return true
	
		# event.Enable(self.c.changeIsEnabled()
	#@nonl
	#@-node:OnUpdateReplace
	#@+node:OnUpdateSelectAll
	def OnUpdateSelectAll(self):
		
		w = self.FindFocus()
		return w and (w == self.body or w == self.log)
	#@-node:OnUpdateSelectAll
	#@+node:OnUpdateUndo
	def OnUpdateUndo(self):
		
		w = self.FindFocus()
		enabled = true
		
		if 0: # not ready yet.
			enabled = false
			
			# FindFocus seems to be a bit flakey,so use it only when absolutely needed.
			if  w == self.tree:
				enabled = self.c.canUndo()
			else:
				# Don't use FindFocus.
				if wx.wxPlatform == "__WXGTK__": # text control does not support undo/redo on wxGTK
					enabled = false
				else:
					enabled = self.body.CanUndo()
	
		return enabled
	#@nonl
	#@-node:OnUpdateUndo
	#@+node:hasSelection
	def hasSelection(self,void):
	
		if self.body:
			start,end = self.body.GetSelection()
			return start != end
		else:
			return false
	#@nonl
	#@-node:hasSelection
	#@+node:OnUpdateContractAll
	def OnUpdateContractAll(self):
	
		return self.c.canContractAllHeadlines()
	#@-node:OnUpdateContractAll
	#@+node:OnUpdateContractAllChildren
	def OnUpdateContractAllChildren(self):
		
		return self.c.canContractAllSubheads()
	
	#@-node:OnUpdateContractAllChildren
	#@+node:OnUpdateContractChildren
	def OnUpdateContractChildren(self):
		
		return self.c.canContractSubheads()
	#@-node:OnUpdateContractChildren
	#@+node:OnUpdateCutNode
	def OnUpdateCutNode(self):
		
		return self.c.canCutOutline()
	#@-node:OnUpdateCutNode
	#@+node:OnUpdateDeleteNode
	def OnUpdateDeleteNode(self):
		
		return self.c.canDeleteHeadline()
	#@-node:OnUpdateDeleteNode
	#@+node:OnUpdateDemote
	def OnUpdateDemote(self):
		
		return self.c.canDemote()
	#@-node:OnUpdateDemote
	#@+node:OnUpdateExpandAll
	def OnUpdateExpandAll(self):
		
		return self.c.canExpandAllHeadlines()
	
	#@-node:OnUpdateExpandAll
	#@+node:OnUpdateExpandAllChildren
	def OnUpdateExpandAllChildren(self):
	
		return self.c.canExpandAllSubheads()
	#@-node:OnUpdateExpandAllChildren
	#@+node:OnUpdateExpandChildren
	def OnUpdateExpandChildren(self):
	
		return self.c.canExpandAllSubheads()
	#@-node:OnUpdateExpandChildren
	#@+node:OnUpdateGoBack
	def OnUpdateGoBack(self):
	
		return self.c.canSelectThreadBack()
	#@-node:OnUpdateGoBack
	#@+node:OnUpdateGoNext
	def OnUpdateGoNext(self):
	
		return self.c.canSelectThreadNext()
	#@-node:OnUpdateGoNext
	#@+node:OnUpdateGoNextVisible
	def OnUpdateGoNextVisible(self):
	
		return self.c.canSelectVisNext()
	#@-node:OnUpdateGoNextVisible
	#@+node:OnUpdateGoPrevVisible
	def OnUpdateGoPrevVisible(self):
	
		return self.c.canSelectVisBack()
	#@-node:OnUpdateGoPrevVisible
	#@+node:OnUpdateGoToNextChanged
	def OnUpdateGoToNextChanged(self):
	
		return self.c.canGoToNextDirtyHeadline()
	#@-node:OnUpdateGoToNextChanged
	#@+node:OnUpdateGoToNextMarked
	def OnUpdateGoToNextMarked(self):
	
		return self.c.canGoToNextMarkedHeadline()
	#@-node:OnUpdateGoToNextMarked
	#@+node:OnUpdateMark
	def OnUpdateMark(self):
		
		v = self.c.currentVnode()
		s = choose(v and v.isMarked(),"Unmark","Mark")
		self.updateMenuItem.SetText(s)
	#@nonl
	#@-node:OnUpdateMark
	#@+node:OnUpdateMarkChangedItems
	def OnUpdateMarkChangedItems(self):
	
		return self.c.canMarkChangedHeadlines()
	#@-node:OnUpdateMarkChangedItems
	#@+node:OnUpdateMarkChangedRoots
	def OnUpdateMarkChangedRoots(self):
	
		return self.c.canMarkChangedRoots()
	#@-node:OnUpdateMarkChangedRoots
	#@+node:OnUpdateMarkSubheads
	def OnUpdateMarkSubheads(self):
	
		v = self.c.currentVnode()
		return v and v.hasChildren()
	#@-node:OnUpdateMarkSubheads
	#@+node:OnUpdateMoveDown
	def OnUpdateMoveDown(self):
	
		return self.c.canMoveOutlineDown()
	#@-node:OnUpdateMoveDown
	#@+node:OnUpdateMoveLeft
	def OnUpdateMoveLeft(self):
	
		return self.c.canMoveOutlineLeft()
	#@-node:OnUpdateMoveLeft
	#@+node:OnUpdateMoveRight
	def OnUpdateMoveRight(self):
	
		return self.c.canMoveOutlineRight()
	#@-node:OnUpdateMoveRight
	#@+node:OnUpdateMoveUp
	def OnUpdateMoveUp(self):
	
		return self.c.canMoveOutlineUp()
	#@-node:OnUpdateMoveUp
	#@+node:OnUpdatePasteNode
	def OnUpdatePasteNode(self):
	
		return self.c.canPasteOutline()
	#@-node:OnUpdatePasteNode
	#@+node:OnUpdatePromote
	def OnUpdatePromote(self):
	
		return self.c.canPromote()
	#@-node:OnUpdatePromote
	#@+node:OnUpdateSortNode
	def OnUpdateSortNode(self):
	
		return self.c.canSort()
	#@-node:OnUpdateSortNode
	#@+node:OnNew
	def OnNew(self,event):
		
		c,frame = app.gui.newLeoCommanderAndFrame(fileName=None)
		doHook("new",old_c=self,new_c=c)
	
		frame.setInitialWindowGeometry()
		frame.deiconify()
		frame.lift()
		frame.resizePanesToRatio(frame.ratio,frame.secondary_ratio)
		
		c.beginUpdate()
		t = leoNodes.tnode()
		v = leoNodes.vnode(c,t)
		v.initHeadString("NewHeadline")
		v.moveToRoot()
		c.editVnode(v)
		c.endUpdate()
		
		set_focus(c,frame.body)
	#@nonl
	#@-node:OnNew
	#@+node:OnOpen
	def OnOpen(self,event):
	
		# Create the Open dialog.
		d = wx.wxFileDialog(
			None,"Choose a Leo file",
			"",# default directory
			"",# default file
			"*.leo",# wildcard
			wx.wxOPEN | wx.wxMULTIPLE, # style of dialog.
			wx.wxDefaultPosition)
	
		if d.ShowModal()== wx.wxID_OK:
			for path in d.GetPaths():
				openWithFileName(path)
	#@nonl
	#@-node:OnOpen
	#@+node:OnClose
	def OnClose(self,event):
	
		# Close the frame,giving the close handler a chance to veto.
		self.Close()
	#@-node:OnClose
	#@+node:OnSave
	# Most of this code is common code.  Only the dialog stuff is unique to wx.
	
	def OnSave(self,event):
		
		c = self.commands
	
		if c.mFileName:
			c.fileCommands.save(c.mFileName)
			c.setChanged(false)
			return
		else:
			c.mFileName = ""
	
		d = wx.wxFileDialog(None,"Save",
			(""),        # default directory
			c.mFileName, # default file
			("*.leo"),   # wildcard
			wx.wxSAVE | wx.wxOVERWRITE_PROMPT,
			wx.wxDefaultPosition)
			
		# Tk allows the following params...
			# filetypes=[("Leo files", "*.leo")],
			# defaultextension=".leo")
	
		if d.ShowModal()== wxID_OK:
			fileName = d.GetPath()
			if fileName > 0:
				c.mFileName = ensure_extension(fileName, ".leo")
				self.title = c.mFileName
				self.SetLabel(computeWindowTitle(c.mFileName))
				c.fileCommands.save(c.mFileName)
				self.updateRecentFiles(c.mFileName)
	#@nonl
	#@-node:OnSave
	#@+node:OnSaveAs
	def OnSaveAs(self,event):
			
		c = self.commands
	
		# Make sure we never pass None to the ctor.
		if not c.mFileName:
			c.mFileName = ""
			
		d = wx.wxFileDialog(None,"Save As",
			(""),      # default directory
			c.mFileName, # default file
			("*.leo"), # wildcard
			wx.wxSAVE | wx.wxOVERWRITE_PROMPT,
			wx.wxDefaultPosition)
	
		if d.ShowModal()== wx.wxID_OK:
			fileName = d.GetPath()
			if fileName:
				c.mFileName = ensure_extension(fileName, ".leo")
				self.title = c.mFileName
				self.SetLabel(computeWindowTitle(c.mFileName))
				self.commands.fileCommands.saveAs(c.mFileName)
				self.updateRecentFiles(c.mFileName)
	#@nonl
	#@-node:OnSaveAs
	#@+node:OnSaveTo
	def OnSaveTo(self,event):
	
		c = self.commands
	
		# Make sure we never pass None to the ctor.
		if not c.mFileName:
			c.mFileName = ""
			
		d = wx.wxFileDialog(None,"Save To",
			(""),        # default directory
			c.mFileName, # default file
			("*.leo"),   # wildcard
			wx.wxSAVE | wx.wxOVERWRITE_PROMPT,
			wx.wxDefaultPosition)
	
		if d.ShowModal()== wx.wxID_OK:
			fileName = d.GetPath()
			if fileName:
				fileName = ensure_extension(fileName, ".leo")
				self.commands.fileCommands.saveTo(fileName)
				self.updateRecentFiles(c.mFileName)
	#@nonl
	#@-node:OnSaveTo
	#@+node:OnRevert
	def OnRevert(self,event):
		
		c = self.c ; fileName = c.mFileName
	
		# Make sure the user wants to Revert.
		prompt = "Revert to previous version of %s?" % fileName
		answer = wx.wxMessageBox(prompt,"Revert to saved?", wx.wxYES_NO)
		if answer == wx.wxNO: return
		
		# Kludge: rename this frame so OpenWithFileName won't think it is open.
		c.mFileName = ""
	
		# Create a new frame before deleting this frame.
		frame = openWithFileName(fileName)
	
		# Delete the form.
		self.reverting = true  # Indicate that no prompt is needed.
		self.Close()
		self.reverting = false
	
		# Bring the already-opened frame to the front.
		frame.Show(false)
		frame.Show(true)
	#@-node:OnRevert
	#@+node:OnPageSetup
	def OnPageSetup(self,event):
		pass
	#@-node:OnPageSetup
	#@+node:OnPrint
	def OnPrint(self,event):
		pass
	#@-node:OnPrint
	#@+node:OnTangleSubmenu
	def OnTangleSubmenu(self,event):
		pass
	#@nonl
	#@-node:OnTangleSubmenu
	#@+node:OnUntangleSubmenu
	def OnUntangleSubmenu(self,event):
		pass
	#@nonl
	#@-node:OnUntangleSubmenu
	#@+node:OnImportExportSubmenu
	def OnImportExportSubmenu(self,event):
		pass
	#@nonl
	#@-node:OnImportExportSubmenu
	#@+node:OnQuit
	def OnQuit(self,event):
	
		self.quitting = true
	
		# Closing all windows terminates Leo.  Stop if the user aborts.
		while app.windowList:
			w = app.windowList[0]
			if not w.Close():
				break # User cancelled a close.
	
		self.quitting = false
	#@nonl
	#@-node:OnQuit
	#@+node:OnReadOutlineOnly
	def OnReadOutlineOnly(self,event):
	
		d = wxFileDialog(
			None,"Choose a Leo file",
			"",# default directory
			"",# default file
			"*.leo",# wildcard
			wxOPEN | wxMULTIPLE, # style of dialog.
			wxDefaultPosition)
	
		if d.ShowModal()== wxID_OK:
			paths = d.GetPaths(paths)
			count = paths.Count()
			for i in xrange(count):
				self.readOutlineOnly(paths.Item(i))
	#@-node:OnReadOutlineOnly
	#@+node:readOutlineOnly
	def readOutlineOnly(self,fileName):
	
		# Don't take an exception if the file doesn't exist.
		if not os.path.exists(fileName):
			es("Can not open: " + fileName)
			return
		try:
			frame = LeoFrame()
			frame.self.c.readOutlineOnly(fileName)
			frame.Show(true)
			frame.c.fileName = fileName
			self.activeFrame = frame
		except:
			es("Error opening: " + fileName)
	#@-node:readOutlineOnly
	#@+node:OnReadAtFileNodes
	def OnReadAtFileNodes(self,event):
		self.c.readAtFileNodes()
	#@-node:OnReadAtFileNodes
	#@+node:OnWriteOutlineOnly
	def OnWriteOutlineOnly(self,event):
		self.c.writeOutlineOnly()
	#@-node:OnWriteOutlineOnly
	#@+node:OnWriteAtFileNodes
	def OnWriteAtFileNodes(self,event):
		self.c.writeAtFileNodes()
	#@-node:OnWriteAtFileNodes
	#@+node:OnTangleAll
	def OnTangleAll(self,event):
		self.c.tangleAll()
	#@-node:OnTangleAll
	#@+node:OnTangleMarked
	def OnTangleMarked(self,event):
		self.c.tangleMarked()
	#@-node:OnTangleMarked
	#@+node:OnTangle
	def OnTangle(self,event):
		self.c.tangle()
	#@-node:OnTangle
	#@+node:OnUntangleAll
	def OnUntangleAll(self,event):
		self.c.untangleAll()
	#@-node:OnUntangleAll
	#@+node:OnUntangleMarked
	def OnUntangleMarked(self,event):
		self.c.untangleMarked()
	#@-node:OnUntangleMarked
	#@+node:OnUntangle
	def OnUntangle(self,event):
		self.c.untangle()
	#@-node:OnUntangle
	#@+node:OnImportFiles
	def OnImportFiles(self,event):
	
		d = wxFileDialog(
			None,"Import Files",
			"",# default directory
			"",# default file
			"*.*",# wildcard
			wxOPEN | wxMULTIPLE | wxFILE_MUST_EXIST, # style of dialog.
			wxDefaultPosition)
	
		if d.ShowModal()== wxID_OK:
			paths = d.GetPaths(paths)
			self.c.ImportFilesCommand(paths)
	#@-node:OnImportFiles
	#@+node:OnImportCWEBFiles
	def OnImportCWEBFiles(self,event):
		
		d = wxFileDialog(
			None,"Import CWEB Files",
			"",# default directory
			"",# default file
			"*.*",# wildcard
			wxOPEN | wxMULTIPLE | wxFILE_MUST_EXIST, # style of dialog.
			wxDefaultPosition)
	
		if d.ShowModal()== wxID_OK:
			paths = d.GetPaths(paths)
			self.c.CWEBToOutlineCommand(paths)
	#@-node:OnImportCWEBFiles
	#@+node:OnImportNowebFiles
	def OnImportNowebFiles(self,event):
		pass
	#@-node:OnImportNowebFiles
	#@+node:OnImportMoreText
	def OnImportMoreText(self,event):
	
		d = wxFileDialog(
			None,"Import MORE Text",
			"",# default directory
			"",# default file
			"*.*",# wildcard
			wxOPEN | wxFILE_MUST_EXIST, # style of dialog.
			wxDefaultPosition)
	
		if d.ShowModal()== wxID_OK:
			paths = d.GetPaths(paths)
			self.c.importMoreText(paths)
	#@-node:OnImportMoreText
	#@+node:OnFlattenOutline
	def OnFlattenOutline(self,event):
	
		d = wxFileDialog(
			None,"Flatten Outline",
			"",# default directory
			"flat.txt",# default file
			"*.*",# wildcard
			wxSAVE | wxOVERWRITE_PROMPT, # style of dialog.
			wxDefaultPosition)
	
		if d.ShowModal()== wxID_OK:
			paths = d.GetPaths(paths)
			self.c.flattenOutline(paths)
	#@-node:OnFlattenOutline
	#@+node:OnUndo
	def OnUndo(self,event):
		
		w = self.FindFocus()
		# FindFocus seems to be a bit flakey,so use it only when absolutely needed.
		if w == self.tree:
			self.c.undo()
		elif wx.wxPlatform != "__WXGTK__": # text control does not support undo/redo on wxGTK
			if self.body and self.body.CanUndo():
				self.body.Undo()
	#@-node:OnUndo
	#@+node:OnRedo
	def OnRedo(self,event):
		
		# The tree control does not support redo.
		if wx.wxPlatform != "__WXGTK__": # text control does not support undo/redo on wxGTK
			if  self.body and self.body.CanRedo():
				self.body.Redo()
	#@nonl
	#@-node:OnRedo
	#@+node:OnCut
	def OnCut(self,event):
		w = self.FindFocus()
		if w and w == self.body:
			self.body. Cut()
		elif w and w == mLogCtrl:
			mLogCtrl. Cut()
	#@-node:OnCut
	#@+node:OnCopy
	def OnCopy(self,event):
		w = self.FindFocus()
		if w and w == self.body:
			self.body. Copy()
		elif w and w == mLogCtrl:
			mLogCtrl. Copy()
	#@-node:OnCopy
	#@+node:OnPaste
	def OnPaste(self,event):
		w = self.FindFocus()
		if w and w == self.body:
			self.body. Paste()
		elif w and w == mLogCtrl:
			mLogCtrl. Paste()
	#@-node:OnPaste
	#@+node:OnDelete
	def OnDelete(self,event):
	
		if self.body:
			start,end = self.body.GetSelection()
			if start < end:
				self.body.Remove(start,end)
			else:
				self.body.Remove(end,start)
	#@-node:OnDelete
	#@+node:OnSelectAll
	def OnSelectAll(self,event):
		w = self.FindFocus()
		if w == self.body:
			to = self.body.GetLastPosition()
			self.body.SetSelection(0,to)
		elif w == mLogCtrl:
			to = mLogCtrl.GetLastPosition()
			mLogCtrl.SetSelection(0,to)
	#@-node:OnSelectAll
	#@+node:OnEditHeadline
	def OnEditHeadline(self,event):
	
		if wx.wxPlatform != "__WXMSW__": # EditLabel is buggy.  Hitting a control key or tab will crash.
			item = self.tree.GetSelection()
			if item:
				self.tree.EditLabel(item)
	#@nonl
	#@-node:OnEditHeadline
	#@+node:OnFontPanel
	def OnFontPanel(self,event):
	
		data = None
		data.SetInitialFont(self.body.GetFont())
		data.SetColour(self.body.GetForegroundColour())
		dialog = wxFontDialog(self,data)
		if wx.wxPlatform != "__WXGTK__": # Causes problems on GTK+ version of wxWindows.
			dialog.CentreOnScreen()
		if dialog.ShowModal()!= wxID_OK: return
		retData = dialog.GetFontData()
		font = retData.GetChosenFont()
		color = retData.GetColour()
		# On Linux, SetFont apparently clears the text control's text string!
		if wx.wxPlatform == "__WXGTK__":
			contents = self.body.GetValue()
			self.body.SetFont(font)
			self.body.SetForegroundColour(color)
			self.body.SetValue(contents)
		else:
			self.body.SetFont(font)
			self.body.SetForegroundColour(color)
		self.Refresh()
		trace("font_info:face: %s, family: %s\nsize: %d, style: %s, weight: %s" %
			(font.GetFaceName(), font.GetFamilyString(),
			font.GetPointSize(), font.GetStyleString(), font.GetWeightString()))
	#@nonl
	#@-node:OnFontPanel
	#@+node:OnSyntaxColoring
	def OnSyntaxColoring(self,event):
		pass
	#@-node:OnSyntaxColoring
	#@+node:OnPreferences
	def OnPreferences(self,event):
	
		if gPrefsFrame == None:
			gPrefsFrame = PrefsFrame()
			gPrefsFrame.initialize()
		gPrefsFrame.CenterOnScreen()
		gPrefsFrame.Show(true)
		gPrefsFrame.Raise()
	#@-node:OnPreferences
	#@+node:OnConvertBlanks
	def OnConvertBlanks(self,event):
		self.c.convertBlanks()
	#@-node:OnConvertBlanks
	#@+node:OnExtractSection
	def OnExtractSection(self,event):
		self.c.extractSection()
	#@-node:OnExtractSection
	#@+node:OnExtractNames
	def OnExtractNames(self,event):
		self.c.extractSectionNames()
	#@-node:OnExtractNames
	#@+node:OnExtract
	def OnExtract(self,event):
		self.c.extract()
	#@-node:OnExtract
	#@+node:OnFindPanel
	def OnFindPanel(self,event):
	
		# On windows,this activates the frame.
		app.findFrame.Show()
		app.findFrame.Raise()
	#@-node:OnFindPanel
	#@+node:OnFindNext
	def OnFindNext(self,event):
		self.c.doFindNextCommand()
	#@-node:OnFindNext
	#@+node:OnFindPrevious
	def OnFindPrevious(self,event):
		self.c.doFindPreviousCommand()
	#@-node:OnFindPrevious
	#@+node:OnReplace
	def OnReplace(self,event):
		self.c.doChangeCommand()
	#@-node:OnReplace
	#@+node:OnReplaceThenFind
	def OnReplaceThenFind(self,event):
		self.c.doChangeThenFindCommand()
	#@-node:OnReplaceThenFind
	#@+node:OnCutNode
	def OnCutNode(self,event):
		self.c.cutOutline()
	#@-node:OnCutNode
	#@+node:OnCopyNode
	def OnCopyNode(self,event):
		self.c.copyOutline()
	#@-node:OnCopyNode
	#@+node:OnPasteNode
	def OnPasteNode(self,event):
		self.c.pasteOutline()
	#@-node:OnPasteNode
	#@+node:OnExpandAll
	def OnExpandAll(self,event):
		self.c.expandAllHeadlines()
	#@-node:OnExpandAll
	#@+node:OnExpandAllChildren
	def OnExpandAllChildren(self,event):
		self.c.expandAllSubheads()
	#@-node:OnExpandAllChildren
	#@+node:OnExpandChildren
	def OnExpandChildren(self,event):
		self.c.expandSubheads()
	#@-node:OnExpandChildren
	#@+node:OnContractAll
	def OnContractAll(self,event):
		self.c.contractAllHeadlines()
	#@-node:OnContractAll
	#@+node:OnContractAllChildren
	def OnContractAllChildren(self,event):
		self.c.contractAllSubheads()
	#@-node:OnContractAllChildren
	#@+node:OnContractChildren
	def OnContractChildren(self,event):
		self.c.contractSubheads()
	#@-node:OnContractChildren
	#@+node:OnExpandNextLevel
	def OnExpandNextLevel(self,event):
		self.c.expandNextLevel()
	#@-node:OnExpandNextLevel
	#@+node:OnExpandToLevel1
	def OnExpandToLevel1(self,event):
		self.c.expandLevel1()
	#@-node:OnExpandToLevel1
	#@+node:OnExpandToLevel2
	def OnExpandToLevel2(self,event):
		self.c.expandLevel2()
	#@-node:OnExpandToLevel2
	#@+node:OnExpandToLevel3
	def OnExpandToLevel3(self,event):
		self.c.expandLevel3()
	#@-node:OnExpandToLevel3
	#@+node:OnExpandToLevel4
	def OnExpandToLevel4(self,event):
		self.c.expandLevel4()
	#@-node:OnExpandToLevel4
	#@+node:OnExpandToLevel5
	def OnExpandToLevel5(self,event):
		self.c.expandLevel5()
	#@-node:OnExpandToLevel5
	#@+node:OnExpandToLevel6
	def OnExpandToLevel6(self,event):
		self.c.expandLevel6()
	#@-node:OnExpandToLevel6
	#@+node:OnExpandToLevel7
	def OnExpandToLevel7(self,event):
		self.c.expandLevel7()
	#@-node:OnExpandToLevel7
	#@+node:OnExpandToLevel8
	def OnExpandToLevel8(self,event):
		self.c.expandLevel8()
	#@-node:OnExpandToLevel8
	#@+node:OnExpandToLevel9
	def OnExpandToLevel9(self,event):
		self.c.expandLevel9()
	#@-node:OnExpandToLevel9
	#@+node:OnDeleteNode
	def OnDeleteNode(self,event):
		self.c.deleteHeadline()
	#@-node:OnDeleteNode
	#@+node:OnInsertNode
	def OnInsertNode(self,event):
		self.c.insertHeadline()
	#@-node:OnInsertNode
	#@+node:OnCloneNode
	def OnCloneNode(self,event):
		self.c.clone()
	#@-node:OnCloneNode
	#@+node:OnGoPrevVisible
	def OnGoPrevVisible(self,event):
		self.c.moveOutlineUp()
	#@-node:OnGoPrevVisible
	#@+node:OnGoNextVisible
	def OnGoNextVisible(self,event):
		self.c.selectVisNext()
	#@-node:OnGoNextVisible
	#@+node:OnGoBack
	def OnGoBack(self,event):
		self.c.selectThreadBack()
	#@-node:OnGoBack
	#@+node:OnGoNext
	def OnGoNext(self,event):
		self.c.selectThreadNext()
	#@-node:OnGoNext
	#@+node:OnMark
	def OnMark(self,event):
		self.c.markHeadline()
	#@-node:OnMark
	#@+node:OnMarkSubheads
	def OnMarkSubheads(self,event):
		self.c.markSubheads()
	#@-node:OnMarkSubheads
	#@+node:OnMarkChangedItems
	def OnMarkChangedItems(self,event):
		self.c.markChangedHeadlines()
	#@-node:OnMarkChangedItems
	#@+node:OnMarkChangedRoots
	def OnMarkChangedRoots(self,event):
		self.c.markChangedRoots()
	#@-node:OnMarkChangedRoots
	#@+node:OnMarkAllAtFileNodesDirty
	def OnMarkAllAtFileNodesDirty(self,event):
		self.c.markAllAtFileNodesDirty()
	#@-node:OnMarkAllAtFileNodesDirty
	#@+node:OnMarkAtFileNodesDirty
	def OnMarkAtFileNodesDirty(self,event):
		self.c.markAtFileNodesDirty()
	#@-node:OnMarkAtFileNodesDirty
	#@+node:OnUnmarkAll
	def OnUnmarkAll(self,event):
		self.c.unmarkAll()
	#@-node:OnUnmarkAll
	#@+node:OnGoToNextMarked
	def OnGoToNextMarked(self,event):
		self.c.goToNextMarkedHeadline()
	#@-node:OnGoToNextMarked
	#@+node:OnGoToNextChanged
	def OnGoToNextChanged(self,event):
		self.c.goToNextDirtyHeadline()
	#@-node:OnGoToNextChanged
	#@+node:OnMoveDown
	def OnMoveDown(self,event):
		self.c.moveOutlineDown()
	#@-node:OnMoveDown
	#@+node:OnMoveLeft
	def OnMoveLeft(self,event):
		self.c.moveOutlineLeft()
	#@-node:OnMoveLeft
	#@+node:OnMoveRight
	def OnMoveRight(self,event):
		self.c.moveOutlineRight()
	#@-node:OnMoveRight
	#@+node:OnMoveUp
	def OnMoveUp(self,event):
		self.c.moveOutlineUp()
	#@-node:OnMoveUp
	#@+node:OnPromote
	def OnPromote(self,event):
		self.c.promote()
	#@-node:OnPromote
	#@+node:OnDemote
	def OnDemote(self,event):
		self.c.demote()
	#@-node:OnDemote
	#@+node:OnSortNode
	def OnSortNode(self,event):
		self.c.sort()
	#@-node:OnSortNode
	#@+node:OnEqualSizedPanes
	def OnEqualSizedPanes(self,event):
		self.c.equalSizedPanes()
	#@-node:OnEqualSizedPanes
	#@+node:OnToggleActivePane
	def OnToggleActivePane(self,event):
		w = self.FindFocus()
		if w == None or w == self.tree:
			self.body.SetFocus()
		else:
			self.tree.SetFocus()
	#@-node:OnToggleActivePane
	#@+node:OnChangeDirection
	def OnChangeDirection(self,event):
	
		mode = self.splitter1.GetSplitMode()
		self.splitter1.Unsplit()# Hides the text control.
		if  mode == wxSPLIT_VERTICAL:
			self.splitter1.SplitHorizontally(self.tree,self.body,0)
		else:
			self.splitter1.SplitVertically(self.tree,self.body,0)
		self.body.Show()
		self.body.SetFocus()
	#@-node:OnChangeDirection
	#@+node:OnCascade
	def OnCascade(self,event):
		
		p = wx.wxPoint(10,10)
		for f in app.windowList:
			f.Move(p)
			p.x += 30
			p.y += 30
			if p.x > 200:
				p.x = 10
				p.y = 40
	#@nonl
	#@-node:OnCascade
	#@+node:OnMinimizeAll
	def OnMinimizeAll(self,event):
	
		# trace(app.windowList)
		for w in app.windowList:
			w.Iconize(true)
			
		if app.findFrame:
			app.findFrame.Iconize()
		
		if 0: # old code
			if gPrefsFrame:
				gPrefsFrame.Iconize()
			if app.findFrame:
				app.findFrame.Iconize()
			if gPythonFrame:
				gPythonFrame.Iconize()
	#@nonl
	#@-node:OnMinimizeAll
	#@+node:OnOpenPythonWindow
	if wx.wxPlatform == "__WXMSW__":
		
		pass
	
		#void LeoFrame::OnOpenPythonWindow(wxCommandEvent& WXUNUSED(event))
		#gPythonFrame = wxPythonFrame::create((char *)"leoc",(char *)"leo",(void(*)())initleoc)
		#gPythonFrame.Show(true)
	#@nonl
	#@-node:OnOpenPythonWindow
	#@+node:OnRecentWindows
	def OnRecentWindows(self,event):
		pass
	#@-node:OnRecentWindows
	#@+node:OnAbout
	def OnAbout(self,event=None):
		
		message = u"\n\
	Leo Version 4.0, October 11, 2003\n\
	\n\
	Copyright © 2001 by Edward K. Ream\n\
	All Rights Reserved \n\
	Leo is distributed under the Python License"
	
		wx.wxMessageBox(message,"About Leo",wx.wxCenter,self)
	#@nonl
	#@-node:OnAbout
	#@-others
#@nonl
#@-node:wxLeoFrame class
#@+node:wxFindFrame class
class wxFindFrame (wx.wxFrame):

	#@	<< FindPanel public globals >>
	#@+node:<< FindPanel public globals >> (to be moved to Leo's core)
	reset_search_flag = None
	batch_flag = None
	wrap_flag = None
	whole_word_flag = None
	ignore_case_flag = None
	pattern_match_flag = None
	search_headline_flag = None
	search_body_flag = None
	suboutline_only_flag = None
	mark_changes_flag = None
	mark_finds_flag = None
	reverse_flag = None
	find_text = ""
	change_text = ""
	#@-node:<< FindPanel public globals >> (to be moved to Leo's core)
	#@nl

	#@	@+others
	#@+node:FindFrame.__init__
	def __init__ (self):
	
		# Init the base class
		wx.wxFrame.__init__(self,None,-1,"Leo Find/Change",
			wx.wxPoint(50,50), wx.wxDefaultSize,
			wx.wxMINIMIZE_BOX | wx.wxTHICK_FRAME | wx.wxSYSTEM_MENU | wx.wxCAPTION)
	
		self.findPanel = wxFindPanel(self)
	
		# Resize to fit the panel.
		sizer = wx.wxBoxSizer(wx.wxVERTICAL)
		sizer.Add(self.findPanel)
		self.SetAutoLayout(true)# tell dialog to use sizer
		self.SetSizer(sizer) # actually set the sizer
		sizer.Fit(self)# set size to minimum size as calculated by the sizer
		sizer.SetSizeHints(self)# set size hints to honour mininum size
	
		# Set the window icon.
		if wx.wxPlatform == '__WXMSW__':
			pass ## self.SetIcon(wx.wxIcon("LeoIcon"))
	
		# Set the focus.
		self.findPanel.findText.SetFocus()
			
		#@	<< declare event handlers >>
		#@+node:<< declare event handlers >>
		if wx.wxPlatform == "__WXMSW__": # Activate events exist only on windows.
			pass ## wx.EVT_ACTIVATE(self.OnActivateFindFrame)
		else:
			wx.EVT_SET_FOCUS(self.OnSetFocus)
		
		## wx.EVT_CLOSE(self.OnCloseFindFrame)
		
		for name,command in (
			("cChangeButton",self.OnChangeButton),
			("cChangeAllButton",self.OnChangeAllButton),
			("cChangeThenFindButton",self.OnChangeThenFindButton),
			("cFindButton",self.OnFindButton),
			("cFindAllButton",self.OnFindAllButton)):
			
			wx.EVT_BUTTON(self,const(name),command)
			
		for name,command in (
			("cBatchCheckBox",self.OnBatchCheckBox),
			("cIgnoreCaseCheckBox",self.OnIgnoreCaseCheckBox),
			("cMarkChangesCheckBox",self.OnMarkChangesCheckBox),
			("cMarkFindsCheckBox",self.OnMarkFindsCheckBox),
			("cPatternMatchCheckBox",self.OnPatternMatchCheckBox),
			("cReverseCheckBox",self.OnReverseCheckBox),
			("cSearchHeadlineCheckBox",self.OnSearchHeadlineCheckBox),
			("cSearchBodyTextCheckBox",self.OnSearchBodyTextCheckBox),
			("cSuboutlineOnlyCheckBox",self.OnSuboutlineOnlyCheckBox),
			("cWrapAroundCheckBox",self.OnWrapAroundCheckBox),
			("cWholeWordCheckBox",self.OnWholeWordCheckBox)):
			
			wx.EVT_CHECKBOX(self,const(name),command)
			
		for name,command in (
			("cFindTextCtrl",self.OnFindText),
			("cChangeTextCtrl",self.OnChangeText)):
			
			wx.EVT_TEXT(self,const(name),command)
		
		if 0:
			wx.EVT_BUTTON(self,cChangeButton,self.OnChangeButton)
			wx.EVT_BUTTON(self,cChangeAllButton,self.OnChangeAllButton)
			wx.EVT_BUTTON(self,cChangeThenFindButton,self.OnChangeThenFindButton)
			wx.EVT_BUTTON(self,cFindButton,self.OnFindButton)
			wx.EVT_BUTTON(self,cFindAllButton,self.OnFindAllButton)
			
			wx.EVT_CHECKBOX(self,cBatchCheckBox,self.OnBatchCheckBox)
			wx.EVT_CHECKBOX(self,cIgnoreCaseCheckBox,self.OnIgnoreCaseCheckBox)
			wx.EVT_CHECKBOX(self,cMarkChangesCheckBox,self.OnMarkChangesCheckBox)
			wx.EVT_CHECKBOX(cMarkFindsCheckBox,self.OnMarkFindsCheckBox)
			wx.EVT_CHECKBOX(cPatternMatchCheckBox,self.OnPatternMatchCheckBox)
			wx.EVT_CHECKBOX(cReverseCheckBox,self.OnReverseCheckBox)
			wx.EVT_CHECKBOX(cSearchHeadlineCheckBox,self.OnSearchHeadlineCheckBox)
			wx.EVT_CHECKBOX(cSearchBodyTextCheckBox,self.OnSearchBodyTextCheckBox)
			wx.EVT_CHECKBOX(cSuboutlineOnlyCheckBox,self.OnSuboutlineOnlyCheckBox)
			wx.EVT_CHECKBOX(cWrapAroundCheckBox,self.OnWrapAroundCheckBox)
			wx.EVT_CHECKBOX(cWholeWordCheckBox,self.OnWholeWordCheckBox)
			wx.EVT_TEXT(cFindTextCtrl,self.OnFindText)
			wx.EVT_TEXT(cChangeTextCtrl,self.OnChangeText)
		#@nonl
		#@-node:<< declare event handlers >>
		#@nl
	#@-node:FindFrame.__init__
	#@+node:OnActivateFindFrame & OnSetFocus
	if wx.wxPlatform == "__WXMSW__": # This event exists only on Windows.
	
		def OnActivateFindFrame(self,event):
			if event.GetActive():
				self.set_check_boxes()
				c = self.findPanel.self.findText
				s = c.GetValue()
				c.SetFocus()
				c.SetSelection(0,s.Length())
	else:
		def OnSetFocus(self,event):
			self.set_check_boxes()
			c = self.findPanel.self.findText
			s = c.GetValue()
			c.SetFocus()
			c.SetSelection(0,s.Length())
	#@nonl
	#@-node:OnActivateFindFrame & OnSetFocus
	#@+node:OnCloseFindFrame
	#@+at 
	#@nonl
	# This is an event handler function called when the user has tried to 
	# close a frame or dialog box.
	# 
	# It is called via the wxWindow::Close function,so that the application 
	# can also invoke the handler programmatically.
	# You should check whether the application is forcing the deletion of the 
	# window using CanVeto.
	# 
	# If CanVeto returns FALSE,it is not possible to skip window deletion; 
	# destroy the window using wxWindow::Destroy.
	# If not,it is up to you whether you respond by destroying the window.
	# 
	# If you don't destroy the window,you should call wxCloseEvent::Veto to 
	# let the calling code know that you did not destroy the window. This 
	# allows the wxWindow::Close function to return TRUE or FALSE depending on 
	# whether the close instruction was honoured or not.
	#@-at
	#@@c
	
	def OnCloseFindFrame(self,event):
		
		if event.CanVeto():
			event.Veto()     # Did not destroy the window.
			self.Show(false) # Just hide the window.
		else:
			self.Destroy()
			app.findFrame = None
	#@-node:OnCloseFindFrame
	#@+node:OnChangeButton
	def OnChangeButton(self,event):
	
		if self.activeFrame:
			self.activeFrame.c.doChangeButton()
	#@-node:OnChangeButton
	#@+node:OnChangeAllButton
	def OnChangeAllButton(self,event):
		if self.activeFrame:
			self.activeFrame.c.doChangeAllButton()
	#@-node:OnChangeAllButton
	#@+node:OnChangeThenFindButton
	def OnChangeThenFindButton(self,event):
		if self.activeFrame:
			self.activeFrame.c.doChangeThenFindButton()
	#@-node:OnChangeThenFindButton
	#@+node:OnFindButton
	def OnFindButton(self,event):
		# This is the default button,so make sure there is find text.
		if  self.activeFrame and find_text.Length()> 0:
			self.activeFrame.c.doFindButton()
	#@-node:OnFindButton
	#@+node:OnFindAllButton
	def OnFindAllButton(self,event):
		if self.activeFrame:
			self.activeFrame.c.doFindAllButton()
	#@-node:OnFindAllButton
	#@+node:OnBatchCheckBox
	def OnBatchCheckBox(self,event):
		box = event.GetEventObject()
		batch_flag = box.GetValue()
	#@-node:OnBatchCheckBox
	#@+node:OnIgnoreCaseCheckBox
	def OnIgnoreCaseCheckBox(self,event):
		box = event.GetEventObject()
		ignore_case_flag = box.GetValue()
		if self.activeFrame:
			self.activeFrame.c.setup(true)# reset the search.
	#@-node:OnIgnoreCaseCheckBox
	#@+node:OnMarkChangesCheckBox
	def OnMarkChangesCheckBox(self,event):
		box = event.GetEventObject()
		mark_changes_flag = box.GetValue()
	#@-node:OnMarkChangesCheckBox
	#@+node:OnMarkFindsCheckBox
	def OnMarkFindsCheckBox(self,event):
		box = event.GetEventObject()
		mark_finds_flag = box.GetValue()
	#@-node:OnMarkFindsCheckBox
	#@+node:OnPatternMatchCheckBox
	def OnPatternMatchCheckBox(self,event):
		box = event.GetEventObject()
		pattern_match_flag = box.GetValue()
		if self.activeFrame:
			self.activeFrame.c.setup(true)# reset the search.
	#@-node:OnPatternMatchCheckBox
	#@+node:OnReverseCheckBox
	def OnReverseCheckBox(self,event):
		box = event.GetEventObject()
		reverse_flag = box.GetValue()
	#@-node:OnReverseCheckBox
	#@+node:OnSearchBodyTextCheckBox
	def OnSearchBodyTextCheckBox(self,event):
		box = event.GetEventObject()
		search_body_flag = box.GetValue()
		if self.activeFrame:
			self.activeFrame.c.setup(true)# reset the search.
	#@-node:OnSearchBodyTextCheckBox
	#@+node:OnSearchHeadlineCheckBox
	def OnSearchHeadlineCheckBox(self,event):
		box = event.GetEventObject()
		search_headline_flag = box.GetValue()
	#@-node:OnSearchHeadlineCheckBox
	#@+node:OnSuboutlineOnlyCheckBox
	def OnSuboutlineOnlyCheckBox(self,event):
		box = event.GetEventObject()
		suboutline_only_flag = box.GetValue()
	#@-node:OnSuboutlineOnlyCheckBox
	#@+node:OnWrapAroundCheckBox
	def OnWrapAroundCheckBox(self,event):
		box = event.GetEventObject()
		wrap_flag = box.GetValue()
	#@-node:OnWrapAroundCheckBox
	#@+node:OnWholeWordCheckBox
	def OnWholeWordCheckBox(self,event):
		
		box = event.GetEventObject()
		whole_word_flag = box.GetValue()
		if self.activeFrame:
			self.activeFrame.c.setup(true)# reset the search.
	
	#@-node:OnWholeWordCheckBox
	#@+node:OnChangeText
	def OnChangeText(self,event):
		text = event.GetEventObject()
		change_text = text.GetValue()
		if self.activeFrame:
			self.activeFrame.c.setup(true)# reset the search.
	#@-node:OnChangeText
	#@+node:OnFindText
	def OnFindText(self,event):
		text = event.GetEventObject()
		find_text = text.GetValue()
		if self.activeFrame:
			self.activeFrame.c.setup(true)# reset the search.
	#@-node:OnFindText
	#@+node:Interface with commander
	def set_ivars (self, *args, **keys):
		
		trace(*args,**keys)
	#@nonl
	#@-node:Interface with commander
	#@+node:set_check_boxes
	def set_check_boxes(self,void):
	
		self.findPanel.mBatchCheckBox.SetValue(batch_flag)
		self.findPanel.mWrapAroundCheckBox.SetValue(wrap_flag)
		self.findPanel.mWholeWordCheckBox.SetValue(whole_word_flag)
		self.findPanel.mIgnoreCaseCheckBox.SetValue(ignore_case_flag)
		self.findPanel.mPatternMatchCheckBox.SetValue(pattern_match_flag)
		self.findPanel.mSearchHeadlineCheckBox.SetValue(search_headline_flag)
		self.findPanel.mSearchBodyTextCheckBox.SetValue(search_body_flag)
		self.findPanel.mSuboutlineOnlyCheckBox.SetValue(suboutline_only_flag)
		self.findPanel.mMarkChangesCheckBox.SetValue(mark_changes_flag)
		self.findPanel.mMarkFindsCheckBox.SetValue(mark_finds_flag)
		self.findPanel.mReverseCheckBox.SetValue(reverse_flag)
		self.findPanel.findText.SetValue(find_text)
		self.findPanel.changeText.SetValue(change_text)
	#@nonl
	#@-node:set_check_boxes
	#@-others
#@nonl
#@-node:wxFindFrame class
#@+node:wxFindPanel class
class wxFindPanel (wx.wxPanel):

	#@	@+others
	#@+node:FindPanel.__init__
	def __init__(self,frame):
		 
		# Init the base class.
		wx.wxPanel.__init__(self,frame,-1)
	
		topSizer = wx.wxBoxSizer(wx.wxVERTICAL)
		topSizer.Add(0,10)
	
		#@	<< Create the find text box >>
		#@+node:<< Create the find text box >>
		findSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
		findSizer.Add(5,5)# Extra space.
		
		# Label.
		findSizer.Add(
			wx.wxStaticText(self,-1,"Find:",
				wx.wxPoint(-1,10), wx.wxSize(50,25),0,""),
			0, wx.wxBORDER | wx.wxTOP,15) # Vertical offset.
		
		findSizer.Add(10,0) # Width.
		
		# Text.
		self.findText = wx.wxTextCtrl(self,
			const("cFindTextCtrl"),"",
			wx.wxDefaultPosition, wx.wxSize(300,60),
			wx.wxTE_PROCESS_TAB | wx.wxTE_MULTILINE,
			wx.wxDefaultValidator,"")
		
		findSizer.Add(self.findText)
		findSizer.Add(5,0)# Width.
		topSizer.Add(findSizer)
		topSizer.Add(0,10)
		#@nonl
		#@-node:<< Create the find text box >>
		#@nl
		#@	<< Create the change text box >>
		#@+node:<< Create the change text box >>
		changeSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
		changeSizer.Add(5,5)# Extra space.
		
		# Label.
		changeSizer.Add(
			wx.wxStaticText(self,-1,"Change:",
				wx.wxPoint(-1,10),wx.wxSize(50,25),0,""),
			0, wx.wxBORDER | wx.wxTOP,15)# Vertical offset.
		
		changeSizer.Add(10,0) # Width.
		
		# Text.
		self.changeText = wx.wxTextCtrl(self,
			const("cChangeTextCtrl"),"",
			wx.wxDefaultPosition, wx.wxSize(300,60),
			wx.wxTE_PROCESS_TAB | wx.wxTE_MULTILINE,
			wx.wxDefaultValidator,"")
		
		changeSizer.Add(self.changeText)
		changeSizer.Add(5,0)# Width.
		topSizer.Add(changeSizer)
		topSizer.Add(0,10)
		#@nonl
		#@-node:<< Create the change text box >>
		#@nl
		#@	<< Create all the find check boxes >>
		#@+node:<< Create all the find check boxes >>
		col1Sizer = wx.wxBoxSizer(wx.wxVERTICAL)
		#@<< Create the first column of check boxes >>
		#@+node:<< Create the first column of check boxes >>
		for ivar,cname,label in (
			("batchCheckBox","cBatchCheckBox","Batch"),
			("wrapAroundCheckBox","cWrapAroundCheckBox","Wrap Around"),
			("wholeWordCheckBox","cWholeWordCheckBox","Whole Word"),
			("ignoreCaseCheckBox","cIgnoreCaseCheckBox","Ignore Case"),
			("patternMatchCheckBox","cPatternMatchCheckBox","Pattern Match")
			):
			
			box = wx.wxCheckBox(
				self,const(cname),label,
				wx.wxDefaultPosition,(150,25),
				0,wx.wxDefaultValidator,"")
				
			setattr(self,ivar,box)
			col1Sizer.Add(box,0,wx.wxBORDER | wx.wxLEFT,50)
		#@nonl
		#@-node:<< Create the first column of check boxes >>
		#@nl
		
		col2Sizer = wx.wxBoxSizer(wx.wxVERTICAL)
		#@<< Create the second column of check boxes >>
		#@+node:<< Create the second column of check boxes >>
		for ivar,cname,label in (
			("searchHeadlineCheckBox","cSearchHeadlineCheckBox","Search Headline Text"),
			("searchBodyTextCheckBox","cSearchBodyTextCheckBox","Search Body Text"),
			("suboutlineOnlyCheckBox","cSuboutlineOnlyCheckBox","Suboutline Only"),
			("markChangesCheckBox","cMarkChangesCheckBox","Mark Changes"),
			("markFindsCheckBox","cMarkFindsCheckBox","Mark Finds")
			):
			
			box = wx.wxCheckBox(
				self,const(cname),label,
				wx.wxDefaultPosition,(150,25),
				0,wx.wxDefaultValidator,"")
		
			setattr(self,ivar,box)
			col2Sizer.Add(box)
		#@nonl
		#@-node:<< Create the second column of check boxes >>
		#@nl
		
		# Pack the two columns
		checkBoxSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
		checkBoxSizer.Add(col1Sizer)
		checkBoxSizer.Add(col2Sizer)
		topSizer.Add(checkBoxSizer)
		topSizer.Add(0,10)
		#@nonl
		#@-node:<< Create all the find check boxes >>
		#@nl
		#@	<< Create all the find buttons >>
		#@+node:<< Create all the find buttons >>
		# The row sizers are a bit dim:  they should distribute the buttons automatically.
		
		row1Sizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
		#@<< Create the first row of buttons >>
		#@+node:<< Create the first row of buttons >>
		row1Sizer.Add(20,0)
		
		for ivar,cname,label,size,adj in (
			("findButton","cFindButton","Find",(80,25),None),
			("reverseCheckBox","cReverseCheckBox","Reverse",(100,25),(24,0)),
			("findAllButton","cFindAllButton","Find All",(80,25),None)):
			
			button = wx.wxButton(
				self,const(cname),label,
				wx.wxDefaultPosition,size,
				0,wx.wxDefaultValidator,"")
				
			setattr(self,ivar,button)
			row1Sizer.Add(button)
			if adj:
				row1Sizer.Add(adj)
		#@nonl
		#@-node:<< Create the first row of buttons >>
		#@nl
		
		row2Sizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
		#@<< Create the second row of buttons >>
		#@+node:<< Create the second row of buttons >>
		row2Sizer.Add(20,0)
		
		for ivar,cname,label,size,adj in (
			("changeButton","cChangeButton","Change",(80,25),(24,0)),
			("changeThenFindButton","cChangeThenFindButton","Change,Then Find",(122,25),(24,0)),
			("changeAllButton","cChangeAllButton","Change All",(80,25),None)):
			
			button = wx.wxButton(
				self,const(cname),label,
				wx.wxDefaultPosition,size,
				0,wx.wxDefaultValidator,"")
				
			setattr(self,ivar,button)
			row2Sizer.Add(button)
			if adj:
				row2Sizer.Add(adj)
		#@nonl
		#@-node:<< Create the second row of buttons >>
		#@nl
		
		# Pack the two rows
		buttonSizer = wx.wxBoxSizer(wx.wxVERTICAL)
		buttonSizer.Add(row1Sizer)
		buttonSizer.Add(0,10)
		buttonSizer.Add(row2Sizer)
		topSizer.Add(buttonSizer)
		topSizer.Add(0,10)
		#@nonl
		#@-node:<< Create all the find buttons >>
		#@nl
	
		self.SetAutoLayout(true) # tell dialog to use sizer
		self.SetSizer(topSizer) # actually set the sizer
		topSizer.Fit(self)# set size to minimum size as calculated by the sizer
		topSizer.SetSizeHints(self)# set size hints to honour mininum size
	#@nonl
	#@-node:FindPanel.__init__
	#@-others
#@nonl
#@-node:wxFindPanel class
#@+node:wxLeoPrefs class
class wxLeoPrefs (wx.wxFrame):
	#@	@+others
	#@+node:wxLeoPrefs.__init__
	def __init__():
		
		# Init the base frame.
		wxFrame.__init__(None,-1,"Leo Preferences",
			wx.wxPoint(50,50),wxDefaultSize,
			wxMINIMIZE_BOX | wxTHICK_FRAME | wxSYSTEM_MENU | wxCAPTION)
	
		mPrefsPanel = PrefsPanel(self)
	
		# Resize to fit the panel.
		sizer = wxBoxSizer(wxVERTICAL)
		sizer.Add(mPrefsPanel)
		SetAutoLayout(true)# tell dialog to use sizer
		SetSizer(sizer) # actually set the sizer
		sizer.Fit(self)# set size to minimum size as calculated by the sizer
		sizer.SetSizeHints(self)# set size hints to honour mininum size
	
		# Set the window icon.
		if wx.wxPlatform == '__WXMSW__':
			self.SetIcon(wxIcon("LeoIcon"))
			
		#@	<< define event handlers for wxLeoPrefsFrame >>
		#@+node:<< define event handlers for wxLeoPrefsFrame >>
		wx.EVT_ACTIVATE(self,self.OnActivatePrefsFrame)
		wx.EVT_CLOSE(self,self.OnClosePrefsFrame)
		
		# Global options panel...
		wx.EVT_TEXT(self,cPrefsPageWidthText,self.OnPageWidthText)
		wx.EVT_CHECKBOX(self,cPrefsDoneBatCheckBox,self.OnDoneBatCheckBox)
		wx.EVT_CHECKBOX(self,cPrefsUnBatCheckBox,self.OnUnBatCheckBox)
		
		# Tangle options panel...
		wx.EVT_TEXT(self,cPrefsTangleDirectoryText,self.OnTangleDirectoryText)
		wx.EVT_CHECKBOX(self,cPrefsHeaderCheckBox,self.OnHeaderCheckBox)
		wx.EVT_CHECKBOX(self,cPrefsDocChunksCheckBox,self.OnDocChunksCheckBox)
		
		# Target language panel...
		wx.EVT_RADIOBOX(self,cPrefsTargetLanguageRadioBox,self.OnTargetLanguageRadioBox)
		#@nonl
		#@-node:<< define event handlers for wxLeoPrefsFrame >>
		#@nl
	#@nonl
	#@-node:wxLeoPrefs.__init__
	#@+node:initialize
	def initialize (self,void):
		
		# This may be called during construction.
		if not gPrefsFrame:  return
		s = ""
		if self.activeFrame:
			s += "%d" % self.activeFrame.mPageWidth
			mPrefsPanel.mPrefsPageWidthText.SetValue(s)
			mPrefsPanel.mPrefsDoneBatCheckBox.SetValue(self.activeFrame.mTangleBatchFlag)
			mPrefsPanel.mPrefsUnBatCheckBox.SetValue(self.activeFrame.mUntangleBatchFlag)
			mPrefsPanel.mPrefsTangleDirectoryText.SetValue(self.activeFrame.mDefaultDirectory)
			mPrefsPanel.mPrefsHeaderCheckBox.SetValue(self.activeFrame.mUseHeaderFlag)
			mPrefsPanel.mPrefsDocChunksCheckBox.SetValue(self.activeFrame.mOutputDocFlag)
			mPrefsPanel.mTargetLanguageRadioBox.SetSelection(languageToTarget(self.activeFrame.mTargetLanguage))
		else:
			s += "%d" % arg_page_width
			mPrefsPanel.mPrefsPageWidthText.SetValue(s)
			mPrefsPanel.mPrefsDoneBatCheckBox.SetValue(arg_tangle_batch)
			mPrefsPanel.mPrefsUnBatCheckBox.SetValue(arg_untangle_batch)
			# No global setting for director.
			mPrefsPanel.mPrefsHeaderCheckBox.SetValue(arg_use_header_flag)
			mPrefsPanel.mPrefsDocChunksCheckBox.SetValue(arg_output_doc_flag)
			mPrefsPanel.mTargetLanguageRadioBox.SetSelection(languageToTarget(arg_target_language))
	#@nonl
	#@-node:initialize
	#@+node:targetToLanguage (should be in Leo's core)
	if 0:
		def targetToLanguage(self,target):
			
			pass
	
			# switch(target)
			# case c_target: return c_language
			# case cweb_target: return cweb_language
			# case html_target: return html_language
			# case java_target: return java_language
			# case perl_target: return perl_language
			# case perlpod_target: return perlpod_language
			# case pascal_target: return pascal_language
			# case plain_text_target: return plain_text_language
			# case python_target: return python_language
			# default: return plain_text_language
	#@-node:targetToLanguage (should be in Leo's core)
	#@+node:languageToTarget (should be in Leo's core)
	def languageToTarget(self,language):
		
		pass
	
		# switch(language)
		# case c_language: return c_target
		# case cweb_language: return cweb_target
		# case html_language: return html_target
		# case java_language: return java_target
		# case pascal_language: return pascal_target
		# case perl_language: return perl_target
		# case perlpod_language: return perlpod_target
		# case plain_text_language: return plain_text_target
		# case python_language: return python_target
		# default: return plain_text_target
	#@nonl
	#@-node:languageToTarget (should be in Leo's core)
	#@+node:OnActivatePrefsFrame
	def OnActivatePrefsFrame(self,event):
	
		if gPrefsFrame and event.GetActive():
			gPrefsFrame.initialize()
	#@-node:OnActivatePrefsFrame
	#@+node:OnClosePrefsFrame
	#@+at 
	#@nonl
	# This is an event handler function called when the user has tried to 
	# close a frame or dialog box.
	# 
	# It is called via the  wxWindow::Close function, so that the application 
	# can also invoke the handler programmatically.  You should check whether 
	# the application is forcing the deletion of the window using CanVeto. If 
	# CanVeto returns FALSE, it is  not possible to skip window deletion; 
	# destroy the window using wxWindow::Destroy. If not, it is up to you 
	# whether you respond  by destroying the window.  If you don't destroy the 
	# window, you should call wxCloseEvent::Veto to let the calling code know 
	# that you did not destroy the  window. This allows the wxWindow::Close 
	# function to return TRUE or FALSE depending on whether the close 
	# instruction was  honoured or not.
	#@-at
	#@@c
	
	def OnClosePrefsFrame(self,event):
	
		if event.CanVeto():
			event.Veto()# Did not destroy the window.
			self.Show(false) # Just hide the window.
		else:
			self.Destroy()
			gPrefsFrame = None
	#@-node:OnClosePrefsFrame
	#@+node:OnPageWidthText
	def OnPageWidthText(self,event):
		
		text = event.GetEventObject()
		s = text.GetValue()
	
		try:
			n = int(s)
			arg_page_width = default_page_width = n
			if self.activeFrame:
				self.activeFrame.mPageWidth = arg_page_width
		except: pass
	
	#@-node:OnPageWidthText
	#@+node:OnDoneBatCheckBox
	def OnDoneBatCheckBox(self,event):
		
		box =event.GetEventObject()
		arg_tangle_batch = default_tangle_batch = box.GetValue()
		if self.activeFrame:
			self.activeFrame.mTangleBatchFlag = arg_tangle_batch
	
	#@-node:OnDoneBatCheckBox
	#@+node:OnUnBatCheckBox
	def OnUnBatCheckBox(self,event):
		
		box = event.GetEventObject()
		arg_untangle_batch = default_untangle_batch = box.GetValue()
		if self.activeFrame:
			self.activeFrame.mUntangleBatchFlag = arg_untangle_batch
	
	#@-node:OnUnBatCheckBox
	#@+node:OnTangleDirectoryText
	def OnTangleDirectoryText(self,event):
	
		text = event.GetEventObject()
		s = text.GetValue()
		if self.activeFrame:
			self.activeFrame.mDefaultDirectory = s
			if self.activeFrame.mDefaultDirectory.Length()> 0:
				wxSetWorkingDirectory(self.activeFrame.mDefaultDirectory)
			elif self.activeFrame.mOpenDirectory.Length()> 0:
				wxSetWorkingDirectory(self.activeFrame.mOpenDirectory)
	#@nonl
	#@-node:OnTangleDirectoryText
	#@+node:OnHeaderCheckBox
	def OnHeaderCheckBox(self,event):
		
		box = event.GetEventObject()
		arg_use_header_flag = default_use_header_flag = box.GetValue()
		if self.activeFrame:
			self.activeFrame.mUseHeaderFlag = arg_use_header_flag
	
	#@-node:OnHeaderCheckBox
	#@+node:OnDocChunksCheckBox
	def OnDocChunksCheckBox(self,event):
		
		box = event.GetEventObject()
		arg_output_doc_flag = default_output_doc_flag = box.GetValue()
		if self.activeFrame:
			self.activeFrame.mOutputDocFlag = arg_output_doc_flag
	
	#@-node:OnDocChunksCheckBox
	#@+node:OnTargetLanguageRadioBox
	def OnTargetLanguageRadioBox(self,event):
		
		box = event.GetEventObject()
		targetIndex = box.GetSelection()
		default_target_language = arg_target_language = targetToLanguage(targetIndex)
	
		# Careful:  The @language or @nocolor will override this.
		if self.activeFrame:
			self.activeFrame.mTargetLanguage = arg_target_language
			c = self.activeFrame.c
			v = c.currentVnode()
			self.activeFrame.c.scanAllDirectives(v,cDontRequirePath,cDontIssueErrors)
	#@nonl
	#@-node:OnTargetLanguageRadioBox
	#@+node:PrefsPanel.__init__
	def __init__(frame):
		
		# Init the base class.
		wxPanel.__init__(frame,-1)
		
		topSizer = wxBoxSizer(wxVERTICAL)
		#@	<< Create the Global Options static box >>
		#@+node:<< Create the Global Options static box >>
		globalOptionsBox = wxStaticBox(self,-1,
			"Global Options",(10,10),(250,110),0,"")
		sizer = wxStaticBoxSizer(globalOptionsBox,wxVERTICAL)
		lineSizer = wxBoxSizer(wxHORIZONTAL)
		sizer.Add(0,5)# Extra vertical space.
		
		# Text control.
		mPrefsPageWidthText = wxTextCtrl(self,
			cPrefsPageWidthText,"132",
			wxDefaultPosition,wx.wxSize(50,25),0,wxDefaultValidator,"")
		
		lineSizer.Add(mPrefsPageWidthText)
		lineSizer.Add(20,0)# Width.
		
		# Label for text control.
		lineSizer.Add(
			wxStaticText(self,-1,"Page Width",
				(-1,10),(100,25),0,""),
			0,wxBORDER | wxTOP,5)# Vertical offset 5.
		sizer.Add(lineSizer)
		
		mPrefsDoneBatCheckBox = wxCheckBox(self,
			cPrefsDoneBatCheckBox,
			"Execute Leo_done.bat after Tangle",
			wxDefaultPosition,(235,25),0,wxDefaultValidator,"")
		sizer.Add(mPrefsDoneBatCheckBox)
		
		mPrefsUnBatCheckBox = wxCheckBox(self,
			cPrefsUnBatCheckBox,
			"Execute Leo_un.bat after Untangle",
			wxDefaultPosition,(235,25),0,wxDefaultValidator,"")
		sizer.Add(mPrefsUnBatCheckBox)
		#@nonl
		#@-node:<< Create the Global Options static box >>
		#@nl
		topSizer.Add(sizer)
		topSizer.Add(0,10)
		#@	<< Create the Default Tangle Options static box >>
		#@+node:<< Create the Default Tangle Options static box >>
		optionsBox = wxStaticBox(self,-1,
			"Default Tangle Options",
			wxDefaultPosition,wx.wxSize(250,210),
			0,"zzzz")
		
		sizer2 = wxStaticBoxSizer(optionsBox,wxVERTICAL)
		sizer2.Add(0,10)# Vertical space.
		# Label.
		sizer2.Add(
			wxStaticText(self,-1,
				"Default Tangle directory",
				wxDefaultPosition,wx.wxSize(165,25),0,""),
			0,wxBORDER | wxLEFT,30)# Indent 30.
		
		mPrefsTangleDirectoryText = wxTextCtrl(self,
			cPrefsTangleDirectoryText,"",
			wxDefaultPosition,wx.wxSize(230,25),0,
			wxDefaultValidator,"")
		sizer2.Add(mPrefsTangleDirectoryText)
		
		mPrefsHeaderCheckBox = wxCheckBox(self,
			cPrefsHeaderCheckBox,
			"Tangle outputs header line",
			wxDefaultPosition,wx.wxSize(235,25),0,
			wxDefaultValidator,"")
		sizer2.Add(mPrefsHeaderCheckBox)
		
		mPrefsDocChunksCheckBox = wxCheckBox(self,
			cPrefsDocChunksCheckBox,
			"Tangle outputs document chunks",
			wxDefaultPosition,wx.wxSize(235,25),0,
			wxDefaultValidator,"")
		sizer2.Add(mPrefsDocChunksCheckBox)
		#@nonl
		#@-node:<< Create the Default Tangle Options static box >>
		#@nl
		topSizer.Add(sizer2)
		topSizer.Add(0,10)
		#@	<< Create the Default Target Language radio buttons >>
		#@+node:<< Create the Default Target Language radio buttons >>
		targetLanguageChoices= [
			"C/C++","CWEB","HTML","Java",
			"Pascal","Perl","Perl + POD","Plain text","Python"]
			
		# We specify rows so that items will be sorted down the columns.
		mTargetLanguageRadioBox = wxRadioBox(self,
			cPrefsTargetLanguageRadioBox,
			"Default Target Language",
			wxDefaultPosition,wx.wxSize(245,145),
			WXSIZEOF(targetLanguageChoices),
			targetLanguageChoices,
			5,wxRA_SPECIFY_ROWS)
		#@nonl
		#@-node:<< Create the Default Target Language radio buttons >>
		#@nl
		topSizer.Add(mTargetLanguageRadioBox)
		SetAutoLayout(true)# tell dialog to use sizer
		SetSizer(topSizer) # actually set the sizer
		topSizer.Fit(self)# set size to minimum size as calculated by the sizer
		topSizer.SetSizeHints(self)# set size hints to honour mininum size
	#@nonl
	#@-node:PrefsPanel.__init__
	#@-others
#@-node:wxLeoPrefs class
#@-others

if wx and 0: # Enable the plugin...

	if app.gui is None:
		print "Installing wxPython gui"
		#@		<< Set app.gui >>
		#@+node:<< set app.gui >>
		app.gui = wxGui()
		app.root = app.gui.createRootWindow()
		app.gui.finishCreate()
		#@-node:<< set app.gui >>
		#@nl
		__version__ = "0.1" # Set version for the plugin handler.
		plugin_signon(__name__)
	else:
		s = "Can't install wxPython gui: previous gui installed"
		print s ; es(s,color="red")
#@nonl
#@-node:@file __wx_gui.py
#@-leo
