示例#1
0
def fetch_local_file(save_dir, save_name):

	import preferences
	if not preferences.get(FETCH_PREFERENCES, FETCH_LOCAL):
		return None
	dir = preferences.get(FETCH_PREFERENCES, FETCH_DIRECTORY)
	if not dir:
		return None
	from os.path import join, isfile
	path = join(dir, save_dir, save_name)
	if not isfile(path):
		return None
	return path
def fetch_local_file(save_dir, save_name):

    import preferences
    if not preferences.get(FETCH_PREFERENCES, FETCH_LOCAL):
        return None
    dir = preferences.get(FETCH_PREFERENCES, FETCH_DIRECTORY)
    if not dir:
        return None
    from os.path import join, isfile
    path = join(dir, save_dir, save_name)
    if not isfile(path):
        return None
    return path
示例#3
0
def show_message(text, append = 0, blankAfter=None, color='black',
                 followWith="", followTime=20, clickCallback=None,
                 showNow = True):

  status = status_line()
  if not status:
    return

  global _statusBlankHandle
  if _statusBlankHandle:
    status.frame.after_cancel(_statusBlankHandle)
    _statusBlankHandle = None

  status.message(text, append, color, clickCallback, showNow)

  blankTime = blankAfter
  if blankAfter is None:
    import preferences
    from chimera.replyobj import REPLY_PREFERENCES, STATUS_CLEARING
    blankTime = preferences.get(REPLY_PREFERENCES, STATUS_CLEARING)
  if blankTime != 0:
    if not followWith:
    	followTime = 0
    _statusBlankHandle = status.frame.after(1000 * blankTime, lambda:
			show_message(followWith, blankAfter=followTime))
示例#4
0
def show_message(text,
                 append=0,
                 blankAfter=None,
                 color='black',
                 followWith="",
                 followTime=20,
                 clickCallback=None,
                 showNow=True):

    status = status_line()
    if not status:
        return

    global _statusBlankHandle
    if _statusBlankHandle:
        status.frame.after_cancel(_statusBlankHandle)
        _statusBlankHandle = None

    status.message(text, append, color, clickCallback, showNow)

    blankTime = blankAfter
    if blankAfter is None:
        import preferences
        from chimera.replyobj import REPLY_PREFERENCES, STATUS_CLEARING
        blankTime = preferences.get(REPLY_PREFERENCES, STATUS_CLEARING)
    if blankTime != 0:
        if not followWith:
            followTime = 0
        _statusBlankHandle = status.frame.after(
            1000 * blankTime,
            lambda: show_message(followWith, blankAfter=followTime))
示例#5
0
def _bgCheckColor(cat, opt, c):
    oc = preferences.get(cat, opt)
    if c is None:
        if oc is not None:
            preferences.set(cat, opt, None)
    else:
        nc = c.rgba()
        if oc != nc:
            preferences.set(cat, opt, nc)
示例#6
0
def save_location(save_dir, save_name):

	import preferences
	if not preferences.get(FETCH_PREFERENCES, FETCH_SAVE):
		return None
	dir = preferences.get(FETCH_PREFERENCES, FETCH_DIRECTORY)
	from os.path import isdir, join, dirname
	if not dir or not isdir(dir):
		return None
	spath = join(dir, save_dir, save_name)
	sdir = dirname(spath)
	if not isdir(sdir):
		import os
		try:
			os.makedirs(sdir)
		except IOError:
			return None
	return spath
示例#7
0
def _bgCheckColor(cat, opt, c):
	oc = preferences.get(cat, opt)
	if c is None:
		if oc is not None:
			preferences.set(cat, opt, None)
	else:
		nc = c.rgba()
		if oc != nc:
			preferences.set(cat, opt, nc)
def save_location(save_dir, save_name):

    import preferences
    if not preferences.get(FETCH_PREFERENCES, FETCH_SAVE):
        return None
    dir = preferences.get(FETCH_PREFERENCES, FETCH_DIRECTORY)
    from os.path import isdir, join, dirname
    if not dir or not isdir(dir):
        return None
    spath = join(dir, save_dir, save_name)
    sdir = dirname(spath)
    if not isdir(sdir):
        import os
        try:
            os.makedirs(sdir)
        except IOError:
            return None
    return spath
示例#9
0
	def status(self, msg, blankAfter=None, echoToMain=False, log=False,
			followWith="", followTime=20, color='black'):
		"""Display a status message

		   'blankAfter' controls how long (in seconds) before the
		   status area is automatically cleared.  Use zero to disable
		   auto-clearing this message.  'None' uses the user preference.

		   'echoToMain' and 'log' control sending an identical message
		   to the main window status line and the reply log,
		   respectively.

		   'followWith' is a message to follow the first one with.
		   'followTime' is how long until the followup message is
		   cleared (ala blankAfter).

		   Show the text in 'color' color.
		"""
		from chimera import replyobj
		if not self.provideStatus:
			raise ValueError("no status support in dialog")
		if self._statusBlankHandle:
			self.statusLine.after_cancel(self._statusBlankHandle)
			self._statusBlankHandle = None

		if echoToMain:
			replyobj.status(msg, blankAfter=blankAfter, color=color)
		if log:
			replyobj.info(msg)
			if followWith:
				if not msg.endswith("\n"):
					msg += "\n"
				msg += "[above message copied to Reply Log]"
		self.statusLine.configure(text=msg.strip(), fg=color)
		self.statusLine.update_idletasks()

		blankTime = blankAfter
		if blankAfter is None:
			import preferences
			from replyobj import REPLY_PREFERENCES, STATUS_CLEARING
			blankTime = preferences.get(REPLY_PREFERENCES,
							STATUS_CLEARING)
		if blankTime != 0:
			if followWith:
				nextMsg = followWith
				nextTime = followTime
			elif log:
				nextMsg = "Previous message also written" \
						" to reply log"
				nextTime = 20
			else:
				nextMsg = ""
				nextTime = 0
			self._statusBlankHandle = self.statusLine.after(
				1000 * blankTime, lambda:
				self.status(nextMsg, blankAfter=nextTime))
def imageArgs(units, width=None, height=None, supersample=None):
	"""return 3-tuple with horizontal pixels, vertical pixels, supersample"""
	if not width:
		width, height = chimera.viewer.windowSize
	if units == 'pixels':
		scale = 1
	elif preferences.get(IMAGE_SETUP, USE_PRINT_UNITS):
		adjust = convert[units] / convert['inches']
		scale = preferences.get(IMAGE_SETUP, DPI) * adjust
	else:
		# use screen resolution
		scale = convert[units] / convert['pixels']
	if supersample is None:
		supersample = preferences.get(IMAGE_SETUP, SUPERSAMPLE)
	else:
		supersample = int(supersample)
	horizPixels = int(scale * width + 0.5)
	vertPixels = int(scale * height + 0.5)
	return horizPixels, vertPixels, supersample
示例#11
0
  def set_selections(self):
    # Construct selection icon by tinting the b/w version with
    # the selection color
    if self.image_selection is None:
      from bgprefs import BACKGROUND, HCOLOR
      import preferences
      sel_color = [ int(i * 255) for i in preferences.get(BACKGROUND, HCOLOR) ]
      self.image_selection = tint(self.pil_selection, tuple(sel_color),
								  self.frame)
      del self.pil_selection
    if self._any_selected():
      self.selections_button.config(image=self.image_selection)
    else:
      self.selections_button.config(image=self.image_selection_bw)
示例#12
0
 def set_selections(self):
     # Construct selection icon by tinting the b/w version with
     # the selection color
     if self.image_selection is None:
         from bgprefs import BACKGROUND, HCOLOR
         import preferences
         sel_color = [
             int(i * 255) for i in preferences.get(BACKGROUND, HCOLOR)
         ]
         self.image_selection = tint(self.pil_selection, tuple(sel_color),
                                     self.frame)
         del self.pil_selection
     if self._any_selected():
         self.selections_button.config(image=self.image_selection)
     else:
         self.selections_button.config(image=self.image_selection_bw)
 def popMode(self, log=0, **kw):
     """Exit a message mode"""
     if len(self._mode) == 1:
         return
     if self._mode[0] == STATUS:
         if log:
             info("".join(self._messages[0]))
             if 'followWith' not in kw:
                 kw['followWith'] = \
                "Previous message also written to reply log\n"
         self._showStatus(**kw)
         del self._messages[0]
     elif self._mode[0] != NORMAL:
         import preferences
         p = preferences.get(REPLY_PREFERENCES, self._mode[0])
         if p == DisplayDialog:
             self._showDialog()
         del self._messages[0]
     del self._mode[0]
     self._setMode(self._mode[0])
示例#14
0
	def popMode(self, log=0, **kw):
		"""Exit a message mode"""
		if len(self._mode) == 1:
			return
		if self._mode[0] == STATUS:
			if log:
				info("".join(self._messages[0]))
				if 'followWith' not in kw:
					kw['followWith'] = \
				"Previous message also written to reply log\n"
			self._showStatus(**kw)
			del self._messages[0]
		elif self._mode[0] != NORMAL:
			import preferences
			p = preferences.get(REPLY_PREFERENCES, self._mode[0])
			if p == DisplayDialog:
				self._showDialog()
			del self._messages[0]
		del self._mode[0]
		self._setMode(self._mode[0])
def checkPovrayLicense():
	if preferences.get(POVRAY_AGREE, LICENSE_AGREE):
		return True
	if not chimera.nogui:
		dialog = PovrayCheckLicense()
		agree = dialog.run(chimera.tkgui.app)
	else:
		text = PovrayLicenseText()
		if text:
			text = ("You must read and accept the following"
				" license agreement before raytracing an image"
				" with POV-Ray:\n\n") + text
		if not text:
			text = "You must read and accept the POV-Ray End-User License at <http://www.povray.org/povlegal.html>."
		print text
		import sys
		sys.stdout.write("\nDo you agree to the Pov-Ray End-User License (y/n)? [n] ")
		yesno = sys.stdin.readline() 
		agree = yesno[0] in "yY"
	preferences.set(POVRAY_AGREE, LICENSE_AGREE, agree)
	return agree
	def updateImageUnits(self, *args):
		units = self.units.get()
		if units == 'pixels':
			self.printRes.disable()
			self.adjustFOV.disable()
		else:
			self.printRes.enable()
			self.adjustFOV.enable()
		if units != preferences.get(IMAGE_SETUP, UNITS):
			preferences.set(IMAGE_SETUP, UNITS, units)
		try:
			adjust = convert[units]
		except KeyError:
			adjust = -1
		if adjust == self.adjust:
			return
		if self.adjust != -1 and adjust != -1:
			factor = self.adjust / adjust
			w = self.iWidth.get() * factor
			self.iWidth.set(w)
			h = self.iHeight.get() * factor
			self.iHeight.set(h)
		if adjust == -1:
			# entering pixel mode
			w, h = chimera.viewer.windowSize
			self.iWidth.set(w)
			self.iHeight.set(h)
		elif self.adjust == -1:
			pass
			# leaving pixel mode, sanity check
			#w, h = paper_types[preferences.get(PAGE_SETUP, PAPER_TYPE)]
			#if self.iWidth.get() > w:
			#	self.iWidth.set(w)
			#if self.iHeight.get() > h:
			#	self.iHeight.set(h)
		self.adjust = adjust
		self._computeMaxLineWidth()
示例#17
0
def _bgCheckOpt(cat, opt, b):
	ob = preferences.get(cat, opt)
	if ob != b:
		preferences.set(cat, opt, b)
    def status(self,
               msg,
               blankAfter=None,
               echoToMain=False,
               log=False,
               followWith="",
               followTime=20,
               color='black'):
        """Display a status message

		   'blankAfter' controls how long (in seconds) before the
		   status area is automatically cleared.  Use zero to disable
		   auto-clearing this message.  'None' uses the user preference.

		   'echoToMain' and 'log' control sending an identical message
		   to the main window status line and the reply log,
		   respectively.

		   'followWith' is a message to follow the first one with.
		   'followTime' is how long until the followup message is
		   cleared (ala blankAfter).

		   Show the text in 'color' color.
		"""
        from chimera import replyobj
        if not self.provideStatus:
            raise ValueError("no status support in dialog")
        if self._statusBlankHandle:
            self.statusLine.after_cancel(self._statusBlankHandle)
            self._statusBlankHandle = None

        if echoToMain:
            replyobj.status(msg, blankAfter=blankAfter, color=color)
        if log:
            replyobj.info(msg)
            if followWith:
                if not msg.endswith("\n"):
                    msg += "\n"
                msg += "[above message copied to Reply Log]"
        self.statusLine.configure(text=msg.strip(), fg=color)
        self.statusLine.update_idletasks()

        blankTime = blankAfter
        if blankAfter is None:
            import preferences
            from replyobj import REPLY_PREFERENCES, STATUS_CLEARING
            blankTime = preferences.get(REPLY_PREFERENCES, STATUS_CLEARING)
        if blankTime != 0:
            if followWith:
                nextMsg = followWith
                nextTime = followTime
            elif log:
                nextMsg = "Previous message also written" \
                  " to reply log"
                nextTime = 20
            else:
                nextMsg = ""
                nextTime = 0
            self._statusBlankHandle = self.statusLine.after(
                1000 * blankTime,
                lambda: self.status(nextMsg, blankAfter=nextTime))
示例#19
0
 def test_get(self):
     self.assertEqual(
         preferences.get(default=None, key='suspend - Electron'), None)
		subproc.setProgress(progress)
		info = 'running "%s"' % '" "'.join(cmd)
		if not chimera.nogui and statusMessages:
			from chimera import dialogs, tkgui
			dialogs.display(tkgui._ReplyDialog.name)
			replyobj.info(info + '\n')
		task.updateStatus(info)
		subprog = SM.monitor('running POV-Ray', subproc,
					title="POV-Ray progress",
					task=task,
					afterCB=afterCB)
		if raytraceWait:
			subprog.wait()
		return
	status("Rendering high resolution image...", blankAfter=0)
	artist = preferences.get(IMAGE_CREDITS, ARTIST).strip()
	copyright = preferences.get(IMAGE_CREDITS, COPYRIGHT).strip()
	if raiseWindow and not chimera.nogui:
		from chimera import tkgui
		import CGLtk
		CGLtk.raiseWindow(tkgui.app)
		# guarantee label balloon is gone (for command line interface)
		tkgui.app.cancelLabelBalloon()
	# encourage raise to take place
	if hideDialogs and not chimera.nogui:
		tkgui._hideChildren(tkgui.app, None)
		chimera.tkgui.update_windows()
	# if background has opacity then save opacity
	opacity = chimera.bgopacity
	try:
		images = chimera.viewer.pilImages(horizPixels, vertPixels,
示例#21
0
def chimeraLabel(item, showModel=None, modelName=False, style=None,
						diffWith=None, bondSep="-"):
	"""Return preferred chimera label for atom/bond/residue/molecule

	   'showModel' controls whether the model ID is part of the label
	   If the value type is boolean, then the model is shown if the value
	   is true.  If the value is None, then the model is shown if there
	   are multiple models, otherwise the model is omitted.

	   'modelName' controls whether the model name is part of the label.
	   Has no effect if atom specs are being returned.

	   'diffWith' can either be a string or of the same type as 'item';
	   the returned label will not include any leading components that
	   are the same as those in 'diffWith'

	   'style' controls whether the label uses atom specs, quasi-
	   English-like contents, or serial numbers.  It is either 'simple',
	   'command'/'command-line'/'osl', 'serial number', or None.
	   If None, then the user's preferences controls the contents.

	   'bondSep' controls the text separator between parts of a bond
	   when using English-like contents.
	"""

	if diffWith and not isinstance(diffWith, basestring):
		diffWith = chimeraLabel(diffWith, showModel, modelName, style)

	if not style:
		if chimera.nogui:
			style = "osl"
		else:
			import preferences
			from tkgui import GENERAL, ATOMSPEC_CONTENTS, \
					ATOMSPEC_SERIAL, ATOMSPEC_SIMPLE
			preferred = preferences.get(GENERAL, ATOMSPEC_CONTENTS)
			if preferred == ATOMSPEC_SERIAL:
				style = "serial number"
			elif preferred == ATOMSPEC_SIMPLE:
				style = "simple"
			else:
				# ATOMSPEC_MIDAS doesn't match value used
				# in NamingStyleOption, so make this the
				# 'else' case
				style = "osl"
	if style.startswith('command'):
		style = "osl"
	elif style.startswith('serial'):
		# command keyword values might only be 'serial'
		style = "serial number"

	if style == "serial number" and (not isinstance(item,  chimera.Atom)
				or not hasattr(item, 'serialNumber')):
		style = "simple"

	if isinstance(item, chimera.Bond) \
	or isinstance(item, chimera.PseudoBond):
		l1 = chimeraLabel(item.atoms[0], showModel, modelName,
								style, diffWith)
		l2 = chimeraLabel(item.atoms[1], showModel,
							modelName, style, l1)
		if not l2:
			l2 = item.atoms[1].name
		return l1 + bondSep + l2

	doShowModel = False
	if showModel:
		doShowModel = True
	if not doShowModel and isinstance(item, chimera.Model):
		doShowModel = True
	if not doShowModel and showModel == None \
	and len(chimera.openModels.list()) > 1:
		doShowModel = True
	if style == "osl":
		return chimeraOslLabel(item, diffWith, doShowModel)

	components = []
	if doShowModel:
		if hasattr(item, 'molecule') and item.molecule:
			mol = item.molecule
		else:
			mol = item

		if showModel or not modelName:
			components.append(mol.oslIdent())
		if modelName:
			if doShowModel:
				components.append("%s(%s)" % (mol.name,
							mol.oslIdent()))
			else:
				components.append(mol.name)
	if style == "serial number":
		if components and diffWith and diffWith.startswith(
							components[0] + " "):
			components = []
		return " ".join(components + [str(item.serialNumber)])
	res = None
	if isinstance(item, chimera.Residue):
		res = item
	elif isinstance(item, chimera.Atom):
		res = item.residue
	if res:
		components.append("%s %s" % (res.type, res.id))

	if isinstance(item, chimera.Atom):
		components.append(item.oslIdent(chimera.SelAtom)[1:])

	if len(components) == 0:
		retVal = chimeraOslLabel(item)	# Non-molecular object
	else:
		retVal = " ".join(components)
	full = retVal
	if diffWith:
		if full == diffWith:
			return ""
		for i in range(len(components)):
			if diffWith.startswith(" ".join(components[:i+1])+" "):
				retVal = " ".join(components[i+1:])
	return retVal
def saveImage(filename=None, width=None, height=None, format=None,
	      units="pixels", description=None, supersample=None,
	      master=None, printMode=None, raytrace=False,
	      raytracePreview=None, raytraceWait=None,
	      raytraceKeepInput=None,
	      hideDialogs=True, statusMessages=True, raiseWindow=True,
	      task=None):
	if chimera.nogui and chimera.opengl_platform() != 'OSMESA':
		raise chimera.UserError, "Need graphics to save images (or use headless Linux version)"
	if statusMessages:
		from replyobj import status
	else:
		def status(*args, **kw):
			pass
	if printMode is None:
		printMode = chimera.viewer.camera.mode()
	horizPixels, vertPixels, supersample = \
			imageArgs(units, width, height, supersample)
	savedSD = None	# saved screen distance
	if units != 'pixels':
		adjustFOV = preferences.get(IMAGE_SETUP, ADJUST_FOV)
		if adjustFOV == 1 or (adjustFOV == ONLY_STEREO_CAMERAS
						and printMode != 'mono'):
			# if image is twice as wide as screen,
			# screenDistance is half as much
			savedSD = chimera.viewer.camera.screenDistance
			adjust = convert[units] / convert['millimeters']
			image_width = width * adjust
			adjust = chimera.viewer.camera.windowWidth / image_width
			chimera.viewer.camera.screenDistance *= adjust
	if raytrace:
		if not checkPovrayLicense():
			return
		# TODO: make default an argument or preference
		if raytraceWait is None:
			raytraceWait = preferences.get(POVRAY_SETUP, WAIT_POVRAY)
		if raytraceKeepInput is None:
			raytraceKeepInput = preferences.get(POVRAY_SETUP, KEEP_INPUT)
		if raytracePreview is None:
			raytracePreview = preferences.get(POVRAY_SETUP, SHOW_PREVIEW)
		quality = DEFAULT_JPEG_QUALITY
		format = 'PNG'
		if not chimera.nogui and not filename:
			if not master:
				master = tkgui.app
			chooseDialog = _ChooseFileDialog(filterSet='povray',
					format=format)
			result = chooseDialog.run(master)
			if result is None:
				status("Image save cancelled.")
				return
			filename, format = result[0]
			quality = chooseDialog.quality.get()
		if not filename:
			replyobj.error("Need filename for POV-Ray output")
			return
		if filename.endswith('.png') or filename.endswith('.jpg'):
			povfilename = filename[:-4] + '.pov'
			inifilename = filename[:-4] + '.ini'
		else:
			povfilename = filename + '.pov'
			inifilename = filename + '.ini'
		if task is None:
			from chimera.tasks import Task
			task = Task("raytrace image", None)
		task.updateStatus("Generating POV-Ray data file")
		import exports
		exports.doExportCommand('POV-Ray', povfilename)
		task.updateStatus("Generating POV-Ray parameter file")
		if savedSD is not None:
			chimera.viewer.camera.screenDistance = savedSD
		import SubprocessMonitor as SM
		cmd = [
			preferences.get(POVRAY_SETUP, POVRAY_EXE),
			inifilename,
			"+I%s" % povfilename,
			"+O%s" % filename,
			"+V"		# need verbose to monitor progress
		]
		inifile = open(inifilename, 'w')
		print >> inifile, (
			"Width=%d\n"
			"Height=%d\n"
			# add font path, CHIMERA/share/fonts
			"Library_Path=\"%s\"\n"
			"Bounding=On\n"
			"Bounding_Threshold=1\n"
			"Split_Unions=On\n"
			"Remove_Bounds=On\n"
			"Quality=%d"
		) % (
			horizPixels,
			vertPixels,
			os.path.join(os.environ['CHIMERA'], 'share', 'fonts'),
			preferences.get(POVRAY_SETUP, POV_QUALITY)
		)
		if not preferences.get(POVRAY_SETUP, ANTIALIAS):
			print >> inifile, "Antialias=Off"
		else:
			print >> inifile, (
				"Antialias=On\n"
				"Antialias_Threshold=%f\n"
				"Antialias_Depth=%d\n"
				"Sampling_Method=%d"
			) % (
				preferences.get(POVRAY_SETUP, ANTIALIAS_THRESHOLD),
				preferences.get(POVRAY_SETUP, ANTIALIAS_DEPTH),
				preferences.get(POVRAY_SETUP, ANTIALIAS_METHOD)
			)
		if not preferences.get(POVRAY_SETUP, JITTER):
			print >> inifile, "Jitter=Off"
		else:
			print >> inifile, (
				"Jitter=On\n"
				"Jitter_Amount=%f\n"
			) % (
				preferences.get(POVRAY_SETUP, JITTER_AMOUNT),
			)
		oa = preferences.get(POVRAY_SETUP, OUTPUT_ALPHA)
		if oa == 1 or (oa == 2 and chimera.bgopacity):
			if chimera.viewer.depthCue:
				replyobj.warning("Depth-cueing disables transparent background")
			print >> inifile, "Output_Alpha=On"
		if format in ('PNG', 'Stereo PNG'):
			print >> inifile, ("; output PNG\n"
							"Output_File_Type=N8")
		elif format in ('JPEG', 'Stereo JPEG'):
			print >> inifile, ("; output JPEG\n"
					"Output_File_Type=J%d") % quality
		elif format in ('PPM'):
			print >> inifile, ("; output PPM\n"
							"Output_File_Type=P")
		if chimera.nogui or not raytracePreview:
			print >> inifile, "Display=Off"
		else:
			print >> inifile, "Display=On"
			if not raytraceWait:
				print >> inifile, "Pause_when_Done=On"
		inifile.close()
		if raytraceKeepInput:
			inputs = []
		else:
			inputs = [ povfilename, inifilename ]
		def afterCB(aborted, inputs=inputs, outputs=[filename]):
			import os
			for fn in inputs:
				try:
					os.remove(fn)
				except OSError:
					pass
			if aborted:
				for fn in outputs:
					try:
						os.remove(fn)
					except OSError:
						pass
		task.updateStatus("Starting POV-Ray")
		try:
			subproc = SM.Popen(cmd, stdin=None, stdout=None,
						stderr=SM.PIPE, daemon=True)
		except OSError, e:
			raise chimera.UserError, "Unable run POV-Ray executable: %s" % e
		progress = povrayProgress(subproc)
		progress.start()
		subproc.setProgress(progress)
		info = 'running "%s"' % '" "'.join(cmd)
		if not chimera.nogui and statusMessages:
			from chimera import dialogs, tkgui
			dialogs.display(tkgui._ReplyDialog.name)
			replyobj.info(info + '\n')
		task.updateStatus(info)
		subprog = SM.monitor('running POV-Ray', subproc,
					title="POV-Ray progress",
					task=task,
					afterCB=afterCB)
		if raytraceWait:
			subprog.wait()
		return
示例#23
0
def get_suspend_preference(pid):
    return preferences.get("suspend - %s" % process.get_name(pid))
	def fillInUI(self, master):
		self._ModelTrigger = None
		#self._SetupTrigger = None
		self._SizeTrigger = None
		self.raytrace = None
		# Image Size
		imageSetup = Tix.LabelFrame(master, label="Image Size")
		imageSetup.pack(fill=Tk.X, ipadx=2, ipady=2)
		subframe = imageSetup.frame
		#subframe = Tk.Frame(imageSetup.frame)
		#subframe.pack(fill=Tk.BOTH, expand=1)

		# add in conversion factor for pixels and graphics screen
		from chimera import tkgui
		win = tkgui.app.graphics
		res = tkgui.getScreenMMWidth() / win.winfo_screenwidth()
		convert['pixels'] = mm2pt(res)

		self.matchAspect = Tk.BooleanVar(master)
		self.matchAspect.set(1)

		self.usePrint = Tk.BooleanVar(master)
		self.usePrint.set(preferences.get(IMAGE_SETUP, USE_PRINT_UNITS))
		import itertools
		row = itertools.count()

		self.showUsePrint = Tk.Checkbutton(subframe, indicatoron=1,
				variable=self.usePrint, highlightthickness=0,
				text=USE_PRINT_UNITS,
				command=self._updateUsePrint)
		self.showUsePrint.grid(columnspan=2, row=row.next(), sticky=Tk.W)

		w, h = chimera.viewer.windowSize
		self.units = ImageUnitsOption(subframe, row.next(), UNITS,
						'pixels', self.updateImageUnits)
		self.iWidth = FloatOption(subframe, row.next(), 'Image width',
					w, self.updateImageWidth, min=1e-10)
		self.iHeight = FloatOption(subframe, row.next(), 'Image height',
					h, self.updateImageHeight, min=1e-10)

		matchAspect = Tk.Checkbutton(subframe, indicatoron=1,
				variable=self.matchAspect, highlightthickness=0,
				text="Maintain current aspect ratio",
				command=self.updateMatchAspect)
		matchAspect.grid(columnspan=2, row=row.next(), sticky=Tk.W)
		self.grow = Tk.Button(imageSetup.frame, text="Grow to Fit",
					command=self.Resize, state=Tk.DISABLED)
		fitrow = row.next()
		self.grow.grid(row=fitrow, column=0, padx=2, pady=2,
								sticky=Tk.NSEW)
		self.shrink = Tk.Button(imageSetup.frame, text="Shrink to Fit",
				command=lambda f=self.Resize: f(False),
				state=Tk.DISABLED)
		self.shrink.grid(row=fitrow, column=1, padx=2, pady=2,
								sticky=Tk.NSEW)

		#fetch = Tk.Button(imageSetup.frame, text="Get Pixels",
		#				command=self.fetchWindowSize)
		#fetch.grid(row=row.next(), column=0, padx=2, pady=2, sticky=Tk.NSEW)

		#calc = Tk.Button(imageSetup.frame, text="Image Setup",
		#			command=self.showImageSetupDialog)
		#calc.grid(row=row.next(), column=1, padx=2, pady=2, sticky=Tk.NSEW)

		self.printRes = FloatOption(subframe, row.next(), DPI,
				preferences.get(IMAGE_SETUP, DPI),
				self._updatePrint, min=1)

		# Image Information
		info = Tix.LabelFrame(master, label="Image Information")
		info.pack(fill=Tk.X)
		d = Tk.Label(info.frame, text="Description:")
		d.grid(columnspan=2, row=0, column=0, sticky=Tk.W, padx=2,
									pady=1)
		self.description = Tk.Entry(info.frame)
		info.frame.grid_columnconfigure(0, weight=1)
		info.frame.grid_columnconfigure(1, weight=1)
		self.description.grid(columnspan=2, row=1, column=0,
						sticky=Tk.EW, padx=2, pady=2)
		imageCredits = Tk.Button(info.frame,
					text="Image Credits",
					command=self.showImageCreditsDialog)
		imageCredits.grid(row=2, column=0, padx=2, pady=2)
		credit = Tk.Button(info.frame, text="Citing Chimera",
				command=lambda: help.display("credits.html"))
		credit.grid(row=2, column=1, padx=2, pady=2)

		# Image camera
		self.raytrace = BooleanOption(master, -1,
				'Raytrace with POV-Ray', False,
				self._updateRaytrace)
		self.raytraceOptions = Tk.Button(master, text=POVRAY_SETUP,
					command=self.showPOVRayOptions)
		self.raytraceOptions.pack()
		self.raytraceOptions.pack_forget()
		self.supersample = SupersampleOption(master, -1, SUPERSAMPLE,
				preferences.get(IMAGE_SETUP, SUPERSAMPLE),
				self._updateSS)
		self.adjustFOV = AdjustFOVOption(master, -1, ADJUST_FOV,
				preferences.get(IMAGE_SETUP, ADJUST_FOV),
				self._updateAdjustFOV)
		self.printMode = _PrintModeOption(master, -1,
				'Image camera mode', _PrintModeOption.SAME,
				self._updatePrintMode)
		self.lenticular = IntOption(master, -1,
				'Number of lenticular images',
				chimera.Camera.lenticularImageCount(),
				self._updateLenticular, min=2, width=4)
		self.lenticular.forget()

		# switch to user's prefered units
		self.adjust = convert['pixels']
		units = preferences.get(IMAGE_SETUP, UNITS)
		self._updateUsePrint()
		self.units.set(units)
		self.updateImageUnits()
示例#25
0
def _bgCheckOpt(cat, opt, b):
    ob = preferences.get(cat, opt)
    if ob != b:
        preferences.set(cat, opt, b)
示例#26
0
def chimeraLabel(item,
                 showModel=None,
                 modelName=False,
                 style=None,
                 diffWith=None,
                 bondSep="-"):
    """Return preferred chimera label for atom/bond/residue/molecule

	   'showModel' controls whether the model ID is part of the label
	   If the value type is boolean, then the model is shown if the value
	   is true.  If the value is None, then the model is shown if there
	   are multiple models, otherwise the model is omitted.

	   'modelName' controls whether the model name is part of the label.
	   Has no effect if atom specs are being returned.

	   'diffWith' can either be a string or of the same type as 'item';
	   the returned label will not include any leading components that
	   are the same as those in 'diffWith'

	   'style' controls whether the label uses atom specs, quasi-
	   English-like contents, or serial numbers.  It is either 'simple',
	   'command'/'command-line'/'osl', 'serial number', or None.
	   If None, then the user's preferences controls the contents.

	   'bondSep' controls the text separator between parts of a bond
	   when using English-like contents.
	"""

    if diffWith and not isinstance(diffWith, basestring):
        diffWith = chimeraLabel(diffWith, showModel, modelName, style)

    if not style:
        if chimera.nogui:
            style = "osl"
        else:
            import preferences
            from tkgui import GENERAL, ATOMSPEC_CONTENTS, \
              ATOMSPEC_SERIAL, ATOMSPEC_SIMPLE
            preferred = preferences.get(GENERAL, ATOMSPEC_CONTENTS)
            if preferred == ATOMSPEC_SERIAL:
                style = "serial number"
            elif preferred == ATOMSPEC_SIMPLE:
                style = "simple"
            else:
                # ATOMSPEC_MIDAS doesn't match value used
                # in NamingStyleOption, so make this the
                # 'else' case
                style = "osl"
    if style.startswith('command'):
        style = "osl"
    elif style.startswith('serial'):
        # command keyword values might only be 'serial'
        style = "serial number"

    if style == "serial number" and (not isinstance(item, chimera.Atom)
                                     or not hasattr(item, 'serialNumber')):
        style = "simple"

    if isinstance(item, chimera.Bond) \
    or isinstance(item, chimera.PseudoBond):
        l1 = chimeraLabel(item.atoms[0], showModel, modelName, style, diffWith)
        l2 = chimeraLabel(item.atoms[1], showModel, modelName, style, l1)
        if not l2:
            l2 = item.atoms[1].name
        return l1 + bondSep + l2

    doShowModel = False
    if showModel:
        doShowModel = True
    if not doShowModel and isinstance(item, chimera.Model):
        doShowModel = True
    if not doShowModel and showModel == None \
    and len(chimera.openModels.list()) > 1:
        doShowModel = True
    if style == "osl":
        return chimeraOslLabel(item, diffWith, doShowModel)

    components = []
    if doShowModel:
        if hasattr(item, 'molecule') and item.molecule:
            mol = item.molecule
        else:
            mol = item

        if showModel or not modelName:
            components.append(mol.oslIdent())
        if modelName:
            if doShowModel:
                components.append("%s(%s)" % (mol.name, mol.oslIdent()))
            else:
                components.append(mol.name)
    if style == "serial number":
        if components and diffWith and diffWith.startswith(components[0] +
                                                           " "):
            components = []
        return " ".join(components + [str(item.serialNumber)])
    res = None
    if isinstance(item, chimera.Residue):
        res = item
    elif isinstance(item, chimera.Atom):
        res = item.residue
    if res:
        components.append("%s %s" % (res.type, res.id))

    if isinstance(item, chimera.Atom):
        components.append(item.oslIdent(chimera.SelAtom)[1:])

    if len(components) == 0:
        retVal = chimeraOslLabel(item)  # Non-molecular object
    else:
        retVal = " ".join(components)
    full = retVal
    if diffWith:
        if full == diffWith:
            return ""
        for i in range(len(components)):
            if diffWith.startswith(" ".join(components[:i + 1]) + " "):
                retVal = " ".join(components[i + 1:])
    return retVal
示例#27
0
文件: install.py 项目: laffra/Tempo
import utils
import os
import preferences

APP_LOCATION = "/Applications/tempo.app"
SETUP_SCRIPT = 'tell application "System Events" to make login item at end with properties {path:"%s", hidden:false}' % APP_LOCATION
LAUNCH_AT_LOGIN_KEY = "ENABLE_LAUNCH_AT_LOGIN"

if os.path.exists(APP_LOCATION):
    if preferences.get(LAUNCH_AT_LOGIN_KEY):
        preferences.set(LAUNCH_AT_LOGIN_KEY, "true")
        utils.run_osa_script(SETUP_SCRIPT)

示例#28
0
def get_license():
    try:
        return preferences.get("license") or download_license()
    except:
        error.error("Cannot find license")