#@+leo-ver=4
#@+node:@file scripts_menu.py
"""Create a Scripts menu for LeoPy.leo"""

from leoPlugins import *
from leoGlobals import *
import glob,os

#@+others
#@+node:createScriptsMenu
def createScriptsMenu (tag,keywords):

	c = keywords.get("c")
	path = os.path.join(app().loadDir,"..","scripts")
	
	if os.path.exists(path):

		# Create lists of scripts and subdirectories.
		entries = glob.glob(os.path.join(path,"*"))
		top_scripts = glob.glob(os.path.join(path,"*.py"))
		dirs = [f for f in entries if os.path.isdir(f)]
		#@		<< Return if no scripts exist anywhere >>
		#@+node:<< Return if no scripts exist anywhere >>
		if not top_scripts:
			found = false
			for dir in dirs:
				scripts = glob.glob(os.path.join(dir,"*.py"))
				if scripts:
					found = true ; break
			if not found:
				return
		#@-node:<< Return if no scripts exist anywhere >>
		#@nl
	
		scriptsMenu = c.frame.createNewMenu("&Scripts")
		table = []
		#@		<< Create top-level entries for every script in top_scripts >>
		#@+node:<< Create top-level entries for every script in top_scripts >>
		table = []
		top_scripts.sort()
		for script in top_scripts:
			name = shortFileName(script)
			def doScript(event=None,name=name):
				executeScript(name)
			table.append((name,None,doScript),)
			
		c.frame.createMenuEntries(scriptsMenu, table)
		#@-node:<< Create top-level entries for every script in top_scripts >>
		#@nl
		for dir in dirs:
			files = glob.glob(os.path.join(dir,"*.py"))
			if files:
				#@				<< Create a submenu for dir containing each file in files >>
				#@+node:<< Create a submenu for dir containing each file in files >>
				# Create the submenu.
				name = os.path.join("scripts",shortFileName(dir))
				menu = c.frame.createNewMenu(name,"&Scripts")
				
				# Populate the submenu.
				table = []
				for file in files:
					name = shortFileName(file)
					def doScript(event=None,name=name):
						from leoGlobals import executeScript
						executeScript(name)
					table.append((name,None,doScript),)
				
				c.frame.createMenuEntries(menu, table)
				#@nonl
				#@-node:<< Create a submenu for dir containing each file in files >>
				#@nl
#@nonl
#@-node:createScriptsMenu
#@-others

if 1: # Register the handlers...
	registerHandler("create-optional-menus",createScriptsMenu)
	
	__version__ = "1.4"
	plugin_signon(__name__)
#@nonl
#@-node:@file scripts_menu.py
#@-leo
