Пример #1
0
def get(image, master, allowRelativePath=False):
	"""Get image from standard locations.

	get(image, master) => TkImage

	image can be either a filename (or URL) or a Image.Image.  Filenames
	are searched for by chimera.pathFinder().  Master is the widget the
	result TkImage will be created for.  The master is needed for the Tk
	interpreter to place the image in and to find out the background color
	to blend the image with if it is semi-transparent.
	"""

	if isinstance(image, basestring):
		import os.path
		if allowRelativePath or os.path.isabs(image):
			filename = image
		else:
			filename = chimera.pathFinder().firstExistingFile(
						"chimera",
						os.path.join("images", image),
						False, False)
			if not filename:
				import errno
				raise IOError(errno.ENOENT,
					os.strerror(errno.ENOENT), image)
		try:
			image = Image.open(filename)
		except IOError, e:
			# PIL's IOError is missing the filename
			e = IOError(*(e.args + (filename,)))
			raise e
def create():
	global root
	global _reply
	global splash
	root = Tk.Tk(screenName=chimera.screen, className=chimera.AppName,
							sync=chimera.debug)
	splash = Tk.Frame(root, background="white")
	splash.columnconfigure(0, weight=1)
	splash.columnconfigure(2, weight=1)
	splash.rowconfigure(0, weight=1)
	root.title(chimera.title)
	if chimera.geometry:
		root.geometry(chimera.geometry)
	splash.master.protocol("WM_DELETE_WINDOW", _earlyExit)

	status = Tk.Label(splash, background="white", foreground="black",
			font="Helvetica -14 italic", anchor=Tk.W,
			justify=Tk.LEFT, borderwidth=0, text='startup status')
	status.grid(row=1, column=0, columnspan=2, sticky=Tk.EW)

	import chimage
	icon = chimage.get('chimera48.png', splash)
	logo = Tk.Label(splash, image=icon, borderwidth=0)
	logo.__image = icon
	logo.grid(row=0, column=0, sticky=Tk.E)

	icon = chimage.get('titleChimera.png', root)
	title = Tk.Label(splash, image=icon, borderwidth=0)
	title.__image = icon
	title.grid(row=0, column=1, sticky=Tk.EW)

	icon2 = chimage.get('brand.png', root)
	brand = Tk.Label(splash, image=icon2, borderwidth=0)
	brand.__image = icon2
	brand.grid(row=0, rowspan=2, column=2, sticky=Tk.W)

	winsys = splash.tk.call('tk', 'windowingsystem')
	if winsys == 'win32':
		import os.path
		filename = chimera.pathFinder().firstExistingFile("chimera",
					os.path.join("Icons", "chimera32.ico"),
					False, False)
		if filename:
			# this requires Tcl/Tk 8.3.3 (or newer)
			# top.wm_iconbitmap(filename)
			root.tk.call('wm', 'iconbitmap', root._w, filename)
	elif winsys == 'aqua':
		# in Tk 8.5 (8.6 carbon?), need to set useCustomMDEF for
		# images and colors in menus entries
		splash.tk.call("set", "::tk::mac::useCustomMDEF", "1")
		splash.tk.createcommand('::tk::mac::OpenDocument',
								_openDocument)

	splashReply = replyobj.SplashReply(status)
	_reply = replyobj.pushReply(splashReply, takeStdout=0, takeStderr=0)

	splash.pack(expand=True, fill=Tk.BOTH)
	if not splash.winfo_viewable():
		splash.wait_visibility()
 def icon(self):
     import chimera
     import os.path
     file = chimera.pathFinder().firstExistingFile(
         "chimera", os.path.join("images", "sideview.png"), False, False)
     if not file:
         return None
     return file
Пример #4
0
	def icon(self):
		import chimera
		import os.path
		file = chimera.pathFinder().firstExistingFile("chimera",
					os.path.join("images", "sideview.png"),
					False, False)
		if not file:
			return None
		return file
Пример #5
0
def setup():
	import StdTools
	preferences.addCategory("Tools", ToolsCategory, aliases=["Extensions"],
				manager=manager)
	manager.loadDirectory(chimera.pathFinder().dataRoot)
	StdTools.registerStandardTools()
	if chimera.nogui:
		return
	manager.createMenu()
	manager.showToolbarButtons()
Пример #6
0
def _getCacheDir():
    global _cacheDir
    if _cacheDir is None:
        import chimera
        pf = chimera.pathFinder()
        paths = pf.pathList("", "ccdcache", False, False, True)
        if paths:
            _cacheDir = paths[0]
        else:
            _cacheDir = ""
    return _cacheDir
Пример #7
0
def _getCacheDir():
	global _cacheDir
	if _cacheDir is None:
		import chimera
		pf = chimera.pathFinder()
		paths = pf.pathList("", "ccdcache", False, False, True)
		if paths:
			_cacheDir = paths[0]
		else:
			_cacheDir = ""
	return _cacheDir
Пример #8
0
    def __init__(self):
        from chimera import pathFinder
        import os.path
        import SwishE

        pf = pathFinder()
        data_root = pf.dataRoot
        idx_file = os.path.join(data_root,"chimera","helpdir","chimera-docs.idx")
        self.index = idx_file
        self.index = self.index.replace("\\","/")

        self.swisher = SwishE.new(repr(self.index))
Пример #9
0
def setup():
    import StdTools
    preferences.addCategory("Tools",
                            ToolsCategory,
                            aliases=["Extensions"],
                            manager=manager)
    manager.loadDirectory(chimera.pathFinder().dataRoot)
    StdTools.registerStandardTools()
    if chimera.nogui:
        return
    manager.createMenu()
    manager.showToolbarButtons()
def checkRegistration(nag=1):
    "Check registration status."

    pf = chimera.pathFinder()
    filenames = pf.allExistingFiles('', RegistrationFile)
    if not filenames:
        if nag:
            return _checkUsage(pf)
        else:
            return
    import x509
    store = x509.CAStore()
    smime = x509.SMIME(store)
    for filename in filenames:
        try:
            text, signers = smime.verifyFile(filename)
        except x509.error, emsg:
            if emsg == 'Verify error:Certificate has expired':
                replyobj.warning('Registration file "%s" '
                                 'has expired.\n' % filename)
            continue
        valid = 0
        for cert in signers:
            fromUC = 0
            fromCGL = 0
            fields = string.split(cert.subject(), '/')
            for f in fields:
                if f == 'O=University of California, San Francisco':
                    fromUC = 1
                elif f == 'OU=Computer Graphics Laboratory':
                    fromCGL = 1
            if fromUC and fromCGL:
                valid = 1
                break
        if not valid:
            replyobj.warning('Registration file "%s" '
                             'is not signed by CGL.\n' % filename)
        lines = string.split(text, '\r\n')
        param = {}
        for line in lines:
            try:
                key, value = map(string.strip, string.split(line, ':'))
            except ValueError:
                pass
            else:
                param[key] = value
        if param.has_key('Expires') \
        and time.time() > float(param['Expires']):
            replyobj.warning('Registration file "%s" '
                             'has expired.\n' % filename)
        # Other parameter-dependent processing can go here
        return param
    def __init__(self):
        from chimera import pathFinder
        import os.path
        import SwishE

        pf = pathFinder()
        data_root = pf.dataRoot
        idx_file = os.path.join(data_root, "chimera", "helpdir",
                                "chimera-docs.idx")
        self.index = idx_file
        self.index = self.index.replace("\\", "/")

        self.swisher = SwishE.new(repr(self.index))
Пример #12
0
	def __init__(self):
		dataFile = chimera.pathFinder().firstExistingFile("ResProp",
							"schemaData.py", 0, 1)
		if not dataFile:
			raise ImportError, "Could not find schema data file"

		execfile(dataFile)
		for name, colorScheme in self.colorSchemes.items():
			if _oldSelMain in colorScheme:
				for old, new in _translationDict.items():
					colorScheme[new] = colorScheme[old]
					del colorScheme[old]
		for schema in self.schemas:
			self.registerSchemaAsSelector(schema)
    def __init__(self):
        dataFile = chimera.pathFinder().firstExistingFile(
            "ResProp", "schemaData.py", 0, 1)
        if not dataFile:
            raise ImportError, "Could not find schema data file"

        execfile(dataFile)
        for name, colorScheme in self.colorSchemes.items():
            if _oldSelMain in colorScheme:
                for old, new in _translationDict.items():
                    colorScheme[new] = colorScheme[old]
                    del colorScheme[old]
        for schema in self.schemas:
            self.registerSchemaAsSelector(schema)
Пример #14
0
def filenames():
	import chimera
	pf = chimera.pathFinder()
	paths = pf.pathList("", "gfxinfo.txt")
	paths = paths[:-1]	# skip system location
	paths.reverse()
	for p in paths:
		if os.path.isabs(p):
			name = p
	else:
		name = os.path.abspath(paths[0])
	base = os.path.splitext(name)[0]
	save = base + '.sav'
	return name, save
def filenames():
    import chimera
    pf = chimera.pathFinder()
    paths = pf.pathList("", "gfxinfo.txt")
    paths = paths[:-1]  # skip system location
    paths.reverse()
    for p in paths:
        if os.path.isabs(p):
            name = p
    else:
        name = os.path.abspath(paths[0])
    base = os.path.splitext(name)[0]
    save = base + '.sav'
    return name, save
Пример #16
0
    def __init__(self):

        pf = pathFinder()
        img_src = os.path.join(pf.dataRoot, "DBPuppet", "image_bs.gif")

        WizShell.__init__(self, 4, 450, 175, img_src, img_bg_color='black')

        self.ftm = FileTypeMan.FileTypeMan()

        self.configStatus = True
        self.configStatusString = ''

        self.createPanelOne()
        self.createPanelTwo()
        self.createPanelThree()
        self.createPanelFour()
    def __init__(self):

        pf = pathFinder()
        img_src = os.path.join(pf.dataRoot, "DBPuppet", "image_bs.gif")

        WizShell.__init__(self, 4, 450, 175, img_src, img_bg_color='black')

        self.ftm = FileTypeMan.FileTypeMan()

        self.configStatus = True
        self.configStatusString = ''

        self.createPanelOne()
        self.createPanelTwo()
        self.createPanelThree()
        self.createPanelFour()
Пример #18
0
	def revertToDefaults(self):
		# temporarily protect 'self' from the execfile()
		s = self
		class dummyClass:
			pass
		self = dummyClass()
		dataFile = chimera.pathFinder().firstExistingFile("ResProp",
							"schemaData.py", 0, 0)
		if not dataFile:
			raise ImportError, "Could not find schema data file"
		execfile(dataFile)
		data = self
		self = s
		
		for schema in data.schemas:
			if schema in self.schemas:
				self.deleteSchema(schema)
			self.addSchema(schema, data.selections[schema],
						data.colorSchemes[schema])
Пример #19
0
    def __init__(self):
	pf = chimera.pathFinder()

	ROOT = pf.dataRoot

	img_src = os.path.join(ROOT, "BugReport", "1bug1.png")

	WizShell.__init__(self, 3, 200, 300, img_src, img_bg_color="white")


	self.createIntroPanel()

	if not self.checkConnection():
	    self.introText.configure(state='normal')
	    self.introText.delete(0.0, 'end')
	    self.introText.insert(0.0, "<font color=\"red\" size=\"+4\">"
		"Can't find network connection!</font>"
		"<p>Thank you for assisting us in the development process"
		" by using our feedback submission system."
		"  It does not appear that you are connected to the internet."
		"  A network connection is needed in order to send the"
		" feedback to the UCSF Computer Graphics Lab."
		"  Please try again when your computer is connected to a"
		" network.</p>"
		"<p>If you <i>do have</i> a network connection,"
		" but use a proxy to connect to the web,"
		" you can try configuring the proxy settings in the"
		" <a href=\"python:import dialogs, chimera;dialogs.display('preferences')."
		"setCategoryMenu(chimera.initprefs.WEBACCESS_PREF)\" "
		"title=\"Click to open 'Web Access' preferences\"> "
		"Web Access</a> preference category."
		"  More information on how to do this can be found in the"
		" <a href=\"python:chimera.help.display('UsersGuide/preferences.html#Web Access')\""
		" title=\"'Web Access' Preference category documentation\">"
		" Preferences documentation</a>.</p>"
		)
	    self.introText.configure(state='disabled')
	    self.buttonWidgets['Next'].configure(state='disabled')
	    self.buttonWidgets['Cancel'].configure(text='Try again later')

	self.createReportPanel()
	self.createResultPanel()
Пример #20
0
    def __init__(self):
        pf = chimera.pathFinder()

        ROOT = pf.dataRoot

        img_src = os.path.join(ROOT, "BugReport", "1bug1.png")

        WizShell.__init__(self, 3, 200, 300, img_src, img_bg_color="white")

        self.createIntroPanel()

        if not self.checkConnection():
            self.introText.configure(state='normal')
            self.introText.delete(0.0, 'end')
            self.introText.insert(
                0.0, "<font color=\"red\" size=\"+4\">"
                "Can't find network connection!</font>"
                "<p>Thank you for assisting us in the development process"
                " by using our feedback submission system."
                "  It does not appear that you are connected to the internet."
                "  A network connection is needed in order to send the"
                " feedback to the UCSF Computer Graphics Lab."
                "  Please try again when your computer is connected to a"
                " network.</p>"
                "<p>If you <i>do have</i> a network connection,"
                " but use a proxy to connect to the web,"
                " you can try configuring the proxy settings in the"
                " <a href=\"python:import dialogs, chimera;dialogs.display('preferences')."
                "setCategoryMenu(chimera.initprefs.WEBACCESS_PREF)\" "
                "title=\"Click to open 'Web Access' preferences\"> "
                "Web Access</a> preference category."
                "  More information on how to do this can be found in the"
                " <a href=\"python:chimera.help.display('UsersGuide/preferences.html#Web Access')\""
                " title=\"'Web Access' Preference category documentation\">"
                " Preferences documentation</a>.</p>")
            self.introText.configure(state='disabled')
            self.buttonWidgets['Next'].configure(state='disabled')
            self.buttonWidgets['Cancel'].configure(text='Try again later')

        self.createReportPanel()
        self.createResultPanel()
    def revertToDefaults(self):
        # temporarily protect 'self' from the execfile()
        s = self

        class dummyClass:
            pass

        self = dummyClass()
        dataFile = chimera.pathFinder().firstExistingFile(
            "ResProp", "schemaData.py", 0, 0)
        if not dataFile:
            raise ImportError, "Could not find schema data file"
        execfile(dataFile)
        data = self
        self = s

        for schema in data.schemas:
            if schema in self.schemas:
                self.deleteSchema(schema)
            self.addSchema(schema, data.selections[schema],
                           data.colorSchemes[schema])
Пример #22
0
	def saveSchemas(self):
		if not self.initialized:
			return

		saveLocs = chimera.pathFinder().pathList("ResProp",
						"schemaData.py", 0, 0, 1)
		for saveLoc in saveLocs:
			if not os.path.exists(saveLoc):
				# try to create
				dirPath, fileName = os.path.split(saveLoc)
				if not os.path.exists(dirPath):
					try:
						os.makedirs(dirPath)
					except:
						Pmw.MessageDialog(
						  title='Save Error',
						  message_text="Cannot create category save directory '%s'" % (dirPath))
						return
			try:
				saveFile = open(saveLoc, 'w')
			except IOError:
				print "Cannot write to %s" % saveLoc
				continue
			saveFile.write("self.schemas = %s\n"
						% repr(schemaMgr.schemas))
			saveFile.write("self.residues = %s\n"
						% repr(schemaMgr.residues))
			saveFile.write("self.selections = %s\n"
						% repr(schemaMgr.selections))
			saveFile.write("self.colorSchemes = {}\n")
			for schema in schemaMgr.schemas:
				saveFile.write("self.colorSchemes['%s'] = %s\n"
					% (schema,
					repr(schemaMgr.colorSchemes[schema])))
			saveFile.close()
			return
		Pmw.MessageDialog(message_text="Cannot save schema data.")
    def saveSchemas(self):
        if not self.initialized:
            return

        saveLocs = chimera.pathFinder().pathList("ResProp", "schemaData.py", 0,
                                                 0, 1)
        for saveLoc in saveLocs:
            if not os.path.exists(saveLoc):
                # try to create
                dirPath, fileName = os.path.split(saveLoc)
                if not os.path.exists(dirPath):
                    try:
                        os.makedirs(dirPath)
                    except:
                        Pmw.MessageDialog(
                            title='Save Error',
                            message_text=
                            "Cannot create category save directory '%s'" %
                            (dirPath))
                        return
            try:
                saveFile = open(saveLoc, 'w')
            except IOError:
                print "Cannot write to %s" % saveLoc
                continue
            saveFile.write("self.schemas = %s\n" % repr(schemaMgr.schemas))
            saveFile.write("self.residues = %s\n" % repr(schemaMgr.residues))
            saveFile.write("self.selections = %s\n" %
                           repr(schemaMgr.selections))
            saveFile.write("self.colorSchemes = {}\n")
            for schema in schemaMgr.schemas:
                saveFile.write("self.colorSchemes['%s'] = %s\n" %
                               (schema, repr(schemaMgr.colorSchemes[schema])))
            saveFile.close()
            return
        Pmw.MessageDialog(message_text="Cannot save schema data.")
Пример #24
0
  def __init__(self):

    self.shown = 0
    self.check_for_click = False
    
    import tkgui
    import Tkinter
    f = Tkinter.Frame(tkgui.app)
    self.frame = f

    # Create ext widget for displaying messages
    msg = Tkinter.Text(f, width = 0, height = 1,
                       borderwidth = 2, relief = 'ridge',
                       takefocus = False, cursor = 'left_ptr',
                       state = 'disabled')
    msg.bind('<Map>', self.message_label_mapped_cb)
    msg.grid(row = 0, column = 1, sticky = 'ew')
    f.columnconfigure(1, weight = 1)
    self.message_label = msg

    # Read in static icons
    import chimage
    self.image_info = chimage.get("information_frame.png", f)
    self.image_info_bw = chimage.get("information_frame_bw.png", f)
    self.image_stop = chimage.get("cross_octagon_frame.png", f)

    # Read in the selection icon, which is only in b/w because
    # we want to tint it with the user selected highlight color.
    # To do so, we need to have a PIL image to play with, so we
    # cannot use chimage.
    from CGLtk import textForeground
    icon_name = "magnifier_left_%s.png" % textForeground(f["background"])
    import chimera, os.path
    filename = chimera.pathFinder().firstExistingFile("chimera",
				      os.path.join("images", icon_name),
				      False, False)
    if not filename:
      import errno, os
      raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), icon_name)
    from PIL import Image
    self.pil_selection = image = Image.open(filename)
    self.image_selection_bw = remove_alpha(self.pil_selection, f)
    self.image_selection = None		# to be constructed later

    # Create selection button
    self.selections_button = Tkinter.Button(f, image=self.image_selection_bw,
					      command=self._sel_cb,
					      **button_opts)
    self.selections_button.grid(row=0, column=3, **grid_opts)
    self.selection_handler_ID = None
    self.first_selection = True

    # Create task buttons
    self.task_info_button = Tkinter.Button(f, image=self.image_info_bw,
					    command=self._task_info_cb,
					    **button_opts)
    self.task_info_button.grid(row=0, column=2, **grid_opts)
    self.task_stop_button = Tkinter.Button(f, image=self.image_stop,
					    command=self._task_stop_cb,
					    **button_opts)
    # Stop button is created here but grid'ed in only when needed
    self.task_event_queue = []
    self.task_stop_button.bind("<Key>", self._task_stop_key_handler)
    self.task_stop_button.bind("<Button-1>", self._task_stop_button_handler)

    # Create resize handle
    import Ttk
    sg = Ttk.Sizegrip(f)
    sg.grid(row=0, column=4, sticky='se')

    # Add help balloons to buttons
    import help
    help.register(self.selections_button, balloon="selection inspector")
    help.register(self.task_info_button, balloon="task panel")
    help.register(self.task_stop_button, balloon="cancel current task")
Пример #25
0
#
# Find a preferences file and load it
#
if chimera.preferencesFile is not None:
	pf = None
	if os.access(chimera.preferencesFile, os.R_OK):
		filename = chimera.preferencesFile
		preferences.load(filename)
	else:
		from chimera import replyobj
		replyobj.error("File \"%s\" is not readable\n" %
				chimera.preferencesFile)
		filename = None
else:
	pf = chimera.pathFinder()
	files = pf.allExistingFiles("", PreferenceFile)
	if files:
		for filename in files:
			try:
				preferences.load(filename)
			except IOError:
				continue
			except Exception, e:
				from chimera import replyobj
				replyobj.error(
					'%s: %s.\n'
					'Using factory default preference '
					'settings.\n'
					'The settings in the current '
					'preferences file cannot be\n'
Пример #26
0
except ImportError:
	pass

try:
	# attempt to get main/side chain selectors registered
	import chain
except ImportError:
	pass

try:
	# attempt to get surface category selectors registered
	import Categorizer
except ImportError:
	pass

# restore saved selectors
saveLoc = chimera.pathFinder().firstExistingFile(
					"selectionGUI", "selectors", 0, 1)
if saveLoc:
	try:
		saveFile = open(saveLoc, 'r')
	except:
		replyobj.error("Cannot read existing selector save file '%s'\n"
								% (saveLoc))
		saveFile = None
	if saveFile:
		selMgr.integrateSelDict(eval(saveFile.read()))
	del saveFile
del saveLoc

Пример #27
0
#
# Find a preferences file and load it
#
if chimera.preferencesFile is not None:
    pf = None
    if os.access(chimera.preferencesFile, os.R_OK):
        filename = chimera.preferencesFile
        preferences.load(filename)
    else:
        from chimera import replyobj
        replyobj.error("File \"%s\" is not readable\n" %
                       chimera.preferencesFile)
        filename = None
else:
    pf = chimera.pathFinder()
    files = pf.allExistingFiles("", PreferenceFile)
    if files:
        for filename in files:
            try:
                preferences.load(filename)
            except IOError:
                continue
            except Exception, e:
                from chimera import replyobj
                replyobj.error('%s: %s.\n'
                               'Using factory default preference '
                               'settings.\n'
                               'The settings in the current '
                               'preferences file cannot be\n'
                               'applied until the file has been '
Пример #28
0
				raise ValueError, "Line %d of %s is %s, " \
					"expected %s" % (chars.index(char)+1,
					fileName, fields[0], char)
			for i in range(len(chars)):
				matrix[(fields[0], chars[i])] = float(
								fields[i+1])
		mfile.close()
		break
	return matrix

import chimera
import os
matrices = {}
matrixFiles = {}

for dir in chimera.pathFinder().allExistingDirs("SmithWaterman", "matrices"):
	for matrixFile in os.listdir(dir):
		if matrixFile.endswith(".matrix"):
			ftype = "protein"
			name = matrixFile[:-7]
		elif matrixFile.endswith(".dnamatrix"):
			ftype = "dna"
			name = matrixFile[:-10]
		else:
			continue
		path = os.path.join(dir, matrixFile)
		try:
			matrices[name] = readMatrixFile(path, style=ftype)
		except ValueError:
			chimera.replyobj.reportException()
		matrixFiles[name] = path
Пример #29
0
    def __init__(self):

        self.shown = 0
        self.check_for_click = False

        import tkgui
        import Tkinter
        f = Tkinter.Frame(tkgui.app)
        self.frame = f

        # Create ext widget for displaying messages
        msg = Tkinter.Text(f,
                           width=0,
                           height=1,
                           borderwidth=2,
                           relief='ridge',
                           takefocus=False,
                           cursor='left_ptr',
                           state='disabled')
        msg.bind('<Map>', self.message_label_mapped_cb)
        msg.grid(row=0, column=1, sticky='ew')
        f.columnconfigure(1, weight=1)
        self.message_label = msg

        # Read in static icons
        import chimage
        self.image_info = chimage.get("information_frame.png", f)
        self.image_info_bw = chimage.get("information_frame_bw.png", f)
        self.image_stop = chimage.get("cross_octagon_frame.png", f)

        # Read in the selection icon, which is only in b/w because
        # we want to tint it with the user selected highlight color.
        # To do so, we need to have a PIL image to play with, so we
        # cannot use chimage.
        from CGLtk import textForeground
        icon_name = "magnifier_left_%s.png" % textForeground(f["background"])
        import chimera, os.path
        filename = chimera.pathFinder().firstExistingFile(
            "chimera", os.path.join("images", icon_name), False, False)
        if not filename:
            import errno, os
            raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), icon_name)
        from PIL import Image
        self.pil_selection = image = Image.open(filename)
        self.image_selection_bw = remove_alpha(self.pil_selection, f)
        self.image_selection = None  # to be constructed later

        # Create selection button
        self.selections_button = Tkinter.Button(f,
                                                image=self.image_selection_bw,
                                                command=self._sel_cb,
                                                **button_opts)
        self.selections_button.grid(row=0, column=3, **grid_opts)
        self.selection_handler_ID = None
        self.first_selection = True

        # Create task buttons
        self.task_info_button = Tkinter.Button(f,
                                               image=self.image_info_bw,
                                               command=self._task_info_cb,
                                               **button_opts)
        self.task_info_button.grid(row=0, column=2, **grid_opts)
        self.task_stop_button = Tkinter.Button(f,
                                               image=self.image_stop,
                                               command=self._task_stop_cb,
                                               **button_opts)
        # Stop button is created here but grid'ed in only when needed
        self.task_event_queue = []
        self.task_stop_button.bind("<Key>", self._task_stop_key_handler)
        self.task_stop_button.bind("<Button-1>",
                                   self._task_stop_button_handler)

        # Create resize handle
        import Ttk
        sg = Ttk.Sizegrip(f)
        sg.grid(row=0, column=4, sticky='se')

        # Add help balloons to buttons
        import help
        help.register(self.selections_button, balloon="selection inspector")
        help.register(self.task_info_button, balloon="task panel")
        help.register(self.task_stop_button, balloon="cancel current task")
    import residues
except ImportError:
    pass

try:
    # attempt to get main/side chain selectors registered
    import chain
except ImportError:
    pass

try:
    # attempt to get surface category selectors registered
    import Categorizer
except ImportError:
    pass

# restore saved selectors
saveLoc = chimera.pathFinder().firstExistingFile("selectionGUI", "selectors",
                                                 0, 1)
if saveLoc:
    try:
        saveFile = open(saveLoc, 'r')
    except:
        replyobj.error("Cannot read existing selector save file '%s'\n" %
                       (saveLoc))
        saveFile = None
    if saveFile:
        selMgr.integrateSelDict(eval(saveFile.read()))
    del saveFile
del saveLoc
                raise ValueError, "Line %d of %s is %s, " \
                 "expected %s" % (chars.index(char)+1,
                 fileName, fields[0], char)
            for i in range(len(chars)):
                matrix[(fields[0], chars[i])] = float(fields[i + 1])
        mfile.close()
        break
    return matrix


import chimera
import os
matrices = {}
matrixFiles = {}

for dir in chimera.pathFinder().allExistingDirs("SmithWaterman", "matrices"):
    for matrixFile in os.listdir(dir):
        if matrixFile.endswith(".matrix"):
            ftype = "protein"
            name = matrixFile[:-7]
        elif matrixFile.endswith(".dnamatrix"):
            ftype = "dna"
            name = matrixFile[:-10]
        else:
            continue
        path = os.path.join(dir, matrixFile)
        try:
            matrices[name] = readMatrixFile(path, style=ftype)
        except ValueError:
            chimera.replyobj.reportException()
        matrixFiles[name] = path