python_code
stringlengths 0
992k
| repo_name
stringlengths 8
46
| file_path
stringlengths 5
162
|
---|---|---|
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
builtin_command_loaders.py -- loaders for NE1 builtin commands, used in order.
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
Module classification: [bruce 080209]
For now, part of Command Sequencer package, since knows
the list of hardcoded commandnames the Command Sequencer uses
to let other code invoke builtin commands, and knows which
ones should be always loaded and in what order.
Someday, after refactoring, it might belong in ne1_startup.
(Maybe it even belongs there now.)
History:
Bruce 080209 split this out of GLPane.py (where it existed
for purely historical reasons). Semantically it was part
of the Command Sequencer, and it's now split out of there
too.
TODO:
Refactor the code that uses this data (in Command Sequencer)
so its _commandTable is a separate object with which
we register the loading code herein, so it can load
some commands lazily.
"""
from commands.BuildCrystal.BuildCrystal_Command import BuildCrystal_Command
from commands.Extrude.extrudeMode import extrudeMode
from commands.Paste.PasteFromClipboard_Command import PasteFromClipboard_Command
from commands.PartLibrary.PartLibrary_Command import PartLibrary_Command
from commands.PlayMovie.movieMode import movieMode
from commands.PlaneProperties.Plane_EditCommand import Plane_EditCommand
from commands.RotaryMotorProperties.RotaryMotor_EditCommand import RotaryMotor_EditCommand
from commands.LinearMotorProperties.LinearMotor_EditCommand import LinearMotor_EditCommand
from commands.BuildAtoms.BuildAtoms_Command import BuildAtoms_Command
from commands.SelectAtoms.SelectAtoms_Command import SelectAtoms_Command
from commands.SelectChunks.SelectChunks_Command import SelectChunks_Command
from commands.Move.Move_Command import Move_Command
from commands.Rotate.RotateChunks_Command import RotateChunks_Command
from commands.Translate.TranslateChunks_Command import TranslateChunks_Command
from commands.Fuse.FuseChunks_Command import FuseChunks_Command
from commands.StereoProperties.StereoProperties_Command import StereoProperties_Command
from commands.TestGraphics.TestGraphics_Command import TestGraphics_Command
from commands.ColorScheme.ColorScheme_Command import ColorScheme_Command
from commands.LightingScheme.LightingScheme_Command import LightingScheme_Command
from commands.QuteMol.QuteMol_Command import QuteMol_Command
from temporary_commands.ZoomToAreaMode import ZoomToAreaMode
from temporary_commands.ZoomInOutMode import ZoomInOutMode
from temporary_commands.PanMode import PanMode
from temporary_commands.RotateMode import RotateMode
from temporary_commands.LineMode.Line_Command import Line_Command
from temporary_commands.RotateAboutPoint_Command import RotateAboutPoint_Command
# Carbon nanotube commands
from cnt.commands.BuildNanotube.BuildNanotube_EditCommand import BuildNanotube_EditCommand
from cnt.commands.InsertNanotube.InsertNanotube_EditCommand import InsertNanotube_EditCommand
from cnt.commands.EditNanotube.EditNanotube_EditCommand import EditNanotube_EditCommand
# DNA commands
from dna.commands.BuildDna.BuildDna_EditCommand import BuildDna_EditCommand
from dna.commands.InsertDna.InsertDna_EditCommand import InsertDna_EditCommand
from dna.commands.DnaSegment.DnaSegment_EditCommand import DnaSegment_EditCommand
from dna.commands.DnaStrand.DnaStrand_EditCommand import DnaStrand_EditCommand
from dna.commands.MakeCrossovers.MakeCrossovers_Command import MakeCrossovers_Command
from dna.commands.BreakStrands.BreakStrands_Command import BreakStrands_Command
from dna.commands.JoinStrands.JoinStrands_Command import JoinStrands_Command
from dna.commands.OrderDna.OrderDna_Command import OrderDna_Command
from dna.commands.DnaDisplayStyle.DnaDisplayStyle_Command import DnaDisplayStyle_Command
from dna.commands.MultipleDnaSegmentResize.MultipleDnaSegmentResize_EditCommand import MultipleDnaSegmentResize_EditCommand
from dna.temporary_commands.DnaLineMode import DnaLineMode
from dna.commands.JoinStrands.ClickToJoinStrands_Command import ClickToJoinStrands_Command
from dna.commands.JoinStrands.JoinStrands_By_DND_RequestCommand import JoinStrands_By_DND_RequestCommand
from dna.commands.ConvertDna.ConvertDna_Command import ConvertDna_Command
# Protein commands
from protein.commands.InsertPeptide.InsertPeptide_EditCommand import InsertPeptide_EditCommand
from protein.commands.ProteinDisplayStyle.ProteinDisplayStyle_Command import ProteinDisplayStyle_Command
from protein.commands.EditProtein.EditProtein_Command import EditProtein_Command
from protein.commands.EditResidues.EditResidues_Command import EditResidues_Command
from protein.commands.CompareProteins.CompareProteins_Command import CompareProteins_Command
from protein.commands.BuildProtein.BuildProtein_Command import BuildProtein_Command
from protein.commands.BuildProtein.ModelProtein_Command import ModelProtein_Command
from protein.commands.BuildProtein.SimulateProtein_Command import SimulateProtein_Command
from protein.commands.FixedBBProteinSim.FixedBBProteinSim_Command import FixedBBProteinSim_Command
from protein.commands.BackrubProteinSim.BackrubProteinSim_Command import BackrubProteinSim_Command
# Graphene commands
from commands.InsertGraphene.Graphene_EditCommand import Graphene_EditCommand
from commands.BuildAtoms.BondTool_Command import SingleBondTool
from commands.BuildAtoms.BondTool_Command import DoubleBondTool
from commands.BuildAtoms.BondTool_Command import TripleBondTool
from commands.BuildAtoms.BondTool_Command import AromaticBondTool
from commands.BuildAtoms.BondTool_Command import GraphiticBondTool
from commands.BuildAtoms.BondTool_Command import DeleteBondTool
from commands.BuildAtoms.BondTool_Command import BondTool_Command
from commands.BuildAtoms.AtomsTool_Command import AtomsTool_Command
def preloaded_command_classes():
"""
Return a list of command classes for the commands which are always loaded
on startup, and should always be reinitialized (in this order)
when new command objects are needed.
@note: currently this includes all loadable builtin commands,
but soon we will implement a way for some commands to be
loaded lazily, and remove many commands from this list.
@note: commands should be initialized in this order, in case this makes
some bugs deterministic. In theory, any order should work (and it's
a bug if it doesn't), but in practice, we have found that some
mysterious Qt bugs (C crashes) depend on which command classes are
instantiated at startup, so it seems safest to keep all this
deterministic, even at the cost of failing to detect our own
order-dependency bugs if any creep in.
"""
# classes for builtin commands (or unsplit modes) which were preloaded
# by toplevel imports above, in order of desired instantiation:
command_classes = [
SelectChunks_Command,
SelectAtoms_Command,
BuildAtoms_Command,
Move_Command,
BuildCrystal_Command,
extrudeMode,
movieMode,
ZoomToAreaMode,
ZoomInOutMode,
PanMode,
RotateMode,
PasteFromClipboard_Command,
PartLibrary_Command,
Line_Command,
DnaLineMode,
InsertDna_EditCommand,
Plane_EditCommand,
LinearMotor_EditCommand,
RotaryMotor_EditCommand,
BreakStrands_Command,
JoinStrands_Command,
ClickToJoinStrands_Command,
JoinStrands_By_DND_RequestCommand,
MakeCrossovers_Command,
BuildDna_EditCommand,
DnaSegment_EditCommand,
DnaStrand_EditCommand,
MultipleDnaSegmentResize_EditCommand,
OrderDna_Command,
ConvertDna_Command,
DnaDisplayStyle_Command,
BuildNanotube_EditCommand,
InsertNanotube_EditCommand,
EditNanotube_EditCommand,
Graphene_EditCommand,
RotateChunks_Command,
TranslateChunks_Command,
FuseChunks_Command,
RotateAboutPoint_Command,
StereoProperties_Command,
TestGraphics_Command,
QuteMol_Command,
ColorScheme_Command,
InsertPeptide_EditCommand,
ProteinDisplayStyle_Command,
LightingScheme_Command,
EditProtein_Command,
EditResidues_Command,
CompareProteins_Command,
ModelProtein_Command,
SimulateProtein_Command,
BuildProtein_Command,
FixedBBProteinSim_Command,
BackrubProteinSim_Command,
#Tools in Build Atoms command --
SingleBondTool,
DoubleBondTool,
TripleBondTool,
AromaticBondTool,
GraphiticBondTool,
DeleteBondTool,
AtomsTool_Command,
BondTool_Command
]
# note: we could extract each one's commandName (class constant)
# if we wanted to return them as commandName, commandClass pairs
return command_classes
# end
| NanoCAD-master | cad/src/commandSequencer/builtin_command_loaders.py |
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details.
"""
CommandSequencer.py - class for sequencing commands and maintaining command stack.
Each Assembly owns one of these.
@author: Bruce (partly based on older code by Josh)
@version: $Id$
@copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details.
History:
Bruce 2004 or 2005: written (partly based on older code by Josh),
as class modeMixin in modes.py, mixin class for GLPane
Bruce 071009 split into its own file
Bruce 071030 file (but not class) renamed to CommandSequencer
Bruce 2008 made "not GLPANE_IS_COMMAND_SEQUENCER" work (not yet on by default)
Bruce 2008 (with Ninad working in other files) made USE_COMMAND_STACK work
Bruce 080909 class renamed from modeMixin to CommandSequencer
Bruce 080911 turned off GLPANE_IS_COMMAND_SEQUENCER by default
Bruce 080925 remove support for GLPANE_IS_COMMAND_SEQUENCER
Ninad 2008-09-26: Turned on USE_COMMAND_STACK by default; stripped out old code
[old comment:]
roughly: mode -> command or currentCommand, ...
"""
import os
import sys
from utilities.constants import DEFAULT_COMMAND
from utilities.debug import print_compact_traceback, print_compact_stack
from utilities import debug_flags
import foundation.env as env
from commandSequencer.command_levels import allowed_parent
from command_support.modes import nullMode
from command_support.baseCommand import baseCommand # only for isinstance assertion
_DEBUG_CSEQ_INIT = False # DO NOT COMMIT with True
_SAFE_MODE = DEFAULT_COMMAND
DEBUG_COMMAND_SEQUENCER = False
_DEBUG_F_UPDATE_CURRENT_COMMAND = False
_DEBUG_COMMAND_STACK_LOCKING = False
# ==
# TODO: mode -> command or currentCommand in lots of comments, some method names
class CommandSequencer(object):
"""
Controller/owner class for command stack and command switching behavior.
(Each Assembly owns one of these. Before 080911/080925, it was instead
a mixin of class GLPane.)
External API for changing command stack (will be revised):
to enter a given command:
- userEnterCommand
to exit a command (and perhaps then enter a specific new one):
- command.command_Done, others
other:
- start_using_initial_mode
- exit_all_commands
Maintains instance attributes currentCommand, graphicsMode (deprecated
to access it from here) (both read-only for public access), and mostly private
attributes for access by command-sequencing code in class Command,
such as nullmode and _commandTable.
@note: graphicsMode is also available from GLPane, which gets it from here
via its assy. Maybe it won't be needed from here at all... so we print
a console warning whenever it's accessed directly from here.
Public attributes available during calls of command.command_will_exit:
exit_is_cancel -- whether this exit is caused by Cancel.
exit_is_forced -- whether this exit is forced to occur (e.g. caused by
exit_all_commands when closing a model).
warn_about_abandoned_changes -- when exit_is_forced, whether the user should
be warned about changes (if any) stored in active commands being exited
(as opposed to changes stored in the model in assy, as usual) which are
being discarded unavoidably
exit_is_implicit -- whether this exit is occuring only as a prerequisite
of entering some other command
exit_target -- if not None, the goal of the exit is ultimately to exit
the command of this commandName
enter_target -- if not None, the goal of the exit is ultimately to enter
the command of this commandName
"""
# Note: works directly with some code in class baseCommand and basicCommand
#
# older comment: this class will be replaced with an aspect of the command
# sequencer, and will use self.currentCommand rather than self.mode...
# so some code which uses glpane.mode is being changed to get
# commandSequencer from win.commandSequencer (which for now is just the
# glpane; that will change) and then use commandSequencer.currentCommand.
# But the command-changing methods like userEnterCommand are being left as
# commandSequencer.userEnterCommand until they're better understood.
# [bruce 071008 comment]
# Note: see "new code" far below for comments and definitions about the
# attributes of self which we maintain, namely mode, graphicsMode,
# currentCommand.
prevMode = property() # hopefully this causes errors on any access of it ### check this
_command_stack_change_counter = 0
_flyout_command_change_counter = 0
_previous_flyout_update_indicators = None
# these are documented in our class docstring:
exit_is_cancel = False
exit_is_forced = False
warn_about_abandoned_changes = True
exit_is_implicit = False
exit_target = None
enter_target = None
pass
def __init__(self, assy): #bruce 080813
"""
WARNING: This only partly initializes self.
Subsequent init calls should also be made, namely:
- _reinit_modes, from glpane.setAssy, from _make_and_init_assy or GLPane.__init__
- start_using_initial_mode - end of MWsemantics.__init__, or _make_and_init_assy.
To reuse self "from scratch", perhaps with new command objects (as used to be necessary
when self was a GLPane mixin which could be reused with a new assy)
and/or new command classes (e.g. after a developer reloads some of them),
first call self.exit_all_commands(), then do only the "subsequent init calls"
mentioned above -- don't call this method again.
"""
# todo: should try to clean up init code (see docstring)
# now that USE_COMMAND_STACK is always true.
if _DEBUG_CSEQ_INIT:
print "_DEBUG_CSEQ_INIT: __init__"###
self.assy = assy
self.win = assy.win
assert self.assy
assert self.win
# make sure certain attributes are present (important once we're a
# standalone object, since external code expects us to have these
# even if we don't need them ourselves) (but it's ok if they're still None)
self.win # probably used only in EditCommand and in some methods in self
self.assy # used in self and in an unknown amount of external code
self._registered_command_classes = {} #bruce 080805
self._recreate_nullmode()
self._use_nullmode()
# see docstring for additional inits needed as external calls
return
def _recreate_nullmode(self): # only called from this file, as of 080805
self.nullmode = nullMode()
# TODO: rename self.nullmode; note that it's semi-public [###REVIEW: what uses it?];
# it's a safe place to absorb events that come at the wrong time
# (mainly in case of bugs, but also happens routinely sometimes)
return
def _reinit_modes(self): #revised, bruce 050911, 080209
"""
@see: docstring for __init__
"""
# note: as of 080812, not called directly in this file; called from:
# - GLPane.setAssy (end of function),
# which is called from:
# - GLPane.__init__ (in partwindow init)
# - MWSemantics._make_and_init_assy (fileOpen/fileClose)
# - extrudeMode.extrude_reload (followed by .start_using_initial_mode( '$DEFAULT_MODE' )).
# Each call is followed eventually by start_using_initial_mode,
# but in some cases this is in a different method or not nearby.
#
# Maybe todo: encapsulate that pair (_reinit_modes and start_using_initial_mode)
# into a reset_command_sequencer method, even though it can't yet be used
# by the main calls of this listed above; and/or make the reinit of
# command objects lazy (per-command-class), so calling this is optional,
# at least in methods like extrude_reload.
# old docstring:
"""
[bruce comment 040922, when I split this out from GLPane's
setAssy method; comment is fairly specific to GLPane:]
Call this near the end of __init__, and whenever the mode
objects need to be remade. Create new mode objects (one
for each mode, ready to take over mouse-interaction
whenever that mode is in effect).
[As of 050911, leave self.mode as nullmode, not the default mode.]
We redo this whenever
the current assembly changes, since the mode objects store
the current assembly in some menus they make. (At least
that's one reason I noticed -- there might be more. None of
this was documented before now.) (#e Storing the current
assembly in the modes might cause trouble, if our
functionality is extended in certain ways; if we someday
fix that, the mode objects could be retained for the
lifetime of their command sequencer. But there's no reason we need to
keep them longer, unless they store some other sort of
state (like user preferences), which is probably also bad
for them to do. So we can ignore this for now.)
"""
if _DEBUG_CSEQ_INIT:
print "_DEBUG_CSEQ_INIT: reinit modes"###
self.exit_all_commands()
self._commandTable = {}
# this discards any mode objects that already existed
# (it probably doesn't destroy them -- they are likely
# to be part of reference cycles)
# create new mode objects; they know about our method
# self.store_commandObject, and call it with their modenames and
# themselves
#bruce 050911 revised this: now includes class of default mode
#bruce 080209 change:
# import the following now, not when GLPane is imported (as was
# effectively done before today's refactoring split out this new file)
# (might help with bug 2614?)
from commandSequencer.builtin_command_loaders import preloaded_command_classes # don't move this import to toplevel!
# review: could this be toplevel now that GLPANE_IS_COMMAND_SEQUENCER
# is never true? I don't know; I can't recall why this should not be
# toplevel, though I do recall I had a good reason when I added
# that comment fairly recently. [bruce 080925 comment]
for command_class in preloaded_command_classes():
commandName = command_class.commandName
assert not self._commandTable.has_key(commandName)
# use preloaded_command_classes for ordering, even when
# instantiating registered classes that replace them
actual_class = self._registered_command_classes.get(
commandName, command_class )
if actual_class is not command_class:
print "fyi: instantiating replacement command %r" % (actual_class,)
assert actual_class.commandName == commandName
# always true, due to how these are stored and looked up
self._instantiate_cached_command( actual_class)
# now do the rest of the registered classes
# (in order of their commandNames, so bugs are more likely
# to be deterministic)
more_items = self._registered_command_classes.items()
more_items.sort()
for commandName, actual_class in more_items:
if not self._commandTable.has_key(commandName):
print "fyi: instantiating registered non-built-in command %r" % (actual_class,)
self._instantiate_cached_command( actual_class)
# todo: something to support lazily loaded/instantiated commands
# (make self._commandTable a dictlike object that loads on demand?)
## self.start_using_initial_mode( '$DEFAULT_MODE')
#bruce 050911 removed this; now we leave it at nullmode,
# let direct or indirect callers put in the mode they want
# (since different callers want different modes, and during init
# some modes are not ready to be entered anyway)
return # from _reinit_modes
def _instantiate_cached_command( self, command_class): #bruce 080805 split this out
new_command = command_class(self)
# kluge: new mode object passes itself to
# self.store_commandObject; it would be better for us to store
# it ourselves
# (to implement that, first add code to assert every command
# does this in the name we expect)
assert new_command is self._commandTable[command_class.commandName]
return new_command
def store_commandObject(self, commandName, commandObject): #bruce 080209
"""
Store a command object to use (i.e. enter) for the given commandName.
(If a prior one is stored for the same commandName, replace it.)
@note: commands call this in their __init__ methods. (Unfortunately.)
"""
assert commandObject.commandName == commandName #bruce 080805
self._commandTable[commandName] = commandObject
def exit_all_commands(self, warn_about_abandoned_changes = True):
"""
Exit all currently active commands (even the default command),
and leave the current command as nullMode.
During the exiting, make sure self.exit_is_forced is true
when examined by exit-related methods in command classes.
@param warn_about_abandoned_changes: if False, unsaved changes (if any)
stored in self's active commands
(as opposed to unsaved changes stored
in the model in self.assy)
can be discarded with no user warning.
(Otherwise they are discarded with a
warning. There is no way for this code
or the user to avoid discarding them.)
Note that it is too late to offer to
not discard them -- caller must do that
separately if desired (and if user
agrees to discard them, caller should
pass True to this option to avoid a
duplicate warning).
This is only needed due to there being
some changes stored in commands but
not in assy, which are not noticed by
assy.has_changed(). Most commands don't
store any such changes.
@type warn_about_abandoned_changes: boolean
"""
#bruce 080806 split this out; used in _reinit_modes and extrude_reload
#bruce 080909 new feature, warn_about_abandoned_changes can be false
while self._raw_currentCommand and \
not self.currentCommand.is_null and \
not self.currentCommand.is_default_command():
# exit current command
old_commandName = self.currentCommand.commandName
try:
self._exit_currentCommand_with_flags(
forced = True,
warn_about_abandoned_changes = warn_about_abandoned_changes
)
except:
print_compact_traceback()
if self._raw_currentCommand and \
self.currentCommand.commandName == old_commandName:
print "bug: failed to exit", self.currentCommand
break
continue
# Now we're in the default command. Some callers require us to exit
# that too. Exiting it in the above loop would fail, but fortunately
# we can just discard it (unlike for a general command). [Note: this
# might change if it was given a PM.]
self._use_nullmode()
return
def _exit_currentCommand_with_flags(self,
cancel = False,
forced = False,
warn_about_abandoned_changes = True,
implicit = False,
exit_target = None,
enter_target = None
): #bruce 080827
"""
Call self.currentCommand._f_command_do_exit_if_ok
(and return what it returns)
while setting attrs on self (only during this call)
based on the options passed (as documented below).
@param cancel: value for self.exit_is_cancel, default False
@param forced: value for self.exit_is_forced, default False
(only passed as True by exit_all_commands)
@param implicit: value for self.exit_is_implicit, default False
@param exit_target: value for self.exit_target, default None
@param enter_target: value for self.enter_target, default None
"""
assert self.currentCommand and self.currentCommand.parentCommand
# set attrs for telling command_will_exit what side effects to do
self.exit_is_cancel = cancel
self.exit_is_forced = forced
self.warn_about_abandoned_changes = warn_about_abandoned_changes
self.exit_is_implicit = implicit
# set attrs to let command_exit methods construct dialog text, etc
# (when used along with the other attrs)
self.exit_target = exit_target # a commandName, if we're exiting it as a goal ### FIX to featurename?
self.enter_target = enter_target # a commandName, if we're entering it as a goal ### FIX to featurename?
# exit the current command, return whether it worked
try:
res = self.currentCommand._f_command_do_exit_if_ok()
finally:
#TODO: except clause, protect callers (unless that method does it)
self.exit_is_cancel = False
self.exit_is_forced = False
self.warn_about_abandoned_changes = True
self.exit_is_implicit = False
self.exit_target = None
self.enter_target = None
return res
def remove_command_object(self, commandName): #bruce 080805
try:
del self._commandTable[commandName]
except KeyError:
print "fyi: no command object for %r in prepare_to_reload_commandClass" % commandName
return
def register_command_class(self, commandName, command_class): #bruce 080805
"""
Cause this command class to be instantiated by the next call
of self._reinit_modes, or [nim] the next time something needs
to look up a command object for commandName.
"""
assert command_class.commandName == commandName
self._registered_command_classes[commandName] = command_class
# REVIEW: also remove_command_object? only safe when it can be recreated lazily.
return
def _use_nullmode(self):
"""
[private]
self._raw_currentCommand = self.nullmode
"""
# note: 4 calls, all in this file, as of before 080805; making it private
#
# Note: This is only called during
# exit_all_commands (with current command being default command),
# and during init or reinit of self (with current command always being
# nullMode, according to debug prints no longer present).
#[bruce 080814/080909 comment]
self._raw_currentCommand = self.nullmode
def is_this_command_current(self, command):
"""
Semi-private method for use by Command.isCurrentCommand;
for doc, see that method.
"""
# We compare to self._raw_currentCommand in case self.currentCommand
# has been wrapped by an API-enforcement (or any other) proxy.
return self._raw_currentCommand is command
# not used as of before 080929, but keep for now:
## def _update_model_between_commands(self):
## # review: when USE_COMMAND_STACK, this might be needed (as much as it ever was),
## # but calling it is NIM. For now, we'll try not calling it and
## # see if this ever matters. It may be that we even do update_parts
## # before redraw or undo checkpoint, which makes this even less necessary.
## # [bruce 080909 comment]
## #bruce 050317: do update_parts to insulate new mode from prior one's bugs
## try:
## self.assy.update_parts()
## # Note: this is overkill (only known to be needed when leaving
## # extrude, and really it's a bug that it doesn't do this itself),
## # and potentially too slow (though I doubt it),
## # and not a substitute for doing this at the end of operations
## # that need it (esp. once we have Undo); but doing it here will make
## # things more robust. Ideally we should "assert_this_was_not_needed".
## except:
## print_compact_traceback("bug: update_parts: ")
## else:
## if debug_flags.atom_debug:
## self.assy.checkparts() #bruce 050315 assy/part debug code
## return
def start_using_initial_mode(self, mode): #bruce 080812
"""
[semi-private]
Initialize self to the given initial mode,
which must be one of the strings '$STARTUP_MODE' or '$DEFAULT_MODE',
just after self is created or _reinit_modes is called.
@see: docstring of __init__.
@see: exit_all_commands
"""
# as of 080812, this is called from 3 places:
# - MWsemantics.__init__
# - _make_and_init_assy
# - extrude_reload
assert mode in ('$STARTUP_MODE', '$DEFAULT_MODE')
#bruce 080814 guess for USE_COMMAND_STACK case:
self._raw_currentCommand = None ###??
command_instance = self._find_command_instance( mode)
# note: exception if this fails to find command (never returns false)
entered = command_instance._command_do_enter_if_ok()
assert entered
return
def _cseq_update_after_new_mode(self): # rename?
"""
Do whatever updates are needed after self.currentCommand (including
its graphicsMode aspect) might have changed.
@note: it's ok if this is called more than needed, except it
might be too slow. In practice, as of 080813 it looks
like it is usually called twice after most command changes.
This should be fixed, but it's not urgent.
"""
#bruce 080813 moved/renamed this from GLPane.update_after_new_mode,
# and refactored it
if DEBUG_COMMAND_SEQUENCER:
print "DEBUG_COMMAND_SEQUENCER: calling _cseq_update_after_new_mode"
glpane = self.assy.glpane
glpane.update_GLPane_after_new_command()
#bruce 080903 moved this before the call of update_after_new_graphicsMode
# (precaution, in case glpane.scale, which it can alter, affects that)
glpane.update_after_new_graphicsMode() # includes gl_update
self.win.win_update() # includes gl_update (redundant calls of that are ok)
#e also update tool-icon visual state in the toolbar? [presumably done elsewhere now]
# bruce 041222 [comment revised 050408, 080813]:
# changed this to a full update (not just a glpane update),
# and changed MWsemantics to make that safe during our __init__
# (when that was written, it referred to GLPane.__init__,
# which is when self was initialized then).
return
def _Entering_Mode_message(self, mode, resuming = False):
featurename = mode.get_featurename()
if resuming:
msg = "Resuming %s" % featurename
else:
msg = "Entering %s" % featurename
try: # bruce 050112
# (could be made cleaner by defining too_early in HistoryWidget,
# or giving message() a too_early_ok option)
too_early = env.history.too_early # true when early in init
except AttributeError: # not defined after init!
too_early = 0
if not too_early:
from utilities.Log import greenmsg
env.history.message( greenmsg( msg), norepeat_id = msg )
return msg
def _find_command_instance(self, commandName_or_obj = None): # note: only used in this file [080806]
"""
Internal method: look up the specified commandName
(e.g. 'MODIFY' for Move)
or command-role symbolic name (e.g. '$DEFAULT_MODE')
in self._commandTable, and return the command object found.
Or if a command object is passed, return it unchanged.
Exception if requested command object is not found -- unlike
pre-050911 code, never return some other command than asked for;
let caller use a different one if desired.
"""
# todo: clean up the old term MODE used in the string constants
assert commandName_or_obj, "commandName_or_obj arg should be a command object " \
"or commandName, not None or whatever false value it is here: %r" % \
(commandName_or_obj,)
if type(commandName_or_obj) == type(''):
# usual case - internal or symbolic commandName string
# TODO: a future refactoring should cause caller to do
# the symbol replacements, so this is either a commandName
# or object, since caller will need to match this to currently
# active commands anyway. [bruce 080806 comment]
commandName = commandName_or_obj
if commandName == '$SAFE_MODE':
commandName = _SAFE_MODE
if commandName == '$STARTUP_MODE':
commandName = self.startup_commandName() # might be '$DEFAULT_MODE'
if commandName == '$DEFAULT_MODE':
commandName = self.default_commandName()
# todo: provision for lazy instantiation, if not already in _commandTable
return self._commandTable[ commandName]
else:
# assume it's a command object; make sure it's legit
command = commandName_or_obj
commandName = command.commandName # make sure it has this attr
# (todo: rule out error of it's being a command class)
#bruce 080806 removed the following:
## mode1 = self._commandTable[commandName] # the one we'll return
## if mode1 is not command:
## # this should never happen
## print "bug: invalid internal command; using %r" % \
## (commandName,)
## return mode1
return command
pass
def _commandName_properties(self, commandName): #bruce 080814
# STUB -- just use the cached instance for its properties.
# (Note: if commandName is a command object, this method just returns that object.
# For now, we depend on this in test_commands_init.py. [bruce 080910 comment])
return self._find_command_instance(commandName)
# default and startup command name methods.
# These were written by bruce 060403 in UserPrefs.py (now Preferences.py)
# and at some point were settable by user preferences.
# They were revised to constants by ninad 070501 for A9,
# then moved into this class by bruce 080709 as a refactoring.
def default_commandName(self):
"""
Return the commandName string of the user's default mode.
"""
# note: at one point this made use of env.prefs[ defaultMode_prefs_key].
return DEFAULT_COMMAND
def startup_commandName(self):
"""
Return the commandName string (literal or symbolic, e.g.
'$DEFAULT_MODE') of the user's startup mode.
"""
# note: at one point this made use of env.prefs[ startupMode_prefs_key].
return DEFAULT_COMMAND
# user requests a specific new command.
def userEnterCommand(self, want_commandName, always_update = False):
"""
[main public method for changing command stack
to get into a specified command]
Exit and enter commands as needed, so that the current command
has the given commandName.
@see: userEnterCommand_OLD_DOCSTRING
"""
### TODO: docstring probably could use more info which is now in
# the docstring of userEnterCommand_OLD_DOCSTRING. But most of that
# docstring is obsolete, so I'm not just copying it here unedited.
# [bruce 080929 comment]
#
# todo: remove always_update from callers if ok.
self._f_assert_command_stack_unlocked()
do_update = always_update # might be set to True below
del always_update
error = False # might be changed below
# look up properties of desired command
want_command = self._commandName_properties(want_commandName)
# has command properties needed for this...
# for now, just a command instance, but AFAIK the code
# only assumes it has a few properties and methods,
# namely command_level, command_parent, and helper methods
# for interpreting them.
if want_commandName != want_command.commandName:
#bruce 080910
if want_commandName is want_command:
# this is routine when we're called from test_commands_init.py
print "fyi: command object %r passed as want_commandName to userEnterCommand" % want_commandName
want_commandName = want_command.commandName # make following code work
else:
assert 0, "commandName mismatch: userEnterCommand gets want_commandName %r, " \
"led to want_command %r whose commandName is %r" % \
(want_commandName, want_command, want_command.commandName )
pass
pass
assert type(want_commandName) == type(""), "not a string: %r" % (want_commandName,) #bruce 080910
# exit incompatible commands as needed
while not error:
# exit current command, if necessary and possible
old_commandName = self.currentCommand.commandName
if old_commandName == want_commandName:
# maybe: add option to avoid this check, for use on reloaded commands
break
if self._need_to_exit(self.currentCommand, want_command):
do_update = True # even if error
exited = self._exit_currentCommand_with_flags(implicit = True,
enter_target = want_commandName)
assert exited == (old_commandName != self.currentCommand.commandName)
# review: zap retval and just use this condition?
if not exited:
error = True
else:
break
continue
# enter prerequisite parent commands as needed, then the wanted command
# (note: this code is similar to that in _enterRequestCommand)
while not error:
# enter the next command we need to enter, if possible
old_commandName = self.currentCommand.commandName
if old_commandName == want_commandName:
break
next_commandName_to_enter = self._next_commandName_to_enter( self.currentCommand, want_command)
# note: might be want_commandName; never None
assert old_commandName != next_commandName_to_enter, \
"should be different: old_commandName %r, next_commandName_to_enter %r" % \
(old_commandName, next_commandName_to_enter)
do_update = True # even if error
command_instance = self._find_command_instance( next_commandName_to_enter)
# note: exception if this fails to find command (never returns None)
entered = command_instance._command_do_enter_if_ok()
assert entered == (old_commandName != self.currentCommand.commandName)
assert entered == (next_commandName_to_enter == self.currentCommand.commandName)
# review: zap retval and just use this last condition?
if not entered:
error = True
# review: add direct protection against infinite loop?
# bugs to protect against include a cycle or infinite series
# in the return values of _next_commandName_to_enter, or modifications
# to command stack in unexpected places in this loop.
continue
if error:
print "error trying to enter", want_commandName #e more info
if do_update:
self._cseq_update_after_new_mode()
# Q: when do we call command_post_event_ui_updater, which calls command_update_state,
# and some related methods in the current command and/or all active commands?
# A: after the current user event handler finishes.
# Q: how do we tell something that it needs to be called?
# A: we don't, it's always called (after every user event).
return
def _enterRequestCommand(self, commandName): #bruce 080904
"""
[private]
Immediately enter the specified command, by pushing it on the command
stack, not changing the command stack in any other ways (e.g. exiting
commands or checking for required parent commands).
Do necessary updates from changing the command stack, but not
_update_model_between_commands (in case it's too slow).
@see: callRequestCommand, which calls this.
"""
# note: this code is similar to parts of userEnterCommand
old_commandName = self.currentCommand.commandName
command_instance = self._find_command_instance( commandName)
# note: exception if this fails to find command (never returns None)
entered = command_instance._command_do_enter_if_ok()
# note: that method might be overkill, but it's probably ok for now
assert entered == (old_commandName != self.currentCommand.commandName)
assert entered == (commandName == self.currentCommand.commandName)
assert entered, "error trying to enter %r" % commandName
# neither caller nor this method's API yet tolerates failure to enter
self._cseq_update_after_new_mode()
# REVIEW: should this be up to caller, or controlled by an option?
return
def _need_to_exit(self, currentCommand, want_command): #bruce 080814 # maybe: rename?
"""
"""
return not allowed_parent( want_command, currentCommand )
def _next_commandName_to_enter(self, currentCommand, want_command): #bruce 080814
"""
Assume we need to enter zero or more commands and then enter want_command,
and are at the given currentCommand (known to not already be want_command).
Assume that we don't need to exit any commands (caller has already done
that if it was needed).
Return the commandName of the next command we should try to enter.
If want_command is nestable, this is always its own commandName.
Otherwise, it's its own name if currentCommand is its required
parentCommand, otherwise it's the name of its required parentCommand
(or perhaps of a required grandparent command, etc, if that can ever happen).
We never return the name of the default command, since we assume
it's always on the command stack. [### REVIEW whether that's good or true]
"""
if not want_command.is_fixed_parent_command():
# nestable command (partly or fully)
return want_command.commandName
else:
# fixed-parent command
### STUB: ASSUME ONLY ONE LEVEL OF REQUIRED PARENT COMMAND IS POSSIBLE (probably ok for now)
needs_parentName = want_command.command_parent or self.default_commandName()
if currentCommand.commandName == needs_parentName:
return want_command.commandName
# future: check other choices, if more than one level of required
# parent is possible.
# note: if this is wrong, nothing is going to verify we're ready
# to enter this command -- it's just going to get immediately
# entered (pushed on the command stack).
return needs_parentName
pass
def _f_exit_active_command(self, command, cancel = False, forced = False, implicit = False): #bruce 080827
"""
Exit the given command (which must be active), after first exiting
any subcommands it may have.
Do side effects appropriate to the options passed, by setting
corresponding attributes in self which can be tested by subclass
implementations of command_will_exit. For documentation of these
attributes and their intended effects, see the callers which pass
them, listed below, and the attributes of related names in
this class, described in the class docstring.
@param command: the command it's our ultimate goal to exit.
Must be an active command, but may or may not be
self.currentCommand. Its commandName is saved as
self.exit_target.
@param cancel: @see: baseCommand.command_Cancel and self.exit_is_cancel
@param forced: @see: CommandSequencer.exit_all_commands and self.exit_is_forced
@param implicit: @see: baseCommand.command_Done and self.exit_is_implicit
"""
self._f_assert_command_stack_unlocked()
if DEBUG_COMMAND_SEQUENCER:
print "DEBUG_COMMAND_SEQUENCER: _f_exit_active_command wants to exit back to", command
assert command.command_is_active(), "can't exit inactive command: %r" % command
# exit commands, innermost (current) first, until we fail,
# or exit the command we were passed (our exit_target).
error = False
do_update = False
while not error:
old_command = self.currentCommand
if DEBUG_COMMAND_SEQUENCER:
print "DEBUG_COMMAND_SEQUENCER: _f_exit_active_command will exit currentCommand", old_command
exited = self._exit_currentCommand_with_flags( cancel = cancel,
forced = forced,
implicit = implicit,
exit_target = command.commandName )
if not exited:
error = True
break
else:
do_update = True
assert self.currentCommand is not old_command
if old_command is command:
# we're done
break
continue # exit more commands
if do_update:
# note: this can happen even if error is True
# (when exiting multiple commands at once)
# review: should we call self._update_model_between_commands() like old code did?
# Note that no calls to it are implemented in USE_COMMAND_STACK case
# (not for entering commands, either). This might cause new bugs.
self._cseq_update_after_new_mode()
pass
if DEBUG_COMMAND_SEQUENCER:
print "DEBUG_COMMAND_SEQUENCER: _f_exit_active_command returns, currentCommand is", self.currentCommand
return
_f_command_stack_is_locked = None # None or a reason string
def _f_lock_command_stack(self, why = None):
assert not self._f_command_stack_is_locked
self._f_command_stack_is_locked = why or "for some reason"
if _DEBUG_COMMAND_STACK_LOCKING:
print "_DEBUG_COMMAND_STACK_LOCKING: locking command stack:", self._f_command_stack_is_locked ###
return
def _f_unlock_command_stack(self):
assert self._f_command_stack_is_locked
self._f_command_stack_is_locked = None
if _DEBUG_COMMAND_STACK_LOCKING:
print "_DEBUG_COMMAND_STACK_LOCKING: unlocking command stack"
return
def _f_assert_command_stack_unlocked(self):
assert not self._f_command_stack_is_locked, \
"bug: command stack is locked: %r" % \
self._f_command_stack_is_locked
return
# ==
def userEnterCommand_OLD_DOCSTRING(self, commandName, always_update = False):
### TODO: docstring needs merging into that of userEnterCommand
"""
Public method, called from the UI when the user asks to enter
a specific command (named by commandName), e.g. using a toolbutton
or menu item. It can also be called inside commands which want to
change to another command.
The commandName argument can be a commandName string, e.g. 'DEPOSIT',
or a symbolic name like '$DEFAULT_MODE', or [### VERIFY THIS]
a command instance object. (Details of commandName, and all options,
are documented in Command._f_userEnterCommand [### TODO: revise doc,
since that method no longer exists].)
If commandName is a command name string and we are already in that
command, then do nothing unless always_update is true [new feature,
080730; prior code did nothing except self._cseq_update_after_new_mode(),
equivalent to passing always_update = True to new code].
Note: all calls which pass always_update as of 080730 do so only
to preserve old code behavior; passing it is probably not needed
for most of them. [###REVIEW those calls]
The current command has to exit (or be suspended) before the new one
can be entered, but it's allowed to refuse to exit, and if it does
exit it needs a chance to clean up first. So we let the current
command implement this method and decide whether to honor the user's
request. (If it doesn't, it should emit a message explaining why not.
If it does, it should call the appropriate lower-level command-switching
method [### TODO: doc what those are or where to find out].
(If that raises an exception, we assume the current command has a bug
and fall back to default behavior here.)
TODO: The tool icons ought to visually indicate the current command,
but for now this is done by ad-hoc code inside individual commands
rather than in any uniform way. One defect of that scheme is that
the code for each command has to know what UI buttons might invoke it;
another is that it leads to that code assuming that a UI exists,
complicating future scripting support. When this is improved, the
updating of toolbutton status might be done by
self._cseq_update_after_new_mode().
[Note, that's now in GLPane but should probably move into this class.]
@see: MWsemantics.ensureInCommand
"""
assert 0 # this method exists only for its docstring
# ==
def find_innermost_command_named(self, commandName, starting_from = None):
"""
@return: the innermost command with the given commandName attribute,
or None if no such command is found.
@rtype: an active command object, or None
@param commandName: name of command we're searching for (e.g. 'BUILD_PROTEIN')
@type: string
@param starting_from: if provided, start the search at this command
@type: an active command object (*not* a command name), or None.
"""
for command in self.all_active_commands(starting_from = starting_from):
if command.commandName == commandName:
return command
return None
def all_active_commands(self, starting_from = None):
"""
@return: all active commands, innermost (current) first
@rtype: list of one or more active command objects
@param starting_from: if provided, must be an active command,
and the return value only includes it and
its parent commands (recursively).
Note that passing the current command is
equivalent to not providing this argument.
"""
# note: could be written as a generator, but there's no need
# (the command stack is never very deep).
if starting_from is None:
starting_from = self.currentCommand
# maybe: assert starting_from is an active command
commands = [starting_from]
command = starting_from.parentCommand # might be None
while command is not None:
commands.append(command)
command = command.parentCommand
return commands
# ==
_entering_request_command = False
_request_arguments = None
_accept_request_results = None
_fyi_request_data_was_accessed = False
def callRequestCommand(self,
commandName,
arguments = None,
accept_results = None
): #bruce 080801
"""
"Call" the specified request command (asynchronously -- push it on the
command stack and return immediately).
As it's entered (during this method call), it will record the given
arguments (a tuple, default ()) for use by the request command.
When it eventually exits (never during this method call, and almost
always in a separate user event handler from this method call),
it will call accept_results with the request results
(or with None if it was cancelled and has no results ### DECIDE whether it
might instead just not bother to call it if canceled -- for now,
this depends on the caller, but current callers require that this
callback be called no matter how the request command exits).
It should then exit itself by calling one of its methods
command_Done or command_Cancel.
The format and nature of the request arguments and results depend on
the particular request command, but by convention (possibly
enforced) they are always tuples.
The accept_results callback is usually a bound method in the command
which is calling this method.
@param commandName: commandName of request command to call
@type commandName: string
@param arguments: tuple of request arguments (None is interpreted as ())
@type arguments: tuple, or None
@param accept_results: callback for returning request results
@type accept_results: callable (required argument, can't be None) ###DOC args it takes
"""
if arguments is None:
arguments = ()
assert type(arguments) == type(())
assert accept_results is not None
self._f_assert_command_stack_unlocked()
assert self._entering_request_command == False
assert self._request_arguments is None
assert self._accept_request_results is None
self._entering_request_command = True
self._request_arguments = arguments
self._accept_request_results = accept_results
self._fyi_request_data_was_accessed = False
try:
self._enterRequestCommand(commandName)
if not self._fyi_request_data_was_accessed:
print "bug: request command forgot to call _args_and_callback_for_request_command:", commandName
finally:
self._entering_request_command = False
self._request_arguments = None
self._accept_request_results = None
self._fyi_request_data_was_accessed = False
return # from callRequestCommand
def _f_get_data_while_entering_request_command(self): #bruce 080801
if self._entering_request_command:
assert self._request_arguments is not None
assert self._accept_request_results is not None
res = ( self._request_arguments, self._accept_request_results )
self._fyi_request_data_was_accessed = True
else:
res = (None, None)
msg = "likely bug: entering a possible request command which was not called as such using callRequestCommand"
print_compact_stack( msg + ": ")
return res
# ==
# update methods [bruce 080812]
def _f_update_current_command(self): #bruce 080812
"""
[private; called from baseCommand.command_post_event_ui_updater]
Update the command stack, command state (for all active commands),
and current command UI.
"""
if self._f_command_stack_is_locked:
# This can happen, even after I fixed the lack of gl_update
# when ZoomToAreaMode exits (bug was unrelated to this method).
#
# When it happens, it's unsafe to do any updates
# (especially those which alter the command stack).
#
# REVIEW: do we also need something like the old
# "stop_sending_us_events" system (which temporarily
# set current command to nullmode),
# to protect from all kinds of events? [bruce 080829]
if _DEBUG_F_UPDATE_CURRENT_COMMAND:
print "_DEBUG_F_UPDATE_CURRENT_COMMAND: _f_update_current_command does nothing since command stack is locked (%s)" % \
self._f_command_stack_is_locked
return
else:
# this is very common
if _DEBUG_F_UPDATE_CURRENT_COMMAND:
print "_DEBUG_F_UPDATE_CURRENT_COMMAND: _f_update_current_command called, stack not locked"
self._f_assert_command_stack_unlocked()
# update the command stack itself, and any current command state
# which can affect that
already_called = []
good = False # might be reset below
while self.currentCommand not in already_called:
command = self.currentCommand
already_called.append( command)
command.command_update_state() # might alter command stack
if self.currentCommand is not command:
# command_update_state altered command stack
continue
else:
# command stack reached a fixed point without error
good = True
break
pass
if not good:
print "likely bug: command_update_state changed current command " \
"away from, then back to, %r" % self.currentCommand
# command stack should not be changed after this point
command = self.currentCommand
# update internal state of all active commands
command.command_update_internal_state()
assert command is self.currentCommand, \
"%r.command_update_internal_state() should not have changed " \
"current command (to %r)" % (command, self.currentCommand)
# maybe: warn if default command's command_update_internal_state
# was not called, by comparing a counter before/after
# update current command UI
command.command_update_UI()
assert command is self.currentCommand, \
"%r.command_update_UI() should not have changed " \
"current command (to %r)" % (command, self.currentCommand)
# make sure the correct Property Manager is shown.
# (ideally this would be done by an update method in an object
# whose job is to control the PM slot. TODO: refactor it that way.)
# Note: we can't assume anything has kept track of which PM is shown,
# until all code to show or hide/close it is revised. (That is,
# we have to assume some old code exists which shows, hides, or
# changes the PM without telling us about it.)
#
# So for now, we just check whether the PM in the UI is the one we want,
# and if not, fix that.
old_PM = self._KLUGE_current_PM()
desired_PM = self.currentCommand.propMgr
if desired_PM is not old_PM:
if old_PM:
try:
old_PM.close() # might not be needed, if desired_PM is not None ### REVIEW
except:
# might happen for same reason as an existing common exception related to this...
print "fyi: discarded exception in closing %r" % old_PM
pass
if desired_PM:
desired_PM.show()
pass
# let currentCommand update its flyout toolbar if command stack has
# changed since any command last did that using this code [bruce 080910]
flyout_update_indicators = ( self._flyout_command_change_counter, )
if self._previous_flyout_update_indicators != flyout_update_indicators:
self._previous_flyout_update_indicators = flyout_update_indicators
command.command_update_flyout()
assert command is self.currentCommand, \
"%r.command_update_flyout() should not have changed " \
"current command (to %r)" % (command, self.currentCommand)
pass
return # from _f_update_current_command
def _KLUGE_current_PM(self):
"""
private method, and a kluge;
see KLUGE_current_PropertyManager docstring for more info
"""
#bruce 070627; new option 080819
#bruce 080929 moved to this file and revised
pw = self.win.activePartWindow()
if not pw:
# I don't know if pw can be None
print "fyi: _KLUGE_current_PM sees pw of None" ###
return None
try:
return pw.KLUGE_current_PropertyManager()
except:
# I don't know if this can happen
msg = "ignoring exception in %r.KLUGE_current_PropertyManager()" % (pw,)
print_compact_traceback(msg + ": ")
return None
pass
# ==
# USE_COMMAND_STACK case [bruce 080814] ### TODO: review uses of _raw_currentCommand re this ###
# provide:
# - a private attr we store it on directly, and modify by direct assignment;
# (named the same as before, __raw_currentCommand)
# (might be None, briefly during init or while it's being modified)
# - get and set methods which implement _f_currentCommand, for internal & external (friend-only) use, get and set allowed
# - but _f_set_currentCommand can also be called directly
# - value can be None, otherwise might as well just use .currentCommand
# - if we ever wrap with proxies, this holds the not-wrapped version
# - for back-compat (for now), make _raw_currentCommand identical to _f_currentCommand,
# for get and set, many internal and one external use
# - currentCommand itself has only a get method, asserts it's not None and correct class
__raw_currentCommand = None
def _get_raw_currentCommand(self):
return self.__raw_currentCommand
def _set_raw_currentCommand(self, command):
assert command is None or isinstance(command, baseCommand)
self.__raw_currentCommand = command
self._command_stack_change_counter += 1
if command and command.command_affects_flyout():
self._flyout_command_change_counter += 1
return
_raw_currentCommand = property( _get_raw_currentCommand, _set_raw_currentCommand)
_f_currentCommand = _raw_currentCommand
_f_set_currentCommand = _set_raw_currentCommand
def _get_currentCommand(self):
assert self._raw_currentCommand is not None
return self._raw_currentCommand
def _set_currentCommand(self, command):
assert 0, "illegal to set %r.currentCommand directly" % self
currentCommand = property( _get_currentCommand, _set_currentCommand)
def command_stack_change_indicator(self):
"""
Return the current value of a "change indicator"
for the command stack as a whole. Any change to the command stack
causes this to change, provided it's viewed during one of the
command_update* methods in the Command API (see baseCommand
for their default defs and docstrings).
@see: same-named method in class Assembly.
"""
return self._command_stack_change_counter
pass
# ==
# custom command methods [bruce 080209 moved these here from GLPane]
## TODO: review/rewrite for USE_COMMAND_STACK
def custom_modes_menuspec(self):
"""
Return a menu_spec list for entering the available custom modes.
"""
#bruce 080209 split this out of GLPane.debug_menu_items
#e should add special text to the item for current mode (if any)
# saying we'll reload it
modemenu = []
for commandName, modefile in self._custom_mode_names_files():
modemenu.append(( commandName,
lambda arg1 = None, arg2 = None,
commandName = commandName,
modefile = modefile :
self._enter_custom_mode(commandName, modefile)
# not sure how many args are passed
))
return modemenu
def _custom_mode_names_files(self):
#bruce 061207 & 070427 & 080306 revised this
res = []
try:
# special case for cad/src/exprs/testmode.py (or .pyc)
from utilities.constants import CAD_SRC_PATH
## CAD_SRC_PATH = os.path.dirname(__file__)
for filename in ('testmode.py', 'testmode.pyc'):
testmodefile = os.path.join( CAD_SRC_PATH, "exprs", filename)
if os.path.isfile(testmodefile):
# note: this fails inside site-packages.zip (in Mac release);
# a workaround is below
res.append(( 'testmode', testmodefile ))
break
if not res and CAD_SRC_PATH.endswith('site-packages.zip'):
res.append(( 'testmode', testmodefile ))
# special case for Mac release (untested in built release?
# not sure) (do other platforms need this?)
assert res
except:
if debug_flags.atom_debug:
print "fyi: error adding testmode.py from cad/src/exprs " \
"to custom modes menu (ignored)"
pass
try:
import platform_dependent.gpl_only as gpl_only
except ImportError:
pass
else:
modes_dir = os.path.join( self.win.tmpFilePath, "Modes")
if os.path.isdir( modes_dir):
for file in os.listdir( modes_dir):
if file.endswith('.py') and '-' not in file:
commandName, ext = os.path.splitext(file)
modefile = os.path.join( modes_dir, file)
res.append(( commandName, modefile ))
pass
res.sort()
return res
def _enter_custom_mode( self, commandName, modefile): #bruce 050515
fn = modefile
if not os.path.exists(fn) and commandName != 'testmode':
msg = "should never happen: file does not exist: [%s]" % fn
env.history.message( msg)
return
if commandName == 'testmode':
#bruce 070429 explicit import probably needed for sake of py2app
# (so an explicit --include is not needed for it)
# (but this is apparently still failing to let the testmode
# item work in a built release -- I don't know why ###FIX)
print "_enter_custom_mode specialcase for testmode"
#e remove this print, when it works in a built release
import exprs.testmode as testmode
## reload(testmode) # This reload is part of what prevented
# this case from working in A9 [bruce 070611]
from exprs.testmode import testmode as _modeclass
print "_enter_custom_mode specialcase -- import succeeded"
else:
dir, file = os.path.split(fn)
base, ext = os.path.splitext(file)
## commandName = base
###e need better way to import from this specific file!
# (Like using an appropriate function in the import-related
# Python library module.)
# This kluge is not protected against weird chars in base.
oldpath = list(sys.path)
if dir not in sys.path:
sys.path.append(dir)
# Note: this doesn't guarantee we load file from that dir --
# if it's present in another one on path (e.g. cad/src),
# we'll load it from there instead. That's basically a bug,
# but prepending dir onto path would risk much worse bugs
# if dir masked any standard modules which got loaded now.
import platform_dependent.gpl_only as gpl_only
# make sure exec is ok in this version
# (caller should have done this already)
_module = _modeclass = None
# fool pylint into realizing this is not undefined 2 lines below
exec("import %s as _module" % (base,))
reload(_module)
exec("from %s import %s as _modeclass" % (base,base))
sys.path = oldpath
modeobj = _modeclass(self)
# this should put it into self._commandTable under the name
# defined in the mode module
# note: this self is probably supposed to be the command sequencer
self._commandTable[commandName] = modeobj
# also put it in under this name, if different
### [will this cause bugs?]
self.userEnterCommand(commandName, always_update = True)
return
pass # end of class CommandSequencer
# end
| NanoCAD-master | cad/src/commandSequencer/CommandSequencer.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
command_levels.py - utilities for interpreting and using command_level values,
including the rules for how commands can nest on the command stack
@author: Bruce
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
# fixed_parent command levels:
from utilities.constants import CL_DEFAULT_MODE
from utilities.constants import CL_ENVIRONMENT_PROVIDING
from utilities.constants import CL_MISC_TOPLEVEL # like subcommand of default mode, I think ###
from utilities.constants import CL_SUBCOMMAND
# nestable (or partly nestable) command levels:
from utilities.constants import CL_EDIT_GENERIC
from utilities.constants import CL_EXTERNAL_ACTION
from utilities.constants import CL_GLOBAL_PROPERTIES
from utilities.constants import CL_VIEW_CHANGE
from utilities.constants import CL_REQUEST
# level constants not allowed for actual commands:
from utilities.constants import CL_ABSTRACT # for abstract command classes
# (warning if instantiated directly)
from utilities.constants import CL_UNUSED # for command classes thought to be presently unused
# (warning if instantiated directly, or (if practical) if a subclass is
# instantiated)
from utilities.constants import DEFAULT_COMMAND
# ==
# set up rules for fixed-parent command levels
_USE_COMMAND_PARENT = '_USE_COMMAND_PARENT' # marks a fixed-parent command
_ALLOWED_PARENT_LEVELS = {
CL_DEFAULT_MODE: (), # no parent is acceptable!
CL_ENVIRONMENT_PROVIDING: _USE_COMMAND_PARENT,
# this means only the specified command_parent is acceptable, no other!
# (or the default command, if none is specified.)
# So it needs special case code, since it's not just
# a level like the others.
CL_MISC_TOPLEVEL: (CL_DEFAULT_MODE,),
CL_SUBCOMMAND: _USE_COMMAND_PARENT,
} # note: this dict is modified below
# add rules for nestable levels
_apl = _ALLOWED_PARENT_LEVELS # make following mods more readable
_apl[ CL_EDIT_GENERIC ] = \
(CL_ENVIRONMENT_PROVIDING, CL_DEFAULT_MODE) # "partly nestable"
_apl[ CL_EXTERNAL_ACTION ] = \
(CL_EDIT_GENERIC, CL_SUBCOMMAND, CL_MISC_TOPLEVEL,
CL_ENVIRONMENT_PROVIDING, CL_DEFAULT_MODE) # "fully nestable"
_apl[ CL_GLOBAL_PROPERTIES ] = \
(CL_EXTERNAL_ACTION,) + _apl[ CL_EXTERNAL_ACTION ]
_apl[ CL_VIEW_CHANGE ] = \
(CL_GLOBAL_PROPERTIES,) + _apl[ CL_GLOBAL_PROPERTIES ]
# request command rule is added last, since it refers to all keys added so far:
_apl[ CL_REQUEST ] = tuple( [CL_REQUEST] + _apl.keys() ) # not sorted, should be ok
# public constants constructed from the above private ones
LEGAL_COMMAND_LEVELS = _ALLOWED_PARENT_LEVELS.keys()
FIXED_PARENT_LEVELS = [level
for level in LEGAL_COMMAND_LEVELS
if _apl[level] == _USE_COMMAND_PARENT]
_IGNORE_FLYOUT_LEVELS = (
CL_VIEW_CHANGE,
CL_REQUEST,
CL_ABSTRACT,
CL_UNUSED,
)
AFFECTS_FLYOUT_LEVELS = filter( lambda level: level not in _IGNORE_FLYOUT_LEVELS,
LEGAL_COMMAND_LEVELS )
def allowed_parent( want, parent ): #bruce 080815
"""
Assume that the user wants to enter command class (or instance) <want>,
and current command class (or instance) is <parent>,
and that the caller already knows we're not *already* in the desired
command.
(Note that this means that if we immediately entered <want>,
its parent command would be <parent>, whether or not that's
acceptable.)
@return: whether <parent> is a suitable parent
or grandparent (etc) command for <want>.
@rtype: boolean
If we return True, it means the caller shouldn't exit
any commands, though it may need to enter some before
entering <want>.
If we return False, it means the caller does need to exit <parent>,
then call us again to decide what to do.
"""
# future: will we need any other retvals besides yes and no?
# maybe, more info about what to do to get to <want>?
# make sure the info we will use is present:
want.command_level
want.command_parent
parent.command_level
parent.command_parent
parent.commandName
# if want.command_level is illegal, the following will fail (KeyError)
# (we should check this earlier, in the "command description"
# (i.e. FeatureDescriptor) #todo)
# (we might revise the caller to pass the FeatureDescriptor here,
# in place of what's now used for want and parent, namely,
# actual command instances)
allowed_parent_levels = _ALLOWED_PARENT_LEVELS[ want.command_level ]
if allowed_parent_levels == _USE_COMMAND_PARENT:
# want is a fixed-parent command
# just check whether parent is the desired parent, or is a parent of that ...
### really part of a higher alg in caller? and/or a new command class method?
allowed_parent_names = [ want.command_parent or DEFAULT_COMMAND ]
allowed_parent_names += [ DEFAULT_COMMAND ] # don't bother to remove duplicates
# WARNING: THIS ASSUMES AT MOST ONE LEVEL OF REQUIRED PARENTS
res = parent.commandName in allowed_parent_names
else:
# <want> is nestable
# (or a fixed parent command that doesn't care about
# its command_parent field? I don't think that's possible.)
# (Note: this scheme would not be sufficient for a command which is
# "nestable under any subcommand of a given environment-providing command,
# but not under other kinds of subcommands".)
res = parent.command_level in allowed_parent_levels
return res
# end
| NanoCAD-master | cad/src/commandSequencer/command_levels.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
TreeModel_api.py - API class for a TreeModel needed by ModelTreeGui
@author: Will, Bruce
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
from modelTree.Api import Api
from operations.ops_select import topmost_selected_nodes
class TreeModel_api(Api):
"""
API (and some base class implementations) for a TreeModel object,
suitable to be displayed and edited by a ModelTreeGui as its treemodel
@warning: perhaps not all API methods are documented here.
"""
#bruce 081216 split this out of ModelTree_api, which has since been removed,
# and then moved it into its own file
def get_topnodes(self):
"""
Return a list of the top-level nodes, typically assy.tree and assy.shelf for an assembly.
"""
raise Exception("overload me")
def get_nodes_to_highlight(self): #bruce 080507
"""
Return a dictionary of nodes which should be drawn as highlighted right now.
(The keys are those nodes, and the values are arbitrary.)
"""
return {}
def get_current_part_topnode(self): #bruce 070509 added this to API ##e rename?
"""
Return a node guaranteed to contain all selected nodes, and be fast.
"""
raise Exception("overload me")
def make_cmenuspec_for_set(self, nodeset, nodeset_whole, optflag):
"""
Return a Menu_spec list (of a format suitable for makemenu_helper)
for a context menu suitable for nodeset, a list of 0 or more selected nodes
(which includes only the topmost selected nodes, i.e. it includes no
children of selected nodes even if they are selected).
<optflag> can be 'Option' or None, in case menus want to include
additional items when it's 'Option'.
Subclasses should override this to provide an actual menu spec.
The subclass implementation can directly examine the selection status of nodes
below those in nodeset, if desired, and can assume every node in nodeset is picked,
and every node not in it or under something in it is not picked
(or at least, will be unpicked when the operation occurs,
which happens for picked nodes inside unpicked leaf-like Groups
such as DnaStrand).
[all subclasses should override this]
"""
raise Exception("overload me")
def recurseOnNodes(self,
func,
topnode = None,
fake_nodes_to_mark_groups = False,
visible_only = False ):
"""
Call func on every node on or under topnode,
or if topnode is None, on every node in or under
all nodes in self.get_topnodes();
but only descend into openable nodes
(further limited to open nodes, if visible_only is true).
@param fake_nodes_to_mark_groups: bracket sequences of calls
of func on child node lists with calls of func(0) and func(1)
@type fake_nodes_to_mark_groups: boolean
@param visible_only: only descend into open nodes
@type visible_only: boolean
@return: None
@note: a node is open if node.open is true.
@note: a node is openable if node.openable() is true.
@see: node.MT_kids() for node's list of child nodes
(defined and meaningful whenever it's openable)
@see: topmost_selected_nodes
"""
# note: used only in itself and in ModelTreeGui.mt_update
#bruce 070509 new features:
# - fake_nodes_to_mark_groups [not used as of 080306],
# - visible_only [always true as of 080306] [can be False as of 081217]
# review, low priority: would this be more useful as a generator?
if topnode is None:
for topnode in self.get_topnodes():
self.recurseOnNodes(func, topnode,
fake_nodes_to_mark_groups = fake_nodes_to_mark_groups,
visible_only = visible_only)
continue
else:
func(topnode)
if visible_only and not topnode.open:
children = ()
elif not topnode.openable():
children = ()
else:
children = topnode.MT_kids()
#bruce 080306 use MT_kids, not .members, to fix some bugs
# note: we're required to not care what MT_kids returns
# unless topnode.openable() is true, but as of 081217
# we can use it regardless of node.open.
if children:
if fake_nodes_to_mark_groups:
func(0)
for child in children:
self.recurseOnNodes(func, child,
fake_nodes_to_mark_groups = fake_nodes_to_mark_groups,
visible_only = visible_only)
continue
if fake_nodes_to_mark_groups:
func(1)
pass
return
def topmost_selected_nodes(self, topnode = None, whole_nodes_only = False):
"""
@return: list of all selected nodes which are not inside selected Groups
@param topnode: if provided, limit return value to nodes on or under it
@type topnode: a Node or None
@param whole_nodes_only: if True (NOT the default), don't descend inside
non-openable groups (which means, picked nodes
inside unpicked non-openable Groups, aka "partly
picked whole nodes", will not be included in our
return value)
@type whole_nodes_only: boolean
@see: deselect_partly_picked_whole_nodes
@see: recurseOnNodes
"""
#bruce 081218 revising this, adding options, re bug 2948
# REVIEW: should this be defined in the implem class instead?
# (either way, it needs to be in the API)
# TODO: factor out common code with recurseOnNodes, using a generator?
if topnode is None:
topnode = self.get_current_part_topnode()
if not whole_nodes_only:
# old version, still used for many operations;
# REVIEW: might need better integration with new version
# (this one uses .members rather than MT_kids)
res = topmost_selected_nodes( [topnode] ) # defined in ops_select
else:
res = []
def func(node):
if node.picked:
res.append(node)
elif node.openable():
children = node.MT_kids() # even if not open
for child in children:
func(child)
return
func(topnode)
return res
def deselect_partly_picked_whole_nodes(self): #bruce 081218
"""
Deselect the topmost selected nodes which are not "whole nodes"
(i.e. which are inside non-openable nodes).
"""
keep_selected = self.topmost_selected_nodes( whole_nodes_only = True)
all_selected = self.topmost_selected_nodes()
deselect_these = dict([(n,n) for n in all_selected]) # modified below
for node in keep_selected:
del deselect_these[node]
for node in deselect_these:
node.unpick()
return
# note: the first implem caused visual glitches due to
# intermediate updates in both MT and GLPane:
## self.unpick_all()
## for node in keep_selected:
## node.pick()
def unpick_all(self): #bruce 081218 moved this here from ModelTreeGUI
for node in self.topmost_selected_nodes( whole_nodes_only = False):
node.unpick()
return
pass # end of class TreeModel_api
# end
| NanoCAD-master | cad/src/modelTree/TreeModel_api.py |
NanoCAD-master | cad/src/modelTree/__init__.py |
|
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
TreeModel.py - tree of nodes and rules for its appearance and behavior,
for use in NE1 model tree
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
History:
For earlier history, see ModelTree.py.
Bruce 081216 is doing some cleanup and refactoring, including splitting
ModelTree and TreeModel into separate objects with separate classes and
_api classes, and splitting some code into separate files.
TODO:
As of 081218 (just after fixing bug 2948),
there are unexplained bugs in gl_update after MT selection click
(it happens, but the changed selection status is not redrawn;
might be a bug in other code) and non-undoability of MT selection
click (could it be lack of calls to change the selection counter in assy?)
"""
import foundation.env as env
from foundation.Group import Group
from foundation.wiki_help import wiki_help_menuspec_for_object
from model.chunk import Chunk
from model.jigs import Jig
from model.jigs_planes import RectGadget
from modelTree.TreeModel_api import TreeModel_api
from modelTree.mt_statistics import all_attrs_act_as_counters
from modelTree.mt_statistics import mt_accumulate_stats
from operations.ops_select import selection_from_part
from platform_dependent.PlatformDependent import fix_plurals
from utilities import debug_flags
from utilities.GlobalPreferences import pref_show_highlighting_in_MT
from utilities.Log import orangemsg
from utilities.constants import gensym
from utilities.constants import noop
from utilities.debug import print_compact_traceback
from widgets.widget_helpers import RGBf_to_QColor
# ===
class TreeModel(TreeModel_api):
"""
"""
#bruce 081216 split ModelTree and TreeModel into separate objects
def __init__(self, modeltree, win):
self._modeltree = modeltree # only needed for .mt_update and .modelTreeGui
self.win = win # used often
self.assy = self.win.assy # review: might not be needed, since set in get_topnodes
return
def mt_update(self):
return self._modeltree.mt_update()
# == callbacks from self._modeltree.modelTreeGui to help it update the display
def get_topnodes(self):
self.assy = self.win.assy #k need to save it like this?
self.assy.tree.name = self.assy.name
#k is this still desirable, now that we have PartGroup
# so it's no longer needed for safety?
self.assy.kluge_patch_toplevel_groups( assert_this_was_not_needed = True)
# fixes Group subclasses of assy.shelf and assy.tree
self.tree_node, self.shelf_node = self.assy.tree, self.assy.shelf
topnodes = [self.assy.tree, self.assy.shelf]
return topnodes
def get_nodes_to_highlight(self): #bruce 080507
"""
Return a dictionary of nodes which should be drawn as highlighted right now.
(The keys are those nodes, and the values are arbitrary.)
"""
if not pref_show_highlighting_in_MT():
return {}
glpane = self.win.glpane
nodes_containing_selobj = glpane.get_nodes_containing_selobj()
# note: can contain duplicate nodes
topnodes = self.get_topnodes()
# these happen to be the nodes we consider to be
# too high in the tree to show highlighted
# (at least when the highlighting comes from
# them containing glpane.selobj -- for mouseover
# of these nodes in MT iself, we'd still show them
# as highlighted, once that's implemented)
res = {}
for node in nodes_containing_selobj:
if not node in topnodes:
res[node] = True
return res
def get_current_part_topnode(self): #bruce 070509 added this to the API
return self.win.assy.part.topnode
# ===
# methods related to context menu -- menu maker, and handlers for each op
def make_cmenuspec_for_set(self, nodeset, nodeset_whole, optflag):
"""
#doc... see superclass docstring, and the term "menu_spec"
"""
# Note: we use nodeset_whole (a subset of nodeset, or equal to it)
# for operations which might be unsafe on partly-selected "whole nodes"
# (i.e. unopenable nodes such as DnaStrand).
# (Doing this on the Group operation is part of fixing bug 2948.)
# These menu commands need corresponding changes in their cm methods,
# namely, calling deselect_partly_picked_whole_nodes at the start.
# All cm_duplicate methods (on individual nodes) also may need to do
# this if they care about the selection.
# [bruce 081218]
#e some advice [bruce]: put "display changes" (eg Hide) before "structural changes" (such as Group/Ungroup)...
#e a context-menu command "duplicate" which produces
##a copy of them, with related names and a "sibling" position.
##Whereas the menu command called "copy" produces a copy of the selected
##things in the system-wide "clipboard" shared by all apps.)
# I think we might as well remake this every time, for most kinds of menus,
# so it's easy for it to depend on current state.
# I really doubt this will be too slow. [bruce 050113]
if not nodeset:
#e later we'll add useful menu commands for no nodes,
# i.e. for a "context menu of the background".
# In fact, we'll probably remove this special case
# and instead let each menu command decide whether it applies
# in this case.
res = [('Model Tree (nothing selected)',noop,'disabled')]
#bruce 050505 adding some commands here (cm_delete_clipboard is a just-reported NFR from Mark)
res.append(( 'Create new empty clipboard item', self.cm_new_clipboard_item ))
lenshelf = len(self.assy.shelf.MT_kids()) #bruce 081217 use MT_kids
if lenshelf:
if lenshelf > 2:
text = 'Delete all %d clipboard items' % lenshelf
else:
text = 'Delete all clipboard items'
res.append(( text, self.cm_delete_clipboard ))
return res
res = []
if len(nodeset_whole) < len(nodeset):
# alert user to presence of partly-selected items [bruce 081218]
# (which are not marked as selected on nodes seeable in MT)
# (review: should we mark them in some other way?)
#
# (note about older text,
# "deselect %d partly-selected item(s)":
# the count is wrong if one partly-selected leaflike group
# contains more than one selected node, and nothing explains
# the situation well to the user)
#
# (about this text: it might be ambiguous whether they're too deep
# because of groups being closed, or being leaflike; mitigated
# by saying "shown" rather than "visible")
text = "Deselect %d node(s) too deep to be shown" % \
(len(nodeset) - len(nodeset_whole))
text = fix_plurals(text)
res.append(( text, self.cm_deselect_partly_selected_items ))
res.append(None)
pass
# old comment, not recently reviewed/updated as of 081217:
# first put in a Hide item, checked or unchecked. But what if the hidden-state is mixed?
# then there is a need for two menu commands! Or, use the command twice, fully hide then fully unhide -- not so good.
# Hmm... let's put in Hide (with checkmark meaning "all hidden"), then iff that's not enough, Unhide.
# So how do we know if a node is hidden -- this is only defined for leaf nodes now!
# I guess we figure it out... I guess we might as well classify nodeset and its kids.
# [update, bruce 080108/080306: does "and its kids" refer to members, or MT_kids?
# It might be some of each -- we would want to include members present but not shown
# in the MT (like the members of DnaGroup or DnaStrand), which are in members but not in
# MT_kids, but we might also want to cover "shared members", like DnaStrandChunks,
# which *might* be included in both strands and segments for this purpose (in the future;
# shared members are NIM now).]
allstats = all_attrs_act_as_counters()
for node in nodeset:
node_stats = all_attrs_act_as_counters()
node.apply2all( lambda node1: mt_accumulate_stats( node1, node_stats) )
allstats += node_stats # totals to allstats
# Hide command (and sometimes Unhide)
# now can we figure out how much is/could be hidden, etc
#e (later, modularize this, make assertfails only affect certain menu commands, etc)
nleafs = allstats.n - allstats.ngroups
assert nleafs >= 0
nhidden = allstats.nhidden
nunhidden = nleafs - nhidden # since only leafs can be hidden
assert nunhidden >= 0
# We'll always define a Hide item. Checked means all is hidden (and the command will be unhide);
# unchecked means not all is hidden (and the command will be hide).
# First handle degenerate case where there are no leafs selected.
if nleafs == 0:
res.append(( 'Hide', noop, 'disabled')) # nothing that can be hidden
elif nunhidden == 0:
# all is hidden -- show that, and offer to unhide it all
## res.append(( 'Hidden', self.cm_unhide, 'checked'))
res.append(( 'Unhide', self.cm_unhide)) # will this be better?
##e do we want special cases saying "Unhide All", here and below,
# when all hidden items would be unhidden, or vice versa?
# (on PartGroup, or in other cases, so detect by comparing counts for sel and tree_node.)
elif nhidden > 0:
# some is not hidden, some is hidden -- make this clear & offer both extremes
## res.append(( 'Hide (' + fix_plurals('%d item(s)' % nunhidden) + ')', self.cm_hide )) #e fix_plurals bug, worked around
res.append(( fix_plurals('Unhide %d item(s)' % nhidden), self.cm_unhide ))
res.append(( fix_plurals('Hide %d item(s)' % nunhidden), self.cm_hide ))
else:
# all is unhidden -- just offer to hide it
res.append(( 'Hide', self.cm_hide ))
try:
njigs = allstats.njigs
if njigs == 1 and allstats.n == 1:
# exactly one jig selected. Show its disabled state, with option to change this if permitted.
# warning: depends on details of Jig.is_disabled() implem. Ideally we should ask Jig to contribute
# this part of the menu-spec itself #e. [bruce 050421]
jig = nodeset[0]
if not isinstance(jig, RectGadget): # remove this menu item for RectGadget [Huaicai 10/11/05]
disabled_must = jig.disabled_by_atoms() # (by its atoms being in the wrong part)
disabled_choice = jig.disabled_by_user_choice
disabled_menu_item = disabled_must # menu item is disabled iff jig disabled state can't be changed, ie is "stuck on"
checked = disabled_must or disabled_choice # menu item is checked if it's disabled for whatever reason (also affects text)
if checked:
command = self.cm_enable
if disabled_must:
text = "Disabled (atoms in other Part)"
else:
text = "Disabled"
else:
command = self.cm_disable
text = "Disable"
res.append(( text, command, checked and 'checked' or None, disabled_menu_item and 'disabled' or None ))
except:
print "bug in MT njigs == 1, ignored"
## raise # just during devel
pass
if nodeset_whole:
res.append(None) # separator
# (from here on, only add these at start of optional items
# or sets of items)
# Group command -- only offered for 2 or more subtrees of any Part,
# or for exactly one clipboard item topnode itself if it's not already a Group.
# [rules loosened by bruce 050419-050421]
if optflag or len(nodeset_whole) >= 2:
# note that these nodes are always in the same Part and can't include its topnode
ok = True
else:
# exactly one node - ok iff it's a clipboard item and not a group
node = nodeset_whole[0]
ok = (node.dad is self.shelf_node and not node.is_group())
if not ok:
res.append(( 'Group', noop, 'disabled' ))
else:
res.append(( 'Group', self.cm_group ))
# Ungroup command -- only when exactly one picked Group is what we have, of a suitable kind.
# (As for Group, later this can become more general, tho in this case it might be general
# enough already -- it's more "self-contained" than the Group command can be.)
offered_ungroup = False # modified below; used by other menu items farther below
if len(nodeset_whole) == 1 and nodeset_whole[0].permits_ungrouping():
# (this implies it's a group, or enough like one)
node = nodeset_whole[0]
if not node.members: #bruce 080207
#REVIEW: use MT_kids? [same issue in many places in this file, as of 080306]
#reply, bruce 081217: not yet; really we need a new Node or Group API method
# "offer to remove as empty Group"; meanwhile, be conservative by using .members
text = "Remove empty Group"
elif node.dad == self.shelf_node and len(node.members) > 1:
# todo: "Ungroup into %d separate clipboard item(s)"
text = "Ungroup into separate clipboard items" #bruce 050419 new feature (distinct text in this case)
else:
# todo: "Ungroup %d item(s)"
text = "Ungroup"
res.append(( text, self.cm_ungroup ))
offered_ungroup = True
else:
# review: is this clear enough for nodes that are internally Groups
# but for which permits_ungrouping is false, or would some other
# text be better, or would leaving this item out be better?
# An old suggestion of "Ungroup (unsupported)" seems bad now,
# since it might sound like "a desired feature that's nim".
# [bruce 081212 comment]
res.append(( "Ungroup", noop, 'disabled' ))
# Remove all %d empty Groups (which permit ungrouping) [bruce 080207]
count_holder = [0]
def func(group, count_holder = count_holder):
if not group.members and group.permits_ungrouping():
count_holder[0] += 1 # UnboundLocalError when this was count += 1
for node in nodeset_whole:
node.apply_to_groups(func) # note: this descends into groups that don't permit ungrouping, e.g. DnaStrand
count = count_holder[0]
if count == 1 and len(nodeset_whole) == 1 and not nodeset_whole[0].members:
# this is about the single top selected node,
# so it's redundant with the Ungroup command above
# (and if that was not offered, this should not be either)
pass
elif count:
res.append(( 'Remove all %d empty Groups' % count, self.cm_remove_empty_groups ))
# lack of fix_plurals seems best here; review when seen
else:
pass
pass
# Edit Properties command -- only provide this when there's exactly one thing to apply it to,
# and it says it can handle it.
###e Command name should depend on what the thing is, e.g. "Part Properties", "Chunk Properties".
# Need to add methods to return that "user-visible class name".
res.append(None) # separator
if debug_flags.atom_debug:
if len(nodeset) == 1:
res.append(( "debug._node =", self.cm_set_node ))
else:
res.append(( "debug._nodeset =", self.cm_set_node ))
if len(nodeset) == 1 and nodeset[0].editProperties_enabled():
res.append(( 'Edit Properties...', self.cm_properties ))
else:
res.append(( 'Edit Properties...', noop, 'disabled' )) # nim for multiple items
#ninad 070320 - context menu option to edit color of multiple chunks
if allstats.nchunks:
res.append(("Edit Chunk Color...", self.cmEditChunkColor))
if allstats.canShowOverlayText:
res.append(("Show Overlay Text", self.cmShowOverlayText))
if allstats.canHideOverlayText:
res.append(("Hide Overlay Text", self.cmHideOverlayText))
#bruce 070531 - rename node -- temporary workaround for inability to do this in MT, or, maybe we'll like it to stay
if len(nodeset) == 1:
node = nodeset[0]
if node.rename_enabled():
res.append(("Rename node...", self.cmRenameNode)) ##k should it be called node or item in this menu text?
# subsection of menu (not a submenu unless they specify one)
# for node-class-specific menu items, when exactly one node
# (old way, based on methodnames that start with __CM;
# and new better way, using Node method ModelTree_context_menu_section)
if len(nodeset) == 1:
node = nodeset[0]
submenu = []
attrs = filter( lambda attr: "__CM_" in attr, dir( node.__class__ )) #e should do in order of superclasses
attrs.sort() # ok if empty list
#bruce 050708 -- provide a way for these custom menu items to specify a list of menu_spec options (e.g. 'disabled') --
# they should define a method with the same name + "__options" and have it return a list of options, e.g. ['disabled'],
# or [] if it doesn't want to provide any options. It will be called again every time the context menu is shown.
# If it wants to remove the menu item entirely, it can return the special value (not a list) 'remove'.
opts = {}
for attr in attrs: # pass 1 - record menu options for certain commands
if attr.endswith("__options"):
boundmethod = getattr( node, attr)
try:
lis = boundmethod()
assert type(lis) == type([]) or lis == 'remove'
opts[attr] = lis # for use in pass 2
except:
print_compact_traceback("exception ignored in %r.%s(): " % (node, attr))
pass
for attr in attrs: # pass 2
if attr.endswith("__options"):
continue
classname, menutext = attr.split("__CM_",1)
boundmethod = getattr( node, attr)
if callable(boundmethod):
lis = opts.get(attr + "__options") or []
if lis != 'remove':
mitem = tuple([menutext.replace('_',' '), boundmethod] + lis)
submenu.append(mitem)
elif boundmethod is None:
# kluge: None means remove any existing menu items (before the submenu) with this menutext!
res = filter( lambda text_cmd: text_cmd and text_cmd[0] != menutext, res ) # text_cmd might be None
while res and res[0] == None:
res = res[1:]
#e should also remove adjacent Nones inside res
else:
assert 0, "not a callable or None: %r" % boundmethod
if submenu:
## res.append(( 'other', submenu )) #e improve submenu name, ordering, location
res.extend(submenu) # changed append to extend -- Mark and Bruce at Retreat 050621
# new system, used in addition to __CM above (preferred in new code):
# [bruce 080225]
try:
submenu = node.ModelTree_context_menu_section()
assert submenu is not None # catch a likely possible error specifically
assert type(submenu) is type([]) # it should be a menu_spec list
except:
print_compact_traceback("exception ignored in %r.%s() " \
"or in checking its result: " % \
(node, 'ModelTree_context_menu_section'))
submenu = []
if submenu:
res.extend(submenu)
pass
if nodeset_whole:
# copy, cut, delete, maybe duplicate...
# bruce 050704 revisions:
# - these are probably ok for clipboard items; I'll enable them there and let them be tested there.
# - I'll remove Copy when the selection only contains jigs that won't copy themselves
# unless some of their atoms are copied (which for now is true of all jigs).
# More generally (in principle -- the implem is not general), Copy should be removed
# when the selection contains nothing which makes sense to copy on its own,
# only things which make sense to copy only in conjunction with other things.
# I think this is equivalent to whether all the selected things would fail to get copied,
# when the copy command was run.
# - I'll add Duplicate for single selected jigs which provide an appropriate method,
# and show it dimmed for those that don't.
res.append(None) # separator
# figure out whether Copy would actually copy anything.
part = nodeset_whole[0].part # the same for all nodes in nodeset_whole
sel = selection_from_part(part, use_selatoms = False) #k should this be the first code to use selection_from_MT() instead?
doit = False
for node in nodeset_whole:
if node.will_copy_if_selected(sel, False):
#wware 060329 added realCopy arg, False here (this is not a real copy, so do not issue a warning).
#bruce 060329 points out about realCopy being False vs True that at this point in the code we don't
# yet know whether the real copy will be made, and when we do, will_copy_if_selected
# might like to be re-called with True, but that's presently nim. ###@@@
#
# if this test is too slow, could inline it by knowing about Jigs here; but better to speed it up instead!
doit = True
break
if doit:
res.append(( 'Copy', self.cm_copy ))
# For single items, add a Duplicate command and enable it if they support the method. [bruce 050704 new feature]
# For now, hardly anything offers this command, so I'm changing the plan, and removing it (not disabling it)
# when not available. This should be reconsidered if more things offer it.
if len(nodeset_whole) == 1:
node = nodeset_whole[0]
try:
method = node.cm_duplicate
# Warning 1: different API than self.cm_xxx methods (arg differs)
# or __CM_ methods (disabled rather than missing, if not defined).
# Warning 2: if a class provides it, no way for a subclass to stop
# providing it. This aspect of the API is bad, should be revised.
# Warning 3: consider whether each implem of this needs to call
# self.deselect_partly_picked_whole_nodes().
assert callable(method)
except:
dupok = False
else:
dupok = True
if dupok:
res.append(( 'Duplicate', method ))
else:
pass ## res.append(( 'Duplicate', noop, 'disabled' ))
# Cut (unlike Copy), and Delete, should always be ok.
res.append(( 'Cut', self.cm_cut ))
res.append(( 'Delete', self.cm_delete ))
#ninad060816 added option to select all atoms of the selected chunks.
#I don't know how to handle a case when a whole group is selected.
#So putting a condition allstats.nchunks == allstats.n.
#Perhaps, I should unpick the groups while picking atoms?
if allstats.nchunks == allstats.n and allstats.nchunks :
res.append((fix_plurals("Select all atoms of %d chunk(s)" %
allstats.nchunks),
self.cmSelectAllAtomsInChunk))
# add basic info on what's selected at the end
# (later might turn into commands related to subclasses of nodes)
if allstats.nchunks + allstats.njigs:
# otherwise, nothing we can yet print stats on... (e.g. clipboard)
res.append(None) # separator
res.append(( "selection:", noop, 'disabled' ))
if allstats.nchunks:
res.append(( fix_plurals("%d chunk(s)" % allstats.nchunks), noop, 'disabled' ))
if allstats.njigs:
res.append(( fix_plurals("%d jig(s)" % allstats.njigs), noop, 'disabled' ))
if allstats.nhidden:
res.append(( "(%d of these are hidden)" % allstats.nhidden, noop, 'disabled' ))
if allstats.njigs == allstats.n and allstats.njigs:
# only jigs are selected -- offer to select their atoms [bruce 050504]
# (text searches for this code might like to find "Select this jig's" or "Select these jigs'")
want_select_item = True #bruce 051208
if allstats.njigs == 1:
jig = nodeset[0]
if isinstance(jig, RectGadget): # remove menu item for RectGadget [Huaicai 10/11/05]
## return res -- this 'return' was causing bug 1189 by skipping the rest of the menu, not just this item.
# Try to do something less drastic. [bruce 051208]
want_select_item = False
else:
natoms = len(nodeset[0].atoms)
myatoms = fix_plurals( "this jig's %d atom(s)" % natoms )
else:
myatoms = "these jigs' atoms"
if want_select_item:
res.append(('Select ' + myatoms, self.cm_select_jigs_atoms ))
## ##e following msg is not true, since nodeset doesn't include selection under selected groups!
## # need to replace it with a better breakdown of what's selected,
## # incl how much under selected groups is selected. Maybe we'll add a list of major types
## # of selected things, as submenus, lower down (with commands like "select only these", "deselect these").
##
## res.append(( fix_plurals("(%d selected item(s))" % len(nodeset)), noop, 'disabled' ))
# for single items that have a featurename, add wiki-help command [bruce 051201]
if len(nodeset) == 1:
node = nodeset[0]
ms = wiki_help_menuspec_for_object(node) # will be [] if this node should have no wiki help menu items
#review: will this func ever need to know which widget is asking?
if ms:
res.append(None) # separator
res.extend(ms)
return res # from make_cmenuspec_for_set
# Context menu handler functions [bruce 050112 renamed them; e.g. old name "hide" overrode a method of QWidget!]
#
# Note: these must do their own updates (win_update, gl_update, mt_update) as needed.
def cm_deselect_partly_selected_items(self): #bruce 081218
# todo: call statusbar_message in modeltreegui
self.deselect_partly_picked_whole_nodes()
self.win.win_update()
def cm_hide(self):
env.history.message("Hide: %d selected items or groups" % \
len(self.topmost_selected_nodes()))
#bruce 050517/081216 comment: doing self.assy.permit_pick_parts() here
# (by me, unknown when or why) caused bug 500; removing it seems ok.
self.assy.Hide() # includes win_update
def cm_unhide(self):
env.history.message("Unhide: %d selected items or groups" % \
len(self.topmost_selected_nodes()))
## self.assy.permit_pick_parts() #e should not be needed here [see same comment above]
self.assy.Unhide() # includes win_update
def cm_set_node(self): #bruce 050604, for debugging
import utilities.debug as debug
nodeset = self.topmost_selected_nodes()
if len(nodeset) == 1:
debug._node = nodeset[0]
print "set debug._node to", debug._node
else:
debug._nodeset = nodeset
print "set debug._nodeset to list of %d items" % len(debug._nodeset)
return
def cm_properties(self):
nodeset = self.topmost_selected_nodes()
if len(nodeset) != 1:
env.history.message("error: cm_properties called on no or multiple items")
# (internal error, not user error)
else:
node = nodeset[0]
#UM 20080730: if its a protein chunk, enter build protein mode
# (REVIEW: shouldn't this special case be done inside Chunk.edit instead? [bruce 090106 comment])
if hasattr(node, 'isProteinChunk') and node.isProteinChunk():
res = node.protein.edit(self.win)
else:
res = node.edit()
if res:
env.history.message(res) # added by bruce 050121 for error messages
else:
self.win.win_update()
return
def cm_group(self): # bruce 050126 adding comments and changing behavior; 050420 permitting exactly one subtree
"""
put the selected subtrees (one or more than one) into a new Group (and update)
"""
##e I wonder if option/alt/middleButton should be like a "force" or "power" flag
# for cmenus; in this case, it would let this work even for a single element,
# making a 1-item group. That idea can wait. [bruce 050126]
#bruce 050420 making this work inside clipboard items too
# TEST if assy.part updated in time ####@@@@ -- no, change to selgroup!
self.deselect_partly_picked_whole_nodes()
sg = self.assy.current_selgroup()
node = sg.hindmost() # smallest nodetree containing all picked nodes
if not node:
env.history.message("nothing selected to Group") # should never happen
return
if node.picked:
#bruce 050420: permit this case whenever possible (formation of 1-item group);
# cmenu constructor should disable or leave out the menu command when desired.
if node != sg:
assert node.dad # in fact, it'll be part of the same sg subtree (perhaps equal to sg)
node = node.dad
assert not node.picked
# fall through -- general case below can handle this.
else:
# the picked item is the topnode of a selection group.
# If it's the main part, we could make a new group inside it
# containing all its children (0 or more). This can't happen yet
# so I'll be lazy and save it for later.
assert node != self.assy.tree
# Otherwise it's a clipboard item. Let the Part take care of it
# since it needs to patch up its topnode, choose the right name,
# preserve its view attributes, etc.
assert node.part.topnode == node
newtop = node.part.create_new_toplevel_group()
env.history.message("made new group %s" % newtop.name) ###k see if this looks ok with autogenerated name
self.mt_update()
return
# (above 'if' might change node and then fall through to here)
# node is an unpicked Group inside (or equal to) sg;
# more than one of its children (or exactly one if we fell through from the node.picked case above)
# are either picked or contain something picked (but maybe none of them are directly picked).
# We'll make a new Group inside node, just before the first child containing
# anything picked, and move all picked subtrees into it (preserving their order;
# but losing their structure in terms of unpicked groups that contain some of them).
###e what do we do with the picked state of things we move? worry about the invariant! ####@@@@
# make a new Group (inside node, same assy)
###e future: require all assys the same, or, do this once per topnode or assy-node.
# for now: this will have bugs when done across topnodes!
# so the caller doesn't let that happen, for now. [050126]
new = Group(gensym("Group", node.assy), node.assy, node) # was self.assy
assert not new.picked
# put it where we want it -- before the first node member-tree with anything picked in it
for m in node.members:
if m.haspicked():
assert m != new
## node.delmember(new) #e (addsibling ought to do this for us...) [now it does]
m.addsibling(new, before = True)
break # (this always happens, since something was picked under node)
node.apply2picked(lambda(x): x.moveto(new))
# this will have skipped new before moving anything picked into it!
# even so, I'd feel better if it unpicked them before moving them...
# but I guess it doesn't. for now, just see if it works this way... seems to work.
# ... later [050316], it evidently does unpick them, or maybe delmember does.
msg = fix_plurals("grouped %d item(s) into " % len(new.members)) + "%s" % new.name
env.history.message( msg)
# now, should we pick the new group so that glpane picked state has not changed?
# or not, and then make sure to redraw as well? hmm...
# - possibility 1: try picking the group, then see if anyone complains.
# Caveat: future changes might cause glpane redraw to occur anyway, defeating the speed-purpose of this...
# and as a UI feature I'm not sure what's better.
# - possibility 2: don't pick it, do update glpane. This is consistent with Ungroup (for now)
# and most other commands, so I'll do it.
#
# BTW, the prior code didn't pick the group
# and orginally didn't unpick the members but now does, so it had a bug (failure to update
# glpane to show new picked state), whose bug number I forget, which this should fix.
# [bruce 050316]
## new.pick() # this will emit an undesirable history message... fix that?
self.win.glpane.gl_update() #k needed? (e.g. for selection change? not sure.)
self.mt_update()
return
def cm_ungroup(self):
self.deselect_partly_picked_whole_nodes()
nodeset = self.topmost_selected_nodes()
assert len(nodeset) == 1 # caller guarantees this
node = nodeset[0]
assert node.permits_ungrouping() # ditto
need_update_parts = []
pickme = None
if node.is_top_of_selection_group():
# this case is harder, since dissolving this node causes its members to become
# new selection groups. Whether there's one or more members, Part structure needs fixing;
# if more than one, interpart bonds need breaking (or in future might keep some subsets of
# members together; more likely we'd have a different command for that).
# simplest fix -- just make sure to update the part structure when you're done.
# [bruce 050316]
need_update_parts.append( node.assy)
#bruce 050419 comment: if exactly one child, might as well retain the same Part... does this matter?
# Want to retain its name (if group name was automade)? think about this a bit before doing it...
# maybe fixing bugs for >1 child case will also cover this case. ###e
#bruce 050420 addendum: I did some things in Part.__init__ which might handle all this well enough. We'll see. ###@@@ #k
#bruce 050528 addendum: it's not handled well enough, so try this: hmm, it's not enough! try adding pickme too... ###@@@
if len(node.members) == 1 and node.part.topnode is node:
node.part.topnode = pickme = node.members[0]
if node.is_top_of_selection_group() and len(node.members) > 1:
msg = "splitting %r into %d new clipboard items" % (node.name, len(node.members))
else:
msg = fix_plurals("ungrouping %d item(s) from " % len(node.members)) + "%s" % node.name
env.history.message( msg)
node.ungroup()
# this also unpicks the nodes... is that good? Not really, it'd be nice to see who they were,
# and to be consistent with Group command, and to avoid a glpane redraw.
# But it's some work to make it pick them now, so for now I'll leave it like that.
# BTW, if this group is a clipboard item and has >1 member, we couldn't pick all the members anyway!
#bruce 050528 addendum: we can do it in this case, temporarily, just to get selgroup changed:
if pickme is not None:
pickme.pick() # just to change selgroup (too lazy to look up the official way to only do that)
pickme.unpick() # then make it look the same as for all other "ungroup" ops
#e history.message?
for assy in need_update_parts:
assy.update_parts() # this should break new inter-part bonds
self.win.glpane.gl_update() #k needed? (e.g. for selection change? not sure. Needed if inter-part bonds break!)
self.mt_update()
return
def cm_remove_empty_groups(self): #bruce 080207
self.deselect_partly_picked_whole_nodes()
nodeset = self.topmost_selected_nodes()
empties = []
def func(group):
if not group.members and group.permits_ungrouping():
empties.append(group)
for node in nodeset:
node.apply_to_groups(func)
for group in empties:
group.kill()
msg = fix_plurals("removed %d empty Group(s)" % len(empties))
env.history.message( msg)
self.mt_update()
return
# copy and cut and delete are doable by tool buttons
# so they might as well be available from here as well;
# anyway I tried to fix or mitigate their bugs [bruce 050131]:
def cm_copy(self):
self.deselect_partly_picked_whole_nodes()
self.assy.copy_sel(use_selatoms = False) # does win_update
def cm_cut(self):
self.deselect_partly_picked_whole_nodes()
self.assy.cut_sel(use_selatoms = False) # does win_update
def cm_delete(self): # renamed from cm_kill which was renamed from kill
self.deselect_partly_picked_whole_nodes()
# note: after this point, this is now the same code as MWsemantics.killDo. [bruce 050131]
self.assy.delete_sel(use_selatoms = False) #bruce 050505 don't touch atoms, to fix bug (reported yesterday in checkin mail)
##bruce 050427 moved win_update into delete_sel as part of fixing bug 566
##self.win.win_update()
def cmSelectAllAtomsInChunk(self): #Ninad060816
"""
Selects all the atoms preseent in the selected chunk(s)
"""
nodeset = self.topmost_selected_nodes()
self.assy.part.permit_pick_atoms()
for m in nodeset:
for a in m.atoms.itervalues():
a.pick()
self.win.win_update()
def cmEditChunkColor(self): #Ninad 070321
"""
Edit the color of the selected chunks using the Model Tree context menu
"""
nodeset = self.topmost_selected_nodes()
chunkList = []
#Find the chunks in the selection and store them temporarily
for m in nodeset:
if isinstance(m, Chunk):
chunkList.append(m)
#Following selects the current color of the chunk
#in the QColor dialog. If multiple chunks are selected,
#it simply sets the selected color in the dialog as 'white'
if len(chunkList) == 1:
m = chunkList[0]
if m.color:
m_QColor = RGBf_to_QColor(m.color)
else:
m_QColor = None
self.win.dispObjectColor(initialColor = m_QColor)
else:
self.win.dispObjectColor()
def cmShowOverlayText(self):
"""
Context menu entry for chunks. Turns on the showOverlayText
flag in each chunk which has overlayText in some of its atoms.
"""
nodeset = self.topmost_selected_nodes()
for m in nodeset:
if isinstance(m, Chunk):
m.showOverlayText = True
def cmHideOverlayText(self):
"""
Context menu entry for chunks. Turns off the showOverlayText
flag in each chunk which has overlayText in some of its atoms.
"""
nodeset = self.topmost_selected_nodes()
for m in nodeset:
if isinstance(m, Chunk):
m.showOverlayText = False
def cmRenameNode(self): #bruce 070531
"""
Put up a dialog to let the user rename the selected node. (Only one node for now.)
"""
nodeset = self.topmost_selected_nodes()
assert len(nodeset) == 1 # caller guarantees this
node = nodeset[0]
self._modeltree.modelTreeGui.rename_node_using_dialog( node) # note: this checks node.rename_enabled() first
return
def cm_disable(self): #bruce 050421
nodeset = self.topmost_selected_nodes()
assert len(nodeset) == 1 # caller guarantees this
node = nodeset[0]
jig = node # caller guarantees this is a jig; if not, this silently has no effect
jig.set_disabled_by_user_choice( True) # use Node method as part of fixing bug 593 [bruce 050505]
self.win.win_update()
def cm_enable(self): #bruce 050421
nodeset = self.topmost_selected_nodes()
assert len(nodeset) == 1, "len nodeset should be 1, but nodeset is %r" % nodeset
node = nodeset[0]
jig = node
jig.set_disabled_by_user_choice( False)
self.win.win_update()
def cm_select_jigs_atoms(self): #bruce 050504
nodeset = self.topmost_selected_nodes()
otherpart = {} #bruce 050505 to fix bug 589
did_these = {}
nprior = len(self.assy.selatoms)
for jig in nodeset:
assert isinstance( jig, Jig) # caller guarantees they are all jigs
# If we didn't want to desel the jig, I'd have to say:
# note: this does not deselect the jig (good); and permit_pick_atoms would deselect it (bad);
# so to keep things straight (not sure this is actually needed except to avoid a debug message),
# just set SELWHAT_ATOMS here; this is legal because no chunks are selected. Actually, bugs might occur
# in which that's not true... I forget whether I fixed those recently or only analyzed them (due to delays
# in update event posting vs processing)... but even if they can occur, it's not high-priority to fix them,
# esp since selection rules might get revised soon.
## self.assy.set_selwhat(SELWHAT_ATOMS)
# but (I forgot when I wrote that) we *do* desel the jig,
# so instead I can just say:
self.assy.part.permit_pick_atoms() # changes selwhat and deselects all chunks, jigs, and groups
# [bruce 050519 8pm]
for atm in jig.atoms:
if atm.molecule.part == jig.part:
atm.pick()
did_these[atm.key] = atm
else:
otherpart[atm.key] = atm
## jig.unpick() # not done by picking atoms [no longer needed since done by permit_pick_atoms]
msg = fix_plurals("Selected %d atom(s)" % len(did_these)) # might be 0, that's ok
if nprior: #bruce 050519
#e msg should distinguish between atoms already selected and also selected again just now,
# vs already and not now; for now, instead, we just try to be ambiguous about that
msg += fix_plurals(" (%d atom(s) remain selected from before)" % nprior)
if otherpart:
msg += fix_plurals(" (skipped %d atom(s) which were not in this Part)" % len(otherpart))
msg = orangemsg(msg) # the whole thing, I guess
env.history.message(msg)
self.win.win_update()
# note: caller (which puts up context menu) does
# self.win.update_select_mode(); we depend on that. [### still true??]
return
def cm_new_clipboard_item(self): #bruce 050505
name = self.assy.name_autogrouped_nodes_for_clipboard( [] ) # will this end up being the part name too? not sure... ###k
self.assy.shelf.addchild( Group(name, self.assy, None) )
self.assy.update_parts()
self.mt_update()
def cm_delete_clipboard(self): #bruce 050505; docstring added 050602
"""
Delete all clipboard items
"""
###e get confirmation from user?
for node in self.assy.shelf.MT_kids()[:]: #bruce 081217 use MT_kids
node.kill() # will this be safe even if one of these is presently displayed? ###k
self.mt_update()
pass # end of class TreeModel
# end
| NanoCAD-master | cad/src/modelTree/TreeModel.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
Api.py - superclass for testing API compliance
Note: this is used in NE1 if certain private debug flags are set,
but has not been tested or maintained for a long time (as of 081216).
If it is ever verified to work and be useful, it can be moved into a
more general place.
@author: Will
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
# Yet another experiment with testing API compliance in Python
def _inheritance_chains(klas, endpoint):
if klas is endpoint:
return [ (endpoint,) ]
lst = [ ]
for base in klas.__bases__:
for seq in _inheritance_chains(base, endpoint):
lst.append((klas,) + seq)
return lst
# This little hack is a way to ensure that a class implementing an API does so completely. API
# compliance also requires that the caller not call any methods _not_ defined by the API, but
# that's a harder problem that we'll ignore for the moment.
class Api(object):
#bruce 081216 added superclass object, untested
def _verify_api_compliance(self):
from types import MethodType
myclass = self.__class__
mystuff = myclass.__dict__
ouch = False
for legacy in _inheritance_chains(myclass, Api):
assert len(legacy) >= 3
api = legacy[-2]
print api, api.__dict__
for method in api.__dict__:
if not method.startswith("__"):
assert type(getattr(api, method)) is MethodType
assert type(getattr(self, method)) is MethodType
this_method_ok = False
for ancestor in legacy[:-2]:
if method in ancestor.__dict__:
this_method_ok = True
if not this_method_ok:
print myclass, 'does not implement', method, 'from', api
ouch = True
if ouch:
raise Exception('Class does not comply with its API')
# end
| NanoCAD-master | cad/src/modelTree/Api.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
ModelTreeGUI_api.py - API class for ModelTreeGui
@author: Will, Bruce
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
from modelTree.Api import Api
# old comments by Will from his refactoring circa 2006:
# These base classes [various _api classes in this modelTree package]
# are JUST the API [external, and inter-object internal].
# Functionality is implemented by extending these base classes.
# Context menu events can rearrange the tree structure in various ways. Items in the model tree can be
# hidden or disabled or deleted. An item can be moved or copied from one place in the tree to
# another. These things are done by the customer, OUTSIDE the model tree, and then the customer
# gives the model tree a new structure. Aside from the context menus, the model tree does not make
# callbacks to the customer code.
# Customer code should depend ONLY on the API as presented, and treat it as a contract. Then any
# bugs are either API bugs and implementation bugs, and the implementation bugs become relatively
# isolated and easier to fix.
# http://en.wikipedia.org/wiki/Duck_typing describes how API compliance works in Python. In Java or
# C++, the only way to guarantee that class B complies with class A's API is for B to subclass A. In
# Python, there is no such compile-time check, Python just raises an exception if we try to use a
# method that isn't implemented.
# =============================
# Bruce's original intent was that this code should be useful for other trees besides the model tree.
# To do that, you should subclass ModelTreeGui below and redefine make_new_subtree_for_node() to refer to
# a new class that inherits _QtTreeItem. Perhaps the subclass of QItemDelegate could be a parameter of
# ModelTreeGui. [This comment is no longer correct now that _QtTreeItem's two roles, which never belonged
# together, are split into _our_QItemDelegate and (misnamed) _our_TreeItem. bruce 070525]
#
# How this was done previously was that the NE-1 model would define a method for creating the item for
# a Node.
#
# =============================
#
# How does renaming work in Qt 3?
#
# TreeWidget.slot_itemRenamed() is connected to Q3ListView.itemRenamed(). It accepts an item, a column
# number, and the new text. If everything is OK, it calls item.setText(col,newname). What I am not
# seeing is how the name gets from the Q3ListViewItem back to the Node. So renaming is a big mystery to
# me, and I'll ask Bruce about it later.
# ===
class ModelTreeGUI_api(Api):
"""
This should be a Qt4 widget that can be put into a layout.
"""
# note: this classname and modulename contains "GUI" not "Gui",
# like class ModelTreeGui someday ought to, but doesn't now.
# [bruce 081216]
def mt_update(self, nodetree = None): # in ModelTreeGUI_api
"""
External code (or event bindings in a subclass, if they don't do enough repainting themselves)
should call this when it might have changed any state that should
affect what's shown in the tree. (Specifically: the ordering or grouping of nodes,
or the icons or text they should display, or their open or selected state.) (BTW external
code probably has no business changing node.open since it is slated to become a tree-
widget-specific state in the near future.)
If these changes are known to be confined to a single node and its children,
that node can be passed as a second argument as a possible optimization
(though as of 050113 the current implem does not take advantage of this).
@warning: as of 080306 the implementations of this don't conform to the
argspec, since they don't even accept (let alone pay attention
to) the nodetree optional argument.
"""
raise Exception("overload me")
def repaint_some_nodes(self, nodes): #bruce 080507, for cross-highlighting
"""
For each node in nodes, repaint that node, if it was painted the last
time we repainted self as a whole. (Not an error if it wasn't.)
"""
raise Exception("overload me")
pass
# end
| NanoCAD-master | cad/src/modelTree/ModelTreeGUI_api.py |
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
Node_as_MT_DND_Target.py -- controller for a Node as a Model Tree DND target
@author: Bruce
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
History:
Bruce 071025 moved these methods from class Node
and class ClipboardShelfGroup (where I'd written them long ago)
into this new controller class, to remove an import from class Node
to ops_copy. I left behind only a new Node API method this needs
to call, drop_on_should_autogroup.
TODO:
- drop_under is not finished or called (for drop between nodes)
- this uses 3 different ways of asking whether something is a Group!
- there's a longstanding request to revise the position under a group
into which a node gets dropped (from new last child to new first child,
I think). It has a bug number. One motivation is that there is some
place it's not possible to drop a node unless this is revised,
described in the bug report.
"""
from foundation.Group import Group # for isinstance and for autogrouping; could remove by
# asking the assy (and/or the dropped on node) to do the grouping
from operations.ops_copy import copy_nodes_in_order
from operations.ops_copy import copied_nodes_for_DND
import foundation.env as env
from utilities.GlobalPreferences import pref_drop_onto_Group_puts_nodes_at_top
# ==
class MT_DND_Target_API(object):
# a stub; intent is to fill it in with default methods
# (which fail if implems are required)
# which specify the api used by our subclass below;
# this doesn't matter much until we get more than one subclass
# or the api gets more complicated.
pass
# ==
class Node_as_MT_DND_Target( MT_DND_Target_API):
"""
Control the use of a node as a Model Tree DND target.
Can be used as a flyweight class, since it contains no state.
"""
def __init__(self, node):
"""
@param node: one node (leaf or Group) currently displayed in the
model tree.
@type node: Node (can be Group or not).
"""
self.node = node
def drop_on_ok(self, drag_type, nodes): #bruce 080303 revised return value
"""
Say whether "drag and drop" should be allowed to drop the given set
of nodes onto self.node, when they are dragged in the given way
('move' or 'copy' -- nodes arg has the originals, not the copies),
and if not, why not.
(Typically, self.node (if it says ok by returning True from this method)
would insert the moved or copied nodes inside itself as new members,
or below itself as new siblings if it's a leaf node (until we support
dropping into gaps between nodes for that), if they were actually
dropped. For that see drop_on.)
@return: ( ok, whynot ), i.e. (False, whynot) or (True, arbitrary).
@rtype: 2-tuple of ( boolean, string), with string suitable for use
in a statusbar message.
[some subclasses should override this]
"""
# someday: return ( True, what ) where what describes what we would do,
# for use in statusbar message while user mouses over a drop point.
#
#bruce 050216 add exception for cycle-forming request ### needs testing
# (to fix bug 360 item 6 comment 9, which had been fixed in the old MT's
# DND code too)
if drag_type == 'move':
for node in nodes:
if (node is not self.node and node.is_ascendant(self.node)) or \
(node is self.node and node.MT_DND_can_drop_inside()):
print "fyi: refusing drag-move since it would form a cycle"
whynot = "would form a cycle"
return ( False, whynot )
return ( True, None)
# someday: probably change to False for leaf nodes, once we support
# dropping into gaps
def drop_on(self, drag_type, nodes): ###@@@ needs a big cleanup
# todo: also return description of what we did (for statusbar text)
# [bruce 080303 comment]
"""
After a "drag and drop" of type 'move' or 'copy' (according to
drag_type), perform the drop of the given list of nodes
onto self.node. The list always contains the original nodes --
for drag_type == 'copy', this method should make the copies itself.
Exactly how to do this depends on whether self.node is a leaf or group;
subclasses of Node can override this to change the UI behavior.
(As of 050307, only the Clipboard overrides this. Update 071025:
that's now done by an 'if' statement in the following method,
which calls self.node.drop_on_should_autogroup, which is what
the Clipboard overrides.)
@return: list of new nodes made by this operation, which is [] if it
didn't make any (making them is normal for copy, but can also
happen in some cases for move)
@rtype: list of nodes
"""
will_drop_inside = self.node.MT_DND_can_drop_inside()
# if true, nodes or their copies will become new children of self.node;
# if false, they will become new siblings. [revised, bruce 080317]
autogroup_at_top = will_drop_inside and \
self.node.drop_on_should_autogroup(drag_type, nodes)
drop_onto_Group_at_top = pref_drop_onto_Group_puts_nodes_at_top() #bruce 080414
if autogroup_at_top:
#bruce 050203/080303:
# nodes dropped onto the clipboard come from one
# "physical space" (Part) and ought to stay that way by default;
# user can drag them one-at-a-time if desired. (In theory this
# autogrouping need only be done for the subsets of them which
# are bonded; for now that's too hard -- maybe not for long,
# similar to bug 371. But this simpler behavior might be better
# anyway.)
if drag_type == 'move':
name = self.node.assy.name_autogrouped_nodes_for_clipboard( nodes, howmade = drag_type )
new = Group(name, self.node.assy, None)
for node in nodes[:]: #bruce 050216 don't reverse the order, it's already correct
node.unpick() #bruce 050216; don't know if needed or matters; 050307 moved from after to before moveto
node.moveto(new) ####@@@@ guess, same as in super.drop_on (move here, regardless of drag_type? no, not correct!)
nodes = [new] # a new length-1 list of nodes
env.history.message( "(fyi: Grouped some nodes to keep them in one clipboard item)" ) ###e improve text
else:
# the above implem is wrong for copy, so we handle it differently below,
# when autogroup_at_top and drag_type != 'move'
pass
pass
#e rewrite to use copy_nodes (nim)? (also rewrite the assy methods? not for alpha)
res = [] #bruce 050203: return any new nodes this creates (toplevel nodes only, for copied groups)
#bruce 050216: order is correct if you're dropping on a group, but (for the ops used below)
# wrong if you're dropping on a node. This needs a big cleanup, but for now, use this kluge
# [revised to fix bug 2403 (most likely, this never worked as intended for copy until now), bruce 070525]:
if not will_drop_inside:
# drops on nodes which act like leaf nodes are placed after them,
# when done by the methods named in the following flags,
# so to drop several nodes in a row and preserve order,
# drop them in reverse order -- but *when* we reverse them
# (as well as which method we use) depends on whether we're
# doing move or copy, so these flags are used in the right
# place below.
## reverse_moveto = True
reverse_addmember = True # for either addchild or addsibling
pass
else:
# will_drop_inside is True
#
# drops on groups which accept drops inside themselves
# go at the end of their members,
# when done by those methods, so *don't* reverse node order --
# UNLESS drop_onto_Group_at_top is set, which means, we put nodes dropped
# on groups at the beginning of their members list.
# REVIEW: are there any other things that need to be changed for that? ###
## assert not debug_pref_DND_drop_at_start_of_groups()
## reverse_moveto = drop_onto_Group_at_top
reverse_addmember = drop_onto_Group_at_top
#bruce 060203 removing this, to implement one aspect of NFR 932:
## self.node.open = True # open groups which have nodes dropped on them [bruce 050528 new feature]
pass
if drag_type == 'move':
# TODO: this code is now the same as the end of the copy case;
# after the release, clean this up by moving the common code
# outside of (after) this move/copy 'if' statement.
# [bruce 080414 comment]
if reverse_addmember: # [bruce 080414 post-rc0 code cleanup: reverse_moveto -> reverse_addmember]
nodes = nodes[::-1]
for node in nodes[:]:
## node.moveto(self.node)
if will_drop_inside:
self.node.addchild(node, top = drop_onto_Group_at_top)
else:
self.node.addsibling(node, before = False)
continue
pass
else:
#bruce 050527 [revised 071025] this uses copied_nodes_for_DND,
# new code to "copy anything". That code is preliminary
# (probably not enough history messages, or maybe sometimes
# too many). It would be better to create the Copier object
# (done in that subr?) earlier, when the drag is started,
# for various reasons mentioned elsewhere.
# update 071025: autogroup_at_top is now set at start of this method
## autogroup_at_top = isinstance(self.node, ClipboardShelfGroup)
#####@@@@@ kluge! replace with per-group variable or func.
#e or perhaps better, a per-group method to process the nodes list, eg to do the grouping
# as the comment in copied_nodes_for_DND or its subr suggests.
nodes = copied_nodes_for_DND(nodes, autogroup_at_top = autogroup_at_top)
# Note: this ignores order within input list of nodes, using only their MT order
# to affect the order of copied nodes which it returns. [bruce 070525 comment]
if not nodes: # might be None
return res # return copied nodes [bruce 080414 post-rc0 code cleanup: [] -> res]
res.extend(nodes)
# note: the following code is the same in the move/copy cases;
# see above for more about this.
if reverse_addmember:
nodes = nodes[::-1]
# note: if autogroup_at_top makes len(nodes) == 1, this has no effect,
# but it's harmless then, and logically best to do it whenever using
# addmember on list elements.
for node in nodes[:]:
# node is a "copied node" [bruce 080414 post-rc0 code cleanup: renamed nc -> node]
## self.node.addmember(node) # self.node is sometimes a Group,
## # so this does need to be addmember (not addchild or addsibling)
if will_drop_inside:
self.node.addchild(node, top = drop_onto_Group_at_top)
else:
self.node.addsibling(node, before = False)
continue
pass
self.node.assy.update_parts() #e could be optimized to scan only what's needed (same for most other calls of update_parts)
return res
# Note: the methods drop_under_ok and drop_under are never called
# (and drop_under is not fully implemented, as its comments indicate),
# but they should be kept around -- they are a partly-done implementation
# of an API extension to support Model Tree DND to points between nodes
# (as opposed to DND to points on top of single nodes, which is all the MT
# can do now). [bruce 050203/070703]
# Update, bruce 071025: if these methods become real, they might end up as the
# drop_on methods of a different controller, InterNodeGap_as_MT_DND_Target or so.
def drop_under_ok(self, drag_type, nodes, after = None): ###@@@ todo: honor it!
"""
Say whether it's ok to drag these nodes (using drag_type)
into a child-position under self.node,
either after the given child 'after'
or (by default) as the new first child.
Tree widgets can use this to offer drop-points shown in gaps
between existing adjacent nodes.
[some subclasses should override this]
"""
return self.node.MT_DND_can_drop_inside()
# See comment above for status of unused method 'drop_under', which should be kept around. [bruce 070703]
def drop_under(self, drag_type, nodes, after = None): #e move to Group[obs idea?], implem subrs, use ###@@@
"""
#doc
"""
if drag_type == 'copy':
nodes = copy_nodes_in_order(nodes) # make a homeless copy of the set (someday preserving inter-node bonds, etc)
for node in nodes:
self.node.addchildren(nodes, after = after) ###@@@ IMPLEM (and make it not matter if they are homeless? for addchild)
return
pass
# ==
# not yet used, but might be someday:
#
##from debug_prefs import debug_pref, Choice_boolean_False ##, Choice_boolean_True
## # this is not really needed, can remove if necessary
##
##def debug_pref_DND_drop_at_start_of_groups():
## #bruce 070525 -- this is so we can experiment with this NFR someday.
## # The code that needs to be affected by this is not yet implemented (but has a commented out call to it).
## # If we implement that and it works and we like it,
## # we'll change the default, or maybe even hardcode it, or maybe make it an official pref setting.
## return debug_pref("DND: drop at start of groups?", Choice_boolean_False,
## non_debug = True, prefs_key = True)
# end
| NanoCAD-master | cad/src/modelTree/Node_as_MT_DND_Target.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
modelTreeGui.py - provide a Qt4-compatible Model Tree widget,
inherited by modelTree.py to provide NE1's Model Tree of Nodes.
@author: Will, Bruce
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
Goals (of Will's refactoring, as part of the Qt3 -> Qt4 port):
There is now a clear simple API for the model tree, which amounts to a refactoring of the code
previously appearing in TreeView.py, TreeWidget.py, and modelTree.py. [For history, see the
modelTree.py docstring.]
The API needs to accomplish three things. First it must work in just this file with a very
restricted set of data, and in this context I [Will] need to bang on issues of selection, display, and
other GUI stuff. Second it needs to work with the uiPrototype.py stuff for the new user interface.
Third it needs to migrate into the NE-1 code cleanly, ideally with just a change of the filename.
Recent history:
Those goals were partly achieved, and in particular the API superclasses add a lot of clarity,
but in the implementation there were serious missing features and logic bugs... I have solved
some of these by bringing back some of the old code, and abandoning use of Qt's concept of selected
items, and rewriting the node-selection-related behaviors. In doing this, I added a few methods
to the APIs (not all of which are documented there -- see ##doc comments to find those that aren't).
There remain some serious cosmetic and performance bugs, relative to the Qt3 version, which I'm
still working on. [bruce 070508]
Update 070612: I [bruce] did a major rewrite to fix scrollbar bugs (circa May 07), mentioned in
comments below, before A9 release, using QScrollArea instead of QTreeView. Now I am removing the
obsolete code which used QTreeView, but some comments still refer to its classes. What's being
removed includes the classes:
class _our_QItemDelegate(QItemDelegate): # removed
class _our_TreeItem: # removed
class _QtTreeModel(QAbstractItemModel): # removed
class ModelTreeGui_QTreeView(QTreeView, ModelTreeGui_common): # removed
late 2007 and/or early 2008: Mark and Bruce implemented atom content indicators,
though some bugs remain
080507: Bruce partly implemented GLPane -> MT cross-highlighting
Bruce 081216 is doing some cleanup and refactoring, including splitting
ModelTree and TreeModel into separate objects with separate classes and
_api classes, and splitting some code into separate files.
"""
import sys
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.Qt import Qt
from PyQt4.Qt import QScrollArea
from PyQt4.Qt import QIcon
from PyQt4.Qt import QDrag
from PyQt4.Qt import QMimeData
from PyQt4.Qt import QPoint
from PyQt4.Qt import QPixmap
from PyQt4.Qt import QPainter
from PyQt4.Qt import QFontMetrics
from PyQt4.Qt import QLineEdit
from PyQt4.Qt import QColor
from PyQt4.Qt import QRect
from PyQt4.Qt import QPalette
import foundation.env as env
from modelTree.ModelTreeGUI_api import ModelTreeGUI_api
from modelTree.Node_as_MT_DND_Target import Node_as_MT_DND_Target #bruce 071025
from platform_dependent.PlatformDependent import fix_plurals
from PM.PM_Colors import getPalette
from utilities.GlobalPreferences import pref_show_node_color_in_MT
from utilities.Log import quote_html
from utilities.constants import AC_INVISIBLE, AC_HAS_INDIVIDUAL_DISPLAY_STYLE
from utilities.debug import print_compact_traceback, print_compact_stack
from utilities.debug_prefs import debug_pref, Choice_boolean_True, Choice_boolean_False, Choice
from utilities.icon_utilities import getpixmap
from utilities.icon_utilities import imagename_to_pixmap
from utilities.prefs_constants import mtColor_prefs_key
from widgets.menu_helpers import makemenu_helper
from widgets.simple_dialogs import grab_text_line_using_dialog
from widgets.widget_helpers import RGBf_to_QColor
_DEBUG0 = False # debug api compliance
_DEBUG = False # debug selection stuff
_DEBUG2 = False # mouse press event details
_DEBUG3 = False # stack, begin, end, for event processing
_DEBUG4 = False # print mousePress gl_updates
_ICONSIZE = (22, 22)
ITEM_HEIGHT = _ICONSIZE[1] # in theory, these need not be the same,
# but other values are untested [bruce 070529 guess]
_cached_icons = {} #bruce 070529 presumed optimization
def _paintnode(node, painter, x, y, widget, option_holder = None):
"""
Draw node in painter.
x,y are coords for topleft of type-icon.
widget (the modelTreeGui) is used for palette.
@param option_holder: the MT_View, used for dictionary attribute
_f_nodes_to_highlight and (in future)
for some prefs flags.
"""
#bruce 070529 split this out
#bruce 080507 added option_holder
### todo: revise appearance of highlighted nodes
## print "_paintnode",node, painter, x, y, widget
# x is 20, 40, etc (indent level)
# y is 0 for the top item, incrs by 22 for other items -- but this varies as we scroll.
# find state of node which determines how we draw it
selected = node.picked
disabled = node.is_disabled() ### might be slow!
display_prefs = display_prefs_for_node(node)
# someday these might also depend on parent node and/or on ModelTreeGui (i.e. widget)
text_color = None
if pref_show_node_color_in_MT():
# [bruce 080507 new feature, mainly for testing]
# review: should the modelTree itself (treemodel) test this pref
# and tell us the text_color for each node?
### is this debug_pref test too slow? if it is, so is the debug_pref lower down...
# could fix using option_holder to know the pref values
# note: this should work for all nodes with a .color attribute,
# not just chunks, but to work with Groups (including DnaStrand etc)
# it would need some revisions, e.g. call a new Node method
# get_node_color_for_MT (which would be a good refactoring anyway)
text_color = getattr(node, 'color', None) # node.color
highlighted = option_holder and node in option_holder._f_nodes_to_highlight
# fyi: for now, this means "highlighted in glpane",
# but in the future we'll also use it for MT mouseover highlighting
# draw it
node_icon = node.node_icon(display_prefs) # a QPixmap object
try:
pixmap = _cached_icons[node_icon]
except KeyError:
# print "making pixmap for node_icon", node_icon # should occur once per unique icon per session
pixmap = QIcon(node_icon).pixmap(_ICONSIZE[0], _ICONSIZE[1]) # vary the size
_cached_icons[node_icon] = pixmap
pass
# draw it (icon and label), possibly transforming the painter before and during this.
# Note about save/restore: Qt 4.1 doc says:
# After painting, you should ensure that the painter is returned to the state it was supplied in
# when this function was called. For example, it may be useful to call QPainter::save()
# before painting and QPainter::restore() afterwards.
need_save = disabled or selected or (text_color is not None) or highlighted
#bruce 070529 presumed optimization (not usually set for most nodes)
if need_save:
painter.save()
if disabled: # before
# draw icon and label in slanted form
painter.shear(0, -0.5)
painter.translate(0.5 * y + 4, 0.0)
painter.drawPixmap(x, y, pixmap)
# Draw a special symbol in the upper right corner of the node icon if one
# of the following conditions is true:
# - draw a small yellow dot if the node contains atoms that have their
# display style set to something other than diDEFAULT.
# - draw a small white ghost if the node contains invisible or hidden
# chunks and/or atoms.
# - draw a small yellow ghost if the node contains invisible or hidden
# chunks and/or atoms _and_ the node also contains atoms that have their
# display style set to something other than diDEFAULT.
# Mark 2008-03-04
#
# revised by bruce 080306, but not yet in final form, or in final place in this file. ###
# What remains to do (assuming this works so far):
# - some optimizations in the code for maintaining the node flags this accesses
# - MT needs to subscribe to changes in this data for nodes it draws (and get mt_update when that changes)
# - MT needs to include this data in what it compares about a node when deciding if redraw is needed.
# Until it does, even an MT click often won't update the MT as needed.
# (So to test this as it is so far, modify the model, then save and reopen the file.)
#
# Also need to revise behavior. See Qs below. Here are notes about the answers: [080314]
##yellow ghost: chunks in groups count (for both indicators)
##but hidden whole can coexist with ghost if the ghost is about hidden atoms
## (since unhide of them requires another step)
## (and the latter is nim, we'll make bug report)
node_symbols = debug_pref("Model Tree: add content symbols to node icons?",
#bruce 080416 renamed this, special -> content,
# for clarity
Choice_boolean_True, #bruce 080307 False -> True
non_debug = True,
prefs_key = True #bruce 080307 (safe now)
)
if node_symbols:
flags = node.get_atom_content(AC_INVISIBLE | AC_HAS_INDIVIDUAL_DISPLAY_STYLE)
# Hidden nodes get ghosts. [hmm, probably not right ### FIX]
node_has_invisible_contents = node.hidden
# NIM: so do nodes with hidden sub-nodes. ##### IMPLEM
# So do nodes which contain invisible (aka hidden) atoms:
if flags & AC_INVISIBLE:
node_has_invisible_contents = True
# Nodes which contain atoms with non-default display styles get yellow dots
# (or yellow ghosts if they already would have ghosts).
node_has_special_display_contents = False
if flags & AC_HAS_INDIVIDUAL_DISPLAY_STYLE:
node_has_special_display_contents = True
# What about non-default display styles on chunks? ### DECIDE, FIX
# Now draw all this.
if node_has_invisible_contents and node_has_special_display_contents:
painter.drawPixmap(x, y,
imagename_to_pixmap("modeltree/yellow_ghost.png"))
elif node_has_invisible_contents:
painter.drawPixmap(x, y,
imagename_to_pixmap("modeltree/white_ghost.png"))
elif node_has_special_display_contents:
painter.drawPixmap(x, y,
imagename_to_pixmap("modeltree/yellow_dot.png"))
if highlighted:
background = Qt.yellow # initial test, NOT IDEAL since obscures selectedness ######
elif selected:
background = widget.palette().highlight() #k what type is this? QColor or something else?
else:
background = None
if background is not None:
# draw a selection or highlight color as text bg color
###BUG: should use color role so it depends on app being in bg or fg
### (like it does for native QTreeView selectedness)
# (note: this used to be done before drawing the icon, but even then it did not affect the icon.
# so it would be ok in either place.)
## background = painter.background()
## backgroundMode = painter.backgroundMode()
painter.setBackground(background)
painter.setBackgroundMode(Qt.OpaqueMode)
if text_color is not None:
painter.setPen(RGBf_to_QColor(text_color))
yoffset = _ICONSIZE[1] / 2 + 4
painter.drawText(x + _ICONSIZE[0] + 4, y + yoffset, node.name)
if need_save:
painter.restore()
# About fixing bug 2372 by drawing the "red donut" to show the current Part:
# the following code works, and would be correct if we ported the sg and condition code,
# but it looks too ugly to consider using, IMHO (on my iMac G5).
# Maybe we should draw some sort of icon for this? [bruce 070514]
#
## ## sg = assy.current_selgroup_iff_valid()
## dotcolor = Qt.red
## if 1: ### sg == node and node != assy.tree:
## painter.save()
## painter.setPen(QPen(dotcolor, 3)) # 3 is pen thickness;
## # btw, this also sets color of the "moving 1 item"
## # at bottom of DND graphic!
## h = 9
## dx,dy = -38,8 # topleft of what we draw;
## # 0,0 is topleft corner of icon; neg coords work, not sure how far or how safe
## painter.drawEllipse(x + dx, y + dy, h, h)
## painter.restore()
return
# ==
_buttons = dict(left = Qt.LeftButton,
mid = Qt.MidButton,
right = Qt.RightButton )
_modifiers = dict(shift = Qt.ShiftModifier,
control = Qt.ControlModifier,
alt = Qt.AltModifier,
meta = Qt.MetaModifier,
keypad = Qt.KeypadModifier,
X11_Mode_switch = Qt.GroupSwitchModifier )
# http://www.riverbankcomputing.com/Docs/PyQt4/html/qt.html says:
# Note: On Mac OS X, the ControlModifier value corresponds to the Command keys on the Macintosh keyboard,
# and the MetaModifier value corresponds to the Control keys. The KeypadModifier value will also be set
# when an arrow key is pressed as the arrow keys are considered part of the keypad.
# Thus, on any platform we can use ControlModifier for de-select, but context menu requests on the Mac
# may involve either RightButton or MetaModifier. (Also, Qt seems to mess them up in a complicated way,
# splitting them into an event with inconsistent button/buttons flags (LMB and RMB respectively), followed
# by a contextMenuEvent call, at least if we don't use setContextMenuPolicy.
def describe_buttons(buttons):
return _describe( int(buttons), _buttons)
def describe_modifiers(modifiers):
return _describe( int(modifiers), _modifiers)
def _describe( flags, name_val_dict):
origflags = flags
flags = int(flags)
res = []
items = name_val_dict.items()
items.sort() #e suboptimal order
for name, val in items:
val = int(val)
if val & flags:
res.append(name)
flags = flags &~ val
if flags:
res.append("unknown flags %#x" % flags)
desc = ", ".join(res) # might be empty
return "%#x (%s)" % (int(origflags), desc)
# ==
# Things can be simpler if we admit that display_prefs don't yet depend on the ModelTreeGui object.
# So for now I'm pulling this out of that object, so _our_QItemDelegate.paint can access it without having a pointer to that object.
# I'm also optimizing it, since it'll be called a lot more often now.
# (Even better would be to optimize the node_icon API so we can pass .open directly.
# We don't want to let the node use its own .open, in case in future we show one node in different MTs.)
# [bruce 070511]
def display_prefs_for_node(node):
"""
Return a dict of the *incremental* display prefs for the node,
relative to whatever its parent passes as display prefs for its own MT_kids.
Any prefs that it should inherit from its parent's env should be left out of this dict.
The complete set of display prefs can be used by node_icon to decide what icon the treeview
should display for this node. (It can also use the node class or state.)
In current code, the only thing this needs to include is whether this node
is openable, and if so, whether it's open.
[Subclasses can override this.]
[Using this cumbersomeness just to say whether the item is open
is not worthwhile in hindsight. Fix it sometime. #e]
"""
if node.openable():
if node.open:
return _DISPLAY_PREFS_OPEN
else:
return _DISPLAY_PREFS_CLOSED
else:
return _DISPLAY_PREFS_LEAF
pass
_DISPLAY_PREFS_OPEN = dict(openable = True, open = True)
_DISPLAY_PREFS_CLOSED = dict(openable = True, open = False)
_DISPLAY_PREFS_LEAF = {}
# ==
class DoNotDrop(Exception): pass
class ModelTreeGui_common(ModelTreeGUI_api):
"""
The part of our ModelTreeGui implementation which is the same
for either type of Qt widget used to show it.
"""
# not private, but only used in this file so far [bruce 080306 comment]
#bruce 070529 split this out of class ModelTreeGui
def __init__(self, win, treemodel):
self.win = win
self.treemodel = treemodel
self._mousepress_info_for_move = None
# set by any mousePress that supports mouseMove not being a noop,
# to info about what that move should do #bruce 070509
self._ongoing_DND_info = None
# set to a tuple of a private format, during a DND drag
# (not used during a selection-drag #k)
self.setAcceptDrops(True)
if _DEBUG0:
self._verify_api_compliance()
# Make sure certain debug_prefs are visible from the start,
# in the debug_prefs menu -- but only the ones that matter
# for the MT implem we're using in this session.
# WARNING (kluge): the defaults and other options are
# duplicated code, but are only honored in these calls
# (since these calls happen first).
# these are used in both MT implems:
self.debug_pref_use_fancy_DND_graphic()
self.MT_debug_prints()
return
def topmost_selected_nodes(self, topnode = None, whole_nodes_only = False):
"""
@return: a list of all selected nodes which are not inside selected Groups
@see: TreeModel_api version, for more detailed documentation
"""
#bruce 070529 moved method body into self.treemodel
#bruce 081216 removed this from ModelTreeGUI_api,
# since it's just a convenience method in this implem
return self.treemodel.topmost_selected_nodes(topnode = topnode,
whole_nodes_only = whole_nodes_only )
def MT_debug_prints(self):
return debug_pref("MT debug: debug prints", Choice_boolean_False, prefs_key = True)
def display_prefs_for_node(self, node):
"""
For doc, see the global function of the same name.
"""
return display_prefs_for_node(node) #bruce 070511 revised this to make it a global function
# == DND start methods
def _start_DND(self, item, option_modifier):
thisnode = item.node
drag_type = option_modifier and 'copy' or 'move'
#bruce 070509 kluge condition, not sure fully correct (Qt3 code used fix_event then looked for MidButton)
###REVIEW: what sets the drag cursor -- does it redundantly compute this? Or does the cursor think it's *always* copy?
nodes = self._dnd_nodes
# set in mousepress, using info we no longer have
# (due to its having already altered the selection)
# now filter these nodes for the ones ok to drag, in the same way the Qt3 code did --
# and not in every drag move event method [bruce 070509]
nodes = self.filter_drag_nodes( drag_type, nodes ) # might be None
if not nodes: # whether None or []
return # message already emitted (if one is desired)
# work around visual bug due to unwanted deselection of some of these nodes (during mousePressEvent)
self.unpick_all()
for node in nodes:
node.pick()
self.mt_update()
# if that doesn't work, try self.repaint()
self._ongoing_DND_info = (nodes, drag_type)
# as a temporary workaround for the DND graphic being inadequate,
# at least print a decent sbar message about it.
# make up some text to be dragged in case the custom pixmap doesn't work or is nim
dragobj_text = "%s %d item(s)" % (drag_type, len(nodes)) # e.g. "copy 5 item(s)"
dragobj_text = fix_plurals(dragobj_text) # e.g. "copy 5 items" or "move 1 item" -- no "ing" to keep it as short as possible
# make the dragobj [move sbar code above this? #e]
## dragsource = self
## dragobj = QTextDrag( dragobj_text, dragsource)
## # \n and \r were each turned to \n, \n\r gave two \ns - even in "od -c"; as processed through Terminal
dragobj = QDrag(self)
mimedata = QMimeData()
mimedata.setText("need a string here for a valid mimetype")
dragobj.setMimeData(mimedata)
pixmap = self.get_pixmap_for_dragging_nodes(drag_type, nodes)
if pixmap:
dragobj.setPixmap(pixmap)
sbar_text = self.get_whatting_n_items_text( drag_type, nodes)
self.statusbar_message( sbar_text)
dragobj.setHotSpot(QPoint(-18, 8)) #bruce 070514 tweak hotspot
requested_action = {'copy':Qt.CopyAction, 'move':Qt.MoveAction}[drag_type]
#bruce 070514 fix bug in DND cursor copy/move indication
dragobj.start( requested_action)
return # nodes
def filter_drag_nodes(self, drag_type, nodes):
#bruce 070509 copied this from Qt3 TreeWidget.py [#k same as in Qt4 TreeWidget??]
"""
See which of the given nodes can be dragged (as a group) in the given way.
Return a subset of them to be actually dragged
(having emitted a warning, if desired, if this is not all of them),
or someday perhaps a processed version of them (e.g. you could pre-make copies for a 'copy' drag),
or None (*not* just a list [] of 0 nodes to drag! that might be possible to drag!)
if you want to refuse this drag (also after emitting a suitable warning).
"""
if drag_type == 'move':
nodes_ok = filter( lambda n: n.drag_move_ok(), nodes)
else:
nodes_ok = filter( lambda n: n.drag_copy_ok(), nodes)
oops = len(nodes) - len(nodes_ok)
if oops:
## msg = "some selected nodes can't be dragged that way -- try again" ###e improve msg
## msg = "The Part can't be moved"
## # kluge: this is the only known case! (that I can remember...) #e generalize this
## self.redmsg(msg)
#bruce 070509 commented that out, since I think it will often
# happen by accident for "small move onto self"
# note: self.redmsg is probably not yet defined
return None
return nodes_ok # same as nodes for now, but we might change above code so it's not
def debug_pref_use_fancy_DND_graphic(self):
return debug_pref("Model Tree: use fancy DND graphic?",
Choice_boolean_True,
non_debug = True,
prefs_key = True)
def get_pixmap_for_dragging_nodes(self, drag_type, nodes):
if self.debug_pref_use_fancy_DND_graphic():
pixmap = self.get_pixmap_for_dragging_nodes_Qt3(drag_type, nodes)
else:
# stub version, just the icon from the first node
display_prefs = self.display_prefs_for_node(nodes[0])
#bruce 070504 bugfix (partial fix only)
pixmap = nodes[0].node_icon(display_prefs)
return pixmap
def get_whatting_n_items_text(self, drag_type, nodes):
"""
return something like 'moving 1 item' or 'copying 5 items'
"""
ing_dict = { "move":"moving", "copy":"copying" }
whatting = ing_dict[ drag_type] # moving or copying?
return fix_plurals( "%s %d item(s)" % (whatting, len(nodes)) )
# not quite the same as the shorter text for the QDragObject itself;
#e might become more different in the future if we include the class
# when they're all nodes of the same subclass...
def statusbar_message(self, msg):
# note: spelling difference.
# maybe todo: rename all methods of that name like this.
# [bruce 070531 & 081216]
# todo: store current msg for this widget, so we can share statusbar
# with other widgets; or better, the method we're calling should do that
# for all widgets (or their parts) in a uniform way
env.history.statusbar_msg( msg)
# == Qt3 code for drag graphic, not yet ported, used only if debug_pref set [copied from Qt3/TreeWidget.py, bruce 070511]
# == [update: I think this is now fully ported and used by default, long before 080507]
def get_pixmap_for_dragging_nodes_Qt3(self, drag_type, nodes):
#e [also put the drag-text-making code in another method near here? or even the dragobj maker?
# or even the decision of what to do when the motion is large enough (ie let drag_handler role be only to notice that,
# not to do whatever should be done at that point? as if its role was to filter our events into higher level ones
# where one of them would be enoughMotionToStartADragEvent?] ###e yes, lots of cleanup is possible here...
"""
Our current drag_handler can call this to ask us for a nice-looking pixmap
representing this drag_type of these nodes,
to put into its QDragObject as a custom pixmap.
If we're not yet sure how to make one, we can just return None.
"""
listview = self
##pixmap = QPixmap("/Nanorex/Working/cad/src/butterfly.png") # this works
##print pixmap,pixmap.width(),pixmap.height(),pixmap.size(),pixmap.depth()
w,h = 160,130
if 1:
# but that's not good if len(nodes) is large, so use the following;
# note that it depends on the details of hardcoded stuff in other functions
# and those don't even have comments warning about that! ###
# [bruce 050202 10:20am]:
item = self.nodeItem(nodes[0]) # Grab a node to find out it's height
ih = item.height()
h = max(1,min(3,len(nodes))) * ih + ih # the last 24 is a guess for the text at the bottom
w = self.get_drag_pixmap_width(nodes)
if len(nodes)>3:
h += 10 # for the "..."
pass
pixmap = QPixmap(w,h) # should have size w,h, depth of video mode, dflt optimization
##print pixmap,pixmap.width(),pixmap.height(),pixmap.size(),pixmap.depth()
## pixmap.fill(Qt.red) # makes it red; what's dragged is a pretty transparent version of this, but red... (looks nice)
# CAREFUL: calling pixmap.fill() with no arguments creates problems
# on Windows and Linux. Text will not be drawn. Be sure to include
# a QColor argument so that the QPainter's setPen color can work
# as expected. Mark 050205
#
#pixmap.fill() # makes pixmap white, but text can't be drawn
## pixmap.fill(listview,0,0)
## following would fill with this widget's bgcolor...
## but it actually looks worse: very faint stripes, all faintly visible
p = QPainter(pixmap)
# Determine the pixmap's background and text color
if 1: ## sys.platform == 'darwin': # Mac
hicolor = Qt.white
textcolor = Qt.black
# Note: I disabled the following special case, since it's not yet ported to Qt4 (it caused bug 2395) -- bruce 070514
## else: # Window and Linux
## colorgroup = listview.palette().active()
## hicolor = QColor (colorgroup.highlight())
## textcolor = QColor (colorgroup.highlightedText())
pixmap.fill(hicolor) # Pixmap backgroup color
p.setPen(textcolor) # Pixmap text draw color
try:
self.paint_nodes(p, drag_type, nodes)
return pixmap
except:
p.end() # this is needed to avoid segfaults here
print_compact_traceback("error making drag-pixmap: ")
return None
pass
def paint_node(self, p, drag_type, node):
"""
paint one node's item into QPainter p, and translate it down by the item's height
"""
#e someday also paint the little openclose triangles if they are groups?
#e unselect items first, at least for copy?
item = self.nodeItem(node)
width = self.paint_item( p, item) # was 99 for one example -- note, font used was a bit too wide
height = item.height() # was 24
p.translate(0,height)
return width, height
#btw exception in above (when two subr levels up and different named vars) caused a segfault!
# [before we caught exception, and did p.end(), in routine creating painter p]
##Qt: QPaintDevice: Cannot destroy paint device that is being painted. Be sure to QPainter::end() painters!
##NameError: global name 'item' is not defined
##Segmentation fault
##Exit 139
# This means I need to catch exceptions inside the functions that make painters!
# And keep the painters inside so they refdecr on the way out.
# (Or actually "end" them... in fact that turns out to be needed too.)
def paint_nodes(self, p, drag_type, nodes):
"""
paint a dragobject picture of these nodes into the QPainter p; if you give up, raise an exception; return w,h used??
"""
nn = len(nodes)
if not nn:
print nodes,"no nodes??" # when i try to drag the clipboard?? because unselected.
# need to filter it somehow... should be done now, so this should no longer happen.
# also the history warning is annoying... otoh i am not *supposed* to drag it so nevermind.
return
if nn >= 1:
self.paint_node( p, drag_type, nodes[0])
if nn >= 2:
self.paint_node( p, drag_type, nodes[1])
if nn >= 4: # yes, i know 4 and 3 appear in reversed order in this code...
# put in "..."
p.drawText(0,6," ...") # y=6 is baseline. It works! Only required 5 or 6 steps of directed evolution to get it right.
p.translate(0,10) # room for a "..." we plan to put in above # 8 is a guess
if nn >= 3:
self.paint_node( p, drag_type, nodes[-1])
#e also put in the same text we'd put into the statusbar
text = self.get_whatting_n_items_text(drag_type, nodes)
item = self.nodeItem(nodes[0]) # Grab a node to find out it's height
h = item.height()
w = self.get_drag_pixmap_width(nodes)
flags = 0 # guess
p.drawText(4,4,w,h,flags,text) # in this drawText version, we're supplying bounding rect, not baseline.
#e want smaller font, italic, colored...
return
def get_drag_pixmap_width(self, nodes):
return 168 ###STUB
## pt = QPainter(self, True) # Qt3 version
#print "before QP"
pt = QPainter(self) # this prints:
## QPainter::begin: Widget painting can only begin as a result of a paintEvent
# then later we get
## QPainter::end: Painter not active, aborted
#print "after QP"
try:
fontmetrics = pt.fontMetrics()
w = pt.fontMetrics().width("Copying 99 items") ## AttributeError: width
maxw = w * 1.5
for node in nodes:
item = self.nodeItem(node)
cw = item.width(fontmetrics, self, 0)
if cw > w: w = cw
except:
w = 160
print_compact_traceback( "Exception in get_drag_pixmap_width: w = %r: " % (w,) )
pt.end()
# guess: this line is what prints
## QPainter::end: Painter not active, aborted
# and that must raise an exception which prevents the NameError from maxw.
# But why don't I see that exception? Maybe it's something weirder than an exception?!?
return min(maxw, w + 8)
# == DND event methods ###SLATED FOR REVIEW and likely eventual rewrite or replacement
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dragMoveEvent(self, event):
event.acceptProposedAction()
def dropEvent(self, event):
try:
self._do_drop_or_raise_DoNotDrop(event)
except DoNotDrop:
event.ignore()
self.mt_update()
self._ongoing_DND_info = None # nodes
return
def _do_drop_or_raise_DoNotDrop(self, event): #bruce 070511 split this out
"""
[private] Do a drop, or raise a DoNotDrop exception.
Print a message, but do appropriate updates only if we succeed.
"""
#bruce 070511 brought in several error messages from Qt3/TreeWidget.py,
# modified some of them, made them use statusbar_message rather than history
# redmsg
item, rectjunk = self.item_and_rect_at_event_pos(event)
if item is None:
msg = "drop into empty space ignored (drops under groups " \
"not supported; drop onto them instead)"
self.statusbar_message( msg)
raise DoNotDrop()
nodes, drag_type = self._ongoing_DND_info
targetnode = item.node
if targetnode in nodes:
# don't print a message -- probably common for small mouse motions
# (thus, don't leave this for drop_on_ok to find)
# (not verified by test that it *will* find it, though it ought to)
if _DEBUG2:
print "debug warning: MT DND: targetnode in nodes, refusing drop" # new behavior, bruce 070509
#e should generalize based on what Qt3 code does [obs cmt?]
raise DoNotDrop()
ok, whynot = Node_as_MT_DND_Target(targetnode).drop_on_ok(drag_type, nodes)
if not ok:
msg = "drop refused by %s" % quote_html(targetnode.name)
if whynot:
msg += ": %s" % (whynot,) #bruce 080303
self.statusbar_message( msg )
raise DoNotDrop()
event.acceptProposedAction() # this should come after any DoNotDrop we might raise
#bruce 070511 fixing some bugs by bringing in copiednodes & oldpart & unpick/pick code from Qt3/TreeWidget.py
oldpart = nodes[0].part #bruce 060203
oldassy = nodes[0].assy # not needed (assy can't be different yet) but ok for now [bruce 070511 comment]
if drag_type == 'move':
#bruce 060203 see if this helps implement NFR/bug 932 (which says, don't pick moved nodes or open their drop target);
# do this first to make sure they're not picked when we move them... which might change current part [unverified claim].
for node1 in nodes:
node1.unpick()
copiednodes = Node_as_MT_DND_Target(targetnode).drop_on(drag_type, nodes)
#bruce 050203: copiednodes is a list of copied nodes made by drop_on
# (toplevel only, when groups are copied).
# For a move, it's []. We use it to select the copies, below.
#bruce 050203 cause moved nodes to remain picked;
# for copied nodes, we want the copies not originals to be picked.
#bruce 060203 no longer pick moved nodes if moved into a different part, but still pick copies,
# or nodes moved into the same part (or entire parts moved as a whole, only possible w/in clipboard).
if drag_type == 'move':
# this case rewritten by bruce 060203 re bug/NFR 932 (whose full fix also involved other files)
self.unpick_all() # probably redundant now
# pick the moved nodes, iff they are still in the same part.
# run update_parts to help us; this covers case of moving an entire part w/in the clipboard,
# in which it should remain picked.
# (Someday it might be useful to look at nodes[0].find_selection_group() instead...)
self.win.assy.update_parts()
# FYI: drop_on sometimes does update_parts, but not always, so do it here to be safe. Optim this later.
# Note: knowing anything about parts, and maybe even knowing self.win.assy, violates modularity
# (re supposed generality of TreeWidget as opposed to modelTree); fix this later.
# (I guess just about this entire method violates modularity, and probably so does much else in this file.
# As an older comment said:
# Note that this behavior should be subclass-specific, as should any knowledge of "the clipboard" at all!
# This needs review and cleanup -- maybe all this selection behavior needs to ask nodes what to do.)
newpart = nodes[0].part
if oldpart is newpart:
for node1 in nodes:
node1.pick()
pass
else:
self.unpick_all()
# Pre-060203 code: we pick the copies iff they remain in the main part.
# The reason we don't pick them otherwise is:
# - NFR 932 thinks we shouldn't, in some cases (tho it probably doesn't think that
# if they are and remain in one clipboard part)
# - there's a bug in drop_on which can put them in more than one clipboard item,
# but the selection is confined to one clipboard item.
# With a little work we could improve this (in the cases not affected by that bug).
# [comment revised, bruce 060203]
## if not targetnode.in_clipboard(): # [method removed, 090119]
## for node1 in copiednodes:
## node1.pick()
#bruce 060203 revising this to use similar scheme to move case (but not when copies get split up):
# pick the copies if they're in the same part as the originals.
# (I believe this will either pick all copies or none of them.)
self.win.assy.update_parts()
for node1 in copiednodes:
if node1.part is oldpart:
node1.pick()
pass
# ... too common for a history message, i guess...
msg = "dropped %d item(s) onto %s" % \
(len(nodes), quote_html(targetnode.name))
#e should be more specific about what happened to them...
# ask the target node itself? have drop_on return this info?
msg = fix_plurals(msg)
self.statusbar_message( msg)
#bruce 050203: mt_update is not enough, in case selection changed
# (which can happen as a side effect of nodes moving under new dads in the tree)
self.win.win_update()
return
def unpick_all(self):
self.treemodel.unpick_all()
# == mouse click and selection drag events, and DND start code
def mouseMoveEvent(self, event):
if _DEBUG3:
print "begin mouseMoveEvent"
try:
if self._mousepress_info_for_move is None:
return
(item, eventInRect, option_modifier) = self._mousepress_info_for_move
# might we be a DND, or a dragged-out selection [nim]?
# for DND we need item and eventInRect (and if true, we only start one if one is not ongoing);
# for selection we need not eventInRect (and perhaps item).
if item and eventInRect:
# possibly start a DND (if not already doing one)
if self._ongoing_DND_info is not None:
return
### old LOGIC BUGS, hopefully fixed as of bruce 070509
# - should not do this unless we decided the press event was in a place that would permit it
# - the dragged object should depend on that press, not on the cursor position now (unlike how index is computed below)
dragLength = (event.globalPos() - self.mouse_press_qpoint).manhattanLength()
if dragLength < 10: ## QApplication.startDragDistance(): ###REVIEW: is this the best distance threshhold to use?
# the mouse hasn't moved far enough yet
return
self._start_DND( item, option_modifier)
return
#e dragging out a selection is nim; the hard parts include:
# - need to know what items were in between the ones hit
# - need to recompute selected items based on original ones,
# altered ones by drag, and selection inference rules
# for both picking (into kids) and unpicking (into parents)
# - need faster update of state and display than we have
# [bruce 070609 comments]
return
finally:
if _DEBUG3:
print "end mouseMoveEvent"
pass
# ==
_mousepress_info_for_doubleclick = None, None # always a pair; always set; but only matters in QScrollArea implem
def mousePressEvent(self, event, _doubleclick = False):
"""
called by Qt on mousePress, or by our own method with private option _doubleclick = True
"""
## self.mouse_press_scrollpos = self.get_scrollpos("start of mousePressEvent")
###BUG: messes up manual scroll + click elsewhere (causing mt_update) -- this pos rules, discarding the manual scroll.
# partial workaround for now -- do this only for a cmenu click... still causes that bug right after it, i think...
# unless we del the attr then? no, we don't know *when* to del it -- "after updates caused by event X"???
# This is more often correct than the one we get during a later paintEvent after a cmenu command,
# for unknown reasons, so save it and use it (to preserve scroll position) instead of whatever we get then.
# Note: this is unlikely to cure the scroll-jump-to-top that sometimes happens (on Mac) when the app is
# brought to the foreground (also for unknown reasons, but the mouseclick that does that can even be on
# the dock area, presumably unseen by this object). Maybe we can intercept an "app now in foreground event"
# and change its behavior? Should I browse the Qt source code for stray scrollToTops etc?
self._mousepress_info_for_move = None
_prior_mousepress_info_for_doubleclick = self._mousepress_info_for_doubleclick
self._mousepress_info_for_doubleclick = None, None
# Note: set below; used only when called later with _doubleclick, which is only done
# by the QScrollArea implem subclass, not the QTreeView one.
qp = event.globalPos() # clone the point to keep it constant
self.mouse_press_button = button = event.button() #bruce 070509
self.mouse_press_buttons = buttons = event.buttons()
self.mouse_press_modifiers = modifiers = event.modifiers()
# simulate effect of fix_buttons / fix_event in the type-of-event analysis
# [bruce 070509; later should ###REVIEW for consistency, or use one of those functions]
option_modifier = (button == Qt.MidButton) or (modifiers & Qt.AltModifier) ###TODO: other conds like this should use this flag
contextMenu = (button == Qt.RightButton) or (modifiers & Qt.MetaModifier)
if contextMenu and hasattr(self, 'get_scrollpos'): # hasattr is kluge, varies by subclass [bruce 070529]
# do this asap in case its value changes for mysterious reasons (as seems plausible from experience)
self.mouse_press_scrollpos = self.get_scrollpos("start of mousePressEvent for cmenu")
###BUG: see comment for same thing at start of method
else:
self.mouse_press_scrollpos = None
del self.mouse_press_scrollpos
if _DEBUG2:
print "\nMT mousePressEvent: button %r, buttons %s, modifiers %s, globalPos %r, pos %r" % \
(button,
describe_buttons(buttons), # str and repr only show the class, which is PyQt4.QtCore.MouseButtons; int works
describe_modifiers(modifiers),
(qp.x(), qp.y()),
(event.pos().x(), event.pos().y())
)
self.mouse_press_qpoint = QPoint(qp.x(), qp.y()) # used in mouseMoveEvent to see if drag length is long enough
item, rect = self.item_and_rect_at_event_pos(event)
# note about coordinates:
# in QTreeView implem, I am not sure which coords event and this rect are in, contents or viewport.
# in QScrollArea implem, they should be in viewport (once item_and_rect_at_event_pos is bugfixed).
eventInRect = False # might be changed below; says whether event hits rect including icon(??) and name/label
if item is not None:
self.statusbar_message( quote_html( item.node.name)) #bruce 070511 -- no other way to see long node names!
# (at least for now -- tooltips are off for some reason, MT can't be widened, and it has no horizontal scrollbar,
# though it did a few days ago -- don't know why.)
alreadySelected = item.node.picked #bruce 070509
if _DEBUG2:
print "visualRect coords",rect.left(), rect.right(), rect.top(), rect.bottom()
qfm = QFontMetrics(QLineEdit(self).font())
rect.setWidth(qfm.width(item.node.name) + _ICONSIZE[0] + 4)
if _DEBUG2:
print "visualRect coords, modified:",rect.left(), rect.right(), rect.top(), rect.bottom()
# looks like icon and text, a bit taller than text (guesses)
eventInRect = rect.contains(event.pos())
if _DEBUG2:
print "real item: eventInRect = %r, item = %r, alreadySelected = %r" % \
(eventInRect, item, alreadySelected)
else:
alreadySelected = False # bruce 070509
if _DEBUG2:
print "no item"
pass
if _doubleclick:
# Either handle a double click (if all is ok for that), or do nothing for this event (return early).
# (Question: will there be a mouseRelease event for this??)
if eventInRect and not contextMenu \
and not (modifiers & Qt.ShiftModifier) and not (modifiers & Qt.ControlModifier):
olditem, oldrect_junk = _prior_mousepress_info_for_doubleclick
if olditem and (olditem.node is item.node):
self.handle_doubleclick( event, item, rect) # this should do all needed updates
return
if eventInRect and not contextMenu \
and not (modifiers & Qt.ShiftModifier) and not (modifiers & Qt.ControlModifier):
assert item
self._mousepress_info_for_doubleclick = (item, rect) # use this only if next call has _doubleclick true
# if not eventInRect, should also figure out if we are to left or right (maybe; nim),
# or on openclose decoration (certainly; done now)
if not eventInRect and item and item.node.openable():
# we're on item's row, and item has an openclose decoration (or should have one anyway) -- are we on it?
left_delta = rect.left() - event.pos().x()
if _DEBUG2:
print "left_delta is %r" % left_delta
if 0 < left_delta < 20:
# guess; precise value doesn't matter for correctness, only for "feel" of the UI
# (see also OPENCLOSE_AREA_WIDTH, but that's defined only for one of our two implems)
# we presume they're toggling the openclose decoration
node = item.node
node.open = not node.open
self.mt_update()
## self.win.glpane.gl_update()
if _DEBUG3:
print "returning from mousePressEvent (openclose case)"
return
pass
# ISSUE: if this press starts a DND, we don't want the same
# selection effects as if it doesn't. What did the Qt3 code do?
# ###REVIEW that....
# for now, save some info for mouseMoveEvent to use.
# (Might be clearer if saved in separate attrs? #e)
if not contextMenu:
self._mousepress_info_for_move = (item, eventInRect, option_modifier)
# value determines whether a mouse move after this press might
# drag nodes, drag out a selection (nim), or do nothing
if item:
# figure out nodes to drag by DND, since we might change them
# below but wish we hadn't (kluge until better fix is found)
if alreadySelected:
self._dnd_nodes = self.topmost_selected_nodes( whole_nodes_only = True)
# note: using whole_nodes_only = True here should
# fix bug 2948 for DND [bruce 081218]
else:
self._dnd_nodes = [item.node]
# Flags indicating actions we might take (mostly, modifying selection)
unselectOthers = False
# if you set this, you must also set selectThis or unselectThis,
# unless there's no item
# i.e. not eventInRect ###k I think [bruce 070509]; see if we do
selectThis = False
unselectThis = False
toggleThis = False # toggle selection state
# See "Feature:Model Tree" in the public wiki for model tree mouse controls
###REVIEW: is it right to look at event.buttons() but ignore event.button(), here?
# Evidently not (at least for cmenu on Mac)... Revising it [bruce 070509]
if 1:
if modifiers & Qt.ShiftModifier:
if modifiers & Qt.ControlModifier:
# shift control left click
unselectOthers = False
toggleThis = eventInRect
else:
# shift left click
unselectOthers = False
selectThis = eventInRect
unselectThis = False #bruce 070509 revised, was unselectThis = not eventInRect
else:
if modifiers & Qt.ControlModifier:
# control left click
## pass
unselectThis = eventInRect #bruce 070509 revised, was a noop
selectThis = False
else:
# left click
selectThis = eventInRect
unselectThis = False #bruce 070509 revised, was unselectThis = not eventInRect
if not (alreadySelected and contextMenu):
# this cond is bruce 070509 bugfix; this would make it wrong for DND,
# but to avoid that we saved the selected nodes earlier (see comments there for caveats).
unselectOthers = True
if _DEBUG:
print
print "unselectOthers", unselectOthers
print "selectThis", selectThis
print "unselectThis", unselectThis
print "toggleThis", toggleThis
print "contextMenu", contextMenu
print "SELECTED BEFORE <<<"
print self.topmost_selected_nodes( whole_nodes_only = False)
print ">>>"
assert not (selectThis and toggleThis) # confusing case to be avoided
assert not (selectThis and unselectThis) # confusing case to be avoided
assert not eventInRect or not unselectOthers or (selectThis or unselectThis) #bruce 070509 added this
# take whatever actions are required (one or more of the following, in order -- selection and maybe cmenu)
updateGui = False # whether we need to update MT and/or GLPane at the end
###TODO: optimize by only setting updateGui if something changes
if unselectOthers:
###REVIEW: this actually unselects all (this node too), not just
# others -- is that ok? Even if it's inside a picked group?
# I think it's ok provided we reselect it due to selectThis
# (or specifically unselect it too).
self.unpick_all() #bruce 070509 optimization
updateGui = True
if selectThis and item is not None:
item.node.pick()
updateGui = True
if unselectThis and item is not None:
item.node.unpick()
updateGui = True
if toggleThis and item is not None:
assert not unselectOthers
if item.node.picked:
item.node.unpick()
else:
item.node.pick()
updateGui = True
if contextMenu:
# Note: some of the above selection actions may have also been done.
# In the QScrollArea implem, we need to redraw the MT to show them;
# in the QTreeView implem, we apparently didn't need to, but it shouldn't hurt.
if updateGui:
self.mt_update()
self._renamed_contextMenuEvent(event)
# Why no updateGui = True here? Because the cmenu commands are supposed to do their own updates as needed.
# But it probably has little effect now to not do it, because we probably do it anyway
# during the selection phase above.
if eventInRect and not contextMenu \
and not (modifiers & Qt.ShiftModifier) and not (modifiers & Qt.ControlModifier):
# plain left click --
# also do direct left click effects for nodes that have any
# [new feature, bruce 080213]
assert item.node
try:
item.node.ModelTree_plain_left_click
except AttributeError:
pass # soon, this should never happen
else:
self.mt_update()
# kluge (not sure it'll work) -- try to update the MT
# at the start, not end, of long-running side effects
# in the following method, like animating a view change.
# (But we will still do it again below, in case something
# changed during a long op here (this is ok since it
# should be fast if nothing changed).
item.node.ModelTree_plain_left_click()
pass
if _DEBUG:
print "SELECTED AFTER <<<"
print self.topmost_selected_nodes( whole_nodes_only = False)
print ">>>"
if updateGui: # this is often overkill, needs optim
if _DEBUG3:
print "doing updateGui at end of mousePressEvent"
self.mt_update()
self.win.glpane.gl_update()
if _DEBUG4:
###### BUG: clicks in MT do gl_update as this shows,
# but don't always redraw with the correct picked state!
# Not yet reproducable except when testing fixed bug 2948.
print "mt did gl_update, selected nodes are", self.topmost_selected_nodes()
if _DEBUG3:
print "end mousePressEvent"
return # from mousePressEvent
def mouseReleaseEvent(self, event):
if _DEBUG3:
print "begin/end mouseReleaseEvent (almost-noop method)"
self._ongoing_DND_info = None
# ==
def contextMenuEvent(self, event): ###bruce hack, temporary, just to make sure it's no longer called directly
if 1:
print "\n *** fyi: MT: something called self.contextMenuEvent directly -- likely bug ***\n"
print_compact_stack("hmm, who called it?: ")
# Note: this can be called directly by app.exec_() in main.py,
# and is, if we use microsoft mouse right click on iMac G5 in Qt 4.2.2, *or* control-left-click;
# if that can't be changed (by finding an interceptable caller in common with mousePressEvent),
# we might need to revise this to also do selection click actions,
# but OTOH, for reasons unknown, mousePressedEvent is running *first* as if it was a left click
# (but with an unknown modifier flag, the same one for either right-click or control-left-click),
# which might remove the need for that if we can be sure it will always happen.
# We also need to know whether all this happens the same way for control-left-click on Mac (I guess yes),
# and/or for other mice, and/or on Windows, and/or in later versions of Qt.
# Need to ###REVIEW:
# - Qt docs for this (both about modifiers, and buttons/button, and sequence of event calls for contextMenuEvent)
# - comments in fix_buttons (which we're not using but maybe should be)
# - is it related to buttons not always including button?
# What's happening in that first event is buttons = 1 (left), button = 2 (right).
# This still leaves unexplained (1) who calls contextMenuEvent, (2) why two events occur at all.
# (Could it have anything to do with the tab control?? ###REVIEW)
# What about for a plain left click? Then we get button 1, buttons 0x1 (left) (inconsistent).
return self._renamed_contextMenuEvent(event)
def _renamed_contextMenuEvent(self, event):
if _DEBUG3:
print "begin _renamed_contextMenuEvent"
# See TreeWidget.selection_click() call from TreeWidget.menuReq(), in the Qt 3 code...
# but that's done by our caller, not us. We're no longer called directly from Qt, only from other methods here.
# [bruce 070509]
if hasattr(self, 'get_scrollpos'): #kluge, varies by subclass [bruce 070529]
self.get_scrollpos("start of _renamed_contextMenuEvent")###k see if this is more correct than the one we get later...
# not sure, since querying it may have had the effect of fixing the bug of it changing later! not sure yet...
event.accept() ##k #bruce 070511, see if this fixes scroll to top for these events --
# note, event is probably a mouse press, not a cmenu event per se
nodeset = self.topmost_selected_nodes( whole_nodes_only = False)
nodeset_whole = self.topmost_selected_nodes( whole_nodes_only = True)
# note: nodeset_whole (with whole_nodes_only = True) is part of
# fixing bug 2948, along with code to use it when certain cmenu
# commands are run. REVIEW: it is not used for all cmenu commands,
# since for some of them it might be suboptimal UI design
# (e.g. Hide/Unhide).
if 0:
if len(nodeset_whole) != len(nodeset):
print "len(nodeset_whole) = %d, len(nodeset) = %d" % (len(nodeset_whole) , len(nodeset)) ###
assert len(nodeset_whole) < len(nodeset)
pass
###TODO: we should consolidate the several checks for the optflag condition into one place, maybe mousePressEvent.
optflag = (((self.mouse_press_buttons & Qt.MidButton) or
(self.mouse_press_modifiers & Qt.AltModifier)) and 'Option' or None)
cmenu_spec = self.treemodel.make_cmenuspec_for_set(nodeset, nodeset_whole, optflag)
menu = makemenu_helper(self, cmenu_spec)
#bruce 070514 fix bug 2374 and probably others by using makemenu_helper
menu.exec_(event.globalPos())
if _DEBUG3:
print "end _renamed_contextMenuEvent"
return
# ==
# Note: if we ever want our own keyPressEvent or keyReleaseEvent bindings, see the code and comments
# in TreeWidget.keyPressEvent about doing this correctly, and for how Qt3 did the arrow key actions.
# We will need the filter_key call it does (or an equivalent use of wrap_key_event as done in GLPane)
# or NE1 will have a Mac-specific delete key bug whenever the MT has the focus. This does not happen now
# since MWsemantics handles our key presses, and it passes them to GLPane, which has the bugfix for that.
# See also the comments in filter_key(). [bruce 070517 comment]
# ==
def get_scrollpos(self, msg = ""):
"""
Return the current scrollposition (as x,y, in scrollbar units), and if _DEBUG3 also print it using msg.
"""
## res = ( self.horizontalOffset(), self.verticalOffset() )
# This is in pixels, and it apparently works, but it's not useful
# because setting it (using QWidget.scroll) doesn't work properly and has bad side effects.
# So, get it in "scrollbar units" instead, and set it by talking directly to the scrollbars.
hsb = self.horizontalScrollBar()
x = hsb and hsb.value() or 0
vsb = self.verticalScrollBar()
y = vsb and vsb.value() or 0
res = x,y
if _DEBUG3:
if msg:
msg = " (%s)" % (msg,)
print "get_scrollpos%s returns %r" % (msg, res,)
return res
def set_scrollpos(self, pos): # used only in QTreeView implem, but should be correct in QScrollArea implem too
"""
Set the scrollposition (as x,y, in scrollbar units), and if _DEBUG3 print various warnings if anything looks funny.
"""
x, y = pos # this is in scrollbar units, not necessarily pixels
hsb = self.horizontalScrollBar()
if hsb:
hsb.setValue(x) # even if x is 0, since we don't know if the current value is 0
else:
if x and _DEBUG3:
print "warning: can't set scrollpos x = %r since no horizontalScrollBar" % (x,)
vsb = self.verticalScrollBar()
if vsb:
vsb.setValue(y)
else:
if y and _DEBUG3:
print "warning: can't set scrollpos y = %r since no verticalScrollBar" % (y,)
pos1 = self.get_scrollpos("verifying set_scrollpos")
if pos != pos1:
if _DEBUG3:
print "warning: tried to set scrollpos to %r, but it's now %r" % (pos,pos1)
return
def rename_node_using_dialog(self, node): #bruce 070531
"""
[newly in public API -- ###doc that. Used by callers in more than one file.]
Put up a dialog to let the user rename the given node. (Only one node for now.)
Emit an appropriate statusbar message, and do necessary updates if successful.
@see: Node.rename_using_dialog()
"""
node.rename_using_dialog()
return
pass # end of class ModelTreeGui_common
# ==
# newer version of model tree gui which doesn't use QTreeView [bruce 070529] (older one is removed now)
MT_CONTENT_WIDTH = 500 # fixed content width for now
OPENCLOSE_AREA_WIDTH = 20
INDENT_OFFSET = 20
INDENT_0 = 20
MT_CONTENT_TOP_Y = 0
def x_for_indent(n):
return INDENT_0 + INDENT_OFFSET * n
class MT_View(QtGui.QWidget):
"""
contents view for ModelTreeGui
"""
def __init__(self, parent, palette_widget, modeltreegui):
QtGui.QWidget.__init__(self, parent)
self.palette_widget = palette_widget #e rename?
self.modeltreegui = modeltreegui
self.treemodel = self.modeltreegui.treemodel ###KLUGE? not sure. consider passing this directly?
self.get_icons()
return
def mt_update(self):
self.modeltreegui.mt_update()
def get_icons(self):
# note: geticon calls QIcon, but painter has no drawIcon, and drawPixmap doesn't accept them,
# so here we use getpixmap which calls QPixmap. We could also try QImage and painter.drawImage
# (known to work for crate.bmp and other test images, but presumably slower).
## painter.drawImage(QtCore.QPoint(0, 0), self.image)
if 0:
# these are the pixmaps meant for groupbox buttons on the Mac; they're workable here:
self.mac_collapsed = getpixmap("ui/modeltree/mac_collapsed_icon.png") # 16 x 15, centering looks best
self.mac_expanded = getpixmap("ui/modeltree/mac_expanded_icon.png") # 16 x 8 (.width() x .height()), centering looks best
# (The Windows groupbox icons, win_expand_icon.png and win_collapse_icon.png, are not useful in an MT.)
## print "size:", self.mac_expanded.width(), self.mac_expanded.height(), # size 16 8
# As of 070530 9pm the following are renamed copies of the Mac groupbox icons above,
# and are the same on Mac and Windows, but we should replace them with imitations of
# the standard ones for those platforms.
# We load them all here, since a debug_pref can switch between Mac and Win styles at runtime.
# The comments describe their conventional appearance (NIM for Win style) and its interpretation.
self.mac_collapsed = getpixmap("ui/modeltree/mac_collapsed_mtnode.png") # triangle pointing right (indicates "collapsed")
self.mac_expanded = getpixmap("ui/modeltree/mac_expanded_mtnode.png") # triangle pointing down (indicates "expanded")
self.win_collapsed = getpixmap("ui/modeltree/win_collapsed_mtnode.png") # plus in a box (indicates "expand action")
self.win_expanded = getpixmap("ui/modeltree/win_expanded_mtnode.png") # minus in a box (indicates "collapse action")
### TODO: also get content indicator icons here, ie yellow ghost @@@@
# Default MT style depends on platform, but user can change it at runtime
# to the same set of possibilities on all platforms. For now this uses debug_prefs.
if sys.platform == 'darwin':
# Macintosh
self._icon_style_choice = Choice(['mac', 'win'])
self._openclose_lines_choice = Choice_boolean_False
else:
# Windows or Linux
self._icon_style_choice = Choice(['win', 'mac'])
self._openclose_lines_choice = Choice_boolean_True
return
def _setup_openclose_style(self):
"""
[private]
As an optimization, choose the openclose icons (etc) just once before drawing.
"""
style = debug_pref("Model Tree: openclose icon style", self._icon_style_choice,
non_debug = True, prefs_key = "A9/MT openclose icon style",
call_with_new_value = (lambda val: self.mt_update()) )
if style == 'mac':
self.collapsed_mtnode_icon = self.mac_collapsed
self.expanded_mtnode_icon = self.mac_expanded
else:
self.collapsed_mtnode_icon = self.win_collapsed
self.expanded_mtnode_icon = self.win_expanded
self.draw_openclose_lines = debug_pref("Model Tree: openclose lines", self._openclose_lines_choice,
non_debug = True, prefs_key = "A9/MT openclose lines",
call_with_new_value = (lambda val: self.mt_update()) )
return
def sizeHint(self):
# Note: this probably has no effect, since it's overridden by a resize in every mt_update.
return QtCore.QSize(MT_CONTENT_WIDTH, 700)
_painted = None # not {}, so not mutable; after first paintEvent will be a
# dictionary, which maps node to (x, y) for whatever nodes were painted
# during the last full repaint [bruce 080507]
def paintEvent(self, event):
# Note: if this paintEvent was in QAbstractScrollArea, Qt doc for that warns:
# Note: If you open a painter, make sure to open it on the viewport().
# But, it's not in that (or its subclass QScrollArea), it's in the widget we're setting in that.
# Note: we're painting using contents coords, not viewport coords (and this is working, as expected).
# Question: would this change cliprect?
## painter.setViewport(0, 0, self.width(), self.height())
if self.modeltreegui.MT_debug_prints():
print 'paint' # note: this worked once we called update (it didn't require sizeHint to be defined)
self._setup_full_repaint_variables()
# needed before _paintnode can use us as its option_holder,
# and for other reasons
painter = QtGui.QPainter()
painter.begin(self)
try:
topnodes = self.treemodel.get_topnodes()
x, y = x_for_indent(0), MT_CONTENT_TOP_Y
for node in topnodes:
y = self.paint_subtree(node, painter, x, y)
pass
finally:
painter.end()
return
def _setup_full_repaint_variables(self): #bruce 080507 split this out, extended it
self._setup_openclose_style()
# todo: optim: implem this: self._setup_prefs(),
# so _paintnode needn't repeatedly test the same debug_prefs for each node
self._f_nodes_to_highlight = self.treemodel.get_nodes_to_highlight()
# a dictionary from node to an arbitrary value;
# in future, could store highlight color, etc
self._painted = {} # modified in paint_subtree when we call _paintnode
return
def paint_subtree(self, node, painter, x, y, line_to_pos = None, last_child = True):
"""
Paint node and its visible subtree (at x,y in painter);
return the y value to use for the next lower node.
If this is a child node, the y position to which an "openclose line"
(in case we're drawing them) needs to be drawn up to (from the center
of our openclose icon) is passed in line_to_pos as an int; otherwise
line_to_pos is None. Also, if last_child is False, we draw the openclose
line (if we're drawing them) a bit lower down as well, so we can draw it
before our openclose icon so as not to obscure it. Warning: those optional
args are sometimes passed positionally.
"""
openable = node.openable()
open = node.open and openable
if open:
children = node.MT_kids() #bruce 080306 use MT_kids
else:
children = ()
# openclose line
draw_openclose_lines = self.draw_openclose_lines
next_line_to_pos = y + ITEM_HEIGHT # easiest to do this all the time
if draw_openclose_lines:
# draw them first (including the start of one going down, if needed), so they won't obscure icons.
# In this section we draw the ones that go through (under) the center of our own openclose icon.
doanything = (line_to_pos is not None) or children
if doanything:
# compute openclose area center:
lx1 = x - OPENCLOSE_AREA_WIDTH / 2
ly1 = y + ITEM_HEIGHT / 2
painter.save() # otherwise we mess up the node text color -- I guess _paintnode is not self-contained re that
painter.setPen(QColor(Qt.gray)) # width 0, solid line
if line_to_pos is not None:
# vertical line
if last_child:
painter.drawLine(lx1, line_to_pos, lx1, ly1 )
else:
painter.drawLine(lx1, line_to_pos, lx1, y + ITEM_HEIGHT ) # this goes a bit lower down;
# the knowledge of how much lower down is also known to the caller
# (i.e. this recursive function, in children loop below)
# horizontal line
painter.drawLine(lx1, ly1, x + _ICONSIZE[0]/2, ly1)
if children:
painter.drawLine(lx1 + INDENT_OFFSET, ly1,
lx1 + INDENT_OFFSET, next_line_to_pos)
if doanything:
painter.restore()
# node type icon and node name text (possibly looking selected and/or disabled)
_paintnode(node, painter, x, y, self.palette_widget, option_holder = self)
self._painted[node] = (x, y)
# openclose decoration -- uses style set up by _setup_openclose_style for Mac or Win
if openable:
if open:
pixmap = self.expanded_mtnode_icon
else:
pixmap = self.collapsed_mtnode_icon
w = pixmap.width()
h = pixmap.height()
painter.drawPixmap(x - (OPENCLOSE_AREA_WIDTH + w)/2, y + (ITEM_HEIGHT - h)/2, pixmap)
# this adjusts posn for pixmap size, to center the pixmap
pass
y += ITEM_HEIGHT
if open:
x += INDENT_OFFSET
for child in children:
its_last_child = (child is children[-1]) # wrong if children can occur twice
y0 = y
y = self.paint_subtree(child, painter, x, y, next_line_to_pos, its_last_child)
# following only matters if not its_last_child
next_line_to_pos = y0 + ITEM_HEIGHT
return y
def any_of_these_nodes_are_painted(self, nodes): #bruce 080507, for cross-highlighting
"""
@return: whether any of the given nodes were painted during the last
full repaint of self.
@rtype: boolean
"""
if not self._painted:
# called too early; not an error
return False
for node in nodes:
where = self._painted.get(node) # (x, y) or None
if where is not None:
return True
continue
return False
def look_for_y(self, y):
"""
Given y (in contents coordinates), find the node drawn under it,
and return (node, its depth, its y0).
If no node is under it, return None, None, None.
"""
y0 = MT_CONTENT_TOP_Y
d = 0 # indent level
if y < y0:
return None, None, None
for child in self.treemodel.get_topnodes():
resnode, resdepth, resy0, y0 = self.look_for_y_recursive( child, y0, d, y)
if resnode:
return resnode, resdepth, resy0
return None, None, None
def look_for_y_recursive(self, node, y0, d, y):
"""
assuming node is drawn at vertical position y0 (in contents coordinates)
and indent level d, find the node in its visible subtree (perhaps node itself)
which is drawn over position y; return (that node, its depth, its y0, None), or (None, None, None, next_y0),
where next_y0 is the y coordinate for the next node below the given node and its visible subtree.
Assume without checking that y >= y0.
"""
y0 += ITEM_HEIGHT
if y < y0:
return node, d, y0 - ITEM_HEIGHT, None
if node.open and node.openable():
d += 1
for child in node.MT_kids(): #bruce 080108 change for Block: use MT_kids
resnode, resdepth, resy0, y0 = self.look_for_y_recursive( child, y0, d, y)
if resnode:
return resnode, resdepth, resy0, y0
return (None, None, None, y0)
def statusbar_message(self, text): #bruce 070531; still used?
self.modeltreegui.statusbar_message(text)
return
pass # end of class MT_View
# ===
class FakeItem:
def __init__(self, node):
self.node = node
def height(self):
return ITEM_HEIGHT
pass
class ModelTreeGui(QScrollArea, ModelTreeGui_common):
"""
The GUI part of the NE1 model tree widget.
"""
# REVIEW: rename class and module to ModelTreeGUI?
# (class is now ending Gui not GUI; module is now lowercase at start)
# [bruce 081216 question]
#
#bruce 070529-30 rewrite of some of [now-removed] class ModelTreeGui_QTreeView
def __init__(self, win, name, treemodel, parent = None):
## print "what are these args?", win, name, treemodel, parent
# win = <MWsemantics.MWsemantics object at 0x4ce8a08>
# name = modelTreeView
# treemodel = <modelTree.TreeModel.TreeModel instance at 0x4cfb3a0>
# parent = <PyQt4.QtGui.QWidget object at 0x4cff468>
del name
QScrollArea.__init__(self, parent)
###e setWidgetResizable ? (default False - honors size of widget - done when fitToWindow checked, in the imageviewer example)
# adjustSize? (called when *not* fitToWindow -- more like our case... i don't fully understand it from docs)
# updateGeometry? (call when sizeHint changed)
## self.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
self.setContextMenuPolicy(Qt.PreventContextMenu) #bruce 070509 change; I hope it will prevent direct calls of contextMenuEvent
# this has to be done after QScrollArea.__init__, since it assumes QWidget init has occurred
ModelTreeGui_common.__init__(self, win, treemodel) ## mouse and DND methods -- better off in view widget or here??
# will this intercept events meant for the scrollbars themselves??? need to use the contents event methods?
self.view = MT_View( self, self, self) # args are: parent, palette_widget, modeltreegui
self.setWidget(self.view)
# Model Tree background color. Mark 2007-06-04
mtColor = RGBf_to_QColor(env.prefs[mtColor_prefs_key])
self.setPalette(getPalette(None, QPalette.Window, mtColor))
#e not sure if mt_update would be safe at this point (were cooperating objects fully initialized?)
## self._debug_scrollbars("init") # they have arbitrary-looking values at this point, later corrected, evidently
return
def _scrollbars(self):
hsb = self.horizontalScrollBar()
vsb = self.verticalScrollBar()
return hsb, vsb
def _debug_scrollbars(self, when): # not normally called except when debugging
print "debug_scrollbars (%s)" % when
hsb, vsb = self._scrollbars() # they are always there, even when not shown, it seems
## if hsb:
## print "hsb pageStep = %r, singleStep = %r, minimum = %r, maximum = %r" % \
## (hsb.pageStep(), hsb.singleStep(), hsb.minimum(), hsb.maximum())
if vsb:
print "vsb pageStep = %r, singleStep = %r, minimum = %r, maximum = %r" % \
(vsb.pageStep(), vsb.singleStep(), vsb.minimum(), vsb.maximum())
return
def nodeItem(self, node):
return FakeItem(node)
def mt_update(self):
"""
part of the public API:
- recompute desired size for scroll area based on visible nodes
- resize scroll area if needed
- _do_widget_updates to make sure we get redrawn soon
"""
if self.MT_debug_prints():
print "mt_update", time.asctime()
# probably we need to scan the nodes and decide what needs remaking
# (on next paintevent) and how tall it is; should we do this in MT_View? yes.
self.__count = 0
def func(node):
self.__count += 1 # using a local var doesn't work, due to Python scoping
self.treemodel.recurseOnNodes(func, visible_only = True)
NUMBER_OF_BLANK_ITEMS_AT_BOTTOM = 1
# not 0, to let user be certain they are at the end
# [bruce 080306 new feature]
self.__count += NUMBER_OF_BLANK_ITEMS_AT_BOTTOM
height = self.__count * ITEM_HEIGHT
if self.MT_debug_prints():
print "mt_update: total height", height
## self._debug_scrollbars("mt_update pre-resize")
self.view.resize(MT_CONTENT_WIDTH, height)
#e updateGeometry? guess: this does that itself. I don't know for sure,
# but the scrollbars do seem to adjust properly.
## self._debug_scrollbars("mt_update post-resize")
hsb, vsb = self._scrollbars()
if vsb:
vsb.setSingleStep( ITEM_HEIGHT )
vsb.setPageStep( vsb.pageStep() / ITEM_HEIGHT * ITEM_HEIGHT )
#k Note: It might be enough to do setSingleStep once during init, since the value seems to stick --
# but the page step is being quantized, so that has to be redone every time.
# NFR: I don't know how to set a "motion quantum" which affects user-set positions too.
## self._debug_scrollbars("mt_update post-correct")
self._do_widget_updates()
## self._debug_scrollbars("mt_update post-update")
return
def _do_widget_updates(self): #bruce 080507 split this out
"""
[private]
Call QWidget.update on our widgets, so that Qt will redraw us soon
(which it will do by calling paintEvent in our MT_View, self.view)
"""
self.view.update() # this works
self.update() # this alone doesn't update the contents, but do it anyway
# to be sure we get the scrollbars (will it be enough?)
return
def paint_item(self, painter, item): # probably only used for DND drag graphic (in superclass)
x,y = 0,0
node = item.node
_paintnode(node, painter, x, y,
self.view, # self.view is a widget used for its palette
option_holder = None # could be self.view,
# but only if we told it to _setup_full_repaint_variables
)
width = 160 ###k guess; should compute in paint and return, or in an aux subr if Qt would not like that
return width
def repaint_some_nodes(self, nodes): #bruce 080507, for cross-highlighting
"""
For each node in nodes, repaint that node, if it was painted the last
time we repainted self as a whole. (Not an error if it wasn't.)
"""
# we can't do it this way (using a hypothetical method,
# not yet implemented in class MT_View), since we're not
# inside paintEvent:
## self.view.repaint_some_nodes(nodes)
if self.view.any_of_these_nodes_are_painted(nodes):
self._do_widget_updates() # also called by mt_update
return
def item_and_rect_at_event_pos(self, event):
"""
Given a mouse event, return the item under it (or None if no item),
and a QRect encompassing certain(?) parts of it (or None if no item).
### which parts?
### what coords?
"""
pos = event.pos()
x, y = pos.x(), pos.y()
## print "viewport pos x = %r, y = %r" % (x,y)
dx, dy = self.get_scrollpos("item_and_rect_at_event_pos") # in pixels (will that remain true if we scroll by items?)
cx = x + dx
cy = y + dy
# do item hit test in contents (inner) coords cx, cy, but return item's rect in viewport (outer) coords x, y.
# Note: in variable names for x or y coords, we use 'c' to mean "contents coords" (otherwise viewport),
# and suffix '0' to mean "coordinate of item reference point (top left of type icon)" (otherwise of mouse event).
node, depth, cy0 = self.view.look_for_y( cy)
if node:
item = self.nodeItem(node)
if 1:
cx0 = x_for_indent(depth)
# Note: this is correct if the rect is supposed to be including the type icon -- is it? I think so.
# (This affects whether clicks on type icon can select the node. I think it's good if they can.)
x0 = cx0 - dx
y0 = cy0 - dy
w = MT_CONTENT_WIDTH #STUB, but good enough for now --
# maybe better than being correct re clicks to right of text?? not sure.
# To make it correct, could use the code that makes a temporary QLineEdit, if slow is ok (I think it is)...
# Wait, that code is being used on exactly this value in our caller, so what we set here doesn't matter!
h = ITEM_HEIGHT
rect = QRect( x0, y0, w, h) # viewport coords
return item, rect
else:
return None, None
pass
def set_scrollpos(self, pos):
assert 0, "don't use set_scrollpos in this QScrollArea-using subclass, without thinking twice!"
def mouseDoubleClickEvent(self, event):
self.mousePressEvent(event, _doubleclick = True) # this calls the following method in self (sometimes)
def handle_doubleclick(self, event, item, rect):
# print "handle_doubleclick" # this gets called when expected
# temporary kluge, 070531, to be released for A9: use a dialog.
# (Later we'll try using an in-place QLineEdit; some stub code for that is elsewhere in this file.)
node = item.node
self.rename_node_using_dialog( node) # note: this checks node.rename_enabled() first
return
pass # end of class ModelTreeGui
# bugs in new class ModelTreeGui based on QScrollArea [070531 2pm PT]:
#
# - mouse events:
# openclose - works now
# selection - some works, rest not tested
# cmenus - some work, except bug [fixed now] in selection update when menu is shown, i.e.
# it fails to do click select behavior in visible way, when putting up menu, tho it probably does it internally
# [fixed, tho update is too slow -- incremental redrawing of changed items (when only selection changes) would be better]
# DND - seems to work; not fully tested
# renaming - in place is NIM; using dialog works now
# key events: arrow keys should move the selectedness up and down in the nodes, but now they move the scrollbar.
#
# - drawing:
# - decoration icons need improvement
# - bg color is wrong (or, need transparent icons)
# - it's missing the header that says "model tree" -- we decided that's a feature, not a bug
# - too slow
# - set painter state less often? (esp for text)
# - profile it?
# - see if text or icons are taking the time
# - is icon caching helping?
# - make an image to keep it in, so it scrolls faster?
# Maybe enough to just draw only in inval rect.
#
# - other:
# - hsb always there, fixed content width
# - rename_enabled ignored -- probably fixed
# - maybe so are some properties about DND being permitted (not sure)
#
# - highly desired NFRs for A10:
# - cross-highlighting with GLPane
# - DND:
# - autoscrolling during DND
# - drop on group puts node before other members [done, in another file, for NE1 v1.0.0, bruce 080414]
# - drop-point highlighting, between nodes
# end
| NanoCAD-master | cad/src/modelTree/modelTreeGui.py |
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
ModelTree.py -- owner and external interface to the NE1 model tree
(which is implemented as several objects by the modules in this
modelTree package)
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
History:
modelTree.py was originally written by some combination of
Huaicai, Josh, and Mark. Bruce (Jan 2005) reorganized its interface with
Node and Group and their subclasses (Utility.py and other modules)
and rewrote a lot of the model-tree code (mainly to fix bugs),
and split it into three modules:
- TreeView.py (display and update),
- TreeWidget.py (event handling, and some conventions suitable for
all our tree widgets, if we define other ones), and
- modelTree.py (customized for showing "the NE1 model tree" per se).
After that, Will ported it to Qt4, and since the Q3 compatibility
classes were unsupported by PyQt4, rewrote much of it, in the process
replacing TreeView.py and TreeWidget.py by a new file, modelTreeGui.py,
and adding a standalone prototype file modelTreePrototype.py (functional
as a separate test program, but not used by NE1). The current organization
might therefore be:
- modelTreeGui.py (display and update, event handling, and some
conventions suitable for all our tree widgets, if we define other ones), and
- modelTree.py (customized for showing "the NE1 model tree" per se).
Bruce later rewrote much of modelTreeGui.py, and has added lots
of context menu commands to modelTree.py at various times.
Bruce 081216 is doing some cleanup and refactoring, including splitting
ModelTree and TreeModel into separate objects with separate classes and
_api classes, and splitting some code into separate files.
"""
from PyQt4 import QtCore
from modelTree.modelTreeGui import ModelTreeGui
from modelTree.TreeModel import TreeModel
# ===
class ModelTree(object):
"""
NE1's main model tree, serving as public owner of the model tree widget
(self.modelTreeGui, class ModelTreeGui) and private owner of the tree
model shown by that (class TreeModel).
@note: ModelTree is a public class name, and self.modelTreeGui
is a public member, accessed by MWsemantics (or a subobject)
for use in building the Qt widget layout. For public access
purposes it can be considered "the Qt widget containing the model
tree".
"""
def __init__(self, parent, win, name = "modelTreeView", size = (200, 560)):
"""
#doc
"""
self._treemodel = TreeModel(self, win)
self.modelTreeGui = ModelTreeGui(win, name, self._treemodel, parent)
# public member; review: maybe it ought to have a special name
# (or get-method) just for its public purpose, so this attr could
# be made private for internal use
self.mt_update()
return
def mt_update(self):
return self.modelTreeGui.mt_update()
def repaint_some_nodes(self, nodes): #bruce 080507, for cross-highlighting
"""
For each node in nodes, repaint that node, if it was painted the last
time we repainted self as a whole. (Not an error if it wasn't.)
"""
self.modelTreeGui.repaint_some_nodes(nodes)
return
def setMinimumSize(self, h, w):
return self.modelTreeGui.setMinimumSize(h, w)
def setMaximumWidth(self, w): #k might not be needed
return self.modelTreeGui.setMaximumWidth(w)
def setColumnWidth(self, column, w):
return self.modelTreeGui.setColumnWidth(column, w)
def setGeometry(self, w, h): #k might not be needed
return self.modelTreeGui.setGeometry(QtCore.QRect(0,0,w,h))
pass # end of class ModelTree
# end
| NanoCAD-master | cad/src/modelTree/ModelTree.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
Node_api.py - API of Nodes, as assumed by modelTree code
Note: not used (so far, 081216) except as documentation and in test code;
probably not complete
@author: Will, Bruce
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
from modelTree.Api import Api
class Node_api(Api):
# REVIEW: maybe refile this into model/Node_API and inherit from Node??
# [bruce 080107 comment]
# Or, rename it to reflect its specific purpose (for ModelTreeGUI),
# then inherit from it (not sure in which package to put it in that case).
# [bruce 081217 update]
"""
The client of ModelTreeGUI must provide a node type that meets this API.
Note that this is not the Node API for use by most of NE1, or even
by TreeModel -- just for
use specifically by ModelTreeGUI for nodes returned by its treemodel.
Providing a node type can be done by extending this class, or implementing
it yourself.
@see: class Node in Utility.py, used as the superclass for NE1 model tree
nodes, which defines an API which is (we hope) a superset of this one.
It could in principle inherit from this class, and at least ought to
define all its methods.
@note: this class is not used (so far, 081216) except as documentation
and in test code.
"""
# Questions & comments about this API [bruce 070503, 070508] [updated 081217]:
#
# - it ought to include (and the code herein make use of) node.try_rename or so.
#
# - is Node.__init__ part of the API, or just a convenience place for a
# docstring about required instance variables?
# - in Qt3 there *is* a Node API call to support renaming ("try_rename"
# or so). Why isn't it used or listed here?
# New proposed policy relating open, openable, MT_kids, members
# (see also their docstrings herein, revised when this comment was added):
#
# - if node.openable(), then regardless of node.open,
# node.MT_kids() value is meaningful, and doesn't depend on node.open.
# It's the sequence of child nodes to display under node when node is
# open. It will also be used to find picked nodes under node, even when
# node is not open, for the purpose of making MT operations safe when
# some picked nodes only occur inside non-openable unpicked nodes.
#
# - if not node.openable(), then regardless of node.open, node.MT_kids()
# should never be called (but see new docstring re what it should do
# if it's called then anyway).
#
# - some MT operations (defined in TreeMember.py) still use node.members
# (e.g. Group and Ungroup). This needs review whenever MT_kids can be
# anything other than .members for an openable node.
#
# Status: need to review defs of MT_kids and openable for this.
# Then need to implement this policy throughout modelTree and Node classes.
# Short term motivation is fixing bug 2948.
#
# [bruce 081217]
# see MT_kids and __init__ docstrings for documentation of open and members
open = False
members = ()
def __init__(self):
"""
self.name MUST be a string instance variable.
self.hidden MUST be a boolean instance variable.
self.open MUST be a boolean instance variable.
self.members is not part of this API since ModelTreeGUI doesn't
care about it; however, current implem of TreeModel (its client)
*does* care about it.
There is no API requirement about arguments for __init__.
"""
raise Exception("overload me")
def pick(self):
"""
select the object
[extended in many subclasses, notably in Group]
[Note: only Node methods should directly alter self.picked,
since in the future these methods will sometimes invalidate other state
which needs to depend on which Nodes are picked.]
"""
raise Exception("overload me")
def ModelTree_plain_left_click(self): #bruce 080213 addition to Node API
"""
Do desired extra side effects (if any) from a plain, direct left click
in a model tree widget (after the usual effect of self.pick, which can
also happen in several other ways).
"""
pass
def unpick(self):
"""
unselect the object, and all its ancestor nodes.
[extended in many subclasses, notably in Group]
[Note: only Node methods should directly alter self.picked,
since in the future these methods will sometimes invalidate other state
which needs to depend on which Nodes are picked.]
"""
raise Exception("overload me")
def apply2picked(self, func):
"""
Apply fn to the topmost picked nodes under (or equal to) self,
but don't scan below picked nodes. See Group.apply2picked docstring for details.
"""
raise Exception("overload me")
def is_disabled(self):
"""
MUST return a boolean
"""
raise Exception("overload me")
def node_icon(self, display_prefs):
"""
MUST return either a QPixmap or None
"""
# old comment, not recently reviewed as of 081217:
# display_prefs is used in Group.node_icon to indicate whether a group is open or closed. It
# is not used anywhere else. It is a dictionary and the only relevant key for it is "open".
# [Addendum, bruce 070504: it also has a key 'openable'. I don't know if anything looks at
# its value at that key, but "not open but openable" vs "not open and not even openable"
# is a meaningful difference. The value of 'openable' is usually (so far, always)
# implicit in the Node's concrete subclass, so typical methods won't need to look at it.]
raise Exception("overload me")
def MT_kids(self, item_prefs = {}):
"""
When self is openable, return a list of Nodes that the model tree
should show as children of self, whenever self is openable and open.
(The return value should not depend on whether self is open.)
When self is not openable, it doesn't matter what this returns,
but it should either be safe to call then, or should assert
that self is openable (so as to raise an understandable exception).
@note: self is open whenever self.open is true, and is openable
whenever self.openable() is true.
@see: self.members
"""
#bruce 080108 renamed kids -> MT_kids, revised semantics;
# note that so far this is not yet used in all necessary places
#bruce 081217 revised semantics again
raise Exception("overload me")
def openable(self): #bruce 070508
"""
Return True if tree widgets should display an openclose icon
for self, False otherwise.
When this returns true, the openclose icon must always be usable
to indicate and change self.open, and when self.open, self's .MT_kids()
must be displayed under self.
When this returns false, no children should be displayed under self,
regardless of self.open and of the return value of self.MT_kids().
@note: specific nodes are permitted to change this method's return
value over time, e.g. depending on user preference settings.
They must ensure that, at any given time, all required
constraints on its value vs. the use of self.MT_kids() are
followed. For such changes to take effect, modelTree.mt_update()
will generally need to be called; the modelTree code must
ensure that mt_update is sufficient for that purpose.
@note: even when openable returns false, self.open is permitted
to be true, but self is still considered to be closed then.
"""
raise Exception("overload me")
pass
# end
| NanoCAD-master | cad/src/modelTree/Node_api.py |
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
mt_statistics.py - count types of nodes, when making MT context menu commands
@author: Bruce
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
History:
Bruce wrote these long ago within the model tree code
Bruce 081216 split this out of ModelTree.py
"""
from model.chunk import Chunk
from model.jigs import Jig
from foundation.Group import Group
class all_attrs_act_as_counters: #bruce 081216 renamed from statsclass
# todo: rename, and move to its own utility module?
"""
class for holding and totalling counts of whatever you want, in named attributes
"""
def __getattr__(self, attr): # in class all_attrs_act_as_counters
if not attr.startswith('_'):
return 0 # no need to set it
raise AttributeError, attr
def __iadd__(self, other):
"""
this implements self += other for objects of this class,
which adds corresponding counter-attributes separately
"""
for attr in other.__dict__.keys():
setattr( self, attr, getattr( self, attr) + getattr( other, attr) )
return self ###k why would this retval be needed??
# what could it mean in general for += to return something else?
# i don't know, but without it,
# the effect of allstats += somestats is apparently to set allstats to None!
# I need to check out the python doc for __iadd__. [bruce 050125]
def __str__(self): # mainly for debugging
res1 = ""
keys = self.__dict__.keys()
keys.sort()
for attr in keys:
if res1:
res1 += ", "
###k why was there a global here called res?? or was there? maybe exception got discarded.
res1 += "%s = %d" % (attr, getattr(self, attr))
return "<stats (%d attrs): %s>" % (len(keys), res1)
__repr__ = __str__ #k needed?
pass
def mt_accumulate_stats(node, stats): #bruce 081216 renamed from accumulate_stats
"""
When making a context menu from a nodeset (of "topselected nodes"),
this is run once on every topselected node (note: they are all picked)
and once on every node under those (whether or not they are picked).
"""
# todo (refactoring): could be a method on our own subclass of all_attrs_act_as_counters
stats.n += 1
stats.ngroups += int(isinstance(node, Group))
if (isinstance(node, Chunk)):
stats.nchunks += 1
# note: chunkHasOverlayText is only a hint, so it's possible
# this has false positives, even though it becomes accurate
# every time node is drawn. (If it's visible in MT but hidden
# in glpane, I think nothing will update it.) [bruce 090112 comment]
if (node.chunkHasOverlayText and not node.showOverlayText):
stats.canShowOverlayText += 1
if (node.chunkHasOverlayText and node.showOverlayText):
stats.canHideOverlayText += 1
stats.njigs += int(isinstance(node, Jig))
# maybe todo: also show counts of all other subclasses of Node?
stats.npicked += int(node.picked)
stats.nhidden += int(node.hidden)
stats.nopen += int(node.open)
return
# end
| NanoCAD-master | cad/src/modelTree/mt_statistics.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
Plugins.py - a collection of general plugin helper functions for the purpose of
checking and/or verifying that a plugin is enabled and that the path pointed
to by its pref_key is the plugin.
@version: $Id$
@copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details.
History:
mark 2007-12-01
- split out of qutemol.py
Module classification: [bruce 071215, 080104]
Contains ui, operations or utility, and io code.
For now, classified as code type of ui, somewhat arbitrarily,
but filed into "processes" package, since it's all about letting
the user maintain info needed to run external processes.
"""
import foundation.env as env
import os
from PyQt4.Qt import QMessageBox
from processes.Process import Process
def _dialogToOfferPluginPrefsFixup(caption, text):
"""
[private helper for _fixPluginProblem()]
Offer the user a chance to fix a plugin problem.
@param caption: The dialog border caption.
@type caption: text
@param text: The dialog text.
@type text: text
@return: 0 if they accept (after letting them try),
1 if they decline.
@rtype: int
"""
win = env.mainwindow()
ret = QMessageBox.warning(win, caption, text,
"&OK", "Cancel", "",
0, 1 )
if ret == 0: # User clicked "OK"
win.userPrefs.show(pagename = 'Plug-ins') # Show Preferences | Plug-in.
return 0 # let caller figure out whether user fixed the problem
elif ret == 1: # User clicked "Cancel"
return 1
pass
def _fixPluginProblem(plugin_name, errortext):
"""
[private helper for checkPluginPreferences()]
@param plugin_name: name of plug-in (i.e. "QuteMolX", "GROMACS", etc.)
@type plugin_name: text
"""
caption = "%s Problem" % plugin_name
text = "Error: %s.\n" % (errortext,) + \
" Select OK to fix this now in the Plugins page of\n" \
"the Preferences dialog and retry rendering, or Cancel."
return _dialogToOfferPluginPrefsFixup(caption, text)
def verifyExecutable(executable_path):
if (os.access(executable_path, os.F_OK)):
if (os.access(executable_path, os.X_OK)):
return None
return "%s exists, but is not executable" % executable_path
return "%s: file does not exist" % executable_path
def _checkPluginPreferences_0(plugin_name,
plugin_prefs_keys,
insure_executable):
"""
[private helper for checkPluginPreferences()]
Checks <plugin_name> to make sure it is enabled and
that its path points to a file.
@param plugin_name: name of plug-in (i.e. "QuteMolX", "GROMACS", etc.)
@type plugin_name: text
@param plugin_keys: list containing the plugin enable prefs key and the
path prefs key.
@type plugin_keys: List
@return: 0, plugin path on success, or
1, an error message indicating the problem.
@rtype: List
"""
plugin_enabled_prefs_key, plugin_path_prefs_key = plugin_prefs_keys
if env.prefs[plugin_enabled_prefs_key]:
plugin_path = env.prefs[plugin_path_prefs_key]
else:
return 1, "%s is not enabled" % plugin_name
if not plugin_path:
return 1, "%s plug-in executable path is empty" % plugin_name
# We'd like to allow arguments to an executable to be specified,
# but perhaps the executable path itself contains a space in it.
# So, we break the string at each space and check the first part.
# If any of those substrings exists, accept it. We start by
# checking the whole string.
executable_path = plugin_path
while (not os.path.exists(executable_path)):
last_space = executable_path.rfind(" ")
# some platform might report that the empty string file name
# exists, so we don't want to check for it.
if (last_space <= 0):
return 1, "%s executable not found at specified path %s" % (plugin_name, plugin_path)
executable_path = executable_path[0:last_space]
if (insure_executable):
message = verifyExecutable(executable_path)
if (message):
return 1, message
##e should check version of plugin, if we know how
return 0, plugin_path
def checkPluginPreferences(plugin_name,
plugin_prefs_keys,
ask_for_help = True,
extra_check = None,
insure_executable = False):
"""
Checks I{plugin_name} to make sure it is enabled and that its path points
to a file. I{ask_for_help} can be set to B{False} if the user shouldn't be
given a chance to fix the problem via the "Plugin" page in the Preferences
dialog.
Note: this should be refactored to use exceptions.
Returns :0, plugin path on success, or
1 and an error message indicating the problem.
@param plugin_name: name of plug-in (i.e. "QuteMolX", "GROMACS", etc.)
@type plugin_name: text
@param plugin_keys: list containing the plugin enable prefs key and the
path prefs key.
@type plugin_keys: List
@param ask_for_help: If True (default), give the user a chance to fix
problems via the "Plugin" page of the Preferences
dialog (i.e. enable the plugin and set the path to
its executable).
@type ask_for_help: bool
@param extra_check: If not None (default is None), is a routine to
perform extra validation checks on the plugin
path.
@type extra_check: Function which takes path as argument, and
returns either an error message, or None if all
is ok.
@return: 0, plugin path on success, or
1, an error message indicating the problem.
@rtype: List
"""
# Make sure the other prefs settings are correct; if not, maybe repeat
# until user fixes them or gives up.
while 1:
errorcode, errortext_or_path = \
_checkPluginPreferences_0(plugin_name,
plugin_prefs_keys,
insure_executable)
if (extra_check and not errorcode):
extra_message = extra_check(errortext_or_path)
if (extra_message):
errorcode = 1
errortext_or_path = extra_message
if errorcode:
if not ask_for_help:
return errorcode, errortext_or_path
ret = _fixPluginProblem(plugin_name, errortext_or_path)
if ret == 0: # Subroutine has shown Preferences | Plug-in.
continue # repeat the checks, to figure out whether user fixed
# the problem.
elif ret == 1: # User declined to try to fix it now
return errorcode, errortext_or_path
else:
return 0, errortext_or_path
pass # end of checkPluginPreferences
def verifyPluginUsingVersionFlag(plugin_path, version_flag, vstring):
"""
Verifies a plugin by running it with I{version_flag} as the only
command line argument and matching the output to I{vstring}.
@return: 0 if there is a match. Otherwise, returns 1
@rtype: int
@note: This is only useful if the plug-in supports a version flag arguments.
"""
if not plugin_path:
return 1
if not os.path.exists(plugin_path):
return 1
args = [version_flag]
arguments = []
for arg in args:
if arg != "":
arguments.append(arg)
p = Process()
p.start(plugin_path, arguments)
if not p.waitForFinished (10000): # Wait for 10000 milliseconds = 10 seconds
return 1
output = 'Not vstring'
output = str(p.readAllStandardOutput())
#print "output=", output
#print "vstring=", vstring
if output.find(vstring) == -1:
return 1
else:
return 0 # Match found.
| NanoCAD-master | cad/src/processes/Plugins.py |
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details.
"""
ServerManager.py - persistent db and UI for list of servers & current server.
Unclear whether or not this is GAMESS-specific.
[bruce 071217 guess at description]
@author: Huaicai
@version: $Id$
@copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details.
"""
from processes.ServerManagerDialog import Ui_ServerManagerDialog
from PyQt4.Qt import QDialog, QStringList, SIGNAL, QMessageBox
from simulation.SimServer import SimServer
import os
import cPickle as pickle
from utilities.debug import print_compact_stack
from utilities.qt4transition import qt4todo
from platform_dependent.PlatformDependent import find_or_make_Nanorex_directory
class ServerManager(QDialog, Ui_ServerManagerDialog):
"""
Persistent db and UI for list of servers & current server.
#doc more
The servers in our list are SimServer objects.
"""
serverFile = 'serverList'
tmpFilePath = find_or_make_Nanorex_directory()
serverFile = os.path.join(tmpFilePath, "JobManager", serverFile)
def __init__(self):
QDialog.__init__(self)
self.setupUi(self)
self.connect(self.new_btn,SIGNAL("clicked()"),self.addServer)
self.connect(self.exit_btn,SIGNAL("clicked()"),self.close)
self.connect(self.server_listview,SIGNAL("currentChanged(QListViewItem*)"),self.changeServer)
self.connect(self.engine_combox,SIGNAL("activated(const QString&)"),self.engineChanged)
self.connect(self.del_btn,SIGNAL("clicked()"),self.deleteServer)
qt4todo('self.server_listview.setSorting(-1)')
## The ordered server list
self.servers = self._loadServerList()
return
def showDialog(self, selectedServer = 0):
if not selectedServer:
selectedServer = self.servers[0]
self.setup(selectedServer)
self.exec_()
return
def _fillServerProperties(self, s):
"""Display current server properties"""
self.name_linedit.setText(s.hostname)
self.ipaddress_linedit.setText(s.ipaddress)
self.platform_combox.setCurrentText(s.platform)
self.method_combox.setCurrentText(s.method)
self.engine_combox.setCurrentText(s.engine)
self.program_linedit.setText(s.program)
self.username_linedit.setText(s.username)
self.password_linedit.setText(s.password)
return
def setup(self, selectedServer):
self.server_listview.clear()
self.items = []
servers = self.servers[:]
servers.reverse()
for s in servers:
item = QStringList()
item.append(s.server_id)
item.append(s.item)
self.server_listview.addItems(item)
#item = QListViewItem(self.server_listview, str(s.server_id), s.engine)
self.items += [item]
if s == selectedServer:
selectedItem = item
self.items.reverse()
self.server_listview.setCurrentIndex(selectedItem)
self._fillServerProperties(selectedServer)
return
def _applyChange(self):
"""Apply server property changes"""
s = {'hostname':str(self.name_linedit.text()),
'ipaddress':str(self.ipaddress_linedit.text()),
'platform':str(self.platform_combox.currentText()),
'method':str(self.method_combox.currentText()),
'engine':str(self.engine_combox.currentText()),
'program': str(self.program_linedit.text()),
'username':str(self.username_linedit.text()),
'password':str(self.password_linedit.text())}
item = self.server_listview.currentIndex()
item.setText(1, s['engine'])
self.servers[self.items.index(item)].set_parms(s)
return
def engineChanged(self, newItem):
item = self.server_listview.currentIndex()
sevr = self.servers[self.items.index(item)]
sevr.engine = str(newItem)
item.setText(1, sevr.engine)
return
def addServer(self):
"""Add a new server. """
server = SimServer()
self.servers[:0] = [server]
self.setup(server)
return
def deleteServer(self):
"""Delete a server. """
if len(self.servers) == 1:
msg = "At least 1 server must exist. After deleting the last one, "\
"a default new server will be created."
QMessageBox.information(self,
"Deleting a server",
msg,
QMessageBox.Ok )
item = self.server_listview.currentIndex()
self.server_listview.takeItem(item)
del self.servers[self.items.index(item)]
self.items.remove(item)
print "After deleting."
return
def changeServer(self, curItem):
"""Select a different server to display"""
#print "curItem: ", curItem
#print "servers: ", self.servers
self._fillServerProperties(self.servers[self.items.index(curItem)])
return
def closeEvent(self, event):
"""
This is the closeEvent handler, it's called when press 'X' button
on the title bar or 'Esc' key or 'Exit' button in the dialog
"""
try:
self._applyChange()
self._saveServerList()
except:
print_compact_stack("Sim-server pickle exception.")
self.accept()
self.accept()
return
def getServer(self, indx):
"""
Return the server for <indx>, the index of the server in
the server list.
"""
#self._applyChange()
assert type(indx) == type(1)
assert indx in range(len(self.servers))
return self.servers[indx]
def getServerById(self, ids):
"""Return the server with the server_id = ids """
#self._applyChange()
for s in self.servers:
if s.server_id == ids:
return s
return None
def getServers(self):
"""Return the list of servers."""
#self._applyChange()
return self.servers
def _loadServerList(self):
"""Return the list of servers available, otherwise, create a default one. """
if os.path.isfile(self.serverFile):
try:
file = open(self.serverFile, "rb")
return pickle.load(file)
except:
print_compact_stack("Unpickle exception.")
return [SimServer()]
else:
return [SimServer()]
def _saveServerList(self):
"""Save the server list for future use when exit from current dialog."""
self._applyChange()
file = open(self.serverFile, "wb")
pickle.dump(self.servers, file, pickle.HIGHEST_PROTOCOL)
file.close()
return
pass # end of class ServerManager
# == Test code [stub]
if __name__ == '__main__':
from PyQt4.Qt import QApplication, QDialog
# end
| NanoCAD-master | cad/src/processes/ServerManager.py |
# -*- coding: utf-8 -*-
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details.
# Form implementation generated from reading ui file 'ServerManagerDialog.ui'
#
# Created: Wed Sep 20 09:07:05 2006
# by: PyQt4 UI code generator 4.0.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_ServerManagerDialog(object):
def setupUi(self, ServerManagerDialog):
ServerManagerDialog.setObjectName("ServerManagerDialog")
ServerManagerDialog.resize(QtCore.QSize(QtCore.QRect(0,0,673,677).size()).expandedTo(ServerManagerDialog.minimumSizeHint()))
self.vboxlayout = QtGui.QVBoxLayout(ServerManagerDialog)
self.vboxlayout.setMargin(11)
self.vboxlayout.setSpacing(6)
self.vboxlayout.setObjectName("vboxlayout")
self.hboxlayout = QtGui.QHBoxLayout()
self.hboxlayout.setMargin(0)
self.hboxlayout.setSpacing(6)
self.hboxlayout.setObjectName("hboxlayout")
self.server_listview = QtGui.QListWidget(ServerManagerDialog)
self.server_listview.setObjectName("server_listview")
self.hboxlayout.addWidget(self.server_listview)
self.frame4 = QtGui.QFrame(ServerManagerDialog)
self.frame4.setFrameShape(QtGui.QFrame.Box)
self.frame4.setFrameShadow(QtGui.QFrame.Raised)
self.frame4.setObjectName("frame4")
self.vboxlayout1 = QtGui.QVBoxLayout(self.frame4)
self.vboxlayout1.setMargin(11)
self.vboxlayout1.setSpacing(6)
self.vboxlayout1.setObjectName("vboxlayout1")
self.textLabel1 = QtGui.QLabel(self.frame4)
self.textLabel1.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1.setObjectName("textLabel1")
self.vboxlayout1.addWidget(self.textLabel1)
self.name_linedit = QtGui.QLineEdit(self.frame4)
self.name_linedit.setObjectName("name_linedit")
self.vboxlayout1.addWidget(self.name_linedit)
self.textLabel1_3 = QtGui.QLabel(self.frame4)
self.textLabel1_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1_3.setObjectName("textLabel1_3")
self.vboxlayout1.addWidget(self.textLabel1_3)
self.ipaddress_linedit = QtGui.QLineEdit(self.frame4)
self.ipaddress_linedit.setObjectName("ipaddress_linedit")
self.vboxlayout1.addWidget(self.ipaddress_linedit)
self.gridlayout = QtGui.QGridLayout()
self.gridlayout.setMargin(0)
self.gridlayout.setSpacing(6)
self.gridlayout.setObjectName("gridlayout")
self.textLabel1_2 = QtGui.QLabel(self.frame4)
self.textLabel1_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1_2.setObjectName("textLabel1_2")
self.gridlayout.addWidget(self.textLabel1_2,0,0,1,1)
self.method_combox = QtGui.QComboBox(self.frame4)
self.method_combox.setObjectName("method_combox")
self.gridlayout.addWidget(self.method_combox,1,1,1,1)
self.textLabel1_6 = QtGui.QLabel(self.frame4)
self.textLabel1_6.setObjectName("textLabel1_6")
self.gridlayout.addWidget(self.textLabel1_6,0,1,1,1)
self.platform_combox = QtGui.QComboBox(self.frame4)
self.platform_combox.setObjectName("platform_combox")
self.gridlayout.addWidget(self.platform_combox,1,0,1,1)
self.vboxlayout1.addLayout(self.gridlayout)
self.textLabel1_4 = QtGui.QLabel(self.frame4)
self.textLabel1_4.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1_4.setObjectName("textLabel1_4")
self.vboxlayout1.addWidget(self.textLabel1_4)
self.hboxlayout1 = QtGui.QHBoxLayout()
self.hboxlayout1.setMargin(0)
self.hboxlayout1.setSpacing(6)
self.hboxlayout1.setObjectName("hboxlayout1")
self.engine_combox = QtGui.QComboBox(self.frame4)
self.engine_combox.setObjectName("engine_combox")
self.hboxlayout1.addWidget(self.engine_combox)
spacerItem = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout1.addItem(spacerItem)
self.vboxlayout1.addLayout(self.hboxlayout1)
self.textLabel1_5 = QtGui.QLabel(self.frame4)
self.textLabel1_5.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1_5.setObjectName("textLabel1_5")
self.vboxlayout1.addWidget(self.textLabel1_5)
self.program_linedit = QtGui.QLineEdit(self.frame4)
self.program_linedit.setObjectName("program_linedit")
self.vboxlayout1.addWidget(self.program_linedit)
self.textLabel1_2_2 = QtGui.QLabel(self.frame4)
self.textLabel1_2_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1_2_2.setObjectName("textLabel1_2_2")
self.vboxlayout1.addWidget(self.textLabel1_2_2)
self.username_linedit = QtGui.QLineEdit(self.frame4)
self.username_linedit.setObjectName("username_linedit")
self.vboxlayout1.addWidget(self.username_linedit)
self.textLabel1_2_2_2 = QtGui.QLabel(self.frame4)
self.textLabel1_2_2_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.textLabel1_2_2_2.setObjectName("textLabel1_2_2_2")
self.vboxlayout1.addWidget(self.textLabel1_2_2_2)
self.password_linedit = QtGui.QLineEdit(self.frame4)
self.password_linedit.setEchoMode(QtGui.QLineEdit.Password)
self.password_linedit.setObjectName("password_linedit")
self.vboxlayout1.addWidget(self.password_linedit)
self.hboxlayout.addWidget(self.frame4)
self.vboxlayout.addLayout(self.hboxlayout)
self.hboxlayout2 = QtGui.QHBoxLayout()
self.hboxlayout2.setMargin(0)
self.hboxlayout2.setSpacing(6)
self.hboxlayout2.setObjectName("hboxlayout2")
self.new_btn = QtGui.QPushButton(ServerManagerDialog)
self.new_btn.setEnabled(True)
self.new_btn.setObjectName("new_btn")
self.hboxlayout2.addWidget(self.new_btn)
self.del_btn = QtGui.QPushButton(ServerManagerDialog)
self.del_btn.setObjectName("del_btn")
self.hboxlayout2.addWidget(self.del_btn)
self.test_btn = QtGui.QPushButton(ServerManagerDialog)
self.test_btn.setObjectName("test_btn")
self.hboxlayout2.addWidget(self.test_btn)
self.exit_btn = QtGui.QPushButton(ServerManagerDialog)
self.exit_btn.setObjectName("exit_btn")
self.hboxlayout2.addWidget(self.exit_btn)
self.vboxlayout.addLayout(self.hboxlayout2)
self.retranslateUi(ServerManagerDialog)
QtCore.QObject.connect(self.exit_btn,QtCore.SIGNAL("clicked()"),ServerManagerDialog.close)
QtCore.QMetaObject.connectSlotsByName(ServerManagerDialog)
def retranslateUi(self, ServerManagerDialog):
ServerManagerDialog.setWindowTitle(QtGui.QApplication.translate("ServerManagerDialog", "Server Manager", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1.setText(QtGui.QApplication.translate("ServerManagerDialog", "Server Name :", None, QtGui.QApplication.UnicodeUTF8))
self.name_linedit.setText(QtGui.QApplication.translate("ServerManagerDialog", "localhost", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_3.setText(QtGui.QApplication.translate("ServerManagerDialog", "IP Address :", None, QtGui.QApplication.UnicodeUTF8))
self.ipaddress_linedit.setText(QtGui.QApplication.translate("ServerManagerDialog", "127.0.0.1", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2.setText(QtGui.QApplication.translate("ServerManagerDialog", "Platform :", None, QtGui.QApplication.UnicodeUTF8))
self.method_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Local access", None, QtGui.QApplication.UnicodeUTF8))
self.method_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Ssh/scp", None, QtGui.QApplication.UnicodeUTF8))
self.method_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Rsh/rcp", None, QtGui.QApplication.UnicodeUTF8))
self.method_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Telnet/ftp", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_6.setText(QtGui.QApplication.translate("ServerManagerDialog", "Method:", None, QtGui.QApplication.UnicodeUTF8))
self.platform_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Linux", None, QtGui.QApplication.UnicodeUTF8))
self.platform_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Mac OS", None, QtGui.QApplication.UnicodeUTF8))
self.platform_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "Windows", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_4.setText(QtGui.QApplication.translate("ServerManagerDialog", "Engine :", None, QtGui.QApplication.UnicodeUTF8))
self.engine_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "PC GAMESS", None, QtGui.QApplication.UnicodeUTF8))
self.engine_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "nanoSIM-1", None, QtGui.QApplication.UnicodeUTF8))
self.engine_combox.addItem(QtGui.QApplication.translate("ServerManagerDialog", "GAMESS", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_5.setText(QtGui.QApplication.translate("ServerManagerDialog", "Executing Program :", None, QtGui.QApplication.UnicodeUTF8))
self.program_linedit.setText(QtGui.QApplication.translate("ServerManagerDialog", "C:\\PCGAMESS", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_2.setText(QtGui.QApplication.translate("ServerManagerDialog", "Username :", None, QtGui.QApplication.UnicodeUTF8))
self.username_linedit.setText(QtGui.QApplication.translate("ServerManagerDialog", "nanorex", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_2_2.setText(QtGui.QApplication.translate("ServerManagerDialog", "Password :", None, QtGui.QApplication.UnicodeUTF8))
self.password_linedit.setText(QtGui.QApplication.translate("ServerManagerDialog", "nanorex", None, QtGui.QApplication.UnicodeUTF8))
self.new_btn.setText(QtGui.QApplication.translate("ServerManagerDialog", "New", None, QtGui.QApplication.UnicodeUTF8))
self.del_btn.setText(QtGui.QApplication.translate("ServerManagerDialog", "Delete", None, QtGui.QApplication.UnicodeUTF8))
self.test_btn.setText(QtGui.QApplication.translate("ServerManagerDialog", "Test", None, QtGui.QApplication.UnicodeUTF8))
self.exit_btn.setText(QtGui.QApplication.translate("ServerManagerDialog", "Exit", None, QtGui.QApplication.UnicodeUTF8))
| NanoCAD-master | cad/src/processes/ServerManagerDialog.py |
NanoCAD-master | cad/src/processes/__init__.py |
|
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details.
"""
Process.py
Provides class Process, a QProcess subclass which is more convenient to use,
and a convenience function run_command() for using it to run external commands.
@author: Bruce, EricM
@version: $Id$
@copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details.
History:
bruce 050902 made this, using Qt doc and existing QProcess calls for guidance.
ericm 0712xx apparently ported it to Qt 4 (?), and added some features.
Future plans:
This can be extended as needed to be able to do more flexible communication
with external processes, and have better convenience functions, e.g. for
running multiple processes concurrently.
And it might as well be extended enough to replace some existing uses of QProcess
with uses of this class, if that would simplify them (but I'm not sure whether it would).
"""
from PyQt4.Qt import QProcess, QStringList, qApp, SIGNAL, QDir, QString
import time
import foundation.env as env
def ensure_QStringList(args):
if type(args) == type([]):
arguments = QStringList()
for arg in args:
arguments.append(arg)
args = arguments
assert isinstance(args, QStringList) # fails if caller passes the wrong thing
return args
def ensure_QDir(arg):
if type(arg) == type(""):
arg = QString(arg)
if isinstance(arg, QString):
arg = QDir(arg)
assert isinstance(arg, QDir) # fails if caller passes the wrong thing
return arg
super = QProcess
class Process(QProcess):
"""
Subclass of QProcess which is able to capture and record stdout/stderr,
and has other convenience methods.
"""
stdout = stderr = None
def __init__(self, *args):
"""
Like QProcess.__init__, but the form with arguments might not be usable with a Python list.
"""
super.__init__(self, *args)
# I don't know if we'd need to use these signals if we wanted to discard the data.
# The issue is whether it's going into a pipe which fills up and blocks the process.
# In order to not have to worry about this, we read it all, whether or not caller wants it.
# We discard it here (in these slot methods) if caller didn't call set_stdout or set_stderr.
# See also QProcess.communication property (whose meaning or effect is not documented in Qt Assistant).
self.connect( self, SIGNAL('readyReadStandardOutput()'), self.read_stdout) ###k
self.connect( self, SIGNAL('readyReadStandardError()'), self.read_stderr) ###k
self.connect( self, SIGNAL('error(int)'), self.got_error) ###k
self.connect( self, SIGNAL('finished(int)'), self.process_exited) ###k
self.currentError = None
self.stdoutRedirected = False
self.stderrRedirected = False
self.stdoutPassThrough = False
self.stderrPassThrough = False
self.processName = "subprocess"
def read_stdout(self):
self.setReadChannel(QProcess.StandardOutput)
while (self.bytesAvailable()):
line = self.readLine() # QByteArray
line = str(line) ###k
self.standardOutputLine(line)
def read_stderr(self):
self.setReadChannel(QProcess.StandardError)
while (self.bytesAvailable()):
line = self.readLine() # QByteArray
line = str(line) ###k
self.standardErrorLine(line)
def got_error(self, err):
# it doesn't seem like Qt ever calls this on Linux
self.currentError = err
print "got error: " + self.processState()
def process_exited(self, exitvalue):
self.set_stdout(None)
self.set_stderr(None)
#exit_code = self.exitCode()
#exit_status = self.exitStatus()
#print "%s exited, code: %d, status: %d" % (self.processName, exit_code, exit_status)
##def setArguments(self, args): #k needed?
##"Overrides QProcess.setArguments so it can accept a Python list as well as a QStringList."
##args = ensure_QStringList(args)
##super.setArguments(self, args)
##def setWorkingDirectory(self, arg): # definitely needed
##"Overrides QProcess.setWorkingDirectory so it can accept a Python string or QString as well as a QDir object."
##arg = ensure_QDir(arg)
##super.setWorkingDirectory(self, arg)
def set_stdout(self, stdout):
"""
Cause stdout from this process to be written to the given file-like object
(which must have write method, and whose flush method is also used if it exists).
This should be called before starting the process.
If it's never called, stdout from the process will be read and discarded.
"""
if (self.stdout and self.stdoutRedirected):
self.stdout.close()
self.stdoutRedirected = False
self.stdout = stdout
def set_stderr(self, stderr):
"""
Like set_stdout but for stderr.
"""
if (self.stderr and self.stderrRedirected):
self.stderr.close()
self.stderrRedirected = False
self.stderr = stderr
def redirect_stdout_to_file(self, filename):
self.stdout = open(filename, 'w')
self.stdoutRedirected = True
def redirect_stderr_to_file(self, filename):
self.stderr = open(filename, 'w')
self.stderrRedirected = True
def setStandardOutputPassThrough(self, passThrough):
self.stdoutPassThrough = passThrough
def setStandardErrorPassThrough(self, passThrough):
self.stderrPassThrough = passThrough
def setProcessName(self, name):
self.processName = name
def standardOutputLine(self, bytes):
if self.stdout is not None:
self.stdout.write(bytes)
self.try_flush(self.stdout)
if (self.stdoutPassThrough):
print "%s: %s" % (self.processName, bytes.rstrip())
def standardErrorLine(self, bytes):
if self.stderr is not None:
self.stderr.write(bytes)
self.try_flush(self.stderr)
if (self.stdoutPassThrough):
print "%s(stderr): %s" % (self.processName, bytes.rstrip())
def try_flush(self, file):
try:
file.flush # see if attr is present
except:
pass
else:
file.flush()
return
def processState(self):
s = self.state()
if (s == QProcess.NotRunning):
state = "NotRunning"
elif (s == QProcess.Starting):
state = "Starting"
elif (s == QProcess.Running):
state = "Running"
else:
state = "UnknownState: %s" % s
if (self.currentError != None):
if (self.currentError == QProcess.FailedToStart):
err = "FailedToStart"
elif (self.currentError == QProcess.Crashed):
err = "Crashed"
elif (self.currentError == QProcess.Timedout):
err = "Timedout"
elif (self.currentError == QProcess.ReadError):
err = "ReadError"
elif (self.currentError == QProcess.WriteError):
err = "WriteError"
else:
err = "UnknownError"
else:
err = ""
return state + "[" + err + "]"
def wait_for_exit(self, abortHandler, pollFunction = None):
"""
Wait for the process to exit (sleeping by 0.05 seconds in a
loop). Calls pollFunction each time around the loop if it is
specified. Return its exitcode. Call this only after the
process was successfully started using self.start() or
self.launch().
"""
abortPressCount = 0
while (not self.state() == QProcess.NotRunning):
if (abortHandler):
pc = abortHandler.getPressCount()
if (pc > abortPressCount):
abortPressCount = pc
if (abortPressCount > 1):
self.terminate()
else:
self.kill()
env.call_qApp_processEvents() #bruce 050908 replaced qApp.processEvents()
#k is this required for us to get the slot calls for stdout / stderr ?
# I don't know, but we want it even if not.
if (pollFunction):
pollFunction()
time.sleep(0.05)
if (abortHandler):
abortHandler.finish()
return self.exitCode()
def getExitValue(self, abortHandler, pollFunction = None):
"""
Return the exitcode, or -2 if it crashed or was terminated. Only call
this after it exited.
"""
code = self.wait_for_exit(abortHandler, pollFunction)
if (self.exitStatus() == QProcess.NormalExit):
return code
return -2
def run(self, program, args = None, background = False, abortHandler = None, pollFunction = None):
"""
Starts the program I{program} in a new process, passing the command
line arguments in I{args}.
On Windows, arguments that contain spaces are wrapped in quotes.
@param program: The program to start.
@type program: string
@param args: a list of arguments.
@type args: list
@param background: If True, starts the program I{program} in a new
process, and detaches from it. If NE1 exits, the
detached process will continue to live.
The default is False (not backgrounded).
@type background: boolean
@param abortHandler: The abort handler.
@type abortHandler: L{AbortHandler}
@param pollFunction: Called once every 0.05 seconds while process is running.
@type pollFunction: function.
@return: 0 if the process starts successfully.
@rtype: int
@note: processes are started asynchronously, which means the started()
and error() signals may be delayed. If this is not a backgrounded
process, run() makes sure the process has started (or has failed to
start) and those signals have been emitted. For a backgrounded process
"""
if (args is None):
args = []
self.currentError = None
if background:
print "\n%s [%s]: starting in the background with args:\n%s" \
% (self.processName, program, args)
# Run 'program' as a separate process.
# startDetached() returns True on success.
rval = not self.startDetached(program, args)
else:
print "\n%s [%s]: starting in the foreground with args:\n%s" \
% (self.processName, program, args)
# Run 'program' as a child process.
self.start(program, args) #k ok that we provide no stdin? #e might need to provide an env here
rval = self.getExitValue(abortHandler, pollFunction)
if 1:
print "%s: started. Return val=%d" % (self.processName, rval)
return rval
pass
def run_command( program, args = [], stdout = None, stderr = None, cwd = None ):
"""
Run program, with optional args, as a separate process,
optionally capturing its stdout and stderr to the given file-like objects
(or discarding it if those are not provided),
optionally changing its current working directory to the specified directory cwd.
Wait for it to exit and return its exitcode, or -2 if it crashed.
If something goes wrong in finding or starting the program, raise an exception.
"""
pp = Process()
if cwd:
pp.setWorkingDirectory(cwd)
pp.set_stdout( stdout) # ok if this is None
pp.set_stderr( stderr)
ec = pp.run(program, args)
return ec
# == test code
class ProcessTest(object):
def _test(self, program, args = None, wd = None):
import sys
pp = Process()
print
print "program: %s, args: " % program, args
if wd:
print "working dir:", wd
if wd:
pp.setWorkingDirectory(wd)
#pp.set_stdout( sys.stdout) #k might be more useful if we labelled the first uses or the lines...
pp.set_stderr(sys.stderr)
##pp.setProcessChannelMode(QProcess.ForwardedChannels)
ec = pp.run(program, args)
print "exitcode was", ec
def _all_tests(self):
self._test("ferdisaferd")
##Wed Dec 31 16:00:08 PST 1969
##exitcode was 0
#self._test("date", ["-rrr", "8"] )
##date: illegal time format
##usage: date [-nu] [-r seconds] [+format]
## date [[[[[cc]yy]mm]dd]hh]mm[.ss]
##exitcode was 1
#self._test("ls", ["-f"], "/tmp" )
##501
##mcx_compositor
##printers
##exitcode was 0
global app
app.quit()
if __name__ == '__main__':
from PyQt4.Qt import QApplication, QTimer
import sys
test = ProcessTest()
app = QApplication(sys.argv, False)
timer = QTimer()
timer.connect(timer, SIGNAL("timeout()"), test._all_tests)
timer.setSingleShot(True)
timer.start(10)
app.exec_()
# end
| NanoCAD-master | cad/src/processes/Process.py |
# -*- coding: utf-8 -*-
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
# Form implementation generated from reading ui file 'LinearMotorPropDialog.ui'
#
# Created: Wed Sep 20 10:14:34 2006
# by: PyQt4 UI code generator 4.0.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_LinearMotorPropDialog(object):
def setupUi(self, LinearMotorPropDialog):
LinearMotorPropDialog.setObjectName("LinearMotorPropDialog")
LinearMotorPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,295,372).size()).expandedTo(LinearMotorPropDialog.minimumSizeHint()))
LinearMotorPropDialog.setSizeGripEnabled(True)
self.gridlayout = QtGui.QGridLayout(LinearMotorPropDialog)
self.gridlayout.setMargin(11)
self.gridlayout.setSpacing(6)
self.gridlayout.setObjectName("gridlayout")
self.groupBox3 = QtGui.QGroupBox(LinearMotorPropDialog)
self.groupBox3.setObjectName("groupBox3")
self.gridlayout1 = QtGui.QGridLayout(self.groupBox3)
self.gridlayout1.setMargin(11)
self.gridlayout1.setSpacing(6)
self.gridlayout1.setObjectName("gridlayout1")
self.widthLineEdit = QtGui.QLineEdit(self.groupBox3)
self.widthLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.widthLineEdit.setObjectName("widthLineEdit")
self.gridlayout1.addWidget(self.widthLineEdit,1,1,1,1)
self.textLabel3 = QtGui.QLabel(self.groupBox3)
self.textLabel3.setObjectName("textLabel3")
self.gridlayout1.addWidget(self.textLabel3,0,2,1,1)
self.sradiusLineEdit = QtGui.QLineEdit(self.groupBox3)
self.sradiusLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.sradiusLineEdit.setObjectName("sradiusLineEdit")
self.gridlayout1.addWidget(self.sradiusLineEdit,2,1,1,1)
self.lengthLineEdit = QtGui.QLineEdit(self.groupBox3)
self.lengthLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.lengthLineEdit.setObjectName("lengthLineEdit")
self.gridlayout1.addWidget(self.lengthLineEdit,0,1,1,1)
self.textLabel3_3 = QtGui.QLabel(self.groupBox3)
self.textLabel3_3.setObjectName("textLabel3_3")
self.gridlayout1.addWidget(self.textLabel3_3,2,2,1,1)
self.textLabel3_2 = QtGui.QLabel(self.groupBox3)
self.textLabel3_2.setObjectName("textLabel3_2")
self.gridlayout1.addWidget(self.textLabel3_2,1,2,1,1)
self.hboxlayout = QtGui.QHBoxLayout()
self.hboxlayout.setMargin(0)
self.hboxlayout.setSpacing(6)
self.hboxlayout.setObjectName("hboxlayout")
self.hboxlayout1 = QtGui.QHBoxLayout()
self.hboxlayout1.setMargin(0)
self.hboxlayout1.setSpacing(6)
self.hboxlayout1.setObjectName("hboxlayout1")
self.jig_color_pixmap = QtGui.QLabel(self.groupBox3)
self.jig_color_pixmap.setMinimumSize(QtCore.QSize(40,0))
self.jig_color_pixmap.setScaledContents(True)
self.jig_color_pixmap.setObjectName("jig_color_pixmap")
self.hboxlayout1.addWidget(self.jig_color_pixmap)
self.choose_color_btn = QtGui.QPushButton(self.groupBox3)
self.choose_color_btn.setEnabled(True)
self.choose_color_btn.setAutoDefault(False)
self.choose_color_btn.setObjectName("choose_color_btn")
self.hboxlayout1.addWidget(self.choose_color_btn)
self.hboxlayout.addLayout(self.hboxlayout1)
spacerItem = QtGui.QSpacerItem(46,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout.addItem(spacerItem)
self.gridlayout1.addLayout(self.hboxlayout,3,1,1,2)
self.textLabel1_3 = QtGui.QLabel(self.groupBox3)
self.textLabel1_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_3.setObjectName("textLabel1_3")
self.gridlayout1.addWidget(self.textLabel1_3,0,0,1,1)
self.textLabel1_2_2 = QtGui.QLabel(self.groupBox3)
self.textLabel1_2_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2_2.setObjectName("textLabel1_2_2")
self.gridlayout1.addWidget(self.textLabel1_2_2,1,0,1,1)
self.textLabel1_2_2_2 = QtGui.QLabel(self.groupBox3)
self.textLabel1_2_2_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2_2_2.setObjectName("textLabel1_2_2_2")
self.gridlayout1.addWidget(self.textLabel1_2_2_2,2,0,1,1)
self.colorTextLabel = QtGui.QLabel(self.groupBox3)
self.colorTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.colorTextLabel.setObjectName("colorTextLabel")
self.gridlayout1.addWidget(self.colorTextLabel,3,0,1,1)
self.gridlayout.addWidget(self.groupBox3,2,0,1,1)
spacerItem1 = QtGui.QSpacerItem(20,16,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding)
self.gridlayout.addItem(spacerItem1,3,0,1,1)
self.hboxlayout2 = QtGui.QHBoxLayout()
self.hboxlayout2.setMargin(0)
self.hboxlayout2.setSpacing(6)
self.hboxlayout2.setObjectName("hboxlayout2")
spacerItem2 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout2.addItem(spacerItem2)
self.ok_btn = QtGui.QPushButton(LinearMotorPropDialog)
self.ok_btn.setAutoDefault(False)
self.ok_btn.setDefault(False)
self.ok_btn.setObjectName("ok_btn")
self.hboxlayout2.addWidget(self.ok_btn)
self.cancel_btn = QtGui.QPushButton(LinearMotorPropDialog)
self.cancel_btn.setAutoDefault(False)
self.cancel_btn.setObjectName("cancel_btn")
self.hboxlayout2.addWidget(self.cancel_btn)
self.gridlayout.addLayout(self.hboxlayout2,4,0,1,1)
self.hboxlayout3 = QtGui.QHBoxLayout()
self.hboxlayout3.setMargin(0)
self.hboxlayout3.setSpacing(6)
self.hboxlayout3.setObjectName("hboxlayout3")
self.vboxlayout = QtGui.QVBoxLayout()
self.vboxlayout.setMargin(0)
self.vboxlayout.setSpacing(6)
self.vboxlayout.setObjectName("vboxlayout")
self.nameTextLabel = QtGui.QLabel(LinearMotorPropDialog)
self.nameTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.nameTextLabel.setObjectName("nameTextLabel")
self.vboxlayout.addWidget(self.nameTextLabel)
self.textLabel1 = QtGui.QLabel(LinearMotorPropDialog)
font = QtGui.QFont(self.textLabel1.font())
font.setFamily("Sans Serif")
font.setPointSize(9)
font.setWeight(50)
font.setItalic(False)
font.setUnderline(False)
font.setStrikeOut(False)
font.setBold(False)
self.textLabel1.setFont(font)
self.textLabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1.setObjectName("textLabel1")
self.vboxlayout.addWidget(self.textLabel1)
self.textLabel1_2 = QtGui.QLabel(LinearMotorPropDialog)
self.textLabel1_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2.setObjectName("textLabel1_2")
self.vboxlayout.addWidget(self.textLabel1_2)
self.hboxlayout3.addLayout(self.vboxlayout)
self.gridlayout2 = QtGui.QGridLayout()
self.gridlayout2.setMargin(0)
self.gridlayout2.setSpacing(6)
self.gridlayout2.setObjectName("gridlayout2")
self.forceLineEdit = QtGui.QLineEdit(LinearMotorPropDialog)
self.forceLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.forceLineEdit.setObjectName("forceLineEdit")
self.gridlayout2.addWidget(self.forceLineEdit,1,0,1,1)
self.textLabel2 = QtGui.QLabel(LinearMotorPropDialog)
self.textLabel2.setObjectName("textLabel2")
self.gridlayout2.addWidget(self.textLabel2,2,1,1,1)
self.textLabel1_4 = QtGui.QLabel(LinearMotorPropDialog)
self.textLabel1_4.setObjectName("textLabel1_4")
self.gridlayout2.addWidget(self.textLabel1_4,1,1,1,1)
self.nameLineEdit = QtGui.QLineEdit(LinearMotorPropDialog)
self.nameLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.nameLineEdit.setReadOnly(False)
self.nameLineEdit.setObjectName("nameLineEdit")
self.gridlayout2.addWidget(self.nameLineEdit,0,0,1,2)
self.stiffnessLineEdit = QtGui.QLineEdit(LinearMotorPropDialog)
self.stiffnessLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.stiffnessLineEdit.setObjectName("stiffnessLineEdit")
self.gridlayout2.addWidget(self.stiffnessLineEdit,2,0,1,1)
self.hboxlayout3.addLayout(self.gridlayout2)
spacerItem3 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout3.addItem(spacerItem3)
self.gridlayout.addLayout(self.hboxlayout3,0,0,1,1)
self.hboxlayout4 = QtGui.QHBoxLayout()
self.hboxlayout4.setMargin(0)
self.hboxlayout4.setSpacing(6)
self.hboxlayout4.setObjectName("hboxlayout4")
self.textLabel1_5 = QtGui.QLabel(LinearMotorPropDialog)
self.textLabel1_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_5.setObjectName("textLabel1_5")
self.hboxlayout4.addWidget(self.textLabel1_5)
self.enable_minimize_checkbox = QtGui.QCheckBox(LinearMotorPropDialog)
self.enable_minimize_checkbox.setObjectName("enable_minimize_checkbox")
self.hboxlayout4.addWidget(self.enable_minimize_checkbox)
spacerItem4 = QtGui.QSpacerItem(92,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout4.addItem(spacerItem4)
self.gridlayout.addLayout(self.hboxlayout4,1,0,1,1)
#self.textLabel1.setBuddy(LinearMotorPropDialog.lineEdit9)
#self.textLabel1_2.setBuddy(LinearMotorPropDialog.lineEdit9_2)
self.retranslateUi(LinearMotorPropDialog)
QtCore.QObject.connect(self.cancel_btn,QtCore.SIGNAL("clicked()"),LinearMotorPropDialog.reject)
QtCore.QObject.connect(self.ok_btn,QtCore.SIGNAL("clicked()"),LinearMotorPropDialog.accept)
QtCore.QMetaObject.connectSlotsByName(LinearMotorPropDialog)
LinearMotorPropDialog.setTabOrder(self.nameLineEdit,self.forceLineEdit)
LinearMotorPropDialog.setTabOrder(self.forceLineEdit,self.stiffnessLineEdit)
LinearMotorPropDialog.setTabOrder(self.stiffnessLineEdit,self.enable_minimize_checkbox)
LinearMotorPropDialog.setTabOrder(self.enable_minimize_checkbox,self.lengthLineEdit)
LinearMotorPropDialog.setTabOrder(self.lengthLineEdit,self.widthLineEdit)
LinearMotorPropDialog.setTabOrder(self.widthLineEdit,self.sradiusLineEdit)
LinearMotorPropDialog.setTabOrder(self.sradiusLineEdit,self.choose_color_btn)
LinearMotorPropDialog.setTabOrder(self.choose_color_btn,self.ok_btn)
LinearMotorPropDialog.setTabOrder(self.ok_btn,self.cancel_btn)
def retranslateUi(self, LinearMotorPropDialog):
LinearMotorPropDialog.setWindowTitle(QtGui.QApplication.translate("LinearMotorPropDialog", "Linear Motor Properties", None, QtGui.QApplication.UnicodeUTF8))
LinearMotorPropDialog.setWindowIcon(QtGui.QIcon("ui/border/LinearMotor"))
self.groupBox3.setTitle(QtGui.QApplication.translate("LinearMotorPropDialog", "Size and Color", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel3.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Angstroms", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel3_3.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Angstroms", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel3_2.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Angstroms", None, QtGui.QApplication.UnicodeUTF8))
self.choose_color_btn.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_3.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Motor Length:", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_2.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Motor Width:", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_2_2.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Spoke Radius:", None, QtGui.QApplication.UnicodeUTF8))
self.colorTextLabel.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Color:", None, QtGui.QApplication.UnicodeUTF8))
self.ok_btn.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8))
self.ok_btn.setShortcut(QtGui.QApplication.translate("LinearMotorPropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8))
self.cancel_btn.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8))
self.cancel_btn.setShortcut(QtGui.QApplication.translate("LinearMotorPropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8))
self.nameTextLabel.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Name:", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Force:", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Stiffness:", None, QtGui.QApplication.UnicodeUTF8))
self.forceLineEdit.setToolTip(QtGui.QApplication.translate("LinearMotorPropDialog", "Simulations will begin with the motor\'s force set to this value.", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel2.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "N/m", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_4.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "pN", None, QtGui.QApplication.UnicodeUTF8))
self.nameLineEdit.setToolTip(QtGui.QApplication.translate("LinearMotorPropDialog", "Name of Linear Motor", None, QtGui.QApplication.UnicodeUTF8))
self.stiffnessLineEdit.setToolTip(QtGui.QApplication.translate("LinearMotorPropDialog", "Simulations will begin with the motor\'s stiffness set to this value.", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_5.setToolTip(QtGui.QApplication.translate("LinearMotorPropDialog", "If checked, the force value is applied to the motor\'s atoms during minimization.", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_5.setText(QtGui.QApplication.translate("LinearMotorPropDialog", "Enable in Minimize (experimental) :", None, QtGui.QApplication.UnicodeUTF8))
self.enable_minimize_checkbox.setToolTip(QtGui.QApplication.translate("LinearMotorPropDialog", "If checked, the force value is applied to the motor\'s atoms during minimization.", None, QtGui.QApplication.UnicodeUTF8))
| NanoCAD-master | cad/src/outtakes/LinearMotorPropDialog.py |
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details.
"""
PropertyManagerMixin.py
@author: Ninad
@version: $Id$
@copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details.
History:
ninad20061215: created this mixin class to provide helper methods in various
Property managers
ninad20070206: added many new methods to help prop manager ui generation.
mark 2007-05-17: added the new property manager base class PropMgrBaseClass. [now in its own file]
bruce 2007-06-15: partly cleaned up inheritance (by splitting out PropertyManager_common).
"""
__author__ = "Ninad"
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import Qt
from PyQt4.Qt import QPalette
from PyQt4.Qt import QSizePolicy
from PyQt4.Qt import QGroupBox
from PyQt4.Qt import QFrame
from PyQt4.Qt import QHBoxLayout
from PyQt4.Qt import QLabel
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QSpacerItem
from PyQt4.Qt import QToolButton
from PyQt4.Qt import QSize
from PyQt4.Qt import QWhatsThis
from PyQt4.Qt import QVBoxLayout
from PyQt4.Qt import QTextOption
from PyQt4.Qt import QPushButton
from PyQt4.Qt import QTextEdit
from utilities import debug_flags
from utilities.icon_utilities import geticon, getpixmap
from sponsors.Sponsors import SponsorableMixin
from utilities.qt4transition import lineage
from utilities.debug import print_compact_traceback
from PropMgrBaseClass import PropertyManager_common, getPalette
from PM.PropMgr_Constants import pmColor
from PM.PropMgr_Constants import pmAllButtons
from PM.PropMgr_Constants import pmTitleFrameColor
from PM.PropMgr_Constants import pmTitleLabelColor
from PM.PropMgr_Constants import pmMessageTextEditColor
from PM.PropMgr_Constants import pmGrpBoxColor
from PM.PropMgr_Constants import pmGrpBoxButtonColor
from PM.PropMgr_Constants import pmCheckBoxTextColor
from PM.PropMgr_Constants import pmCheckBoxButtonColor
from PM.PropMgr_Constants import pmGrpBoxBorderColor
from PM.PropMgr_Constants import pmGrpBoxButtonBorderColor
from PM.PropMgr_Constants import pmGrpBoxButtonTextColor
from PM.PropMgr_Constants import pmGrpBoxExpandedImage
from PM.PropMgr_Constants import pmGrpBoxCollapsedImage
from PM.PropMgr_Constants import pmGrpBoxVboxLayoutMargin
from PM.PropMgr_Constants import pmGrpBoxVboxLayoutSpacing
from PM.PropMgr_Constants import pmMainVboxLayoutMargin
from PM.PropMgr_Constants import pmMainVboxLayoutSpacing
from PM.PropMgr_Constants import pmHeaderFrameMargin
from PM.PropMgr_Constants import pmHeaderFrameSpacing
from PM.PropMgr_Constants import pmLabelLeftAlignment
from PM.PropMgr_Constants import getHeaderFont
from PM.PropMgr_Constants import pmSponsorFrameMargin
from PM.PropMgr_Constants import pmSponsorFrameSpacing
from PM.PropMgr_Constants import pmTopRowBtnsMargin
from PM.PropMgr_Constants import pmTopRowBtnsSpacing
from PM.PropMgr_Constants import pmDoneButton
from PM.PropMgr_Constants import pmCancelButton
from PM.PropMgr_Constants import pmRestoreDefaultsButton
from PM.PropMgr_Constants import pmPreviewButton
from PM.PropMgr_Constants import pmWhatsThisButton
from PM.PropMgr_Constants import pmMsgGrpBoxMargin
from PM.PropMgr_Constants import pmMsgGrpBoxSpacing
from PM.PropMgr_Constants import pmMinWidth
from PM.PropMgr_Constants import pmGroupBoxSpacing
def pmVBoxLayout(propMgr):
"""Create the master vertical box layout for <propMgr>.
"""
propMgr.pmVBoxLayout = QtGui.QVBoxLayout(propMgr)
propMgr.pmVBoxLayout.setMargin(pmMainVboxLayoutMargin)
propMgr.pmVBoxLayout.setSpacing(pmMainVboxLayoutSpacing)
propMgr.pmVBoxLayout.setObjectName("pmVBoxLayout")
def pmSetPropMgrTitle(propMgr, title):
"""Set the Property Manager header title to string <title>.
"""
propMgr.header_label.setText(title)
def pmSetPropMgrIcon(propMgr, png_path):
"""Set the Property Manager icon in the header.
<png_path> is the relative path to the PNG file.
"""
propMgr.header_pixmap.setPixmap(getpixmap(png_path))
#@ self.heading_pixmap = QtGui.QLabel(self.heading_frame)
#@ self.heading_pixmap.setPixmap(getpixmap('ui/actions/Tools/Build Structures/Atoms.png'))
def pmAddHeader(propMgr):
"""Creates the Property Manager header, which contains
a pixmap and white text label.
"""
# Heading frame (dark gray), which contains
# a pixmap and (white) heading text.
propMgr.header_frame = QFrame(propMgr)
propMgr.header_frame.setFrameShape(QFrame.NoFrame)
propMgr.header_frame.setFrameShadow(QFrame.Plain)
header_frame_palette = propMgr.getPropMgrTitleFramePalette()
propMgr.header_frame.setPalette(header_frame_palette)
propMgr.header_frame.setAutoFillBackground(True)
# HBox layout for heading frame, containing the pixmap
# and label (title).
HeaderFrameHLayout = QHBoxLayout(propMgr.header_frame)
HeaderFrameHLayout.setMargin(pmHeaderFrameMargin) # 2 pixels around edges.
HeaderFrameHLayout.setSpacing(pmHeaderFrameSpacing) # 5 pixel between pixmap and label.
# PropMgr icon. Set image by calling setPropMgrIcon() at any time.
propMgr.header_pixmap = QLabel(propMgr.header_frame)
propMgr.header_pixmap.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed),
QSizePolicy.Policy(QSizePolicy.Fixed)))
propMgr.header_pixmap.setScaledContents(True)
HeaderFrameHLayout.addWidget(propMgr.header_pixmap)
# PropMgr title label
propMgr.header_label = QLabel(propMgr.header_frame)
header_label_palette = propMgr.getPropMgrTitleLabelPalette()
propMgr.header_label.setPalette(header_label_palette)
propMgr.header_label.setAlignment(pmLabelLeftAlignment)
# PropMgr heading font (for label).
propMgr.header_label.setFont(getHeaderFont())
HeaderFrameHLayout.addWidget(propMgr.header_label)
propMgr.pmVBoxLayout.addWidget(propMgr.header_frame)
def pmAddSponsorButton(propMgr):
"""Creates the sponsor button for <propMgr>.
"""
propMgr.sponsor_frame = QtGui.QFrame(propMgr)
propMgr.sponsor_frame.setFrameShape(QtGui.QFrame.NoFrame)
propMgr.sponsor_frame.setFrameShadow(QtGui.QFrame.Plain)
propMgr.sponsor_frame.setObjectName("sponsor_frame")
propMgr.gridlayout_sponsor = QtGui.QGridLayout(propMgr.sponsor_frame)
propMgr.gridlayout_sponsor.setMargin(pmSponsorFrameMargin)
propMgr.gridlayout_sponsor.setSpacing(pmSponsorFrameSpacing)
propMgr.sponsor_btn = QtGui.QPushButton(propMgr.sponsor_frame)
propMgr.sponsor_btn.setAutoDefault(False)
propMgr.sponsor_btn.setFlat(True)
propMgr.sponsor_btn.setObjectName("sponsor_btn")
propMgr.gridlayout_sponsor.addWidget(propMgr.sponsor_btn,0,0,1,1)
propMgr.connect(propMgr.sponsor_btn,
SIGNAL("clicked()"),
propMgr.sponsor_btn_clicked)
propMgr.pmVBoxLayout.addWidget(propMgr.sponsor_frame)
def pmAddTopRowButtons(propMgr, showFlags=pmAllButtons):
"""Creates the OK, Cancel, Preview, and What's This
buttons row at the top of the Property Manager <propMgr>.
<showFlags> is an enum that can be used to show only certain
Property Manager buttons, where:
pmDoneButton = 1
pmCancelButton = 2
pmRestoreDefaultsButton = 4
pmPreviewButton = 8
pmWhatsThisButton = 16
pmAllButtons = 31
These flags are defined in PropMgr_Constants.py.
This subroutine is used by the following Property Managers
(which are still not using the PropMgrBaseClass):
- Build Atoms
- Build Crystal
- Extrude
- Move
- Movie Player
- Fuse Chunks
Note: This subrouting is temporary. It will be removed after the
PropMgrs in this list are converted to the PropMgrBaseClass.
Mark 2007-06-24
"""
# The Top Buttons Row includes the following widgets:
#
# - propMgr.pmTopRowBtns (Hbox Layout containing everything:)
#
# - frame
# - hbox layout "frameHboxLO" (margin=2, spacing=2)
# - Done (OK) button
# - Abort (Cancel) button
# - Restore Defaults button
# - Preview button
# - What's This button
# - right spacer (10x10)
# Main "button group" widget (but it is not a QButtonGroup).
propMgr.pmTopRowBtns = QHBoxLayout()
# Horizontal spacer
HSpacer = QSpacerItem(1, 1,
QSizePolicy.Expanding,
QSizePolicy.Minimum)
# Frame containing all the buttons.
propMgr.TopRowBtnsFrame = QFrame()
propMgr.TopRowBtnsFrame.setFrameShape(QFrame.NoFrame)
propMgr.TopRowBtnsFrame.setFrameShadow(QFrame.Plain)
# Create Hbox layout for main frame.
TopRowBtnsHLayout = QHBoxLayout(propMgr.TopRowBtnsFrame)
TopRowBtnsHLayout.setMargin(pmTopRowBtnsMargin)
TopRowBtnsHLayout.setSpacing(pmTopRowBtnsSpacing)
TopRowBtnsHLayout.addItem(HSpacer)
# Set button type.
buttonType = QToolButton
# May want to use QToolButton.setAutoRaise(1) below. Mark 2007-05-29
# OK (Done) button.
propMgr.done_btn = buttonType(propMgr.TopRowBtnsFrame)
propMgr.done_btn.setIcon(
geticon("ui/actions/Properties Manager/Done.png"))
propMgr.done_btn.setIconSize(QSize(22,22))
propMgr.connect(propMgr.done_btn,
SIGNAL("clicked()"),
propMgr.ok_btn_clicked)
propMgr.done_btn.setToolTip("Done")
TopRowBtnsHLayout.addWidget(propMgr.done_btn)
# Cancel (Abort) button.
propMgr.abort_btn = buttonType(propMgr.TopRowBtnsFrame)
propMgr.abort_btn.setIcon(
geticon("ui/actions/Properties Manager/Abort.png"))
propMgr.abort_btn.setIconSize(QSize(22,22))
propMgr.connect(propMgr.abort_btn,
SIGNAL("clicked()"),
propMgr.abort_btn_clicked)
propMgr.abort_btn.setToolTip("Cancel")
TopRowBtnsHLayout.addWidget(propMgr.abort_btn)
# Restore Defaults button.
propMgr.restore_defaults_btn = buttonType(propMgr.TopRowBtnsFrame)
propMgr.restore_defaults_btn.setIcon(
geticon("ui/actions/Properties Manager/Restore.png"))
propMgr.restore_defaults_btn.setIconSize(QSize(22,22))
propMgr.connect(propMgr.restore_defaults_btn,
SIGNAL("clicked()"),
propMgr.restore_defaults_btn_clicked)
propMgr.restore_defaults_btn.setToolTip("Restore Defaults")
TopRowBtnsHLayout.addWidget(propMgr.restore_defaults_btn)
# Preview (glasses) button.
propMgr.preview_btn = buttonType(propMgr.TopRowBtnsFrame)
propMgr.preview_btn.setIcon(
geticon("ui/actions/Properties Manager/Preview.png"))
propMgr.preview_btn.setIconSize(QSize(22,22))
propMgr.connect(propMgr.preview_btn,
SIGNAL("clicked()"),
propMgr.preview_btn_clicked)
propMgr.preview_btn.setToolTip("Preview")
TopRowBtnsHLayout.addWidget(propMgr.preview_btn)
# What's This (?) button.
propMgr.whatsthis_btn = buttonType(propMgr.TopRowBtnsFrame)
propMgr.whatsthis_btn.setIcon(
geticon("ui/actions/Properties Manager/WhatsThis.png"))
propMgr.whatsthis_btn.setIconSize(QSize(22,22))
propMgr.connect(propMgr.whatsthis_btn,
SIGNAL("clicked()"),
QWhatsThis.enterWhatsThisMode)
propMgr.whatsthis_btn.setToolTip("What\'s This Help")
TopRowBtnsHLayout.addWidget(propMgr.whatsthis_btn)
TopRowBtnsHLayout.addItem(HSpacer)
# Create Button Row
propMgr.pmTopRowBtns.addWidget(propMgr.TopRowBtnsFrame)
propMgr.pmVBoxLayout.addLayout(propMgr.pmTopRowBtns)
# Add What's This for buttons.
propMgr.done_btn.setWhatsThis("""<b>Done</b>
<p><img source=\"ui/actions/Properties Manager/Done.png\"><br>
Completes and/or exits the current command.</p>""")
propMgr.abort_btn.setWhatsThis("""<b>Cancel</b>
<p><img source=\"ui/actions/Properties Manager/Abort.png\"><br>
Cancels the current command.</p>""")
propMgr.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b>
<p><img source=\"ui/actions/Properties Manager/Restore.png\"><br>
Restores the defaut values of the Property Manager.</p>""")
propMgr.preview_btn.setWhatsThis("""<b>Preview</b>
<p><img source=\"ui/actions/Properties Manager/Preview.png\"><br>
Preview the structure based on current Property Manager settings.</p>""")
propMgr.whatsthis_btn.setWhatsThis("""<b>What's This</b>
<p><img source=\"ui/actions/Properties Manager/WhatsThis.png\"><br>
Click this option to invoke a small question mark that is attached to the mouse pointer,
then click on an object which you would like more information about.
A pop-up box appears with information about the object you selected.</p>""")
# Hide the buttons that shouldn't be displayed base on <showFlags>.
if not showFlags & pmDoneButton:
propMgr.done_btn.hide()
if not showFlags & pmCancelButton:
propMgr.abort_btn.hide()
if not showFlags & pmRestoreDefaultsButton:
propMgr.restore_defaults_btn.hide()
if not showFlags & pmPreviewButton:
propMgr.preview_btn.hide()
if not showFlags & pmWhatsThisButton:
propMgr.whatsthis_btn.hide()
return
class pmMessageGroupBox(QGroupBox, PropertyManager_common):
"""Creates a Message group box.
This class is used by the following Property Managers
(which are still not using the PropMgrBaseClass):
- Build Atoms
- Build Crystal
- Extrude
- Move
- Movie Player
- Fuse Chunks
Note: This class is temporary. It will be removed after the
PropMgrs in this list are converted to the PropMgrBaseClass.
Mark 2007-06-21
"""
expanded = True # Set to False when groupbox is collapsed.
defaultText = ""
# The default text that is displayed whenever the Property Manager is displayed.
setAsDefault = True
# Checked to determine if <defaultText> should be restored whenever the
# Property Manager is displayed.
def __init__(self,
parent,
title = ''):
QGroupBox.__init__(self)
if parent:
self.setParent(parent) #Fixed bug 2465 -- ninad 20070622
self.setAutoFillBackground(True)
self.setPalette(self.getPropMgrGroupBoxPalette())
self.setStyleSheet(self.getStyleSheet())
# Create vertical box layout
self.VBoxLayout = QVBoxLayout(self)
self.VBoxLayout.setMargin(pmMsgGrpBoxMargin)
self.VBoxLayout.setSpacing(pmMsgGrpBoxSpacing)
# Add title button to GroupBox
self.titleButton = self.getTitleButton(title, self)
self.VBoxLayout.addWidget(self.titleButton)
self.connect(self.titleButton,SIGNAL("clicked()"),
self.toggleExpandCollapse)
# Yellow MessageTextEdit
self.MessageTextEdit = QtGui.QTextEdit(self)
self.MessageTextEdit.setMaximumHeight(80) # 80 pixels height
self.MessageTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.VBoxLayout.addWidget(self.MessageTextEdit)
msg_palette = self.getMessageTextEditPalette()
self.MessageTextEdit.setPalette(msg_palette)
self.MessageTextEdit.setReadOnly(True)
# wrapWrapMode seems to be set to QTextOption.WrapAnywhere on MacOS,
# so let's force it here. Mark 2007-05-22.
self.MessageTextEdit.setWordWrapMode(QTextOption.WordWrap)
# These two policies very important. Mark 2007-05-22
self.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.MessageTextEdit.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.setWhatsThis("""<b>Messages</b>
<p>This prompts the user for a requisite operation and/or displays
helpful messages to the user.</p>""")
parent.MessageTextEdit = self.MessageTextEdit
self.hide()
def getTitleButton(self, title, parent=None, showExpanded=True): #Ninad 070206
""" Return the groupbox title pushbutton. The pushbutton is customized
such that it appears as a title bar to the user. If the user clicks on
this 'titlebar' it sends appropriate signals to open or close the
groupboxes 'name = string -- title of the groupbox
'showExpanded' = boolean .. NE1 uses a different background
image in the button's Style Sheet depending on the bool.
(i.e. if showExpanded = True it uses a opened group image '^')
See also: getGroupBoxTitleCheckBox , getGroupBoxButtonStyleSheet methods
"""
button = QPushButton(title, parent)
button.setFlat(False)
button.setAutoFillBackground(True)
button.setStyleSheet(self.getTitleButtonStyleSheet(showExpanded))
button.setPalette(self.getTitleButtonPalette())
#ninad 070221 set a non existant 'Ghost Icon' for this button
#By setting such an icon, the button text left aligns!
#(which what we want :-) )
#So this might be a bug in Qt4.2. If we don't use the following kludge,
#there is no way to left align the push button text but to subclass it.
#(could mean a lot of work for such a minor thing) So OK for now
button.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
return button
def getTitleButtonStyleSheet(self, showExpanded=True):
"""Returns the style sheet for a groupbox title button (or checkbox).
If <showExpanded> is True, the style sheet includes an expanded icon.
If <showExpanded> is False, the style sheet includes a collapsed icon.
"""
# Need to move border color and text color to top (make global constants).
if showExpanded:
styleSheet = "QPushButton {border-style:outset;\
border-width: 2px;\
border-color: " + pmGrpBoxButtonBorderColor + ";\
border-radius:2px;\
font:bold 12px 'Arial'; \
color: " + pmGrpBoxButtonTextColor + ";\
min-width:10em;\
background-image: url(" + pmGrpBoxExpandedImage + ");\
background-position: right;\
background-repeat: no-repeat;\
}"
else:
styleSheet = "QPushButton {border-style:outset;\
border-width: 2px;\
border-color: " + pmGrpBoxButtonBorderColor + ";\
border-radius:2px;\
font: bold 12px 'Arial'; \
color: " + pmGrpBoxButtonTextColor + ";\
min-width:10em;\
background-image: url(" + pmGrpBoxCollapsedImage + ");\
background-position: right;\
background-repeat: no-repeat;\
}"
return styleSheet
def toggleExpandCollapse(self):
"""Slot method for the title button to expand/collapse the groupbox.
"""
if self.expanded: # Collapse groupbox by hiding ahe yellow TextEdit.
# The styleSheet contains the expand/collapse icon.
styleSheet = self.getTitleButtonStyleSheet(showExpanded = False)
self.titleButton.setStyleSheet(styleSheet)
# Why do we have to keep resetting the palette?
# Does assigning a new styleSheet reset the button's palette?
# If yes, we should add the button's color to the styleSheet.
# Mark 2007-05-20
self.titleButton.setPalette(self.getTitleButtonPalette())
self.titleButton.setIcon(
geticon("ui/actions/Properties Manager/GHOST_ICON"))
self.MessageTextEdit.hide()
self.expanded = False
else: # Expand groupbox by showing the yellow TextEdit.
# The styleSheet contains the expand/collapse icon.
styleSheet = self.getTitleButtonStyleSheet(showExpanded = True)
self.titleButton.setStyleSheet(styleSheet)
# Why do we have to keep resetting the palette?
# Does assigning a new styleSheet reset the button's palette?
# If yes, we should add the button's color to the styleSheet.
# Mark 2007-05-20
self.titleButton.setPalette(self.getTitleButtonPalette())
self.titleButton.setIcon(
geticon("ui/actions/Properties Manager/GHOST_ICON"))
self.MessageTextEdit.show()
self.expanded = True
def getStyleSheet(self):
"""Return the style sheet for a groupbox. This sets the following
properties only:
- border style
- border width
- border color
- border radius (on corners)
The background color for a groupbox is set using getPalette()."""
styleSheet = "QGroupBox {border-style:solid;\
border-width: 1px;\
border-color: " + pmGrpBoxBorderColor + ";\
border-radius: 0px;\
min-width: 10em; }"
## For Groupboxs' Pushbutton :
##Other options not used : font:bold 10px;
return styleSheet
def insertHtmlMessage(self, text, setAsDefault=True,
minLines=4, maxLines=10,
replace=True):
"""Insert <text> (HTML) into the message groupbox.
<minLines> - The minimum number of lines (of text) to display in the TextEdit.
if <minLines>=0 the TextEdit will fit its own height to fit <text>. The
default height is 4 (lines of text).
<maxLines> - The maximum number of lines to display in the TextEdit widget.
<replace> should be set to False if you do not wish
to replace the current text. It will append <text> instead.
Shows the message groupbox if it is hidden.
"""
if setAsDefault:
self.defaultText = text
self.setAsDefault = True
if replace:
self.MessageTextEdit.clear()
if text:
self._setHeight(minLines, maxLines)
QTextEdit.insertHtml(self.MessageTextEdit, text)
self.show()
else:
# Hide the message groupbox if it contains no text.
self.hide()
def _setHeight(self, minLines=4, maxLines=8):
"""Set the height just high enough to display
the current text without a vertical scrollbar.
<minLines> is the minimum number of lines to
display, even if the text takes up fewer lines.
<maxLines> is the maximum number of lines to
diplay before adding a vertical scrollbar.
"""
if minLines == 0:
fitToHeight=True
else:
fitToHeight=False
# Current width of PropMgrTextEdit widget.
current_width = self.MessageTextEdit.sizeHint().width()
# Probably including Html tags.
text = self.MessageTextEdit.toPlainText()
text_width = self.MessageTextEdit.fontMetrics().width(text)
num_lines = text_width/current_width + 1
# + 1 may create an extra (empty) line on rare occasions.
if fitToHeight:
num_lines = min(num_lines, maxLines)
else:
num_lines = max(num_lines, minLines)
#margin = self.fontMetrics().leading() * 2 # leading() returned 0. Mark 2007-05-28
margin = 10 # Based on trial and error. Maybe it is pm?Spacing=5 (*2)? Mark 2007-05-28
new_height = num_lines * self.MessageTextEdit.fontMetrics().lineSpacing() + margin
if 0: # Debugging code for me. Mark 2007-05-24
print "--------------------------------"
print "Widget name =", self.objectName()
print "minLines =", minLines
print "maxLines =", maxLines
print "num_lines=", num_lines
print "New height=", new_height
print "text =", text
print "Text width=", text_width
print "current_width (of PropMgrTextEdit)=", current_width
# Reset height of PropMgrTextEdit.
self.MessageTextEdit.setMinimumSize(QSize(pmMinWidth * 0.5, new_height))
self.MessageTextEdit.setMaximumHeight(new_height)
# End of messageGroupBox class. ###################
def pmAddBottomSpacer(parent, vlayout, last=False):
"""Adds a vertical spacer to the bottom of <parent>, a group box.
<vlayout> is the VBoxLayout of the Property Manager.
<last> - Set to True if <parent> is the last (bottom) groupbox in
the Property Manager.
Note: There is a copy of this in every
"""
if last:
parent.bottom_spacer = \
QtGui.QSpacerItem(10, 0, \
QtGui.QSizePolicy.Fixed, \
QtGui.QSizePolicy.Expanding)
else:
parent.bottom_spacer = \
QtGui.QSpacerItem(10, pmGroupBoxSpacing, \
QtGui.QSizePolicy.Fixed, \
QtGui.QSizePolicy.Fixed)
vlayout.addItem(parent.bottom_spacer)
# ==
# Class PropertyManagerMixin is currently [when?] used by:
#
# - Build > Atoms (depositMode/MMKit)
# - Build > Crystal (cookieCutter)
# - Tools > Extrude (extrudeMode)
# - Tools > Fuse (fuseMode)
# - Tools > Move (modifyMode)
# - Simulator > Play Movie (movieMode)
#
# Once all these have been migrated to the new PropMgrBaseClass,
# this class can be removed permanently. Mark 2007-05-25
class PropertyManagerMixin(PropertyManager_common, SponsorableMixin):
"""Mixin class that provides methods common to various property managers (but not to PropMgrBaseClass)"""
def openPropertyManager(self, tab):
#tab = property manager widget
self.pw = self.w.activePartWindow()
self.pw.updatePropertyManagerTab(tab)
try:
tab.setSponsor()
except:
print "tab has no attribute 'setSponsor()' ignoring."
self.pw.featureManager.setCurrentIndex(self.pw.featureManager.indexOf(tab))
def closePropertyManager(self):
if not self.pw:
self.pw = self.w.activePartWindow()
self.pw.featureManager.setCurrentIndex(0)
try:
pmWidget = self.pw.propertyManagerScrollArea.widget()
pmWidget.update_props_if_needed_before_closing()
except:
if debug_flags.atom_debug:
msg1 = "Last PropMgr doesn't have method updatePropsBeforeClosing."
msg2 = " That is OK (for now, only implemented in GeometryGenerators)"
msg3 = "Ignoring Exception: "
print_compact_traceback(msg1 + msg2 + msg3)
pass
self.pw.featureManager.removeTab(self.pw.featureManager.indexOf(self.pw.propertyManagerScrollArea))
if self.pw.propertyManagerTab:
self.pw.propertyManagerTab = None
def toggle_groupbox(self, button, *things):
"""This is intended to be part of the slot method for clicking on an open/close icon
of a dialog GroupBox. The arguments should be the button (whose icon will be altered here)
and the child widgets in the groupbox whose visibility should be toggled.
"""
if things:
if things[0].isVisible():
styleSheet = self.getGroupBoxButtonStyleSheet(bool_expand = False)
button.setStyleSheet(styleSheet)
palette = self.getGroupBoxButtonPalette()
button.setPalette(palette)
button.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
for thing in things:
thing.hide()
else:
styleSheet = self.getGroupBoxButtonStyleSheet(bool_expand = True)
button.setStyleSheet(styleSheet)
palette = self.getGroupBoxButtonPalette()
button.setPalette(palette)
button.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
for thing in things:
thing.show()
else:
print "Groupbox has no widgets. Clicking on groupbox button has no effect."
return
def getMsgGroupBoxPalette(self): # note: not used by anything as of 070615
""" Return a palette for Property Manager message groupboxes.
"""
return self.getPalette(None,
QtGui.QPalette.Base,
pmMessageTextEditColor)
def getGroupBoxPalette(self):
""" Return a palette for Property Manager groupboxes.
This distinguishes the groupboxes in a property manager.
The color is slightly darker than the property manager background.
"""
#bgrole(10) is 'Windows'
return self.getPalette(None,
QtGui.QPalette.ColorRole(10),
pmGrpBoxColor)
def getGroupBoxButtonPalette(self):
""" Return a palette for the groupbox Title button.
"""
return self.getPalette(None,
QtGui.QPalette.Button,
pmGrpBoxButtonColor)
def getGroupBoxCheckBoxPalette(self):
""" Returns the background color for the checkbox of any groupbox
in a Property Manager. The color is slightly darker than the
background palette of the groupbox.
"""
palette = self.getPalette(None,
QtGui.QPalette.WindowText,
pmCheckBoxTextColor)
return self.getPalette(palette,
QtGui.QPalette.Button,
pmCheckBoxButtonColor)
def getGroupBoxStyleSheet(self):
"""Return the style sheet for a groupbox. Example border style, border
width etc. The background color for a groupbox is set separately"""
styleSheet = "QGroupBox {border-style:solid;\
border-width: 1px;\
border-color: " + pmGrpBoxBorderColor + ";\
border-radius: 0px;\
min-width: 10em; }"
## For Groupboxs' Pushbutton :
##Other options not used : font:bold 10px;
return styleSheet
def getGroupBoxTitleButton(self, name, parent = None, bool_expand = True): #Ninad 070206
""" Return the groupbox title pushbutton. The pushbutton is customized
such that it appears as a title bar to the user. If the user clicks on
this 'titlebar' it sends appropriate signals to open or close the
groupboxes 'name = string -- title of the groupbox
'bool_expand' = boolean .. NE1 uses a different background
image in the button's Style Sheet depending on the bool.
(i.e. if bool_expand = True it uses a opened group image '^')
See also: getGroupBoxTitleCheckBox , getGroupBoxButtonStyleSheet methods
"""
button = QtGui.QPushButton(name, parent)
button.setFlat(False)
button.setAutoFillBackground(True)
palette = self.getGroupBoxButtonPalette()
button.setPalette(palette)
styleSheet = self.getGroupBoxButtonStyleSheet(bool_expand)
button.setStyleSheet(styleSheet)
#ninad 070221 set a non existant 'Ghost Icon' for this button
#By setting such an icon, the button text left aligns!
#(which what we want :-) )
#So this might be a bug in Qt4.2. If we don't use the following kludge,
#there is no way to left align the push button text but to subclass it.
#(could mean a lot of work for such a minor thing) So OK for now
button.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
return button
def getGroupBoxButtonStyleSheet(self, bool_expand = True):
""" Returns the syle sheet for a groupbox title button (or checkbox)
of a property manager. Returns a string.
bool_expand' = boolean .. NE1 uses a different background image in the
button's Style Sheet depending on the bool.
(i.e. if bool_expand = True it uses a opened group image '^')
"""
# Need to move border color and text color to top (make global constants).
if bool_expand:
styleSheet = "QPushButton {border-style:outset;\
border-width: 2px;\
border-color: " + pmGrpBoxButtonBorderColor + ";\
border-radius:2px;\
font:bold 12px 'Arial'; \
color: " + pmGrpBoxButtonTextColor + ";\
min-width:10em;\
background-image: url(" + pmGrpBoxExpandedImage + ");\
background-position: right;\
background-repeat: no-repeat;\
}"
else:
styleSheet = "QPushButton {border-style:outset;\
border-width: 2px;\
border-color: " + pmGrpBoxButtonBorderColor + ";\
border-radius:2px;\
font: bold 12px 'Arial'; \
color: " + pmGrpBoxButtonTextColor + ";\
min-width:10em;\
background-image: url(" + pmGrpBoxCollapsedImage + ");\
background-position: right;\
background-repeat: no-repeat;\
}"
return styleSheet
def getGroupBoxTitleCheckBox(self, name, parent = None, bool_expand = True):#Ninad 070207
""" Return the groupbox title checkbox . The checkbox is customized such that
it appears as a title bar to the user. If the user clicks on this 'titlebar' it sends
appropriate signals to open or close the groupboxes (and also to check or uncheck the box.)
'name = string -- title of the groupbox
'bool_expand' = boolean .. NE1 uses a different background image in the button's
Style Sheet depending on the bool. (i.e. if bool_expand = True it uses a opened group image '^')
See also: getGroupBoxTitleButton method.
"""
checkbox = QtGui.QCheckBox(name, parent)
checkbox.setAutoFillBackground(True)
palette = self.getGroupBoxCheckBoxPalette()
checkbox.setPalette(palette)
styleSheet = self.getGroupBoxCheckBoxStyleSheet(bool_expand)
checkbox.setStyleSheet(styleSheet)
checkbox.setText(name)
return checkbox
def getGroupBoxCheckBoxStyleSheet(self, bool_expand = True):
""" Returns the syle sheet for a groupbox checkbox of a property manager
Returns a string.
bool_expand' = boolean .. NE1 uses a different background image in the button's
Style Sheet depending on the bool. (i.e. if bool_expand = True it uses a opened group image '^')
"""
if bool_expand:
styleSheet = "QCheckBox {\
color: " + pmGrpBoxButtonTextColor + ";\
font: bold 12px 'Arial';\
}"
else:
styleSheet = "QCheckBox {\
color: " + pmGrpBoxButtonTextColor + ";\
font: bold 12px 'Arial';\
}"
# Excluded attributes (has issues)--
##background-image: url(ui/actions/Properties Manager/Opened_GroupBox.png);\
##background-position: right;\
##background-repeat: no-repeat;\
return styleSheet
def hideGroupBox(self, groupBoxButton, groupBoxWidget):
"""Hide a groupbox (this is not the same as 'toggle' groupbox)"""
groupBoxWidget.hide()
styleSheet = self.getGroupBoxButtonStyleSheet(bool_expand = False)
groupBoxButton.setStyleSheet(styleSheet)
palette = self.getGroupBoxButtonPalette()
groupBoxButton.setPalette(palette)
groupBoxButton.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
def showGroupBox(self, groupBoxButton, groupBoxWidget):
"""Show a groupbox (this is not the same as 'toggle' groupbox)"""
if not groupBoxWidget.isVisible():
groupBoxWidget.show()
styleSheet = self.getGroupBoxButtonStyleSheet(bool_expand = True)
groupBoxButton.setStyleSheet(styleSheet)
palette = self.getGroupBoxButtonPalette()
groupBoxButton.setPalette(palette)
groupBoxButton.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
def ok_btn_clicked(self):
self.w.toolsDone()
pass
def abort_btn_clicked(self):
self.w.toolsCancel()
pass
def restore_defaults_btn_clicked(self):
pass
def preview_btn_clicked(self):
pass
pass # end of class PropertyManagerMixin
# end
| NanoCAD-master | cad/src/outtakes/PropertyManagerMixin.py |
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
depositMode.py -- Build Atoms mode.
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
TODO: As of 2007-01-04
- Items listed in BuildAtoms_GraphicsMode
- Items listed in Select_GraphicsMode.py
History:
depositMode.py Originally by Josh Hall and then significantly modified by
several developers.
In January 2008, the old depositMode class was split into new Command and
GraphicsMode parts and the these classes were moved into their own module
[ See BuildAtoms_Command.py and BuildAtoms_GraphicsMode.py]
"""
from commands.BuildAtoms.BuildAtoms_Command import BuildAtoms_basicCommand
from commands.BuildAtoms.BuildAtoms_GraphicsMode import BuildAtoms_basicGraphicsMode
class depositMode( BuildAtoms_basicCommand,
BuildAtoms_basicGraphicsMode):
# this class (and file) is no longer needed except by testmode [as of before 080812]
"""
Build Atoms Mode (hybrid object which encompasses both - command and
graphicsMode objects as self)
"""
def __init__(self, commandSequencer):
glpane = commandSequencer.assy.glpane
BuildAtoms_basicCommand.__init__(self, commandSequencer)
# was just basicCommand in original
BuildAtoms_basicGraphicsMode.__init__(self, glpane)
# was just basicGraphicsMode in original
return
# (the rest would come from basicMode if post-inheriting it worked,
# or we could split it out of basicMode as a post-mixin to use there
# and here)
def __get_command(self):
return self
command = property(__get_command)
def __get_graphicsMode(self):
return self
graphicsMode = property(__get_graphicsMode)
| NanoCAD-master | cad/src/outtakes/depositMode.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
test_modelTreeGui.py - test code for modelTreeGui.py (non-working)
@author: Will
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
update, bruce 081215:
This test code has not worked for a long time.
To run it at all (in its old location at the end of modelTreeGui.py),
it's necessary to use ExecSubDir (see comment below for details).
Then, the test_api call below, specifically, has bugs:
- it might reveal a bug in ExecSubDir.py, which fails to modify argv
to remove itself as an argument and fix argv[0] to the expected value;
- the test_api code fails due to no args to __init__ in api class.
But commenting it out (and running with /ExecSubDir.py modelTree/modelTreeGui.py)
also fails:
AssertionError: too early to call image_directory()
which is due to a recent new requirement in initializing NE1.
There are other similar recent requirements.
All could be solved, by adding some startup code to be called by all test code,
but since I doubt this test code works even once they are solved (since it wasn't
maintained across major finishings and rewrites of this module), it's not worth
the time for now.
So I will move it into an outtakes file, from which it could be
revived and fixed later if desired. I will not bother to port the
imports from that file. Note that that file may be split into several
smaller ones in the near future.
"""
#### TODO: to figure out imports -- this code used to be at the end of the module modelTreeGui.py ####
# the only ones here are the ones no longer used in the main file after this was removed
from PyQt4.Qt import QMainWindow
from PyQt4.Qt import QGroupBox
from PyQt4.Qt import QApplication
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QPushButton
from PyQt4.Qt import QVBoxLayout
from PyQt4.Qt import QHBoxLayout
class TestNode(Node_api):
# WARNING: this test code has not been rerun or actively maintained
# since modelTreeGui rewrite circa May 07 (or some time before).
# And bruce 071025 moved drop_on and drop_on_ok from Node_api
# to MT_DND_Target_API, but made no attempt to update this test code
# except by removing those methods from it and Node_api, and wrapping
# the node they're called on below in the same way as in real code above.
def __init__(self, name, parent = None, icon = None, icon_hidden = None):
self.open = False #bruce 070508 added this for api compliance; it's not otherwise used by test code
self.hidden = False
self._disabled = False
self.name = name
self.icon = icon
self.icon_hidden = icon_hidden
class FakeAssembly:
def update_parts(self):
pass
self.assy = FakeAssembly() #bruce 070511 comment: this appears to never be used
self.parentNode = parent
if parent is not None:
parent.members.append(self)
self.members = [ ]
self.picked = False
if _DEBUG0:
self._verify_api_compliance()
def showTree(self, indent = 0):
"""
handy diagnostic
"""
s = (indent * '\t') + repr(self)
if self.picked: s += ' PICKED'
print s
for ch in self.members:
ch.showTree(indent + 1)
# beginning of official API
def pick(self):
self.picked = True
def unpick(self):
self.picked = False
def apply2picked(self, func):
if self.picked:
func(self)
for x in self.members:
x.apply2picked(func)
## def drop_on_ok(self, drag_type, nodes):
## import sys, traceback
## for node in nodes:
## # don't drop stuff that's already here
## if node in self.members:
## traceback.print_stack(file = sys.stdout)
## print self, nodes, node, self.members
## print 'node is in children already'
## return False, 'node is in children already'
## # We can't drop things on chunks or jigs
## if self.name.startswith("Chunk"):
## traceback.print_stack(file = sys.stdout)
## print self, node, self.members
## print 'cannot drop on a chunk'
## return False, 'cannot drop on a chunk'
## if self.name.startswith("Jig"):
## traceback.print_stack(file = sys.stdout)
## print self, node, self.members
## print 'cannot drop on a jig'
## return False, 'cannot drop on a jig'
## return True, None
## def drop_on(self, drag_type, nodes):
## previous_parents = { }
## for node in nodes:
## if drag_type == 'copy':
## node = node.clone()
## previous_parents[node] = node.parentNode
## self.members.append(node)
## node.parentNode = self
## node.unpick()
## if drag_type == 'move':
## for node in nodes:
## previous_parents[node].members.remove(node)
## return [ ]
def node_icon(self, display_prefs):
# read up on display_prefs?
if self.hidden:
return self.icon_hidden
else:
return self.icon
def is_disabled(self):
return self._disabled
# end of official API
def clone(self):
newguy = self.__class__(self.name + "-copy", None, self.icon, self.icon_hidden)
newguy.hidden = self.hidden
newguy._disabled = self._disabled
newguy.members = self.members[:]
return newguy
def MT_kids(self, item_prefs = {}):
return self.members
def __repr__(self):
return "<Node \"%s\">" % self.name
class TestClipboardNode(TestNode):
def __init__(self, name):
TestNode.__init__(self, name)
self.iconEmpty = QPixmap("../images/clipboard-empty.png")
self.iconFull = QPixmap("../images/clipboard-full.png")
self.iconGray = QPixmap("../images/clipboard-gray.png")
if _DEBUG0:
self._verify_api_compliance()
def node_icon(self, display_prefs):
if self.hidden: # is the clipboard ever hidden??
return self.iconGray
elif self.members:
return self.iconFull
else:
return self.iconEmpty
class TestNe1Model(ModelTree_api):
def __init__(self):
self.untitledNode = TestNode("Untitled", None,
QPixmap("../images/part.png"))
self.clipboardNode = TestClipboardNode("Clipboard")
if _DEBUG0:
self._verify_api_compliance()
def get_topnodes(self):
return [self.untitledNode, self.clipboardNode]
def make_cmenuspec_for_set(self, nodeset, optflag):
for node in nodeset:
def thunk(str):
def _thunk(str=str):
print str
return _thunk
if isinstance(node, TestNode):
disableTuple = ('Disable', lambda node=node: self.cm_disable(node))
if node.name.startswith("Chunk"):
disableTuple += ('disabled',)
return [('Copy', lambda node=node: self.cm_copy(node)),
('Cut', lambda node=node: self.cm_cut(node)),
('Hide', lambda node=node: self.cm_hide(node)),
disableTuple,
None,
('Delete', lambda node=node: self.cm_delete(node))]
else:
return [('A', thunk('A')),
('B', thunk('B')),
None,
('C', thunk('C'), 'disabled'),
('D', thunk('D'))]
return [ ]
def complete_context_menu_action(self):
# unpick all nodes
for x in self.get_topnodes():
x.apply2picked(lambda node: node.unpick())
self.view.mt_update()
def cm_copy(self, node):
nodelist = self.view.topmost_selected_nodes()
if node not in nodelist:
nodelist.append(node)
Node_as_MT_DND_Target(self.clipboardNode).drop_on('copy', nodelist)
self.complete_context_menu_action()
def cm_cut(self, node):
nodelist = self.view.topmost_selected_nodes()
if node not in nodelist:
nodelist.append(node)
Node_as_MT_DND_Target(self.clipboardNode).drop_on('move', nodelist)
self.complete_context_menu_action()
def cm_disable(self, node):
node._disabled = not node._disabled
self.complete_context_menu_action()
def cm_hide(self, node):
node.hidden = not node.hidden
self.complete_context_menu_action()
def cm_delete(self, node):
node.parentNode.members.remove(node)
self.complete_context_menu_action()
class TestGLPane:
def gl_update(self):
print "GLPane update"
class TestMainWindow:
def __init__(self):
self.glpane = TestGLPane()
self.orientationWindow = None
class TestWrapper(QGroupBox):
def __init__(self):
QGroupBox.__init__(self)
self.treemodel = treemodel = TestNe1Model()
self.view = view = ModelTreeGui(TestMainWindow(), "Model tree", treemodel, self)
view.mt_update()
self.chunkNum = 2
self.gbox = QGroupBox()
vl = QVBoxLayout(self)
vl.setSpacing(0)
vl.setMargin(0)
vl.addWidget(self.view)
self.buttonLayout = hl = QHBoxLayout()
hl.setSpacing(0)
hl.setMargin(0)
vl.addLayout(hl)
self.buttonNum = 1
for func in (self.addmol, self.addjig, self.selected):
self.addButton(func)
def addButton(self, func):
button = QPushButton(func.__doc__)
setattr(self, "button%d" % self.buttonNum, button)
self.buttonNum += 1
self.buttonLayout.addWidget(button)
self.connect(button, SIGNAL('clicked()'), func)
def addIconButton(self, icon, func):
button = QPushButton()
button.setIcon(icon)
setattr(self, "button%d" % self.buttonNum, button)
self.buttonNum += 1
self.buttonLayout.addWidget(button)
self.connect(button, SIGNAL('clicked()'), func)
def addsomething(self, what):
if what == "Chunk":
icon = QPixmap('../images/moldefault.png')
icon_h = QPixmap('../images/moldefault-hide.png')
else:
icon = QPixmap('../images/measuredistance.png')
icon_h = QPixmap('../images/measuredistance-hide.png')
chunk = TestNode("%s-%d" % (what, self.chunkNum),
self.treemodel.untitledNode, icon, icon_h)
self.chunkNum += 1
self.view.mt_update()
def addmol(self):
"""
Chunk
"""
# This is equivalent to Part.addmol() in part.py
self.addsomething("Chunk")
def addjig(self):
"""
Jig
"""
self.addsomething("Jig")
def selected(self):
"""
Selected
"""
print self.view.topmost_selected_nodes()
# ===
def test_api():
# Test API compliance. If we remove all the functionality, pushing buttons shouldn't raise any
# exceptions.
global ModelTreeGui
## global _our_QItemDelegate, _QtTreeModel
ModelTreeGui = ModelTreeGui_api # in test code
## del _our_QItemDelegate, _QtTreeModel
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.wrapper = TestWrapper()
self.setCentralWidget(self.wrapper)
self.resize(200, 300)
self.wrapper.show()
if __name__ == "__main__":
# To run this test code:
# % cd cad/src
# then
# % ./ExecSubDir.py modelTree/modelTreeGui.py
# --or--
# % python ExecSubDir.py modelTree/modelTreeGui.py
import sys
if len(sys.argv) > 1:
test_api()
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
# end
| NanoCAD-master | cad/src/outtakes/test_modelTreeGui.py |
def selection_changed(self): #bruce 070925 [not used outside this file as of 080731, except in docstrings/comments]
return
def selobj_changed(self): #bruce 071116 [not mentioned outside this file as of 080731] 8
return
def view_changed(self): #bruce 071116 [not mentioned outside this file as of 080731]8
return
def something_changed(self): #bruce 071116 [not used outside this file as of 080731, except in comments]
return
def selection_changed(self): #bruce 070925 added this to Command API
"""
Subclasses should extend this (or make sure their self.propMgr defines
it) to check whether any selection state has changed that should be
reflected in their UI, and if so, update their UI accordingly.
"""
### REVIEW: Decide whether highlighting (selobj) is covered by it
# (guess yes -- all kinds of selection).
### maybe: call when entering/resuming the command, and say so,
# and document order of call relative to update_gui. And deprecate
# update_gui or make it more efficient. And add other methods that only
# use usage-tracked state and are only called as needed.
if self.propMgr:
if hasattr( self.propMgr, 'selection_changed'):
self.propMgr.selection_changed()
return
def selobj_changed(self):
"""
Called whenever the glpane.selobj (object under mouse)
may have changed, so that self can do UI updates in response to that.
"""
if self.propMgr:
if hasattr( self.propMgr, 'selobj_changed'):
self.propMgr.selobj_changed()
return
def view_changed(self):
"""
Called whenever the glpane's view (view center, direction, projection)
may have changed, so that self can do UI updates in response to that.
"""
# REVIEW: I'm not sure this gets called for Ortho/Perspective change,
# but it should be! [bruce 071116]
if self.propMgr:
if hasattr( self.propMgr, 'view_changed'):
self.propMgr.view_changed()
return
def something_changed(self):
"""
Called once, immediately after any or all of the methods
model_changed, selection_changed, selobj_changed, or view_changed
were called.
"""
if self.propMgr:
if hasattr( self.propMgr, 'something_changed'):
self.propMgr.something_changed()
return
_last_model_change_counter = None
_last_selection_change_counter = None
_last_selobj = -1 # not None, since that's a legal value of selobj
_last_view_change_counter = None
def state_may_have_changed_OBSOLETE(self): #bruce 070925 added this to command API; update 080731: WILL BE REVISED SOON
"""
Call whichever we need to of the methods
model_changed, selection_changed, selobj_changed, view_changed,
in that order. The need is determined by whether the associated
change counters or state has changed since this method
(state_may_have_changed) was last called on self.
Then if any of those was called, also call something_changed.
This permits subclasses which just want to update after any change
to define only one method, and be sure it's not called more than
once per change. Or they can set specific change flags in the
specific change methods, and then respond to those all at once
or in a different order, in something_changed.
Note: this method should not normally be overridden by subclasses.
Note: the "only as needed" aspect is NIM, except when an
experimental debug_pref is set, but it should become the usual case.
FYI: This is called by env.do_post_event_updates() by a registered
"post_event_ui_updater" set up by MWsemantics. [still true 080731]
"""
if debug_pref("call model_changed (etc) only when needed?",
Choice_boolean_False,
## non_debug = True,
#bruce 080416 hide this since the commands can't yet
# handle it properly, so it causes bugs
# (this change didn't make it into .rc2)
prefs_key = True):
### experimental, but will become the usual case soon [bruce 071116]:
# call each method only when needed, using assy change counters, and a selobj test.
counters = self.assy.all_change_counters()
model_change_counter = counters[0] # MAYBE: make assy break them out for us?
selection_change_counter = counters[1] # note: doesn't cover selobj changes
view_change_counter = counters[2]
selobj = self.glpane.selobj
something_changed = False # will be updated if something changed
# the following order must be maintained,
# so that updating methods can assume it:
if model_change_counter != self._last_model_change_counter:
self._last_model_change_counter = model_change_counter
self.model_changed()
something_changed = True
if selection_change_counter != self._last_selection_change_counter:
self._last_selection_change_counter = selection_change_counter
self.selection_changed()
something_changed = True
if selobj is not self._last_selobj:
self._last_selobj = selobj
self.selobj_changed() # will be renamed
something_changed = True
if view_change_counter != self._last_view_change_counter:
self._last_view_change_counter = view_change_counter
self.view_changed()
something_changed = True
if something_changed:
self.something_changed()
pass
else:
# current bad code: always call every method.
self.model_changed()
self.selection_changed()
self.selobj_changed()
self.view_changed()
self.something_changed()
return # end of an OBSOLETE method
| NanoCAD-master | cad/src/outtakes/model_changed-outtakes.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
TreeView.py -- NO LONGER USED IN Qt4 NE1
-- display and update, for a tree widget based on QTreeView,
and meant to display Nodes (with interface and semantics as in Utility.py).
Assumes each node is shown in at most one place in the widget.
This could in theory be changed (see code for details).
$Id$
History: modelTree.py was originally written by some combination of
Huaicai, Josh, and Mark. Bruce (Jan 2005) reorganized its interface with
Node and Group and their subclasses (Utility.py and other modules)
and rewrote a lot of the model-tree code (to fix bugs and add features),
and split it into three modules:
- TreeView.py (display and update),
- TreeWidget.py (event handling, and some conventions suitable for
all our tree widgets, if we define other ones), and
- modelTree.py (customized for showing a "model tree" per se).
"""
assert 0, "TreeView.py is NO LONGER USED IN Qt4 NE1" #bruce 070503 Qt4
debug_painting = 0 ###@@@ DO NOT COMMIT with 1
debug_mt_updates = 0 ###@@@ DO NOT COMMIT with 1
debug_prints = 0 # whether atom_debug enables dprint; ok to commit with 0 or 1
###@@@ some of these imports are only needed by subclasses
from PyQt4.Qt import *
from constants import *
from chem import *
from jigs import *
from Utility import *
from foundation.Group import Group
import sys, os, time
from utilities import debug_flags
from qt4transition import *
class ModelTreeItem(QItemDelegate):
def __init__(self, name, parent, node):
QItemDelegate.__init__(self)
self.parentItem = parent
self.name = name
self.object = node
self.icon = None
self.childItems = [ ]
def __repr__(self):
return "<ModelTreeItem@%x \"%s\">" % (id(self), self.name)
def text(self, column):
raise Exception()
def setIcon(self, icon):
self.icon = icon
def row(self):
try:
return self.parentItem.childItems.index(self)
except:
return 0
def appendChild(self, x):
self.childItems.append(x)
def paint(self, painter, option, index):
item = index.internalPointer()
x, y = option.rect.x(), option.rect.y()
selected = (index in self.view.selectedIndexes())
if selected: # before
background = painter.background()
backgroundMode = painter.backgroundMode()
painter.setBackground(self.view.palette().highlight())
painter.setBackgroundMode(Qt.OpaqueMode)
if item.object.is_disabled(): # before
painter.shear(0, -0.5)
painter.translate(0.5 * y + 4, 0.0)
painter.drawPixmap(x, y, item.icon.pixmap(16, 16))
painter.drawText(x + 20, y + 12, item.name)
if item.object.is_disabled(): # after
painter.translate(-0.5 * y - 4, 0.0)
painter.shear(0, 0.5)
if selected: # after
painter.setBackground(background)
painter.setBackgroundMode(backgroundMode)
def _paint(self, painter, option, index):
item = index.internalPointer()
x, y = option.rect.x(), option.rect.y()
# What's failing here is not the display mechanism. Set this flag
# to True and all distance measurement jigs will be shown as disabled.
# The problem is with the context menu in modelTree.py, which is not
# doing the right thing with the cm_disable method somehow. The 'Disable'
# option appears in the context menu, but when you choose it, cm_disable
# does not get called, as verified by putting a print statement in it.
TEST_TO_SEE_IF_DISABLED_DISPLAY_WORKS = False
if TEST_TO_SEE_IF_DISABLED_DISPLAY_WORKS:
if item.name.startswith("Distance"):
def is_disabled():
return True
item.object.is_disabled = is_disabled
if item.object.is_disabled():
# Apply shear or other effects for "Hidden" and "Disabled" and "Selected"
painter.shear(0, -0.5)
painter.translate(0.5 * y + 4, 0.0)
if item.icon is not None:
painter.drawPixmap(x, y, item.icon.pixmap(16, 16))
painter.drawText(x + 20, y + 12, item.name)
painter.translate(-0.5 * y - 4, 0.0)
painter.shear(0, 0.5)
else:
if item.icon is not None:
painter.drawPixmap(x, y, item.icon.pixmap(16, 16))
painter.drawText(x + 20, y + 12, item.name)
def pr(self, indent=""):
print indent, self
for x in self.childItems:
x.pr(indent + " ")
####################################################################
class ModelTreeModel(QAbstractItemModel):
def __init__(self, rootItem=None):
QAbstractItemModel.__init__(self)
if rootItem is None:
rootItem = ModelTreeItem('Model Tree', None, None)
self.rootItem = rootItem
def veryShallowClone(self):
#
# This is part of the magic to UPDATING the model tree. We
# clone the model, and call setModel on the new guy. We can
# use a very shallow clone for this, the QTreeView only needs
# to see the pointer change.
#
return ModelTreeModel(self.rootItem)
def pr(self):
print self
self.rootItem.pr(" ")
# The following methods are the the official API required by
# QTreeView's idea of how QAbstractItemModel should work.
def columnCount(self, parent):
return 1
def data(self, index, role):
if not index.isValid():
return QVariant()
if role != Qt.DisplayRole:
return QVariant()
item = index.internalPointer()
return QVariant(item.name)
def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.rootItem.name)
return QVariant()
def index(self, row, column, parent):
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
if not hasattr(parentItem, 'childItems'):
return QModelIndex()
if row >= len(parentItem.childItems):
return QModelIndex()
childItem = parentItem.childItems[row]
if childItem:
return self.createIndex(row, column, childItem)
else:
return QModelIndex()
def parent(self, index):
if not index.isValid():
return QModelIndex()
childItem = index.internalPointer()
if not hasattr(childItem, 'parentItem'):
return self.createIndex(0, 0, childItem)
parentItem = childItem.parentItem
if parentItem == self.rootItem:
return QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent):
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return len(parentItem.childItems)
##################################
class TreeView(QTreeView):
needs_update_state = 0
initialized = 0 ####@@@@ review use of this here vs in subclasses
def __init__(self, parent, win, name = None, columns = ["node tree"], size = (100, 560)): ###@@@ review all init args & instvars, here vs subclasses
"""Create a TreeView (superclasses include QTreeView, QScrollView, QWidget).
parent is the Qt widget parent.
win (required) is our main window, stored in self.win
and used for debug menu (by some subclasses).
and for history messages (by subclasses -- not sure if also by this class).
name is used by Qt as the widget name. #k
columns is a list of column names (error if not at least one, if it's supplied).
Note: we create all columns requested, but the present implem is only
known to work for one column; some code in it only bothers trying to
support one column (e.g. it assumes everything should be done only in column 0).
"""
assert False # we shouldn't be using TreeWidget or TreeView any more
self.win = win
self._node_items = {}
QTreeView.__init__(self,parent) ###@@@ would any wflags be appropriate?
# try doing these first, but if that fails, do them after columns are made [as before]:
qt4skipit('self.setSorting(-1)')
self.setRootIsDecorated(1)
qt4skipit('self.setShowSortIndicator(0) # [this used to be done after setResizePolicy]')
#self.columns = columns
self.setItemsExpandable(True)
self.model = model = ModelTreeModel()
model.rootItem.view = self
self.setModel(model)
self.setItemDelegate(model.rootItem)
self.expandAll()
self.setSelectionMode(self.MultiSelection)
## self.addColumn("col2") # experiment - worked, but resulted in unwanted
## # sort indicator in col2 (with redraw bugs) [see QHeader in Qt docs?]
## ... might work better if done after we've turned off sorting.
qt4todo('self.header().setClickEnabled(0, self.header().count() - 1) #k what\'s this?')
# Qt doc says it's turning off the clicked signal for clicks in a certain
# section header (which one? I don't know if count() is 1 or 2 for our one column.)
# [some of the following might belong in a subclass or need to be influenced by one:]
qt4skipit('self.setGeometry(QRect(0, 0, size[0], size[1]))')
self.setMaximumWidth(200)
# make a change needed by Geoff Leach [see his mail to cad 050304],
# needed (at least back then) on his Linux system and/or Qt/PyQt installation
# (this relates to some reported bug whose bug number I forget)
# [bruce 050408]
self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Expanding))
qt4skipit('self.setShowToolTips(True)')
# bruce 050109 added this; but it doesn't seem to work
###@@@ where is item.setExpandable? implicit??
# this is not safe to do here -- subclasses need to do it themselves!
# if they forget, the symptom might be that no updates seem to happen.
## self.initialized = 1
## self.mt_update()
return # from TreeView.__init__
# invalidation function for use by external code
# (and by some internal code in subclasses)
def expandAll(self):
#
# With Qt 4.2, QTreeView will have its own expandAll method.
#
modelIndex = QModelIndex()
while True:
self.expand(modelIndex)
modelIndex = self.indexBelow(modelIndex)
if modelIndex.row() == -1:
return
def itemAt(self, qpoint):
# emulate the equivalent function for QTreeView
index = self.indexAt(qpoint)
item = index.internalPointer()
assert isinstance(item, ModelTreeItem)
return item
def visualItemRect(self, item):
# get the index for this item
index = self.model.createIndex(0, 0)
while True:
if index.internalPointer() == item:
return self.visualRect(index)
if index.row() == -1:
# item wasn't found
assert False
index = self.indexBelow(index)
def mt_update(self, nodetree = None): ###@@@ review name of this function, whether subclasses need to override it
"""External code (or event bindings in a subclass, if they don't do enough repainting themselves)
should call this when it might have changed any state that should
affect what's shown in the tree. (Specifically: the ordering or grouping of nodes,
or the icons or text they should display, or their open or selected state.) (BTW external
code probably has no business changing node.open since it is slated to become a tree-
widget-specific state in the near future.)
If these changes are known to be confined to a single node and its children,
that node can be passed as a second argument as a possible optimization
(though as of 050113 the current implem does not take advantage of this).
"""
if debug_mt_updates:
print "debug_mt_updates: mt_update called"
self.needs_update_state = 1 # we'll respond to this in our custom method during the next paintEvent
if not self.updatesEnabled():
if debug_flags.atom_debug:
print_compact_stack("atom_debug: stack in mt_update when not isUpdatesEnabled: ")
# Force a repaint by changing the pointer to the model, using a shallow clone.
self.model = self.model.veryShallowClone()
self.model.rootItem.view = self
self.setModel(self.model)
self.expandAll()
# debugging functions [might as well keep the commented-out ones around for awhile]
_last_dprinttime_stamp = None
def dprinttime(self):
"call this to print a timestamp before every debug line for which the same time was never before printed"
if not debug_prints: return
if not debug_flags.atom_debug: return
import time
stamp = time.asctime() #e improve
if stamp != self._last_dprinttime_stamp:
print
print stamp
self._last_dprinttime_stamp = stamp
return
def dprint(self, msg):
if not debug_prints: return
if debug_flags.atom_debug:
self.dprinttime()
print msg
return
# update-related functions, and related event-processing
# (not user input events -- those should be defined in subclasses)
# (###@@@ #e though we might want to override them here to mask QTreeView from seeing them -- but maybe no need)
def updateContents(self):
if debug_prints:
self.dprinttime()
print "fyi: modelTree.updateContents() called (by Qt, maybe by triggerUpdate)"
print_compact_stack("stack in updateContents(): ")
self.update()
def resize(self): #k does this get called? no.
if debug_prints:
self.dprinttime()
print "fyi: modelTree.resize() called (by Qt, presumably)"
print_compact_stack("stack in resize(): ")
return QTreeView.resize(self)
###@@@ move this? for eventual use, into a subclass, but for debug use, keep a copy here...
def drawbluething(self, painter, pos = (0,0), color = Qt.blue): # bruce 050110 taken from my local canvas_b2.py
"[for debugging] draw a recognizable symbol in the given QPainter, at given position, of given color"
p = painter # caller should have called begin on the widget, assuming that works
p.setPen(QPen(color, 3)) # 3 is pen thickness
w,h = 100,9 # bbox rect size of what we draw (i think)
x,y = pos # topleft of what we draw
p.drawEllipse(x,y,h,h)
fudge_up = 1 # 1 for h = 9, 2 for h = 10
p.drawLine(x+h, y+h/2 - fudge_up, x+w, y+h/2 - fudge_up)
def paintEvent(self, event):
"""[This (viewportPaintEvent) turns out to be the main redrawing event for a QTreeView (in Qt3) --
not that you can tell that from the Qt docs for it.
"""
self.update_state_iff_needed(event)
return QTreeView.paintEvent(self, event)
def update_state_iff_needed(self, event):
if self.needs_update_state and self.initialized:
# new code 050110, see if it fixes any bugs -- defer state updates
# (but should we instead do it in updateContents so it happens before that?? and/or do that here??) ###@@@ did neither for now
try:
self.needs_update_state = 0 # in case of exception
self.update_state(event) # used to be mt_update; event is not really needed i think
self.needs_update_state = 0 # in case of bug that sets this during that call
# [not sure this is good, but might avoid "infrepeat"]
#e also call updateContents now? let's try it, see if it helps Group formation update bug:
self.updateContents() ####k syntax and doc, for both qlistview and qscrollview ####@@@@
except:
self.dprinttime()
print_compact_traceback("exception in update_state() or updateContents(): ")
self.repaint()
###@@@ move this comment down below:
# main tree-remaking function (runs more often than it would need to in a more incremental implem)
# bruce 050107 renamed this 'update' -> 'mt_update';
# then bruce 050110 renamed it 'update_state' and made it
# no longer public, but called inside paintEvent(?)
# when mt_update records the need for this
def update_state(self, paintevent):
"""[private]
Rebuild the tree of ModelTreeItems. Details in update_state_0 docstring.
[no longer named update, since that conflicts with QWidget.update]
"""
# Qt doc makes it clear (well, at least deducible)
# that disabling updates is not redundant here,
# and it says other things which lead me to guess
# that it might avoid infrecur from repaint by QTreeView,
# and even if not, might reduce screen flicker or other problems.
if debug_mt_updates:
print "debug_mt_updates: update_state called"
old_UpdatesEnabled = self.updatesEnabled()
if not old_UpdatesEnabled:
self.dprint( "atom_debug: not old_UpdatesEnabled") # error?
self.setUpdatesEnabled( False)
try:
self.update_state_0( paintevent)
finally:
self.setUpdatesEnabled( old_UpdatesEnabled)
self.update() # might cause infrepeat... try it anyway [seems to be ok]
#e should be no need to do an update right here, since we're only
# called when a repaint is about to happen! But an updateContents
# might be good, here or in the sole caller or grandcaller. ###@@@
if debug_mt_updates:
print "debug_mt_updates: update_state returning normally"
return
def update_state_0( self, paintevent):
"""[private]
Build or rebuild a new tree of ModelTreeItems in this widget
corresponding to the node tree of the current model; ###@@@ how does subclass tell us where to look for root nodes?
assume updates are disabled in this widget.
(#e Someday we might do this incrementally, ie. rebuild only part of the tree
depending on what has been invalidated or is measured now to be invalid,
though this is not done as of 050120. Relatedly, someday we might not build
items for all hidden children (items whose parent items are closed), but
for now we do.)
"""
del paintevent
# heavily revised by bruce circa 050109 [from the version called mt_update]
# and split into this method and one or more subclass methods, bruce 050120
# record the current scroll position so it can later be set to something similar
qt4todo('self.scrollpos = self.viewportToContents(0,0)')
#self.clear() # this destroys all our ModelTreeItems!
self.clear_nodeItems() # and this makes sure we don't still try to update them.
# As of 050113 this is still the only place we delete listview items.
# We might do this more incrementally in the future,
# for nodes whose kid order or set of kids changed --
# though as far as I know, this won't fix bugs, it's just an optimization.
# We don't yet take much care to avoid old node.tritem pointing to
# deleted list items! (Though current code won't experience this except
# when it has bugs.) If those are ever used it causes a Qt exception.
# This can be fixed when node.tritem is replaced with a
# per-treewidget dict from nodes to their tree items...
# as has now been done [050119], with self.nodeItem().
listview = self # (would be self.widget if we were a megawidget)
# subclass supplies one or more root nodes for the tree
# [should be ok if this list is non-constant, but that's untested as of 050120]
self.topnodes = self.get_topnodes()
self.topitems = [] # rebuilt below, to correspond with topnodes
self.model = model = ModelTreeModel()
model.rootItem.view = self
self.setItemDelegate(model.rootItem)
self.setModel(model)
lastitem = None ####@@@@ got to about here
for node in self.topnodes:
item = self.make_new_subtree_for_node(node, listview, self.model.rootItem, after = lastitem)
lastitem = item
self.topitems.append(item)
self.expandAll()
# Update open/highlighted state of all tree items [text, icon already done above]
###@@@ code copied below - merge?
for item in self.topitems:
self.update_open_selected_in_itemtree( item)
self.post_update_topitems() # let subclass know about new self.topitems
# set the scroll position to what it ought to be
# [bruce circa 050113. Fixes bug 177.]
qt4todo('x, y = self.scrollpos')
qt4todo('self.setContentsPos( x, y)')
###@@@ not yet perfect, since we need to correct height
# to be larger than needed for all items, when collapsing a group
# which went below the visible area, so the group doesn't move on
# screen due to QTreeView not liking empty space below the items.
## a note about why ensureItemVisible is not useful [bruce circa 050109]:
##self.ensureItemVisible(self.last_selected_node.tritem)
## this "works", but it looks pretty bad:
## - there's a lot of flickering, incl of the scrollbar (disabling updates might fix that)
## - it always puts this item at the very bottom, for the ones that would otherwise be off the bottom
## - even if this item is already visible near the top, it moves stuff, perhaps as if trying to center it.
return # from update_state_0
def get_topnodes(self):
"[subclasses must override this to tell us what nodes to actually show]"
return [] #e a better stub/testing value might be a comment node, if there is such a node class
def post_update_topitems(self):
"#doc"
pass
def update_selection_highlighting(self): ###@@@ #e let caller pass a subset or list to do it for?
"""The selection state might have changed; for each item whose selection state
might be different now, set it properly via item.setSelected and repaint the item.
"""
# [Note: this is presently only called from subclasses, because it's only useful as part of an incremental update
# (otherwise the items were created with this already correct, or updated en masse right afterwards)
# and so far only some subclass's own event methods do incremental updates.
# But someday we'll let ourselves be given incremental inval info (by subclass event methods, or outside code)
# and call this from our own update function when only certain kinds of incremental invals occurred.]
###@@@ this is way more work than needed -- just do it for single items in old xor new members of selitems lists!
# we'll need to fix this to make the selection behavior look fast enough, else it'll look bad.
for item in self.topitems:
self.update_open_selected_in_itemtree(item, do_setOpen=0)
###@@@ code copied from above -- but this code will change, anyway. so nevermind.
# w/o flag do_setOpen=0 it might do illegal changes for a slot function... not sure
return
# default implems, subclasses could override (but don't, so far); also,
# self.isOpen(item) (nim) ought to be separated from display_prefs and not included in them.
def display_prefs_for_node(self, node):
"""Return a dict of the *incremental* display prefs for the node,
relative to whatever its parent passes as display prefs for its own kids.
Any prefs that it should inherit from its parent's env should be left out of this dict.
The main thing this needs to include (if this is an openable node)
is whether this node should be open in this view.
[Subclasses can override this.]
[Using this cumbersomeness just to say whether the item is open
is not worthwhile in hindsight. Fix it sometime. #e]
"""
res = {}
if node.openable(): ###e should use item_isOpen, but that's for items...
res['openable'] = True ###@@@??? see setExpandable; and discussion in ModelTreeItem docs, esp about setup() function
try:
node.open ###@@@ obs, will be changed
except:
print "fyi: bug? openable node has no .open attr: %r" % node ###@@@ soon, none will need this, i think...
res['open'] = False
else:
res['open'] = not not node.open
return res
def display_prefs_for_kids_of(self, node):
"""Return a dict of the *incremental* display prefs for this node's kids,
relative to whatever its parent passes as display prefs for its own kids.
Any that should inherit from parent's env should be left out of this dict.
"""
return {}
# basic data structure -- move this to some earlier position in the class #e
def set_nodeItem(self, node, item): #050119
self._node_items[node] = item # does not destroy old item, if any!
def nodeItem(self, node):
"""Return the ModelTreeItem currently representing Node (in self)
(this item might be hidden under closed higher nodes), or None.
(If this item exists, then normally item.object == node.)
Note that we (usually??) insist on node.dad corresponding to
item.parent, so (always) one node can be shown in at most one place
(per treewidget), thus can have at most one item per treewidget.
[If you want to change this, consider instead using a new layer of
nodes with these properties, between the tree widget and whatever
nodes you're actually showing. If you *still* want to change it,
then we'll still insist, I think, on all structural state being
derived from display rules (which include the per-item "open" state)
and node-tree structure, so that changes to the node tree result in
deterministic but perhaps multiple changes to the item tree.
But if that item tree, knowing "open", is ever lazily created in,
terms of real ModelTreeItems, then we might end up needing to use
permanent ones which end up being that same extra layer of nodes
or at least permanent-item-position-ids.]
"""
return self._node_items.get(node)
# historical note [bruce 050119]:
# this used to be stored in node.tritem (except that
# attr was missing when this was None); this had two problems:
# - no possibility for more than one tree widget showing the same nodes;
# - there was no clear_nodeItems(), resulting in bugs from accessing
# deleted Qt objects when simple incremental update schemes were tried.
# Unreviewed recent comment by me: "all this seems to be for is
# setSelected, setOpen, and bookkeeping, and being created".
# (Presumably, for other needs, we already have the item. If we go to
# item-centric updating, then conceivably we'll no longer need this at
# all -- then it would be easy to let it be a one-to-many function!
# Well, we might still want it (in that form) for invalidation. Though
# at the moment we survive without any per-node inval, so maybe not.)
def clear_nodeItems(self):
self._node_items.clear() # does not destroy old items!
"""Bug 1070 is one of these 'underlying C/C++ object has been
deleted' bugs. These come up periodically, and they make me wonder
if there is something we should be doing to detect when underlying
C objects get deleted, and remove our own references to them. For
the present, we should try to detect such instances and clean up as
best we can. Maybe the rearchitecture will resolve this problem in
a more satisfactory way. - wware 051206
"""
# wware 051206 fixing bug 1070
def tooltip_nodeItems(self, tooltip):
"""Step through the nodes for this tree, and fill in the QToolTip for
the ModelTreeItems in the viewport of the QlistView for the tree."""
_node_items = self._node_items
for node in _node_items.keys():
name = node.name
if len(name) > 12:
item = _node_items[node]
try:
vp = self.viewport()
if not isinstance(vp, QWidget):
if debug_flags.atom_debug:
# See bug 2113 - this does not appear to be very serious. wware 060727
sys.stderr.write("QScrollView.viewport() should return a QWidget (bug 1457)\n")
sys.stderr.write("Instead it returned " + repr(vp) + "\n")
return
# qrect = vp.itemRect(item) ? ?
qrect = self.itemRect(item)
tooltip.add(vp, qrect, node.name)
except RuntimeError:
qrect = None
# underlying C/C++ object has been deleted
# item is invalid, remove it from _node_items
del _node_items[node]
# update helpers; will want some revision but this is not urgent I think #e
def make_new_subtree_for_node(self, node, parent, nodeParent, display_prefs = {}, after = None):
"""Make one or more new treeitems (ModelTreeItems) in this treewidget (a QTreeView),
as needed to display the given node under the given parent
(which should be a treeitem or this treewidget).
The display prefs (in our argument) are the ones from the env supplied by the parent --
they don't include the ones for this node itself (e.g. whether it's open),
though (someday) they might include policies for whether or not to honor those.
Return the toplevel treeitem made (the one corresponding to node).
###redoc: MAYBE: Include all kids of node (as if the node was open), whether or not it's actually open.
[###@@@ that might be changed, but that's how it was in the pre-050109 code.]
"""
# This replaces the pre-050109 Node.upMT and Group.upMT, as well as the buildNode methods they called.
## display_prefs = {} ###@@@ get from caller; includes 'open' ###@@@ as temp kluge, set node.open here??
# modify display_prefs for this node, and for kids (separately!).
item_prefs = dict(display_prefs)
item_prefs.update( self.display_prefs_for_node(node) ) # incls. whether node should be open in this view
item_prefs['open'] = True ###@@@ imitate the old code - include all the kids
kid_prefs = dict(display_prefs)
kid_prefs.update( self.display_prefs_for_kids_of(node) ) # as of 050109, does nothing, but that might change soon
item = self.make_new_item_for_node(node, parent, nodeParent, item_prefs, after)
self.set_nodeItem(node, item) ## node.tritem = item
kids = node.kids(item_prefs)
lastkid = None
for kid in kids: ###@@@ also gaps for dnd -- but only later when we translate this to a canvas
kiditem = self.make_new_subtree_for_node( kid, item, item, kid_prefs, after = lastkid)
# kiditem.setParent(item)
lastkid = kiditem
del kiditem
###@@@ what about dnd here?? was it grabbed from each node or passed from toplevel upMT call?
## kid.upMT(item, dnd)
return item
###@@@ I think existing code would not rebuild tree except when expand/collapse;
# eg would not do it just when sel changed. notsure. at least that must be why it has separate setProp.
# bruce 050108 moved this back into mtree (from the Node.buildNode methods)
###@@@ qt doc explains why it comes in wrong order, and tells how to fix it
def make_new_item_for_node(self, node, parent, nodeParent, display_prefs = {}, after = None):
"""build and return a single new tree item in this tree widget
(as part of building the entire tree from scratch, or maybe an entire subtree)
corresponding to node; the args are:
self, this tree widget; not sure if this was avail to the orig buildnode -- maybe as one of the other args?
node, the node
parent, can be another tree item (ModelTreeItem) or the tree widget itself (a QTreeView)
icon - the icon to use for this node
dnd - whether to enable drag and drop (not sure which part of it this is about)
rename - whether to enable in-place editing of the name
some of these args might be replaced by computations we do here or in sole caller ###@@@ do it all
####@@@redoc below
after - None, or another listview item we come after
.. .must add to nodes: options to specify dnd, rename, icon(openness).
NOTE: it does not add in the kids! that must be done by upMT. and only if the item should be open.
"""
item = ModelTreeItem(node.name, nodeParent, node)
nodeParent.appendChild(item)
item.display_prefs = display_prefs # needed when we update the icon
item.setIcon(QIcon(node.node_icon(display_prefs))) ###@@@ and/or, update the icon directly when we open/close?
qt4todo('item.setRenameEnabled(0, node.rename_enabled()) ###k what is the 0 arg?')
return item
def update_item_icon(self, item): ###@@@ should also use this in some other methods, i think
node = item.object
display_prefs = dict(item.display_prefs) # make a copy to hold local changes
display_prefs.update( self.display_prefs_for_node(node) ) # patches in current 'open' pref
icon = node.node_icon( display_prefs)
item.setIcon(icon) # 0 is the column the pixmap is in
# Qt doc doesn't say whether this repaints or updates or neither,
# but something seems to make it look right after this
# everything after this: new methods by bruce 050108-050110, many temporary,
# as I tease apart mtree and Utility to have a clean boundary ###@@@
###@@@@ the following should be rewritten to scan item tree, not node tree...
# then maybe it would not matter if item.parent ~= node.dad.
# so it'd work for viewdata nodes even if we don't make that correspondence strict.
def update_open_selected_in_itemtree(self, item, do_setOpen = True, do_invisible_nodes = True):
###@@@ change to also update text, icon? anything but structure... rename??
###@@@ this implem is temporary and wrong:
self.update_items_from_nodes_open_selected(item.object, do_setOpen = do_setOpen, do_invisible_nodes = do_invisible_nodes)
def update_items_from_nodes_open_selected(self, node, _guard_ = None, do_setOpen = True, do_invisible_nodes = True):
# bruce 050110 temporary; deprecated, only call from above method and not for long! ###@@@
"""set the properties in the model tree widget to match
those in the tree datastructure #redoc
"""
assert _guard_ is None # this makes sure we don't supply too many positional arguments!
# bruce 050110 made this from the old Node.setProp and Group.setProp methods,
# deprecated now (removed asap).
# this will pull them into this file;
# later worry about making them item-centric not node-centric...
# and about fixing them to use methods on items not in tw, so sel works better.
# btw what about viewdata members (kids but not members, might not be reached here)?
# is it moot? ignore for now. or ask node for all members for this use... ie all possible kids, kids_if_open...
# useful in our treemaker too i guess.
listview = self
item = self.nodeItem(node)
#bruce 050512 re bug 620: it can happen that item is None because node is newly made
# since the last time the MT was fully updated. To fix comment#0 of that bug, check for this.
# For details of how that can happen, see my comments in that bug report. Roughly, if you click
# in MT while waiting for a long op to finish which at the end needs to remake MT and does so by
# calling mt_update, it happens because Qt first processes our click, then the mt update event.
# [#e One better fix might be to remake the MT at the end of the user event that messed up the nodes it shows.
# Then this would happen before the click was processed so it'd be up to date... we might still want to
# detect this and discard that click in case it was on the wrong item. Anyway that's all NIM for now.
# Another fix would be to scan the item-tree here (as last made from a node-tree), not the new node-tree. #e]
if not item:
if debug_flags.atom_debug:
print "atom_debug: fyi: MT node with no item (still waiting for MT.update Qt event?)"
return
# bruce 050512 continues: Worse, it can happen that item is no longer valid -- the first time we call a method on it,
# we get an exception from PyQt "RuntimeError: underlying C/C++ object has been deleted". My bug 620 comments give
# details on that as well. Let's check this here with a harmless method and get it over with:
try:
item.text(0) # returns text in column 0
except:
if debug_flags.atom_debug:
print "atom_debug: fyi: MT node with invalid item (still waiting for MT.update Qt event?)"
return
# Now it should be safe to use item.
if do_setOpen:
if node.openable(): ###e needs cleanup: use node_isOpen/isOpenable split from current item_ methods
self.expandItem(item)
qt4todo('item.repaint()')
self.repaint()
if hasattr(node, 'members'): # clean this up... won't be enough for PartGroup! ###@@@
if not do_invisible_nodes:
# if the members are not visible now, don't update them now (optim, I guess)
if not (node.openable() and getattr(node,'open',False)):
return
for kid in node.members: ###@@@ for viewdata guys, use kids_if_open
self.update_items_from_nodes_open_selected(kid, do_setOpen = do_setOpen)
return
pass # end of class TreeView
# end
| NanoCAD-master | cad/src/outtakes/TreeView.py |
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details.
"""
prefsTree.py -- experimental code related to showing
user preferences in the model tree
(not presently used as of 050612, but works; very incomplete)
@author: Bruce
@version: $Id$
@copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details.
History:
bruce 050613 started this.
Module classification: [bruce 071215]
Tentatively, "model", though arguably it also contains ui code.
Used by model_tree but also in assembly (which is in "model").
Perhaps ought to be split into two files?
"""
import os
from foundation.Utility import Node
from foundation.Group import Group
from model.part import Part
from utilities.constants import noop, dispLabel, default_display_mode
import foundation.env as env
_debug_prefstree = True # safe for commit even when True
class PrefNode(Node):
"""
Leaf node for storing a local change to a single preference attribute
"""
#e or is PrefsGroup the same class? not sure...
## no_selgroup_is_ok = True
def __init__(self, assy, name = "prefnode"):
Node.__init__(self, assy, name)
return
def __CM_Add_Node(self):
self.addsibling( PrefNode(self.assy, "prefnode") )
pass
class PrefChoiceNode(PrefNode):
"""
A PrefNode which lets the user choose one of a small finite set of choices
using its cmenu (or maybe in other ways too?)
"""
def __init__(self, assy, name, choices = None, default_name = None, defaultValue = None, typename = None ):
PrefNode.__init__(self, assy, name)
self.choices = choices or [('No choices!', None)]
self.choicedict = {}
self.typename = typename #k not used?
for name, val in self.choices:
self.choicedict[name] = val
if default_name is not None:
self.default_name = default_name
self.defaultValue = self.choicedict[default_name] # it better be in there!
elif defaultValue is not None or None in self.choicedict.values():
for name, val in self.choices:
if val == defaultValue:
self.default_name = name
self.defaultValue = val
break
else:
self.default_name, self.defaultValue = self.choices[0]
return
def __cmenu_items(self): ###IMPLEM a call of this
submenu = []
for choice in self.choicelist:
submenu.append((choice, noop)) ###noop -> lambda
res = []
res.append(("choices",submenu))
return res
pass
# these exprs are of the form [ class, opts( opt1 = val1, ... ) ]
def opts(**kws):
return dict(kws)
bool_choice = [ PrefChoiceNode, opts(
typename = "boolean", #??
choices = [('True', True), ('False', False)],
default_name = 'False'
)]
# not very useful, better to use checkmark presence or not on the pref item itself, not this submenu from it
# (that requires using the QListViewItem subclass with a checkmark)
# or alternatively, having a submenu with some boolean toggle items in it (our menu_spec could offer that option)
dispmode_choice = [ PrefChoiceNode, opts(
typename = "display mode",
choices = zip( dispLabel, range(len(dispLabel)) ),
defaultValue = default_display_mode
)]
# ==
class PrefsGroup(Group):
"""
Group node for storing a set of local changes to preference attributes
"""
## no_selgroup_is_ok = True
def __init__(self, assy, name): # arg order is like Node, not like Group
dad = None
Group.__init__(self, name, assy, dad)
# dad arg is required (#e should not be) and arg order is inconsistent (should not be)
def __CM_Add_Node(self):
self.addchild( PrefNode(self.assy, "prefnode") )
self.assy.w.mt.mt_update() #k why needed? (and does it help?)
pass
# ==
# print _node._MainPrefsGroup__CM_Save_Prefs()
def prefsPath(assy):
return os.path.join( assy.w.tmpFilePath, "Preferences", "prefs.mmp" ) #e use common code for the dir
class MainPrefsGroup(PrefsGroup): # kind of like PartGroup; where do we say it's immortal? in the part, not the node.
def is_top_of_selection_group(self): return True
def rename_enabled(self): return False
def drag_move_ok(self): return False
def permits_ungrouping(self): return False
def description_for_history(self):
"""
[overridden from Group method]
"""
return "Preferences"
def __CM_Save_Prefs(self):
"""
[temporary kluge, should autosave whenever changed, or from dialog buttons]
save this node's part into a constant-named mmp file in prefs dir
(for now -- details of where/how it saves them is private and might change)
"""
path = prefsPath(self.assy)
self.part.writemmpfile( path) ####@@@@ need options? their defaults were changed on 051209 w/o reviewing this code.
env.history.message( "saved Preferences Group" )
# kluge: zap some useless cmenu items for this kind of node (activates special kluge in mtree cmenu maker)
__CM_Hide = None
__CM_Group = None
__CM_Ungroup = None
pass
class MainPrefsGroupPart(Part):
"""
[public, meant to be imported and used by code in assembly.py]
"""
def immortal(self): return True
def glpane_label_text(self):
return "(preferences area; not in the mmp file)"
def location_name(self):
return "prefs tree" #k used??
def movie_suffix(self):
"""
what suffix should we use in movie filenames? None means don't permit making them.
"""
None #k does this still work?
pass
def prefsTree(assy):
"""
Make or return the prefsTree object for the given assy
"""
#e really there should be a single one per session, but this should work
try:
## assert isinstance(assy.prefsTree, prefsTree_class) # multiple ways this can fail, and that's normal
# above messes up reloading, so do this instead:
assert assy.prefsTree.__class__.__name__ == "prefsTree_class"
return assy.prefsTree
except:
if _debug_prefstree:
print "remaking prefsTree object for", assy # this is normal
pass
assy.prefsTree = prefsTree_class(assy)
assy.prefs_node = assy.prefsTree.topnode #e might be better for assy to look it up this way itself
assy.update_parts()
# this will set assy.prefs_node.part to a MainPrefsGroupPart instance, if it has no .part yet (as we expect)
return assy.prefsTree
class prefsTree_class:
topnode = None
def __init__(self, assy):
self.assy = assy
self.topnode = MainPrefsGroup(assy, "Preferences")
path = prefsPath(self.assy)
stuff = read_mmp_single_part( assy, path) # a list of one ordinary group named Preferences
(prefsgroup,) = stuff
mems = prefsgroup.steal_members()
for mem in mems:
self.topnode.addchild( mem)
pass
def read_mmp_single_part(assy, filename):
from files.mmp.files_mmp import readmmp
# start incredible kluge block
history = env.history
#bruce 050901 revised this.
# It depends on there being only one active history object at a time.
# (Before 050913, that object was stored as both env.history and win.history.)
oldmessage = history.message
from utilities.constants import noop
history.message = noop # don't bother user with this file being nonstd (bad, should pass a flag, so other errors seen)
try:
ok, grouplist = readmmp(assy, filename, isInsert = True)
finally:
history.message = oldmessage
if grouplist:
viewdata, mainpart, shelf = grouplist
return mainpart.steal_members() # a python list of whatever toplevel stuff was in the mmp file
return None
# need object to describe available state in the program, and its structure as a tree
# (eg list of modes available; widget layout; rendering loop -- this is partly user-mutable and partly not)
# and then the prefsnodes are an interface to that object,
# and can load their state from it or save their state to it.
# it might also be nodes, not sure
# ==
# remaking nodes destroys any renames I did for them, would mess up DND results too --
# need to keep them around and update them instead (ok if I remake the owner object, though)
# or perhaps let them be proxies for other state (harder, but might be needed anyway, to save that state)
# end
| NanoCAD-master | cad/src/outtakes/prefsTree.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
DnaDuplexGenerator.py
@author: Mark Sims
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
History:
Mark 2007-10-18:
- Created. Major rewrite of DnaGenerator.py.
"""
from foundation.Group import Group
from utilities.Log import redmsg, greenmsg
from geometry.VQT import V, Veq
from dna.commands.BuildDuplex.DnaDuplex import B_Dna_PAM3
from command_support.GeneratorBaseClass import GeneratorBaseClass
from utilities.exception_classes import CadBug, PluginBug, UserError
from dna.commands.BuildDuplex.DnaDuplexPropertyManager import DnaDuplexPropertyManager
############################################################################
# DnaDuplexPropertyManager must come BEFORE GeneratorBaseClass in this list
class DnaDuplexGenerator(DnaDuplexPropertyManager, GeneratorBaseClass):
cmd = greenmsg("Build DNA: ")
sponsor_keyword = 'DNA'
prefix = 'DNA-' # used for gensym
# Generators for DNA, nanotubes and graphene have their MT name
# generated (in GeneratorBaseClass) from the prefix.
create_name_from_prefix = True
# pass window arg to constructor rather than use a global, wware 051103
def __init__(self, win):
DnaDuplexPropertyManager.__init__(self)
GeneratorBaseClass.__init__(self, win)
self._random_data = []
# ##################################################
# How to build this kind of structure, along with
# any necessary helper functions.
def gather_parameters(self):
"""
Return the parameters from the property manager UI.
@return: All the parameters:
- numberOfBases
- dnaForm
- basesPerTurn
- endPoint1
- endPoint2
@rtype: tuple
"""
numberOfBases = self.numberOfBasesSpinBox.value()
dnaForm = str(self.conformationComboBox.currentText())
basesPerTurn = self.basesPerTurnDoubleSpinBox.value()
# First endpoint (origin) of DNA duplex
x1 = self.x1SpinBox.value()
y1 = self.y1SpinBox.value()
z1 = self.z1SpinBox.value()
# Second endpoint (direction vector/axis) of DNA duplex.
x2 = self.x2SpinBox.value()
y2 = self.y2SpinBox.value()
z2 = self.z2SpinBox.value()
endPoint1 = V(x1, y1, z1)
endPoint2 = V(x2, y2, z2)
return (numberOfBases,
dnaForm,
basesPerTurn,
endPoint1,
endPoint2)
def build_struct(self, name, params, position):
"""
Build the DNA helix based on parameters in the UI.
@param name: The name to assign the node in the model tree.
@type name: str
@param params: The list of parameters gathered from the PM.
@type params: tuple
@param position: The position in 3d model space at which to
create the DNA strand. This is always 0, 0, 0.
@type position: position
"""
# No error checking in build_struct, do all your error
# checking in gather_parameters
numberOfBases, \
dnaForm, \
basesPerTurn, \
endPoint1, \
endPoint2 = params
if Veq(endPoint1, endPoint2):
raise CadBug("DNA endpoints cannot be the same point.")
if numberOfBases < 1:
msg = redmsg("Cannot to preview/insert a DNA duplex with 0 bases.")
self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=False)
self.dna = None # Fixes bug 2530. Mark 2007-09-02
return None
if dnaForm == 'B-DNA':
dna = B_Dna_PAM3()
else:
raise PluginBug("Unsupported DNA Form: " + dnaForm)
self.dna = dna # needed for done msg
# Create the model tree group node.
dnaGroup = Group(self.name,
self.win.assy,
self.win.assy.part.topnode)
try:
# Make the DNA duplex. <dnaGroup> will contain three chunks:
# - Strand1
# - Strand2
# - Axis
dna.make(dnaGroup,
numberOfBases,
basesPerTurn,
endPoint1,
endPoint2)
return dnaGroup
except (PluginBug, UserError):
# Why do we need UserError here? Mark 2007-08-28
rawDnaGroup.kill()
raise PluginBug("Internal error while trying to create DNA duplex.")
pass
###################################################
# The done message
#@ THIS SHOULD BE REMOVED. Mark
def done_msg(self):
if not self.dna: # Mark 2007-06-01
return "No DNA added."
return "Done creating a strand of %s." % (self.dna.form)
| NanoCAD-master | cad/src/outtakes/DnaDuplexGenerator.py |
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
old_extrude_widgets.py - these were used in the original Extrude Mode dashboard.
@author: Bruce
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
from PyQt4.Qt import QGroupBox, QSpinBox, QCheckBox
from PyQt4.Qt import QVBoxLayout
from PyQt4.Qt import QHBoxLayout
from PyQt4.Qt import QLabel
from utilities.qt4transition import qt4warning, qt4todo
# These don't exist in Qt4 but we can make begin(QVBox) and
# begin(QHBox) act the same as before.
QVBox, QHBox = range(2)
class widget_filler:
"""
Helper class to make it more convenient to revise the code
which creates nested widget structures (vbox, hbox, splitters, etc).
For example of use, see extrudeMode.py.
In the future we might also give this the power to let user prefs
override the requested structure.
"""
def __init__(self, parent, label_prefix = None, textfilter = None):
"""
Parent should be the widget or megawidget to be filled with
subwidgets using this widget_filler instance.
"""
self.where = [parent]
# stack of widgets or megawidgets currently being filled with subwidgets;
# each one contains the next, and the last one (top of stack)
# is the innermost one in the UI, which will contain newly
# created widgets (assuming they specify self.parent() as
# their parent).
self.label_prefix = label_prefix
self.textfilter = textfilter
self.layoutstack = [ ]
def parent(self):
"""
To use this widget_filler, create new widgets whose parent is what
this method returns (always a qt widget, not a megawidget)
[#e we might need a raw_parent method to return megawidgets directly]
"""
# return qt_widget( self.where[-1] )
return self.where[-1]
class MyGroupBox(QGroupBox):
pass
def begin(self, thing):
"""
use this to start a QVBox or QHBox, or a splitter;
thing is the Qt widget class
"""
# someday: or can thing be a megawidget?
assert thing in (QVBox, QHBox)
if len(self.layoutstack) == len(self.where):
grpbox = self.MyGroupBox()
self.where.append(grpbox)
self.layoutstack[-1].addWidget(grpbox)
p = self.where[-1]
if thing is QVBox:
layoutklas = QVBoxLayout
else:
layoutklas = QHBoxLayout
layout = layoutklas()
self.layoutstack.append(layout)
if len(self.where) > 1:
p.setLayout(layout)
if False: # debug
print '<<<'
for x, y in map(None, self.where, self.layoutstack):
print x, y
print '>>>'
return 1
# return value is so you can say "if begin(): ..." if you want to
# use python indentation to show the widget nesting structure
# if this doesn't work, look at
# PyQt-x11-gpl-4.0.1/examples/widgets/spinboxes.py
def end(self):
self.layoutstack.pop()
if isinstance(self.where[-1], self.MyGroupBox):
self.where.pop()
def label(self, text):
if self.label_prefix is not None:
name = self.label_prefix + text.strip()
else:
name = None #k ok?
#label = QLabel(self.parent(), name)
label = QLabel(self.parent()) # ignore name for Qt 4
if self.textfilter:
text = self.textfilter(text)
label.setText(text) # initial text
return label # caller doesn't usually need this, except to vary the text
pass
# these custom widgets were originally defined at the top of extrudeMode.py.
class FloatSpinBox(QSpinBox):
"""
spinbox for a coordinate in angstroms -- permits negatives, floats
"""
range_angstroms = 1000.0 # value can go to +- this many angstroms
precision_angstroms = 100 # with this many detectable units per angstrom
min_length = 0.1 # prevent problems with 0 or negative lengths provided by user
max_length = 2 * range_angstroms # longer than possible from max xyz inputs
def __init__(self, *args, **kws):
#k why was i not allowed to put 'for_a_length = 0' into this arglist??
for_a_length = kws.pop('for_a_length',0)
assert not kws, "keyword arguments are not supported by QSpinBox"
# QSpinBox.__init__(self, *args) #k #e note, if the args can affect the range, we'll mess that up below
QSpinBox.__init__(self) #k #e note, if the args can affect the range, we'll mess that up below
assert len(args) is 2
assert type(args[1]) is type('abc')
self.setObjectName(args[1])
qt4warning('QSpinBox() ignoring args: ' + repr(args))
## self.setValidator(0) # no keystrokes are prevented from being entered
## TypeError: argument 1 of QSpinBox.setValidator() has an invalid type -- hmm, manual didn't think so -- try None? #e
qt4todo('self.setValidator( QDoubleValidator( - self.range_angstroms, self.range_angstroms, 2, self ))')
# QDoubleValidator has a bug: it turns 10.2 into 10.19! But mostly it works. Someday we'll need our own. [bruce 041009]
if not for_a_length:
self.setRange( - int(self.range_angstroms * self.precision_angstroms),
int(self.range_angstroms * self.precision_angstroms) )
else:
self.setRange( int(self.min_length * self.precision_angstroms),
int(self.max_length * self.precision_angstroms) )
qt4todo('self.setSteps( self.precision_angstroms, self.precision_angstroms * 10 ) # set linestep and pagestep')
def mapTextToValue(self):
text = self.cleanText()
text = str(text) # since it's a qt string
##print "fyi: float spinbox got text %r" % text
try:
fval = float(text)
ival = int(fval * self.precision_angstroms) # 2-digit precision
return ival, True
except:
return 0, False
def mapValueToText(self, ival):
fval = float(ival)/self.precision_angstroms
return str(fval) #k should not need to make it a QString
def floatValue(self):
return float( self.value() ) / self.precision_angstroms
def setFloatValue(self, fval):
self.setValue( int( fval * self.precision_angstroms ) )
pass
class TogglePrefCheckBox(QCheckBox):
"""
checkbox, with configurable sense of whether checked means True or False
"""
def __init__(self, *args, **kws):
self.sense = kws.pop('sense', True) # whether checking the box makes our value (seen by callers) True or False
self.default = kws.pop('default', True) # whether our default value (*not* default checked-state) is True or False
self.tooltip = kws.pop('tooltip', "") # tooltip to show ###e NIM
# public attributes:
self.attr = kws.pop('attr', None) # name of mode attribute (if any) which this should set
self.repaintQ = kws.pop('repaintQ', False) # whether mode might need to repaint if this changes
assert not kws, "keyword arguments are not supported by QCheckBox"
assert len(args) is 3
assert type(args[0]) is type('abc')
assert type(args[2]) is type('abc')
QCheckBox.__init__(self, args[0])
self.setObjectName(args[2])
#e set tooltip - how? see .py file made from .ui to find out (qt assistant didn't say).
def value(self):
if self.isChecked():
return self.sense
else:
return not self.sense
def setValue(self, bool1):
if self.sense:
self.setChecked( bool1)
else:
self.setChecked( not bool1)
def initValue(self):
self.setValue(self.default)
pass
| NanoCAD-master | cad/src/outtakes/old_extrude_widgets.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
MMKitDialog.py
THIS FILE HAS BEEN DEPRECATED.
SEE NEW IMPLEMETATION IN --
Ui_BuildAtomsPropertyManager.py,
BuildAtomsPropertyManager.py,
Ui_PartLibPropertyManager.py,
PartLibPropertyManager.py,
Ui_PastePropertyManager.py
PastePropertyManager.py
$Id$
History:
-Originally created by Mark and Huaicai using Qt3 designer
Till Alpha8, MMKit existed as a Dialog.
-October 2006 Will ported MMKitDialog from Qt3 to Qt4
-October 2006 onwards Ninad integrated Build Dashboard and MMKitDialog
and converted it into a 'Property Manager' with further enhancements.
As of 20070717 it is still refered as MMKitDialog. Should really be called
'Build Atoms Property Manager' -- ninad 20070717
mark 2007-05-29: Fixed sizePolicy for all widgets so everything behaves itself
in a fixed width Property Manager (for Alpha 9).
"""
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import QSize
from PyQt4.Qt import Qt
from PyQt4.Qt import QPalette
from PyQt4.Qt import QSizePolicy
from PyQt4.Qt import QFont
from PyQt4.Qt import QLineEdit
from foundation.Utility import geticon, getpixmap
import foundation.env as env
from PropMgrBaseClass import getPalette
from PropertyManagerMixin import pmVBoxLayout
from PropertyManagerMixin import pmAddHeader
from PropertyManagerMixin import pmAddSponsorButton
from PropertyManagerMixin import pmAddTopRowButtons
from PropertyManagerMixin import pmMessageGroupBox
from PropertyManagerMixin import pmAddBottomSpacer
from PM.PropMgr_Constants import pmDoneButton
from PM.PropMgr_Constants import pmWhatsThisButton
from PM.PropMgr_Constants import pmMainVboxLayoutMargin
from PM.PropMgr_Constants import pmMainVboxLayoutSpacing
from PM.PropMgr_Constants import pmHeaderFrameMargin
from PM.PropMgr_Constants import pmHeaderFrameSpacing
from PM.PropMgr_Constants import getHeaderFont
from PM.PropMgr_Constants import pmLabelLeftAlignment
from PM.PropMgr_Constants import pmSponsorFrameMargin
from PM.PropMgr_Constants import pmSponsorFrameSpacing
from PM.PropMgr_Constants import pmGroupBoxSpacing
from PM.PropMgr_Constants import pmTopRowBtnsMargin
from PM.PropMgr_Constants import pmTopRowBtnsSpacing
from PM.PropMgr_Constants import pmMessageTextEditColor
from PM.PropMgr_Constants import pmGrpBoxVboxLayoutMargin
from PM.PropMgr_Constants import pmGrpBoxVboxLayoutSpacing
from PM.PropMgr_Constants import pmMMKitPageMargin
from PM.PropMgr_Constants import pmMMKitButtonFont
from PM.PropMgr_Constants import pmMMKitButtonFontPointSize
from PM.PropMgr_Constants import pmMMKitButtonFontBold
from PM.PropMgr_Constants import pmMMKitButtonHeight
from PM.PropMgr_Constants import pmMMKitButtonWidth
from utilities.prefs_constants import buildModeAutobondEnabled_prefs_key
from utilities.prefs_constants import buildModeHighlightingEnabled_prefs_key
from utilities.prefs_constants import buildModeWaterEnabled_prefs_key
class Ui_MMKitDialog(object):
"""
THIS CLASS HAS BEEN DEPRECATED.
SEE NEW IMPLEMETATION IN --
Ui_BuildAtomsPropertyManager.py,
BuildAtomsPropertyManager.py,
Ui_PartLibPropertyManager.py,
PartLibPropertyManager.py,
Ui_PastePropertyManager.py
PastePropertyManager.py
"""
def setupUi(self, MMKitDialog):
# Note: MMKitDialog (which as a local variable should not be named with an initial capital)
# is an object of class MMKit, which inherits from PropertyManagerMixin,
# and some methods from PropertyManagerMixin are used on it herein,
# for example, inside self.ui_message_GroupBox(). [bruce 070618 comment]
MMKitDialog.setObjectName("MMKitDialog")
pmVBoxLayout(MMKitDialog)
pmAddHeader(MMKitDialog)
pmAddSponsorButton(MMKitDialog)
pmAddTopRowButtons(MMKitDialog,
showFlags = pmDoneButton | pmWhatsThisButton)
self.MessageGroupBox = pmMessageGroupBox(self, title="Message")
self.pmVBoxLayout.addWidget(self.MessageGroupBox)
pmAddBottomSpacer(self.MessageGroupBox, self.pmVBoxLayout)
self.ui_bondTools_grpBox(MMKitDialog)
pmAddBottomSpacer(self.bondTools_grpBox, self.pmVBoxLayout)
self.ui_preview_GroupBox(MMKitDialog)
pmAddBottomSpacer(self.thumbView_groupBox, self.pmVBoxLayout)
self.ui_MMKit_GroupBox(MMKitDialog)
pmAddBottomSpacer(self.MMKit_groupBox, self.pmVBoxLayout)
self.ui_selectionFilter_GroupBox(MMKitDialog)
pmAddBottomSpacer(self.selectionFilter_groupBox, self.pmVBoxLayout)
self.ui_advancedOptions_groupBox(MMKitDialog)
pmAddBottomSpacer(self.advancedOptions_groupBox, self.pmVBoxLayout, last=True)
######################################################.
self.retranslateUi(MMKitDialog)
QtCore.QMetaObject.connectSlotsByName(MMKitDialog)
# End of MMKitDialog ####################################
def ui_bondTools_grpBox(self, MMKitDialog):
#Start Atom Bond tools Groupbox
self.bondTools_grpBox = QtGui.QGroupBox(MMKitDialog)
self.bondTools_grpBox.setObjectName("bondTools_grpBox")
self.bondTools_grpBox.setAutoFillBackground(True)
palette = MMKitDialog.getGroupBoxPalette()
self.bondTools_grpBox.setPalette(palette)
styleSheet = MMKitDialog.getGroupBoxStyleSheet()
self.bondTools_grpBox.setStyleSheet(styleSheet)
self.vboxlayout_grpbox1 = QtGui.QVBoxLayout(self.bondTools_grpBox)
self.vboxlayout_grpbox1.setMargin(pmGrpBoxVboxLayoutMargin)
self.vboxlayout_grpbox1.setSpacing(pmGrpBoxVboxLayoutSpacing)
self.vboxlayout_grpbox1.setObjectName("vboxlayout_grpbox1")
self.bondTool_groupBoxButton = MMKitDialog.getGroupBoxTitleButton(
"Bonds Tool",
self.bondTools_grpBox)
self.vboxlayout_grpbox1.addWidget(self.bondTool_groupBoxButton)
self.bondToolWidget = QtGui.QWidget(self.bondTools_grpBox)
hlo_bondtool = QtGui.QHBoxLayout(self.bondToolWidget)
hlo_bondtool.setMargin(2)
hlo_bondtool.setSpacing(2)
for action in self.parentMode.bond1Action, self.parentMode.bond2Action, \
self.parentMode.bond3Action, self.parentMode.bondaAction, \
self.parentMode.bondgAction, self.parentMode.cutBondsAction:
btn = QtGui.QToolButton()
btn.setDefaultAction(action)
btn.setIconSize(QtCore.QSize(22,22))
btn.setAutoRaise(1)
action.setCheckable(True)
self.parentMode.bondToolsActionGroup.addAction(action)
hlo_bondtool.addWidget(btn)
self.vboxlayout_grpbox1.addWidget(self.bondToolWidget)
# End Atom Bond Tools Groupbox
self.pmVBoxLayout.addWidget(self.bondTools_grpBox)
# Height is fixed. Mark 2007-05-29.
self.bondTools_grpBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
def ui_preview_GroupBox(self, MMKitDialog):
# Start MMKit ThumbView (Preview) GroupBox
self.thumbView_groupBox = QtGui.QGroupBox(MMKitDialog)
self.thumbView_groupBox.setObjectName("thumbView_groupBox")
self.thumbView_groupBox.setAutoFillBackground(True)
palette = MMKitDialog.getGroupBoxPalette()
self.thumbView_groupBox.setPalette(palette)
styleSheet = MMKitDialog.getGroupBoxStyleSheet()
self.thumbView_groupBox.setStyleSheet(styleSheet)
self.vboxlayout_grpbox2 = QtGui.QVBoxLayout(self.thumbView_groupBox)
self.vboxlayout_grpbox2.setMargin(pmGrpBoxVboxLayoutMargin)
self.vboxlayout_grpbox2.setSpacing(pmGrpBoxVboxLayoutSpacing)
self.vboxlayout_grpbox2.setObjectName("vboxlayout_grpbox2")
self.thumbView_groupBoxButton = MMKitDialog.getGroupBoxTitleButton("Preview", self.thumbView_groupBox)
self.vboxlayout_grpbox2.addWidget(self.thumbView_groupBoxButton)
self.elementFrame = QtGui.QFrame(self.thumbView_groupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(0))
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.elementFrame.sizePolicy().hasHeightForWidth())
self.elementFrame.setSizePolicy(sizePolicy)
self.elementFrame.setMinimumSize(QtCore.QSize(150,150))
self.elementFrame.setFrameShape(QtGui.QFrame.Box)
self.elementFrame.setFrameShadow(QtGui.QFrame.Raised)
self.elementFrame.setObjectName("elementFrame")
self.vboxlayout_grpbox2.addWidget(self.elementFrame)
#End MMKit ThumbView (Preview) GroupBox
self.pmVBoxLayout.addWidget(self.thumbView_groupBox)
# Height is fixed. Mark 2007-05-29.
self.thumbView_groupBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
def ui_MMKit_GroupBox(self, MMKitDialog):
#Start MMKit groupbox (includes atom, clipboard and library tabs)
self.MMKit_groupBox = QtGui.QGroupBox(MMKitDialog)
self.MMKit_groupBox.setObjectName("MMKit_groupBox")
self.MMKit_groupBox.setAutoFillBackground(True)
palette = MMKitDialog.getGroupBoxPalette()
self.MMKit_groupBox.setPalette(palette)
styleSheet = MMKitDialog.getGroupBoxStyleSheet()
self.MMKit_groupBox.setStyleSheet(styleSheet)
self.MMKitGrpBox_VBoxLayout = QtGui.QVBoxLayout(self.MMKit_groupBox)
self.MMKitGrpBox_VBoxLayout.setMargin(pmGrpBoxVboxLayoutMargin)
self.MMKitGrpBox_VBoxLayout.setSpacing(pmGrpBoxVboxLayoutSpacing)
self.MMKitGrpBox_VBoxLayout.setObjectName("MMKitGrpBox_VBoxLayout")
self.MMKitGrpBox_TitleButton = MMKitDialog.getGroupBoxTitleButton("MMKit", self.MMKit_groupBox)
self.MMKitGrpBox_VBoxLayout.addWidget(self.MMKitGrpBox_TitleButton)
self.mmkit_tab = QtGui.QTabWidget(self.MMKit_groupBox)
self.mmkit_tab.setEnabled(True)
# Height is fixed. Mark 2007-05-29.
self.mmkit_tab.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.mmkit_tab.setObjectName("mmkit_tab")
self.atomsPage = QtGui.QWidget()
self.atomsPage.setObjectName("atomsPage")
self.mmkit_tab.addTab(self.atomsPage, "")
self.atomsPageFrame = QtGui.QFrame(self.atomsPage)
# atomsPageFrame needs to be reviewed carefully. Mark 2007-06-20
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(3),QtGui.QSizePolicy.Policy(1))
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.atomsPageFrame.sizePolicy().hasHeightForWidth())
self.atomsPageFrame.setSizePolicy(sizePolicy)
self.atomsPageFrame.setFrameShape(QtGui.QFrame.NoFrame)
self.atomsPageFrame.setFrameShadow(QtGui.QFrame.Plain)
self.atomsPageFrame.setMinimumSize(QtCore.QSize(100,100))
self.atomsPageFrame.setObjectName("atomsPageFrame")
self.atomsPage_VBoxLayout = QtGui.QVBoxLayout(self.atomsPageFrame)
self.atomsPage_VBoxLayout.setMargin(pmMMKitPageMargin) # Was 4. Mark 2007-05-30
self.atomsPage_VBoxLayout.setSpacing(2)
# Element Button GroupBox begins here. #####################
self.elementButtonGroup = QtGui.QGroupBox(self.atomsPageFrame)
sizePolicy = QtGui.QSizePolicy(
QtGui.QSizePolicy.MinimumExpanding,
QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
self.elementButtonGroup.setSizePolicy(sizePolicy)
self.elementButtonGroup.setMinimumSize(
QtCore.QSize(pmMMKitButtonWidth * 4,
pmMMKitButtonHeight * 4 + 4))
self.elementButtonGroup.setObjectName("elementButtonGroup")
self.MMKit_GridLayout = QtGui.QGridLayout(self.elementButtonGroup)
self.MMKit_GridLayout.setMargin(1) # Was 0. Mark 2007-05-30
self.MMKit_GridLayout.setSpacing(0)
self.MMKit_GridLayout.setObjectName("MMKit_GridLayout")
# Font for toolbuttons.
font = QFont(self.atomsPageFrame.font())
font.setFamily(pmMMKitButtonFont)
font.setPointSize(pmMMKitButtonFontPointSize)
font.setBold(pmMMKitButtonFontBold)
#font.setWeight(75)
#font.setItalic(False)
#font.setUnderline(False)
#font.setStrikeOut(False)
# All this would be much nicer using a dictionary in a loop.
# Later, when time permits. Mark 2007-05-30.
self.toolButton1 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton1.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton1.setCheckable(True)
self.toolButton1.setFont(font)
self.toolButton1.setObjectName("toolButton1")
self.MMKit_GridLayout.addWidget(self.toolButton1,0,4,1,1)
self.toolButton2 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton2.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton2.setCheckable(True)
self.toolButton2.setFont(font)
self.toolButton2.setObjectName("toolButton2")
self.MMKit_GridLayout.addWidget(self.toolButton2,0,5,1,1)
self.toolButton6 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton6.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton6.setCheckable(True)
self.toolButton6.setFont(font)
self.toolButton6.setObjectName("toolButton6")
self.MMKit_GridLayout.addWidget(self.toolButton6,1,1,1,1)
self.toolButton7 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton7.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton7.setCheckable(True)
self.toolButton7.setFont(font)
self.toolButton7.setObjectName("toolButton7")
self.MMKit_GridLayout.addWidget(self.toolButton7,1,2,1,1)
self.toolButton8 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton8.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton8.setCheckable(True)
self.toolButton8.setFont(font)
self.toolButton8.setObjectName("toolButton8")
self.MMKit_GridLayout.addWidget(self.toolButton8,1,3,1,1)
self.toolButton10 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton10.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton10.setCheckable(True)
self.toolButton10.setFont(font)
self.toolButton10.setObjectName("toolButton10")
self.MMKit_GridLayout.addWidget(self.toolButton10,1,5,1,1)
self.toolButton9 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton9.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton9.setCheckable(True)
self.toolButton9.setFont(font)
self.toolButton9.setObjectName("toolButton9")
self.MMKit_GridLayout.addWidget(self.toolButton9,1,4,1,1)
self.toolButton13 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton13.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton13.setCheckable(True)
self.toolButton13.setFont(font)
self.toolButton13.setObjectName("toolButton13")
self.MMKit_GridLayout.addWidget(self.toolButton13,2,0,1,1)
self.toolButton17 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton17.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton17.setCheckable(True)
self.toolButton17.setFont(font)
self.toolButton17.setObjectName("toolButton17")
self.MMKit_GridLayout.addWidget(self.toolButton17,2,4,1,1)
self.toolButton5 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton5.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton5.setCheckable(True)
self.toolButton5.setFont(font)
self.toolButton5.setObjectName("toolButton5")
self.MMKit_GridLayout.addWidget(self.toolButton5,1,0,1,1)
self.toolButton10_2 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton10_2.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton10_2.setCheckable(True)
self.toolButton10_2.setFont(font)
self.toolButton10_2.setObjectName("toolButton10_2")
self.MMKit_GridLayout.addWidget(self.toolButton10_2,2,5,1,1)
self.toolButton15 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton15.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton15.setCheckable(True)
self.toolButton15.setFont(font)
self.toolButton15.setObjectName("toolButton15")
self.MMKit_GridLayout.addWidget(self.toolButton15,2,2,1,1)
self.toolButton16 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton16.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton16.setCheckable(True)
self.toolButton16.setFont(font)
self.toolButton16.setObjectName("toolButton16")
self.MMKit_GridLayout.addWidget(self.toolButton16,2,3,1,1)
self.toolButton14 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton14.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton14.setCheckable(True)
self.toolButton14.setFont(font)
self.toolButton14.setObjectName("toolButton14")
self.MMKit_GridLayout.addWidget(self.toolButton14,2,1,1,1)
self.toolButton33 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton33.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton33.setCheckable(True)
self.toolButton33.setFont(font)
self.toolButton33.setObjectName("toolButton33")
self.MMKit_GridLayout.addWidget(self.toolButton33,3,2,1,1)
self.toolButton34 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton34.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton34.setCheckable(True)
self.toolButton34.setFont(font)
self.toolButton34.setObjectName("toolButton34")
self.MMKit_GridLayout.addWidget(self.toolButton34,3,3,1,1)
self.toolButton35 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton35.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton35.setCheckable(True)
self.toolButton35.setFont(font)
self.toolButton35.setObjectName("toolButton35")
self.MMKit_GridLayout.addWidget(self.toolButton35,3,4,1,1)
self.toolButton32 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton32.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton32.setCheckable(True)
self.toolButton32.setFont(font)
self.toolButton32.setObjectName("toolButton32")
self.MMKit_GridLayout.addWidget(self.toolButton32,3,1,1,1)
self.toolButton36 = QtGui.QToolButton(self.elementButtonGroup)
self.toolButton36.setFixedSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.toolButton36.setCheckable(True)
self.toolButton36.setFont(font)
self.toolButton36.setObjectName("toolButton36")
self.MMKit_GridLayout.addWidget(self.toolButton36,3,5,1,1)
self.atomsPage_VBoxLayout.addWidget(self.elementButtonGroup)
# Height is fixed (i.e. locked). Mark 2007-05-29.
self.elementButtonGroup.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
# Atomic Hybrid label
self.atomic_hybrids_label = QtGui.QLabel(self.atomsPageFrame)
self.atomic_hybrids_label.setText("Atomic Hybrids :")
self.atomsPage_VBoxLayout.addWidget(self.atomic_hybrids_label)
# Elements Button GroupBox ends here. #######################
# This special HBoxLayout contains both the hybrid button group and a
# vert spacer (width = 0) to keep the Qt layout working properly
# in certain situations like that described in bug 2407.
# Mark 2007-06-20.
self.special_HBoxLayout = QtGui.QHBoxLayout()
self.special_HBoxLayout.setMargin(0)
self.special_HBoxLayout.setSpacing(6)
self.special_HBoxLayout.setObjectName("special_HBoxLayout")
self.atomsPage_VBoxLayout.addLayout(self.special_HBoxLayout)
# Hybrid GroupBox begins here ###############################
self.hybrid_btngrp = QtGui.QGroupBox(self.atomsPageFrame)
self.hybrid_btngrp.setObjectName("hybrid_btngrp")
self.special_HBoxLayout.addWidget(self.hybrid_btngrp)
self.hybridBtns_HBoxLayout = QtGui.QHBoxLayout(self.hybrid_btngrp)
self.hybridBtns_HBoxLayout.setMargin(2)
self.hybridBtns_HBoxLayout.setSpacing(0)
self.hybridBtns_HBoxLayout.setObjectName("hybridBtns_HBoxLayout")
self.sp3_btn = QtGui.QToolButton(self.hybrid_btngrp)
self.sp3_btn.setMinimumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.sp3_btn.setMaximumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.sp3_btn.setCheckable(True)
self.sp3_btn.setObjectName("sp3_btn")
self.hybridBtns_HBoxLayout.addWidget(self.sp3_btn)
self.sp2_btn = QtGui.QToolButton(self.hybrid_btngrp)
self.sp2_btn.setMinimumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.sp2_btn.setMaximumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.sp2_btn.setCheckable(True)
self.sp2_btn.setObjectName("sp2_btn")
self.hybridBtns_HBoxLayout.addWidget(self.sp2_btn)
self.sp_btn = QtGui.QToolButton(self.hybrid_btngrp)
self.sp_btn.setMinimumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.sp_btn.setMaximumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.sp_btn.setCheckable(True)
self.sp_btn.setObjectName("sp_btn")
self.hybridBtns_HBoxLayout.addWidget(self.sp_btn)
self.graphitic_btn = QtGui.QToolButton(self.hybrid_btngrp)
self.graphitic_btn.setMinimumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.graphitic_btn.setMaximumSize(QtCore.QSize(pmMMKitButtonWidth,pmMMKitButtonHeight))
self.graphitic_btn.setCheckable(True)
self.graphitic_btn.setObjectName("graphitic_btn")
self.hybridBtns_HBoxLayout.addWidget(self.graphitic_btn)
# This VSpacer is needed to help (but not completely) fix bug 2407. It
# maintains the height of the layout(s) containing the hybrid button
# group when it is hidden using hide(). Without this spacer the layout
# gets screwed up in special situations like that described in bug 2407.
# The + 10 below is needed to account for the margin (4 pixels) and
# the additional 6 just help (I have a theory that the height of the
# frame containing the label above the hybrid group box shrinks when
# the label is hidden by inserting a space character). I'm
# not going to worry about this now. +10 works well enough.
# Mark 2007-06-20.
VSpacer = QtGui.QSpacerItem(0, pmMMKitButtonHeight + 10,
QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Fixed)
#self.hybridBtns_HBoxLayout.addItem(VSpacer)
self.special_HBoxLayout.addItem(VSpacer)
self.hybridBtns_HBoxLayout.addStretch(0)
# Height is fixed. Mark 2007-05-29.
self.hybrid_btngrp.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.MinimumExpanding),
QSizePolicy.Policy(QSizePolicy.Fixed)))
# This spacer keeps the MMKit button grid compressed when
# the hybrid button group is hidden.
self.atomsPageBottomVSpacer = \
QtGui.QSpacerItem(5, 0,
QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.MinimumExpanding)
self.atomsPage_VBoxLayout.addItem(self.atomsPageBottomVSpacer)
# Clipboard page begins here ############################################
self.clipboardPage = QtGui.QWidget()
self.clipboardPage.setObjectName("clipboardPage")
self.gridlayout3 = QtGui.QGridLayout(self.clipboardPage)
self.gridlayout3.setMargin(pmMMKitPageMargin) # Was 4. Mark 2007-05-30
self.gridlayout3.setSpacing(2)
self.gridlayout3.setObjectName("gridlayout3")
self.chunkListBox = QtGui.QListWidget(self.clipboardPage)
self.chunkListBox.setMinimumSize(QtCore.QSize(100,100))
# Height is fixed. Mark 2007-05-29.
self.chunkListBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.MinimumExpanding),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.chunkListBox.setObjectName("chunkListBox")
self.gridlayout3.addWidget(self.chunkListBox,0,0,1,1)
self.mmkit_tab.addTab(self.clipboardPage, "")
self.libraryPage = QtGui.QWidget()
#self.libraryPage = QtGui.QScrollArea()
#self.libraryPageWidget = QtGui.QWidget()
#self.libraryPage.setWidget(self.libraryPageWidget)
self.libraryPage.setObjectName("libraryPage")
self.mmkit_tab.addTab(self.libraryPage, "")
self.MMKitGrpBox_VBoxLayout.addWidget(self.mmkit_tab)
self.transmuteAtomsAction = QtGui.QWidgetAction(self.w)
self.transmuteAtomsAction.setText("Transmute Atoms")
self.transmuteAtomsAction.setIcon(geticon(
'ui/actions/Toolbars/Smart/Transmute_Atoms'))
self.transmuteAtomsAction.setCheckable(False)
transmuteBtn_HBoxLayout = QtGui.QHBoxLayout()
self.transmuteBtn = QtGui.QToolButton(self.MMKit_groupBox)
self.transmuteBtn.setDefaultAction(self.transmuteAtomsAction)
self.transmuteBtn.setFixedSize(QtCore.QSize(36, 36))
self.transmuteBtn.setIconSize(QtCore.QSize(22,22))
transmuteBtn_HBoxLayout.addWidget(self.transmuteBtn)
self.browseButton = QtGui.QPushButton(MMKitDialog)
transmuteBtn_HBoxLayout.addWidget(self.browseButton)
self.defaultPartLibButton = QtGui.QPushButton(MMKitDialog)
transmuteBtn_HBoxLayout.addWidget(self.defaultPartLibButton)
self.atomsPageSpacer = QtGui.QSpacerItem(0, 5,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Minimum)
transmuteBtn_HBoxLayout.addItem(self.atomsPageSpacer)
self.MMKitGrpBox_VBoxLayout.addLayout(transmuteBtn_HBoxLayout)
self.transmuteCB = QtGui.QCheckBox(" Force to Keep Bonds", self.MMKit_groupBox)
self.MMKitGrpBox_VBoxLayout.addWidget(self.transmuteCB)
#End MMKit groupbox
self.pmVBoxLayout.addWidget(self.MMKit_groupBox)
# This line is important. Without it, the MMKit groupbox is
# too wide by default and causes a horizontal scrollbar
# to be displayed at the bottom of the PropMgr. Mark 2007-05-30
self.MMKit_groupBox.setMinimumWidth(200)
# Height is fixed. Mark 2007-05-29.
self.MMKit_groupBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.MinimumExpanding),
QSizePolicy.Policy(QSizePolicy.Fixed)))
def ui_selectionFilter_GroupBox(self, MMKitDialog):
#Start Selection Filter GroupBox
self.selectionFilter_groupBox = QtGui.QGroupBox(MMKitDialog)
self.selectionFilter_groupBox.setObjectName("selectionFilter_groupBox")
self.selectionFilter_groupBox.setAutoFillBackground(True)
palette = MMKitDialog.getGroupBoxPalette()
self.selectionFilter_groupBox.setPalette(palette)
styleSheet = MMKitDialog.getGroupBoxStyleSheet()
self.selectionFilter_groupBox.setStyleSheet(styleSheet)
self.hboxlayout_selfilter = QtGui.QHBoxLayout()
self.hboxlayout_selfilter.setMargin(pmGrpBoxVboxLayoutMargin)
self.hboxlayout_selfilter.setSpacing(6)
self.hboxlayout_selfilter.setObjectName("hboxlayout_selfilter")
self.vboxlayout_selfilter = QtGui.QVBoxLayout(self.selectionFilter_groupBox)
self.vboxlayout_selfilter.setMargin(pmGrpBoxVboxLayoutMargin)
self.vboxlayout_selfilter.setSpacing(6)
self.vboxlayout_selfilter.setObjectName("vboxlayout_selfilter")
self.filterCB = MMKitDialog.getGroupBoxTitleCheckBox("Selection Filter ", self.selectionFilter_groupBox )
self.vboxlayout_selfilter.addWidget(self.filterCB)
self.selectionFilter_label = QtGui.QLabel(self.selectionFilter_groupBox)
self.vboxlayout_selfilter.addWidget(self.selectionFilter_label)
self.filterlistLE = QLineEdit(self.selectionFilter_groupBox)
self.filterlistLE.setReadOnly(1)
self.filterlistLE.setEnabled(0)
if self.filterCB.isChecked():
self.filterlistLE.show()
self.selectionFilter_label.show()
else:
self.filterlistLE.hide()
self.selectionFilter_label.hide()
self.vboxlayout_selfilter.addWidget(self.filterlistLE)
#End Selection filter GroupBox
self.pmVBoxLayout.addWidget(self.selectionFilter_groupBox)
# Height is fixed. Mark 2007-05-29.
self.selectionFilter_groupBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
def ui_advancedOptions_groupBox(self, MMKitDialog):
#Start Advanced Options GroupBox
self.advancedOptions_groupBox = QtGui.QGroupBox(MMKitDialog)
self.advancedOptions_groupBox.setObjectName("advancedOptions_groupBox")
self.advancedOptions_groupBox.setAutoFillBackground(True)
palette = MMKitDialog.getGroupBoxPalette()
self.advancedOptions_groupBox.setPalette(palette)
styleSheet = MMKitDialog.getGroupBoxStyleSheet()
self.advancedOptions_groupBox.setStyleSheet(styleSheet)
self.vboxlayout_grpbox4 = QtGui.QVBoxLayout(self.advancedOptions_groupBox)
self.vboxlayout_grpbox4.setMargin(pmGrpBoxVboxLayoutMargin)
self.vboxlayout_grpbox4.setSpacing(pmGrpBoxVboxLayoutSpacing)
self.vboxlayout_grpbox4.setObjectName("vboxlayout_grpbox4")
self.advancedOptions_groupBoxButton = MMKitDialog.getGroupBoxTitleButton("Advanced Options",
self.advancedOptions_groupBox)
self.vboxlayout_grpbox4.addWidget(self.advancedOptions_groupBoxButton)
self.autobondCB = QtGui.QCheckBox("Autobond", self.advancedOptions_groupBox )
self.autobondCB.setChecked(env.prefs[buildModeAutobondEnabled_prefs_key])
self.vboxlayout_grpbox4.addWidget(self.autobondCB)
self.highlightingCB = QtGui.QCheckBox("Highlighting", self.advancedOptions_groupBox )
self.highlightingCB.setChecked(env.prefs[buildModeHighlightingEnabled_prefs_key])
self.vboxlayout_grpbox4.addWidget(self.highlightingCB)
self.waterCB = QtGui.QCheckBox("Water", self.advancedOptions_groupBox )
self.waterCB.setChecked(env.prefs[buildModeWaterEnabled_prefs_key])
self.vboxlayout_grpbox4.addWidget(self.waterCB)
#End Advanced Options GroupBox
self.pmVBoxLayout.addWidget(self.advancedOptions_groupBox)
# Height is fixed. Mark 2007-05-29.
self.advancedOptions_groupBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
def retranslateUi(self, MMKitDialog):
MMKitDialog.setWindowTitle(QtGui.QApplication.translate("MMKitDialog",
"MMKit", None, QtGui.QApplication.UnicodeUTF8))
MMKitDialog.setWindowIcon(QtGui.QIcon("ui/border/MMKit"))
self.elementFrame.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Preview window of active object.", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton1.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Hydrogen", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton1.setText(QtGui.QApplication.translate("MMKitDialog", "H", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton1.setShortcut(QtGui.QApplication.translate("MMKitDialog", "H", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton2.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Helium", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton2.setText(QtGui.QApplication.translate("MMKitDialog", "He", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton6.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Carbon", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton6.setText(QtGui.QApplication.translate("MMKitDialog", "C", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton6.setShortcut(QtGui.QApplication.translate("MMKitDialog", "C", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton7.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Nitrogen", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton7.setText(QtGui.QApplication.translate("MMKitDialog", "N", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton7.setShortcut(QtGui.QApplication.translate("MMKitDialog", "N", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton8.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Oxygen", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton8.setText(QtGui.QApplication.translate("MMKitDialog", "O", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton8.setShortcut(QtGui.QApplication.translate("MMKitDialog", "O", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton10.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Neon", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton10.setText(QtGui.QApplication.translate("MMKitDialog", "Ne", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton9.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Fluorine", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton9.setText(QtGui.QApplication.translate("MMKitDialog", "F", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton9.setShortcut(QtGui.QApplication.translate("MMKitDialog", "F", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton13.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Aluminum", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton13.setText(QtGui.QApplication.translate("MMKitDialog", "Al", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton13.setShortcut(QtGui.QApplication.translate("MMKitDialog", "A", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton17.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Chlorine", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton17.setText(QtGui.QApplication.translate("MMKitDialog", "Cl", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton17.setShortcut(QtGui.QApplication.translate("MMKitDialog", "L", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton5.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Boron", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton5.setText(QtGui.QApplication.translate("MMKitDialog", "B", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton5.setShortcut(QtGui.QApplication.translate("MMKitDialog", "B", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton10_2.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Argon", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton10_2.setText(QtGui.QApplication.translate("MMKitDialog", "Ar", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton15.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Phosphorus", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton15.setText(QtGui.QApplication.translate("MMKitDialog", "P", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton15.setShortcut(QtGui.QApplication.translate("MMKitDialog", "P", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton16.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Sulfur", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton16.setText(QtGui.QApplication.translate("MMKitDialog", "S", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton16.setShortcut(QtGui.QApplication.translate("MMKitDialog", "S", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton14.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Silicon", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton14.setText(QtGui.QApplication.translate("MMKitDialog", "Si", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton14.setShortcut(QtGui.QApplication.translate("MMKitDialog", "Q", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton33.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Arsenic", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton33.setText(QtGui.QApplication.translate("MMKitDialog", "As", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton34.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Selenium", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton34.setText(QtGui.QApplication.translate("MMKitDialog", "Se", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton35.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Bromine", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton35.setText(QtGui.QApplication.translate("MMKitDialog", "Br", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton32.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Germanium", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton32.setText(QtGui.QApplication.translate("MMKitDialog", "Ge", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton36.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Krypton", None, QtGui.QApplication.UnicodeUTF8))
self.toolButton36.setText(QtGui.QApplication.translate("MMKitDialog", "Kr", None, QtGui.QApplication.UnicodeUTF8))
self.sp3_btn.setToolTip(QtGui.QApplication.translate("MMKitDialog", "sp3", None, QtGui.QApplication.UnicodeUTF8))
self.sp3_btn.setShortcut(QtGui.QApplication.translate("MMKitDialog", "3", None, QtGui.QApplication.UnicodeUTF8))
self.sp2_btn.setToolTip(QtGui.QApplication.translate("MMKitDialog", "sp2", None, QtGui.QApplication.UnicodeUTF8))
self.sp2_btn.setShortcut(QtGui.QApplication.translate("MMKitDialog", "2", None, QtGui.QApplication.UnicodeUTF8))
self.sp_btn.setToolTip(QtGui.QApplication.translate("MMKitDialog", "sp", None, QtGui.QApplication.UnicodeUTF8))
self.sp_btn.setShortcut(QtGui.QApplication.translate("MMKitDialog", "1", None, QtGui.QApplication.UnicodeUTF8))
self.graphitic_btn.setToolTip(QtGui.QApplication.translate("MMKitDialog", "Graphitic", None, QtGui.QApplication.UnicodeUTF8))
self.graphitic_btn.setShortcut(QtGui.QApplication.translate("MMKitDialog", "4", None, QtGui.QApplication.UnicodeUTF8))
self.mmkit_tab.setTabText(self.mmkit_tab.indexOf(self.atomsPage), QtGui.QApplication.translate("MMKitDialog", "", None, QtGui.QApplication.UnicodeUTF8))
self.mmkit_tab.setTabText(self.mmkit_tab.indexOf(self.clipboardPage), QtGui.QApplication.translate("MMKitDialog", "", None, QtGui.QApplication.UnicodeUTF8))
self.mmkit_tab.setTabText(self.mmkit_tab.indexOf(self.libraryPage), QtGui.QApplication.translate("MMKitDialog", "", None, QtGui.QApplication.UnicodeUTF8))
self.selectionFilter_label.setText(QtGui.QApplication.translate("selectionFilter_groupBox",
"Apply Filter To:",
None, QtGui.QApplication.UnicodeUTF8))
self.browseButton.setToolTip(QtGui.QApplication.translate(
"MMKitDialog",
"Open file chooser dialog to select a new directory.",
None, QtGui.QApplication.UnicodeUTF8))
self.browseButton.setText(QtGui.QApplication.translate(
"MMKitDialog", "Browse...",None, QtGui.QApplication.UnicodeUTF8))
self.defaultPartLibButton.setText(QtGui.QApplication.translate(
"MMKitDialog", "Default Dir", None, QtGui.QApplication.UnicodeUTF8))
self.defaultPartLibButton.setToolTip(QtGui.QApplication.translate(
"MMKitDialog", "Reset the partlib directory path to program default",
None, QtGui.QApplication.UnicodeUTF8))
| NanoCAD-master | cad/src/outtakes/MMKitDialog.py |
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details.
"""
modelTreePrototype.py
$Id$
This is a prototype for a Qt 4 compatible Model Tree. It is a standalone test program, not part of NE1 proper.
Usage: on some sysems, this can be run from the command line using
% pythonw `pwd`/modelTreePrototype.py
Goals/plans:
Develop a clear simple API for the model tree, then work on the model tree in isolation using simple
test data, and then plug the working model tree into the rest of NE-1. This amounts to a refactoring
of the code currently spread between TreeView.py, TreeWidget.py, and modelTree.py.
The API needs to accomplish three things. First it must work in just this file with a very
restricted set of data, and in this context I need to bang on issues of selection, display, and
other GUI stuff. Second it needs to work with the uiPrototype.py stuff for the new user interface.
Third it needs to migrate into the NE-1 code cleanly, ideally with just a change of the filename.
"""
import sys
from PyQt4.Qt import QTreeView
from PyQt4.Qt import QItemDelegate
from PyQt4.Qt import QAbstractItemModel
from PyQt4.Qt import QGroupBox
from PyQt4.Qt import QMainWindow
from PyQt4.Qt import QIcon
from PyQt4.Qt import QTextEdit
from PyQt4.Qt import QVariant
from PyQt4.Qt import Qt
from PyQt4.Qt import QModelIndex
from PyQt4.Qt import QItemSelectionModel
from PyQt4.Qt import QFontMetrics
from PyQt4.Qt import QLineEdit
from PyQt4.Qt import QDrag
from PyQt4.Qt import QMimeData
from PyQt4.Qt import QPoint
from PyQt4.Qt import QMouseEvent
from PyQt4.Qt import QMenu
from PyQt4.Qt import QAction
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QPixmap
from PyQt4.Qt import QVBoxLayout
from PyQt4.Qt import QHBoxLayout
from PyQt4.Qt import QPushButton
from PyQt4.Qt import QApplication
_ICONSIZE = (22, 22) #bruce 070507 copied this over, not used enough
def todo(x):
print 'TODO:', x
# These base classes are JUST the API. Functionality is implemented by extending these base classes.
# Context menu events can rearrange the structure in various ways. Items in the model tree can be
# hidden or disabled or deleted. An item can be moved or copied from one place in the tree to
# another. These things are done by the customer, OUTSIDE the model tree, and then the customer
# gives the model tree a new structure. Aside from the context menus, the model tree does not make
# callbacks to the customer code.
# Customer code should depend ONLY on the API as presented, and treat it as a contract. Then any
# bugs are either API bugs and implementation bugs, and the implementation bugs become relatively
# isolated and easier to fix.
# http://en.wikipedia.org/wiki/Duck_typing describes how API compliance works in Python. In Java or
# C++, the only way to guarantee that class B complies with class A's API is for B to subclass A. In
# Python, there is no such compile-time check, Python just raises an exception if we try to use a
# method that isn't implemented.
"""
Bruce suggests the following. Make a list of all the methods in TreeView/TreeWidget/modelTree, and
classify all those methods as follows. Here I will use the word 'model' to refer to NE-1's concept
of a tree of Nodes, rather than the Qt4 concept of a model as a tree of items.
(1) Methods that are internal to the view, which should be limited to TreeView and TreeWidget.
(2) Methods that are internal to the model, which should be limited to modelTree.
(3) Methods which the view exposes to the model: their definitions appear in TreeView or
TreeWidget, but they are used in modelTree.
(4) Methods which the model exposes to the view: their definitions appear in modelTree, but they
are used in TreeView or TreeWidget.
The (3) methods define the view API as seen by the model. The (4) methods define the model API as
seen by the view. One thing we will find in (4) is a callback to create a context menu spec, and the
model doesn't know when the view will need that so it does have to be a callback.
The model includes, but is not limited to, the tree of Nodes that I've been thinking about thusfar.
So my API is the (3) and (4) methods, and I can ignore the (1) and (2) methods.
Generally, what will happen is that the NE-1 'model' will be translated to a Qt4 'model' by
something like make_new_subtree_for_node. So the use of the words 'view' and 'model' here are from
NE-1's perspective, not the way Qt4 thinks of them.
-----------------------------------------------
The API that the view exposes to the model is these (3) methods:
pick(self, item, group_select_kids=True)
unpick(self, item, group_select_kids=True)
topmost_selected_nodes(self)
mt_update(self, nodetree=None)
toggle_open(self, item, openflag=None)
The API that the model exposes to the view is these (4) methods:
get_topnodes(self)
post_update_topitems(self)
QListViewItem_subclass_for_node(self, node, parent, display_prefs, after)
make_cmenuspec_for_set(self, nodeset, optflag)
=============================
How does renaming work in Qt 3?
TreeWidget.slot_itemRenamed() is connected to Q3ListView.itemRenamed(). It accepts an item, a column
number, and the new text. If everything is OK, it calls item.setText(col,newname). What I am not
seeing is how the name gets from the Q3ListViewItem back to the Node. So renaming is a big mystery to
me, and I'll ask Bruce about it later.
"""
class ModelTree_api: #bruce 081216 renamed this from Ne1Model_api to ModelTree_api
def get_topnodes(self):
"""Return a list of the top-level nodes, typically assy.tree and assy.shelf for an Assembly.
"""
raise Exception('overload me')
return []
def make_cmenuspec_for_set(self, nodeset, optflag):
"""Return a Menu_spec list (of a format suitable for makemenu_helper)
for a context menu suitable for nodeset, a list of 0 or more selected nodes
(which includes only the topmost selected nodes, i.e. it includes no
children of selected nodes even if they are selected).
<optflag> can be 'Option' or None, in case menus want to include
additional items when it's 'Option'.
Subclasses should override this to provide an actual menu spec.
The subclass implementation can directly examine the selection status of nodes
below those in nodeset, if desired, and can assume every node in nodeset is picked,
and every node not in it or under something in it is not picked.
[all subclasses should override this]
"""
raise Exception('overload me')
return [ ]
#
# These other two methods, I think I maybe don't need.
#
def post_update_topitems(self):
"#doc"
# The Qt 3 code provides no useful documentation on this method. What it actually does is
# just <<< self.tree_item, self.shelf_item = self.topitems[0:2] >>>. self.tree_item is used
# in viewportPaintEvent (described as 'the main redrawing event for a QListView').
# self.shelf_item is some kind of pointer to the clipboard, and is used as an argument to
# toggle_open(). self.tree_item and self.shelf_item are subclasses of QListViewItem.
# I will need to think about the behavior for opening groups and clipboards.
# The NE-1 model should NEVER EVER thinks about Qt items. I will consider this method to be
# internal to the view and not a part of the formal API.
raise Exception('overload me')
def QtItem_subclass_for_node(self, node, parent, display_prefs, after):
"""Return an appropriate subclass of QItemDelegate for this node.
This subclass's __init__ must work for either of these two forms of arglist,
by testing the type of the second argument:
self, parent, after (after = another QListView item)
or self, parent, text.
Furthermore, its setText method must work for (self, 0, text)
in the same way as its __init__ method (or by letting QListViewItem handle it).
[Subclasses of TreeView can override this method, perhaps by letting their
tree's nodes influence the chosen subclass, or perhaps having a custom subclass
for the entire tree.]
"""
# I don't want to use this. Bruce's original intent was that this code should be useful for
# other trees besides the model tree. To do that, you should subclass ModelTree below and
# redefine make_new_subtree_for_node() to refer to a new class that inherits _QtTreeItem.
#
# The NE-1 model should NEVER EVER thinks about Qt items. Let the customer code define
# subclasses of ModelTree and _QtTreeItem, and confine any magical paint() code to those.
raise Exception('overload me')
class Node_api:
"""The customer must provide a node type that meets this API. This can be done by extending this
class, or implementing it yourself.
"""
# There still needs to be an API call to support renaming, where the model tree is allowed to
# change the Node's name.
def __init__(self):
"""self.name MUST be a string instance variable. self.hidden MUST be a boolean instance
variable. There is no API requirement about arguments for __init__.
"""
raise Exception('overload me')
def is_disabled(self):
"""MUST return a boolean"""
raise Exception('overload me')
def node_icon(self, display_prefs):
"""MUST return either a QPixmap or None"""
# display_prefs is used in Group.node_icon to indicate whether a group is open or closed. It
# is not used anywhere else. It is a dictionary and the only relevant key for it is"open".
raise Exception('overload me')
def drop_on_ok(self, drag_type, nodes):
"""Say whether 'drag and drop' can drop the given set of nodes onto this node, when they are
dragged in the given way
"""
raise Exception('overload me')
def drop_on(self, drag_type, nodes):
"""After a 'drag and drop' of type 'move' or 'copy' (according to drag_type), perform the
drop of the given list of nodes onto this node. Return any new nodes this creates (toplevel
nodes only, for copied groups).
"""
raise Exception('overload me')
def kids(self, item_prefs):
"""Return a list of Nodes that are a child of this Node.
"""
raise Exception('overload me')
class ModelTreeGUI_api(QTreeView): #bruce 081216 renamed this from ModelTree_api to ModelTreeGUI_api
"""
This should be a Qt4 widget that can be put into a layout.
"""
def pick(self, item, group_select_kids=True):
"select the given item (actually the node or group it shows)"
raise Exception('overload me')
def unpick(self, item, group_select_kids=True):
"deselect the given item (actually the node or group it shows)"
raise Exception('overload me')
def topmost_selected_nodes(self): #e might be needed by some context menus... how should the makers ask for it?
"return a list of all selected nodes as seen by apply2picked, i.e. without looking inside selected Groups"
raise Exception('overload me')
def mt_update(self, nodetree=None):
"""External code (or event bindings in a subclass, if they don't do enough repainting themselves)
should call this when it might have changed any state that should
affect what's shown in the tree. (Specifically: the ordering or grouping of nodes,
or the icons or text they should display, or their open or selected state.) (BTW external
code probably has no business changing node.open since it is slated to become a tree-
widget-specific state in the near future.)
If these changes are known to be confined to a single node and its children,
that node can be passed as a second argument as a possible optimization
(though as of 050113 the current implem does not take advantage of this).
"""
raise Exception('overload me')
def toggle_open(self, item, openflag=None):
"""Toggle the open/closed state of this item, or set it to openflag
if that's supplied. Do all necessary invals or repaints, including
creation of new child items if needed.
(Error if item is not openable; this may or may not be checked here.)
"""
raise Exception('overload me')
####################### End of the API #############################
####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
#################### Implementation ################################
class _QtTreeItem(QItemDelegate):
# Extending QItemDelegate allows you to customize the paint() method. We need to do this because
# we have a combination of requirements that weren't anticipated in Qt 4.1, more might be
# available in Qt 4.2.
#
# QTreeWidget can give you icons and a tree structure, but you don't get much ability to
# customize things like shear, and you can't force a repaint of the model tree when you want it.
#
# QTreeView provides a forced repaint with the setModel() method (see notes below about
# veryShallowClone). The hassle of doing this is needing to learn the intricacies of Qt's
# model/view programming model.
#
def __init__(self, node, parent=None):
QItemDelegate.__init__(self, parent)
self.node = node
self.childItems = []
self.cmenu = [ ]
self.editing = False
if parent is not None:
parent.childItems.append(self)
self.parentItem = parent
def __repr__(self):
return '<%s \"%s\">' % (self.__class__.__name__, self.node.name)
def paint(self, painter, option, index):
item = index.internalPointer()
x, y = option.rect.x(), option.rect.y()
## selected = (index in self.view.selectedIndexes())
selected = item.node.picked
disabled = item.node.is_disabled()
hidden = item.node.hidden
if selected: # before
background = painter.background()
backgroundMode = painter.backgroundMode()
painter.setBackground(self.view.palette().highlight())
painter.setBackgroundMode(Qt.OpaqueMode)
if disabled: # before
painter.shear(0, -0.5)
painter.translate(0.5 * y + 4, 0.0)
display_prefs = { } # ? ? ? ?
pixmap = QIcon(item.node.node_icon(display_prefs)).pixmap(16, 16)
painter.drawPixmap(x, y, pixmap)
painter.drawText(x + 20, y + 12, item.node.name)
if disabled: # after
painter.translate(-0.5 * y - 4, 0.0)
painter.shear(0, 0.5)
if selected: # after
painter.setBackground(background)
painter.setBackgroundMode(backgroundMode)
#def sizeHint(self, styleOptions, index):
# return QSize(16, 16)
# This stuff is supposed to help with renaming, but it's not working yet.
#
def createEditor(self, parent, option, index):
editor = QTextEdit(parent)
editor.setMinimumHeight(24)
return editor
def setEditorData(self, textEdit, index):
value = str(index.model().data(index, Qt.DisplayRole).toString())
textEdit.setPlainText(value)
def setModelData(self, textEdit, model, index):
value = textEdit.toPlainText()
model.setData(index, QVariant(value))
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
####################################################################
# Here is a potentially confusing point. There are two levels of model. Because of
# Qt's model/view paradigm, we need a "Qt model" separate from the view of the data
# in the model. But all that stuff is packaged into something that looks like a
# view, from NE-1's perspective.
class _QtTreeModel(QAbstractItemModel):
def __init__(self, rootItem=None):
QAbstractItemModel.__init__(self)
self.rootItem = rootItem
self.indexdict = { } # maps Nodes to indexes?
def helper(item, self=self):
row = 0
for x in item.childItems:
self.indexdict[x] = self.createIndex(row, 0, x)
row += 1
helper(x)
helper(rootItem)
def veryShallowClone(self):
# This is part of the magic to UPDATING the model tree. We clone the model, and call
# setModel on the new guy. We can use a very shallow clone for this, the QTreeView only
# needs to see the pointer change.
#
return _QtTreeModel(self.rootItem)
# We don't need indexToItem because we can use index.internalPointer().
def itemToIndex(self, item):
try:
return self.indexdict[item]
except KeyError:
return QModelIndex()
# The following methods are the the official API required by QTreeView's idea of how
# QAbstractItemModel should work.
def columnCount(self, parent):
return 1
def data(self, index, role):
if not index.isValid():
return QVariant()
if role != Qt.DisplayRole:
return QVariant()
item = index.internalPointer()
return QVariant(item.node.name)
def setData(self, index, qvar):
item = index.internalPointer()
item.node.name = str(qvar.toString())
def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled | Qt.ItemIsEditable
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.rootItem.node.name)
return QVariant()
def index(self, row, column, parent):
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.childItems[row]
if childItem:
return self.createIndex(row, column, childItem)
else:
return QModelIndex()
def parent(self, index):
if not index.isValid():
return QModelIndex()
childItem = index.internalPointer()
parentItem = childItem.parentItem
if parentItem == self.rootItem:
return QModelIndex()
if parentItem.parentItem is None:
parentRow = 0
else:
parentRow = parentItem.parentItem.childItems.index(parentItem)
return self.createIndex(parentRow, 0, parentItem)
def rowCount(self, parent):
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return len(parentItem.childItems)
####################################################################
class ModelTree(ModelTreeGUI_api):
def __init__(self, name, treemodel, parent=None):
QTreeView.__init__(self, parent)
self.treemodel = treemodel #bruce 081216 renamed this from ne1model
treemodel.view = self
self.setSelectionMode(self.ExtendedSelection) #bruce 070507 MultiSelection -> ExtendedSelection
self.qtmodel = None
self.drag = None
self.setAcceptDrops(True)
def selectedList(self):
return map(lambda x: x.internalPointer().node,
self.selectedIndexes())
def selectNodes(self, nodes, but_not=[ ]):
selmodel = QItemSelectionModel(self.qtmodel, self)
self.setSelectionModel(selmodel)
for x in nodes:
if x not in but_not:
item = self.node_to_item_dict.get(x, None)
if item is not None:
index = self.qtmodel.itemToIndex(item)
if index.isValid():
selmodel.select(index, selmodel.Select)
def mt_update(self):
###REVIEW: this is an update method, but ideally it would be an invalidation method
# (like I think it was in Qt3, though I'm not sure). Certainly it might be pretty slow this way
# since it might do more updates than needed. [bruce 070504 comment]
# save the list of which nodes are selected, we need them later
selectedList = self.selectedList()
# throw away all references to existing list items
self.item_to_node_dict = { }
self.node_to_item_dict = { }
# Make a "fake" root node and give it the list of top nodes as children. Then convert the
# tree of Nodes to a whole new tree of _QtTreeItems, populating the two dicts as we go.
class FakeTopNode:
def __init__(self, name, kidlist):
self.name = name
self.hidden = False
self.kidlist = kidlist
def kids(self, item_prefs):
return self.kidlist
def is_disabled(self):
return False
def node_icon(self, display_prefs):
return None
rootNode = FakeTopNode("Model tree", self.treemodel.get_topnodes())
rootItem = self.make_new_subtree_for_node(rootNode)
self.qtmodel = model = _QtTreeModel(rootItem)
self.setModel(model)
self.setItemDelegate(rootItem)
rootItem.view = self # needed for paint()
# When we did setModel(), we lost the old selection information, so reselect
self.selectNodes(selectedList)
self.expandAll() ###BUG
self.show()
def make_new_subtree_for_node(self, node, parent=None):
item = _QtTreeItem(node, parent)
display_prefs = item_prefs = { } # ? ? ?
# item.icon = QIcon(node.node_icon(display_prefs))
self.item_to_node_dict[item] = node
self.node_to_item_dict[node] = item
for kid in node.kids(item_prefs):
self.make_new_subtree_for_node(kid, item)
return item
def expandAll(self):
# With Qt 4.2, QTreeView will have its own expandAll method.
# [bruce 070504 comment: we don't need this method anyway -- its only call is a bug.]
for index in self.qtmodel.indexdict.values():
self.expand(index)
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dragMoveEvent(self, event):
event.acceptProposedAction()
def dropEvent(self, event):
index = self.indexAt(event.pos())
sellst = self.selectedList()
if index.isValid():
target_node = index.internalPointer().node
dragged_nodes, drag_type, qdrag = self.drag
# I don't think we need qdrag for anything, but it can't hurt.
if target_node.drop_on_ok(drag_type, dragged_nodes):
self.selectNodes(sellst, but_not=dragged_nodes)
target_node.drop_on(drag_type, dragged_nodes)
event.acceptProposedAction()
self.mt_update()
self.drag = None
return
event.ignore()
self.mt_update()
self.drag = None
def mouseMoveEvent(self, event):
if self.drag is not None:
QTreeView.mouseMoveEvent(self, event)
return
if ((event.globalPos() - self.mouse_press_qpoint).manhattanLength()
< QApplication.startDragDistance()):
return
#
# starting a drag
# [logic bug, after bruce change 070507: should not do this
# if we already started dragging out a selection. How can we tell?
# Only by whether the initial press had eventInRect, I think
# (not yet recorded), or at least, the initial move (#e could record here).]
#
index = self.indexAt(event.pos())
sellst = self.selectedList() # bruce 070507 move earlier
DEBUG2 = True
if index.isValid():
thisnode = index.internalPointer().node
#bruce 070507 bring in some code from modelTreeGui.py
alreadySelected = (thisnode in sellst)
item = index.internalPointer()
rect = self.visualRect(index)
if DEBUG2:
print "visualRect coords",rect.left(), rect.right(), rect.top(), rect.bottom()
qfm = QFontMetrics(QLineEdit(self).font())
rect.setWidth(qfm.width(item.node.name) + _ICONSIZE[0] + 4)
if DEBUG2:
print "visualRect coords, modified:",rect.left(), rect.right(), rect.top(), rect.bottom()
# looks like icon and text, a bit taller than text (guesses)
eventInRect = rect.contains(event.pos())
if DEBUG2:
print "valid index: eventInRect = %r, item = %r, index = %r, alreadySelected = %r" % \
(eventInRect, item, index, alreadySelected)#######
else:
thisnode = item = None
alreadySelected = eventInRect = False
if not eventInRect:
# nothing to drag, but [bruce 070507] let super handle it (for dragging over nodes to select)
self.drag_is_not_DND = True ### not yet used
QTreeView.mouseMoveEvent(self, event)
return
if thisnode in sellst:
# if dragging something selected, drag along all other selected ones
dragged_nodes = sellst
else:
# if dragging something unselected, ignore any selected ones
dragged_nodes = [ thisnode ]
qdrag = QDrag(self)
drag_type = 'move' # how do I decide between 'move' and 'copy'?
self.drag = (dragged_nodes, drag_type, qdrag)
mimedata = QMimeData()
mimedata.setText("need a string here for a valid mimetype")
qdrag.setMimeData(mimedata)
display_prefs = { }
pixmap = dragged_nodes[0].node_icon(display_prefs)
qdrag.setPixmap(pixmap)
qdrag.setHotSpot(QPoint(-8, 8))
qdrag.start()
def mousePressEvent(self, event):
self.drag_is_not_DND = False # don't know yet
qp = event.globalPos() # clone the point to keep it constant
self.mouse_press_qpoint = QPoint(qp.x(), qp.y())
self.mouse_press_event = QMouseEvent(event.type(),
QPoint(event.x(), event.y()),
event.button(), event.buttons(),
event.modifiers())
def mouseReleaseEvent(self, event):
self.drag_is_not_DND = False
if self.drag is None:
QTreeView.mousePressEvent(self, self.mouse_press_event)
self.drag = None
QTreeView.mouseReleaseEvent(self, event)
def contextMenuEvent(self, event):
menu = QMenu(self)
pos = event.pos()
index = self.indexAt(pos)
if index.isValid():
item = self.indexAt(pos).internalPointer()
node = self.item_to_node_dict[item]
nodeset = [ node ] # ? ? ? ?
optflag = False # ? ? ? ?
cmenu_spec = self.treemodel.make_cmenuspec_for_set(nodeset, optflag)
for x in cmenu_spec:
if x is not None:
str, thunk = x[:2]
act = QAction(str, self)
act.setEnabled("disabled" not in x[2:])
self.connect(act, SIGNAL("triggered()"), thunk)
menu.addAction(act)
else:
menu.addSeparator()
menu.exec_(event.globalPos())
################ End of implementation #############################
####################################################################
####################################################################
####################################################################
####################################################################
##################### Test code ####################################
class TestNode(Node_api):
def __init__(self, name, parent=None, icon=None, icon_hidden=None):
self.hidden = False
self._disabled = False
self.name = name
self.picked = True #bruce 070509 added this
self.icon = icon
self.icon_hidden = icon_hidden
# We need to implement a tree structure with Nodes, which
# is then duplicated in the _QtTreeItems.
self.parentNode = parent
if parent is not None:
parent.childNodes.append(self)
self.childNodes = [ ]
# beginning of official API
def drop_on_ok(self, drag_type, nodes):
import traceback
# We can't drop things on chunks or jigs
for node in nodes:
# don't drop stuff that's already here
if node in self.childNodes:
traceback.print_stack()
print self, nodes, node, self.childNodes
print 'node is in children already'
return False
if self.name.startswith("Chunk"):
traceback.print_stack()
print self, node, self.childNodes
print 'cannot drop on a chunk'
return False
if self.name.startswith("Jig"):
traceback.print_stack()
print self, node, self.childNodes
print 'cannot drop on a jig'
return False
return True
def drop_on(self, drag_type, nodes):
previous_parents = { }
for node in nodes:
if drag_type == 'copy':
node = node.clone()
previous_parents[node] = node.parentNode
self.childNodes.append(node)
node.parentNode = self
if drag_type == 'move':
for node in nodes:
if previous_parents.has_key(node):
previous_parents[node].childNodes.remove(node)
return [ ]
def node_icon(self, display_prefs):
# read up on display_prefs?
if self.hidden:
return self.icon_hidden
else:
return self.icon
def is_disabled(self):
return self._disabled
# end of official API
def clone(self):
newguy = self.__class__(self.name + "-copy", None, self.icon, self.icon_hidden)
newguy.hidden = self.hidden
newguy._disabled = self._disabled
newguy.childNodes = self.childNodes[:]
return newguy
def kids(self, item_prefs):
return self.childNodes
def __repr__(self):
return "<Node \"%s\">" % self.name
class TestClipboardNode(TestNode):
def __init__(self, name):
TestNode.__init__(self, name)
self.iconEmpty = QPixmap("../images/clipboard-empty.png")
self.iconFull = QPixmap("../images/clipboard-full.png")
self.iconGray = QPixmap("../images/clipboard-gray.png")
def node_icon(self, display_prefs):
if self.hidden: # is the clipboard ever hidden??
return self.iconGray
elif self.childNodes:
return self.iconFull
else:
return self.iconEmpty
class TestNe1Model(ModelTree_api):
def __init__(self):
self.untitledNode = TestNode("Untitled", None,
QPixmap("../images/part.png"))
self.clipboardNode = TestClipboardNode("Clipboard")
def get_topnodes(self):
return [self.untitledNode, self.clipboardNode]
def make_cmenuspec_for_set(self, nodeset, optflag):
for node in nodeset:
def thunk(str):
def _thunk(str=str):
print str
return _thunk
if isinstance(node, TestNode):
disableTuple = ('Disable', lambda node=node: self.cm_disable(node))
if node.name.startswith("Chunk"):
disableTuple += ('disabled',)
return [('Copy', lambda node=node: self.cm_copy(node)),
('Cut', lambda node=node: self.cm_cut(node)),
('Hide', lambda node=node: self.cm_hide(node)),
disableTuple,
None,
('Delete', lambda node=node: self.cm_delete(node))]
else:
return [('A', thunk('A')),
('B', thunk('B')),
None,
('C', thunk('C'), 'disabled'),
('D', thunk('D'))]
def cm_copy(self, node):
nodelist = self.view.selectedList()
if node not in nodelist:
nodelist.append(node)
self.clipboardNode.drop_on('copy', nodelist)
self.view.mt_update()
def cm_cut(self, node):
nodelist = self.view.selectedList()
if node not in nodelist:
nodelist.append(node)
self.clipboardNode.drop_on('move', nodelist)
self.view.mt_update()
def cm_disable(self, node):
node._disabled = not node._disabled
self.view.mt_update()
def cm_hide(self, node):
node.hidden = not node.hidden
self.view.mt_update()
def cm_delete(self, node):
self.untitledNode.childNodes.remove(node)
self.view.mt_update()
class TestWrapper(QGroupBox):
def __init__(self):
QGroupBox.__init__(self)
self.treemodel = treemodel = TestNe1Model()
self.view = view = ModelTree("Model tree", treemodel, self)
view.mt_update()
def thunk(str):
def _thunk(str=str):
print str
return _thunk
self.chunkNum = 2
self.gbox = QGroupBox()
vl = QVBoxLayout(self)
vl.setSpacing(0)
vl.setMargin(0)
vl.addWidget(self.view)
self.buttonLayout = hl = QHBoxLayout()
hl.setSpacing(0)
hl.setMargin(0)
vl.addLayout(hl)
self.buttonNum = 1
for func in (self.addmol, self.addjig, self.selected):
self.addButton(func)
def addButton(self, func):
button = QPushButton(func.__doc__)
setattr(self, "button%d" % self.buttonNum, button)
self.buttonNum += 1
self.buttonLayout.addWidget(button)
self.connect(button, SIGNAL('clicked()'), func)
def addIconButton(self, icon, func):
button = QPushButton()
button.setIcon(icon)
setattr(self, "button%d" % self.buttonNum, button)
self.buttonNum += 1
self.buttonLayout.addWidget(button)
self.connect(button, SIGNAL('clicked()'), func)
def addsomething(self, what):
if what == "Chunk":
icon = QPixmap('../images/moldefault.png')
icon_h = QPixmap('../images/moldefault-hide.png')
else:
icon = QPixmap('../images/measuredistance.png')
icon_h = QPixmap('../images/measuredistance-hide.png')
chunk = TestNode("%s-%d" % (what, self.chunkNum),
self.treemodel.untitledNode, icon, icon_h)
self.chunkNum += 1
self.view.mt_update()
def addmol(self):
"Chunk"
# This is equivalent to Part.addmol() in part.py
self.addsomething("Chunk")
def addjig(self):
"Jig"
self.addsomething("Jig")
def selected(self):
"Selected"
print self.view.selectedList()
####################################################################
def test_api():
# Test API compliance. If we remove all the functionality, pushing buttons shouldn't raise any
# exceptions.
global ModelTree, _QtTreeItem, _QtTreeModel
ModelTree = ModelTreeGUI_api
del _QtTreeModel
del _QtTreeItem
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.wrapper = TestWrapper()
self.setCentralWidget(self.wrapper)
self.resize(200, 300)
self.wrapper.show()
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
test_api()
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
| NanoCAD-master | cad/src/outtakes/modelTreePrototype.py |
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
NanotubeGroup.py - ...
@author: Bruce, Mark
@version: $Id$
@copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
from foundation.Group import Group
from utilities.constants import gensym
from utilities.icon_utilities import imagename_to_pixmap
from utilities import debug_flags
from utilities.debug import print_compact_stack
class NanotubeGroup(Group):
"""
Model object which packages together some Dna Segments, Dna Strands,
and other objects needed to represent all their PAM atoms and markers.
Specific kinds of Group member contents include:
- NanotubeSegments (optionally inside Groups)
- Groups (someday might be called Blocks when they occur in this context;
note that class Block is deprecated and should not be used for these)
- DnaMarkers (a kind of Jig, always inside an owning NanotubeSegment)
As other attributes:
- whatever other properties the user needs to assign, which are not
covered by the member nodes or superclass attributes. [nim?]
"""
# This should be a tuple of classifications that appear in
# files_mmp._GROUP_CLASSIFICATIONS, most general first.
# See comment in class Group for more info. [bruce 080115]
_mmp_group_classifications = ('NanotubeGroup',)
# Open/closed state of the Dna Group in the Model Tree --
# default closed.
open = False
autodelete_when_empty = True
# (but only if current command permits that for this class --
# see comment near Group.autodelete_when_empty for more info,
# and implems of Command.keep_empty_group)
def node_icon(self, display_prefs):
"""
Model Tree node icon for the nanotube group node
@see: Group.all_content_is_hidden()
"""
open = display_prefs.get('open', False)
if open:
if self.all_content_is_hidden():
return imagename_to_pixmap("modeltree/NanotubeGroup-expanded-hide.png")
else:
return imagename_to_pixmap("modeltree/NanotubeGroup-expanded.png")
else:
if self.all_content_is_hidden():
return imagename_to_pixmap("modeltree/NanotubeGroup-collapsed-hide.png")
else:
return imagename_to_pixmap("modeltree/NanotubeGroup-collapsed.png")
# Note: some methods below this point are examples or experiments or stubs,
# and are likely to be revised significantly or replaced.
# [bruce 080115 comment]
# example method:
def getSegments(self):
"""
Return a list of all our NanotubeSegment objects.
"""
return self.get_topmost_subnodes_of_class(self.assy.NanotubeSegment)
def isEmpty(self):
"""
Returns True if there are no nanotube chunks as its members
(Returns True even when there are empty NanotubeSegment objects inside)
@see: BuildNanotube_EditCommand._finalizeStructure where this test is used.
"""
#May be for the short term, we can use self.getAtomList()? But that
#doesn't ensure if the DnaGroup always has atom of type either
#'strand' or 'axis' .
if len(self.getSegments()) == 0:
return True
else:
return False
def addSegment(self, segment):
"""
Adds a new segment object for this dnaGroup.
@param segment: The NanotubeSegment to be added to this NanotubeGroup object
@type: B{NanotubeSegment}
"""
self.addchild(segment)
def getProps(self):
"""
Method to support Dna duplex editing. see Group.__init__ for
a comment
THIS IS THE DEFAULT IMPLEMENTATION. TO BE MODIFIED
"""
#Should it supply the Dna Segment list (children) and then add
#individual segments when setProps is called??
# [probably not; see B&N email discussion from when this comment was added]
if self.editCommand:
props = ()
return props
def setProps(self, props):
"""
Method to support Dna duplex editing. see Group.__init__ for
a comment
THIS IS THE DEFAULT IMPLEMENTATION. TO BE MODIFIED
"""
#Should it accept the Dna Segment list and then add individual segments?
pass
def edit(self):
"""
@see: Group.edit()
"""
commandSequencer = self.assy.w.commandSequencer
commandSequencer.userEnterCommand('BUILD_NANOTUBE', always_update = True)
currentCommand = commandSequencer.currentCommand
assert currentCommand.commandName == 'BUILD_NANOTUBE'
currentCommand.editStructure(self)
def getSelectedSegments(self):
"""
Returns a list of segments whose all members are selected.
@return: A list containing the selected strand objects
within self.
@rtype: list
"""
#TODO: This is a TEMPORARY KLUDGE until Dna model is fully functional.
#Must be revised. Basically it returns a list of NanotubeSegments whose
#all members are selected.
#See BuildDna_PropertyManager._currentSelectionParams() where it is used
#-- Ninad 2008-01-18
segmentList = self.getSegments()
selectedSegmentList = []
for segment in segmentList:
pickedNodes = []
unpickedNodes = []
def func(node):
if isinstance(node, self.assy.Chunk):
if not node.picked:
unpickedNodes.append(node)
else:
pickedNodes.append(node)
segment.apply2all(func)
if len(unpickedNodes) == 0 and pickedNodes:
selectedSegmentList.append(segment)
return selectedSegmentList
def getAtomList(self):
"""
Return a list of all atoms contained within this NanotubeGroup
"""
atomList = []
def func(node):
if isinstance(node, self.assy.Chunk):
atomList.extend(node.atoms.itervalues())
self.apply2all(func)
return atomList
def draw_highlighted(self, glpane, color):
"""
Draw the nanotube segment chunks as highlighted. (Calls the related
methods in the chunk class)
@param: GLPane object
@param color: The highlight color
@see: Chunk.draw_highlighted()
@see: SelectChunks_GraphicsMode.draw_highlightedChunk()
@see: SelectChunks_GraphicsMode._get_objects_to_highlight()
"""
for c in self.getSegments():
c.draw_highlighted(glpane, color)
pass # end of class NanotubeGroup
# ==
| NanoCAD-master | cad/src/outtakes/NanotubeGroup.py |
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
PeptideSegment.py - ...
WARNING: this class is reportedly not used and will soon be moved to outtakes.
@author: Mark
@version: $Id$
@copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details.
Note: related to DnaStrandOrSegment, from which it was copied and modified.
"""
import foundation.env as env
from utilities.debug import print_compact_stack, print_compact_traceback
from model.chunk import Chunk
from model.chem import Atom
from model.bonds import Bond
from geometry.VQT import V, norm, vlen
from utilities.icon_utilities import imagename_to_pixmap
from utilities.Comparison import same_vals
from foundation.LeafLikeGroup import LeafLikeGroup
_superclass = LeafLikeGroup
class PeptideSegment(LeafLikeGroup):
"""
Model object which represents a Peptide Segment inside a Peptide Group.
Internally, this is just a specialized Group containing a single chunk,
itself containing all the atoms of a Peptide.
"""
# This should be a tuple of classifications that appear in
# files_mmp._GROUP_CLASSIFICATIONS, most general first.
# See comment in class Group for more info. [bruce 080115]
_mmp_group_classifications = ('PeptideSegment',)
Peptide = None
_endPoint1 = None
_endPoint2 = None
# TODO: undo or copy code for those attrs,
# and updating them when the underlying structure changes.
# But maybe that won't be needed, if they are replaced
# by computing them from the atom geometry as needed.
# [bruce 080227 comment]
autodelete_when_empty = True
# (but only if current command permits that for this class --
# see comment near Group.autodelete_when_empty for more info,
# and implems of Command.keep_empty_group)
iconPath = "ui/modeltree/PeptideSegment.png"
hide_iconPath = "ui/modeltree/PeptideSegment-hide.png"
def writemmp_other_info_opengroup(self, mapping): #bruce 080507 refactoring
"""
"""
#bruce 080507 refactoring (split this out of Group.writemmp)
# (I think the following condition is always true, but I didn't
# prove this just now, so I left in the test for now.)
encoded_classifications = self._encoded_classifications()
if encoded_classifications == "PeptideSegment":
# This is a Peptide segment, so write the parameters into an info
# record so we can read and restore them in the next session.
# --Mark 2008-04-12
assert self.Peptide
mapping.write("info opengroup Peptide-parameters = %d, %d, %s, %s\n" \
% (self.Peptide.getChiralityN(),
self.Peptide.getChiralityM(),
self.Peptide.getType(),
self.Peptide.getEndings()))
pass
return
def readmmp_info_opengroup_setitem( self, key, val, interp ):
"""
[extends superclass method]
"""
#bruce 080507 refactoring (split this out of the superclass method)
if key == ['Peptide-parameters']:
# val includes all the parameters, separated by commas.
n, m, type, endings = val.split(",")
self.n = int(n)
self.m = int(m)
self.type = type.lstrip()
self.endings = endings.lstrip()
# Create the Peptide.
from cnt.model.Peptide import Peptide
self.Peptide = Peptide() # Returns a 5x5 CNT.
self.Peptide.setChirality(self.n, self.m)
self.Peptide.setType(self.type)
self.Peptide.setEndings(self.endings)
# The endpoints are recomputed every time it is edited.
else:
_superclass.readmmp_info_opengroup_setitem( self, key, val, interp)
return
def edit(self):
"""
Edit this PeptideSegment.
@see: PeptideSegment_EditCommand
"""
commandSequencer = self.assy.w.commandSequencer
commandSequencer.userEnterCommand('Peptide_SEGMENT')
assert commandSequencer.currentCommand.commandName == 'Peptide_SEGMENT'
commandSequencer.currentCommand.editStructure(self)
def getAxisVector(self, atomAtVectorOrigin = None):
"""
Returns the unit axis vector of the segment (vector between two axis
end points)
"""
# REVIEW: use common code for this method? [bruce 081217 comment]
endPoint1, endPoint2 = self.Peptide.getEndPoints()
if endPoint1 is None or endPoint2 is None:
return V(0, 0, 0)
#@see: RotateAboutAPoint command. The following code is disabled
#as it has bugs (not debugged but could be in
#self.Peptide.getEndPoints). So, rotate about a point won't work for
#rotating a Peptide. -- Ninad 2008-05-13
##if atomAtVectorOrigin is not None:
###If atomAtVectorOrigin is specified, we will return a vector that
###starts at this atom and ends at endPoint1 or endPoint2 .
###Which endPoint to choose will be dicided by the distance between
###atomAtVectorOrigin and the respective endPoints. (will choose the
###frthest endPoint
##origin = atomAtVectorOrigin.posn()
##if vlen(endPoint2 - origin ) > vlen(endPoint1 - origin):
##return norm(endPoint2 - endPoint1)
##else:
##return norm(endPoint1 - endPoint2)
return norm(endPoint2 - endPoint1)
def setProps(self, props):
"""
Sets some properties. These will be used while editing the structure.
(but if the structure is read from an mmp file, this won't work. As a
fall back, it returns some constant values)
@see: InsertPeptide_EditCommand.createStructure which calls this method.
@see: self.getProps, PeptideSegment_EditCommand.editStructure
"""
(_n, _m), _type, _endings, (_endPoint1, _endPoint2) = props
from cnt.model.Peptide import Peptide
self.Peptide = Peptide()
self.Peptide.setChirality(_n, _m)
self.Peptide.setType(_type)
self.Peptide.setEndings(_endings)
self.Peptide.setEndPoints(_endPoint1, _endPoint2)
def getProps(self):
"""
Returns Peptide parameters necessary for editing.
@see: PeptideSegment_EditCommand.editStructure where it is used.
@see: PeptideSegment_PropertyManager.getParameters
@see: PeptideSegmentEditCommand._createStructure
"""
# Recompute the endpoints in case this Peptide was read from
# MMP file (which means this Peptide doesn't have endpoint
# parameters yet).
self.Peptide.computeEndPointsFromChunk(self.members[0])
return self.Peptide.getParameters()
def getPeptideGroup(self):
"""
Return the PeptideGroup we are contained in, or None if we're not
inside one.
"""
return self.parent_node_of_class( self.assy.PeptideGroup)
def isAncestorOf(self, obj):
"""
Checks whether the object <obj> is contained within the PeptideSegment
Example: If the object is an Atom, it checks whether the
atom's chunk is a member of this PeptideSegment (chunk.dad is self)
It also considers all the logical contents of the PeptideSegment to determine
whether self is an ancestor. (returns True even for logical contents)
@see: self.get_all_content_chunks()
@see: PeptideSegment_GraphicsMode.leftDrag
"""
# see my comments in the NanotubeSegment version [bruce 081217]
c = None
if isinstance(obj, Atom):
c = obj.molecule
elif isinstance(obj, Bond):
chunk1 = obj.atom1.molecule
chunk2 = obj.atom1.molecule
if chunk1 is chunk2:
c = chunk1
elif isinstance(obj, Chunk):
c = obj
if c is not None:
if c in self.get_all_content_chunks():
return True
#NOTE: Need to check if the isinstance checks are acceptable (apparently
#don't add any import cycle)
if isinstance(obj, Atom):
chunk = obj.molecule
if chunk.dad is self:
return True
else:
return False
elif isinstance(obj, Bond):
chunk1 = obj.atom1.molecule
chunk2 = obj.atom1.molecule
if (chunk1.dad is self) or (chunk2.dad is self):
return True
elif isinstance(obj, Chunk):
if obj.dad is self:
return True
return False
def node_icon(self, display_prefs):
# REVIEW: use common code for this method? [bruce 081217 comment]
del display_prefs
if self.all_content_is_hidden():
return imagename_to_pixmap( self.hide_iconPath)
else:
return imagename_to_pixmap( self.iconPath)
def permit_as_member(self, node, pre_updaters = True, **opts):
"""
[friend method for enforce_permitted_members_in_groups and subroutines]
Does self permit node as a direct member,
when called from enforce_permitted_members_in_groups with
the same options as we are passed?
@rtype: boolean
[extends superclass method]
"""
# this method was copied from DnaStrandOrSegment and edited for this class
if not LeafLikeGroup.permit_as_member(self, node, pre_updaters, **opts):
# reject if superclass would reject [bruce 081217]
return False
del opts
assy = self.assy
res = isinstance( node, assy.Chunk) #@ NEEDS SOMETHING MORE.
return res
pass # end of class PeptideSegment
# end
| NanoCAD-master | cad/src/outtakes/PeptideSegment.py |
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details.
"""
RotaryMotorGenerator.py
$Id$
History:
Mark 2007-05-27: Created.
"""
__author__ = "Mark"
from utilities.Log import greenmsg
from PyQt4.Qt import QDialog
from RotaryMotorGeneratorDialog import RotaryMotorPropMgr
from command_support.GeneratorBaseClass import GeneratorBaseClass
# RotaryMotorPropMgr must come BEFORE GeneratorBaseClass in this list.
class RotaryMotorGenerator(RotaryMotorPropMgr, GeneratorBaseClass):
"""The Rotary Motor Generator class.
"""
cmd = greenmsg("Insert Rotary Motor: ")
#
prefix = '' # Not used by jigs.
# All jigs like rotary and linear motors already created their
# name, so do not (re)create it (in GeneratorBaseClass) from the prefix.
create_name_from_prefix = False
# We now support multiple keywords in a list or tuple
# sponsor_keyword = ('Graphenes', 'Carbon')
sponsor_keyword = 'RotaryMotor'
# pass window arg to constructor rather than use a global, wware 051103
def __init__(self, win, motor, glpane):
self.jig = motor
self.name = motor.name # Adopt the motor's name as our name.
RotaryMotorPropMgr.__init__(self, motor, glpane)
GeneratorBaseClass.__init__(self, win)
# Display Rotary Motor. Mark 2007-05-28.
self.preview_btn_clicked() # Kludge? Works though.
###################################################
# How to build this kind of structure, along with
# any necessary helper functions
def gather_parameters(self):
"""Return all the parameters from the Property Manager.
"""
torque = self.torqueDblSpinBox.value()
initial_speed = self.initialSpeedDblSpinBox.value()
final_speed = self.finalSpeedDblSpinBox.value()
dampers_state = self.dampersCheckBox.isChecked()
enable_minimize_state = self.enableMinimizeCheckBox.isChecked()
color = self.jig.color
atoms = self.jig.atoms[:]
#atoms = self.selectedAtomsListWidget.atoms
if 1:
print "\n---------------------------------------------------" \
"\ngather_parameters(): "\
"\ntorque = ", torque, \
"\ninitial_speed = ", initial_speed, \
"\nfinal_speed = ", final_speed, \
"\ndampers_state = ", dampers_state, \
"\nenable_minimize_state = ", enable_minimize_state, \
"\ncolor = ", color, \
"\natoms = ", atoms
return (torque, initial_speed, final_speed,
dampers_state, enable_minimize_state,
color, atoms)
def build_struct(self, name, params, position):
"""Build and return a new rotary motor from the parameters in the Property Manager.
"""
torque, initial_speed, final_speed, \
dampers_state, enable_minimize_state, \
color, atoms = params
self.jig.cancelled = False
self.jig.torque = torque
self.jig.initial_speed = initial_speed
self.jig.speed = final_speed
self.jig.dampers_enabled = dampers_state
self.jig.enable_minimize = enable_minimize_state
self.jig.color = color
self.jig.atoms = atoms
if 1:
print "\n---------------------------------------------------" \
"\nbuild_struct(): "\
"\ntorque = ", self.jig.torque, \
"\ninitial_speed = ", self.jig.initial_speed, \
"\nfinal_speed = ", self.jig.speed, \
"\ndampers_state = ", self.jig.dampers_enabled, \
"\nenable_minimize_state =", self.jig.enable_minimize, \
"\ncolor = ", self.jig.color, \
"\natoms = ", self.jig.atoms
return self.jig
| NanoCAD-master | cad/src/outtakes/RotaryMotorGenerator.py |
# Copyright 2007 Nanorex, Inc. See LICENSE file for details.
"""
test_polyline_drag.py
@author: Bruce
@version: $Id$
Simple test/example code for making a polyline.
Goal is just to demonstrate intercepting mouse events
to change the usual meaning of a click,
detecting GLPane enter/leave, etc.
Not yet suitable for use as a real example.
Doesn't yet store the polyline anywhere.
Just a stub for now.
"""
from exprs.State_preMixin import State_preMixin
from prototype.test_commands import ExampleCommand
from geometry.VQT import V
from utilities.constants import red
# TODO: import the following from somewhere
DX = V(1,0,0)
DY = V(0,1,0)
ORIGIN = V(0,0,0)
from exprs.attr_decl_macros import Instance, State
from exprs.Rect import Line
from exprs.Rect import Spacer
from exprs.If_expr import If_expr
from exprs.ExprsConstants import Point
NullDrawable = Spacer() # kluge; should refile
class test_polyline_drag(State_preMixin, ExampleCommand):
# class constants needed by mode API for example commands
commandName = 'test_polyline_drag-commandName'
featurename = "Prototype: Example Polyline Drag Command"
## PM_class = test_polyline_drag_PM
# tracked state
rubberBand_enabled = State(bool, False, doc = "whether we're rubberbanding a new segment now")
# TODO:
### grab a polyline object from an example file in exprs ### (the one that has a closed boolean and can draw in 3d)
### have a list of them, we're rubberbanding last segment of last one...
lastSegmentStart = ORIGIN + 6 * DY # stub
lastSegmentEnd = State( Point, doc = "endpoint of last segment; only meaningful when rubberBand_enabled")
# note: these might be redundant with some points in a polyline object;
# should they be aliases into one?
rubberBandDrawable = If_expr( rubberBand_enabled,
Line( lastSegmentStart, lastSegmentEnd,
red,
thickness = 4
),
NullDrawable
)
whatWeDraw = Instance(rubberBandDrawable)
# init methods
def __init__(self, glpane):
# not sure why this method is needed, see comment in test_connectWithState.__init__
super(test_polyline_drag, self).__init__(glpane)
ExampleCommand.__init__(self, glpane)
return
def Draw(self):
super(test_polyline_drag, self).Draw() #k
self.whatWeDraw.draw()
return
def leftDown(self, event):
print "leftDown"
# TODO:
# get the point (mouseray in plane)
# make a real point there (or mark it as real, if we have a point object for it already)
# (so it has a blue dot of its own)
# update self.rubberBand_enabled
# STUB:
self.rubberBand_enabled = True
self.lastSegmentEnd = self.lastSegmentStart + 3 * DX
ExampleCommand.leftDown(self, event)
### will this prevent this error in mouse release:
## AttributeError: 'test_polyline_drag' object has no attribute 'LMB_press_event'
## [GLPane.py:1805] [selectAtomsMode.py:899]
return
pass
# end
| NanoCAD-master | cad/src/outtakes/test_polyline_drag.py |
"""
the main code will replace __class__ of Atom or Bond with related classes,
since Python supports this. This is done in dna_updater_utils.replace_atom_class().
If Python ever stops supporting this,
here is some unfinished code which indicates the sort of thing we'd have to do.
The hard part is replacing one atom with another in all the various places it can appear.
All the ones I can remember [bruce 071117] are listed in the following comment.
"""
# when i replace an atom (to change its class), i have to update it if it appears in various places:
# in the model:
# - chunk.atoms
# - jig.atoms
# - in all its bonds
# - as a chunk hotspot (only for its own chunk, i think)
# in the selection:
# - part.selatoms for its part (?)
# in highlighting caches:
# - glpane.selobj
# - glpane.selatom
# - the glname allocator? maybe not, if atom only gets into it when it's drawn... (unlike now)
# in undo checkpoints? i can just treat it as a new object --
# provided the changes to objects above, that replace it inside them,
# are undoable and tracked! but wait, they shouldn't need to be,
# since if i replaced it, it was illegal in any checkpointed state,
# assuming i did this for "local reasons" -- hmm, can bps change base atoms? ###
# ... this is a pain -- see if setting __class__ actually works!
def _replace_atom(atom, newatom): # move into chem.py, at least in part
key = atom.key
newatom.key = key
mol = atom.molecule
assert None is newatom.molecule ###k if it's already set, this .atoms mod just below might be already done...
newatom.molecule = mol
mol.atoms[key] = newatom
atom.molecule = None
}# tell chunk to inval its atom list??
assert not newatom.jigs
newatom.jigs = atom.jigs
atom.jigs = []
for jig in newatom.jigs:
replace_in_list(jig.atoms, atom, newatom) #IMPLEM in py utils
assert not newatom.bonds
newatom.bonds = atom.bonds
atom.bonds = []
for bond in newatom.bonds:
if bond.atom1 is atom:
bond.atom1 = newatom
if bond.atom2 is atom:
bond.atom2 = newatom
if mol._hotspot is atom:
mol._hotspot is newatom
}# and more... see above
return
def in_some_other_func():
# put bondpoints and atoms into the right classes
for atom in changed_atoms.itervalues():
if not atom.killed():
if atom._f_actual_class_code != atom._f_desired_class_code:
newatom = newclass( atom) ### IMPLEM
replace_atoms[atom.key] = (atom, newatom)
for atom, newatom in replace_atoms.iteritems():
_replace_atom(atom, newatom)
# ==
# for a bond:
# - copy pi_bond_obj
# - in atom.bonds for its atoms
# - glpane.selobj
# - the glname allocator
# ==
# for a chunk: (i might just make a new one and move atoms in the same way as separate/merge, obviating this)
# - fix atom.molecule for its atoms
# - make sure it's in the right part, gets added to it properly and old chunk removed
# - in its own group
# - selmols?
# - chunkjig refs, if i have that
# - the glname allocator, and selobj, in case we allow it there in future
# end
| NanoCAD-master | cad/src/outtakes/Atom_replace_class.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
TreeWidget.py -- NO LONGER USED IN Qt4 NE1
-- adds event handling and standard event bindings to TreeView.py.
$Id$
History: modelTree.py was originally written by some combination of
Huaicai, Josh, and Mark. Bruce (Jan 2005) reorganized its interface with
Node and Group and their subclasses (Utility.py and other modules)
and rewrote a lot of the model-tree code (mainly to fix bugs),
and split it into three modules:
- TreeView.py (display and update),
- TreeWidget.py (event handling, and some conventions suitable for
all our tree widgets, if we define other ones), and
- modelTree.py (customized for showing a "model tree" per se).
"""
assert 0, "TreeWidget.py is NO LONGER USED IN Qt4 NE1" #bruce 070503 Qt4
from TreeView import * # including class TreeView, and import * from many other modules
from widgets.menu_helpers import makemenu_helper
from platform import fix_buttons_helper
from utilities.debug import DebugMenuMixin, print_compact_stack, print_compact_traceback
allButtons = (leftButton|midButton|rightButton) #e should be defined in same file as the buttons
from utilities import debug_flags
from platform import tupleFromQPoint, fix_plurals
import os
import foundation.env as env
# but platform thinks "# def qpointFromTuple - not needed"; for now, don't argue, just do it here:
def QPointFromTuple((x,y)):
return QPoint(x,y)
debug_keys = env.debug() #####@@@@@
debug_dragstuff = 1 # DO NOT COMMIT with 1. - at least not for the alpha-release version (see below)
# to enable this at runtime, type the following into the "run py code" menu item's dialog:
# import TreeWidget@@@TreeWidget.debug_dragstuff = 1
# catch and fix error of my having committed this code with debug_dragstuff set:
if not (os.path.isdir("/Users/bruce") and os.path.isdir("/Huge")):
# oops, I committed with that set to 1! sorry.
# (well, since this check is here, i might commit it with 1 a few times, but remove it pre-release)
debug_dragstuff = 0
if debug_dragstuff:
print "\n * * * * Running with debug_dragstuff set. \nExpect lots of output if you drag in the model tree!\n"
# For some reason I want this module to be independent of Numeric for now:
def pair_plus((x0,y0),(x1,y1)):
return x0+x1,y0+y1
def pair_minus((x0,y0),(x1,y1)):
return x0-x1,y0-y1
# ==
def sib_index( lis, elt, offset): #bruce 060219; should refile, maybe Utility.py
"""Assuming elt is in lis, return index of its sibling a specified distance
to the right (offset > 0) or left (offset < 0), but when running off the end,
just return the extreme element reached (rather than error, nothing, or wrapping).
"""
index = lis.index(elt)
new = index + offset
if new < 0:
return 0
elif new >= len(lis):
return len(lis) - 1
else:
return new
pass
# == main widget class
class TreeWidget(TreeView, DebugMenuMixin):
def __init__(self, parent, win, name = None, columns = ["node tree"], size = (200, 560)):
"""#doc
creates all columns but only known to work for one column.
most of its code only bothers trying to support one column.
"""
assert False # we shouldn't be using TreeWidget or TreeView any more
self.debug_dragstuff = debug_dragstuff # so TreeView.py can see it [KLUGE! clean up sometime.]
###@@@ review all init args & instvars, here vs subclasses
TreeView.__init__(self, parent, win, name, columns = columns, size = size) # stores self.win
self.setAcceptDrops(True)
#####@@@@@@ btw trying only this one for first time, same as 1st time with this one at all and with scroll signal
# btw see "dragAutoScroll" property in QScrollView docs. dflt true. that's why we have to accept drops on viewport.
if debug_dragstuff:
print "self, and our viewport:",self,self.viewport()
# debug menu and reload command ###e subclasses need to add reload actions too
self._init_time = time.asctime() # for debugging; do before DebugMenuMixin._init1
DebugMenuMixin._init1(self) ###e will this be too early re subclass init actions??
qt4todo('no such method')
#self.setDefaultRenameAction(QListView.Accept)
# I don't think this has any effect, now that we're depriving
# QListView of mouse events, but I'm setting it anyway just in case.
# The "real version of this" is in our own contentsMousePress... method.
# bruce 050112 zapping most signals, we'll handle the events ourself.
self.connect(self, SIGNAL("itemRenamed(QListViewItem*, int, const QString&)"), self._itemRenamed)
self.connect(self, SIGNAL("contentsMoving(int, int)"), self._contentsMoving)
return # from TreeWidget.__init__
# helper functions
def fix_buttons(self, but, when):
return fix_buttons_helper(self, but, when)
def makemenu(self, menu_spec):
# this overrides the one from DebugMenuMixin (with the same code), but that's ok,
# since we want to be self-contained in case someone later removes that mixin class.
# [bruce 050418 comment]
return makemenu_helper(self, menu_spec)
def item_x_edges(self, item):
"""Given a QListViewItem of ours (not None(??) or opts so None seems all to left of openclose, etc??),
return a tuple of interesting x coords related to its appearance (within column 0 only).
These are:
- col0 left edge
- openclose left edge (even if it's not openable -- this is what it would be if it had been openable),
- openclose right edge == icon left edge (actually not the true edge but what to use for a hit-test),
- icon centerline (ideal mousepos for a drop onto that item's depth vs. a child or parent's depth),
-
- ... ###
between
"""
####@@@@ #e will split from below
# this is where i am now 710pm 050201
# mouse event handlers (except for drag & drop, those are farther below)
# helper variable for knowing if you might be inside an external-source drag, not now in the widget...
# might need revision to store more than just the last single event of all types together... #####@@@@@ revise, use [050201]
last_event_type = "none" #k or imitate some other one?
def contentsMouseDoubleClickEvent(self, event):
"[called by Qt]"
return self.contentsMousePressEvent(event, dblclick = 1)
renaming_this_item = None
def contentsMousePressEvent(self, event, dblclick = 0):
"[called by Qt, or by our own contentsMouseDoubleClickEvent]"
self.last_event_type = "press"
self.checkpoint_before_drag(event) #bruce 060328 fix bug 1773
# figure out position and item of click (before doing any side effects)
#e this might be split into a separate routine if it's useful during drag
cpos = event.pos() # this is in contents coords;
# y=1 is just under column label (which does not scroll with content)
vpos = self.contentsToViewport(cpos)
item = self.itemAt(vpos)
# before anything else (except above -- in case this scrolls for some reason),
# let this click finish an in-place renaming, if there was one.
# [050131, added protection against item being deleted during renaming]
self.click_elsewhere_finishes_renaming()
# now figure out what part of the item (if any) we clicked on,
# setting 'part' to a constant string describing which part, or None.
# (someday: if we clicked too far to left or right of visible part of item,
# set item = part = None; or we might have new 'part' values
# for those positions. #e)
part = None
if item:
# where in the item did we click? relevant Qt things:
# QListViewItem::width - width of text in col k (without cropping)
# ... see also PyQt example code, examples3/dirview.py, search for rootIsDecorated
# Note: if we click to right of col0, we never get here, since item is already None.
rootIsDecorated = 1
# more generally: 0 or 1 depending on self.rootIsDecorated()
header = self.header()
col0_left_x = header.sectionPos( header.mapToIndex( 0 ))
# where is this x? by experiment it's always 0 for us. must be left edge of column 0.
# btw, Qt C++ eg uses mapToActual but there's no such attr when tried here.
indent = self.treeStepSize() * (item.depth() + rootIsDecorated) + self.itemMargin()
x_past_openclose = vpos.x() - (col0_left_x + indent)
# this tells whether we hit the left edge of the icon
# (by when it's positive), for a very big icon.
if x_past_openclose > 22: # this cutoff seems ok now; depends on our icon sizes
part = 'text'
#e incorrect if we're to the right of the visible text;
# Qt docs show how to check text width to find out; should use that
# (also we're not checking for still being in column 0, just assuming that)
elif x_past_openclose > 2: # this cutoff seems ok (tho it's a bit subjective)
part = 'icon'
elif (x_past_openclose > -15) and self.item_isOpenable(item):
# warning: item.isExpandable() is wrong here; see item_isOpenable docstring
# this cutoff seems ok; depends on desired size of "click area" around openclose
part = 'openclose'
elif vpos.x() >= col0_left_x:
part = 'left'
else:
part = item = None # to the left of column 0 (not currently possible I think)
pass
else:
col0_left_x = x_past_openclose = -1000 # debug kluge
# If this click's data differs from the prior one, this event shouldn't
# be counted as a double click. Or the same, if too much time passed since prior click,
# which would mean Qt erred and called this a double click even though its first click
# went to a different widget (I don't know if Qt can make that mistake).
# ###e nim feature... and low pri, since Qt seems reasonably conservative
# about what it calls a double click. ###@@@
###e probably store some things here too, in case we'll decide later to start a drag.
self.clicked( event, vpos, item, part, dblclick)
self.update_select_mode() # change user-visible mode to selectMolsMode iff necessary
return # from contentsMousePressedEvent
# == DUPLICATING THE FOLLOWING CODE IN TreeWidget.py and GLPane.py -- should clean up ####@@@@ [bruce 060328]
__pressEvent = None
__flag_and_begin_retval = None
def checkpoint_before_drag(self, event): # GLPane version: extra arg 'but'
if 1: # GLPane version: if but & (leftButton|midButton|rightButton):
if self.__pressEvent is not None and debug_flags.atom_debug:
print "atom_debug: bug: pressEvent in MT didn't get release:", self.__pressEvent
self.__pressEvent = event
self.__flag_and_begin_retval = None
if self.assy:
begin_retval = self.assy.undo_checkpoint_before_command("(model tree)")
# this command name should be replaced sometime during the command
self.__flag_and_begin_retval = True, begin_retval
pass
return
def checkpoint_after_drag(self, event):
"""[see docstring of same method in GLPane]
"""
if self.__pressEvent is not None:
self.__pressEvent = None
if self.__flag_and_begin_retval:
flagjunk, begin_retval = self.__flag_and_begin_retval
self.__flag_and_begin_retval = None
if self.assy:
self.assy.undo_checkpoint_after_command( begin_retval)
return
# == END OF DUPLICATED CODE (whose comments were left only in the original in GLPane) [bruce 060328]
drag_handler = None # this can be set by selection_click()
def contentsMouseMoveEvent(self, event): # note: does not yet use or need fix_buttons
"[overrides QListView method]"
self.last_event_type = "move"
# This method might be needed, to prevent QListView's version of it from messing us up,
# even if it had no body. Anyway, now it does have one.
# Note that it is not called by Qt for a dragMoveEvent,
# but it's involved in drag and drop since it decides whether we should start one.
# WARNING: if it does start one, its subr might not return until that entire drag and drop
# is finished! There will be recursive event processing during that time.
if self.drag_handler:
# this should only be true when some button is down in the event!
# but in case of weirdness in sequence of events we get from Qt,
# let's check this ourselves!
if event.state() & allButtons: # if any mouse button is pressed
self.drag_handler.mouseMoveEvent( event) #k worry about coords?
self.fillInToolTip() # wware 051014 fixing bug 1063
pass
def contentsMouseReleaseEvent(self, event): # note: does not yet use or need fix_buttons
"[overrides QListView method]"
self.last_event_type = "release"
# This method might be needed, to prevent QListView version of it from messing us up,
# even if it does nothing.
# (At least, without it, QListView emits its "clicked" signal.)
# (Many comments for contentsMouseMoveEvent apply to this method as well.)
if self.drag_handler:
self.drag_handler.mouseReleaseEvent( event) #k worry about coords?
self.drag_handler.cleanup(self) # redundant but that's ok ###k
# (if it already cleaned up, it doesn't know self, and might need to someday, so we pass it in)
self.drag_handler = None
self.checkpoint_after_drag(event) #bruce 060328 fix bug 1773
pass
def enterEvent(self, event): ####e #####@@@@@ should this (and Leave) call our drag_handler??
"[should be called by Qt when mouse enters this widget]"
self.last_event_type = "enter"
# [Qt doc says this method is on QWidget; there doesn't seem to be a "contentsEnterEvent".]
# erase any statusbar messages that might be left over from other widgets
# (eg advice from Build mode in glpane)
###e [should replace it with "our current sbar text", not " " --
# see comment near a call of history.statusbar_msg]
self.statusbar_msg(" ") # bruce 050126; works
def statusbar_msg(self, msg):
#e should store the current one for this widget, to share sbar with other widgets;
# or better, the method we're calling should do that for all widgets (or their parts) in a uniform way
env.history.statusbar_msg( msg)
# external update methods
def update_select_mode(self): #bruce 050124; should generalize and refile; should be used for more or for all events ###@@@
#bruce 060403 revised this but didn't update docstring; now it can change from *Chunk modes to Build, only, I think
"""This should be called at the end of event handlers which might have
changed the current internal selection mode (atoms vs chunks),
to resolve disagreements between that and the visible selection mode
iff it's one of the Select modes [or more generally, i assume as of 060403,
if the current mode wants to be ditched if selwhat has to have certain values it dislikes].
If the current mode is not one of Select Atoms or Select Chunks, this routine has no effect.
(In particular, if selwhat changed but could be changed back to what it was,
it does nothing to correct that [obs? see end of docstring], and indeed it doesn't know the old value of
selwhat unless the current mode (being a selectMode) implies that.)
[We should generalize this so that other modes could constrain the selection
mode to just one of atoms vs chunks if they wanted to. However, the details of this
need design, since for those modes we'd change the selection whereas for the
select modes we change which mode we're in and don't change the selection. ###@@@]
If possible, we leave the visible mode the same (even changing assy.selwhat
to fit, if nothing is actually selected [that part was NIM until 050519]).
But if forced to, by what is currently selected, then we change the visible
selection mode to fit what is actually selected. (We always assert that selwhat
permitted whatever was selected to be selected.)
"""
if env.permit_atom_chunk_coselection(): #bruce 060721
return
from commands.SelectChunks.selectMolsMode import selectMolsMode
#bruce 050519 revised docstring and totally rewrote code.
assy = self.assy
win = self.win
mode = self.win.glpane.currentCommand
del self
part = assy.part
# 0. Appraise the situation.
# 0a: assy.selwhat is what internal code thinks selection restriction is, currently.
selwhat = assy.selwhat
assert selwhat in (SELWHAT_CHUNKS, SELWHAT_ATOMS) # any more choices, or change in rules, requires rewriting this method
# 0b. What does current mode think it needs to be?
# (Someday we might distinguish modes that constrain this,
# vs modes that change to fit it or to fit the actual selection.
# For now we only handle modes that change to fit the actual selection.)
selwhat_from_mode = None # most modes don't care
if isinstance( mode, selectMolsMode):
selwhat_from_mode = SELWHAT_CHUNKS
#bruce 060403 commenting out the following, in advance of proposed removal of Select Atoms mode entirely:
## elif isinstance( mode, selectAtomsMode) and mode.commandName == selectAtomsMode.commandName:
## #bruce 060210 added commandName condition to fix bug when current mode is Build (now a subclass of Select Atoms)
## selwhat_from_mode = SELWHAT_ATOMS
change_mode_to_fit = (selwhat_from_mode is not None) # used later; someday some modes won't follow this
# 0c. What does current selection itself think it needs to be?
# (If its desires are inconsistent, complain and fix them.)
if assy.selatoms and assy.selmols:
if debug_flags.atom_debug:
#bruce 060210 made this debug-only, since what it reports is not too bad, and it happens routinely now in Build mode
# if atoms are selected and you then select a chunk in MT
print "atom_debug: bug, fyi: there are both atoms and chunks selected. Deselecting some of them to fit current mode or internal code."
new_selwhat_influences = ( selwhat_from_mode, selwhat) # old mode has first say in this case, if it wants it
#e (We could rewrite this (equivalently) to just use the other case with selwhat_from_sel = None.)
else:
# figure out what to do, in this priority order: actual selection, old mode, internal code.
if assy.selatoms:
selwhat_from_sel = SELWHAT_ATOMS
elif assy.selmols:
selwhat_from_sel = SELWHAT_CHUNKS
else:
selwhat_from_sel = None
new_selwhat_influences = ( selwhat_from_sel, selwhat_from_mode, selwhat)
if selwhat_from_sel is not None and selwhat_from_sel != selwhat:
# following code will fix this with no harm, so let's not consider it a big deal,
# but it does indicate a bug -- so just print a debug-only message.
# (As of 050519 740pm, we get this from the jig cmenu command "select this jig's atoms"
# when the current mode is more compatible with selecting chunks. But I think this causes
# no harm, so I might as well wait until we further revise selection code to fix it.)
if debug_flags.atom_debug:
print "atom_debug: bug, fyi: actual selection (%s) inconsistent " \
"with internal variable for that (%s); will fix internal variable" % \
(SELWHAT_NAMES[selwhat_from_sel], SELWHAT_NAMES[selwhat])
# Let the strongest (first listed) influence, of those with an opinion,
# decide what selmode we'll be in now, and make everything consistent with that.
for opinion in new_selwhat_influences:
if opinion is not None:
# We have our decision. Carry it out (on mode, selection, and assy.selwhat) and return.
selwhat = opinion
if change_mode_to_fit and selwhat_from_mode != selwhat:
#bruce 050520 fix bug 644 by only doing this if needed (i.e. if selwhat_from_mode != selwhat).
# Without this fix, redundantly changing the mode using these tool buttons
# immediately cancels (or completes?) any node-renaming-by-dblclick
# right after it gets initiated (almost too fast to see).
if selwhat == SELWHAT_CHUNKS:
win.toolsSelectMolecules()
print "fyi: forced mode to Select Chunks" # should no longer ever happen as of 060403
elif selwhat == SELWHAT_ATOMS:
win.toolsBuildAtoms() #bruce 060403 change: toolsSelectAtoms -> toolsBuildAtoms
## win.toolsSelectAtoms() #bruce 050504 making use of this case for the first time; seems to work
# that might have fixed the following too, but never mind, we'll just always do it -- sometimes it's needed.
if selwhat == SELWHAT_CHUNKS:
part.unpickatoms()
assy.set_selwhat(SELWHAT_CHUNKS)
elif selwhat == SELWHAT_ATOMS:
if assy.selmols: # only if needed (due to a bug), since this also desels Groups and Jigs
# (never happens if no bug, since then the actual selection has the strongest say -- as of 050519 anyway)
part.unpickparts()
assy.set_selwhat(SELWHAT_ATOMS) # (this by itself does not deselect anything, as of 050519)
return
assert 0, "new_selwhat_influences should not have ended in None: %r" % (new_selwhat_influences,)
# scratch comments:
# if we had been fixing selwhat in the past, it would have fixed bug 500 in spite of permit_pick_parts in cm_hide/cm_unhide.
# So why aren't we? let's find out with some debug code... (now part of the above, in theory)
return
def update_glpane(self):
self.win.glpane.update()
####k will this work already, just making it call paintGL in the next event loop?
# or must we inval something too??
# [new comment, 050127:] it seems to work... needs a bit more testing,
# then can be moved into GLPane as the new implem of gl_update.
# command bindings for clicks on various parts of tree items
# are hardcoded in the 'clicked' method:
"""
We get here by either contentsMousePressEvent or contentsMouseDoubleClickEvent.
Those are methods that Qt 3 provided for QListView.
"""
def clicked( self, event, vpos, item, part, dblclick):
"""Called on every mousedown (regardless of mouse buttons / modifier keys).
Event is the Qt event (not yet passed through fix_buttons).
vpos is its position in viewport coordinates.
item is None or a QListViewItem.
If item, then part is one of ... #doc; otherwise it's None.
dblclick says whether this should count as a double click
(note that for some bindings we'll implement, this won't matter).
(Note that even if dblclick can be determined directly from event,
caller might have its own opinion, which is what we use, so the flag
would need to be separately passed anyway.)
"""
if debug_flags.atom_debug: #bruce 060713 debug code, safe to be permanent
import utilities.debug as debug
debug._event = event
debug._event_state = event.state()
debug._event_stateAfter = event.stateAfter()
# handle debug menu; canonicalize buttons and modifier keys.
if self.debug_event(event, 'mousePressEvent', permit_debug_menu_popup = 1):
return
but = event.stateAfter()
but = self.fix_buttons(but, 'press')
# figure out modifier (not stored, just used here & passed to subrs)
# (option/alt key (mac) aka midButton (other platforms) is used separately below)
if (but & (shiftButton|cntlButton)) == (shiftButton|cntlButton):
modifier = 'ShiftCntl'
elif but & shiftButton:
modifier = 'Shift'
elif but & cntlButton:
modifier = 'Cntl'
else:
modifier = None
# Now check for various user commands, performing the first one that applies,
# and doing whatever inval or update is needed within the tree widget itself,
# but not necessarily all needed external updates (some of these are done
# by our caller).
# handle context menu request.
# no need - QTreeWidget recognizes context menu events without our help
# after this point, treat clicks to left of open/close icon as if on no item.
# (would it be better to treat them as on open/close, or have a special cmenu
# about the parent items, letting you close any of those? ##e)
if part == 'left':
part = item = None
# handle open/close toggling. (ignores modifier keys, mouse buttons, dblclick)
if part == 'openclose':
# this can only happen for a non-leaf item!
self.toggle_open(item) # does all needed inval/update/repaint
return
# handle in-place editing of the item text, on double-click
#e (someday this might be extended to edit a variant of the text,
# if some of it is a fixed label or addendum... to implem that,
# just call item.setText first, within the subroutine.)
if dblclick and part == 'text' and not modifier: # but midButton will also do this, for now
# presumably the first click selected this item... does this matter?? #k
# BTW it would not be true if this was a Control-double-click! This is not allowed now.
# If we wanted to be paranoid, we'd return unless the modkeys and button
# were identical with the saved prior click... #e
col = 0
return self.maybe_beginrename( item, vpos, col)
# what's left?
# - selection.
# - drag-starting, whether for DND or (saved for later #e) a selection range or rect.
# - hover behaviors (tooltip with help info or longer name; cmenu) (saved for later. #e)
#####@@@@ need code to save event info for drag-starting
# handle selection-click, and/or start of a drag
# (we can't in general distinguish these until more events come)
## if dblclick:
## # Too likely this 2nd click was a mistake -- let the first click handle
## # it alone. (This only matters for Control-click, which toggles selection,
## # once the feature of discarding dblclick flag when item/part
## # changed is implemented.)
## return
# after this point, double click acts just like two single clicks
# (since dblclick flag is ignored).
# if buttons are not what we expect, return now (thus avoiding bad effects
# from some possible bugs in the above code)
if (but & allButtons) not in [leftButton, midButton]:
# (note, this is after fix_buttons, so on Mac this means click or option-click)
return
drag_should_copy = but & midButton # standard for Mac; don't know about others
drag_type = (drag_should_copy and 'copy') or 'move'
self.selection_click( item, # might be None
modifier = modifier,
## group_select_kids = (part == 'icon'), ##k ok? could we use dblclick to mean this??
group_select_kids = True, # bruce 050126 after email discussion with Josh
permit_drag_type = drag_type,
event = event )
# note: the same selection_click method, called differently,
# also determines the selection for context menus.
# It does all needed invals/updates except for update_select_mode.
return # from clicked
# context menu requests (the menu items themselves are defined by our subclass)
def menuReq(self, item, pos, modifier, optflag):
"""Context menu items function handler for the Model Tree View
[interface is mostly compatible with a related QListView signal,
but it's no longer called that way; col arg was not used and is now removed;
pos should be the position to put up the menu, in global coords (event.globalPos).]
"""
# First, what items should this context menu be about?
#
# Here's what the Mac (OS 10.2) Finder does:
#
# (btw, for the mac, context menus are asked for by control-click,
# vs. right-click on other platforms -- here I'll say context-click:)
#
# - If you context-click on a selected item, the menu is about
# the set of (one or more) selected items, which does not change.
#
# - If you context-click on another item, the selection changes to
# include just the item you clicked on (and you can see that in
# the selection highlighting), and the menu is about *that* item.
#
# - If you click on no item, you get a menu for the window as a whole
# (whether or not items were selected; if any were, they are unselected).
#
# Furthermore, when the menu is about a set of more than one items,
# the text of its entries makes this clear.
#
# (What about other modifier keys which normally modify selection
# behavior? If you use them, the Mac just does selection and ignores the
# control key (no context menu). I decided [050126] to instead let them
# affect selection as normal, then put up the cmenu on the result --
# especially for Shift, but even for Control which can remove the clicked-
# on item. (Motivation: for shift, I found myself trying to use it this way,
# to extend a selection before getting the cmenu, and failing.)
#
# Note that this implies: the visible selection always shows you what
# set of items the context menu is about and will operate on; it's easy
# to make the menu be about the existing selection, or about no items,
# or (usually) about any existing single item; the only harder case for
# the user is when you want a menu about one item, and it and others are
# selected, in which case, you just click somewhere (to unselect all)
# and then context-click on the desired item; if instead you don't notice
# that any other items are selected, you'll notice your mistake when you
# see the text of the menu entries.
#
# BTW, if you click on an "open/close icon" (or to the left of an item),
# it acts like you clicked on no item, for this purpose. (As of 050124
# our caller behaves differently in this case too, on purpose I guess...)
#
# [refile?] About the menu position and duration:
# In all cases, the menu top left corner is roughly at the click pos,
# and the menu disappears immediately on mouseup, whether or not you
# choose a command from it. [That last part is nim since I don't yet
# know how to make it happen.]
#
# This all seems pretty good, so I will imitate it here. [bruce 050113]
#e correct item to be None if we were not really on the item acc'd to above?
# no, let the caller do that, if it needs to be done.
self.selection_click( item, modifier = modifier, group_select_kids = True, permit_drag_type = None)
# this does all needed invals/updates except update_select_mode
# bruce 050126: group_select_kids changed to True after discussion with Josh...
# the same principle applies to context menu ops as to everything else.
# Also, changed modifier from None to the one passed in.
nodeset = self.topmost_selected_nodes()
# topmost_selected_nodes is "more efficient" than selected_nodes,
# and [050126] equivalent to it now that we're enforcing "selected group
# implies selected members", assuming the command are coded to operate on
# all members of groups (when that makes sense).
menu = self.make_cmenu_for_set( nodeset, optflag)
menu.exec_(pos) # was menu.popup before 050126
#e should we care about which item to put where (e.g. popup(pos,1))?
# the menu commands will do their own updates within this widget (and to glpane),
# but we used exec_ (which does not return until the menu command has run)
# so we can do necessary external updates here. (We might later have to change back
# to menu.popup so we can make the menu go away on mouseup, and then put this update
# into the menu commands. #e)
self.update_select_mode() #k is this done redundantly by our caller? if not, move it there?
return # from menuReq
def make_cmenu_for_set(self, nodeset, optflag):
"""Return a context menu (QPopupMenu object #k)
to show for the given set of (presumably selected) items.
[Might be overridden by subclasses, but usually it's more convenient
and better for them to override make_cmenuspec_for_set instead.]
"""
spec = self.make_cmenuspec_for_set(nodeset, optflag) \
or self.make_cmenuspec_for_set([], optflag) \
or [('(empty context menu)',noop,'disabled')]
return self.makemenu( spec)
def make_cmenuspec_for_set(self, nodeset, optflag):
"""Return a Menu_spec list (of a format suitable for makemenu_helper)
for a context menu suitable for nodeset, a list of 0 or more selected nodes
(which includes only the topmost selected nodes, i.e. it includes no
children of selected nodes even if they are selected).
<optflag> can be 'Option' or None, in case menus want to include additional items when it's 'Option'.
Subclasses should override this to provide an actual menu spec.
The subclass implementation can directly examine the selection status of nodes
below those in nodeset, if desired, and can assume every node in nodeset is picked,
and every node not in it or under something in it is not picked.
[all subclasses should override this]
"""
return []
# sets of selected items or nodes
#e [do we also want versions with node arguments, which search only in subtrees?
# if so, those should just be (or call) Node methods.]
def selected_nodes(self): #bruce 050202 comment: this is not presently used
"return a list of all currently selected nodes (perhaps including both groups and some of their members)"
# For now, it's ok if this is slow, since it's only used to help make a context menu.
# (Later we might need a fast version, for each subtree,
# so the same info will have to be kept incrementally in the nodes. #e)
# (We can also imagine wanting these structured as a tree, e.g. for copying... #e)
res = []
def func(x):
if x.picked:
res.append(x)
for node in self.topnodes:
node.apply2all(func)
return res
def topmost_selected_nodes(self): #e might be needed by some context menus... how should the makers ask for it?
"return a list of all selected nodes as seen by apply2picked, i.e. without looking inside selected Groups"
#bruce 050523 revised this
from operations.ops_select import topmost_selected_nodes
return topmost_selected_nodes( self.topnodes)
# selection logic
def pick( self, item, group_select_kids = True ):
"select the given item (actually the node or group it shows)"
if group_select_kids:
item.object.pick()
else:
item.object.pick_top()
# as of 050131, this is: illegal (since it violates an invariant),
# incorrectly implemented (since it doesn't do leaf-specific pick funcs,
# though this could probably be easily fixed just as I'll fix unpick_top),
# and never called (since group_select_kids is always True).
return
def unpick( self, item, group_select_kids = True ):
"deselect the given item (actually the node or group it shows)"
if group_select_kids:
item.object.unpick()
else:
item.object.unpick_top()
return
def unpick_all(self):
for node in self.topnodes:
node.unpick()
def selection_click(self, item, _guard_ = 67548, \
group_select_kids = True, modifier = None, permit_drag_type = None, event = None):
"""Perform the ordinary selection-modifying behavior for one click on this item (might be None).
Assume the modifier keys for this click were as given in modifier, for purposes of selection or drag(??) semantics.
We immediately modify the set of selected items -- changing the selection state of their Nodes (node.picked),
updating tree-item highlighting (but not anything else in the application -- those will be updated when Qt resumes
event processing after we return from handling this click ###@@@ so we need to inval the glpane to make that work!
until then, it won't update til... when? the next paintGL call. hmm. I guess we just have to fix this now.).
If permit_drag_type is not None, this click might become the start of a drag of the same set of items it
causes to be selected; but this routine only sets some instance variables to help a mouse move method decide whether
to do that. The value of permit_drag_type should be 'move' or 'copy' according to which type of drag should be done
if it's done within this widget. (If the drop occurs outside this widget, ... #doc)
#doc elsewhere: for a single plain click on a selected item, this should not unselect the other items!
# at least finder doesn't (for sel or starting a drag)
# and we need it to not do that for this use as well.
"""
assert _guard_ == 67548, "you passed too many positional arguments to this function!"
###@@@ maybe some of this (or its callers) belongs in the subclass?
# Note: the following behavior uses Shift and Control sort of like the
# GLPane (and original modelTree) do, but in some ways imitates the Mac
# and/or the QListView behavior; in general the Mac behavior is probably
# better (IMHO) and maybe we should imitate it more. (For example, I'm
# very skeptical of the goodness of applying pick or unpick to entire
# subtrees as the default behavior; for now I refrained from changing
# that, but added a new mod-key-pair ShiftCntl to permit defeating it.)
# [bruce 050124]
#e This needs some way to warn the user of what happens in subtrees
# they can't see (when nodes are openable but closed, or even just with
# their kids scrolled out of sight). Probably best is to always show
# sel state of kids in some manner, right inside each Group's item. #e
# warning: in future the pick and unpick methods we're calling here
# might call incremental updaters back in this module or treeview!
# [bruce 050128 adding drag & drop support]
if self.drag_handler:
if debug_dragstuff:
print "should never happen: selection_click finds old drag_handler to dispose of"
try:
self.drag_handler.cleanup(self)
except:
print_compact_traceback("self.drag_handler.cleanup(self): ")
pass
self.drag_handler = None # might be set to an appropriate drag_handler below
## # store info about this click for subsequent mouseMoveEvents, so they can
## # decide whether to start a drag of some kind (for extending a selection, drag & drop, etc).
## #e not clear if it's cleaner to decide that right here, or when this info is used;
## # someday this self.drag_info object might be a drag_handler with its own event methods;
## # we'd then decide on its class here, so try to decide now.
## if item and not modifier:
## # subsequent mouseMoves might start a drag and drop.
## self.drag_info = drag_and_drop_handler(
## self.drag_info = attrholder()
## self.drag_info.permit_drag_type = permit_drag_type # whether or not it's None
###DOC - some comments below are WRONG, they're from before group_select_kids option was honored ####@@@@
if modifier == 'ShiftCntl': # bruce 050124 new behavior [or use Option key? #e]
# toggle the sel state of the clicked item ONLY (no effect on members);
# noop if no item.
if item:
if item.object.picked:
self.unpick( item, group_select_kids = False)
#bruce 050201 need some way to unselect group and not kids; should be ok
else:
self.pick( item, group_select_kids = group_select_kids)
elif modifier == 'Cntl':
# unselect the clicked item (and all its members); noop if no item.
if item:
self.unpick( item, group_select_kids = group_select_kids)
elif modifier == 'Shift':
# Mac would select a range... but I will just add to the selection,
# for now (this item and all its members); noop for no item.
##e in future: create a drag_selection_handler, which behaves differently
# depending on modifiers (since we'll also do it for Cntl
# and maybe even for ShiftCntl) and on whether item is None.
if item:
# whether or not item.object.picked -- this matters
# for groups with not all picked contents!
self.pick( item, group_select_kids = group_select_kids)
else:
# no modifier (among shift and control anyway)...
if item:
if item.object.picked:
# must be noop when item already picked, in case we're
# starting a drag of multiple items
pass
else:
# deselect all items except this one
self.unpick_all()
###e should this only be done within the "current space",
# imitating separate focus for PartGroup subtrees?
# same Q for how far group_select_kids (ie Group.pick) descends?
# Not sure.
self.pick( item, group_select_kids = group_select_kids)
# warning: some nodes don't let themselves become picked (e.g. Clipboard);
# for them self.pick is a noop, so we can't be certain any nodes are picked now.
# this click might later turn out to be starting a drag
# of the now-selected items:
if permit_drag_type:
nodes = self.topmost_selected_nodes()
if nodes:
# this test is enough to exclude the clipboard itself, since it's unselectable
# (which might not always be a good reason not to drag something! but it's ok for now)
self.drag_handler = self.drag_and_drop_handler( permit_drag_type, nodes, event)
# that method will create an object to handle the drag, pass it self,
# tell it how to callback to self in some ways when it starts the drag
else:
# no item
self.unpick_all()
# that should do it!
##e only sometimes do the following? have our own inval flags for these?
## do in subsets? do first on items changed above?
## [latter might be needed soon, for speed of visual feedback]
self.update_selection_highlighting()
self.update_glpane()
return # from selection_click
# selection dragging methods [#e not yet implemented] would go here
# drag and drop event handlers and helpers
# (some might be relevant whether the dragsource is self or something external)
def filter_drag_nodes(self, drag_type, nodes):
"""See which of the given nodes can be dragged (as a group) in the given way.
Return a subset of them to be actually dragged
(having emitted a warning, if desired, if this is not all of them),
or someday perhaps a processed version of them (e.g. you could pre-make copies for a 'copy' drag),
or None (*not* just a list [] of 0 nodes to drag! that might be possible to drag!)
if you want to refuse this drag (also after emitting a suitable warning).
"""
if drag_type == 'move':
nodes_ok = filter( lambda n: n.drag_move_ok(), nodes)
else:
nodes_ok = filter( lambda n: n.drag_copy_ok(), nodes)
oops = len(nodes) - len(nodes_ok)
if oops:
## msg = "some selected nodes can't be dragged that way -- try again" ###e improve msg
msg = "The Part can't be moved" # kluge: this is the only known case! (that I can remember...) #e generalize this
self.redmsg(msg)
return None
return nodes_ok # same as nodes for now, but we might change above code so it's not
def drag_and_drop_handler( self, permit_drag_type, nodes, click_event):
"this instance's way of constructing a drag_and_drop_handler with itself as dragsource"
listview = self
dragsource = listview
client = listview
return drag_and_drop_handler( client, dragsource, permit_drag_type, nodes, click_event)
# in the current imperfect API, this handler knows about the next few special methods
# in this object, and knows that "client" is this object, so it can call them.
# (except that internally it might still sometimes use dragsource when it should use client,
# since those are always the same for now.) [050129]
def advise_ended_drag(self):#####@@@@@ call this
"we call this ourselves - it does not do the operation on the nodes, but it resets variables"
###e should it also undo any highlighting of original nodes?
# or let caller do it? or just let next update do it? not sure...
self.current_drag_type = None
self.current_drag_nodes = []
return
# About tracking the position of a drag from outside (contentsDragEnter/Move/Leave/Drop):
# we don't track a pos from dragEnter since we're not sure it supplies one and since
# the "duplicate Enter bug" worries me. We track the pos from contentsDragMove, given
# in contents coords, but only valid at the then-current contents position
# (and until the next dragMove or dragLeave). When it comes we have to record
# what it was and what the contents position was. And we track changing contents
# positions, reported separately during a scroll (most importantly, during an
# autoscroll done by Qt during the drag event). All these events call a common
# updater for drop-point highlighting, update_drop_point_highlighting, which combines
# all this recorded info to know where to highlight (and remembers where it drew last
# time so it can un-highlight). It should only be called during a drag, and it can ask
# the listview what item is under various points near the drag-point.
# This is the last reported scroll position (topleft contents pos which is visible
# according to scrolling), reported by the contentsMoving signal.
last_scrollpos = (0,0)
# This is the last *reported* dragMoveEvent position, as a pair (x,y) in contents coords,
# or None when there's been a dragLeave since then, or (equivalently) if scrolling occurred
# (presumably autoscrolling during a drag) and we're disabling drops during scrolling.
last_dragMove_cpos = None
# And this is the value of scrollpos at the same time we set self.last_dragMove_cpos.
# (Its value when last_dragMove_cpos is None is undefined, i.e. should not be cared about.)
last_dragMove_scrollpos = (0,0)
# And this is the last "ok flag" for a drag enter or move event, set False by a dragLeave;
# not sure if this is needed, but maybe it's anded with whether last_dragMove_cpos is set... #doc
last_dragMove_ok = False
def contentsDragEnterEvent(self, event):
self.last_event_type = "dragenter"
# warning: for unknown reasons, this is sometimes called twice when i'd expect it to be called once.
## if debug_dragstuff:
## print_compact_stack("contentsDragEnterEvent stack (fyi): ")
ok = QTextDrag.canDecode(event) # this code is duplicated elsewhere
event.accept(ok)
self.last_dragMove_ok = ok
# the Qt docs warn that actually looking at the text might be slow (requires talking to the external app
# if it came from one), so using the text to find out whether the source is external would not be a good idea.
# For a dragMoveEvent, it subclasses DropEvent and thus might have a "source" we can look at... don't know.
## if debug_dragstuff:
## print "enter: ok = %r" % ok
#e maybe do same highlighting as dragmove... but not for now,
# since we have that dup-enter bug that the canvas had
return
def dragEnterEvent(self,event):
self.last_event_type = "dragenter" #k ok to do this here and for contentsDragEnter both??
if debug_dragstuff:
print "dragEnterEvent happened too! SHOULD NOT HAPPEN" # unless we are not accepting drops on the viewport
# To highlight the correct items/gaps under potential drop-points during drag and drop,
# we need to be told when autoscrolling occurs, since Qt neglects to send us new dragMove events
# when the global cursor position doesn't change, even though the position within the contents
# does change due to Qt's own autoscrolling!
## do_update_drop_point_highlighting_in_next_viewportPaintEvent = False
def _contentsMoving(self, x, y):
"""[Called by the Qt signal whose doc says:
"This signal is emitted just before the contents are moved
to position (x, y)." But this wording is misleading --
it's actually the position of the topleft visible part of the
contents (in contents coords), as determined by the scrollbars.
"""
## want one of these?? self.last_event_type = "_contentsMoving"
self.last_scrollpos = (x,y)
# Now, in case we're in a drag (after a dragMove), reset the drag position
# to None, just as a dragLeave would do, so as to disable a drop
# (and drop-point highlighting) during autoscrolling. (Note that any
# scrolling during a drag must be autoscrolling -- user is not touching
# scrollbar, and tree structure should not be changing.)
# For commentary about why this is a feature not a bug,
# even though it was motivated by the difficulty of doing the drop-point
# highlighting properly during autoscroll (and for the details of that
# difficulty and ideas for solving it), see removed comments in this method
# dated 050130 (in rev 1.21 in cvs).
# The following code is similar in dragLeave and Drop and _contentsMoving,
# not sure if identical:
self.last_dragMove_ok = False # not needed right now, but might matter
# after the next dragEnter but before the next dragMove
self.last_dragMove_cpos = None
# The following statusbar_msg suffix is the only way users are told
# why the drop-point highlighting disappeared, or what to do about it.
# It must be short but clear!
self.drop_disabled_because = "drop disabled by autoscroll, until mouse moves" #k still too long?? ###@@@ comes out at wrong time
self.update_drop_point_highlighting()
return
def contentsDragMoveEvent(self, event):
self.last_event_type = "dragmove"
# we can re-accept it (they suggest letting this depend on event.pos())...
# don't know if we need to, but all their doc examples do... so we will.
ok = QTextDrag.canDecode(event) # this code is duplicated elsewhere
event.accept(ok)
# note: using an "empty rect" arg did not cause "continuous dragMove events"
# like the Qt docs promised it would... for details, see comments near here
# in cvs rev. 1.19 [committed 050129] of this file. (Maybe some dragMove
# events were coming but not contentDragMove? I doubt it but who knows.)
self.last_dragMove_ok = ok
## gpos = event.globalPos() # AttributeError: globalPos
pos = event.pos()
## if debug_dragstuff:
## print "drag move pos:",tupleFromQPoint(pos) # this is in contents area coords. it autoscrolls but is not resent then!
self.last_dragMove_cpos = tupleFromQPoint(pos)
self.last_dragMove_scrollpos = self.last_scrollpos
self.update_drop_point_highlighting() # call whether or not self.last_dragMove_ok in case it just changed to False somehow
return
def contentsDragLeaveEvent(self, event):
self.last_event_type = "dragleave"
## if debug_dragstuff:
## print "contentsDragLeaveEvent, event == %r" % event
# the following code is similar in dragLeave and Drop and _contentsMoving,
# not sure if identical
self.last_dragMove_ok = False # not needed right now, but might matter
# after the next dragEnter but before the next dragMove
self.last_dragMove_cpos = None
## self.drop_disabled_because = "(drop outside model tree would drop a short text string, not what you want)" # maybe no need for text like this? ##e
self.drop_disabled_because = "(drop outside model tree -- not yet supported)"
self.update_drop_point_highlighting()
return
def dragLeaveEvent(self, event):
self.last_event_type = "dragleave" ###k ok here too?
if debug_dragstuff:
print "dragLeaveEvent, event == %r, SHOULD NOT HAPPEN" % event
#e remove highlighting from dragmove
true_dragMove_cpos = None
drop_disabled_because = ""
def update_drop_point_highlighting(self, undo_only = False):
#k undo_only might not be needed once a clipping issue is solved -- see call that uses/used it, comments near it
"""###OBS - some of this is wrong since we no longer use viewportPaintEvent as much -- 050131.
Maintain highlighting of possible drop points, which should exist whenever
self.last_dragMove_cpos and self.last_dragMove_ok, based on a drag position
determined by several last_xxx variables as explained in a comment near them.
Do new highlighting and undo old highlighting, by direct drawing and/or
invalidation (QWidget.update).
Note that some of the same drawing also needs
to be done by our custom viewportPaintEvent on top of whatever our superclass
would draw, even if we draw in the same place here -- this routine's drawing
works for things already visible, viewportPaintEvent's for things uncovered
by scrolling, and we're not always sure which is which, nor would it be practical
to fully divide the work even if we were.
So, this routine records what drawing needs to happen (of the "do" type, not
the "undo" type), and calls a common routine to do it, also called by
viewportPaintEvent if its rect might overlap that drawing (which is always
small in vertical extent, since near the drop point -- at least for now).
But for "undo" drawing it's different... I guess viewportPaintEvent needn't do
any "undo drawing" since what its super method draws is "fully undone" already.
Oh, one more thing -- the "original nodes" also look different (during a move),
and this is "do" drawing which changes less often, is done even when the dragged
point is outside the widget, and has a large vertical extent -- so don't do it
in this routine! It too needs doing when it happens and in viewportPaintEvent,
and undoing when that happens (but not in viewportPaintEvent), but is done by some
other routine. ####@@@@ write it!
If in the future we highlight all inactive drop points as well as the one active
one, that too (the inactive ones) would be done separately for the same reasons.
"""
assert not undo_only
bugmsg = 0 # set to 1 to zap wrong msgs for alpha since no time to fix them #bruce 050202
alpha_wrong_msgs = ["drop disabled by autoscroll, until mouse moves", "<bug if you see this>"]
undo_true_dragMove_cpos = self.true_dragMove_cpos # undo whatever was done for this pos
# that only works if we're sure the items have not moved,
# otherwise we'd need to record not just this position
# but whatever drawing we did due to it; should be ok for now
if self.last_dragMove_cpos and self.last_dragMove_ok:
# some drop-point highlighting is wanted; figure out where.
# if we felt like importing Numeric (and even VQT) we could do something like this:
## correction = self.last_scrollpos - self.last_dragMove_scrollpos
## self.true_dragMove_cpos = self.last_dragMove_cpos + correction
# but instead:
correction = pair_minus( self.last_scrollpos, self.last_dragMove_scrollpos )
self.true_dragMove_cpos = pair_plus( self.last_dragMove_cpos, correction )
substatus = "" # use "" since flicker on/off is better than flicker between two texts!
## if debug_dragstuff:
## print "correction = %d - %d = %d; true = lastmovecpos %d + correction = %d" % (
## self.last_scrollpos[1], self.last_dragMove_scrollpos[1], correction[1],
## self.last_dragMove_cpos[1], self.true_dragMove_cpos[1] )
else:
self.true_dragMove_cpos = None
####@@@@ the following is only valid if a dragLeave (I think) was the last event we had in the app! (or so)
# now, this shows up even for a "copy" event which moves the scrollbar! #####@@@@@
# use self.last_event_type somehow (revise it so we can)#####@@@@@
substatus = " -- " + self.drop_disabled_because
# substatus is independent of whether drag is initiated in this widget
if self.drop_disabled_because in alpha_wrong_msgs:
bugmsg = 1
# now figure out where the drag came from and what it means, to mention in statsubar
if self.drag_handler:
# if this exists, then it should be the source... or this message will report that bug
desc = self.drag_handler.describe_your_drag_and_drop()
else:
desc = "drag from outside tree widget" #e subclass should supply widget description
bugmsg = 1
actualmsg = desc + substatus
if bugmsg:
if debug_dragstuff:
print "alpha wanted to put this into statusbar but it's probably a bug, so not doing that:"
print " " + actualmsg
actualmsg = " " # sigh... in fact, don't put it there since it erases our results msg.
else:
self.statusbar_msg( actualmsg )
# now it's time to figure out where we are, if anywhere, and what drop points we would hit
listview = self
cpos = self.true_dragMove_cpos # None or a tuple
if cpos:
x,y = cpos
## not needed: item = self.itemAtCposXY(x,y) # item you might want to drop on directly, or None
# How to detect the mouse pointing at a gap:
# a gap lies between (the rows of) adjacent items-or-None (but never both None);
# the items touch so the gap (as a mouse-target) overlaps each one by some amount;
# if we imagine it extends y_up into top item and y_down into bottom item,
# then it can be looked for by letting mouse drag around a dual-point AFM :-)
# whose points are that much down and up (in reverse order) from its own position...
# that is, look for a top item y_down above your pos, and for a bottom one y_up below your pos.
# Usually y_down == y_up, but that's no excuse to fail to reverse them in this code!
# In fact, to support hysteresis and/or mouse-hotspot-corrections
# we might make them vary a bit, per gap,
# and then they'll differ when looked for above and below one item -- different gaps...
# BTW, the item found above tells us (mostly) what two gaps to look for...
# not if it's None, though...
# For now, to simplify this, just look a fixed amount up or down,
# and see one item in both places (then drop onto that item, regardless of x I think? not sure)
# or see two items-or-Nones (only bottom one can be None, since we leave no empty space at top --
# not true, the top point could look above the top item, but we don't permit a drop there).
# Then you want to drop between them; x position determines desired depth (closest icon-column-
# centerline of permissible drop-depths), can be as left as either item (above or below gap)
# or as right as either item or as hypothetical children of top item if that one is openable.
# (No ambiguity if that matches depth of bottom item! And useful for becoming top child of closed
# items, since drop directly on item makes you bottom child. Sbar message should say where you'd drop. ###e)
# Find the items-or-Nones above and below the gap (if same, you're over that item, not a gap):
###e should change from hardcoded constants below... sorry, the deadline approaches...
top = self.itemAtCposXY(x,y-3) #e these constants will probably need subjective adjustment, maybe hysteresis
bottom = self.itemAtCposXY(x,y+3)
##050309 return #####@@@@@
if top == bottom:
if top:
# dropping inside item top
where = "dropping inside item %r" % top.object.name
else:
# dropping into empty space
where = "dropping into empty space"
elif not top:
# too high to drop (it's above all items, at least for now with no big gaps in the display)
where = "too high, above highest item %r" % bottom.object.name
else:
# dropping into the gap between items top (not None) and bottom (maybe None);
# use x position to figure out desired depth
if bottom:
where = "somewhere in gap between items %r and %r..." % (top.object.name, bottom.object.name)
dtop = self.itemDepth(top) # in units of integers not pixels?? or floats but where 1.0 is the level-change in x?
# or ints but where the level-change is known to us??
dbottom = self.itemDepth(bottom)
##050309 dmouse = self.itemDepthForCposX(x) # depth of the mouse itself (float, 1.0 means "size of one level")
mindepth = min(dtop, dbottom) # leftmost possible drop-point (larger depths are innermore ie to the right)
maxdepth = max(dtop, bottom) # rightmost, not yet counting "new child of top"
maybe_new_child_of_top = False # change below
if 0 and self.isItemOpenable(top): #### 0 in case attrname is wrong, i need to commit now #####@@@@@ where i am #2
maybe_new_child_of_top = True ### 050201 433pm
dtop_child = dtop + 1
if dtop_child > xxx: pass ####
pass ####@@@@@ stubbly here...
else:
where = "under last item %r" % (top.object.name,)
listview.itemAt
### got about this far when the alpha deadline hit...
# now undo old drawing and do new drawing. #####@@@@@
if not debug_dragstuff: return #e remove soon, when next stuff is not a stub
###stub for debugging: draw white to undo and blue to do, of a symbol just showing where this point is.
# always undo first, in case there's an overlap! (might never happen once we're doing real highlighting, not sure)
# for real highlighting some of it will be redrawing of items in different ways, instead of new drawing.
painter = QPainter(self.viewport(), True) # this might not end up drawing in enough places... draws in viewport coords; False###e
# fyi: the following method knows about true_dragMove_cpos perhaps being None, draws nothing in that case
self.draw_stubsymbol_at_cpos_in_viewport(painter, undo_true_dragMove_cpos, color = Qt.white, blot = 1) #e should use backgroundcolor from a palette
###e also redraw any items (incl open/close icons) we might have just drawn over... or make sure we never draw over them.
if not undo_only:
self.draw_stubsymbol_at_cpos_in_viewport(painter, self.true_dragMove_cpos, color = Qt.blue) #e should use highlight color from a palette
def itemDepth(self,item):
return 2.0 #stub #####@@@@@ use item.depth()
def itemAtCposXY(self, x, y):
####WRONG, does not check for too far to left or right, on openclose, etc...
### USE AS STUB but then split out the code from contentsMousePress
# and use that instead of direct itemAt. #####@@@@@
#e also, for DND or seldrag we might want both the item-row and whether we're really in it... for now, assume not...
# but worry about where user will point mouse for gaps if i draw an arrow to the left of the items pointing to them,
# or a circle just outside the icon level...
vpos = self.contentsToViewport(QPoint(x,y)) # or QPointFromTuple((x,y)) #k or i bet QPoint could be left out entirely
return self.itemAt(vpos) # might be None
def draw_stubsymbol_at_cpos_in_viewport(self, painter, cpos, color = Qt.red, blot = False):
if cpos is None:
# warning: other code in this file just says "if cpos",
# so if we switch to Numeric, watch out for (0,0) being false!
return
cx,cy = cpos
dx,dy = self.last_scrollpos
x = cx - dx
y = cy - dy
## if debug_dragstuff:
## print "drawing (white or blue or ...) at vpos:",x,y
# 050309 hacks:
x = 3
# end 050309 hacks
if not blot:
self.drawbluething( painter, (x,y), color)
else:
# blotbluething doesn't work, so just be quick and dirty here:
## for i in [-1,0,+1]:
## for j in [-1,0,1]:
## self.drawbluething( painter, (x+i,y+j), color)
self.drawbluething( painter, (x,y), color) #050130 9:33pm #####@@@@@
return
# this debug func overrides the one in TreeView so I can extend it here
def drawbluething(self, painter, pos = (0,0), color = Qt.blue): # bruce 050110 taken from my local canvas_b2.py
"[for debugging] draw a recognizable symbol in the given QPainter, at given position, of given color"
p = painter # caller should have called begin on the widget, assuming that works
p.setPen(QPen(color, 3)) # 3 is pen thickness
w,h = 100,9 # bbox rect size of what we draw (i think)
# 050309 hacks:
w = 14
# end 050309 hacks
x,y = pos # topleft of what we draw
p.drawEllipse(x,y,h,h)
fudge_up = 1 # 1 for h = 9, 2 for h = 10
p.drawLine(x+h, y+h/2 - fudge_up, x+w, y+h/2 - fudge_up)
## def blotbluething(self, painter, pos = (0,0), color = Qt.white): ###k this doesn't work, why?
## "[for debugging] blot out what drawbluething drew, with 1 pixel margin as well"
## p = painter # caller should have called begin on the widget, assuming that works
## p.setPen(QPen(color, 6)) # 6 is pen thickness, at least half of 11, our height in the end, below
## w,h = 100,9 # bbox rect size of what we draw (i think)
## w += 1 # correct bug in above
## w += 2; h += 2 # margin
## x,y = pos # topleft of what we draw
## x -= 1; y -= 1 # margin
## p.drawRect(x,y,h,h)
def paintEvent(self, event):
"[overrides TreeView.viewportPaintEvent]"
## if debug_dragstuff:
## print "TreeWidget.viewportPaintEvent"
super = TreeView # the class, not the module
res = super.paintEvent(self, event)
cpos = self.true_dragMove_cpos
if cpos and debug_dragstuff:
painter = QPainter(self.viewport(), True)
self.draw_stubsymbol_at_cpos_in_viewport(painter, cpos, color = Qt.green) # i think we're depending on clip to event.rect()
# should use highlightcolor; for debug use diff color than when drawn in the other place that can draw this
if debug_dragstuff:
print "drew in green"
## if self.do_update_drop_point_highlighting_in_next_viewportPaintEvent: ###@@@ 050130
## self.do_update_drop_point_highlighting_in_next_viewportPaintEvent = False
## self.update_drop_point_highlighting()
return res
#e change highlighting/indicating of possible drop points (gaps or items) (e.g. darken icons of items)
#e should we also change whether we accept the drop or not based on where it is? [i think not. surely not for alpha.]
# - do we want to?
# - does it affect the icon appearance? if so will this mislead users into thinking entire widget refuses?
# - does it work, semantically?
# ...also is it possible to actually examine the text being offered, to decide whether to accept it?
# (that way we can tell if it's from inside or outside this app. this would not be needed for alpha.)
# [later solved that: get a contentsMoving signal.]
# so i'd better use the advice above about returning the empty rect!
## # following is not right, we want to try doing this inside the contents.
## listview = self
## wpos = listview.mapFromGlobal(gpos)
def junk_copied_from_above():
unclipped = True # True works, can draw over the QListView column label and the scrollbar. False draws nothing!
# So we have to use True for now, though it's "dangerous" in terms of what we might mess up.
##e probably better (and not hard) to define our own clipper and clip to that...
#e we could also put this painter inside the drawing area, would that work better? try it sometime.
painter = QPainter(listview, unclipped)
gpos = event.globalPos()
wpos = listview.mapFromGlobal(gpos)
x,y=wpos.x(),wpos.y() # this works, scrolled or not, at least with unclipped = True
listview.drawbluething( painter, (x,y)) # guess: this wants viewport coords (ie those of widget). yes.
listview.update() #k needed?
def contentsDropEvent(self, event):
self.last_event_type = "drop"
if debug_dragstuff:
print "contentsDropEvent, event == %r" % event
# should we disable the drag_handler, or rely on mouseRelease to do that? ###e ####@@@@
# We might be inside autoscroll, with drop-point highlighting disabled...
# detectable by self.last_dragMove_cpos is None. In that case we should
# refuse the drop. Ideally we'd report what the drop would have been into...
# not for now since computing that is nim even for an accepted drop! ###e revisit
disabled = (self.last_dragMove_cpos is None) # used more than once below
# the following code is similar in dragLeave and Drop, not sure if identical
self.last_dragMove_ok = False # not needed right now, but might matter
# after the next dragEnter but before the next dragMove
self.last_dragMove_cpos = None
if disabled:
self.drop_disabled_because = "drop ignored since in autoscroll" # will be zapped by redmsg anyway
else:
self.drop_disabled_because = "<bug if you see this>" # only shows up when disabled... clean this up!
#####@@@@@ this comes out when you click and scroll, e.g. if copy in cmenu extends contents height... not in any drag
self.update_drop_point_highlighting()
if disabled:
self.redmsg( "drop refused due to autoscrolling (and no subsequent mouse motion) -- too dangerous.")
event.ignore()
return
oktext = QTextDrag.canDecode(event)
#e in future even this part (choice of dropped data type to look for)
# should be delegated to the current drag_handler if it recognizes it
if oktext:
if debug_dragstuff:
print "accepting text"
str1 = QString() # see dropsite.py in examples3
res = QTextDrag.decode(event, str1)
text = str(str1)
if debug_dragstuff:
print "got this res and text: %r, %r" % (res,text) # guess: from finder it will be filename [was url i think]
event.accept(True)
# up to this point (accepting dropped text) we'll behave the same whether or not it was *our* dropped object.
# (except for the highlighting done by DragMove, which ideally would distinguish that according to which items
# want to accept drops from inside vs outside this widget. But that distinction can be post-Alpha.)
# Now that we accepted the drop, to handle it properly we do need to know whether it was ours.
# If it was ours, it was created by a presently active drag_handler
# (which should be still inside its start_a_drag method), so if we have one, just ask it.
# (Someday we might think it's wise to do this earlier so it had a chance to reject the drop.)
if self.drag_handler:
messed_up_retval = self.drag_handler.one_of_yours_Q( event, text) # False, or a tuple of useful data #e revise!
if messed_up_retval:
# return "true" whether or not it accepts the drag! (once it has that choice) (i mean return "recognized"
# not just "accepted". it could return (recognized, type, nodes) with type == None meaning rejected.
# when it always does that we can change the call to immediately assign the reval to the tuple, if we want.
recognized_Q, drag_type, nodes = messed_up_retval
# but for now we can only handle the following:
assert recognized_Q == True
if debug_dragstuff:
# because recognized_Q:
print "our drag handler recognized this drop as one it had generated"
if drag_type:
print "our drag handler accepted this drop"
assert drag_type in ['copy','move'] # for now it can't reject it; to do that it would return None
# (sorry for the mess, the deadline approaches)
# and nodes is a list of 1 or more nodes, and it's been our job to highlight the originals specially too,
# which means we already knew this list of nodes
assert nodes == nodes #e i mean the ones we already knew about
# and (unlike some other comments' claims nearby)
# it's our job to now do the operation.
self.doit(event, drag_type, nodes)
if 0 and debug_dragstuff:
print "NOT IMPLEMENTED: do the op on these dragged nodes:",nodes
self.redmsg("NIM: do the op %r on %d nodes, first/last names %r, %r" % (
drag_type, len(nodes), nodes[0].name, nodes[-1].name ))
## do the op
## } #####@@@@@@
### OBS WRONG COMMENT:
# not only that, it did all the work needed by it (since it, more than us, knew what it all meant...);
# and it even did all the updates in this widget, required by whatever it did to our state --
# even though some highlighting is set up here but should be undone by it? not sure about that yet!
# (maybe we do the graphics and it does the semantics... but the changes need to be coordinated)
# in other words the interaction between this and the handler is not clear -- they are like parts of one object
# and maybe it's even a bit weird to separate them... we'll see. Anyway, sounds like we're done.
return
pass
# well, that guy didn't want it (or didn't exist) so it's our problem. That means the drop is from another app.
# (or another widget in this app.)
# someday we'll handle these and that will be very useful...
# for now just acknowledge that we got this data and what it contained
# (in a way which might sometimes be marginally useful, and seems non-harmful unless
# someone drops way too much text onto us, which they can easily avoid doing.)
if len(text) > 250:
text = text[:250] + "..."
env.history.message("fyi: accepted (but ignoring) this dropped text from outside this widget: %r" % text)
else:
# drop was not able to provide us with text -- can't possibly be one of ours
if self.drag_handler and self.drag_handler.doing_our_own_drag:
errmsg = "likely bug warning: dropped object should have been ours but provided no text; ignored"
self.redmsg(errmsg) #e redmsg
event.accept(False)
self.redmsg("fyi (nim feature): refused dropped object which could not provide text")
self.statusbar_msg(" ") # probably a good idea -- not sure!
return # from overly-long method contentsDropEvent
def redmsg(self, errmsg): #e someday this might come from the subclass #e refile this method near statusbar_msg
"put an error message into the History"
from history.HistoryWidget import redmsg
env.history.message( redmsg(errmsg))
self.statusbar_msg(" ") # probably a good idea -- not sure!
return
def doit(self, event, drag_type, nodes): #bruce 050201 quick hack for Alpha ###@@@ review #e rename
"stub to do a drop"
from foundation.Utility import node_name
# can't do this: cpos = self.true_dragMove_cpos # None or a tuple
# since attr has been set to None already by our caller
pos = event.pos() # this pos is more recent anyway -- but we might be in the middle of autoscroll, oh well
cpos = tupleFromQPoint(pos)
if not cpos:
# don't print this, let the flyback effect show the result (or maybe it succeeds in dropping text somewhere!)
## print "drop not in widget"
return
x,y = cpos
item = self.itemAtCposXY(x,y) # item you might want to drop on directly, or None
if not item:
self.redmsg( "drop into empty space ignored (drops under groups are not yet supported; drop right onto them instead)")
return
#e worry about where on the item?
targetnode = item.object
if not targetnode.drop_on_ok(drag_type, nodes):
self.redmsg( "drop refused by %r" % node_name(targetnode) )
return
oldpart = nodes[0].part #bruce 060203
if drag_type == 'move':
#bruce 060203 see if this helps implement NFR/bug 932 (which says, don't pick moved nodes or open their drop target);
# do this first to make sure they're not picked when we move them... which might change current part [unverified claim].
for node1 in nodes:
node1.unpick()
copiednodes = targetnode.drop_on(drag_type, nodes) # implems untested! well, now tested for a day or so, for assy.tree ... 050202
#bruce 050203: copiednodes is a list of copied nodes made by drop_on (toplevel only, when groups are copied).
# for a move, it's []. We use it to select the copies, below.
#bruce 050203 cause moved nodes to remain picked;
# for copied nodes, we want the copies not originals to be picked.
#bruce 060203 no longer pick moved nodes if moved into a different part, but still pick copies,
# or nodes moved into the same part (or entire parts moved as a whole, only possible w/in clipboard).
if drag_type == 'move':
# this case rewritten by bruce 060203 re bug/NFR 932 (whose full fix also involved other files)
self.unpick_all() # probably redundant now
# pick the moved nodes, iff they are still in the same part.
# run update_parts to help us; this covers case of moving an entire part w/in the clipboard,
# in which it should remain picked.
# (Someday it might be useful to look at nodes[0].find_selection_group() instead...)
self.assy.update_parts()
# FYI: drop_on sometimes does update_parts, but not always, so do it here to be safe. Optim this later.
# Note: knowing anything about parts, and maybe even knowing self.assy, violates modularity
# (re supposed generality of TreeWidget as opposed to modelTree); fix this later.
# (I guess just about this entire method violates modularity, and probably so does much else in this file.
# As an older comment said:
# Note that this behavior should be subclass-specific, as should any knowledge of "the clipboard" at all!
# This needs review and cleanup -- maybe all this selection behavior needs to ask nodes what to do.)
newpart = nodes[0].part
if oldpart is newpart:
for node1 in nodes:
node1.pick()
pass
else:
self.unpick_all()
# Pre-060203 code: we pick the copies iff they remain in the main part.
# The reason we don't pick them otherwise is:
# - NFR 932 thinks we shouldn't, in some cases (tho it probably doesn't think that
# if they are and remain in one clipboard part)
# - there's a bug in drop_on which can put them in more than one clipboard item,
# but the selection is confined to one clipboard item.
# With a little work we could improve this (in the cases not affected by that bug).
# [comment revised, bruce 060203]
## if not targetnode.in_clipboard():
## for node1 in copiednodes:
## node1.pick()
#bruce 060203 revising this to use similar scheme to move case (but not when copies get split up):
# pick the copies if they're in the same part as the originals.
# (I believe this will either pick all copies or none of them.)
self.assy.update_parts()
for node1 in copiednodes:
if node1.part is oldpart:
node1.pick()
pass
## print "did it!"
# ... too common for a history message, i guess...
msg = "dragged and dropped %d item(s) onto %r" % (len(nodes), node_name(targetnode))
#e should be more specific about what happened to them... ask the target node itself??
msg = fix_plurals(msg)
self.statusbar_msg( msg)
#bruce 050203: mt_update is not enough, in case selection changed
# (which can happen as a side effect of nodes moving under new dads in the tree)
self.win.win_update()
return
# key event handlers
def keyPressEvent(self, event): ####@@@@ Delete might need revision, and belongs in the subclass
key = event.key()
if debug_keys:
print "mt key press",key###########@@@@@
from utilities import debug_flags
key = platform.filter_key(key) #bruce 041220 (needed for bug 93)
####@@@@ as of 050126 this delete binding doesn't seem to work:
if key == Qt.Key_Delete: ####@@@@ belongs in the subclass
# bruce 041220: this fixes bug 93 (Delete on Mac) when the model
# tree has the focus; the fix for other cases is in separate code.
# Note that the Del key (and the Delete key on non-Mac platforms)
# never makes it to this keyPressEvent method, but is handled at
# some earlier stage by the widget, and in a different way;
# probably this happens because it's a menu item accelerator.
# The Del key (or the Delete menu item) always directly runs
# MWsemantics.killDo, regardless of focus.
self.win.killDo()
## part of killDo: self.win.win_update()
elif key == Qt.Key_Escape: # mark 060129. Select None.
self.assy.selectNone()
# bruce 041220: I tried passing other key events to the superclass,
# QListView.keyPressEvent, but I didn't find any that had any effect
# (e.g. arrow keys, letters) so I took that out.
#bruce 060219/20: adding arrow key bindings as an experiment.
elif key == Qt.Key_Up: # up arrow key
self.moveup()
elif key == Qt.Key_Down: # down arrow key
self.movedown()
elif key == Qt.Key_Left: # left arrow key
self.moveleft()
elif key == Qt.Key_Right: # right arrow key
self.moveright()
else:
pass #e should we let the mode process it??
return
def keyReleaseEvent(self, event):
key = event.key()
if debug_keys:
print "mt key release",key###########@@@@@
def moveup(self): #bruce 060219
"Move the selection up (not the nodes, just their selectedness)"
self.move_up_or_down(-1)
def movedown(self): #bruce 060219
"Move the selection down (not the nodes, just their selectedness)"
self.move_up_or_down(1)
def move_up_or_down(self, offset): #bruce 060219, revised 060220
"""Move selection to different nodes (without changing structure of the nodes)
down (-1) or up (1) within sequence of all visible nodes.
"""
#e Bug: what should we do if several nodes are moving down and they get into different selection groups?
# I might hope that someday that's permitted... for now, this is ignored, which sometimes makes one
# disappear and a history message show up,
# Warning: deselected some items in untitled, to limit selection to one clipboard item or the part.
nodeset = self.topmost_selected_nodes()
if not nodeset:
return # avoids win_update
visibles = list(self.assy.tree.genvisibleleaves(include_parents = True)) + \
list(self.assy.shelf.genvisibleleaves(include_parents = True))
#e more correctly, I should use the attr for listing our toplevel tree items... #e
if self.assy.shelf in visibles:
visibles.remove(self.assy.shelf) #e more correctly, remove unpickable nodes
###BUG (undiagnosed, but probably same as old reported bug, see below):
# sometimes clipboard can look open in MT but .open = False! Then this code ignores everything in clipboard
# (still lets you pick inside it, but not use arrow keys there).
# Then if you manually close/open clipboard in MT, .open = True and this code works.
# Guess: some code somewhere sets shelf.open = False (when? why? good??) and doesn't mt_update (bug).
# Not so clear: does that mean it ought to be closed to start with?? ###@@@
#e Possible workaround: detect the treeitem children being present, and fix shelf.open to match reality.
# (Not sure if that could cause trouble.)
# Note: I think this is the same bug that makes the first click to close the shelf not work sometimes.
# That bug is reported, and maybe has a bug comment with some clues about the cause. ###e find out!
##if not visibles:
## # should not happen (due to include_parents = True);
## # without that, might happen if selection is inside a closed Group (or closed shelf), if UI permits that;
## # but it might no longer be correct then (depending on what we do below), so commenting it out.
## return
for node in nodeset:
node.unpick()
for node in nodeset:
if node in visibles:
index = sib_index(visibles, node, offset)
visibles[index].pick() # might be same node as before, if it was at appropriate end of visibles
#e we should probably make this visible in MT
# (shouldn't require opening Groups, since new node was in visibles,
# but maybe do it for safety; might require scrolling MT)
else:
# not visible. ##e should we move it out to a visible place in the MT?? not done for now.
#e known bug: what happens now is that the icon for a closed group looks a bit different after this!
node.pick()
self.win.win_update()
def moveleft(self): #bruce 060219
"Select the Group or Groups containing the selected node or nodes"
nodeset = self.topmost_selected_nodes()
if not nodeset:
return # avoids win_update
for node in nodeset:
if not node.is_top_of_selection_group():
node.dad.pick()
self.win.win_update()
def moveright(self): #bruce 060219, revised 060220
"""Select (only) the first element of each toplevel selected Group;
for toplevel selected leaf nodes, move them down [#untested].
"""
nodeset = self.topmost_selected_nodes()
if not nodeset:
return # avoids win_update
downguys = [] # nodes (whose selectedness is) to be moved down instead of right
newguys = []
for node in nodeset:
if node.is_group() and node.members:
node.unpick() # (unpicks the members too)
newguys.append(node.members[0]) # pick this later, so as not to interfere with moving downguys down
elif not node.is_group():
downguys.append(node) # but leave it picked (kluge)
# and what about for an empty group? maybe also go down? try this for now...
else:
downguys.append(node)
# handle downguys.
# kluge: we left them (and only them) picked, above, so we don't have to pass them to move_up_or_down
# or teach it to accept a list of passed nodes.
if downguys:
self.move_up_or_down(1)
for node in newguys:
node.pick()
node.dad.open = True # need to make sure we can see what we just picked...
#e 1. Should a modkey control this, vs. not scanning into closed Groups?
#e Or worse, should it let you scan into them while leaving them closed??
#e (Which reminds me, we need to visually indicate selection inside unselected closed Groups.)
#e 2. Maybe we should remember we did this, and autoclose it if user just keeps scanning down (or up), out of it?
#e (When several nodes are moving, we'd autoclose when none of them were in an autoopened group anymore.)
#e Not sure if autoclose would be good; guess yes. (Or maybe it should be a user pref.)
# 3. Note that in theory this whole thing can occur inside a closed Group.
self.win.win_update()
# == in-place editing of item text
renaming_this_item = None
def maybe_beginrename(self, item, pos, col):
"""Calls the Qt method necessary to start in-place editing of the given item's name.
Meant to be called as an event-response; presently called for double-click on the name.
"""
self.dprint("maybe_beginrename(%r, %r, %r)"%(item,pos,col))
if not item: return
# Given the event bindings that call this as of 050128,
# the first click of the double-click that gets here selects the item
# (including its members, if it's a group); this might be bad (esp. if
# it's left selected at the end), but
# changing it requires updates (to mtree and glpane) we're not doing now,
# whether we change it before or after the rename,
# and during the rename it might be useful to see what you're renaming
# in the glpane too (and glpane redraw might be slow).
# So I think we'll only unpick when the renaming is done;
# if it's cancelled, we currently never notice this, so we have no place
# to unpick; that's ok for now. [bruce 050128]
## item.object.unpick() #bruce 050128 precautionary change -- undo the picking done by the first click of the double-click
## ###e probably need to update the display too? not sure. ####@@@@
## if item.object.picked: print "didn't work!"####@@@@
## else: print "did work!"
if col != 0: return
if not item.renameEnabled(col):
self.statusbar_msg("renaming %r is not allowed" % item.object.name) #k will this last too long?
return
istr = str(item.text(0))
msg = "(renaming %r; complete by <Return> or click; cancel by <Escape>)" % istr # text, not html!
self.statusbar_msg( msg)
# this happened even for a Datum plane object for which the rename does not work... does it still? ###@@@
###@@@ some minor bugs about that statusbar message: [050126]
# - it needs to reappear in enterEvent rather than having " " appear then
# - it needs to go away after user cancels the rename
# (can some focus-related event or state tell us when?)
# + [fixed:] it could be shortened; also it fails to mention "accept by click elsewhere"
# and wrongly hints this would not work
# - its text (like some of our method names) assumes the item text is something's name,
# but only our subclass (or maybe even only the node) knows what the item text actually represents!
self.renaming_this_item = item # so we can accept renaming if user clicks outside the editfield for the name
item.startRename(0)
###@@@ does any of this belong in the subclass??
def _itemRenamed(self, item, col, text): # [bruce 050114 renamed this from changename]
"receives the signal from QListView saying that the given item has been renamed"
self.dprint("_itemRenamed(%r, %r, %r)" % (item,col,text))
if col != 0: return
oldname = self.done_renaming()
if oldname != item.object.name: #bruce 050128 #e clean all this up, see comments below
if debug_flags.atom_debug:
print "atom_debug: bug, fyi: oldname != item.object.name: %r, %r" % (oldname, item.object.name)
what = (oldname and "%r" % oldname) or "something" # not "node %r"
## del oldname
# bruce 050119 rewrote/bugfixed the following, including the code by
# Huaicai & Mark to strip whitespace, reject null name, and update
# displayed item text if different from whatever ends up as the node's
# name; moved much of that into Node.try_rename.
try:
text_now_displayed = str(text) # turn QString into python string
except UnicodeEncodeError: #bruce 050508 experiment (failed) and bug-mitigation (succeeded)
## if debug_flags.atom_debug:
## print "atom_debug: fyi: trying to handle UnicodeEncodeError for renamed item"
## text_now_displayed = unicode(text)
## # fails: wrong funny chars in glpane, exception when writing new name to history file
(ok, newname) = (False, "non-ASCII characters are not yet supported")
# semi-kluge: text_now_displayed is used below in two ways -- error message (written to hist, must be ascii)
# and must differ from item.object.name so that gets written back into the MT item.
# non-kluge solution would be to bring that code in here too, or separate those uses.
# what I'll do -- make "not ok" also always cause item.setText, below.
text_now_displayed = ('%r' % unicode(text))[2:-1] # change u'...' to ...
assert type(text_now_displayed) == type(""), "repr of unicode is not ordinary string"
del text
else:
del text
# use text_now_displayed (not further changed) for comparison with final name that should be displayed
(ok, newname) = item.object.try_rename(text_now_displayed) #e pass col?
if ok:
res = "renamed %s to %r" % (what, newname)
if newname != item.object.name: #bruce 050128
if debug_flags.atom_debug:
print "atom_debug: bug, fyi: newname != item.object.name: %r, %r" % (newname, item.object.name)
else:
reason = newname
del newname
## newname = oldname # since newname should be what we want to show in the node now!
## # [bruce 050128 to fix new bug mentioned by Ninad and in the catchall bug report]
res = "can't rename %s to \"%s\": %s" % (what, text_now_displayed, reason) #e redmsg too?
##e not sure this is legal (it's a func but maybe not a method): res = env.history.redmsg(res)
newname = item.object.name # better to just get it from here -- shouldn't even return it from try_rename! #e
if (not ok) or text_now_displayed != newname:
# (this can happen for multiple reasons, depending on Node.try_rename:
# new name refused, whitespace stripped, etc)
# update the display to reflect the actual new name
# (might happen later, too, if try_rename invalidated this node;
# even so it's good to do it now so user sees it a bit sooner)
item.setText(col, newname)
env.history.message( res)
#obs: # no need for more mtree updating than that, I hope (maybe selection? not sure)
#bruce 050128 precautionary change -- undo the picking done by the
# first click of the double-click that started the renaming
item.object.unpick()
self.win.win_update()
return
def click_elsewhere_finishes_renaming(self):
"[private] let this click finish an in-place renaming, if there was one."
# [050131, added protection against item being deleted during renaming -- I hope this fixes bug 363]
if self.renaming_this_item:
try:
self.renaming_this_item.okRename(0) # 0 is column # this ends up calling _itemRenamed
# could this scroll the view? I doubt it, but if so,
# it's good that we figured out cpos,vpos,item before that.
except:
# various errors are possible, including (I guess)
# "RuntimeError: underlying C/C++ object has been deleted"
# if user deletes that object from the glpane or a toolbutton during the rename [050131 comment]
pass
self.done_renaming()
# redundant with slot function, but i'm not sure that always runs or gets that far
self.renaming_this_item = None # redundant with done_renaming()... last minute alpha precaution
return
def done_renaming(self):
"call this when renaming is done (and if possible when it's cancelled, tho I don't yet know how)"
try:
oldname = self.renaming_this_item.object.name
except:
# various errors are possible, including (I guess)
# "RuntimeError: underlying C/C++ object has been deleted"
# if user deletes that object from the glpane or a toolbutton during the rename [050131 comment]
oldname = ""
self.renaming_this_item = None
self.statusbar_msg("")
return oldname
# debug menu items
def debug_menu_items(self):
"overrides method from DebugMenuMixin"
super = DebugMenuMixin
usual = super.debug_menu_items(self)
# list of (text, callable) pairs, None for separator
ours = [
("reload modules and remake widget", self._reload_and_remake),
("(treewidget instance created %s)" % self._init_time, lambda x:None, 'disabled'),
("call win_update()", self._call_win_update),
("call mt_update()", self._call_mt_update),
]
ours.append(None)
ours.extend(usual)
return ours
def _call_win_update(self):
self.win.win_update()
def _call_mt_update(self):
self.mt_update()
def _reload_and_remake(self): ###e needs rewriting to let subclass help with the details...
"""reload all necessary modules (not just this one), and replace the existing tree widget
(an instance of some subclass of this class)
with a new one made using the reloaded modules
"""
# for now we might just plop the new one over the existing one! hope that works.
print "_reload_this_module... i mean all needed modules for the tree widget, and remake it..."
width = self.width() #050128
height = self.height()
# figure out which modules to reload. The ones of the classes...
print "finding modules we should reload, innermost first:"
class1 = self.__class__
bases = class1.__bases__ # base classes (tuple), not including class1 - this is not the superclass list!
# there is some method to get supers, but for now let's be quick and simple
classes = [class1]
while bases: # loop on class1 and bases; we've already included class1 in our list
from TreeView import TreeView
if class1 == TreeView:
break # beyond that we get things whose modules print as:
# constants (lots of times), sip, and __builtin__
super = bases[0] # ignore mixins, if any
classes.append(super)
class1 = super
bases = class1.__bases__
modulenames = map( lambda c: c.__module__, classes ) # __module__ is misnamed, it's only a module name
modules = map( lambda n: sys.modules[n], modulenames )
print "module names:", modulenames
print "reloading all these %d modules, outermost first" % len(modules)
modules.reverse()
modules = self.filter_reload_modules(modules) # let subclasses modify this list [050219/050327]
for mod in modules:
print "reloading",mod
reload(mod)
print "now remaking the model tree widget" #e should let subclass give us these details...
from modelTree.ModelTree import modelTree
# figure out where we are
splitter = self.parent() # QSplitter
sizes = splitter.sizes() # e.g. [207, 633]
# record the current scroll position so it can later be set to something similar
scrollpos = self.viewportToContents(0,0)
win = self.win
# imitate MWsemantics.py: Create the model tree widget
win.mt = win.modelTreeView = modelTree(splitter, win, size = (width,height))
x, y = scrollpos
win.mt.setContentsPos( x, y) # do this twice; this first time probably doesn't help
# at this point the new widget is probably to the right of the glpane! hmm...
splitter.moveToFirst(win.mt)
win.mt.show()
self.hide()
splitter.moveToLast(self)
# looking at splitter.sizes() at various times,
# they make no sense, but if the move ops work, then the kids are newmt, glpane, junk.
wantsizes = [width, sum(sizes) - width]
while len(wantsizes) < len(sizes):
wantsizes.append(0)
splitter.setSizes(sizes) ###e this will also help us extend what's stored by save/load window layout.
print "splitter-child sizes after setSizes",splitter.sizes()
splitter.updateGeometry()
splitter.update()
win.mt.setContentsPos( x, y) # do this 3 times ... doesn't help avoid a "flicker to no scrollbar state"
# but i bet setting the contents height initially would help! try it sometime. ###e
env.call_qApp_processEvents() #bruce 050908 replaced qApp.processEvents()
# might be needed before setContentPos in order to make it work
win.mt.setContentsPos( x, y) # do this 3 times - was not enough to do it before updateGeometry above
## win.mt.show()
## self.hide()
print "done reloading... I guess"
env.history.message( "reloaded model tree, init time %s" % win.mt._init_time)
return
def filter_reload_modules(self, modules):
"[subclasses can override this to change which modules we'll reload]"
return modules
def contextMenuEvent(self, event):
# What exactly was Bruce trying to do here? Some modified behavior of context menu...
# print dir(event)
# optflag = (event.buttons() & Qt.MidButton) or (event.modifiers() & Qt.AltModifier)
# optflag = optflag and 'Option' or None # (on Mac this is option key)
# (this only works with ctrl-left, not right -- Qt mac bug??)
cpos = event.pos() # this is in contents coords;
# y=1 is just under column label (which does not scroll with content)
vpos = cpos # vpos = self.contentsToViewport(cpos)
item = self.itemAt(vpos)
optflag = None
pos = event.globalPos()
modifier = Qt.NoModifier
self.menuReq(item, pos, modifier, optflag) # does all needed updates ###k even in glpane?
# TreeView.contextMenuEvent(self, event)
| NanoCAD-master | cad/src/outtakes/TreeWidget.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
MMKit.py
THIS FILE HAS BEEN DEPRECATED.
SEE NEW IMPLEMETATION IN --
Ui_BuildAtomsPropertyManager.py,
BuildAtomsPropertyManager.py,
Ui_PartLibPropertyManager.py,
PartLibPropertyManager.py,
Ui_PastePropertyManager.py
PastePropertyManager.py
$Id$
History:
Created by Huaicai.
Modified by several developers since then.
ninad 20070716: Code cleanup to make mmkit a propMgr object in deposit mode
instead of being inherited by that mode.
"""
import os, sys
from PyQt4 import QtGui
from PyQt4.Qt import Qt
from PyQt4.Qt import QDialog, SIGNAL, QIcon, QVBoxLayout, QStringList, QFileDialog
from PyQt4.Qt import QDir, QTreeView, QTreeWidgetItem, QAbstractItemDelegate, QWhatsThis
from MMKitDialog import Ui_MMKitDialog
from graphics.widgets.ThumbView import MMKitView, ChunkView
from model.elements import PeriodicTable
from utilities.constants import diTUBES
## from model.chem import Atom [not used i think - bruce 071113]
## from model.chunk import Chunk [not used i think - bruce 071113]
from foundation.Utility import imagename_to_icon, geticon
from model.assembly import Assembly
from files.mmp.files_mmp import readmmp
from model.part import Part
import foundation.env as env
from utilities import debug_flags
from utilities.debug import print_compact_traceback
from sponsors.Sponsors import SponsorableMixin
from PropertyManagerMixin import PropertyManagerMixin, pmSetPropMgrIcon, pmSetPropMgrTitle
from PM.PropMgr_Constants import pmMMKitPageMargin
from model.bond_constants import btype_from_v6
# PageId constants for mmkit_tab
AtomsPage = 0
ClipboardPage = 1
LibraryPage = 2
noblegases = ["He", "Ne", "Ar", "Kr"] # Mark 2007-05-31
# debugging flags -- do not commit with True
debug_mmkit_events = False
class MMKit(QDialog,
Ui_MMKitDialog,
PropertyManagerMixin,
SponsorableMixin):
"""
THIS CLASS HAS BEEN DEPRECATED.
SEE NEW IMPLEMETATION IN--
Ui_BuildAtomsPropertyManager.py,
BuildAtomsPropertyManager.py,
Ui_PartLibPropertyManager.py,
PartLibPropertyManager.py,
Ui_PastePropertyManager.py
PastePropertyManager.py
Provide the MMKit PM for Build Atoms mode.
"""
# <title> - the title that appears in the property manager header.
title = "Build Atoms"
# <iconPath> - full path to PNG file that appears in the header.
iconPath = "ui/actions/Tools/Build Structures/Build Atoms.png"
bond_id2name =['sp3', 'sp2', 'sp', 'sp2(graphitic)']
sponsor_keyword = 'Build'
def __init__(self, parentMode, win):
QDialog.__init__(self, win, Qt.Dialog)# Qt.WStyle_Customize | Qt.WStyle_Tool | Qt.WStyle_Title | Qt.WStyle_NoBorder)
self.w = win
self.o = self.w.glpane
#@NOTE: As of 20070717, MMKit supports only depositMode as its parent
#(and perhaps subclasses of depositMode ..but such a class that also
#uses MMKit is NIY so it is unconfirmed) -- ninad
self.parentMode = parentMode
self.setupUi(self)
# setupUi() did not add the icon or title. We do that here.
pmSetPropMgrIcon( self, self.iconPath )
pmSetPropMgrTitle( self, self.title )
#self.connect(self.hybrid_btngrp,SIGNAL("buttonClicked(int)"),self.set_hybrid_type)
self.pw = None # pw = partwindow
self.connect(self.mmkit_tab,
SIGNAL("currentChanged(int)"),
self.tabCurrentChanged)
self.connect(self.chunkListBox,
SIGNAL("currentItemChanged(QListWidgetItem*,QListWidgetItem*)"),
self.chunkChanged)
self.connect(self.browseButton,
SIGNAL("clicked(bool)"),
self.browseDirectories)
self.connect(self.defaultPartLibButton,
SIGNAL("clicked(bool)"),
self.useDefaultPartLibDirectory)
#self.connect(self.elementButtonGroup,SIGNAL("buttonClicked(int)"),self.setElementInfo)
self.connect(self.thumbView_groupBoxButton, SIGNAL("clicked()"),
self.toggle_thumbView_groupBox)
self.connect(self.bondTool_groupBoxButton , SIGNAL("clicked()"),
self.toggle_bondTool_groupBox)
self.connect(self.MMKitGrpBox_TitleButton, SIGNAL("clicked()"),
self.toggle_MMKit_groupBox)
self.connect(self.filterCB, SIGNAL("stateChanged(int)"),
self.toggle_selectionFilter_groupBox)
self.connect(self.advancedOptions_groupBoxButton, SIGNAL("clicked()"),
self.toggle_advancedOptions_groupBox)
# Make the elements act like a big exclusive radio button.
self.theElements = QtGui.QButtonGroup()
self.theElements.setExclusive(True)
self.theElements.addButton(self.toolButton1, 1)
self.theElements.addButton(self.toolButton2, 2)
self.theElements.addButton(self.toolButton6, 6)
self.theElements.addButton(self.toolButton7, 7)
self.theElements.addButton(self.toolButton8, 8)
self.theElements.addButton(self.toolButton10, 10)
self.theElements.addButton(self.toolButton9, 9)
self.theElements.addButton(self.toolButton13,13)
self.theElements.addButton(self.toolButton17,17)
self.theElements.addButton(self.toolButton5, 5)
self.theElements.addButton(self.toolButton10_2, 18)
self.theElements.addButton(self.toolButton15, 15)
self.theElements.addButton(self.toolButton16, 16)
self.theElements.addButton(self.toolButton14, 14)
self.theElements.addButton(self.toolButton33, 33)
self.theElements.addButton(self.toolButton34, 34)
self.theElements.addButton(self.toolButton35, 35)
self.theElements.addButton(self.toolButton32, 32)
self.theElements.addButton(self.toolButton36, 36)
self.connect(self.theElements, SIGNAL("buttonPressed(int)"), self.update_dialog)
self.theHybridizations = QtGui.QButtonGroup()
self.theHybridizations.setExclusive(True)
self.theHybridizations.addButton(self.sp3_btn, 0)
self.theHybridizations.addButton(self.sp2_btn, 1)
self.theHybridizations.addButton(self.sp_btn, 2)
self.theHybridizations.addButton(self.graphitic_btn, 3)
self.connect(self.theHybridizations, SIGNAL("buttonClicked(int)"), self.update_hybrid_btngrp)
self.connect(self.filterCB,
SIGNAL("toggled(bool)"),self.set_selection_filter)
self.elemTable = PeriodicTable
self.displayMode = diTUBES
self.elm = None
self.newModel = None ## used to save the selected lib part
self.flayout = None
# It looks like we now have correct fixes for bugs 1659 and bug 1824. If so, it would be safe to simply
# hardware self.icon_tabs to True and simplify code accordingly. But we're not 100% certain, so by leaving
# it as a debug pref, we can help any users who see those bugs come up again.
# wware 060420
#
# Update, bruce 070328: the False value of this debug_pref is known to fail in the Qt4 version (on Mac anyway),
# due to AttributeError exceptions for setMargin and setTabLabel,
# so I'm changing the prefs key for it in order to let Qt3 and Qt4 have independent debug_pref settings,
# adding a warning in the menu text, and adding a try/except to help in debugging this if anyone ever wants to.
# (If the bugs Will mentioned go away entirely, we can abandon support for the False value instead of fixing it,
# as Will suggested.)
from utilities.debug_prefs import debug_pref, Choice_boolean_True
self.icon_tabs = debug_pref("use icons in MMKit tabs? (only True works in Qt4)", Choice_boolean_True,
prefs_key = "A7/mmkit tab icons/Qt4")
#e Changes to this only take effect in the next session.
# Ideally we'd add a history message about that, when this is changed.
# (It's not yet easy to do that in a supported way in debug_pref.) [bruce 060313]
if not self.icon_tabs:
# This code is known to fail in Qt4 Mac version, as explained above. [bruce 061222 and 070328]
try:
self.mmkit_tab.setMargin ( 0 )
except:
print_compact_traceback("ignoring this Qt4-specific exception: ") #bruce 061222
pass
self.mmkit_tab.setTabLabel (self.atomsPage, 'Atoms')
self.mmkit_tab.setTabLabel (self.clipboardPage, 'Clipbd')
self.mmkit_tab.setTabLabel (self.libraryPage, 'Lib')
else:
# Add icons to MMKit's tabs. mark 060223.
atoms_ic = imagename_to_icon("actions/Properties Manager/MMKit.png")
self.mmkit_tab.setTabIcon(self.mmkit_tab.indexOf(self.atomsPage), QIcon(atoms_ic))
self.update_clipboard_page_icon() # Loads proper icon for clibpoard tab. Mark 2007-06-01
library_ic = imagename_to_icon("actions/Properties Manager/library.png")
self.mmkit_tab.setTabIcon(self.mmkit_tab.indexOf(self.libraryPage), QIcon(library_ic))
# Tab tooltips. mark 060326
self.mmkit_tab.setTabToolTip(self.mmkit_tab.indexOf(self.atomsPage), 'Atoms')
self.mmkit_tab.setTabToolTip(self.mmkit_tab.indexOf(self.clipboardPage), 'Clipboard')
self.mmkit_tab.setTabToolTip(self.mmkit_tab.indexOf(self.libraryPage), 'Part Library')
self._setNewView('MMKitView')
# Set current element in element button group.
self.theElements.button(self.w.Element).setChecked(True)
#self.connect(self., SIGNAL("), )
self.connect(self.w.hybridComboBox, SIGNAL("activated(int)"), self.hybridChangedOutside)
self.connect(self.w.hybridComboBox, SIGNAL("activated(const QString&)"), self.change2AtomsPage)
self.connect(self.w.elemChangeComboBox, SIGNAL("activated(const QString&)"), self.change2AtomsPage)
self.connect(self.w.pasteComboBox, SIGNAL("activated(const QString&)"), self.change2ClipboardPage)
#self.connect(self.w.depositAtomDashboard.pasteBtn, SIGNAL("pressed()"), self.change2ClipboardPage)
self.connect(self.w.depositAtomDashboard.pasteBtn, SIGNAL("stateChanged(int)"), self.pasteBtnStateChanged)
self.connect(self.w.depositAtomDashboard.depositBtn, SIGNAL("stateChanged(int)"), self.depositBtnStateChanged)
self.connect(self.dirView, SIGNAL("selectionChanged(QItemSelection *, QItemSelection *)"), self.partChanged)
self.add_whats_this_text()
return # from __init__
# ==
#bruce 060412 added everything related to __needs_update_xxx, to fix bugs 1726, 1629 and mitigate bug 1677;
# for more info see the comments where update_clipboard_items is called (in depositMode.py).
__needs_update_clipboard_items = False
# (there could be other flags like this for other kinds of updates we might need)
def show_propMgr(self):
"""
Show the Build Property Manager.
"""
#@NOTE: The build property manager files are still refered as MMKit and
#MMKitDialog. This will change in the near future. -- ninad 20070717
self.update_dialog(self.parentMode.w.Element)
self.parentMode.set_selection_filter(False) # disable selection filter
self.openPropertyManager(self)
#Following is an old comment, was originally in depositMode.init_gui:
#Do these before connecting signals or we'll get history msgs.
#Part of fix for bug 1620. mark 060322
self.highlightingCB.setChecked(self.parentMode.hover_highlighting_enabled)
self.waterCB.setChecked(self.parentMode.water_enabled)
def update_dialog(self, elemNum):
"""Called when the current element has been changed.
Update non user interactive controls display for current selected
element: element label info and element graphics info """
elm = self.elemTable.getElement(elemNum)
currentIndex = self.mmkit_tab.currentIndex()
atomPageIndex = self.mmkit_tab.indexOf(self.atomsPage)
##if elm == self.elm and self.currentPageOpen(AtomsPage): return
if elm == self.elm and (currentIndex == atomPageIndex) : return
## The following statements are redundant in some situations.
self.theElements.button(elemNum).setChecked(True)
self.w.Element = elemNum
self.color = self.elemTable.getElemColor(elemNum)
self.elm = self.elemTable.getElement(elemNum)
self.update_hybrid_btngrp()
self.elemGLPane.resetView()
self.elemGLPane.refreshDisplay(self.elm, self.displayMode)
#update the selection filter
self.update_selection_filter_list()
# Fix for bug 353, to allow the dialog to be updated with the correct page. For example,
# when the user selects Paste from the Edit toolbar/menu, the MMKit should show
# the Clipboard page and not the Atoms page. Mark 050808
if self.w.depositState == 'Clipboard':
self.change2ClipboardPage()
else:
self.change2AtomsPage()
self.tabCurrentChanged()
self.updateBuildAtomsMessage() # Mark 2007-06-01
def updateBuildAtomsMessage(self):
"""Updates the message box with an informative message based on the current page
and current selected atom type.
"""
msg = ""
if self.MMKit_groupBox.isVisible():
pageIndex = self.mmkit_tab.currentIndex()
page = None
if pageIndex is 0: # atomsPage
msg = "Double click in empty space to insert a single " + self.elm.name + " atom. "
if not self.elm.symbol in noblegases:
msg += "Click on an atom's <i>red bondpoint</i> to attach a " + self.elm.name + " atom to it."
elif pageIndex is 1: # clipboardPage
pastableItems = self.w.assy.shelf.get_pastable_chunks()
if pastableItems:
msg = "Double click in empty space to insert a copy of the selected clipboard item. \
Click on a <i>red bondpoint</i> to attach a copy of the selected clipboard item."
else:
msg = "There are no items on the clipboard."
elif pageIndex is 2: # libraryPage
msg = "Double click in empty space to insert a copy of the selected part in the library."
else: # Bonds Tool is selected (MMKit groupbox is hidden).
if self.parentMode.cutBondsAction.isChecked():
msg = "<b> Cut Bonds </b> tool is active. \
Click on bonds in order to delete them."
self.MessageGroupBox.insertHtmlMessage(msg)
return
if not hasattr(self, 'bondclick_v6'): # Mark 2007-06-01
return
if self.bondclick_v6:
name = btype_from_v6(self.bondclick_v6)
msg = "Click bonds or bondpoints to make them %s bonds." % name # name is 'single' etc
# Post message.
self.MessageGroupBox.insertHtmlMessage(msg)
#== Atom Selection Filter helper methods
def set_selection_filter(self, enabled):
"""Slot for Atom Selection Filter checkbox. Prints history message when selection filter is
enabled/disabled and updates the cursor.
"""
if enabled != self.w.selection_filter_enabled:
if enabled:
env.history.message("Atom Selection Filter enabled.")
else:
env.history.message("Atom Selection Filter disabled.")
self.w.selection_filter_enabled = enabled
#print "update_selection_filter_list(): self.w.filtered_elements=", self.w.filtered_elements
##self.update_selection_filter_list_widget()
self.update_selection_filter_list()
self.filterlistLE.setEnabled(enabled)
self.filterCB.setChecked(enabled)
self.o.graphicsMode.update_cursor()
def update_selection_filter_list(self):
"""Adds/removes the element selected in the MMKit to/from Atom Selection Filter
based on what modifier key is pressed (if any).
"""
eltnum = self.w.Element
if self.o.modkeys is None:
self.w.filtered_elements = []
self.w.filtered_elements.append(PeriodicTable.getElement(eltnum))
if self.o.modkeys == 'Shift':
if not PeriodicTable.getElement(eltnum) in self.w.filtered_elements[:]:
self.w.filtered_elements.append(PeriodicTable.getElement(eltnum))
elif self.o.modkeys == 'Control':
if PeriodicTable.getElement(eltnum) in self.w.filtered_elements[:]:
self.w.filtered_elements.remove(PeriodicTable.getElement(eltnum))
self.update_selection_filter_list_widget()
def update_selection_filter_list_widget(self):
"""Updates the list of elements displayed in the Atom Selection Filter List.
"""
filtered_syms=''
for e in self.w.filtered_elements[:]:
if filtered_syms: filtered_syms += ", "
filtered_syms += e.symbol
#self.w.depositAtomDashboard.filterlistLE.setText(filtered_syms)
self.filterlistLE.setText(filtered_syms)
def toggle_bondTool_groupBox(self):
self.toggle_groupbox(self.bondTool_groupBoxButton, self.bondToolWidget)
def toggle_thumbView_groupBox(self):
self.toggle_groupbox(self.thumbView_groupBoxButton, self.elementFrame)
def toggle_MMKit_groupBox(self):
self.toggle_groupbox(self.MMKitGrpBox_TitleButton, self.mmkit_tab, self.transmuteBtn, self.transmuteCB)
def toggle_selectionFilter_groupBox(self, state):
""" Toggles the groupbox item display depending on checked state of the selection filter checkbox """
#Current state is 'off' or(Qt.Unchecked)
if state is 0:
styleSheet = self.getGroupBoxCheckBoxStyleSheet(bool_expand = False)
self.filterCB.setStyleSheet(styleSheet)
palette = self.getGroupBoxCheckBoxPalette()
self.filterCB.setPalette(palette)
#hide the following widgets when checkbox is unchecked --
self.selectionFilter_label.hide()
self.filterlistLE.hide()
else:
styleSheet = self.getGroupBoxCheckBoxStyleSheet(bool_expand = True)
self.filterCB.setStyleSheet(styleSheet)
palette = self.getGroupBoxCheckBoxPalette()
self.filterCB.setPalette(palette)
#hide the following widgets when checkbox is unchecked --
self.selectionFilter_label.show()
self.filterlistLE.show()
def toggle_advancedOptions_groupBox(self):
self.toggle_groupbox(self.advancedOptions_groupBoxButton, self.autobondCB, self.waterCB, self.highlightingCB)
#bruce 070615 removed 'def toggle_groupbox', since our mixin superclass PropertyManagerMixin
# provides an identical-enough version.
def tabCurrentChanged(self):
pageIndex = self.mmkit_tab.currentIndex()
page = None
if pageIndex is 0: page = self.atomsPage
elif pageIndex is 1: page = self.clipboardPage
elif pageIndex is 2: page = self.libraryPage
self.setup_current_page(page)
def update_clipboard_items(self):
self.__needs_update_clipboard_items = True
self.update() # this makes sure self.event will get called; it might be better to test the flag only in self.repaint, not sure
return
def event(self, event): #bruce 060412 debug code, but also checks all self.__needs_update_xxx flags (an essential bugfix)
if debug_mmkit_events:
print "debug: MMKit.event got %r, type %r" % (event, event.type())
# Qt doc for QEvent lists 'enum type' codes; the subclass is also printed by %r
if self.__needs_update_clipboard_items:
self.__really_update_clipboard_items()
self.__needs_update_clipboard_items = False
res = QDialog.event(self, event)
if debug_mmkit_events:
if res is not None:
print "debug: MMKit.event returns %r" % (res,) # usually True, sometimes False
# if we return None we get TypeError: invalid result type from MMKit.event()
return res
# ==
def pasteBtnStateChanged(self, state):
"""Slot method. Called when the state of the Paste button of deposit dashboard has been changed. """
if state == QButton.On:
self.change2ClipboardPage()
def depositBtnStateChanged(self, state):
"""Slot method. Called when the state of the Deposit button of deposit dashboard has been changed. """
if state == QButton.On:
self.change2AtomsPage()
def hybridChangedOutside(self, newId):
"""Slot method. Called when user changes element hybridization from the dashboard.
This method achieves the same effect as user clicked one of the hybridization buttons."""
self.theElements.button(newId).setChecked(True)
self.set_hybrid_type(newId)
self.w.Element = newId
## fix bug 868
self.w.depositAtomDashboard.depositBtn.setChecked(True)
def change2AtomsPage(self):
"""Slot method called when user changes element/hybrid combobox or
presses Deposit button from Build mode dashboard.
"""
if self.mmkit_tab.currentIndex() != AtomsPage:
self.mmkit_tab.setCurrentIndex(AtomsPage) # Generates signal
def change2ClipboardPage(self):
"""Slot method called when user changes pastable item combobox or
presses the Paste button from the Build mode dashboard. """
if self.mmkit_tab.currentIndex() != ClipboardPage:
self.mmkit_tab.setCurrentIndex(ClipboardPage) # Generates signal??
def setElementInfo(self,value):
"""Slot method called when an element button is pressed in the element ButtonGroup.
"""
self.w.setElement(value)
def update_hybrid_btngrp(self, buttonIndex = 0):
"""Update the buttons of the current element\'s hybridization types into hybrid_btngrp;
select the specified one if provided"""
elem = PeriodicTable.getElement(self.w.Element) # self.w.Element is atomic number
atypes = elem.atomtypes
if elem.name == 'Carbon':
self.setup_C_hybrid_buttons()
elif elem.name == 'Nitrogen':
self.setup_N_hybrid_buttons()
elif elem.name == 'Oxygen':
self.setup_O_hybrid_buttons()
elif elem.name == 'Sulfur':
self.setup_S_hybrid_buttons()
else:
self.hide_hybrid_btngrp()
self.elemGLPane.changeHybridType(None)
return
#if len(atypes) > 1:
# Prequisite: w.hybridComboBox has been updated at this moment.
b_name = self.bond_id2name[buttonIndex]
self.elemGLPane.changeHybridType(b_name)
self.elemGLPane.refreshDisplay(self.elm, self.displayMode)
self.theHybridizations.button(buttonIndex).setChecked(True)
self.set_hybrid_type(buttonIndex)
# Added Atomic Hybrids label. Mark 2007-05-30
self.atomic_hybrids_label.setText("Atomic Hybrids for " + elem.name + " :")
self.show_hybrid_btngrp()
def show_hybrid_btngrp(self): # Mark 2007-06-20
"""Show the hybrid button group and label above it.
This is a companion method to hide_hybrid_btngrp().
It includes workarounds for Qt layout issues that crop up
when hiding/showing the hybrid button groupbox using Qt's
hide() and show() methods. See bug 2407 for more information.
"""
if 1:
self.hybrid_btngrp.show()
else:
self.hybrid_btngrp.show()
self.atomic_hybrids_label.show()
def hide_hybrid_btngrp(self): # Mark 2007-06-20
"""Hide the hybrid button group and label above it.
This is a companion method to show_hybrid_btngrp().
It includes workarounds for Qt layout issues that crop up
when hiding/showing the hybrid button groupbox using Qt's
hide() and show() methods. See bug 2407 for more information.
"""
if 1:
# This way of hiding confuses the layout manager, so I had
# do create special spacers and set sizepolicies just to make
# this work.
self.hybrid_btngrp.hide()
# I had to do this instead of use hide() since hide()
# confuses the layout manager in special situations, like
# that described in bug 2407. Mark 2007-06-20
self.atomic_hybrids_label.setText(" ")
else:
# Alternate way of hiding. Hide all contents and the QButtonGroupbox
# border, but there is no way to hide the border.
self.sp3_btn.hide()
self.sp2_btn.hide()
self.sp_btn.hide()
self.graphitic_btn.hide()
self.atomic_hybrids_label.hide()
def setup_C_hybrid_buttons(self):
"""Displays the Carbon hybrid buttons.
"""
self.theElements.button(self.w.Element).setChecked(True)
self.sp3_btn.setIcon(imagename_to_icon('modeltree/C_sp3.png'))
self.sp3_btn.show()
self.sp2_btn.setIcon(imagename_to_icon('modeltree/C_sp2.png'))
self.sp2_btn.show()
self.sp_btn.setIcon(imagename_to_icon('modeltree/C_sp.png'))
self.sp_btn.show()
self.graphitic_btn.hide()
def setup_N_hybrid_buttons(self):
"""Displays the Nitrogen hybrid buttons.
"""
self.sp3_btn.setIcon(imagename_to_icon('modeltree/N_sp3.png'))
self.sp3_btn.show()
self.sp2_btn.setIcon(imagename_to_icon('modeltree/N_sp2.png'))
self.sp2_btn.show()
self.sp_btn.setIcon(imagename_to_icon('modeltree/N_sp.png'))
self.sp_btn.show()
self.graphitic_btn.setIcon(imagename_to_icon('modeltree/N_graphitic.png'))
self.graphitic_btn.show()
def setup_O_hybrid_buttons(self):
"""Displays the Oxygen hybrid buttons.
"""
self.sp3_btn.setIcon(imagename_to_icon('modeltree/O_sp3.png'))
self.sp3_btn.show()
self.sp2_btn.setIcon(imagename_to_icon('modeltree/O_sp2.png'))
self.sp2_btn.show()
self.sp_btn.hide()
self.graphitic_btn.hide()
def setup_S_hybrid_buttons(self):
"""Displays the Sulfur hybrid buttons.
"""
self.sp3_btn.setIcon(imagename_to_icon('modeltree/O_sp3.png')) # S and O are the same.
self.sp3_btn.show()
self.sp2_btn.setIcon(imagename_to_icon('modeltree/O_sp2.png'))
self.sp2_btn.show()
self.sp_btn.hide()
self.graphitic_btn.hide()
def set_hybrid_type(self, type_id):
"""Slot method. Called when any of the hybrid type buttons was clicked. """
self.w.hybridComboBox.setCurrentIndex( type_id )
b_name = self.bond_id2name[type_id]
#This condition fixs bug 866, also saves time since no need to draw without MMKIt shown
if self.isVisible():
self.elemGLPane.changeHybridType(b_name)
self.elemGLPane.refreshDisplay(self.elm, self.displayMode)
def setup_current_page(self, page):
"""Slot method that is called whenever a user clicks on the
'Atoms', 'Clipboard' or 'Library' tab to change to that page.
"""
#print "setup_current_page: page=", page
if page == self.atomsPage: # Atoms page
self.w.depositState = 'Atoms'
self.w.update_depositState_buttons()
self.elemGLPane.resetView()
self.elemGLPane.refreshDisplay(self.elm, self.displayMode)
self.browseButton.hide()
self.defaultPartLibButton.hide()
self.atomsPageSpacer.changeSize(0,5,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Minimum)
elif page == self.clipboardPage: # Clipboard page
self.w.depositState = 'Clipboard'
self.w.update_depositState_buttons()
self.elemGLPane.setDisplay(self.displayMode)
self._clipboardPageView()
self.browseButton.hide()
self.defaultPartLibButton.hide()
self.atomsPageSpacer.changeSize(0,5,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Minimum)
elif page == self.libraryPage: # Library page
if self.rootDir:
self.elemGLPane.setDisplay(self.displayMode)
self._libPageView()
self.browseButton.show()
self.defaultPartLibButton.show()
self.atomsPageSpacer.changeSize(0,5,
QtGui.QSizePolicy.Minimum,
QtGui.QSizePolicy.Minimum)
#Turn off both paste and deposit buttons, so when in library page and user choose 'set hotspot and copy'
#it will change to paste page, also, when no chunk selected, a history message shows instead of depositing an atom.
self.w.depositState = 'Library'
self.w.update_depositState_buttons()
else:
print 'Error: MMKit page unknown: ', page
self.elemGLPane.setFocus()
self.updateBuildAtomsMessage()
def chunkChanged(self, item, previous):
"""Slot method. Called when user changed the selected chunk. """
itemId = self.chunkListBox.row(item)
if itemId != -1:
newChunk = self.pastableItems[itemId]
#self.w.pasteComboBox.setCurrentIndex(itemId)
#buildModeObj = self.w.commandSequencer._commandTable['DEPOSIT']
#assert buildModeObj
#buildModeObj.setPaste()
##Compared to the above way, I think this way is better. Modules are more uncoupled.
self.w.pasteComboBox.setCurrentIndex(itemId) # Fixes bug 1754. mark 060325
self.elemGLPane.updateModel(newChunk)
def __really_update_clipboard_items(self): #bruce 060412 renamed this from update_clipboard_items to __really_update_clipboard_items
"""Updates the items in the clipboard\'s listview, if the clipboard is currently shown. """
if self.currentPageOpen(ClipboardPage): #bruce 060313 added this condition to fix bugs 1631, 1669, and MMKit part of 1627
self._clipboardPageView() # includes self.update_clipboard_page_icon()
else:
self.update_clipboard_page_icon() # do this part of it, even if page not shown
return
def partChanged(self, item):
"""Slot method, called when user changed the partlib brower tree"""
if isinstance(item, self.FileItem):
self._libPageView(True)
else:
self.newModel = None
self.elemGLPane.updateModel(self.newModel)
def getPastablePart(self):
"""Public method. Retrieve pastable part and hotspot if current tab page is in libary, otherwise, return None. """
if self.currentPageOpen(LibraryPage):
return self.newModel, self.elemGLPane.hotspotAtom
return None, None
def currentPageOpen(self, page_id):
"""Returns True if <page_id> is the current page open in the tab widget, where:
0 = Atoms page
1 = Clipboard page
2 = Library page
"""
pageIndex = self.mmkit_tab.currentIndex()
if page_id == pageIndex:
return True
else:
return False
def _libPageView(self, isFile = False):
item = self.dirView.selectedItem()
if not isFile and not isinstance(item, self.FileItem):
self.newModel = None
self.elemGLPane.updateModel(self.newModel)
return
mmpfile = str(item.getFileObj())
if os.path.isfile(mmpfile):
#self.newModel = Assembly(self.w, "Assembly 1")
self.newModel = Assembly(self.w, os.path.normpath(mmpfile)) #ninad060924 to fix bug 1164
self.newModel.o = self.elemGLPane ## Make it looks "Assembly" used by glpane.
readmmp(self.newModel, mmpfile)
# What we did in Qt 3:
## #self.newModel = Assembly(self.w, "Assembly 1")
## self.newModel = Assembly(self.w, os.path.normpath(mmpfile)) #ninad060924 to fix bug 1164
## self.newModel.o = self.elemGLPane ## Make it looks "Assembly" used by glpane.
## readmmp(self.newModel, mmpfile)
## # The following is absolute nonsense, and is part of what's breaking the fix of bug 2028,
## # so it needs to be revised, to give this assy a standard structure.
## # We'll have to find some other way to draw the hotspot singlet
## # (e.g. a reasonable, straightforward way). So we did -- MMKitView.always_draw_hotspot is True.
## # [bruce 060627]
## ## # Move all stuff under assembly.tree into assy.shelf. This is needed to draw hotspot singlet
## ## def addChild(child):
## ## self.newModel.shelf.addchild(child)
## ##
## ## # Remove existing clipboard items from the libary part before adopting childern from 'tree'.
## ## self.newModel.shelf.members = []
## ## self.newModel.tree.apply2all(addChild)
## ##
## ## self.newModel.shelf.prior_part = None
## ## self.newModel.part = Part(self.newModel, self.newModel.shelf)
## if 1: #bruce 060627
self.newModel.update_parts() #k not sure if needed after readmmp)
self.newModel.checkparts()
if self.newModel.shelf.members:
if debug_flags.atom_debug:
print "debug warning: library part %r contains clipboard items" % mmpfile
# we'll see if this is common
# happens for e.g. nanokids/nanoKid-C39H42O2.mmp
for m in self.newModel.shelf.members[:]:
m.kill() #k guess about a correct way to handle them
self.newModel.update_parts() #k probably not needed
self.newModel.checkparts() #k probably not needed
else:
self.newModel = None
self.elemGLPane.updateModel(self.newModel)
def _clipboardPageView(self):
"""Updates the clipboard page. """
if not self.currentPageOpen(ClipboardPage):
# (old code permitted this to be false below in 'if len(list):',
# but failed to check for it in the 'else' clause,
# thus causing bug 1627 [I think], now fixed in our caller)
print "bug: _clipboardPageView called when not self.currentPageOpen(ClipboardPage)" #bruce 060313
return
self.pastableItems = self.w.assy.shelf.get_pastable_chunks()
self.chunkListBox.clear()
for item in self.pastableItems:
self.chunkListBox.addItem(item.name)
newModel = None
if len(self.pastableItems):
i = self.w.pasteComboBox.currentIndex()
if i < 0:
i = self.w.pasteComboBox.count() - 1
# Make sure the clipboard page is open before calling selSelected(), because
# setSelected() causes the clipboard page to be displayed when we don't want it to
# be displayed (i.e. pressing Control+C to copy something to the clipboard).
self.chunkListBox.setCurrentItem(self.chunkListBox.item(i))
# bruce 060313 question: why don't we now have to pass the selected chunk to
# self.elemGLPane.updateModel? ###@@@
newModel = self.pastableItems[i]
self.elemGLPane.updateModel(newModel)
self.update_clipboard_page_icon()
def update_clipboard_page_icon(self):
"""Updates the Clipboard page (tab) icon with a full or empty clipboard icon
based on whether there is anything on the clipboard (pasteables).
"""
if not self.icon_tabs:
# Work around for bug 1659. mark 060310 [revised by bruce 060313]
return
if self.w.assy.shelf.get_pastable_chunks():
clipboard_ic = imagename_to_icon("actions/Properties Manager/clipboard-full.png")
else:
clipboard_ic = imagename_to_icon("actions/Properties Manager/clipboard-empty.png")
self.mmkit_tab.setTabIcon(self.mmkit_tab.indexOf(self.clipboardPage), QIcon(clipboard_ic))
class DirView(QTreeView):
def __init__(self, mmkit, parent):
QTreeView.__init__(self, parent)
self.setEnabled(True)
self.model = QtGui.QDirModel(['*.mmp', '*.MMP'], # name filters
QDir.AllEntries|QDir.AllDirs|QDir.NoDotAndDotDot, # filters
QDir.Name # sort order
)
# explanation of filters (from Qt 4.2 doc for QDirModel):
# - QDir.AllEntries = list files, dirs, drives, symlinks.
# - QDir.AllDirs = include dirs regardless of other filters [guess: needed to ignore the name filters for dirs]
# - QDir.NoDotAndDotDot = don't include '.' and '..' dirs
#
# about dirnames of "CVS":
# The docs don't mention any way to filter the dirnames using a callback,
# or any choices besides "filter them same as filenames" or "don't filter them".
# So there is no documented way to filter out the "CVS" subdirectories like we did in Qt3
# (short of subclassing this and overriding some methods,
# but the docs don't make it obvious how to do that correctly).
# Fortunately, autoBuild.py removes them from the partlib copy in built releases.
#
# Other QDirModel methods we might want to use:
# QDirModel.refresh, to update its state from the filesystem (but see the docs --
# they imply we might have to pass the model's root pathname to that method,
# even if it hasn't changed, but they're not entirely clear on that).
#
# [bruce 070502 comments]
self.path = None
self.mmkit = mmkit
self.setModel(self.model)
self.setWindowTitle(self.tr("Dir View"))
self.setItemsExpandable(True)
self.setAlternatingRowColors(True)
self.setColumnWidth(0, 200)
for i in range(2,4):
self.setColumnWidth(i, 4)
self.show()
#Ninad 070326 reimplementing mouseReleaseEvent and resizeEvent
#for DirView Class (which is a subclass of QTreeView)
#The old code reimplemented 'event' class which handles *all* events.
#There was a bad bug which didn't send an event when the widget is resized
# and then the seletcion is changed. In NE1Qt3 this wasn't a problem because
#it only had one column. Now that we have multiple columns
#(which are needed to show the horizontal scrollbar.
# While using Library page only resize event or mouse release events
#by the user should update the thumbview.
#The Qt documentation also suggests reimplementing subevents instead of the main
#event handler method (event())
def mouseReleaseEvent(self, evt):
""" Reimplementation of mouseReleaseEvent method of QTreeView"""
if self.selectedItem() is not None:
self.mmkit._libPageView()
return QTreeView.mouseReleaseEvent(self, evt)
def resizeEvent(self, evt):
""" Reimplementation of resizeEvent method of QTreeView"""
if self.selectedItem() is not None:
self.mmkit._libPageView()
return QTreeView.resizeEvent(self, evt)
#Following method (event() ) is not reimplemented anymore. Instead, the subevent handlers are
#reimplemented (see above) -- ninad 070326
"""
def event(self, evt):
if evt.type() == evt.Timer:
# This is the event we get when the library selection changes, so if there has
# been a library selection, update the library page's GLPane. But this can also
# happen without a selection; in that case don't erase the atom page's display.
if self.selectedItem() is not None:
self.mmkit._libPageView()
return QTreeView.event(self, evt)"""
def setRootPath(self, path):
self.path = path
self.setRootIndex(self.model.index(path))
def selectedItem(self):
indexes = self.selectedIndexes()
if not indexes:
return None
index = indexes[0]
if not index.isValid():
return None
return self.FileItem(str(self.model.filePath(index)))
class FileItem:
def __init__(self, path):
self.path = path
dummy, self.filename = os.path.split(path)
def name(self):
return self.filename
def getFileObj(self):
return self.path
DirView.FileItem = FileItem
def _setNewView(self, viewClassName):
# Put the GL widget inside the frame
if not self.flayout:
self.flayout = QVBoxLayout(self.elementFrame)
self.flayout.setMargin(1)
self.flayout.setSpacing(1)
else:
if self.elemGLPane:
self.flayout.removeChild(self.elemGLPane)
self.elemGLPane = None
if viewClassName == 'ChunkView':
# We never come here! How odd.
self.elemGLPane = ChunkView(self.elementFrame, "chunk glPane", self.w.glpane)
elif viewClassName == 'MMKitView':
self.elemGLPane = MMKitView(self.elementFrame, "MMKitView glPane", self.w.glpane)
self.flayout.addWidget(self.elemGLPane,1)
#ninad 070326. Note that self.DirView inherits QTreeView.
#It has got nothing to do with the experimental class DirView in file Dirview.py
self.dirView = self.DirView(self, self.libraryPage)
self.dirView.setSortingEnabled(False) #bruce 070521 changed True to False -- fixes "reverse order" bug on my Mac
##self.dirView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
libraryPageLayout = QVBoxLayout(self.libraryPage)
libraryPageLayout.setMargin(pmMMKitPageMargin) # Was 4. Mark 2007-05-30
libraryPageLayout.setSpacing(2)
libraryPageLayout.addWidget(self.dirView)
filePath = os.path.dirname(os.path.abspath(sys.argv[0]))
libDir = os.path.normpath(filePath + '/../partlib')
self.libPathKey = '/nanorex/nE-1/libraryPath'
libDir = env.prefs.get(self.libPathKey, libDir)
if os.path.isdir(libDir):
self.rootDir = libDir
self.dirView.setRootPath(libDir)
else:
self.rootDir = None
from history.HistoryWidget import redmsg
env.history.message(redmsg("The part library directory: %s doesn't exist." %libDir))
def browseDirectories(self):
"""Slot method for the browse button of library page. """
# Determine what directory to open.
if self.w.assy.filename:
odir = os.path.dirname(self.w.assy.filename)
else:
from utilities.prefs_constants import workingDirectory_prefs_key
odir = env.prefs[workingDirectory_prefs_key]
fdir = QFileDialog.getExistingDirectory(self, "Choose library directory", odir)
libDir = str(fdir)
if libDir and os.path.isdir(libDir):
env.prefs[self.libPathKey] = libDir
self.dirView.setRootPath(libDir)
#Refresh GL-thumbView display
self.newModel = None
self.elemGLPane.updateModel(self.newModel)
def useDefaultPartLibDirectory(self):
""" Slot method that to reset the part lib directory path to default"""
from history.HistoryWidget import redmsg
#ninad070503 : A future enhancement would be a preference to have
# a user defined 'default dir path' for the
#part lib location.
# set libDir to the standard partlib path
filePath = os.path.dirname(os.path.abspath(sys.argv[0]))
libDir = os.path.normpath(filePath + '/../partlib')
if libDir and os.path.isdir(libDir):
if self.dirView.path == libDir:
msg1 = "Current directory path for the partlib is the default path."
msg2 = " Current path not changed"
env.history.message(redmsg(msg1 + msg2))
return
env.prefs[self.libPathKey] = libDir
self.dirView.setRootPath(libDir)
#Refresh GL-thumbView display
self.newModel = None
self.elemGLPane.updateModel(self.newModel)
else:
msg1 = "The default patlib directory %s doesn't exist."%libDir
msg2 = "Current path not changed"
env.history.message(redmsg(msg1 + msg2))
def closeEvent(self, e):
"""This event handler receives all MMKit close events. In other words,
when this dialog's close() slot gets called, this gets called with event 'e'.
"""
self.hide()
# If the 'Library' page is open, change it to 'Atoms'. Mark 051212.
if self.currentPageOpen(LibraryPage):
self.setup_current_page(self.atomsPage)
#bruce 070615 commented out the following since I think it's obsolete:
# (evidence: no other mentions of 'polish' or 'move_to_best_location' in our code,
# and MMKit is no longer a movable dialog)
## num_polish = 0
##
## def polish(self):
## """This slot is called after a widget has been fully created and before it is shown the very first time.
## Polishing is useful for final initialization which depends on having an instantiated widget.
## This is something a constructor cannot guarantee since the initialization of the subclasses might not be finished.
## After this function, the widget has a proper font and palette and QApplication.polish() has been called.
## Remember to call QDialog's implementation when reimplementing this function.
## """
## QDialog.polish(self) # call QDialog's polish() implementation
## self.num_polish += 1
## #&print "num_polish =", self.num_polish
## if self.num_polish < 2:
## # polish() is called twice; not sure why.
## # Call move_to_best_location() only after the second polish signal since
## # get_location() can only get self.frameGeometry() after that.
## return
## self.move_to_best_location(True)
def show(self):
"""MMKit\'s show slot.
"""
#QDialog.show(self)
#&print "MMKit.move: setting mainwindow to active window"
#Show it in Property Manager Tab ninad061207
if not self.pw or self:
self.pw = self.w.activePartWindow() #@@@ ninad061206
self.pw.updatePropertyManagerTab(self)
self.setSponsor()
else:
if not self.pw:
self.pw = self.w.activePartWindow()
self.pw.updatePropertyManagerTab(self)
self.w.activateWindow() # Fixes bug 1503. mark 060216.
# Required to give the keyboard input focus back to self (MainWindow).
def add_whats_this_text(self):
"""What's This text for some of the widgets in the Build > Atoms Property Manager.
Many are still missing.
"""
self.elementFrame.setWhatsThis("""<b>Preview Window</b>
<p>This displays the active object. It can be inserted by double
clicking in the 3D graphics area.</p>
<p>Left click on a red bondpoint to make it a green <i>hotspot</i>
(clipboard and library parts only). The hotspot indicates which
bondpoint should be used to bond the current object when selecting
a bondpoint in the model.</p>
<p><u>Mouse Commands Supported</u><br>
Left - Select hotspot (clipboard and library parts only)<br>
Middle - Rotate view<br> \
Wheel - Zoom in/out \
</p>""")
self.MMKit_groupBox.setWhatsThis("""<b>Molecular Modeling Kit</b>
<p>A tabular widget for selecting atom types or other structures to insert
into the model.</p>
<p><b>Atoms Tab</b> - A select group of atom types options from the periodic
table of elements.</p>
<p><b>Clipboard Tab</b> - the list of objects copied on the clipboard (using
the Copy command).</p>
<p><b>Library Tab</b> - Accesses the NE1 Part Library. There are hundreds of
structures to choose from.</p>""")
self.transmuteBtn.setWhatsThis("""<b>Transmute Atoms</b>
<p>When clicked, transmutes selected atoms to the current type displayed
in the Preview window.</p>""")
self.transmuteCB.setWhatsThis("""<b>Force to keep bonds</b>
<p>When checked, all bonds remain in place when atoms are transmuted,
even if this will result in unrealistic (chemical) bonds.</p>""")
self.selectionFilter_groupBox.setWhatsThis("""<b>Atoms Selection Filter</b>
<p>When activated, only atoms listed can be selected.</p>""")
self.advancedOptions_groupBox.setWhatsThis("""<b>Advanced Options</b>
<p><b>Autobond</b> - when checked, the atom being inserted or attached to another
atom will autobond to other bondpoints of other candidate atoms automatically.</p>
<p><b>Highlighting</b> - Turns on/off hover highlighting.</p>
<p><b>Water</b>- Adds a tranparent plane normal to the screen through 0,0,0. Anything
behind the water plane can not be selected.</p>""")
self.transmuteAtomsAction.setWhatsThis("""<b>Transmute Atoms</b>
<p>When clicked, transmutes selected atoms to the current type displayed
in the Preview window.</p>""")
pass # end of class MMKit
# end
| NanoCAD-master | cad/src/outtakes/MMKit.py |
"""
$Id$
"""
# debug/test functions (in other submenu of debug menu) which won't be kept around.
# [moved out of undo.py by bruce 071004]
# not all of these are needed, perhaps:
from cPickle import dump, load, HIGHEST_PROTOCOL
import foundation.env as env
from utilities.debug import register_debug_menu_command, register_debug_menu_command_maker
###@@@ don't put all those commands in there -- use a submenu, use atom-debug,
# or let them only show up if a related flag is set, or so...
from PyQt4.Qt import SIGNAL, QObject, QWidget #k ok to do these imports at toplevel? I hope so, since we need them in several places.
from utilities.constants import genKey, noop
from utilities import debug_flags # for atom_debug [bruce 060128, suggested by Mark;
# if this works, we should simplify some defs which worry if it's too early for this]
from utilities.debug import call_func_with_timing_histmsg
def atpos_list(part):
"Return a list of atom-position arrays, one per chunk in part. Warning: might include shared mutable arrays."
res = []
for m in part.molecules:
res.append( m.atpos)
return res
def save_atpos_list(part, filename):
save_obj( atpos_list(part), filename)
def save_obj( thing, filename):
file = open(filename, "wb")
dump( thing, file, HIGHEST_PROTOCOL) # protocols: 0 ascii, 1 binary, 2 (new in 2.3) better for new style classes
file.close()
def load_obj(filename):
file = open(filename, "rb")
res = load(file)
file.close()
return res
def saveposns(part, filename):
env.history.message( "save main part atom posns to file: " + filename )
def doit():
save_atpos_list(part, filename)
call_func_with_timing_histmsg( doit)
def saveposns_cmd( target): # arg is the widget that has this debug menu
win = target.topLevelWidget()
assy = win.assy
part = assy.tree.part
filename = assy.filename + "X"
saveposns(part, filename)
return
## register_debug_menu_command("save atom posns", saveposns_cmd) # put this command into debug menu
# ==
def loadposns( part, filename): # doesn't move atoms (just a file-reading speed test, for now)
env.history.message( "load atom posns from file (discards them, doesn't move atoms): " + filename )
def doit():
return load_obj(filename)
posns = call_func_with_timing_histmsg( doit)
return
def loadposns_cmd( target):
win = target.topLevelWidget()
assy = win.assy
part = assy.tree.part
filename = assy.filename + "X"
loadposns(part, filename)
return
## register_debug_menu_command("load atom posns", loadposns_cmd)
# ==
from Numeric import concatenate, array, UnsignedInt8
def atom_array_of_part(part):
"Return an Array of all atoms in the Part. Try to be linear time."
res = []
for m in part.molecules:
res.append( array(m.atlist) )
# concatenate might fail for chunks with exactly 1 atom -- fix later ####@@@@
return concatenate(res) ###k
def saveelts( part, filename):
env.history.message( "save main part element symbols -- no, atomic numbers -- to file: " + filename )
def doit():
atoms = atom_array_of_part(part)
## elts = [atm.element.symbol for atm in atoms]
elts = [atm.element.eltnum for atm in atoms]
env.history.message( "%d element nums, first few are %r" % (len(elts), elts[:5] ) )
thing = array(elts)
save_obj(thing, filename)
call_func_with_timing_histmsg( doit)
return
def saveelts_cmd( target):
win = target.topLevelWidget()
assy = win.assy
part = assy.tree.part
filename = assy.filename + "E" # E, not X
saveelts(part, filename)
return
## register_debug_menu_command("save atom element numbers", saveelts_cmd)
# ==
def savebtypes( part, filename):
env.history.message( "save main part bond type v6 ints to file: " + filename )
def doit():
atoms = atom_array_of_part(part)
res = []
for atm in atoms:
for b in atm.bonds:
# don't worry for now about hitting each bond twice... well, do, and see if this makes it slower, as i guess.
if b.atom1 is atm:
res.append(b.v6) # a small int
env.history.message( "%d btype ints, first few are %r" % (len(res), res[:5] ) )
thing = array(res, UnsignedInt8) # tell it to use a smaller type; see numpy.pdf page 14 on typecodes.
# update, bruce 070612: we still use Numeric Python (not numarray or numpy). I am not sure what URL
# is referred to by "numpy.pdf" above, but it is probably (and should be) about Numeric Python.
save_obj(thing, filename)
call_func_with_timing_histmsg( doit)
return
def savebtypes_cmd( target):
win = target.topLevelWidget()
assy = win.assy
part = assy.tree.part
filename = assy.filename + "B" # B, not E or X
savebtypes(part, filename)
return
## register_debug_menu_command("save bond type v6 ints", savebtypes_cmd)
# ==
# moved to pyrex_test.py
### this depends on undotest.pyx having been compiled by Pyrex ####@@@@
##
##def count_bonds_cmd( target):
## win = target.topLevelWidget()
## assy = win.assy
## part = assy.tree.part
## mols = part.molecules
## env.history.message( "count bonds (twice each) in %d mols:" % len(mols) )
## from undotest import nbonds # count bonds (twice each) in a sequence of molecules
## def doit():
## return nbonds(mols)
## nb = call_func_with_timing_histmsg( doit)
## env.history.message("count was %d, half that is %d" % (nb, nb/2) )
## return
##
##register_debug_menu_command("count bonds", count_bonds_cmd)
# ==
def blerg_try1(mols):
dict1 = {}
for m in mols:
atlist = m.atlist
atpos = m.atpos
keys = map( lambda a: a.key, atlist )
# now efficiently loop over both those lists. I think there's a better way in python
# (and surely it should be done in pyrex or Numeric anyway), but try easy way first:
for key, pos in zip(keys, atpos):
dict1[key] = pos
# now dict1 maps key->pos for every atom in the system
return len(dict1), 0 # untested retval
def update_keyposdict_keyv6dict_from_mol( dict1, dictb, m):
atlist = m.atlist
atpos = m.atpos
## keys = map( lambda a: a.key, atlist )
# now efficiently loop over both those lists. I think there's a better way in python
# (and surely it should be done in pyrex or Numeric anyway), but try easy way first:
for atm, pos in zip(atlist, atpos):
## dict1[id(atm)] = pos
dict1[atm.key] = pos
for b in atm.bonds:
# use id(b) -- not ideal but good enough test for now
# (before 080229 this code used b.bond_key, which was usually but not entirely unique,
# and now has frequent collisions; note, it was already in outtakes on that date)
dictb[id(b)] = b.v6 # this runs twice per bond
return
def diff_keyposdict_from_mol( dict1, dict2, m):
"""Like update_keyposdict_from_mol, but use dict1 as old state, and store in dict2 just the items that differ.
Deleted atoms must be handled separately -- this won't help find them even when run on all mols.
[Could change that by having this delete what it found from dict1, at further substantial speed cost -- not worth it.]
"""
atlist = m.atlist
atpos = m.atpos
for atm, pos in zip(atlist, atpos):
key = atm.key
if pos != dict1.get(key): # Numeric compare -- might be slow, we'll see
dict2[key] = pos
return
def blerg(mols):
dict1 = {}
dict2 = {}
dictb = {}
for m in mols:
update_keyposdict_keyv6dict_from_mol( dict1, dictb, m)
diff_keyposdict_from_mol( dict1, dict2, m)
# now dict1 maps key->pos for every atom in the system
# and dictb has all v6's of all bonds (mapping from id(bond))
return len(dict1), len(dictb)
def blerg_cmd( target):
win = target.topLevelWidget()
assy = win.assy
part = assy.tree.part
mols = part.molecules
env.history.message( "blorg in %d mols:" % len(mols) )
def doit():
return blerg(mols)
na, nb = call_func_with_timing_histmsg( doit)
env.history.message("count was %d, %d" % (na,nb,) )
return
## register_debug_menu_command("make key->pos dict", blerg_cmd)
| NanoCAD-master | cad/src/outtakes/undo_related_timing_tests.py |
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
PeptideGroup.py - ...
@author: Bruce, Mark
@version: $Id$
@copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
from foundation.Group import Group
from utilities.constants import gensym
from utilities.icon_utilities import imagename_to_pixmap
from utilities import debug_flags
from utilities.debug import print_compact_stack
class PeptideGroup(Group):
"""
Model object which packages together some Dna Segments, Dna Strands,
and other objects needed to represent all their PAM atoms and markers.
Specific kinds of Group member contents include:
- PeptideSegments (optionally inside Groups)
- Groups (someday might be called Blocks when they occur in this context;
note that class Block is deprecated and should not be used for these)
- DnaMarkers (a kind of Jig, always inside an owning PeptideSegment)
As other attributes:
- whatever other properties the user needs to assign, which are not
covered by the member nodes or superclass attributes. [nim?]
"""
# This should be a tuple of classifications that appear in
# files_mmp._GROUP_CLASSIFICATIONS, most general first.
# See comment in class Group for more info. [bruce 080115]
_mmp_group_classifications = ('PeptideGroup',)
# Open/closed state of the Dna Group in the Model Tree --
# default closed.
open = False
autodelete_when_empty = True
# (but only if current command permits that for this class --
# see comment near Group.autodelete_when_empty for more info,
# and implems of Command.keep_empty_group)
def node_icon(self, display_prefs):
"""
Model Tree node icon for the Peptide group node
@see: Group.all_content_is_hidden()
"""
open = display_prefs.get('open', False)
if open:
if self.all_content_is_hidden():
return imagename_to_pixmap("modeltree/PeptideGroup-expanded-hide.png")
else:
return imagename_to_pixmap("modeltree/PeptideGroup-expanded.png")
else:
if self.all_content_is_hidden():
return imagename_to_pixmap("modeltree/PeptideGroup-collapsed-hide.png")
else:
return imagename_to_pixmap("modeltree/PeptideGroup-collapsed.png")
# Note: some methods below this point are examples or experiments or stubs,
# and are likely to be revised significantly or replaced.
# [bruce 080115 comment]
# example method:
def getSegments(self):
"""
Return a list of all our PeptideSegment objects.
"""
return self.get_topmost_subnodes_of_class(self.assy.PeptideSegment)
def isEmpty(self):
"""
Returns True if there are no Peptide chunks as its members
(Returns True even when there are empty PeptideSegment objects inside)
@see: InsertPeptide_EditCommand._finalizeStructure where this test is used.
"""
#May be for the short term, we can use self.getAtomList()? But that
#doesn't ensure if the DnaGroup always has atom of type either
#'strand' or 'axis' .
if len(self.getSegments()) == 0:
return True
else:
return False
def addSegment(self, segment):
"""
Adds a new segment object for this dnaGroup.
@param segment: The PeptideSegment to be added to this PeptideGroup object
@type: B{PeptideSegment}
"""
self.addchild(segment)
def getProps(self):
"""
Method to support Dna duplex editing. see Group.__init__ for
a comment
THIS IS THE DEFAULT IMPLEMENTATION. TO BE MODIFIED
"""
#Should it supply the Dna Segment list (children) and then add
#individual segments when setProps is called??
# [probably not; see B&N email discussion from when this comment was added]
if self.editCommand:
props = ()
return props
def setProps(self, props):
"""
Method to support Dna duplex editing. see Group.__init__ for
a comment
THIS IS THE DEFAULT IMPLEMENTATION. TO BE MODIFIED
"""
#Should it accept the Dna Segment list and then add individual segments?
pass
def edit(self):
"""
@see: Group.edit()
"""
commandSequencer = self.assy.w.commandSequencer
commandSequencer.userEnterCommand('BUILD_Peptide', always_update = True)
currentCommand = commandSequencer.currentCommand
assert currentCommand.commandName == 'BUILD_Peptide'
currentCommand.editStructure(self)
def getSelectedSegments(self):
"""
Returns a list of segments whose all members are selected.
@return: A list containing the selected strand objects
within self.
@rtype: list
"""
#TODO: This is a TEMPORARY KLUDGE until Dna model is fully functional.
#Must be revised. Basically it returns a list of PeptideSegments whose
#all members are selected.
#See BuildDna_PropertyManager._currentSelectionParams() where it is used
#-- Ninad 2008-01-18
segmentList = self.getSegments()
selectedSegmentList = []
for segment in segmentList:
pickedNodes = []
unpickedNodes = []
def func(node):
if isinstance(node, self.assy.Chunk):
if not node.picked:
unpickedNodes.append(node)
else:
pickedNodes.append(node)
segment.apply2all(func)
if len(unpickedNodes) == 0 and pickedNodes:
selectedSegmentList.append(segment)
return selectedSegmentList
def getAtomList(self):
"""
Return a list of all atoms contained within this PeptideGroup
"""
atomList = []
def func(node):
if isinstance(node, self.assy.Chunk):
atomList.extend(node.atoms.itervalues())
self.apply2all(func)
return atomList
def draw_highlighted(self, glpane, color):
"""
Draw the Peptide segment chunks as highlighted. (Calls the related
methods in the chunk class)
@param: GLPane object
@param color: The highlight color
@see: Chunk.draw_highlighted()
@see: SelectChunks_GraphicsMode.draw_highlightedChunk()
@see: SelectChunks_GraphicsMode._get_objects_to_highlight()
"""
for c in self.getSegments():
c.draw_highlighted(glpane, color)
pass # end of class PeptideGroup
# ==
| NanoCAD-master | cad/src/outtakes/PeptideGroup.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
RotaryMotorProp.py
$Id$
"""
from PyQt4.Qt import QDialog
from PyQt4.Qt import QWidget
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QColorDialog
from RotaryMotorPropDialog import Ui_RotaryMotorPropDialog
from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf, get_widget_with_color_palette
class RotaryMotorProp(QDialog, Ui_RotaryMotorPropDialog):
def __init__(self, motor, glpane):
QWidget.__init__(self)
self.setupUi(self)
self.connect(self.cancel_btn,SIGNAL("clicked()"),self.reject)
self.connect(self.ok_btn,SIGNAL("clicked()"),self.accept)
self.connect(self.choose_color_btn,SIGNAL("clicked()"),self.change_jig_color)
self.connect(self.lengthLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
self.connect(self.radiusLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
self.connect(self.sradiusLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
self.jig = motor
self.glpane = glpane
self.nameLineEdit.setWhatsThis("""<b>Name</b><p>Name of Rotary Motor that appears in the Model
Tree</p>""")
self.torqueLineEdit.setWhatsThis("""<b>Torque </b><p>Simulations will begin with the motor's torque
set to this value.</p>""")
self.speedLineEdit.setWhatsThis("""<b>Final Speed</b><p>The final velocity of the motor's flywheel
during simulations.</p>""")
self.initialSpeedLineEdit.setWhatsThis("""<b>Initial Speed</b><p>Simulations will begin with the motor's
flywheel rotating at this velocity.</p>""")
self.dampers_textlabel.setWhatsThis("""<b>Dampers</b><p>If checked, the dampers are enabled for this
motor during a simulation. See the Rotary Motor web page on the NanoEngineer-1 Wiki for more information.</p>""")
self.textLabel1_5.setWhatsThis("""<b>Enable in Minimize <i>(experimental)</i></b><p>If checked,
the torque specified above will be applied to the motor atoms during a structure minimization. While intended to allow simulations
to begin with rotary motors running at speed, this feature requires more work to be useful.</p>""")
self.dampers_checkbox.setWhatsThis("""<b>Dampers</b><p>If checked, the dampers are enabled for this
motor during a simulation. See the Rotary Motor web page on the NanoEngineer-1 Wiki for more information.</p>""")
self.enable_minimize_checkbox.setWhatsThis("""<b>Enable in Minimize <i>(experimental)</i></b><p>If checked,
the torque specified above will be applied to the motor atoms during a structure minimization. While intended to allow simulations
to begin with rotary motors running at speed, this feature requires more work to be useful.</p>""")
def setup(self):
self.jig_attrs = self.jig.copyable_attrs_dict() # Save the jig's attributes in case of Cancel.
# Jig color
self.jig_QColor = RGBf_to_QColor(self.jig.normcolor) # Used as default color by Color Chooser
self.jig_color_pixmap = get_widget_with_color_palette(
self.jig_color_pixmap, self.jig_QColor)
self.nameLineEdit.setText(self.jig.name)
self.torqueLineEdit.setText(str(self.jig.torque))
self.initialSpeedLineEdit.setText(str(self.jig.initial_speed))
self.speedLineEdit.setText(str(self.jig.speed))
self.lengthLineEdit.setText(str(self.jig.length))
self.radiusLineEdit.setText(str(self.jig.radius))
self.sradiusLineEdit.setText(str(self.jig.sradius)) # spoke radius
self.enable_minimize_checkbox.setChecked(self.jig.enable_minimize)
self.dampers_checkbox.setChecked(self.jig.dampers_enabled) # mark & bruce 060421
def change_jig_color(self):
'''Slot method to change the jig's color.'''
color = QColorDialog.getColor(self.jig_QColor, self)
if color.isValid():
self.jig_QColor = color
self.jig_color_pixmap = get_widget_with_color_palette(
self.jig_color_pixmap, self.jig_QColor)
self.jig.color = self.jig.normcolor = QColor_to_RGBf(color)
self.glpane.gl_update()
def change_motor_size(self, gl_update=True):
'''Slot method to change the jig's length, radius and/or spoke radius.'''
self.jig.length = float(str(self.lengthLineEdit.text())) # motor length
self.jig.radius = float(str(self.radiusLineEdit.text())) # motor radius
self.jig.sradius = float(str(self.sradiusLineEdit.text())) # spoke radius
if gl_update:
self.glpane.gl_update()
def accept(self):
'''Slot for the 'OK' button '''
self.jig.cancelled = False
self.jig.try_rename(self.nameLineEdit.text())
self.jig.torque = float(str(self.torqueLineEdit.text()))
self.jig.initial_speed = float(str(self.initialSpeedLineEdit.text()))
self.jig.speed = float(str(self.speedLineEdit.text()))
self.change_motor_size(gl_update=False)
self.jig.enable_minimize = self.enable_minimize_checkbox.isChecked()
self.jig.dampers_enabled = self.dampers_checkbox.isChecked() # bruce 060421
self.jig.assy.w.win_update() # Update model tree
self.jig.assy.changed()
QDialog.accept(self)
def reject(self):
'''Slot for the 'Cancel' button '''
self.jig.attr_update(self.jig_attrs) # Restore attributes of the jig.
self.glpane.gl_update()
QDialog.reject(self)
| NanoCAD-master | cad/src/outtakes/RotaryMotorProp.py |
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details.
'''
widget_hacks.py
Miscellaneous widget-related code (such as experimental code or
temporary bug workarounds) which needs cleanup before being suitable
for widgets.py.
$Id$
History:
Bruce 050809 moved the "Mac OS X 10.4 Tiger QToolButton bug workaround"
(and related code) from debug_prefs.py into this file, and improved the
bug workaround for Alpha6.
'''
__author__ = 'bruce'
# note: this is now obsolete; the same commit that moves this file into outtakes
# also removes commented-out calls into it from several files in cad/src. [bruce 071005]
# for QToolButton, we need the actual class, for isinstance and superclass-for-subclass-definition,
# not the class-as-perhaps-hacked-object-constructor (which might be a function rather than a class),
# so do this in case I'm hacking the constructor as part of the workaround:
try:
from __main__ import original_QToolButton as QToolButton
except:
from PyQt4.Qt import QToolButton
from PyQt4.Qt import QPainter, Qt, QPen, QColor
toolbutton_highlight_color = QColor(80,80,255) # light blue; should perhaps be a pref
_enable_hacked_QToolButton_paintEvent = False # set to True by a specific command
class hacked_QToolButton(QToolButton):
is_hacked_class = True
def paintEvent(self, event):
res = QToolButton.paintEvent(self, event)
if _enable_hacked_QToolButton_paintEvent and self.isChecked():
r = event.rect()
x,y = r.left(), r.top()
w,h = r.width(), r.height()
# There are at least three rect sizes: 30x35, 30x36, 32x33 (see debug-print below).
# Not sure if this sometimes includes some padding around the icon.
## print r.top(),r.bottom(),r.height(), r.left(),r.right(),r.width()
## 0 29 30 0 34 35
## 0 29 30 0 35 36
## 0 31 32 0 32 33
p = QPainter(self, True) # True claims to mean un-clipped -- not sure if this is good.
## Qt4 error: TypeError: too many arguments to QPainter(), 1 at most expected
color = toolbutton_highlight_color
p.setPen(QPen(color, 3)) # try 3 and 2
p.drawRect(x+2,y+2,w-4,h-4) #e could also try drawRoundRect(r, xroundedness, yroundedness)
return res
pass
def replacement_QToolButton_constructor(*args): #e could probably just install the class instead of this function
return hacked_QToolButton(*args)
def replace_QToolButton_constructor( func):
"only call this once, and call it before any QToolButton is made"
import PyQt4.Qt as qt #bruce 070425 bugfix in Qt4 port: added "as qt"
import __main__
__main__.original_QToolButton = qt.QToolButton
qt.QToolButton = func
## print "replaced qt.QToolButton %r with %r" % ( __main__.original_QToolButton, func)
# The following is needed for this to work on Qt4 [bruce 070425]:
for attr in ('MenuButtonPopup',):
val = getattr( __main__.original_QToolButton, attr)
setattr(func, attr, val)
return
def doit3():
"this is called once very early in startup, on Qt3 Macs only"
# Note: it might not be necessary to call this when using Qt4, since the Qt3 bug it was meant to work around
# may have been fixed in Qt4. We've never tested this. The debug menu option it supports,
# "Mac OS 10.4 QToolButton workaround", also doesn't yet work in Qt4 due to an incomplete port
# (see the "Qt4 error" comments herein). For these reasons I'm disabling the call to this routine
# and that debug menu command in Qt4. We'll need to test a built release on Tiger to find out if the
# bug this worked around is still present. If so, we'll need to reenable this code and complete the port to Qt4.
# [bruce 070425]
replace_QToolButton_constructor( replacement_QToolButton_constructor)
# ==
def hack_QToolButton_1(qtoolbutton): #bruce 050729 experiment to work around QToolButton bug in Mac OS X 10.4 Tiger
"""Replace a QToolButton's icons with better ones (but they are not perfect -- the highlight rect is too small; don't know why).
Only works for QToolButtons which don't have text (don't know why).
"""
text = str( qtoolbutton.text() )
if text:
return # return early
iconset = qtoolbutton.iconSet()
## Qt4 error: AttributeError: iconSet
from utilities.debug_prefs import modify_iconset_On_states
modify_iconset_On_states(iconset, use_color = toolbutton_highlight_color )
qtoolbutton.setIcon(iconset) #k might not be needed
return
def apply2allchildwidgets(widget, func):
func(widget)
kids = widget.children() # guess about how to call QObject.children()
if kids: #k not sure if test is needed
for kid in kids:
apply2allchildwidgets( kid, func)
return
def hack_if_toolbutton(widget):
if isinstance(widget, QToolButton):
try:
widget.is_hacked_class
except AttributeError:
pass
else:
return
hack_QToolButton_1(widget) # this one works for toolbars; hacked class works in MMTK; #e make them the same size/pos??
return
def hack_every_QToolButton(win): #bruce 050806, revised 050809
global _enable_hacked_QToolButton_paintEvent
_enable_hacked_QToolButton_paintEvent = True # this gets the ones in the MMTK
apply2allchildwidgets(win, hack_if_toolbutton) # and this is needed for the ones in toolbars
# Warning about MMTK widget: this has no effect on it if it's not yet created (or maybe, not presently shown, I don't know).
# If it is, then it messed up its toolbuttons by making the textual ones blank, though the iconic ones are ok.
# So I exclude them by detecting the fact that they have text. This works, but then they don't benefit from the workaround.
# As for its hybrid buttons, the ones visible at the time work, but if you change elements, they don't,
# not even if you change back to the same element (I don't know why). [as of bruce 050806 6:45pm]
#e It would be good to count how many we do this to, and return that, for printing into history,
# so if you do it again you can see if you caught more that time.
return
# this gets printed into history by caller of hack_every_QToolButton, unless it's "":
hack_every_QToolButton_warning = "(This might not be visible in dialogs until they're next used or reopened.)"
## older: "(As of 050806, this doesn't yet work perfectly for the MMTK buttons.)" ))
# == part of a hack to get another pref checkbox into A6. Not now used, but maybe useful in the future. [bruce 050806-09]
def find_layout(widget):
"search all layouts under widget's toplevel widget to find the (first) (#e enabled?) layout controlling widget"
win = widget.topLevelWidget()
from PyQt4.Qt import QLayout
res = []
keep = [] # for making debug print addrs not be reused
widgeo = widget.geometry() # QRect object
# comparing geometries is the only way i can figure out to find which layout controls which widget;
# I'll take the smallest area layout that contains the widget
##print "widget geom",widgeo,widgeo.left(),widgeo.right(),widgeo.top(),widgeo.bottom()
def hmm(child):
if not isinstance(child,QLayout):
return
## print "layout name:",str(child.name())
## # they all say "unnamed" even though the source code gives them a name
geo = child.geometry() # QRect object
area = (geo.right() - geo.left()) * (geo.bottom() - geo.top())
contains = geo.contains(widgeo)
if not contains:
return
res.append(( area,child ))
return
apply2allchildwidgets(win, hmm)
res.sort()
return res[0][1]
def qlayout_items(qlayout):
return qlayoutiterator_items( qlayout.iterator())
def qlayoutiterator_items(qlayoutiterator):
res = []
res.append(qlayoutiterator.current()) #k not sure if needed, but apparently doesn't cause redundant item
while 1:
n1 = qlayoutiterator.next()
if not n1:
break
res.append(n1) # the ref to this might be needed to make the iterator keep going after it...
# no, that's not it - my debug prints are explained this way:
# if the ref is not kept, we reuse the same mem for each new python obj, so pyobj addr is same tho C obj is diff.
return res
# ===
# end
| NanoCAD-master | cad/src/outtakes/widget_hacks.py |
#!/usr/bin/python
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details.
"""\
<p>This is an attempt to implement Mark's \"Starting NE-1\" slideshow
ideas. This is just a little prototype, and is meant to be tweaked as
we discuss things and reach a consensus about what kind of UI behavior
we want.</p>
<p>This prototype is done in Qt 4. It will encourage people to change
over, and a Qt 3 prototype would grow useless soon, and I can't
practically maintain both versions.</p>
<h1>Workspaces</h1>
<p>When we start, there are no workspaces up. We can bring up one or
more workspaces by selecting <b>File->New</b>. (Some day,
<b>File->Open</b> will also work.)</p>
<p>We probably need a concept of an <i>active</i> workspace, even if it's
only the one that the cursor is above right now. We at least need this to
decide which of the toolbar buttons to gray out.</p>
<h2>Tab widget: model tree, property manager</h2>
<p>Each workspace has its own tabbed area on the left side. There are
two tabs, the model tree and a second tab. The second tab could be a
property manager or any dialog that is appropriate at the moment. The
tabbed area for each workspace works completely independently.</p>
<h1>Command Manager Toolbar</h1>
<p>Until we bring up a workspace, the area for the workspace is empty,
and no command buttons are shown. Once there is at least one
workspace, a bunch of command buttons become available: Features,
Sketch, Build, Dimension, and Simulator.</p>
<p><i>Explain what these do....</i></p>
<p><i>It would make sense to me that usually, a command button will
bring up a dialog in the second tab of the tab widget. Is that
right?</i></p>
<h1>Menu Bar</h1>
This is the typical menu bar that almost every graphical-interface
program has, starting with \"File\" and \"Edit\"...
<h1>Toolbar Buttons</h1>
<p>That's the kind of stuff we already have in NE-1. Those are applicable
in many situations, though in practice some will be grayed out, depending
on which workspace is active.</p>"""
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import QWidget
from PyQt4.Qt import QGLWidget
from PyQt4.Qt import QDialog
from PyQt4.Qt import QMainWindow
from PyQt4.Qt import QSizePolicy
from PyQt4.Qt import QIcon
from PyQt4.Qt import QGLFormat
from PyQt4.Qt import QVBoxLayout
from PyQt4.Qt import QTextEdit
from PyQt4.Qt import QTextOption
from PyQt4.Qt import QPushButton
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QTimer
from PyQt4.Qt import QHBoxLayout
from PyQt4.Qt import QGridLayout
import modelTree.modelTreeGui as modelTreeGui
# Hunt for the icons directory
icons = 'icons'
for i in range(3):
import os
if os.path.exists(icons + '/MainWindowUI_image1.png'):
break
icons = '../' + icons
class PartWindow(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self)
self.parent = parent
self.setWindowTitle("My Part Window")
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
layout = QtGui.QHBoxLayout(self)
layout.setMargin(0)
layout.setSpacing(0)
#########################
holder = QWidget()
holder.setMaximumWidth(200)
sublayout = QVBoxLayout(holder)
sublayout.setMargin(0)
sublayout.setSpacing(0)
layout.addWidget(holder)
###
self.featureManager = QtGui.QTabWidget()
self.featureManager.setCurrentIndex(0)
self.featureManager.setMaximumWidth(200)
self.modelTreeTab = QtGui.QWidget()
self.featureManager.addTab(self.modelTreeTab, "Model Tree")
modelTreeTabLayout = QtGui.QVBoxLayout(self.modelTreeTab)
modelTreeTabLayout.setMargin(0)
modelTreeTabLayout.setSpacing(0)
self.propertyManagerTab = QtGui.QWidget()
self.featureManager.addTab(self.propertyManagerTab, "Property Manager")
sublayout.addWidget(self.featureManager)
###
self.modelTree = modelTreeGui.TestWrapper()
self.modelTree.addIconButton(QIcon(icons + '/GrapheneGeneratorDialog_image3.png'),
self.dismiss)
modelTreeTabLayout.addWidget(self.modelTree)
self.glpane = GLPane()
layout.addWidget(self.glpane)
def setRowCol(self, row, col):
self.row, self.col = row, col
def dismiss(self):
self.parent.removePartWindow(self)
########################################################################
class GLPane(QGLWidget):
def __init__(self, master=None):
glformat = QGLFormat()
glformat.setStencil(True)
QGLWidget.__init__(self, glformat, master)
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
##########################################################################
class GridPosition:
def __init__(self):
self.row, self.col = 0, 0
self.availableSlots = [ ]
self.takenSlots = { }
def next(self, widget):
if len(self.availableSlots) > 0:
row, col = self.availableSlots.pop(0)
else:
row, col = self.row, self.col
if row == col:
# when on the diagonal, start a new self.column
self.row = 0
self.col = col + 1
elif row < col:
# continue moving down the right edge until we're about
# to hit the diagonal, then start a new bottom self.row
if row == col - 1:
self.row = row + 1
self.col = 0
else:
self.row = row + 1
else:
# move right along the bottom edge til you hit the diagonal
self.col = col + 1
self.takenSlots[widget] = (row, col)
return row, col
def removeWidget(self, widget):
rc = self.takenSlots[widget]
self.availableSlots.append(rc)
del self.takenSlots[widget]
class AboutWindow(QDialog):
def __init__(self, html, width=600, timeout=None):
QDialog.__init__(self)
self.setMinimumWidth(width)
self.setObjectName("About NanoEngineer-1")
TextEditLayout = QVBoxLayout(self)
TextEditLayout.setSpacing(0)
TextEditLayout.setMargin(0)
self.text_edit = QTextEdit(self)
self.text_edit.setHtml(html)
self.text_edit.setReadOnly(True)
self.text_edit.setWordWrapMode(QTextOption.WordWrap)
TextEditLayout.addWidget(self.text_edit)
self.quit_button = QPushButton("OK")
TextEditLayout.addWidget(self.quit_button)
self.connect(self.quit_button, SIGNAL("clicked()"), self.close)
if timeout is not None:
self.qt = QTimer()
self.qt.setInterval(1000*timeout)
self.qt.start()
self.connect(self.qt, SIGNAL("timeout()"), self.close)
self.show()
self.exec_()
MAIN_WINDOW_SIZE = (800, 600)
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("My Main Window")
self.setMinimumWidth(MAIN_WINDOW_SIZE[0])
self.setMinimumHeight(MAIN_WINDOW_SIZE[1])
self.statusbar = QtGui.QStatusBar(self)
self.statusbar.showMessage("Status message")
self.setStatusBar(self.statusbar)
################################################
self.menubar = self.menuBar()
# Any menu action makes the status bar message disappear
fileMenu = QtGui.QMenu(self.menubar)
fileMenu.setTitle("File")
self.menubar.addAction(fileMenu.menuAction())
newAction = QtGui.QAction("New", self)
newAction.setIcon(QtGui.QtIcon(icons + '/GroupPropDialog_image0.png'))
fileMenu.addAction(newAction)
openAction = QtGui.QAction("Open", self)
openAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image1"))
fileMenu.addAction(openAction)
saveAction = QtGui.QAction("Save", self)
saveAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image2"))
fileMenu.addAction(saveAction)
self.connect(newAction,SIGNAL("activated()"),self.fileNew)
self.connect(openAction,SIGNAL("activated()"),self.fileOpen)
self.connect(saveAction,SIGNAL("activated()"),self.fileSave)
for otherMenuName in ('Edit', 'View', 'Display', 'Select', 'Modify', 'NanoHive-1'):
otherMenu = QtGui.QMenu(self.menubar)
otherMenu.setTitle(otherMenuName)
self.menubar.addAction(otherMenu.menuAction())
helpMenu = QtGui.QMenu(self.menubar)
helpMenu.setTitle("Help")
self.menubar.addAction(helpMenu.menuAction())
aboutAction = QtGui.QAction("About", self)
aboutAction.setIcon(QtGui.QtIcon(icons + '/MainWindowUI_image0.png'))
helpMenu.addAction(aboutAction)
self.connect(aboutAction,SIGNAL("activated()"),self.helpAbout)
##############################################
self.setMenuBar(self.menubar)
centralwidget = QWidget()
self.setCentralWidget(centralwidget)
layout = QVBoxLayout(centralwidget)
layout.setMargin(0)
layout.setSpacing(0)
middlewidget = QWidget()
self.bigButtons = QWidget()
bblo = QHBoxLayout(self.bigButtons)
bblo.setMargin(0)
bblo.setSpacing(0)
self.bigButtons.setMinimumHeight(50)
self.bigButtons.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
for name in ('Features', 'Sketch', 'Build', 'Dimension', 'Simulator'):
btn = QPushButton(self.bigButtons)
btn.setMaximumWidth(80)
btn.setMinimumHeight(50)
btn.setText(name)
self.bigButtons.layout().addWidget(btn)
self.bigButtons.hide()
layout.addWidget(self.bigButtons)
self.littleIcons = QWidget()
self.littleIcons.setMinimumHeight(30)
self.littleIcons.setMaximumHeight(30)
lilo = QHBoxLayout(self.littleIcons)
lilo.setMargin(0)
lilo.setSpacing(0)
pb = QPushButton(self.littleIcons)
pb.setIcon(QIcon(icons + '/GroupPropDialog_image0.png'))
self.connect(pb,SIGNAL("clicked()"),self.fileNew)
lilo.addWidget(pb)
for x in "1 2 4 5 6 7 8 18 42 10 43 150 93 94 97 137".split():
pb = QPushButton(self.littleIcons)
pb.setIcon(QIcon(icons + '/MainWindowUI_image' + x + '.png'))
lilo.addWidget(pb)
layout.addWidget(self.littleIcons)
layout.addWidget(middlewidget)
self.layout = QGridLayout(middlewidget)
self.layout.setMargin(0)
self.layout.setSpacing(2)
self.gridPosition = GridPosition()
self.numParts = 0
self.show()
explainWindow = AboutWindow("Select <b>Help->About</b>"
" for instructions...",
200, 3)
def removePartWindow(self, pw):
self.layout.removeWidget(pw)
self.gridPosition.removeWidget(pw)
self.numParts -= 1
if self.numParts == 0:
self.bigButtons.hide()
def fileNew(self):
if self.numParts == 0:
self.bigButtons.show()
self.numParts += 1
pw = PartWindow(self)
row, col = self.gridPosition.next(pw)
self.layout.addWidget(pw, row, col)
def fileOpen(self):
print "Let's pretend we're opening a file"
def fileSave(self):
print "Let's pretend we're saving a file"
def helpAbout(self):
AboutWindow(__doc__)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
| NanoCAD-master | cad/src/outtakes/uiPrototype.py |
# -*- coding: utf-8 -*-
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
# Form implementation generated from reading ui file 'RotaryMotorPropDialog.ui'
#
# Created: Wed Sep 20 10:35:36 2006
# by: PyQt4 UI code generator 4.0.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_RotaryMotorPropDialog(object):
def setupUi(self, RotaryMotorPropDialog):
RotaryMotorPropDialog.setObjectName("RotaryMotorPropDialog")
RotaryMotorPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,298,424).size()).expandedTo(RotaryMotorPropDialog.minimumSizeHint()))
#RotaryMotorPropDialog.setSizeGripEnabled(True)
self.vboxlayout = QtGui.QVBoxLayout(RotaryMotorPropDialog)
self.vboxlayout.setMargin(11)
self.vboxlayout.setSpacing(6)
self.vboxlayout.setObjectName("vboxlayout")
self.hboxlayout = QtGui.QHBoxLayout()
self.hboxlayout.setMargin(0)
self.hboxlayout.setSpacing(6)
self.hboxlayout.setObjectName("hboxlayout")
self.hboxlayout1 = QtGui.QHBoxLayout()
self.hboxlayout1.setMargin(0)
self.hboxlayout1.setSpacing(6)
self.hboxlayout1.setObjectName("hboxlayout1")
self.vboxlayout1 = QtGui.QVBoxLayout()
self.vboxlayout1.setMargin(0)
self.vboxlayout1.setSpacing(6)
self.vboxlayout1.setObjectName("vboxlayout1")
self.nameTextLabel = QtGui.QLabel(RotaryMotorPropDialog)
self.nameTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.nameTextLabel.setObjectName("nameTextLabel")
self.vboxlayout1.addWidget(self.nameTextLabel)
self.textLabel1 = QtGui.QLabel(RotaryMotorPropDialog)
font = QtGui.QFont(self.textLabel1.font())
font.setFamily("Sans Serif")
font.setPointSize(9)
font.setWeight(50)
font.setItalic(False)
font.setUnderline(False)
font.setStrikeOut(False)
font.setBold(False)
self.textLabel1.setFont(font)
self.textLabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1.setObjectName("textLabel1")
self.vboxlayout1.addWidget(self.textLabel1)
self.textLabel1_2_3 = QtGui.QLabel(RotaryMotorPropDialog)
self.textLabel1_2_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2_3.setObjectName("textLabel1_2_3")
self.vboxlayout1.addWidget(self.textLabel1_2_3)
self.textLabel1_2 = QtGui.QLabel(RotaryMotorPropDialog)
self.textLabel1_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2.setObjectName("textLabel1_2")
self.vboxlayout1.addWidget(self.textLabel1_2)
self.hboxlayout1.addLayout(self.vboxlayout1)
self.gridlayout = QtGui.QGridLayout()
self.gridlayout.setMargin(0)
self.gridlayout.setSpacing(6)
self.gridlayout.setObjectName("gridlayout")
self.nameLineEdit = QtGui.QLineEdit(RotaryMotorPropDialog)
self.nameLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.nameLineEdit.setReadOnly(False)
self.nameLineEdit.setObjectName("nameLineEdit")
self.gridlayout.addWidget(self.nameLineEdit,0,0,1,2)
self.torqueLineEdit = QtGui.QLineEdit(RotaryMotorPropDialog)
self.torqueLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.torqueLineEdit.setObjectName("torqueLineEdit")
self.gridlayout.addWidget(self.torqueLineEdit,1,0,1,1)
self.speedLineEdit = QtGui.QLineEdit(RotaryMotorPropDialog)
self.speedLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.speedLineEdit.setObjectName("speedLineEdit")
self.gridlayout.addWidget(self.speedLineEdit,3,0,1,1)
self.textLabel1_4 = QtGui.QLabel(RotaryMotorPropDialog)
self.textLabel1_4.setObjectName("textLabel1_4")
self.gridlayout.addWidget(self.textLabel1_4,1,1,1,1)
self.textLabel2 = QtGui.QLabel(RotaryMotorPropDialog)
self.textLabel2.setObjectName("textLabel2")
self.gridlayout.addWidget(self.textLabel2,3,1,1,1)
self.textLabel2_2 = QtGui.QLabel(RotaryMotorPropDialog)
self.textLabel2_2.setObjectName("textLabel2_2")
self.gridlayout.addWidget(self.textLabel2_2,2,1,1,1)
self.initialSpeedLineEdit = QtGui.QLineEdit(RotaryMotorPropDialog)
self.initialSpeedLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.initialSpeedLineEdit.setObjectName("initialSpeedLineEdit")
self.gridlayout.addWidget(self.initialSpeedLineEdit,2,0,1,1)
self.hboxlayout1.addLayout(self.gridlayout)
self.hboxlayout.addLayout(self.hboxlayout1)
spacerItem = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout.addItem(spacerItem)
self.vboxlayout.addLayout(self.hboxlayout)
self.hboxlayout2 = QtGui.QHBoxLayout()
self.hboxlayout2.setMargin(0)
self.hboxlayout2.setSpacing(6)
self.hboxlayout2.setObjectName("hboxlayout2")
self.vboxlayout2 = QtGui.QVBoxLayout()
self.vboxlayout2.setMargin(0)
self.vboxlayout2.setSpacing(6)
self.vboxlayout2.setObjectName("vboxlayout2")
self.dampers_textlabel = QtGui.QLabel(RotaryMotorPropDialog)
self.dampers_textlabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.dampers_textlabel.setObjectName("dampers_textlabel")
self.vboxlayout2.addWidget(self.dampers_textlabel)
self.textLabel1_5 = QtGui.QLabel(RotaryMotorPropDialog)
self.textLabel1_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_5.setObjectName("textLabel1_5")
self.vboxlayout2.addWidget(self.textLabel1_5)
self.hboxlayout2.addLayout(self.vboxlayout2)
self.vboxlayout3 = QtGui.QVBoxLayout()
self.vboxlayout3.setMargin(0)
self.vboxlayout3.setSpacing(6)
self.vboxlayout3.setObjectName("vboxlayout3")
self.dampers_checkbox = QtGui.QCheckBox(RotaryMotorPropDialog)
self.dampers_checkbox.setObjectName("dampers_checkbox")
self.vboxlayout3.addWidget(self.dampers_checkbox)
self.enable_minimize_checkbox = QtGui.QCheckBox(RotaryMotorPropDialog)
self.enable_minimize_checkbox.setObjectName("enable_minimize_checkbox")
self.vboxlayout3.addWidget(self.enable_minimize_checkbox)
self.hboxlayout2.addLayout(self.vboxlayout3)
spacerItem1 = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout2.addItem(spacerItem1)
self.vboxlayout.addLayout(self.hboxlayout2)
self.groupBox1 = QtGui.QGroupBox(RotaryMotorPropDialog)
self.groupBox1.setObjectName("groupBox1")
self.gridlayout1 = QtGui.QGridLayout(self.groupBox1)
self.gridlayout1.setMargin(11)
self.gridlayout1.setSpacing(6)
self.gridlayout1.setObjectName("gridlayout1")
self.hboxlayout3 = QtGui.QHBoxLayout()
self.hboxlayout3.setMargin(0)
self.hboxlayout3.setSpacing(6)
self.hboxlayout3.setObjectName("hboxlayout3")
self.hboxlayout4 = QtGui.QHBoxLayout()
self.hboxlayout4.setMargin(0)
self.hboxlayout4.setSpacing(6)
self.hboxlayout4.setObjectName("hboxlayout4")
self.jig_color_pixmap = QtGui.QLabel(self.groupBox1)
self.jig_color_pixmap.setMinimumSize(QtCore.QSize(40,0))
self.jig_color_pixmap.setScaledContents(True)
self.jig_color_pixmap.setObjectName("jig_color_pixmap")
self.hboxlayout4.addWidget(self.jig_color_pixmap)
self.choose_color_btn = QtGui.QPushButton(self.groupBox1)
self.choose_color_btn.setEnabled(True)
self.choose_color_btn.setAutoDefault(False)
self.choose_color_btn.setObjectName("choose_color_btn")
self.hboxlayout4.addWidget(self.choose_color_btn)
self.hboxlayout3.addLayout(self.hboxlayout4)
spacerItem2 = QtGui.QSpacerItem(46,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout3.addItem(spacerItem2)
self.gridlayout1.addLayout(self.hboxlayout3,3,1,1,2)
self.textLabel1_2_2_2 = QtGui.QLabel(self.groupBox1)
self.textLabel1_2_2_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2_2_2.setObjectName("textLabel1_2_2_2")
self.gridlayout1.addWidget(self.textLabel1_2_2_2,2,0,1,1)
self.textLabel1_3 = QtGui.QLabel(self.groupBox1)
self.textLabel1_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_3.setObjectName("textLabel1_3")
self.gridlayout1.addWidget(self.textLabel1_3,0,0,1,1)
self.textLabel1_2_2 = QtGui.QLabel(self.groupBox1)
self.textLabel1_2_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.textLabel1_2_2.setObjectName("textLabel1_2_2")
self.gridlayout1.addWidget(self.textLabel1_2_2,1,0,1,1)
self.colorTextLabel = QtGui.QLabel(self.groupBox1)
self.colorTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.colorTextLabel.setObjectName("colorTextLabel")
self.gridlayout1.addWidget(self.colorTextLabel,3,0,1,1)
self.lengthLineEdit = QtGui.QLineEdit(self.groupBox1)
self.lengthLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.lengthLineEdit.setObjectName("lengthLineEdit")
self.gridlayout1.addWidget(self.lengthLineEdit,0,1,1,1)
self.sradiusLineEdit = QtGui.QLineEdit(self.groupBox1)
self.sradiusLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.sradiusLineEdit.setObjectName("sradiusLineEdit")
self.gridlayout1.addWidget(self.sradiusLineEdit,2,1,1,1)
self.radiusLineEdit = QtGui.QLineEdit(self.groupBox1)
self.radiusLineEdit.setAlignment(QtCore.Qt.AlignLeading)
self.radiusLineEdit.setObjectName("radiusLineEdit")
self.gridlayout1.addWidget(self.radiusLineEdit,1,1,1,1)
self.textLabel3_2 = QtGui.QLabel(self.groupBox1)
self.textLabel3_2.setObjectName("textLabel3_2")
self.gridlayout1.addWidget(self.textLabel3_2,1,2,1,1)
self.textLabel3 = QtGui.QLabel(self.groupBox1)
self.textLabel3.setObjectName("textLabel3")
self.gridlayout1.addWidget(self.textLabel3,0,2,1,1)
self.textLabel3_3 = QtGui.QLabel(self.groupBox1)
self.textLabel3_3.setObjectName("textLabel3_3")
self.gridlayout1.addWidget(self.textLabel3_3,2,2,1,1)
self.vboxlayout.addWidget(self.groupBox1)
spacerItem3 = QtGui.QSpacerItem(20,16,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding)
self.vboxlayout.addItem(spacerItem3)
self.hboxlayout5 = QtGui.QHBoxLayout()
self.hboxlayout5.setMargin(0)
self.hboxlayout5.setSpacing(6)
self.hboxlayout5.setObjectName("hboxlayout5")
spacerItem4 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)
self.hboxlayout5.addItem(spacerItem4)
self.ok_btn = QtGui.QPushButton(RotaryMotorPropDialog)
self.ok_btn.setAutoDefault(False)
self.ok_btn.setDefault(False)
self.ok_btn.setObjectName("ok_btn")
self.hboxlayout5.addWidget(self.ok_btn)
self.cancel_btn = QtGui.QPushButton(RotaryMotorPropDialog)
self.cancel_btn.setAutoDefault(False)
self.cancel_btn.setObjectName("cancel_btn")
self.hboxlayout5.addWidget(self.cancel_btn)
self.vboxlayout.addLayout(self.hboxlayout5)
#self.textLabel1.setBuddy(RotaryMotorPropDialog.lineEdit9)
#self.textLabel1_2_3.setBuddy(RotaryMotorPropDialog.lineEdit9_2)
#self.textLabel1_2.setBuddy(RotaryMotorPropDialog.lineEdit9_2)
self.retranslateUi(RotaryMotorPropDialog)
QtCore.QObject.connect(self.cancel_btn,QtCore.SIGNAL("clicked()"),RotaryMotorPropDialog.reject)
QtCore.QObject.connect(self.ok_btn,QtCore.SIGNAL("clicked()"),RotaryMotorPropDialog.accept)
QtCore.QMetaObject.connectSlotsByName(RotaryMotorPropDialog)
RotaryMotorPropDialog.setTabOrder(self.nameLineEdit,self.torqueLineEdit)
RotaryMotorPropDialog.setTabOrder(self.torqueLineEdit,self.initialSpeedLineEdit)
RotaryMotorPropDialog.setTabOrder(self.initialSpeedLineEdit,self.speedLineEdit)
RotaryMotorPropDialog.setTabOrder(self.speedLineEdit,self.enable_minimize_checkbox)
RotaryMotorPropDialog.setTabOrder(self.enable_minimize_checkbox,self.lengthLineEdit)
RotaryMotorPropDialog.setTabOrder(self.lengthLineEdit,self.radiusLineEdit)
RotaryMotorPropDialog.setTabOrder(self.radiusLineEdit,self.sradiusLineEdit)
RotaryMotorPropDialog.setTabOrder(self.sradiusLineEdit,self.choose_color_btn)
RotaryMotorPropDialog.setTabOrder(self.choose_color_btn,self.ok_btn)
RotaryMotorPropDialog.setTabOrder(self.ok_btn,self.cancel_btn)
def retranslateUi(self, RotaryMotorPropDialog):
RotaryMotorPropDialog.setWindowTitle(QtGui.QApplication.translate("RotaryMotorPropDialog", "Rotary Motor Properties", None, QtGui.QApplication.UnicodeUTF8))
RotaryMotorPropDialog.setWindowIcon(QtGui.QIcon("ui/border/RotaryMotor"))
self.nameTextLabel.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Name :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Torque :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_3.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Initial Speed :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Final Speed :", None, QtGui.QApplication.UnicodeUTF8))
self.nameLineEdit.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "Name of rotary motor.", None, QtGui.QApplication.UnicodeUTF8))
self.torqueLineEdit.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "Simulations will begin with the motor\'s torque set to this value.", None, QtGui.QApplication.UnicodeUTF8))
self.speedLineEdit.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "The final velocity of the motor\'s flywheel.", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_4.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "nN-nm", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel2.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "GHz", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel2_2.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "GHz", None, QtGui.QApplication.UnicodeUTF8))
self.initialSpeedLineEdit.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "The beginning velocity of the motor\'s flywheel.", None, QtGui.QApplication.UnicodeUTF8))
self.dampers_textlabel.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "If checked, dampers are enabled in the simulator.", None, QtGui.QApplication.UnicodeUTF8))
self.dampers_textlabel.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Dampers :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_5.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "If checked, the torque value is applied to the motor\'s atoms during minimization.", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_5.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Enable in Minimize (experimental) :", None, QtGui.QApplication.UnicodeUTF8))
self.dampers_checkbox.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "If checked, dampers are enabled in the simulator.", None, QtGui.QApplication.UnicodeUTF8))
self.enable_minimize_checkbox.setToolTip(QtGui.QApplication.translate("RotaryMotorPropDialog", "If checked, the torque value is applied to the motor\'s atoms during minimization.", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox1.setTitle(QtGui.QApplication.translate("RotaryMotorPropDialog", "Size and Color", None, QtGui.QApplication.UnicodeUTF8))
self.choose_color_btn.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_2_2.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Spoke Radius :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_3.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Motor Length :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel1_2_2.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Motor Radius :", None, QtGui.QApplication.UnicodeUTF8))
self.colorTextLabel.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Color :", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel3_2.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Angstroms", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel3.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Angstroms", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel3_3.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "Angstroms", None, QtGui.QApplication.UnicodeUTF8))
self.ok_btn.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8))
self.ok_btn.setShortcut(QtGui.QApplication.translate("RotaryMotorPropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8))
self.cancel_btn.setText(QtGui.QApplication.translate("RotaryMotorPropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8))
self.cancel_btn.setShortcut(QtGui.QApplication.translate("RotaryMotorPropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8))
| NanoCAD-master | cad/src/outtakes/RotaryMotorPropDialog.py |
def describe_leftDown_action(self, selatom): # bruce 050124
# [bruce 050124 new feature, to mitigate current lack of model tree highlighting of pastable;
# this copies a lot of logic from leftDown, which is bad, should be merged somehow --
# maybe as one routine to come up with a command object, with a str method for messages,
# called from here to say potential cmd or from leftDown to give actual cmd to do ##e]
# WARNING: this runs with every bareMotion (even when selatom doesn't change),
# so it had better be fast.
onto_open_bond = selatom and selatom.is_singlet()
try:
what = self.describe_paste_action(onto_open_bond) # always a string
if what and len(what) > 60: # guess at limit
what = what[:60] + "..."
except:
if debug_flags.atom_debug:
print_compact_traceback("atom_debug: describe_paste_action failed: ")
what = "click to paste"
if onto_open_bond:
cmd = "%s onto bondpoint at %s" % (what, self.posn_str(selatom))
#bruce 050416 also indicate hotspot if we're on clipboard
# (and if this hotspot will be drawn in special color, since explaining that
# special color is the main point of this statusbar-text addendum)
if selatom is selatom.molecule.hotspot and not self.viewing_main_part():
# also only if chunk at toplevel in clipboard (ie pastable)
# (this is badly in need of cleanup, since both here and chunk.draw
# should not hardcode the cond for that, they should all ask the same method here)
if selatom.molecule in self.o.assy.shelf.members:
cmd += " (hotspot)"
elif selatom is not None:
cmd = "click to drag %r" % selatom
cmd += " (%s)" % selatom.atomtype.fullname_for_msg() # nested parens ###e improve
else:
cmd = "%s at \"water surface\"" % what
#e cmd += " at position ..."
return cmd
from selectMode:
# someday -- we'll need to do this in a callback when selobj is set:
## self.update_selatom(event, msg_about_click = True)
# but for now, I removed the msg_about_click option, since it's no longer used,
# and can't yet be implemented correctly (due to callback issue when selobj
# is not yet known), and it tried to call a method defined only in depositMode,
# describe_leftDown_action, which I'll also remove or comment out. [bruce 071025]
return not new_selobj_unknown # from update_selobj
the def of update_selatom that had code for msg_about_click was in selectAtomsMode.
that code was:
- if msg_about_click:
- # [always do the above, since many things can change what it should
- # say] Come up with a status bar message about what we would paste
- # now.
- # [bruce 050124 new feature, to mitigate current lack of model
- # tree highlighting of pastable]
- msg = self.describe_leftDown_action( glpane.selatom)
- env.history.statusbar_msg( msg)
removing this has also made more depositMode methods have no calls:
def describe_paste_action(self, onto_open_bond): # bruce 050124; added onto_open_bond flag, 050127
"""
return a description of what leftDown would paste or deposit (and how user could do that), if done now
"""
#e should be split into "determine what to paste" and "describe it"
# so the code for "determine it" can be shared with leftDown
# rather than copied from it as now
if self.w.depositState == 'Clipboard':
p = self.pastable
if p:
if onto_open_bond:
ok = is_pastable_onto_singlet( p) #e if this is too slow, we'll memoize it
else:
ok = is_pastable_into_free_space( p) # probably always true, but might as well check
if ok:
return "click to paste %s" % self.pastable.name
else:
return "can't paste %s" % self.pastable.name
else:
return "nothing to paste" # (trying would be an error)
else:
atype = self.pastable_atomtype()
return "click to deposit %s" % atype.fullname_for_msg()
TODO: also check for calls of
posn_str,[still used! but NOT DEFINED IN selMode which uses it! ### FIX]
viewing_main_part,[still used!]
pastable_atomtype, [still used!]
and maybe uses of
self.w.depositState, [still used]
self.pastable, [still used]
is_pastable_onto_singlet, [still used but no longer need imports in depmode]
is_pastable_into_free_space [ditto]
| NanoCAD-master | cad/src/outtakes/describe_leftDown_action.py |
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
Peptide.py -- Peptide generator helper classes, based on empirical data.
@author: Mark Sims
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
History:
Mark 2008-03-09:
- Created (incorporating some code from Will's older file PeptideGenerator.py).
"""
import foundation.env as env
from math import sin, cos, pi
from math import atan2
from Numeric import dot, argmax, argmin, sqrt
from model.chem import Atom
from model.bonds import bond_atoms
from model.bond_constants import V_GRAPHITE, V_SINGLE
from model.bond_constants import atoms_are_bonded
from utilities.Log import greenmsg
from utilities.debug import Stopwatch
from geometry.VQT import Q, V, angleBetween, cross, vlen, norm
from geometry.geometryUtilities import matrix_putting_axis_at_z
from model.chunk import Chunk
from model.elements import PeriodicTable
from model.bonds import CC_GRAPHITIC_BONDLENGTH, BN_GRAPHITIC_BONDLENGTH
ntTypes = ["Carbon", "Boron Nitride"]
ntEndings = ["Hydrogen", "None"] # "Capped" NIY. "Nitrogen" removed. --mark
ntBondLengths = [CC_GRAPHITIC_BONDLENGTH, BN_GRAPHITIC_BONDLENGTH]
sqrt3 = 3 ** 0.5
class Peptide:
"""
Peptide class. Supports both Carbon Peptides (CNTs) or Boron Nitride
Peptides (BNNT).
"""
n = 5
m = 5
type = "Carbon"
endPoint1 = None
endPoint2 = None
endings = "Hydrogen" # "Hydrogen" or "None". "Capped" NIY.
zdist = 0.0 # Angstroms
xydist = 0.0 # Angstroms
twist = 0 # Degrees/Angstrom
bend = 0 # Degrees
numwalls = 1 # Single
spacing = 2.46 # Spacing b/w MWNT in Angstroms
def __init__(self):
"""
Constructor. Creates an instance of a Peptide.
By default, the Peptide is a 5x5 Carbon Peptide. Use the set methods
to change the Peptide's chirality and type (i.e. Boron Nitride).
"""
self.setBondLength()
self._computeRise() # Assigns default rise value.
self._update()
def _update(self):
"""
Private method.
Updates all chirality parameters whenever the following attrs are
changed via their set methods:
- n, m,
- type
- bond_length
"""
n, m = self.getChirality()
type = self.getType()
bond_length = self.getBondLength()
self.maxlen = maxlen = 1.2 * bond_length
self.maxlensq = maxlen**2
x = (n + 0.5 * m) * sqrt3
y = 1.5 * m
angle = atan2(y, x)
twoPiRoverA = (x**2 + y**2) ** .5
AoverR = (2 * pi) / twoPiRoverA
self.__cos = cos(angle)
self.__sin = sin(angle)
# time to get the constants
s, t = self.x1y1(0,0)
u, v = self.x1y1(1./3, 1./3)
w, x = self.x1y1(0,1)
F = (t - v)**2
G = 2 * (1 - cos(AoverR * (s - u)))
H = (v - x)**2
J = 2 * (1 - cos(AoverR * (u - w)))
denom = F * J - G * H
self.R = (bond_length**2 * (F - H) / denom) ** .5
self.B = (bond_length**2 * (J - G) / denom) ** .5
self.A = self.R * AoverR
if 0:
print "--------------"
print "angle =", angle
print "A =", self.A
print "B =", self.B
print "R =", self.R
def x1y1(self, n, m):
c, s = self.__cos, self.__sin
x = (n + .5*m) * sqrt3
y = 1.5 * m
x1 = x * c + y * s
y1 = -x * s + y * c
return (x1, y1)
def mlimits(self, z3min, z3max, n):
if z3max < z3min:
z3min, z3max = z3max, z3min
B, c, s = self.B, self.__cos, self.__sin
P = sqrt3 * B * s
Q = 1.5 * B * (c - s / sqrt3)
m1, m2 = (z3min + P * n) / Q, (z3max + P * n) / Q
return int(m1-1.5), int(m2+1.5) # REVIEW: should this use intRound?
def xyz(self, n, m):
x1, y1 = self.x1y1(n, m)
x2, y2 = self.A * x1, self.B * y1
R = self.R
x3 = R * sin(x2/R)
y3 = R * cos(x2/R)
z3 = y2
return (x3, y3, z3)
def setChirality(self, n, m):
"""
Set the n,m chiral integers of self.
Two restrictions are maintained:
- n >= 2
- 0 <= m <= n
@param n: chiral integer I{n}
@type n: int
@param m: chiral integer I{m}
@type m: int
@return: The chiral integers n, m.
@rtype: tuple of two ints (n, m).
@warning: n and/or m may be changed to maintain the restrictions.
"""
if n < 2:
n = 2
if m != self.m:
# m changed. If m became larger than n, make n bigger.
if m > n:
n = m
elif n != self.n:
# n changed. If n became smaller than m, make m smaller.
if m > n:
m = n
self.n = n
self.m = m
self._update()
return self.getChirality()
def getChirality(self):
"""
Returns the n,m chirality of self.
@return: n, m
@rtype: int, int
"""
return (self.n, self.m)
def getChiralityN(self):
"""
Returns the n chirality of self.
@return: n
@rtype: int
"""
return self.n
def getChiralityM(self):
"""
Returns the m chirality of self.
@return: m
@rtype: int
"""
return self.m
def setType(self, type):
"""
Sets the type of Peptide.
@param type: the type of Peptide, either "Carbon" or "Boron Nitride"
@type type: string
@warning: This resets the bond length based on type.
"""
assert type in ntTypes
self.type = type
self.setBondLength() # Calls _update().
return
def getType(self):
"""
Return the type of Peptide.
@return: the type of Peptide.
@rtype: string
"""
return self.type
def getRadius(self):
"""
Returns the radius of the Peptide.
@return: The radius in Angstroms.
@rtype: float
"""
return self.R
def getDiameter(self):
"""
Returns the diameter of the Peptide.
@return: The diameter in Angstroms.
@rtype: float
"""
return self.R * 2.0
def setBondLength(self, bond_length = None):
"""
Sets the I{bond length} between two neighboring atoms in self.
@param bond_length: The bond length in Angstroms. If None, it will be
assigned a default value based on the current
Peptide type.
@type bond_length: float
"""
if bond_length:
self.bond_length = bond_length
else:
self.bond_length = ntBondLengths[ntTypes.index(self.type)]
self._update()
return
def getBondLength(self):
"""
Returns the bond length between atoms in the Peptide.
@return: The bond length in Angstroms.
@rtype: float
"""
return self.bond_length
def setEndings(self, endings):
"""
Sets the type of I{endings} of the Peptide self.
@param endings: Either "Hydrogen" or "None".
@type endings: string
@note: "Capped" endings are not implemented yet.
"""
assert endings in ntEndings
self.endings = endings
def getEndings(self):
"""
Returns the type of I{endings} of the Peptide self.
@return: Either "Hydrogen" or "None".
@rtype : string
@note: "Capped" endings are not implemented yet.
"""
return self.endings
def setEndPoints(self, endPoint1, endPoint2, trimEndPoint2 = False):
"""
Sets endpoints to I{endPoint1} and I{endPoint2}.
@param endPoint1: point
@type endPoint1: V
@param endPoint2: point
@type endPoint2: V
@param trimEndPoint2: If true, endPoint2 will be trimmed to a point in
which the length of the Peptide is an integral
of the Peptide rise. This is not implemented yet.
@type trimEndPoint2: boolean
@attention: trimEndPoint2 argument is ignored (NIY).
"""
# See drawPeptideLadder() for math needed to implement trimEndPoint2.
self.endPoint1 = endPoint1
self.endPoint2 = endPoint2
def getEndPoints(self):
"""
Return endpoints.
"""
return (self.endPoint1, self.endPoint2)
def getParameters(self):
"""
Returns all the parameters needed to (re) build the Peptide using
build().
@return: The parameters of the Peptide segment.
These parameters are retreived via
L{PeptideSegment.getProps()}, called from
L{PeptideSegment_EditCommand.editStructure()}.
Parameters:
- n, m (chirality)
- type (i.e. carbon or boron nitride)
- endings (none, hydrogen, nitrogen)
- endpoints (endPoint1, endPoint2)
@rtype: list (n, m), type, endings, (endPoint1, endPoint2)
"""
return (self.getChirality(),
self.getType(),
self.getEndings(),
self.getEndPoints())
def computeEndPointsFromChunk(self, chunk, update = True):
"""
Derives and returns the endpoints and radius of a Peptide chunk.
@param chunk: a Peptide chunk
@type chunk: Chunk
@return: endPoint1, endPoint2 and radius
@rtype: Point, Point and float
@note: computing the endpoints works fine when n=m or m=0. Otherwise,
the endpoints can be slightly off the central axis, especially
if the Peptide is short.
@attention: endPoint1 and endPoint2 may not be the original endpoints,
and they may be flipped (opposites of) the original
endpoints.
"""
# Since chunk.axis is not always one of the vectors chunk.evecs
# (actually chunk.poly_evals_evecs_axis[2]), it's best to just use
# the axis and center, then recompute a bounding cylinder.
if not chunk.atoms:
return None
axis = chunk.axis
axis = norm(axis) # needed
center = chunk._get_center()
points = chunk.atpos - center # not sure if basepos points are already centered
# compare following Numeric Python code to findAtomUnderMouse and its caller
matrix = matrix_putting_axis_at_z(axis)
v = dot( points, matrix)
# compute xy distances-squared between axis line and atom centers
r_xy_2 = v[:,0]**2 + v[:,1]**2
# to get radius, take maximum -- not sure if max(r_xy_2) would use Numeric code, but this will for sure:
i = argmax(r_xy_2)
max_xy_2 = r_xy_2[i]
radius = sqrt(max_xy_2)
# to get limits along axis (since we won't assume center is centered between them), use min/max z:
z = v[:,2]
min_z = z[argmin(z)]
max_z = z[argmax(z)]
# Adjust the endpoints such that the ladder rungs (rings) will fall
# on the ring segments.
# TO DO: Fix drawPeptideLadder() to offset the first ring, then I can
# remove this adjustment. --Mark 2008-04-12
z_adjust = self.getEndPointZOffset()
min_z += z_adjust
max_z -= z_adjust
endpoint1 = center + min_z * axis
endpoint2 = center + max_z * axis
if update:
#print "Original endpoints:", self.getEndPoints()
self.setEndPoints(endpoint1, endpoint2)
#print "New endpoints:", self.getEndPoints()
return (endpoint1, endpoint2, radius)
def getEndPointZOffset(self):
"""
Returns the z offset, determined by the endings.
@note: Offset distances are not exact, but approximated, which is good
in this case. Providing exact offset values will result in the last
ladder ring from being drawn by drawPeptideLadder().
"""
endings = self.getEndings()
if endings == "Hydrogen":
return 0.8
elif endings == "Nitrogen":
# Nitrogen endings option removed from PM. 2008-05-02 --Mark
return 1.1
else:
return 0.5
def _computeRise(self): #@ See Python get/set attr builtin methods.
"""
Private method.
Sets the rise. This needs to be called anytime a parameter of self
changes.
This is primarlity used for determining the distance between ladder
rungs when drawing the Peptide ladder, during interactive drawing.
@attention: The computed rise is a hack. Feel free to fix.
"""
# Need formula to compute rise.
# I'm sure this is doable, but I need to research it further to learn
# how to compute rise from these params. --Mark 2008-03-12
self.rise = 2.5 # default
if self.m == 0:
self.rise = 2.146
if self.m == 5:
self.rise = 2.457
def getRise(self):
"""
Returns the Peptide U{rise}.
This is primarlity used for determining the distance between ladder
rungs when drawing the Peptide ladder, during interactive drawing.
@return: The rise in Angstroms.
@rtype: float
"""
return self.rise
def getLengthFromNumberOfCells(self, numberOfCells):
"""
Returns the Peptide length (in Angstroms) given the number of cells.
@param numberOfCells: The number of cells in the Peptide.
@type numberOfCells: int
@return: The length of the Peptide in Angstroms.
@rtype: float
"""
assert numberOfCells >= 0
return self.rise * (numberOfCells - 1)
def getLength(self):
"""
Returns the length of the Peptide.
"""
endPoint1, endPoint2 = self.getEndPoints()
return vlen(endPoint1 - endPoint2)
def populate(self, mol, length):
"""
Populates a chunk (mol) with the atoms.
"""
def add(element, x, y, z, atomtype='sp2'):
atm = Atom(element, V(x, y, z), mol)
atm.set_atomtype_but_dont_revise_singlets(atomtype)
return atm
evenAtomDict = { }
oddAtomDict = { }
bondDict = { }
mfirst = [ ]
mlast = [ ]
for n in range(self.n):
mmin, mmax = self.mlimits(-.5 * length, .5 * length, n)
mfirst.append(mmin)
mlast.append(mmax)
for m in range(mmin, mmax+1):
x, y, z = self.xyz(n, m)
if self.type == "Carbon":
atm = add("C", x, y, z) # CNT
else:
atm = add("B", x, y, z) # BNNT
evenAtomDict[(n,m)] = atm
bondDict[atm] = [(n,m)]
x, y, z = self.xyz(n + 1.0 / 3, m + 1.0 / 3 )
if self.type == "Carbon":
atm = add("C", x, y, z) # CNT
else:
atm = add("N", x, y, z, 'sp3') # BNNT
oddAtomDict[(n,m)] = atm
bondDict[atm] = [(n + 1, m), (n, m + 1)]
# m goes axially along the Peptide, n spirals around the tube
# like a barber pole, with slope depending on chirality. If we
# stopped making bonds now, there'd be a spiral strip of
# missing bonds between the n=self.n-1 row and the n=0 row.
# So we need to connect those. We don't know how the m values
# will line up, so the first time, we need to just hunt for the
# m offset. But then we can apply that constant m offset to the
# remaining atoms along the strip.
n = self.n - 1
mmid = (mfirst[n] + mlast[n]) / 2
atm = oddAtomDict[(n, mmid)]
class FoundMOffset(Exception): pass
try:
for m2 in range(mfirst[0], mlast[0] + 1):
atm2 = evenAtomDict[(0, m2)]
diff = atm.posn() - atm2.posn()
if dot(diff, diff) < self.maxlensq:
moffset = m2 - mmid
# Given the offset, zipping up the rows is easy.
for m in range(mfirst[n], mlast[n]+1):
atm = oddAtomDict[(n, m)]
bondDict[atm].append((0, m + moffset))
raise FoundMOffset()
# If we get to this point, we never found m offset.
# If this ever happens, it indicates a bug.
raise Exception, "can't find m offset"
except FoundMOffset:
pass
# Use the bond information to bond the atoms
for (dict1, dict2) in [(evenAtomDict, oddAtomDict),
(oddAtomDict, evenAtomDict)]:
for n, m in dict1.keys():
atm = dict1[(n, m)]
for n2, m2 in bondDict[atm]:
try:
atm2 = dict2[(n2, m2)]
if not atoms_are_bonded(atm, atm2):
if self.type == "Carbon":
bond_atoms(atm, atm2, V_GRAPHITE) # CNT
else:
bond_atoms(atm, atm2, V_SINGLE) # BNNT
except KeyError:
pass
def build(self, name, assy, position, mol = None, createPrinted = False):
"""
Build a Peptide from the parameters in the Property Manger dialog.
"""
endPoint1, endPoint2 = self.getEndPoints()
cntAxis = endPoint2 - endPoint1
length = vlen(cntAxis)
# This can take a few seconds. Inform the user.
# 100 is a guess. --Mark 051103.
if not createPrinted:
# If it's a multi-wall tube, only print the "Creating" message once.
if length > 100.0:
env.history.message("This may take a moment...")
PROFILE = False
if PROFILE:
sw = Stopwatch()
sw.start()
xyz = self.xyz
if mol == None:
mol = Chunk(assy, name)
atoms = mol.atoms
mlimits = self.mlimits
# populate the tube with some extra carbons on the ends
# so that we can trim them later
self.populate(mol, length + 4 * self.maxlen)
# Apply twist and distortions. Bends probably would come
# after this point because they change the direction for the
# length. I'm worried about Z distortion because it will work
# OK for stretching, but with compression it can fail. BTW,
# "Z distortion" is a misnomer, we're stretching in the Y
# direction.
for atm in atoms.values():
# twist
x, y, z = atm.posn()
twistRadians = self.twist * z
c, s = cos(twistRadians), sin(twistRadians)
x, y = x * c + y * s, -x * s + y * c
atm.setposn(V(x, y, z))
for atm in atoms.values():
# z distortion
x, y, z = atm.posn()
z *= (self.zdist + length) / length
atm.setposn(V(x, y, z))
length += self.zdist
for atm in atoms.values():
# xy distortion
x, y, z = atm.posn()
radius = self.getRadius()
x *= (radius + 0.5 * self.xydist) / radius
y *= (radius - 0.5 * self.xydist) / radius
atm.setposn(V(x, y, z))
# Judgement call: because we're discarding carbons with funky
# valences, we will necessarily get slightly more ragged edges
# on Peptides. This is a parameter we can fiddle with to
# adjust the length. My thought is that users would prefer a
# little extra length, because it's fairly easy to trim the
# ends, but much harder to add new atoms on the end.
LENGTH_TWEAK = self.getBondLength()
# trim all the carbons that fall outside our desired length
# by doing this, we are introducing new singlets
for atm in atoms.values():
x, y, z = atm.posn()
if (z > .5 * (length + LENGTH_TWEAK) or
z < -.5 * (length + LENGTH_TWEAK)):
atm.kill()
# Apply bend. Equations are anomalous for zero bend.
if abs(self.bend) > pi / 360:
R = length / self.bend
for atm in atoms.values():
x, y, z = atm.posn()
theta = z / R
x, z = R - (R - x) * cos(theta), (R - x) * sin(theta)
atm.setposn(V(x, y, z))
def trimCarbons():
"""
Trim all the carbons that only have one carbon neighbor.
"""
for i in range(2):
for atm in atoms.values():
if not atm.is_singlet() and len(atm.realNeighbors()) == 1:
atm.kill()
trimCarbons()
# If we're not picky about endings, we don't need to trim carbons
if self.endings == "Capped":
# buckyball endcaps
addEndcap(mol, length, self.getRadius())
if self.endings == "Hydrogen":
# hydrogen terminations
for atm in atoms.values():
atm.Hydrogenate()
elif self.endings == "Nitrogen":
# nitrogen terminations.
# This option has been removed from the "Endings" combo box
# in the PM. 2008-05-02 --mark
dstElem = PeriodicTable.getElement('N')
atomtype = dstElem.find_atomtype('sp2')
for atm in atoms.values():
if len(atm.realNeighbors()) == 2:
atm.Transmute(dstElem, force=True, atomtype=atomtype)
# Translate structure to desired position
for atm in atoms.values():
v = atm.posn()
atm.setposn(v + position)
if PROFILE:
t = sw.now()
env.history.message(greenmsg("%g seconds to build %d atoms" %
(t, len(atoms.values()))))
if self.numwalls > 1:
n += int(self.spacing * 3 + 0.5) # empirical tinkering
self.build(name, assy,
endPoint1, endPoint2,
position,
mol = mol, createPrinted = True)
# Orient the Peptide.
if self.numwalls == 1:
# This condition ensures that MWCTs get oriented only once.
self._orient(mol, endPoint1, endPoint2)
return mol
pass # End build()
def _postProcess(self, cntCellList):
pass
def _orient(self, cntChunk, pt1, pt2):
"""
Orients the CNT I{cntChunk} based on two points. I{pt1} is
the first endpoint (origin) of the Peptide. The vector I{pt1}, I{pt2}
defines the direction and central axis of the Peptide.
@param pt1: The starting endpoint (origin) of the Peptide.
@type pt1: L{V}
@param pt2: The second point of a vector defining the direction
and central axis of the Peptide.
@type pt2: L{V}
"""
a = V(0.0, 0.0, -1.0)
# <a> is the unit vector pointing down the center axis of the default
# DNA structure which is aligned along the Z axis.
bLine = pt2 - pt1
bLength = vlen(bLine)
b = bLine/bLength
# <b> is the unit vector parallel to the line (i.e. pt1, pt2).
axis = cross(a, b)
# <axis> is the axis of rotation.
theta = angleBetween(a, b)
# <theta> is the angle (in degress) to rotate about <axis>.
scalar = bLength * 0.5
rawOffset = b * scalar
if 0: # Debugging code.
print ""
print "uVector a = ", a
print "uVector b = ", b
print "cross(a,b) =", axis
print "theta =", theta
print "cntRise =", self.getCntRise()
print "# of cells =", self.getNumberOfCells()
print "scalar =", scalar
print "rawOffset =", rawOffset
if theta == 0.0 or theta == 180.0:
axis = V(0, 1, 0)
# print "Now cross(a,b) =", axis
rot = (pi / 180.0) * theta # Convert to radians
qrot = Q(axis, rot) # Quat for rotation delta.
# Move and rotate the Peptide into final orientation.
cntChunk.move(qrot.rot(cntChunk.center) - cntChunk.center + rawOffset + pt1)
cntChunk.rot(qrot)
# Bruce suggested I add this. It works here, but not if its
# before move() and rot() above. Mark 2008-04-11
cntChunk.full_inval_and_update()
pass
| NanoCAD-master | cad/src/outtakes/Peptide.py |
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details.
__author__ = 'Will'
import sys
from distutils.core import setup
from distutils.extension import Extension
if (__name__ == '__main__'):
try:
from Pyrex.Distutils import build_ext
except:
print "Problem importing Pyrex. You need to install Pyrex before it makes sense to run this."
print "For more info see cad/src/README-Pyrex and/or "
print " http://www.nanoengineer-1.net/mediawiki/index.php?title=Integrating_Pyrex_into_the_Build_System"
print "(If you already installed Pyrex, there's a bug in your Pyrex installation or in setup.py, "
print " since the import should have worked.)"
sys.exit(1)
# Hack to prevent -O2/-O3 problems on the Mac
#if sys.platform == "darwin":
# extra_compile_args = [ "-DDISTUTILS", "-O" ]
# Maybe put in some "-O" stuff later
extra_compile_args = [ "-DDISTUTILS", "-Wall", "-g" ]
setup(name = 'Simulator',
ext_modules=[Extension("samevals", ["samevals.c"],
extra_compile_args = extra_compile_args
),
],
cmdclass = {'build_ext': build_ext})
| NanoCAD-master | cad/src/outtakes/setup2.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
LinearMotorProp.py
$Id$
"""
from PyQt4.Qt import QDialog
from PyQt4.Qt import QWidget
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QColorDialog
from LinearMotorPropDialog import Ui_LinearMotorPropDialog
from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf, get_widget_with_color_palette
class LinearMotorProp(QDialog, Ui_LinearMotorPropDialog):
def __init__(self, motor, glpane):
QWidget.__init__(self)
self.setupUi(self)
self.connect(self.cancel_btn,SIGNAL("clicked()"),self.reject)
self.connect(self.ok_btn,SIGNAL("clicked()"),self.accept)
self.connect(self.choose_color_btn,SIGNAL("clicked()"),self.change_jig_color)
self.connect(self.lengthLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
self.connect(self.widthLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
self.connect(self.sradiusLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
self.jig = motor
self.glpane = glpane
self.forceLineEdit.setWhatsThis("""<b>Force </b><p>Simulations will begin with the motor's force
set to this
value. On each simulation time step, the displacement of the linear motor's atoms are computed using Hooke's
Law, where:</p>
<p><b>displacement (x) = - Force(F) / Stiffness(k)</b></p>
<p>The negative sign indicates that the force
exerted by the motor (a spring) is in
direct opposition to the direction of displacement. It is called a
"restoring force",
as it tends to restore the system to equilibrium.</p>
<p>When Stiffness = 0, the restoring force is 0 and the displacement
will
continue in one direction.</p>""")
self.nameLineEdit.setWhatsThis("""<b>Name</b><p>Name of Linear Motor that appears in the Model
Tree</p>""")
self.stiffnessLineEdit.setWhatsThis("""<b>Stiffness </b><p>Simulations will begin with the motor's stiffness
set to this
value. On each simulation time step, the displacement of the linear motor's atoms are computed using Hooke's
Law, where:</p>
<p><b>displacement (x) = - Force(F) / Stiffness(k)</b></p>
<p>The negative sign indicates that the force
exerted by the motor (a spring) is in
direct opposition to the direction of displacement. It is called a
"restoring force",
as it tends to restore the system to equilibrium.</p>
<p>When Stiffness = 0, the restoring force is 0 and the displacement
will
continue in one direction.</p>""")
self.textLabel1_5.setWhatsThis("""<b>Enable in Minimize <i>(experimental)</i></b><p>If checked,
the force specified above will be applied to the motor's atoms during a structure minimization. While intended to allow
simulations to begin with linear motors running at speed, this feature requires more work to be useful.</p>""")
self.enable_minimize_checkbox.setWhatsThis("""<b>Enable in Minimize <i>(experimental)</i></b><p>If checked,
the force specified above will be applied to the motor's atoms during a structure minimization. While intended to allow
simulations to begin with linear motors running at speed, this feature requires more work to be useful.</p>""")
def setup(self):
self.jig_attrs = self.jig.copyable_attrs_dict() # Save the jig's attributes in case of Cancel.
# Jig color
self.jig_QColor = RGBf_to_QColor(self.jig.normcolor) # Used as default color by Color Chooser
self.jig_color_pixmap = get_widget_with_color_palette(
self.jig_color_pixmap, self.jig_QColor)
self.nameLineEdit.setText(self.jig.name)
self.stiffnessLineEdit.setText(str(self.jig.stiffness))
self.forceLineEdit.setText(str(self.jig.force))
self.lengthLineEdit.setText(str(self.jig.length))
self.widthLineEdit.setText(str(self.jig.width))
self.sradiusLineEdit.setText(str(self.jig.sradius)) # spoke radius
self.enable_minimize_checkbox.setChecked(self.jig.enable_minimize)
def change_jig_color(self):
'''Slot method to change the jig's color.'''
color = QColorDialog.getColor(self.jig_QColor, self)
if color.isValid():
self.jig_QColor = color
self.jig_color_pixmap = get_widget_with_color_palette(
self.jig_color_pixmap, self.jig_QColor)
self.jig.color = self.jig.normcolor = QColor_to_RGBf(color)
self.glpane.gl_update()
def change_motor_size(self, gl_update=True):
'''Slot method to change the jig's length, width and/or spoke radius.'''
self.jig.length = float(str(self.lengthLineEdit.text())) # motor length
self.jig.width = float(str(self.widthLineEdit.text())) # motor width
self.jig.sradius = float(str(self.sradiusLineEdit.text())) # spoke radius
if gl_update:
self.glpane.gl_update()
def accept(self):
'''Slot for the 'OK' button '''
self.jig.cancelled = False
self.jig.try_rename(self.nameLineEdit.text())
self.jig.force = float(str(self.forceLineEdit.text()))
self.jig.stiffness = float(str(self.stiffnessLineEdit.text()))
self.change_motor_size(gl_update=False)
self.jig.enable_minimize = self.enable_minimize_checkbox.isChecked()
self.jig.assy.w.win_update() # Update model tree
self.jig.assy.changed()
QDialog.accept(self)
def reject(self):
'''Slot for the 'Cancel' button '''
self.jig.attr_update(self.jig_attrs) # Restore attributes of the jig.
self.glpane.gl_update()
QDialog.reject(self)
| NanoCAD-master | cad/src/outtakes/LinearMotorProp.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@version $Id$
piotr 080713: Added editRotamers action.
"""
import foundation.env as env
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import Qt
from PyQt4.Qt import SIGNAL
from utilities.icon_utilities import geticon
from utilities.Log import greenmsg
from ne1_ui.NE1_QWidgetAction import NE1_QWidgetAction
_theProteinFlyout = None
def setupUi(mainWindow):
"""
Construct the QWidgetActions for the Dna flyout on the
Command Manager toolbar.
"""
global _theDnaFlyout
_theProteinFlyout = ProteinFlyout(mainWindow)
# probably needs a retranslateUi to add tooltips too...
def activateProteinFlyout(mainWindow):
mainWindow.commandToolbar.updateCommandToolbar(mainWindow.buildProteinAction,
_theProteinFlyout)
class ProteinFlyout:
def __init__(self, mainWindow, parentWidget):
"""
Create necessary flyout action list and update the flyout toolbar in
the command toolbar with the actions provided by the object of this
class.
@param mainWindow: The mainWindow object
@type mainWindow: B{MWsemantics}
@param parentWidget: The parentWidget to which actions defined by this
object belong to. This needs to be revised.
"""
self.parentWidget = parentWidget
self.win = mainWindow
self._isActive = False
self._createActions(self.parentWidget)
self._addWhatsThisText()
self._addToolTipText()
def getFlyoutActionList(self):
"""
Returns a tuple that contains lists of actions used to create
the flyout toolbar.
Called by CommandToolbar._createFlyoutToolBar().
@return: params: A tuple that contains 3 lists:
(subControlAreaActionList, commandActionLists, allActionsList)
"""
#'allActionsList' returns all actions in the flyout toolbar
#including the subcontrolArea actions.
allActionsList = []
#Action List for subcontrol Area buttons.
subControlAreaActionList = []
subControlAreaActionList.append(self.exitProteinAction)
separator = QtGui.QAction(self.parentWidget)
separator.setSeparator(True)
subControlAreaActionList.append(separator)
subControlAreaActionList.append(self.buildPeptideAction)
subControlAreaActionList.append(self.editRotamersAction)
subControlAreaActionList.append(self.editResiduesAction)
subControlAreaActionList.append(self.compareProteinsAction)
subControlAreaActionList.append(self.displayProteinStyleAction)
allActionsList.extend(subControlAreaActionList)
commandActionLists = []
#Append empty 'lists' in 'commandActionLists equal to the
#number of actions in subControlArea
for i in range(len(subControlAreaActionList)):
lst = []
commandActionLists.append(lst)
params = (subControlAreaActionList, commandActionLists, allActionsList)
return params
def _createActions(self, parentWidget):
self.exitProteinAction = NE1_QWidgetAction(parentWidget,
win = self.win)
self.exitProteinAction.setText("Exit Protein")
self.exitProteinAction.setIcon(
geticon("ui/actions/Command Toolbar/ControlArea/Exit.png"))
self.exitProteinAction.setCheckable(True)
self.buildPeptideAction = NE1_QWidgetAction(parentWidget,
win = self.win)
self.buildPeptideAction.setText("Insert Peptide")
self.buildPeptideAction.setCheckable(True)
self.buildPeptideAction.setIcon(
geticon("ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png"))
self.editRotamersAction = NE1_QWidgetAction(parentWidget, win = self.win)
self.editRotamersAction.setText("Rotamers")
self.editRotamersAction.setCheckable(True)
self.editRotamersAction.setIcon(
geticon("ui/actions/Command Toolbar/BuildProtein/Rotamers.png"))
self.editResiduesAction = NE1_QWidgetAction(parentWidget, win = self.win)
self.editResiduesAction.setText("Residues")
self.editResiduesAction.setCheckable(True)
self.editResiduesAction.setIcon(
geticon("ui/actions/Command Toolbar/BuildProtein/Residues.png"))
self.compareProteinsAction = NE1_QWidgetAction(parentWidget, win = self.win)
self.compareProteinsAction.setText("Compare")
self.compareProteinsAction.setCheckable(True)
self.compareProteinsAction.setIcon(
geticon("ui/actions/Command Toolbar/BuildProtein/Compare.png"))
self.displayProteinStyleAction = NE1_QWidgetAction(parentWidget,
win = self.win)
self.displayProteinStyleAction.setText("Edit Style")
self.displayProteinStyleAction.setCheckable(True)
self.displayProteinStyleAction.setIcon(
geticon("ui/actions/Command Toolbar/BuildProtein/EditProteinDisplayStyle.png"))
self.subControlActionGroup = QtGui.QActionGroup(self.parentWidget)
self.subControlActionGroup.setExclusive(False)
self.subControlActionGroup.addAction(self.buildPeptideAction)
self.subControlActionGroup.addAction(self.displayProteinStyleAction)
def _addWhatsThisText(self):
"""
Add 'What's This' help text for all actions on toolbar.
"""
#change this later
from ne1_ui.WhatsThisText_for_CommandToolbars import whatsThisTextForProteinCommandToolbar
whatsThisTextForProteinCommandToolbar(self)
return
def _addToolTipText(self):
"""
Add 'Tool tip' help text for all actions on toolbar.
"""
#add something here later
return
def connect_or_disconnect_signals(self, isConnect):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
@see: self.activateFlyoutToolbar, self.deActivateFlyoutToolbar
"""
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.exitProteinAction,
SIGNAL("triggered(bool)"),
self.activateExitProtein)
change_connect(self.buildPeptideAction,
SIGNAL("triggered(bool)"),
self.activateBuildPeptide_EditCommand)
change_connect(self.editRotamersAction,
SIGNAL("triggered(bool)"),
self.activateEditRotamers_EditCommand)
change_connect(self.editResiduesAction,
SIGNAL("triggered(bool)"),
self.activateEditResidues_EditCommand)
change_connect(self.compareProteinsAction,
SIGNAL("triggered(bool)"),
self.activateCompareProteins_EditCommand)
change_connect(self.displayProteinStyleAction,
SIGNAL("triggered(bool)"),
self.activateProteinDisplayStyle_Command)
def activateFlyoutToolbar(self):
"""
Updates the flyout toolbar with the actions this class provides.
"""
if self._isActive:
return
self._isActive = True
self.win.commandToolbar.cmdButtonGroup.button(0).setChecked(True)
#Now update the command toolbar (flyout area)
self.win.commandToolbar.updateCommandToolbar(self.win.buildProteinAction,
self)
#self.win.commandToolbar._setControlButtonMenu_in_flyoutToolbar(
#self.cmdButtonGroup.checkedId())
self.exitProteinAction.setChecked(True)
self.connect_or_disconnect_signals(True)
def deActivateFlyoutToolbar(self):
"""
Updates the flyout toolbar with the actions this class provides.
"""
if not self._isActive:
return
self._isActive = False
self.resetStateOfActions()
self.connect_or_disconnect_signals(False)
self.win.commandToolbar.updateCommandToolbar(self.win.buildProteinAction,
self,
entering = False)
def resetStateOfActions(self):
"""
Resets the state of actions in the flyout toolbar.
Uncheck most of the actions. Basically it
unchecks all the actions EXCEPT the ExitDnaAction
@see: self.deActivateFlyoutToolbar()
@see: self.activateBreakStrands_Command()
@see: baseCommand.command_update_flyout()
"""
#Uncheck all the actions in the flyout toolbar (subcontrol area)
for action in self.subControlActionGroup.actions():
if action.isChecked():
action.setChecked(False)
def activateExitProtein(self, isChecked):
"""
Slot for B{Exit DNA} action.
"""
#@TODO: This needs to be revised.
if hasattr(self.parentWidget, 'ok_btn_clicked'):
if not isChecked:
self.parentWidget.ok_btn_clicked()
def activateBuildPeptide_EditCommand(self, isChecked):
"""
Slot for B{Duplex} action.
"""
self.win.insertPeptide(isChecked)
#Uncheck all the actions except the dna duplex action
#in the flyout toolbar (subcontrol area)
for action in self.subControlActionGroup.actions():
if action is not self.buildPeptideAction and action.isChecked():
action.setChecked(False)
def activateEditRotamers_EditCommand(self, isChecked):
"""
Slot for B{EditRotamers} action.
"""
self.win.enterEditRotamersCommand(isChecked)
for action in self.subControlActionGroup.actions():
if action is not self.editRotamersAction and action.isChecked():
action.setChecked(False)
def activateEditResidues_EditCommand(self, isChecked):
"""
Slot for B{EditResidues} action.
"""
self.win.enterEditResiduesCommand(isChecked)
for action in self.subControlActionGroup.actions():
if action is not self.editResiduesAction and action.isChecked():
action.setChecked(False)
def activateCompareProteins_EditCommand(self, isChecked):
"""
Slot for B{CompareProteins} action.
"""
self.win.enterCompareProteinsCommand(isChecked)
for action in self.subControlActionGroup.actions():
if action is not self.compareProteinsAction and action.isChecked():
action.setChecked(False)
def activateProteinDisplayStyle_Command(self, isChecked):
"""
Call the method that enters DisplayStyle_Command.
(After entering the command) Also make sure that
all the other actions on the DnaFlyout toolbar are unchecked AND
the DisplayStyle Action is checked.
"""
self.win.enterProteinDisplayStyleCommand(isChecked)
#Uncheck all the actions except the (DNA) display style action
#in the flyout toolbar (subcontrol area)
for action in self.subControlActionGroup.actions():
if action is not self.displayProteinStyleAction and action.isChecked():
action.setChecked(False)
| NanoCAD-master | cad/src/outtakes/Ui_ProteinFlyout.py |
class unused_methods_in_class_MT_View: #removed from it, bruce 081216
def repaint_some_nodes_NOT_YET_USED(self, nodes): #bruce 080507 experimental, for cross-highlighting; maybe not used; rename?
"""
For each node in nodes, repaint that node, if it was painted the last
time we repainted self as a whole. (If it wasn't, it might not be an
error, if it was due to that node being inside a closed group, or to
a future optim for nodes not visible due to scrolling, or if we're being
called on a new node before it got painted here the first time; so we
print no warning unless debug flags are set.)
Optimization for non-visible nodes (outside scrollarea viewport) is
permitted, but not implemented as of 080507.
@warning: this can only legally be called during a paintEvent on self.
Otherwise it doesn't paint (but causes no harm, I think)
and Qt prints errors to the console. THE INITIAL IMPLEM IN
THE CALLERS IGNORES THIS ISSUE AND THEREFORE DOESN'T YET WORK.
See code comments for likely fix.
"""
# See docstring comment about the caller implem not yet working.
# The fix will probably be for the outer-class methods to queue up the
# nodes to repaint incrementally, and do the necessary update calls
# so that a paintEvent can occur, and set enough new flags to make it
# incremental, so its main effect will just be to call this method.
# The danger is that other update calls (not via our modelTreeGui's mt_update method)
# are coming from Qt and need to be non-incremental. (Don't know, should find out.)
# So an initial fix might just ignore the "incremental" issue
# except for deferring the mt_update effects themselves
# (but I'm not sure if those effects are legal inside paintEvent!).
if not self._painted:
# called too early; not an error
return
# (Possible optim: it will often happen that none of the passed nodes
# have stored positions. We could check for this first and not bother
# to set up the painter in that case. I'm guessing this is not needed.)
painter = QtGui.QPainter()
painter.begin(self)
try:
for node in nodes:
where = self._painted.get(node) # (x, y) or None
if where:
print "mt debug fyi: repainting %r" % (node,) #### remove when works
x, y = where
_paintnode(node, painter, x, y, self.palette_widget,
option_holder = self)
else:
print "mt debug fyi: NOT repainting %r" % (node,) #### remove when works
continue
finally:
painter.end()
return
# WARNING: the following methods duplicate some of the code in
# _our_QItemDelegate in the other MT implem, far above [now removed].
# Also, they are mostly not yet used (still true, 070612). They might be
# used to help make in-place node-label-edit work again.
def createEditor(self, node):
"""
Create and return a QLineEdit child widget to serve as an editor for the given node; initialize its text.
"""
parent = self
qle = QLineEdit(parent)
self.setEditorData(qle, node)
return qle
def setEditorData(self, lineEdit, node):
"""
copy the editable data from node to lineEdit
"""
value = node.name
lineEdit.setText(value)
return
def setModelData(self, lineEdit, node):
"""
copy the editable data from lineEdit to node (if permitted); display a statusbar message about the result
"""
# Note: try_rename checks node.rename_enabled()
# BUG: try_rename doesn't handle unicode (though it seems to handle some non-ascii chars somehow)
# Note: see similar code in a method in another class in this file.
oldname = node.name
ok, text = node.try_rename( lineEdit.text() )
# if ok, text is the new text, perhaps modified;
# if not ok, text is an error message
if ok:
msg = "Renamed node [%s] to [%s]" % (oldname, text) ##e need quote_html??
self.statusbar_message(msg)
## self.modeltreegui.mt_update() #e might be redundant with caller; if so, might be a speed hit
else:
msg = "Can't rename node [%s]: %s" % (oldname, text) # text is reason why not
self.statusbar_message(msg)
return
def updateEditorGeometry(self, editor, option, index):
rect = option.rect
rect.setX(rect.x() + _ICONSIZE[0])
qfm = QFontMetrics(editor.font())
width = qfm.width(editor.text()) + 10
width = min(width, rect.width() - _ICONSIZE[0])
## parent = self.parent()
parent = self
width = min(width, parent.width() - 50 - rect.x())
rect.setWidth(width)
editor.setGeometry(rect)
return
| NanoCAD-master | cad/src/outtakes/MT_View_outtakes.py |
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details.
"""
PropMgrBaseClass.py
@author: Mark
@version: $Id$
@copyright: 2006-2007 Nanorex, Inc. All rights reserved.
History:
mark 2007-05-20: Split PropMgrBaseClass out of PropertyManagerMixin into
this file.
mark 2007-05-23: New PropMgrBaseClass with support for the following PropMgr
widget classes:
- PropMgrGroupBox (subclass of Qt's QGroupBox widget)
- PropMgrComboBox (subclass of Qt's QComboBox widget)
- PropMgrDoubleSpinBox (subclass of Qt's QDoubleSpinBox widget)
- PropMgrSpinBox (subclass of Qt's QSpinBox widget)
- PropMgrTextEdit (subclass of Qt's QTextEdit widget)
mark 2007-05-25: Added PropMgrPushButton
mark 2007-05-28: Added PropMgrLineEdit, PropMgrCheckBox and PropMgrListWidget
ninad 2007-06-03: Added PropMgrToolButton
ninad 2007-06-05: Added PropMgrRadioButton
bruce 2007-06-15: partly cleaned up inheritance.
"""
__author__ = "Mark"
# Mark's To Do List (by order of priority): updated 2007-06-21
# - Add new "parentPropMgr" attr for all widget classes. (important)
# - Support horizontal resizing using splitter (A9.1 backlog item)
# - Finish support for Restore Defaults:
# - PropMgrComboBox.setItems() and PropMgrComboBox.setCurrentIndex()
# - PropMgrComboBox.setText()
# - Add color theme user pref in Preferences dialog. (minor)
# - Set title button color via style sheet (see getTitleButtonStyleSheet)
# - "range" attr (str) that can be included in What's This text. (minor)
# - override setObjectName() in PropMgrWidgetMixin class to create
# standard names.
# - Add important PropMgr widget classes:
# - PropMgrMMKit (needed by BuildAtomsPropertyManager, a future PropMgr)
# - PropMgrColorChooser
# - PropMgrLabel
# - PropMgrGroupAction (needed by PlanePropertyManager)
import os
from PyQt4 import QtCore
from PyQt4.Qt import Qt
from PyQt4.Qt import QGroupBox
from PyQt4.Qt import QTextEdit
from PyQt4.Qt import QDoubleSpinBox
from PyQt4.Qt import QSpinBox
from PyQt4.Qt import QComboBox
from PyQt4.Qt import QPushButton
from PyQt4.Qt import QLineEdit
from PyQt4.Qt import QCheckBox
from PyQt4.Qt import QListWidget
from PyQt4.Qt import QToolButton
from PyQt4.Qt import QPalette
from PyQt4.Qt import QFrame
from PyQt4.Qt import QHBoxLayout
from PyQt4.Qt import QSpacerItem
from PyQt4.Qt import QLabel
from PyQt4.Qt import QWidget
from PyQt4.Qt import QVBoxLayout
from PyQt4.Qt import QGridLayout
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QTextOption
from PyQt4.Qt import QSizePolicy
from PyQt4.Qt import QSize
from PyQt4.Qt import QRadioButton
from PyQt4.Qt import QTextCursor
from utilities import debug_flags
from utilities.icon_utilities import geticon, getpixmap
from utilities.debug import print_compact_traceback
from PM.PropMgr_Constants import pmColor
from PM.PropMgr_Constants import pmTitleFrameColor
from PM.PropMgr_Constants import pmTitleLabelColor
from PM.PropMgr_Constants import pmMinWidth
from PM.PropMgr_Constants import pmDefaultWidth
from PM.PropMgr_Constants import pmLabelRightAlignment
from PM.PropMgr_Constants import pmLabelLeftAlignment
from PM.PropMgr_Constants import pmMainVboxLayoutMargin
from PM.PropMgr_Constants import pmMainVboxLayoutSpacing
from PM.PropMgr_Constants import pmHeaderFrameMargin
from PM.PropMgr_Constants import pmHeaderFrameSpacing
from PM.PropMgr_Constants import getHeaderFont
from PM.PropMgr_Constants import pmSponsorFrameMargin
from PM.PropMgr_Constants import pmSponsorFrameSpacing
from PM.PropMgr_Constants import pmTopRowBtnsMargin
from PM.PropMgr_Constants import pmTopRowBtnsSpacing
from PM.PropMgr_Constants import pmGroupBoxSpacing
from PM.PropMgr_Constants import pmGrpBoxVboxLayoutMargin
from PM.PropMgr_Constants import pmGrpBoxVboxLayoutSpacing
from PM.PropMgr_Constants import pmGridLayoutMargin
from PM.PropMgr_Constants import pmGridLayoutSpacing
from PM.PropMgr_Constants import pmGrpBoxButtonColor
from PM.PropMgr_Constants import pmGrpBoxButtonBorderColor
from PM.PropMgr_Constants import pmGrpBoxButtonTextColor
from PM.PropMgr_Constants import pmGrpBoxExpandedImage
from PM.PropMgr_Constants import pmGrpBoxCollapsedImage
from PM.PropMgr_Constants import pmGrpBoxGridLayoutMargin
from PM.PropMgr_Constants import pmGrpBoxGridLayoutSpacing
from PM.PropMgr_Constants import pmGrpBoxColor
from PM.PropMgr_Constants import pmGrpBoxBorderColor
from PM.PropMgr_Constants import pmMsgGrpBoxMargin
from PM.PropMgr_Constants import pmMsgGrpBoxSpacing
from PM.PropMgr_Constants import pmMessageTextEditColor
from PM.PropMgr_Constants import pmDoneButton
from PM.PropMgr_Constants import pmCancelButton
from PM.PropMgr_Constants import pmRestoreDefaultsButton
from PM.PropMgr_Constants import pmPreviewButton
from PM.PropMgr_Constants import pmWhatsThisButton
# Special Qt debugging functions written by Mark. 2007-05-24 ############
def getSizePolicyName(sizepolicy):
"""Returns the formal name of <sizepolicy>, a QSizePolicy.
FYI:
QSizePolicy.GrowFlag = 1
QSizePolicy.ExpandFlag = 2
QSizePolicy.ShrinkFlag = 4
QSizePolicy.IgnoreFlag = 8
"""
assert isinstance(sizepolicy, QSizePolicy)
if sizepolicy == QSizePolicy.Fixed:
name = "SizePolicy.Fixed"
if sizepolicy == QSizePolicy.GrowFlag:
name = "SizePolicy.Minimum"
if sizepolicy == QSizePolicy.ShrinkFlag:
name = "SizePolicy.Maximum"
if sizepolicy == (QSizePolicy.GrowFlag | QSizePolicy.ShrinkFlag):
name = "SizePolicy.Preferred"
if sizepolicy == (QSizePolicy.GrowFlag | QSizePolicy.ShrinkFlag |QSizePolicy.ExpandFlag):
name = "SizePolicy.Expanding"
if sizepolicy == (QSizePolicy.GrowFlag | QSizePolicy.ExpandFlag):
name = "SizePolicy.MinimumExpanding"
if sizepolicy == (QSizePolicy.ShrinkFlag | QSizePolicy.GrowFlag | QSizePolicy.IgnoreFlag):
name = "SizePolicy.Ignored"
return name
def printSizePolicy(widget):
"""Special method for debugging Qt sizePolicies.
Prints the horizontal and vertical policy of <widget>.
"""
sizePolicy = widget.sizePolicy()
print "-----------------------------------"
print "Widget name =", widget.objectName()
print "Horizontal SizePolicy =", getSizePolicyName(sizePolicy.horizontalPolicy())
print "Vertical SizePolicy =", getSizePolicyName(sizePolicy.verticalPolicy()
)
def printSizeHints(widget):
"""Special method for debugging Qt size hints.
Prints the minimumSizeHint (width and height)
and the sizeHint (width and height) of <widget>.
"""
print "-----------------------------------"
print "Widget name =", widget.objectName()
print "Current Width, Height =", widget.width(), widget.height()
minSize = widget.minimumSizeHint()
print "Min Width, Height =", minSize.width(), minSize.height()
sizeHint = widget.sizeHint()
print "SizeHint Width, Height =", sizeHint.width(), sizeHint.height()
# PropMgr helper functions ##########################################
def getPalette(palette, obj, color):
""" Given a palette, Qt object and a color, return a new palette.
If palette is None, create and return a new palette.
"""
if palette:
pass # Make sure palette is QPalette.
else:
palette = QPalette()
palette.setColor(QPalette.Active, obj, color)
palette.setColor(QPalette.Inactive, obj, color)
palette.setColor(QPalette.Disabled, obj, color)
return palette
def getWidgetGridLayoutParms(label, row, spanWidth):
"""PropMgr widget GridLayout helper function.
Given <label>, <row> and <spanWitdth>, this function returns
all the parameters needed to place the widget (and its label)
in the caller's groupbox GridLayout.
"""
if not spanWidth:
# This widget and its label are on the same row
labelRow = row
labelColumn = 0
labelSpanCols = 1
labelAlignment = pmLabelRightAlignment
widgetRow = row
widgetColumn = 1
widgetSpanCols = 1
incRows = 1
else: # This widget spans the full width of the groupbox
if label: # The label and widget are on separate rows.
# Set the label's row, column and alignment.
labelRow = row
labelColumn = 0
labelSpanCols = 2
labelAlignment = pmLabelLeftAlignment
# Set this widget's row and column attrs.
widgetRow = row + 1 # Widget is below the label.
widgetColumn = 0
widgetSpanCols = 2
incRows = 2
else: # No label. Just the widget.
labelRow = labelColumn = labelSpanCols = labelAlignment = 0
# Set this widget's row and column attrs.
widgetRow = row
widgetColumn = 0
widgetSpanCols = 2
incRows = 1
return widgetRow, widgetColumn, widgetSpanCols, incRows, \
labelRow, labelColumn, labelSpanCols, labelAlignment
# End of getWidgetGridLayoutParms ####################################
class PropertyManager_common: #bruce 070615 split this out of class PropertyManagerMixin
"""Methods common to PropertyManagerMixin and PropMgrBaseClass.
"""
def getPropertyManagerPalette(self):
""" Return a palette for the property manager.
"""
# in future we might want to set different palette colors for prop managers.
return self.getPalette(None,
QPalette.ColorRole(10),
pmColor)
def getPropMgrTitleFramePalette(self): # note: used only by PropMgrBaseClass as of 070615
""" Return a palette for Property Manager title frame.
"""
#bgrole(10) is 'Windows'
return self.getPalette(None,
QPalette.ColorRole(10),
pmTitleFrameColor)
def getPropMgrTitleLabelPalette(self): # note: used only by PropMgrBaseClass as of 070615
""" Return a palette for Property Manager title label.
"""
return self.getPalette(None,
QPalette.WindowText,
pmTitleLabelColor)
def getPropMgrGroupBoxPalette(self): # note: used only by MessageGroupBox as of 070621
""" Return a palette for Property Manager groupbox.
"""
return self.getPalette(None,
QPalette.ColorRole(10),
pmGrpBoxColor)
def getTitleButtonPalette(self): # note: used only by MessageGroupBox as of 070621
""" Return a palette for a GroupBox title button.
"""
return self.getPalette(None,
QPalette.Button,
pmGrpBoxButtonColor)
def getMessageTextEditPalette(self): # note: used only by MessageGroupBox as of 070621
""" Return a palette for a MessageGroupBox TextEdit (yellow).
"""
return self.getPalette(None,
QPalette.Base,
pmMessageTextEditColor)
def getPalette(self, palette, obj, color): #k maybe only used by methods in this class (not sure) [bruce 070615]
""" Given a palette, Qt object [actually a ColorRole] and a color, return a new palette.
If palette is None, create and return a new palette.
"""
#bruce 070615 replaced with call to another (preexisting) function which has same name and identical code.
return getPalette(palette, obj, color)
###e move more methods here?
pass # end of class PropertyManager_common
# ==
class PropMgrBaseClass(PropertyManager_common): #bruce 070615 inherit PropertyManager_common, so GBC doesn't need to for our sake
"""Property Manager base class.
[To make a PM class from this mixin-superclass, subclass it to customize
the widget set and add behavior, and inherit QDialog (before this class).
You must also provide certain methods provided by GeneratorBaseClass
(either by inheriting it -- not sure if superclass order matters for that --
or by defining them yourself), including ok_btn_clicked and several others,
including at least some defined by SponsorableMixin (open_sponsor_homepage, setSponsor).
This set of requirements may be cleaned up.]
[Note: Technically, this is not a "base class" but a "mixin class".]
"""
widgets = [] # All widgets in the PropMgr dialog
num_groupboxes = 0 # Number of groupboxes in PropMgr.
lastGroupBox = None # The last groupbox in this PropMgr
# (i.e. the most recent GroupBox added).
pmHeightComputed = False # See show() for explaination.
def __init__(self, name):
self.setObjectName(name)
self.widgets = [] # All widgets in the groupbox (except the title button).
# Main pallete for PropMgr.
propmgr_palette = self.getPropertyManagerPalette()
self.setPalette(propmgr_palette)
# Main vertical layout for PropMgr.
self.VBoxLayout = QVBoxLayout(self)
self.VBoxLayout.setMargin(pmMainVboxLayoutMargin)
self.VBoxLayout.setSpacing(pmMainVboxLayoutSpacing)
# PropMgr's Header.
self.addHeader()
self.addSponsorButton()
self.addTopRowBtns() # Create top buttons row
self.MessageGroupBox = PropMgrMessageGroupBox(self, "Message")
if 0: # For me. Mark 2007-05-17.
self.debugSizePolicy()
# Keep this around; it might be useful.
# I may want to use it now that I understand it.
# Mark 2007-05-17.
#QMetaObject.connectSlotsByName(self)
# On the verge of insanity, then I wrote this.... Mark 2007-05-22
def debugSizePolicy(self):
"""Special method for debugging sizePolicy.
Without this, I couldn't figure out how to make groupboxes
(and their widgets) behave themselves when collapsing and
expanding them. I needed to experiment with different sizePolicies,
especially TextEdits and GroupBoxes, to get everything working
just right. Their layouts can be slippery. Mark 2007-05-22
"""
if 0: # Override PropMgr sizePolicy.
self.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Minimum)))
if 0: # Override MessageGroupBox sizePolicy.
self.MessageGroupBox.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
if 0: # Override MessageTextEdit sizePolicy.
self.MessageTextEdit.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
if 1: # Print the current sizePolicies.
printSizePolicy(self)
printSizePolicy(self.MessageGroupBox)
printSizePolicy(self.MessageTextEdit)
def show(self):
"""Show the Property Manager.
"""
self.setSponsor()
if not self.pw or self:
self.pw = self.win.activePartWindow() #@@@ ninad061206
self.pw.updatePropertyManagerTab(self) # Redundant code. Fix after A9. Mark 2007-06-01
self.pw.featureManager.setCurrentIndex(self.pw.featureManager.indexOf(self))
else:
self.pw.updatePropertyManagerTab(self)
self.pw.featureManager.setCurrentIndex(self.pw.featureManager.indexOf(self))
if not self.pmHeightComputed:
# This fixes a bug (discovered by Ninad) in which the
# user *reenters* the PropMgr, and the PropMgr has a
# collapsed groupbox. When the user expands the collapsed groupbox,
# widgets are "crushed" in all expanded groupboxes. Mark 2007-05-24
self.fitContents() # pmHeightComputed set to True in fitContents().
# Show the default message whenever we open the Property Manager.
self.MessageGroupBox.MessageTextEdit.restoreDefault()
def fitContents(self):
"""Sets the final width and height of the PropMgr based on the
current contents. It should be called after all the widgets
have been added to this PropMgr.
The important thing this does is set the height of the PropMgr
after it is loaded with all its GroupBoxes (and their widgets).
Since this PropMgr dialog is sitting in a ScrollArea, we want
the scrollbar to appear only when it should. This is determined
by our height, so we must make sure it is always accurate.
Note: This should be called anytime the height changes.
Examples:
- hiding/showing a widget
- expanding/collapsing a groupbox
- resizing a widget based on contents (i.e. a TextEdit).
To do: I need to try deleting the bottom spacer, compute
pmHeight and adding the spacer back to address expanding/
collapsing groupboxes.
Ask Bruce how to do this. Mark 2007-05-23
"""
if 0: # Let's see what minimumSizeHint and sizeHint say.
printSizeHints(self)
pmWidth = pmDefaultWidth - (4 * 2)
pmHeight = self.sizeHint().height()
self.pmHeightComputed = True # See show() for explanation.
self.resize(pmWidth, pmHeight)
# Save this. May need it when we support resizing via splitter.
#self.resize(QSize(
# QRect(0,0,pmWidth,pmHeight).size()).
# expandedTo(self.minimumSizeHint()))
if 0:
print "PropMgr.fitContents(): Width, Height =", self.width(), self.height()
def addHeader(self):
"""Creates the Property Manager header, which contains
a pixmap and white text label.
"""
# Heading frame (dark gray), which contains
# a pixmap and (white) heading text.
self.header_frame = QFrame(self)
self.header_frame.setFrameShape(QFrame.NoFrame)
self.header_frame.setFrameShadow(QFrame.Plain)
header_frame_palette = self.getPropMgrTitleFramePalette()
self.header_frame.setPalette(header_frame_palette)
self.header_frame.setAutoFillBackground(True)
# HBox layout for heading frame, containing the pixmap
# and label (title).
HeaderFrameHLayout = QHBoxLayout(self.header_frame)
HeaderFrameHLayout.setMargin(pmHeaderFrameMargin) # 2 pixels around edges.
HeaderFrameHLayout.setSpacing(pmHeaderFrameSpacing) # 5 pixel between pixmap and label.
# PropMgr icon. Set image by calling setPropMgrIcon() at any time.
self.header_pixmap = QLabel(self.header_frame)
self.header_pixmap.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.header_pixmap.setScaledContents(True)
HeaderFrameHLayout.addWidget(self.header_pixmap)
# PropMgr title label
self.header_label = QLabel(self.header_frame)
header_label_palette = self.getPropMgrTitleLabelPalette()
self.header_label.setPalette(header_label_palette)
self.header_label.setAlignment(pmLabelLeftAlignment)
# PropMgr heading font (for label).
self.header_label.setFont(getHeaderFont())
HeaderFrameHLayout.addWidget(self.header_label)
self.VBoxLayout.addWidget(self.header_frame)
def setPropMgrTitle(self, title):
"""Set the Property Manager header title to string <title>.
"""
self.header_label.setText(title)
def setPropMgrIcon(self, png_path):
"""Set the Property Manager icon in the header.
<png_path> is the relative path to the PNG file.
"""
self.header_pixmap.setPixmap(getpixmap(png_path))
def addSponsorButton(self):
"""Creates the Property Manager sponsor button, which contains
a QPushButton inside of a QGridLayout inside of a QFrame.
The sponsor logo image is not loaded here.
"""
# Sponsor button (inside a frame)
self.sponsor_frame = QFrame(self)
self.sponsor_frame.setFrameShape(QFrame.NoFrame)
self.sponsor_frame.setFrameShadow(QFrame.Plain)
SponsorFrameGrid = QGridLayout(self.sponsor_frame)
SponsorFrameGrid.setMargin(pmSponsorFrameMargin)
SponsorFrameGrid.setSpacing(pmSponsorFrameSpacing) # Has no effect.
self.sponsor_btn = QPushButton(self.sponsor_frame)
self.sponsor_btn.setAutoDefault(False)
self.sponsor_btn.setFlat(True)
self.connect(self.sponsor_btn,SIGNAL("clicked()"),
self.open_sponsor_homepage)
SponsorFrameGrid.addWidget(self.sponsor_btn,0,0,1,1)
self.VBoxLayout.addWidget(self.sponsor_frame)
button_whatsthis_widget = self.sponsor_btn
#bruce 070615 bugfix -- put tooltip & whatsthis on self.sponsor_btn, not self.
# [self.sponsor_frame might be another possible place to put them.]
button_whatsthis_widget.setWhatsThis("""<b>Sponsor Button</b>
<p>When clicked, this sponsor logo will display a short
description about a NanoEngineer-1 sponsor. This can
be an official sponsor or credit given to a contributor
that has helped code part or all of this command.
A link is provided in the description to learn more
about this sponsor.</p>""")
button_whatsthis_widget.setToolTip("NanoEngineer-1 Sponsor Button")
return
def addTopRowBtns(self, showFlags=None):
"""Creates the OK, Cancel, Preview, and What's This
buttons row at the top of the Pmgr.
"""
# The Top Buttons Row includes the following widgets:
#
# - self.pmTopRowBtns (Hbox Layout containing everything:)
#
# - frame
# - hbox layout "frameHboxLO" (margin=2, spacing=2)
# - Done (OK) button
# - Abort (Cancel) button
# - Restore Defaults button
# - Preview button
# - What's This button
# - right spacer (10x10)
# Main "button group" widget (but it is not a QButtonGroup).
self.pmTopRowBtns = QHBoxLayout()
# This QHBoxLayout is (probably) not necessary. Try using just the frame for
# the foundation. I think it should work. Mark 2007-05-30
# Horizontal spacer
HSpacer = QSpacerItem(1, 1,
QSizePolicy.Expanding,
QSizePolicy.Minimum)
# Frame containing all the buttons.
self.TopRowBtnsFrame = QFrame()
self.TopRowBtnsFrame.setFrameShape(QFrame.NoFrame)
self.TopRowBtnsFrame.setFrameShadow(QFrame.Plain)
# Create Hbox layout for main frame.
TopRowBtnsHLayout = QHBoxLayout(self.TopRowBtnsFrame)
TopRowBtnsHLayout.setMargin(pmTopRowBtnsMargin)
TopRowBtnsHLayout.setSpacing(pmTopRowBtnsSpacing)
TopRowBtnsHLayout.addItem(HSpacer)
# Set button type.
if 1: # Mark 2007-05-30
# Needs to be QToolButton for MacOS. Fine for Windows, too.
buttonType = QToolButton
# May want to use QToolButton.setAutoRaise(1) below. Mark 2007-05-29
else:
buttonType = QPushButton # Do not use.
# OK (Done) button.
self.done_btn = buttonType(self.TopRowBtnsFrame)
self.done_btn.setIcon(
geticon("ui/actions/Properties Manager/Done.png"))
self.done_btn.setIconSize(QSize(22,22))
self.connect(self.done_btn,SIGNAL("clicked()"),
self.ok_btn_clicked)
self.done_btn.setToolTip("Done")
TopRowBtnsHLayout.addWidget(self.done_btn)
# Cancel (Abort) button.
self.abort_btn = buttonType(self.TopRowBtnsFrame)
self.abort_btn.setIcon(
geticon("ui/actions/Properties Manager/Abort.png"))
self.abort_btn.setIconSize(QSize(22,22))
self.connect(self.abort_btn,SIGNAL("clicked()"),
self.abort_btn_clicked)
self.abort_btn.setToolTip("Cancel")
TopRowBtnsHLayout.addWidget(self.abort_btn)
# Restore Defaults button.
self.restore_defaults_btn = buttonType(self.TopRowBtnsFrame)
self.restore_defaults_btn.setIcon(
geticon("ui/actions/Properties Manager/Restore.png"))
self.restore_defaults_btn.setIconSize(QSize(22,22))
self.connect(self.restore_defaults_btn,SIGNAL("clicked()"),
self.restore_defaults_btn_clicked)
self.restore_defaults_btn.setToolTip("Restore Defaults")
TopRowBtnsHLayout.addWidget(self.restore_defaults_btn)
# Preview (glasses) button.
self.preview_btn = buttonType(self.TopRowBtnsFrame)
self.preview_btn.setIcon(
geticon("ui/actions/Properties Manager/Preview.png"))
self.preview_btn.setIconSize(QSize(22,22))
self.connect(self.preview_btn,SIGNAL("clicked()"),
self.preview_btn_clicked)
self.preview_btn.setToolTip("Preview")
TopRowBtnsHLayout.addWidget(self.preview_btn)
# What's This (?) button.
self.whatsthis_btn = buttonType(self.TopRowBtnsFrame)
self.whatsthis_btn.setIcon(
geticon("ui/actions/Properties Manager/WhatsThis.png"))
self.whatsthis_btn.setIconSize(QSize(22,22))
self.connect(self.whatsthis_btn,SIGNAL("clicked()"),
self.enter_WhatsThisMode)
self.whatsthis_btn.setToolTip("What\'s This Help")
TopRowBtnsHLayout.addWidget(self.whatsthis_btn)
TopRowBtnsHLayout.addItem(HSpacer)
# Create Button Row
self.pmTopRowBtns.addWidget(self.TopRowBtnsFrame)
self.VBoxLayout.addLayout(self.pmTopRowBtns)
# Add What's This for buttons.
self.done_btn.setWhatsThis("""<b>Done</b>
<p><img source=\"ui/actions/Properties Manager/Done.png\"><br>
Completes and/or exits the current command.</p>""")
self.abort_btn.setWhatsThis("""<b>Cancel</b>
<p><img source=\"ui/actions/Properties Manager/Abort.png\"><br>
Cancels the current command.</p>""")
self.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b>
<p><img source=\"ui/actions/Properties Manager/Restore.png\"><br>
Restores the defaut values of the Property Manager.</p>""")
self.preview_btn.setWhatsThis("""<b>Preview</b>
<p><img source=\"ui/actions/Properties Manager/Preview.png\"><br>
Preview the structure based on current Property Manager settings.</p>""")
self.whatsthis_btn.setWhatsThis("""<b>What's This</b>
<p><img source=\"ui/actions/Properties Manager/WhatsThis.png\"><br>
Click this option to invoke a small question mark that is attached to the mouse pointer,
then click on an object which you would like more information about.
A pop-up box appears with information about the object you selected.</p>""")
return
def hideTopRowButtons(self, pmButtonFlags=None):
"""Hide one or more top row buttons using <pmButtonFlags>.
Button flags not set will cause the button to be shown
if currently hidden.
The button flags are:
pmDoneButton = 1
pmCancelButton = 2
pmRestoreDefaultsButton = 4
pmPreviewButton = 8
pmWhatsThisButton = 16
pmAllButtons = 31
These flags are defined in PropMgr_Constants.py.
"""
if pmButtonFlags & pmDoneButton: self.done_btn.hide()
else: self.done_btn.show()
if pmButtonFlags & pmCancelButton: self.abort_btn.hide()
else: self.abort_btn.show()
if pmButtonFlags & pmRestoreDefaultsButton:
self.restore_defaults_btn.hide()
else: self.restore_defaults_btn.show()
if pmButtonFlags & pmPreviewButton: self.preview_btn.hide()
else: self.preview_btn.show()
if pmButtonFlags & pmWhatsThisButton: self.whatsthis_btn.hide()
else: self.whatsthis_btn.show()
def restore_defaults_btn_clicked(self):
"""Slot for "Restore Defaults" button in the Property Manager.
"""
for widget in self.widgets:
if isinstance(widget, PropMgrGroupBox):
widget.restoreDefault()
# End of PropMgrBaseClass ############################
class PropMgrWidgetMixin:
"""Property Manager Widget Mixin class.
"""
def addWidgetAndLabelToParent(self, parent, label, spanWidth):
"""Add this widget and its label to <parent>.
<label> is the text for this widget's label. If <label> is
empty, no label will be added.
If <spanWidth> (boolean) is True, the widget (and its label)
will span the entire width of <parent> (a groupbox).
"""
# A function that returns all the widget and label layout params.
widgetRow, widgetColumn, widgetSpanCols, incRows, \
labelRow, labelColumn, labelSpanCols, labelAlignment = \
getWidgetGridLayoutParms(label, parent.num_rows, spanWidth)
if label:
# Create QLabel widget.
self.labelWidget = QLabel()
self.labelWidget.setAlignment(labelAlignment)
self.labelWidget.setText(label)
parent.GridLayout.addWidget(self.labelWidget,
labelRow, 0,
1, labelSpanCols)
else:
self.labelWidget = None
parent.GridLayout.addWidget(self,
widgetRow, widgetColumn,
1, widgetSpanCols)
parent.widgets.append(self)
parent.num_rows += incRows
def hide(self):
"""Hide this widget and its label. If hidden, the widget
will not be displayed when its groupbox is expanded.
Call show() to unhide this widget (and its label).
"""
self.hidden = True
QWidget.hide(self) # Hide self.
if self.labelWidget:# Hide self's label if it has one.
self.labelWidget.hide()
if isinstance(self, PropMgrGroupBox):
# Change the spacer height to zero to "hide" it unless
# self is the last GroupBox in the Property Manager.
# if not self.parent.lastGroupBox is self and \
if self.VSpacerWidget:
self.VSpacerWidget.changeSize(10, 0)
def show(self):
"""Show this widget and its label.
"""
self.hidden = False
QWidget.show(self) # Show self.
if self.labelWidget:# Show self's label if it has one.
self.labelWidget.show()
if isinstance(self, PropMgrGroupBox):
# Reset the height of the VSpacerWidget, if this groupbox has one.
if self.VSpacerWidget:
self.VSpacerWidget.changeSize(10, self.VSpacerWidget.defaultHeight)
def collapse(self):
"""Hides this widget (and its label) when the groupbox is collapsed.
"""
QWidget.hide(self) # Hide self.
if self.labelWidget:# Hide self's label if it has one.
self.labelWidget.hide()
def expand(self):
"""Shows this widget (and its label) when the groupbox is expanded,
unless this widget is hidden (via its hidden attr).
"""
if self.hidden: return
QWidget.show(self) # Show self.
if self.labelWidget:# Show self's label if it has one.
self.labelWidget.show()
def restoreDefault(self):
"""Restores the default value this widget.
Note: Need to disconnect and reconnect wigdets to slots.
"""
if 0: # Debugging. Mark 2007-05-25
if self.setAsDefault:
print "Restoring default for ", self.objectName()
if isinstance(self, PropMgrGroupBox):
for widget in self.widgets:
widget.restoreDefault()
if isinstance(self, PropMgrTextEdit):
if self.setAsDefault:
self.insertHtml(self.defaultText,
setAsDefault = True,
replace = True)
if isinstance(self, PropMgrDoubleSpinBox):
if self.setAsDefault:
self.setValue(self.defaultValue)
if isinstance(self, PropMgrSpinBox):
if self.setAsDefault:
self.setValue(self.defaultValue)
if isinstance(self, PropMgrComboBox):
if self.setAsDefault:
self.clear()
for choice in self.defaultChoices:
self.addItem(choice)
self.setCurrentIndex(self.defaultIdx)
if isinstance(self, PropMgrPushButton):
if self.setAsDefault:
self.setText(self.defaultText)
if isinstance(self, PropMgrLineEdit):
if self.setAsDefault:
self.setText(self.defaultText)
if isinstance(self, PropMgrCheckBox):
if self.setAsDefault:
self.setCheckState(self.defaultState)
if isinstance(self, PropMgrListWidget):
if self.setAsDefault:
self.insertItems(0, self.defaultItems)
self.setCurrentRow(self.defaultRow)
'''
self.clear()
for choice in self.defaultChoices:
self.addItem(choice)
self.setCurrentRow(self.defaultRow)
'''
# End of PropMgrWidgetMixin ############################
class PropMgrGroupBox(QGroupBox, PropMgrWidgetMixin):
"""Group Box class for Property Manager group boxes.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
labelWidget = None # Needed for PropMgrWidgetMixin class (might use to hold title).
expanded = True # Set to False when groupbox is collapsed.
widgets = [] # All widgets in the groupbox (except the title button).
num_rows = 0 # Number of rows in this groupbox.
num_groupboxes = 0 # Number of groupboxes in this groupbox.
lastGroupBox = None # The last groupbox in this GroupBox
# (i.e. the most recent GroupBox added).
setAsDefault = True # If set to False, no widgets in this groupbox will be
# reset to their default value when the Restore Defaults
# button is clicked, regardless thier own <setAsDefault> value.
def __init__(self, parent, title='', titleButton=False, setAsDefault=True):
"""
Appends a QGroupBox widget to <parent>, a property manager groupbox.
Arguments:
<parent> - the main property manager dialog (PropMgrBaseClass).
<title> - the GroupBox title text.
<titleButton> - if True, a titleButton is added to the top of the
GroupBox with the label <title>. The titleButton is
used to collapse and expand the GroupBox.
if False, no titleButton is added. <title> will be
used as the GroupBox title and the GroupBox will
not be collapsable/expandable.
<setAsDefault> - if False, no widgets in this groupbox will have thier
default values restored when the Restore Defaults
button is clicked, regardless thier own <setAsDefault> value.
"""
QGroupBox.__init__(self)
self.parent = parent
parent.num_groupboxes += 1
num_groupboxes = 0
self.setObjectName(parent.objectName() +
"/pmGroupBox" +
str(parent.num_groupboxes))
self.setAsDefault = setAsDefault
# Calling addWidget() here is important. If done at the end,
# the title button does not get assigned its palette for some
# unknown reason. Mark 2007-05-20.
parent.VBoxLayout.addWidget(self) # Add self to PropMgr's VBoxLayout
self.widgets = [] # All widgets in the groupbox (except the title button).
parent.widgets.append(self)
self.setAutoFillBackground(True)
self.setPalette(self.getPalette())
self.setStyleSheet(self.getStyleSheet())
# Create vertical box layout
self.VBoxLayout = QVBoxLayout(self)
self.VBoxLayout.setMargin(pmGrpBoxVboxLayoutMargin)
self.VBoxLayout.setSpacing(pmGrpBoxVboxLayoutSpacing)
# Create grid layout
self.GridLayout = QGridLayout()
self.GridLayout.setMargin(pmGridLayoutMargin)
self.GridLayout.setSpacing(pmGridLayoutSpacing)
# Insert grid layout in its own VBoxLayout
self.VBoxLayout.addLayout(self.GridLayout)
if titleButton: # Add title button to GroupBox
self.titleButton = self.getTitleButton(title, self)
self.VBoxLayout.insertWidget(0, self.titleButton)
self.connect(self.titleButton,SIGNAL("clicked()"),
self.toggleExpandCollapse)
else:
self.setTitle(title)
# Fixes the height of the groupbox. Very important. Mark 2007-05-29
self.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.addBottomSpacer()
def addBottomSpacer(self):
"""Add a vertical spacer below this groupbox <self>.
Assume <self> is going to be the last groupbox in this PropMgr, so set
its spacer's vertical sizePolicy to MinimumExpanding. We then set the
vertical sizePolicy of the last groupbox's spacer to Fixed and set its
height to pmGroupBoxSpacing.
"""
# Spacers are only added to groupboxes in the PropMgr, not
# nested groupboxes.
if not isinstance(self.parent, PropMgrBaseClass):
self.VSpacerWidget = None
return
if self.parent.lastGroupBox:
# lastGroupBox is no longer the last one. <self> will be the
# lastGroupBox, so we must change the VSpacerWidget height
# and sizePolicy of lastGroupBox to be a fixed
# spacer between it and <self>.
defaultHeight = pmGroupBoxSpacing
self.parent.lastGroupBox.VSpacerWidget.changeSize(
10, defaultHeight,
QSizePolicy.Fixed,
QSizePolicy.Fixed)
self.parent.lastGroupBox.VSpacerWidget.defaultHeight = defaultHeight
# Add a 1 pixel high, MinimumExpanding VSpacer below this GroupBox.
# This keeps the PropMgr layout squeezed together as groupboxes
# are expanded, collapsed, hidden and shown again.
defaultHeight = 1
self.VSpacerWidget = QSpacerItem(10, defaultHeight,
QSizePolicy.Fixed,
QSizePolicy.MinimumExpanding)
self.VSpacerWidget.defaultHeight = defaultHeight
self.parent.VBoxLayout.addItem(self.VSpacerWidget)
# This groupbox is now the last one in the PropMgr.
self.parent.lastGroupBox = self
def setTitle(self, title):
"""Sets the groupbox title to <title>.
This overrides QGroupBox's setTitle() method.
"""
# Create QLabel widget.
self.labelWidget = QLabel()
labelAlignment = pmLabelLeftAlignment
self.labelWidget.setAlignment(labelAlignment)
self.labelWidget.setText(title)
self.VBoxLayout.insertWidget(0, self.labelWidget)
# Title Button Methods #####################################
def getTitleButton(self, title, parent=None, showExpanded=True): #Ninad 070206
""" Return the groupbox title pushbutton. The pushbutton is customized
such that it appears as a title bar to the user. If the user clicks on
this 'titlebar' it sends appropriate signals to open or close the
groupboxes 'name = string -- title of the groupbox
'showExpanded' = boolean .. NE1 uses a different background
image in the button's Style Sheet depending on the bool.
(i.e. if showExpanded = True it uses a opened group image '^')
See also: getGroupBoxTitleCheckBox , getGroupBoxButtonStyleSheet methods
"""
button = QPushButton(title, parent)
button.setFlat(False)
button.setAutoFillBackground(True)
button.setStyleSheet(self.getTitleButtonStyleSheet(showExpanded))
self.titleButtonPalette = self.getTitleButtonPalette()
button.setPalette(self.titleButtonPalette)
#ninad 070221 set a non existant 'Ghost Icon' for this button
#By setting such an icon, the button text left aligns!
#(which what we want :-) )
#So this might be a bug in Qt4.2. If we don't use the following kludge,
#there is no way to left align the push button text but to subclass it.
#(could mean a lot of work for such a minor thing) So OK for now
button.setIcon(geticon("ui/actions/Properties Manager/GHOST_ICON"))
return button
def getTitleButtonPalette(self):
""" Return a palette for a GroupBox title button.
"""
return getPalette(None, QPalette.Button, pmGrpBoxButtonColor)
def getTitleButtonStyleSheet(self, showExpanded=True):
"""Returns the style sheet for a groupbox title button (or checkbox).
If <showExpanded> is True, the style sheet includes an expanded icon.
If <showExpanded> is False, the style sheet includes a collapsed icon.
"""
# Need to move border color and text color to top (make global constants).
if showExpanded:
styleSheet = "QPushButton {border-style:outset;\
border-width: 2px;\
border-color: " + pmGrpBoxButtonBorderColor + ";\
border-radius:2px;\
font:bold 12px 'Arial'; \
color: " + pmGrpBoxButtonTextColor + ";\
min-width:10em;\
background-image: url(" + pmGrpBoxExpandedImage + ");\
background-position: right;\
background-repeat: no-repeat;\
}"
else:
styleSheet = "QPushButton {border-style:outset;\
border-width: 2px;\
border-color: " + pmGrpBoxButtonBorderColor + ";\
border-radius:2px;\
font: bold 12px 'Arial'; \
color: " + pmGrpBoxButtonTextColor + ";\
min-width:10em;\
background-image: url(" + pmGrpBoxCollapsedImage + ");\
background-position: right;\
background-repeat: no-repeat;\
}"
return styleSheet
def toggleExpandCollapse(self):
"""Slot method for the title button to expand/collapse the groupbox.
"""
if self.widgets:
if self.expanded: # Collapse groupbox by hiding all widgets in groupbox.
self.GridLayout.setMargin(0)
self.GridLayout.setSpacing(0)
# The styleSheet contains the expand/collapse.
styleSheet = self.getTitleButtonStyleSheet(showExpanded = False)
self.titleButton.setStyleSheet(styleSheet)
# Why do we have to keep resetting the palette?
# Does assigning a new styleSheet reset the button's palette?
# If yes, we should add the button's color to the styleSheet.
# Mark 2007-05-20
self.titleButton.setPalette(self.getTitleButtonPalette())
self.titleButton.setIcon(
geticon("ui/actions/Properties Manager/GHOST_ICON"))
for widget in self.widgets:
widget.collapse()
self.expanded = False
else: # Expand groupbox by showing all widgets in groupbox.
if isinstance(self, PropMgrMessageGroupBox):
# If we don't do this, we get a small space b/w the
# title button and the MessageTextEdit widget.
# Extra code unnecessary, but more readable.
# Mark 2007-05-21
self.GridLayout.setMargin(0)
self.GridLayout.setSpacing(0)
else:
self.GridLayout.setMargin(pmGrpBoxGridLayoutMargin)
self.GridLayout.setSpacing(pmGrpBoxGridLayoutSpacing)
# The styleSheet contains the expand/collapse.
styleSheet = self.getTitleButtonStyleSheet(showExpanded = True)
self.titleButton.setStyleSheet(styleSheet)
# Why do we have to keep resetting the palette?
# Does assigning a new styleSheet reset the button's palette?
# If yes, we should add the button's color to the styleSheet.
# Mark 2007-05-20
self.titleButton.setPalette(self.getTitleButtonPalette())
self.titleButton.setIcon(
geticon("ui/actions/Properties Manager/GHOST_ICON"))
for widget in self.widgets:
widget.expand()
self.expanded = True
else:
print "Groupbox has no widgets. Clicking on groupbox button has no effect"
# GroupBox palette and stylesheet methods. ##############################3
def getPalette(self):
""" Return a palette for this groupbox.
The color should be slightly darker (or lighter) than the property manager background.
"""
#bgrole(10) is 'Windows'
return getPalette(None, QPalette.ColorRole(10), pmGrpBoxColor)
def getStyleSheet(self):
"""Return the style sheet for a groupbox. This sets the following
properties only:
- border style
- border width
- border color
- border radius (on corners)
The background color for a groupbox is set using getPalette()."""
styleSheet = "QGroupBox {border-style:solid;\
border-width: 1px;\
border-color: " + pmGrpBoxBorderColor + ";\
border-radius: 0px;\
min-width: 10em; }"
## For Groupboxs' Pushbutton :
##Other options not used : font:bold 10px;
return styleSheet
# End of PropMgrGroupBox ############################
class PropMgrMessageGroupBox(PropMgrGroupBox):
'''Message GroupBox class'''
expanded = True # Set to False when groupbox is collapsed.
widgets = [] # All widgets in the groupbox (except the title button).
num_rows = 0 # Number of rows in the groupbox.
num_grouboxes = 0 # Number of groupboxes in this msg groupbox.
def __init__(self, parent, title):
"""Constructor for PropMgr group box.
<parent> is the PropMgr dialog (of type PropMgrBaseClass)
<title> is the label used on the the title button
"""
PropMgrGroupBox.__init__(self, parent, title, titleButton=True)
parent.num_groupboxes += 1
num_groupboxes = 0
self.setObjectName(parent.objectName() +
"/pmMessageGroupBox" +
str(parent.num_groupboxes))
self.widgets = [] # All widgets in the groupbox (except the title button).
self.VBoxLayout.setMargin(pmMsgGrpBoxMargin)
self.VBoxLayout.setSpacing(pmMsgGrpBoxSpacing)
self.GridLayout.setMargin(0)
self.GridLayout.setSpacing(0)
self.MessageTextEdit = PropMgrTextEdit(self, label='', spanWidth=True)
# wrapWrapMode seems to be set to QTextOption.WrapAnywhere on MacOS,
# so let's force it here. Mark 2007-05-22.
self.MessageTextEdit.setWordWrapMode(QTextOption.WordWrap)
parent.MessageTextEdit = self.MessageTextEdit
# These two policies very important. Mark 2007-05-22
self.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.MessageTextEdit.setSizePolicy(
QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred),
QSizePolicy.Policy(QSizePolicy.Fixed)))
self.setWhatsThis("""<b>Messages</b>
<p>This prompts the user for a requisite operation and/or displays
helpful messages to the user.</p>""")
# Hide until insertHtmlMessage() loads a message.
self.hide()
def insertHtmlMessage(self, text, setAsDefault=False,
minLines=4, maxLines=10,
replace=True):
"""Insert <text> (HTML) into the Prop Mgr's message groupbox.
<minLines> - The minimum number of lines (of text) to display in the TextEdit.
if <minLines>=0 the TextEdit will fit its own height to fit <text>. The
default height is 4 (lines of text).
<maxLines> - The maximum number of lines to display in the TextEdit widget.
<replace> should be set to False if you do not wish
to replace the current text. It will append <text> instead.
Shows the message groupbox if it is hidden.
"""
self.MessageTextEdit.insertHtml(text, setAsDefault,
minLines=minLines, maxLines=maxLines,
replace=True)
self.show()
# End of PropMgrMessageGroupBox ############################
class PropMgrTextEdit(QTextEdit, PropMgrWidgetMixin, PropertyManager_common):
"""PropMgr TextEdit class, for groupboxes (PropMgrGroupBox) only.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to True if "Restore Defaults" should
# reset this widget's text to defaultText.
setAsDefault = False
defaultText = '' # Default text
def __init__(self, parent, label='', spanWidth=False):
"""
Appends a QTextEdit widget to <parent>, a property manager groupbox.
The QTextEdit is empty (has no text) by default. Use insertHtml()
to insert HTML text into the TextEdit.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left (or above) of the TextEdit.
<spanWidth> - if True, the TextEdit and its label will span the width
of its groupbox. Its label will appear directly above
the TextEdit (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "QTextEdit.__init__():"
print " label=", label
print " spanWidth=",spanWidth
if not parent:
return
QTextEdit.__init__(self)
self.setObjectName(parent.objectName() +
"/pmTextEdit" +
str(parent.num_rows))
self._setHeight() # Default height is 4 lines high.
# Needed for Intel MacOS. Otherwise, the horizontal scrollbar
# is displayed in the MessageGroupBox. Mark 2007-05-24.
# Shouldn't be needed with _setHeight().
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
if isinstance(parent, PropMgrMessageGroupBox):
# Add to parent's VBoxLayout if <parent> is a MessageGroupBox.
parent.VBoxLayout.addWidget(self)
# We should be calling the propmgr's getMessageTextEditPalette() method,
# but that will take some extra work which I will do soon. Mark 2007-06-21
self.setPalette(self.getMessageTextEditPalette())
self.setReadOnly(True)
self.setObjectName("MessageTextEdit")
self.labelWidget = None # Never has one. Mark 2007-05-31
parent.widgets.append(self)
parent.num_rows += 1
else:
self.addWidgetAndLabelToParent(parent, label, spanWidth)
def insertHtml(self, text, setAsDefault=False,
minLines=4, maxLines=6,
replace=True):
"""Insert <text> (HTML) into the Prop Mgr's message groupbox.
<minLines> is the minimum number of lines to
display, even if the text takes up fewer lines. The default
number of lines is 4.
<maxLines> is the maximum number of lines to
diplay before adding a vertical scrollbar.
<replace> should be set to False if you do not wish
to replace the current text. It will append <text> instead.
"""
if setAsDefault:
self.defaultText = text
self.setAsDefault = True
if replace:
# Replace the text by selecting effectively all text and
# insert the new text 'over' it (overwrite). :jbirac: 20070629
cursor = self.textCursor()
cursor.setPosition( 0,
QTextCursor.MoveAnchor )
cursor.setPosition( len(self.toPlainText()),
QTextCursor.KeepAnchor )
self.setTextCursor( cursor )
QTextEdit.insertHtml(self, text)
if replace:
# Restore the previous cursor position/selection and mode.
cursor.setPosition( len(self.toPlainText()),
QTextCursor.MoveAnchor )
self.setTextCursor( cursor )
self._setHeight(minLines, maxLines)
def _setHeight(self, minLines=4, maxLines=8):
"""Set the height just high enough to display
the current text without a vertical scrollbar.
<minLines> is the minimum number of lines to
display, even if the text takes up fewer lines.
<maxLines> is the maximum number of lines to
diplay before adding a vertical scrollbar.
"""
if minLines == 0:
fitToHeight=True
else:
fitToHeight=False
# Current width of PropMgrTextEdit widget.
current_width = self.sizeHint().width()
# Probably including Html tags.
text = self.toPlainText()
text_width = self.fontMetrics().width(text)
num_lines = text_width/current_width + 1
# + 1 may create an extra (empty) line on rare occasions.
if fitToHeight:
num_lines = min(num_lines, maxLines)
else:
num_lines = max(num_lines, minLines)
#margin = self.fontMetrics().leading() * 2 # leading() returned 0. Mark 2007-05-28
margin = 10 # Based on trial and error. Maybe it is pm?Spacing=5 (*2)? Mark 2007-05-28
new_height = num_lines * self.fontMetrics().lineSpacing() + margin
if 0: # Debugging code for me. Mark 2007-05-24
print "--------------------------------"
print "Widget name =", self.objectName()
print "minLines =", minLines
print "maxLines =", maxLines
print "num_lines=", num_lines
print "New height=", new_height
print "text =", text
print "Text width=", text_width
print "current_width (of PropMgrTextEdit)=", current_width
# Reset height of PropMgrTextEdit.
self.setMinimumSize(QSize(pmMinWidth * 0.5, new_height))
self.setMaximumHeight(new_height)
# End of PropMgrTextEdit ############################
class PropMgrDoubleSpinBox(QDoubleSpinBox, PropMgrWidgetMixin):
"""PropMgr SpinBox class, for groupboxes (PropMgrGroupBox) only.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's value to val.
setAsDefault = True
defaultValue = 0 # Default value of spinbox
def __init__(self, parent, label='',
val=0, setAsDefault=True,
min=0, max=99,
singleStep=1.0, decimals=1,
suffix='',
spanWidth=False):
"""
Appends a QDoubleSpinBox widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left (or above) of the SpinBox.
<val> - initial value of SpinBox.
<setAsDefault> - if True, will restore <val>
when the "Restore Defaults" button is clicked.
<min> - minimum value in the SpinBox.
<max> - maximum value in the SpinBox.
<decimals> - precision of SpinBox.
<singleStep> - increment/decrement value when user uses arrows.
<suffix> - suffix.
<spanWidth> - if True, the SpinBox and its label will span the width
of its groupbox. Its label will appear directly above
the SpinBox (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "PropMgrSpinBox.__init__():"
print " label=", label
print " val =", val
print " setAsDefault =", setAsDefault
print " min =", min
print " max =", max
print " singleStep =", singleStep
print " decimals =", decimals
print " suffix =", suffix
print " spanWidth =", spanWidth
if not parent:
return
QDoubleSpinBox.__init__(self)
self.setObjectName(parent.objectName() +
"/pmDoubleSpinBox" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Set QDoubleSpinBox min, max, singleStep, decimals, then val
self.setRange(min, max)
self.setSingleStep(singleStep)
self.setDecimals(decimals)
self.setValue(val) # This must come after setDecimals().
# Add suffix if supplied.
if suffix:
self.setSuffix(suffix)
self.addWidgetAndLabelToParent(parent, label, spanWidth)
def setValue(self, val, setAsDefault=True):
"""Set value of widget to <val>. If <setAsDefault> is True,
<val> becomes the default value for this widget so that
"Restore Defaults" will reset this widget to <val>.
"""
if setAsDefault:
self.setAsDefault=True
self.defaultValue=val
QDoubleSpinBox.setValue(self, val)
# End of PropMgrDoubleSpinBox ############################
class PropMgrSpinBox(QSpinBox, PropMgrWidgetMixin):
"""PropMgr SpinBox class, for groupboxes (PropMgrGroupBox) only.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's value to val.
setAsDefault = True
defaultValue = 0 # Default value of spinbox
def __init__(self, parent, label='',
val=0, setAsDefault=True,
min=0, max=99,
suffix='',
spanWidth=False):
"""
Appends a QSpinBox widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left of (or above) the SpinBox.
<val> - initial value of SpinBox.
<setAsDefault> - if True, will restore <val>
when the "Restore Defaults" button is clicked.
<min> - minimum value in the SpinBox.
<max> - maximum value in the SpinBox.
<suffix> - suffix.
<spanWidth> - if True, the SpinBox and its label will span the width
of its groupbox. Its label will appear directly above
the SpinBox (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "PropMgrSpinBox.__init__():"
print " label=", label
print " val =", val
print " setAsDefault =", setAsDefault
print " min =", min
print " max =", max
print " suffix =", suffix
print " spanWidth =", spanWidth
if not parent:
return
QSpinBox.__init__(self)
self.setObjectName(parent.objectName() +
"/pmSpinBox" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Set QSpinBox min, max and initial value
self.setRange(min, max)
self.setValue(val)
# Set default value
self.defaultValue=val
self.setAsDefault = setAsDefault
# Add suffix if supplied.
if suffix:
self.setSuffix(suffix)
self.addWidgetAndLabelToParent(parent, label, spanWidth)
def setValue(self, val, setAsDefault=True):
"""Set value of widget to <val>. If <setAsDefault> is True,
<val> becomes the default value for this widget so that
"Restore Defaults" will reset this widget to <val>.
"""
if setAsDefault:
self.setAsDefault=True
self.defaultValue=val
QSpinBox.setValue(self, val)
# End of PropMgrSpinBox ############################
class PropMgrComboBox(QComboBox, PropMgrWidgetMixin):
"""PropMgr ComboBox class.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's choice index to idx.
setAsDefault = True
# <defaultIdx> - default index when "Restore Defaults" is clicked
defaultIdx = 0
# <defaultChoices> - default choices when "Restore Defaults" is clicked.
defaultChoices = []
def __init__(self, parent, label='',
choices=[], idx=0, setAsDefault=True,
spanWidth=False):
"""
Appends a QComboBox widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left of (or above) the ComboBox.
<choices> - list of choices (strings) in the ComboBox.
<idx> - initial index (choice) of combobox. (0=first item)
<setAsDefault> - if True, will restore <idx> as the current index
when the "Restore Defaults" button is clicked.
<spanWidth> - if True, the ComboBox and its label will span the width
of its groupbox. Its label will appear directly above
the ComboBox (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "PropMgrComboBox.__init__():"
print " label=",label
print " choices =", choices
print " idx =", idx
print " setAsDefault =", setAsDefault
print " spanWidth =", spanWidth
if not parent:
return
QComboBox.__init__(self)
self.setObjectName(parent.objectName() +
"/pmComboBox" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Load QComboBox widget choices and set initial choice (index).
for choice in choices:
self.addItem(choice)
self.setCurrentIndex(idx)
# Set default index
self.defaultIdx=idx
self.defaultChoices=choices
self.setAsDefault = setAsDefault
self.addWidgetAndLabelToParent(parent, label, spanWidth)
# End of PropMgrComboBox ############################
class PropMgrPushButton(QPushButton, PropMgrWidgetMixin):
"""PropMgr PushButton class.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's text.
setAsDefault = True
# <defaultText> - default text when "Restore Default" is clicked
defaultText = ""
def __init__(self, parent, label='',
text='', setAsDefault=True,
spanWidth=False):
"""
Appends a QPushButton widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left of (or above) the PushButton.
<text> - text displayed on the PushButton.
<setAsDefault> - if True, will restore <text> as the PushButton's text
when the "Restore Defaults" button is clicked.
<spanWidth> - if True, the PushButton and its label will span the width
of its groupbox. Its label will appear directly above
the ComboBox (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "PropMgrPushButton.__init__():"
print " label=",label
print " text =", text
print " setAsDefault =", setAsDefault
print " spanWidth =", spanWidth
if not parent:
return
QPushButton.__init__(self)
self.setObjectName(parent.objectName() +
"/pmPushButton" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Set text
self.setText(text)
# Set default text
self.defaultText=text
self.setAsDefault = setAsDefault
self.addWidgetAndLabelToParent(parent, label, spanWidth)
# End of PropMgrPushButton ############################
class PropMgrLineEdit(QLineEdit, PropMgrWidgetMixin):
"""PropMgr LineEdit class, for groupboxes (PropMgrGroupBox) only.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's value to val.
setAsDefault = True
defaultText = "" # Default value of lineedit
def __init__(self, parent, label='',
text='', setAsDefault=True,
spanWidth=False):
"""
Appends a QLineEdit widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left of (or above) the widget.
<text> - initial value of LineEdit widget.
<setAsDefault> - if True, will restore <val>
when the "Restore Defaults" button is clicked.
<spanWidth> - if True, the widget and its label will span the width
of its groupbox. Its label will appear directly above
the SpinBox (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "PropMgrLineEdit.__init__():"
print " label=", label
print " text =", text
print " setAsDefault =", setAsDefaultfix
print " spanWidth =", spanWidth
if not parent:
return
QLineEdit.__init__(self)
self.setObjectName(parent.objectName() +
"/pmLineEdit" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Set QLineEdit text
self.setText(text)
# Set default value
self.defaultText=text
self.setAsDefault = setAsDefault
self.addWidgetAndLabelToParent(parent, label, spanWidth)
# End of PropMgrLineEdit ############################
class PropMgrCheckBox(QCheckBox, PropMgrWidgetMixin):
"""PropMgr CheckBox class, for groupboxes (PropMgrGroupBox) only.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's value to val.
setAsDefault = True
defaultState = QtCore.Qt.Unchecked # Default state of CheckBox. Qt.Checked is checked.
def __init__(self, parent, label='',
isChecked=False, setAsDefault=True,
spanWidth=False, checkBoxText =''):
"""
Appends a QCheckBox widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left of (or above) the widget.
<isChecked> - can be True, False, or one of the Qt ToggleStates
True = checked
False = unchecked
<setAsDefault> - if True, will restore <val>
when the "Restore Defaults" button is clicked.
<spanWidth> - if True, the widget and its label will span the width
of its groupbox. Its label will appear directly above
the widget (unless the label is empty) left justified.
<checkBoxText> - Text for the checkbox itself. It always appears on the
right hand side of the checkbox
"""
if 0: # Debugging code
print "PropMgrCheckBox.__init__():"
print " label=", label
print " state =", state
print " setAsDefault =", setAsDefaultfix
print " spanWidth =", spanWidth
if not parent:
return
QCheckBox.__init__(self)
self.setObjectName(parent.objectName() +
"/pmCheckBox" +
str(parent.num_groupboxes) +
"/'" + label + "'")
self.setCheckState(isChecked, setAsDefault)
self.setText(checkBoxText)
self.addWidgetAndLabelToParent(parent, label, spanWidth)
def setCheckState(self, state, setAsDefault=True):
"""Set state of widget to <state>. If <setAsDefault> is True,
<state> becomes the default state for this widget so that
"Restore Defaults" will reset this widget to <state>.
<state> can be True, False, or one of the Qt ToggleStates
True = checked
False = unchecked
"""
# Set <state> to the appropriate Qt.ToggleState if True or False.
if state is True: state = Qt.Checked
if state is False: state = Qt.Unchecked
if setAsDefault:
self.setAsDefault=setAsDefault
self.defaultState=state
QCheckBox.setCheckState(self, state)
# End of PropMgrCheckBox ############################
class PropMgrListWidget(QListWidget, PropMgrWidgetMixin):
"""PropMgr ListWidget class, for groupboxes (PropMgrGroupBox) only.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's choice index to idx.
setAsDefault = True
# <defaultRow> - default row when "Restore Defaults" is clicked
defaultRow = 0
# <defaultItems> - list of items when "Restore Defaults" is clicked.
defaultItems = []
def __init__(self, parent, label='',
items=[], row=0, setAsDefault=True,
numRows=6, spanWidth=False):
"""
Appends a QListWidget widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears to the left of (or above) the ComboBox.
<items> - list of items (strings) to be inserted in the widget.
<row> - current row. (0=first item)
<setAsDefault> - if True, will restore <idx> as the current index
when the "Restore Defaults" button is clicked.
<numRows> - the number of rows to display. If <items> is
greater than <numRows>, a scrollbar will be displayed.
<spanWidth> - if True, the widget and its label will span the width
of its groupbox. Its label will appear directly above
the widget (unless the label is empty) left justified.
"""
if 0: # Debugging code
print "PropMgrListWidget.__init__():"
print " label=",label
print " items =", items
print " row =",row
print " setAsDefault =", setAsDefault
print " numRows =",numRows
print " spanWidth =", spanWidth
if not parent:
return
QListWidget.__init__(self)
self.setObjectName(parent.objectName() +
"/pmListWidget" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Load QComboBox widget choices and set initial choice (index).
#for choice in choices:
# self.addItem(choice)
self.insertItems(0, items, setAsDefault)
self.setCurrentRow(row, setAsDefault)
# Need setChoices() method
#self.defaultChoices=choices
# Set height
margin = self.fontMetrics().leading() * 2 # Mark 2007-05-28
height = numRows * self.fontMetrics().lineSpacing() + margin
self.setMaximumHeight(height)
self.addWidgetAndLabelToParent(parent, label, spanWidth)
def insertItems(self, row, items, setAsDefault=True):
"""Insert items of widget starting at <row>.
If <setAsDefault> is True, <items> become the default list of
items for this widget. "Restore Defaults" will reset
the list of items to <items>.
Note: <items> will always replace the list of current items
in the widget. <row> is ignored. This is considered a bug. Mark 2007-06-04
"""
if row <> 0:
msg = "PropMgrListWidget.insertItems(): <row> must be zero. See docstring for details:"
print_compact_traceback(msg)
return
if setAsDefault:
self.setAsDefault = setAsDefault
self.defaultItems=items
self.clear()
QListWidget.insertItems(self, row, items)
def setCurrentRow(self, row, setAsDefault=True):
"""Set current row of widget to <row>. If <setAsDefault> is True,
<row> becomes the default row for this widget so that
"Restore Defaults" will reset this widget to <row>.
"""
if setAsDefault:
self.setAsDefault = setAsDefault
self.defaultRow=row
QListWidget.setCurrentRow(self, row)
# End of PropMgrListWidget ############################
class PropMgrToolButton(QToolButton, PropMgrWidgetMixin):
"""PropMgr ToolButton class.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's text.
setAsDefault = True
# <defaultText> - default text when "Restore Default" is clicked
defaultText = ""
def __init__(self, parent, label='',
labelPlacement = 'left',
icon = None,
toolButtonStyle= 'iconOnly',
text='',
setAsDefault=True,
spanWidth=False):
"""
Appends a QToolButton widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<label> - label that appears at a position specified by <labelPlacement>
relative to the Toolbutton
<labelPlacement> - Placement of the <label> relative to ToolButton.
(left, right, top, bottom) --- NOT IMPLEMENTED YET
<icon> icon for the toolbutton
<toolButtonStyle> NOT IMPLEMENTED YET
<text> - text displayed on the ToolButton.
<setAsDefault> - if True, will restore <text> as the ToolButton's text
when the "Restore Defaults" button is clicked.
<spanWidth> - if True, the ToolButton and its label will span the width
of its groupbox. Its label will appear directly above
the ComboBox (unless the label is empty) left justified.
"""
if not parent:
return
QToolButton.__init__(self)
self.setObjectName(parent.objectName() +
"/pmToolButton" +
str(parent.num_groupboxes) +
"/'" + label + "'")
# Set text
self.setText(text)
# Set default text
self.defaultText=text
self.setAsDefault = setAsDefault
self.addWidgetAndLabelToParent(parent, label, spanWidth)
# End of PropMgrToolButton ############################
class PropMgrRadioButton(QRadioButton, PropMgrWidgetMixin):
"""PropMgr RadioButton class.
"""
# Set to True to always hide this widget, even when groupbox is expanded.
hidden = False
# Set setAsDefault to False if "Restore Defaults" should not
# reset this widget's text.
setAsDefault = True
# <defaultText> - default text when "Restore Default" is clicked
defaultText = ""
def __init__(self, parent,
text='',
setAsDefault=True,
spanWidth=True):
"""
Appends a QRadioButton widget to <parent>, a property manager groupbox.
Arguments:
<parent> - a property manager groupbox (PropMgrGroupBox).
<text> - text displayed on the RadioButton.
<setAsDefault> - if True, will restore <text> as the RadioButton's text
when the "Restore Defaults" button is clicked.
<spanWidth> - if True, the RadioButton will span the width
of its groupbox.
"""
if not parent:
return
QRadioButton.__init__(self)
label = ''
self.setObjectName(parent.objectName()+
"/pmRadioButton" +
str(parent.num_groupboxes) +
"/'" + label + "'")
self.setText(text)
# Set default text
self.defaultText=text
self.setAsDefault = setAsDefault
self.setCheckable(True)
self.addWidgetAndLabelToParent(parent, label, spanWidth)
# End of PropMgrRadioButton ############################
| NanoCAD-master | cad/src/outtakes/PropMgrBaseClass.py |
see also model/prefsTree.py
since then moved to outtakes
=====
from modelTree/TreeModel.py:
_DEBUG_PREFTREE = False # bruce 050602 experiment; do not commit with True
from end of get_topnodes in TreeModel
if _DEBUG_PREFTREE: #bruce 050602
try:
from foundation.Utility import Node
## print "reloading prefsTree"
import model.prefsTree as _X
reload(_X)
from model.prefsTree import prefsTree # constructor for an object which has a tree of nodes and controls them
self.pt = prefsTree(self.assy) # guess; guessing it's ok to remake it each time
ptnode = self.pt.topnode
assert ptnode is not None
assert isinstance(ptnode, Node)
topnodes.append(ptnode)
except:
print_compact_traceback("error importing prefsTree or making one: ")
from TreeModel.make_cmenuspec... just before copy, cut, delete
# Customize command [bruce 050602 experiment -- unfinished and commented out ###@@@]
# [later comment, bruce 050704: I think this was intended to suggest PrefsNodes applicable to the selected item or items,
# and to make them and group them with it. Or (later) to put up a dialog whose end result might be to do that.]
# Provide this when all items are in the same group? no, any items could be grouped...
# so for initial experiments, always provide it. If it's a submenu, the selected items might affect
# what's in it, and some things in it might be already checkmarked if PrefsNodes are above them ...
# for very initial experiment let's provide it only for single items.
# Do we ask them what can be customized about them? I guess so.
##unfinished...
## if _DEBUG_PREFTREE and len(nodeset) == 1:
## mspec = nodeset[0].customize_menuspec()
## submenu = []
======
from assembly.py
from model.prefsTree import MainPrefsGroupPart
in class Assembly:
prefs_node = None #bruce 050602; default value of instance variable; experimental
near end of topnode_partmaker_pairs:
if self.prefs_node is not None:
res.append(( self.prefs_node, MainPrefsGroupPart ))
near end of topnodes_with_own_parts
if self.prefs_node is not None:
res.append( self.prefs_node)
in valid_selgroup:
if not (self.root.is_ascendant(sg) or self.prefs_node is sg): #bruce 050602 kluge: added prefs_node
return False # can this ever happen??
| NanoCAD-master | cad/src/outtakes/prefsTree-in-other-files.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
BuildProtein_EditCommand.py
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
from command_support.EditCommand import EditCommand
from utilities.Log import greenmsg
from ne1_ui.toolbars.Ui_ProteinFlyout import ProteinFlyout
from protein.commands.BuildProtein.BuildProtein_PropertyManager import BuildProtein_PropertyManager
_superclass = EditCommand
class BuildProtein_EditCommand(EditCommand):
"""
BuildProtein_EditCommand provides a convenient way to edit or create
a Protein object
"""
#Property Manager
PM_class = BuildProtein_PropertyManager
#Flyout Toolbar
FlyoutToolbar_class = ProteinFlyout
cmd = greenmsg("Build Protein: ")
prefix = 'ProteinGroup' # used for gensym
cmdname = "Build Protein"
commandName = 'BUILD_PROTEIN'
featurename = "Build Protein"
from utilities.constants import CL_ENVIRONMENT_PROVIDING
command_level = CL_ENVIRONMENT_PROVIDING
command_should_resume_prevMode = False
command_has_its_own_PM = True
create_name_from_prefix = True
call_makeMenus_for_each_event = True
def runCommand(self):
"""
Overrides EditCommand.runCommand
"""
self.struct = None
self.existingStructForEditing = False
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
(and as of 2008-03-06, it is proposed that dna_updater calls this method
when needed.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
if not bool_keep:
if group is self.struct:
bool_keep = True
return bool_keep | NanoCAD-master | cad/src/outtakes/BuildProtein/BuildProtein_EditCommand.py |
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
BuildProtein_PropertyManager.py
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
History: Urmi initially copied from BuildDna_PropertyManager.py but this version
used for proteins is much more simple.
"""
import foundation.env as env
from PyQt4.Qt import SIGNAL
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_SpinBox import PM_SpinBox
from PM.PM_PushButton import PM_PushButton
from command_support.EditCommand_PM import EditCommand_PM
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_Constants import PM_CANCEL_BUTTON
from simulation.ROSETTA.rosetta_commandruns import checkIfProteinChunkInPart
_superclass = EditCommand_PM
class BuildProtein_PropertyManager(EditCommand_PM):
"""
The BuildDna_PropertyManager class provides a Property Manager
for the B{Build > Protein } command.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Build Protein"
pmName = title
#change this icon path later
iconPath = "ui/actions/Tools/Build Structures/Protein.png"
def __init__( self, command ):
"""
Constructor for the Build DNA property manager.
"""
self.current_protein = ""
self.sequenceEditor = command.win.createProteinSequenceEditorIfNeeded()
#see self.connect_or_disconnect_signals for comment about this flag
self.isAlreadyConnected = False
self.isAlreadyDisconnected = False
EditCommand_PM.__init__( self, command)
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_CANCEL_BUTTON | \
PM_WHATS_THIS_BUTTON)
def _updateProteinListForShow(self):
"""
Update the list of proteins in the combo box in the PM.
"""
#first remove from combo box all the proteins that do not exist in NE-1
#part anymore
currentProteinNameList = []
for mol in self.win.assy.molecules:
currentProteinNameList.append(mol.name)
for name in self.protein_name_list:
try:
index = currentProteinNameList.index(name)
except ValueError:
#protein does not exist any more, need to remove it
i = self.protein_name_list.index(name)
self.protein_chunk_list.pop(i)
self.protein_name_list.pop(i)
j = self.structureComboBox.findText(name)
self.structureComboBox.removeItem(j)
for mol in self.win.assy.molecules:
#if molecules does not already exist in combo box list, need to add
#them
if mol.isProteinChunk():
try:
self.protein_name_list.index(mol.name)
except ValueError:
self.protein_chunk_list.append(mol)
self.protein_name_list.append(mol.name)
self.structureComboBox.addItem(mol.name)
return
def show(self):
"""
Overrides superclass show method
"""
env.history.statusbar_msg("")
self._updateProteinListForShow()
self._showProteinParametersAndSequenceEditor()
EditCommand_PM.show(self)
self.updateMessage()
return
def close(self):
"""
Overrides superclass close method
"""
self.sequenceEditor.hide()
env.history.statusbar_msg("")
EditCommand_PM.close(self)
return
def _updateProteinList(self):
"""
Update the list of proteins so that the protein name combo box in this
PM can be populated.
"""
self.protein_chunk_list = []
self.protein_name_list = []
for mol in self.win.assy.molecules:
if mol.isProteinChunk():
self.protein_chunk_list.append(mol)
self.protein_name_list.append(mol.name)
return
def _showProteinParametersAndSequenceEditor(self):
"""
Show/ Hide protein parameters and sequence editor based on if there's
any protein in NE-1 part.
"""
part = self.win.assy.part
proteinExists, proteinChunk = checkIfProteinChunkInPart(part)
if proteinExists:
#check to see if current_protein is still in part, otherwise set
# this to first available protein
try:
index = self.structureComboBox.findText(self.current_protein)
index1 = self.protein_name_list.index(self.current_protein)
except ValueError:
index = 0
index1 = 0
self.set_current_protein_chunk_name(self.protein_name_list[index1])
self.structureComboBox.setCurrentIndex(index)
proteinChunk = self.protein_chunk_list[index1]
self._numberOfAA = len(proteinChunk.protein.get_sequence_string())
else:
#remove all items from the combo box
count = self.structureComboBox.count()
for i in range(count):
self.structureComboBox.removeItem(0)
self._numberOfAA = 0
self.set_current_protein_chunk_name("")
self.numberOfAASpinBox.setValue(self._numberOfAA)
#get the sequence for this protein chunk
if proteinExists:
sequence = proteinChunk.protein.get_sequence_string()
self.sequenceEditor.setSequence(sequence)
secStructure = proteinChunk.protein.get_secondary_structure_string()
self.sequenceEditor.setSecondaryStructure(secStructure)
self.sequenceEditor.setRuler(len(secStructure))
self.editPropertiesPushButton.setEnabled(True)
else:
self.editPropertiesPushButton.setEnabled(False)
self.sequenceEditor.hide()
return
def connect_or_disconnect_signals(self, isConnect):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
"""
if isConnect and self.isAlreadyConnected:
return
if not isConnect and self.isAlreadyDisconnected:
return
self.isAlreadyConnected = isConnect
self.isAlreadyDisconnected = not isConnect
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.structureComboBox,
SIGNAL("currentIndexChanged(int)"),
self._updateProteinParameters)
change_connect(self.editPropertiesPushButton,
SIGNAL("clicked()"),
self._showSeqEditor)
def _showSeqEditor(self):
"""
Show sequence editor
"""
if self.editPropertiesPushButton.isEnabled():
self.sequenceEditor.show()
return
def _updateProteinParameters(self, index):
"""
Update number of amino acids and sequence editor, as well as set the
current protein pdb id which will be used in the child commands and for
rosetta simulation from inside the build protein mode.
@param index: index of the protein combo box
@type index: int
"""
for mol in self.protein_chunk_list:
if mol.name == self.structureComboBox.currentText():
self._numberOfAA = len(mol.protein.get_sequence_string())
self.numberOfAASpinBox.setValue(self._numberOfAA)
sequence = mol.protein.get_sequence_string()
self.sequenceEditor.setSequence(sequence)
secStructure = mol.protein.get_secondary_structure_string()
self.sequenceEditor.setSecondaryStructure(secStructure)
self.sequenceEditor.setRuler(len(secStructure))
break
self.set_current_protein_chunk_name(mol.name)
env.history.statusbar_msg("")
return
def set_current_protein_chunk_name(self, name):
"""
Sets the current protein name
@param name: pdb id of the protein currently selected in the combo box
@type name: str
"""
self.current_protein = name
return
def get_current_protein_chunk_name(self):
"""
gets the current protein name
@return: pdb id of the protein currently selected in the combo box
"""
return self.current_protein
def enable_or_disable_gui_actions(self, bool_enable = False):
"""
Enable or disable some gui actions when this property manager is
opened or closed, depending on the bool_enable.
@param bool_enable: enables/disables some gui action
@type bool_enable: bool
"""
if hasattr(self.command, 'flyoutToolbar') and \
self.command.flyoutToolbar:
self.command.flyoutToolbar.exitProteinAction.setEnabled(not bool_enable)
def _addWhatsThisText( self ):
"""
What's This text for widgets in the DNA Property Manager.
"""
pass
def _addToolTipText(self):
"""
Tool Tip text for widgets in the DNA Property Manager.
"""
pass
def _addGroupBoxes(self):
"""
Add the DNA Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox(self, title = "Parameters")
self._loadGroupBox1(self._pmGroupBox1)
return
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box 1.
@param pmGroupBox: group box that contains protein name combo box and
number of amino acids spin box
@see: L{PM_GroupBox}
"""
self._updateProteinList()
if len(self.protein_name_list) >= 1:
self.set_current_protein_chunk_name(self.protein_name_list[0])
self.structureComboBox = PM_ComboBox( pmGroupBox,
label = "Name:",
choices = self.protein_name_list,
setAsDefault = False)
#Urmi 20080713: May be useful to set the minimum value to not zero
#Now it does not matter, since its disabled. But zero as the minimum
#value in a spinbox does not work otherwise.
self.numberOfAASpinBox = \
PM_SpinBox( pmGroupBox,
label = "Amino Acids:",
value = 0,
setAsDefault = False,
minimum = 0,
maximum = 10000 )
#for now we do not allow changing number of residues
self.numberOfAASpinBox.setEnabled(False)
self.editPropertiesPushButton = PM_PushButton( pmGroupBox,
text = "Edit Sequence",
setAsDefault = True
)
| NanoCAD-master | cad/src/outtakes/BuildProtein/BuildProtein_PropertyManager.py |
NanoCAD-master | cad/src/outtakes/BuildProtein/__init__.py |
|
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details.
"""
$Id$
History:
Mark 2007-05-18: Implemented Nanotube generator dialog using PropMgrBaseClass.
Mark 2007-08-06: Renamed NanotubeGeneratorDialog to NanotubeGeneratorPropertyManager.
"""
import math
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import SIGNAL
from PM.PM_Dialog import PM_Dialog
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_SpinBox import PM_SpinBox
from model.bonds import CC_GRAPHITIC_BONDLENGTH, BN_GRAPHITIC_BONDLENGTH
from utilities.debug import print_compact_traceback
ntBondLengths = [CC_GRAPHITIC_BONDLENGTH, BN_GRAPHITIC_BONDLENGTH]
class NanotubeGeneratorPropertyManager(PM_Dialog):
"""
The NanotubeGeneratorPropertyManager class provides a Property Manager
for the "Build > Nanotube" command.
"""
# The title that appears in the property manager header.
title = "Nanotube"
# The name of this property manager. This will be set to
# the name of the PropMgr (this) object via setObjectName().
pmName = title
# The relative path to PNG file that appears in the header.
iconPath = "ui/actions/Tools/Build Structures/Nanotube.png"
def __init__(self):
"""Construct the Graphene Property Manager.
"""
PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)
#@self.addGroupBoxes()
#@self.add_whats_this_text()
self.updateMessageGroupBox()
def updateMessageGroupBox(self):
msg = ""
# A (4, 4) tube is stable, but a (3, 3) has not been seen in
# isolation. Circumference of a (4, 4) tube is about 6.93.
xOffset = self.n + self.m * math.cos(math.pi/3.0)
yOffset = self.m * math.sin(math.pi/3.0)
circumference = math.sqrt(xOffset * xOffset + yOffset * yOffset)
if (circumference < 6.5):
msg = "Warning: Small diameter nanotubes may be unstable, \
and may give unexpected results when minimized.<p>"
msg = msg + "Edit the Nanotube parameters and select <b>Preview</b> to \
preview the structure. Click <b>Done</b> to insert it into the model."
# This causes the "Message" box to be displayed as well.
# setAsDefault=True causes this message to be reset whenever
# this PropMgr is (re)displayed via show(). Mark 2007-06-01.
self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True)
def _addGroupBoxes(self):
"""
Add the 3 group boxes to the Nanotube Property Manager dialog.
"""
self.pmGroupBox1 = \
PM_GroupBox( self,
title = "Nanotube Parameters" )
self.pmGroupBox2 = \
PM_GroupBox( self,
title = "Nanotube Distortion" )
self.pmGroupBox3 = \
PM_GroupBox( self,
title = "Multi-Walled Nanotubes" )
# Add group box widgets.
self._loadGroupBox1(self.pmGroupBox1)
self._loadGroupBox2(self.pmGroupBox2)
self._loadGroupBox3(self.pmGroupBox3)
def _loadGroupBox1(self, inPmGroupBox):
"""
Load widgets in group box 1.
"""
memberChoices = ["Carbon", "Boron Nitride"]
self.typeComboBox= \
PM_ComboBox( inPmGroupBox,
label = "Type :",
choices = memberChoices,
index = 0,
setAsDefault = True,
spanWidth = False )
self.connect( self.typeComboBox,
SIGNAL("currentIndexChanged(int)"),
self.nt_type_changed)
self.lengthField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "Length :",
value = 20.0,
setAsDefault = True,
minimum = 1.0,
maximum = 1000.0,
singleStep = 1.0,
decimals = 3,
suffix = " Angstroms" )
self.n = 5
self.chiralityNSpinBox = \
PM_SpinBox( inPmGroupBox,
label = "Chirality (n) :",
value = self.n,
setAsDefault = True )
self.connect(self.chiralityNSpinBox,
SIGNAL("valueChanged(int)"),
self.chirality_fixup)
self.m = 5
self.chiralityMSpinBox = \
PM_SpinBox( inPmGroupBox,
label = "Chirality (m) :",
value = self.m,
setAsDefault = True )
self.connect(self.chiralityMSpinBox,
SIGNAL("valueChanged(int)"),
self.chirality_fixup)
self.bondLengthField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "Bond Length :",
value = CC_GRAPHITIC_BONDLENGTH,
setAsDefault = True,
minimum = 1.0,
maximum = 3.0,
singleStep = 0.1,
decimals = 3,
suffix = " Angstroms" )
endingChoices = ["None", "Hydrogen", "Nitrogen"]
self.endingsComboBox= \
PM_ComboBox( inPmGroupBox,
label = "Endings :",
choices = endingChoices,
index = 0,
setAsDefault = True,
spanWidth = False )
def _loadGroupBox2(self, inPmGroupBox):
"""
Load widgets in group box 2.
"""
self.zDistortionField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "Z-distortion :",
value = 0.0,
setAsDefault = True,
minimum = 0.0,
maximum = 10.0,
singleStep = 0.1,
decimals = 3,
suffix = " Angstroms" )
self.xyDistortionField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "XY-distortion :",
value = 0.0,
setAsDefault = True,
minimum = 0.0,
maximum = 2.0,
singleStep = 0.1,
decimals = 3,
suffix = " Angstroms" )
self.twistSpinBox = \
PM_SpinBox( inPmGroupBox,
label = "Twist :",
value = 0,
setAsDefault = True,
minimum = 0,
maximum = 100, # What should maximum be?
suffix = " deg/A" )
self.bendSpinBox = \
PM_SpinBox( inPmGroupBox,
label = "Bend :",
value = 0,
setAsDefault = True,
minimum = 0,
maximum = 360,
suffix = " deg" )
def _loadGroupBox3(self, inPmGroupBox):
"""
Load widgets in group box 3.
"""
# "Number of Nanotubes" SpinBox
self.mwntCountSpinBox = \
PM_SpinBox( inPmGroupBox,
label = "Number :",
value = 1,
setAsDefault = True,
minimum = 1,
maximum = 10,
suffix = " nanotubes" )
self.mwntCountSpinBox.setSpecialValueText("SWNT")
# "Spacing" lineedit.
self.mwntSpacingField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "Spacing :",
value = 2.46,
setAsDefault = True,
minimum = 1.0,
maximum = 10.0,
singleStep = 0.1,
decimals = 3,
suffix = " Angstroms" )
def _addWhatsThisText(self):
"""
What's This text for widgets in this Property Manager.
"""
from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_NanotubeGeneratorPropertyManager
whatsThis_NanotubeGeneratorPropertyManager(self)
def _addToolTipText(self):
"""
Tool Tip text for widgets in this Property Manager.
"""
from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_NanotubeGeneratorPropertyManager
ToolTip_NanotubeGeneratorPropertyManager(self)
def chirality_fixup(self, spinBoxValueJunk = None):
"""
Slot for several validators for different parameters.
This gets called each time a user types anything into a widget or
changes a spinbox.
@param spinBoxValueJunk: This is the Spinbox value from the valueChanged
signal. It is not used. We just want to know
that the spinbox value has changed.
@type spinBoxValueJunk: double or None
"""
if not hasattr(self, 'n'):
print_compact_traceback("Bug: no attr 'n' ") # mark 2007-05-24
return
n_previous = int(self.n)
m_previous = int(self.m)
n = self.chiralityNSpinBox.value()
m = self.chiralityMSpinBox.value()
# Two restrictions to maintain
# n >= 2
# 0 <= m <= n
if n < 2:
n = 2
if m != self.m:
# The user changed m. If m became larger than n, make n bigger.
if m > n:
n = m
elif n != self.n:
# The user changed n. If n became smaller than m, make m smaller.
if m > n:
m = n
self.chiralityNSpinBox.setValue(n)
self.chiralityMSpinBox.setValue(m)
self.m, self.n = m, n
self.updateMessageGroupBox()
def nt_type_changed(self, idx):
"""
Slot for Nanotube Type combobox.
Update the bond length field when the type changes.
"""
self.bondLengthField.setValue(ntBondLengths[idx])
| NanoCAD-master | cad/src/outtakes/InsertNanotube/NanotubeGeneratorPropertyManager.py |
NanoCAD-master | cad/src/outtakes/InsertNanotube/__init__.py |
|
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
NanotubeGenerator.py
@author: Will
@version: $Id$
@copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details.
@see http://www.nanoengineer-1.net/mediawiki/index.php?title=Nanotube_generator_dialog
for notes about what's going on here.
"""
from math import atan2, sin, cos, pi, asin
from Numeric import dot
from geometry.VQT import vlen, cross, norm, V
import foundation.env as env
from utilities import debug_flags
from utilities.debug import Stopwatch
from model.chem import Atom
from model.chunk import Chunk
from model.elements import PeriodicTable
from model.bonds import bond_atoms
from geometry.NeighborhoodGenerator import NeighborhoodGenerator
from model.bond_constants import V_GRAPHITE, V_SINGLE
##from bonds_from_atoms import make_bonds
##from buckyball import BuckyBall
from model.bond_constants import atoms_are_bonded
from commands.InsertNanotube.NanotubeGeneratorPropertyManager import NanotubeGeneratorPropertyManager
from command_support.GeneratorBaseClass import GeneratorBaseClass
from utilities.Log import orangemsg, greenmsg ##, redmsg
sqrt3 = 3 ** 0.5
class Chirality:
def __init__(self, n, m, bond_length):
self.bond_length = bond_length
self.maxlen = maxlen = 1.2 * bond_length
self.maxlensq = maxlen**2
self.n, self.m = n, m
x = (n + 0.5 * m) * sqrt3
y = 1.5 * m
angle = atan2(y, x)
twoPiRoverA = (x**2 + y**2) ** .5
AoverR = (2 * pi) / twoPiRoverA
self.__cos = cos(angle)
self.__sin = sin(angle)
# time to get the constants
s, t = self.x1y1(0,0)
u, v = self.x1y1(1./3, 1./3)
w, x = self.x1y1(0,1)
F = (t - v)**2
G = 2 * (1 - cos(AoverR * (s - u)))
H = (v - x)**2
J = 2 * (1 - cos(AoverR * (u - w)))
denom = F * J - G * H
self.R = (bond_length**2 * (F - H) / denom) ** .5
self.B = (bond_length**2 * (J - G) / denom) ** .5
self.A = self.R * AoverR
def x1y1(self, n, m):
c, s = self.__cos, self.__sin
x = (n + .5*m) * sqrt3
y = 1.5 * m
x1 = x * c + y * s
y1 = -x * s + y * c
return (x1, y1)
def mlimits(self, z3min, z3max, n):
if z3max < z3min:
z3min, z3max = z3max, z3min
B, c, s = self.B, self.__cos, self.__sin
P = sqrt3 * B * s
Q = 1.5 * B * (c - s / sqrt3)
m1, m2 = (z3min + P * n) / Q, (z3max + P * n) / Q
return int(m1-1.5), int(m2+1.5) # REVIEW: should this use intRound?
def xyz(self, n, m):
x1, y1 = self.x1y1(n, m)
x2, y2 = self.A * x1, self.B * y1
R = self.R
x3 = R * sin(x2/R)
y3 = R * cos(x2/R)
z3 = y2
return (x3, y3, z3)
def populate(self, mol, length, bn_members = False):
def add(element, x, y, z, atomtype='sp2'):
atm = Atom(element, V(x, y, z), mol)
atm.set_atomtype_but_dont_revise_singlets(atomtype)
return atm
evenAtomDict = { }
oddAtomDict = { }
bondDict = { }
mfirst = [ ]
mlast = [ ]
for n in range(self.n):
mmin, mmax = self.mlimits(-.5 * length, .5 * length, n)
mfirst.append(mmin)
mlast.append(mmax)
for m in range(mmin, mmax+1):
x, y, z = self.xyz(n, m)
if bn_members:
atm = add("B", x, y, z)
else:
atm = add("C", x, y, z)
evenAtomDict[(n,m)] = atm
bondDict[atm] = [(n,m)]
x, y, z = self.xyz(n+1./3, m+1./3)
if bn_members:
atm = add("N", x, y, z, 'sp3')
else:
atm = add("C", x, y, z)
oddAtomDict[(n,m)] = atm
bondDict[atm] = [(n+1, m), (n, m+1)]
# m goes axially along the nanotube, n spirals around the tube
# like a barber pole, with slope depending on chirality. If we
# stopped making bonds now, there'd be a spiral strip of
# missing bonds between the n=self.n-1 row and the n=0 row.
# So we need to connect those. We don't know how the m values
# will line up, so the first time, we need to just hunt for the
# m offset. But then we can apply that constant m offset to the
# remaining atoms along the strip.
n = self.n - 1
mmid = (mfirst[n] + mlast[n]) / 2
atm = oddAtomDict[(n, mmid)]
class FoundMOffset(Exception): pass
try:
for m2 in range(mfirst[0], mlast[0] + 1):
atm2 = evenAtomDict[(0, m2)]
diff = atm.posn() - atm2.posn()
if dot(diff, diff) < self.maxlensq:
moffset = m2 - mmid
# Given the offset, zipping up the rows is easy.
for m in range(mfirst[n], mlast[n]+1):
atm = oddAtomDict[(n, m)]
bondDict[atm].append((0, m + moffset))
raise FoundMOffset()
# If we get to this point, we never found m offset.
# If this ever happens, it indicates a bug.
raise Exception, "can't find m offset"
except FoundMOffset:
pass
# Use the bond information to bond the atoms
for (dict1, dict2) in [(evenAtomDict, oddAtomDict),
(oddAtomDict, evenAtomDict)]:
for n, m in dict1.keys():
atm = dict1[(n, m)]
for n2, m2 in bondDict[atm]:
try:
atm2 = dict2[(n2, m2)]
if not atoms_are_bonded(atm, atm2):
if bn_members:
bond_atoms(atm, atm2, V_SINGLE)
else:
bond_atoms(atm, atm2, V_GRAPHITE)
except KeyError:
pass
####################################################################
# Endcaps
def addEndcap(mol, length, radius, bondlength):
sphere_center = V(0, length / 2, 0)
def walk_great_circle(P, Q, D, R=radius):
"""Given two points P and Q on or near the surface of the
sphere, use P and Q to define a great circle. Then walk along
that great circle starting at P and going in the direction of
Q, and traveling far enough the chord is of length D. P and Q
are not required to lie exactly on the sphere's surface.
"""
dP, dQ = P - sphere_center, Q - sphere_center
dPs = cross(cross(dP, dQ), dP)
cpart, spart = norm(dP), norm(dPs)
theta = 2 * asin(0.5 * D / R)
return sphere_center + R * (cpart * cos(theta) + spart * sin(theta))
def projectOntoSphere(v, R=radius):
dv = v - sphere_center
dvlen = vlen(dv)
return sphere_center + (R / dvlen) * dv
def cleanupSinglets(atm):
for s in atm.singNeighbors():
s.kill()
atm.make_enough_bondpoints()
def addCarbons(chopSpace, R=radius):
# a buckyball has no more than about 6*r**2 atoms, r in angstroms
# each cap is ideally a half-buckyball
for i in range(int(3.0 * R**2)):
regional_singlets = filter(lambda atm: chopSpace(atm) and atm.is_singlet(),
mol.atoms.values())
for s in regional_singlets:
s.setposn(projectOntoSphere(s.posn()))
if len(regional_singlets) < 3:
# there won't be anything to bond to anyway, let the user
# manually adjust the geometry
return
singlet_pair = None
try:
for s1 in regional_singlets:
s1p = s1.posn()
for s2 in regional_singlets:
if s2.key > s1.key and \
vlen(s2.posn() - s1p) < bondlength:
singlet_pair = (s1, s2)
# break out of both for-loops
raise Exception
except:
pass
if singlet_pair is not None:
# if there is an existing pair of singlets that's close than one bond
# length, use those to make the newguy, so he'll have one open bond left
sing1, sing2 = singlet_pair
owner1, owner2 = sing1.realNeighbors()[0], sing2.realNeighbors()[0]
newpos1 = walk_great_circle(owner1.posn(), sing1.posn(), bondlength)
newpos2 = walk_great_circle(owner2.posn(), sing2.posn(), bondlength)
newpos = 0.5 * (newpos1 + newpos2)
regional_singlets.remove(sing1)
regional_singlets.remove(sing2)
else:
# otherwise choose any pre-existing bond and stick the newguy on him
# prefer a bond whose real atom already has two real neighbors
preferred = filter(lambda atm: len(atm.realNeighbors()[0].realNeighbors()) == 2,
regional_singlets)
if preferred:
sing = preferred[0]
else:
sing = regional_singlets[0]
owner = sing.realNeighbors()[0]
newpos = walk_great_circle(owner.posn(), sing.posn(), bondlength)
regional_singlets.remove(sing)
ngen = NeighborhoodGenerator(mol.atoms.values(), 1.1 * bondlength)
# do not include new guy in neighborhood, add him afterwards
newguy = Atom('C', newpos, mol)
newguy.set_atomtype('sp2')
# if the new atom is close to an older atom, merge them: kill the newer
# atom, give the older one its neighbors, nudge the older one to the midpoint
for oldguy in ngen.region(newpos):
if vlen(oldguy.posn() - newpos) < 0.4:
newpos = 0.5 * (newguy.posn() + oldguy.posn())
newguy.setposn(newpos)
ngen.remove(oldguy)
oldguy.kill()
break
# Bond with anybody close enough. The newer make_bonds
# code doesn't seem to handle this usage very well.
for oldguy in ngen.region(newpos):
r = oldguy.posn() - newpos
rlen = vlen(r)
if (len(newguy.realNeighbors()) < 3 and rlen < 1.1 * bondlength):
if rlen < 0.7 * bondlength:
# nudge them apart
nudge = ((0.7 * bondlength - rlen) / rlen) * r
oldguy.setposn(oldguy.posn() + 0.5 * r)
newguy.setposn(newguy.posn() - 0.5 * r)
bond_atoms(newguy, oldguy, V_GRAPHITE)
cleanupSinglets(newguy)
cleanupSinglets(oldguy)
if len(newguy.realNeighbors()) > 3:
print 'warning: too many bonds on newguy'
# Try moving the new guy around to make his bonds closer to bondlength but
# keep him on or near the surface of the sphere. Use Newton's method in
# three dimensions.
def error(posn):
e = (vlen(posn - sphere_center) - radius) ** 2
for atm in newguy.realNeighbors():
e += (vlen(atm.posn() - posn) - bondlength)**2
return e
p = newguy.posn()
for i in range(2):
h = 1.0e-4
e0 = error(p)
gradient = V((error(p + V(h, 0, 0)) - e0) / h,
(error(p + V(0, h, 0)) - e0) / h,
(error(p + V(0, 0, h)) - e0) / h)
p = p - (e0 / vlen(gradient)**2) * gradient
newguy.setposn(p)
# we may need to reposition singlets
for atm in ngen.region(newguy.posn()):
cleanupSinglets(atm)
cleanupSinglets(newguy)
def is_north(atm):
return atm.posn()[1] > length / 2 - 3.0
def is_south(atm):
return atm.posn()[1] < -length / 2 + 3.0
# great circles now computed for the north end
sphere_center = V(0, length / 2, 0)
addCarbons(is_north)
# great circles now computed for the south end
sphere_center = V(0, -length / 2, 0)
addCarbons(is_south)
env.history.message(orangemsg('Nanotube endcap generation is an inexact science. ' +
'Manual touch-up will be required.'))
#################################################################
class NanotubeGenerator(NanotubeGeneratorPropertyManager, GeneratorBaseClass):
"""
The Nanotube Generator class for the "Build > Nanotube" command.
"""
cmd = greenmsg("Build Nanotube: ")
prefix = 'Nanotube' # used for gensym
# Generators for DNA, nanotubes and graphene have their MT name generated
# (in GeneratorBaseClass) from the prefix.
create_name_from_prefix = True
# We now support multiple keywords in a list or tuple
# sponsor_keyword = ('Nanotubes', 'Carbon')
sponsor_keyword = 'Nanotubes'
# pass window arg to constructor rather than use a global, wware 051103
def __init__(self, win):
NanotubeGeneratorPropertyManager.__init__(self)
GeneratorBaseClass.__init__(self, win)
###################################################
# How to build this kind of structure, along with
# any necessary helper functions
def gather_parameters(self):
"""
Return all the parameters from the Property Manager dialog.
"""
n = self.chiralityNSpinBox.value()
m = self.chiralityMSpinBox.value()
self.length = length = self.lengthField.value()
self.bond_length = bond_length = self.bondLengthField.value()
self.zdist = zdist = self.zDistortionField.value()
self.xydist = xydist = self.xyDistortionField.value()
self.spacing = spacing = self.mwntSpacingField.value()
twist = pi * self.twistSpinBox.value() / 180.0
bend = pi * self.bendSpinBox.value() / 180.0
members = self.typeComboBox.currentIndex()
endings = self.endingsComboBox.currentText()
if endings == "Capped" and not debug_flags.atom_debug:
raise Exception('Nanotube endcaps not implemented yet.')
numwalls = self.mwntCountSpinBox.value()
return (length, n, m, bond_length, zdist, xydist,
twist, bend, members, endings, numwalls, spacing)
def build_struct(self, name, params, position, mol=None, createPrinted=False):
"""
Build a nanotube from the parameters in the Property Manger dialog.
"""
length, n, m, bond_length, zdist, xydist, \
twist, bend, members, endings, numwalls, spacing = params
# This can take a few seconds. Inform the user.
# 100 is a guess on my part. Mark 051103.
if not createPrinted:
# If it's a multi-wall tube, only print the "Creating" message once.
if length > 100.0:
env.history.message(self.cmd + "This may take a moment...")
self.chirality = Chirality(n, m, bond_length)
PROFILE = False
if PROFILE:
sw = Stopwatch()
sw.start()
xyz = self.chirality.xyz
if mol == None:
mol = Chunk(self.win.assy, name)
atoms = mol.atoms
mlimits = self.chirality.mlimits
# populate the tube with some extra carbons on the ends
# so that we can trim them later
self.chirality.populate(mol, length + 4 * self.chirality.maxlen, members != 0)
# Apply twist and distortions. Bends probably would come
# after this point because they change the direction for the
# length. I'm worried about Z distortion because it will work
# OK for stretching, but with compression it can fail. BTW,
# "Z distortion" is a misnomer, we're stretching in the Y
# direction.
for atm in atoms.values():
# twist
x, y, z = atm.posn()
twistRadians = twist * z
c, s = cos(twistRadians), sin(twistRadians)
x, y = x * c + y * s, -x * s + y * c
atm.setposn(V(x, y, z))
for atm in atoms.values():
# z distortion
x, y, z = atm.posn()
z *= (zdist + length) / length
atm.setposn(V(x, y, z))
length += zdist
for atm in atoms.values():
# xy distortion
x, y, z = atm.posn()
radius = self.chirality.R
x *= (radius + 0.5 * xydist) / radius
y *= (radius - 0.5 * xydist) / radius
atm.setposn(V(x, y, z))
# Judgement call: because we're discarding carbons with funky
# valences, we will necessarily get slightly more ragged edges
# on nanotubes. This is a parameter we can fiddle with to
# adjust the length. My thought is that users would prefer a
# little extra length, because it's fairly easy to trim the
# ends, but much harder to add new atoms on the end.
LENGTH_TWEAK = bond_length
# trim all the carbons that fall outside our desired length
# by doing this, we are introducing new singlets
for atm in atoms.values():
x, y, z = atm.posn()
if (z > .5 * (length + LENGTH_TWEAK) or
z < -.5 * (length + LENGTH_TWEAK)):
atm.kill()
# Apply bend. Equations are anomalous for zero bend.
if abs(bend) > pi / 360:
R = length / bend
for atm in atoms.values():
x, y, z = atm.posn()
theta = z / R
x, z = R - (R - x) * cos(theta), (R - x) * sin(theta)
atm.setposn(V(x, y, z))
def trimCarbons():
# trim all the carbons that only have one carbon neighbor
for i in range(2):
for atm in atoms.values():
if not atm.is_singlet() and len(atm.realNeighbors()) == 1:
atm.kill()
trimCarbons()
# if we're not picky about endings, we don't need to trim carbons
if endings == "Capped":
# buckyball endcaps
addEndcap(mol, length, self.chirality.R)
if endings == "Hydrogen":
# hydrogen terminations
for atm in atoms.values():
atm.Hydrogenate()
elif endings == "Nitrogen":
# nitrogen terminations
dstElem = PeriodicTable.getElement('N')
atomtype = dstElem.find_atomtype('sp2')
for atm in atoms.values():
if len(atm.realNeighbors()) == 2:
atm.Transmute(dstElem, force=True, atomtype=atomtype)
# Translate structure to desired position
for atm in atoms.values():
v = atm.posn()
atm.setposn(v + position)
if PROFILE:
t = sw.now()
env.history.message(greenmsg("%g seconds to build %d atoms" %
(t, len(atoms.values()))))
if numwalls > 1:
n += int(spacing * 3 + 0.5) # empirical tinkering
params = (length, n, m, bond_length, zdist, xydist,
twist, bend, members, endings, numwalls-1, spacing)
self.build_struct(name, params, position, mol=mol, createPrinted=True)
return mol
pass
# end
| NanoCAD-master | cad/src/outtakes/InsertNanotube/NanotubeGenerator.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
DnaGenerator.py
WARNING: this file has been mostly superseded by DnaDuplexGenerator.py.
@author: Will Ware
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
History:
Jeff 2007-06-13:
- Moved Dna class (and subclasses) to file Dna.py
[subsequently renamed DnaGenHelper.py].
Mark 2007-08-23:
- Heavily restructured and cleaned up.
Mark 2007-10-18:
- Did a major rewrite of this module, superseding it --
DnaDuplexGenerator.py.
"""
# To do:
# 1) Use two endpoints to create an arbitrarily positioned duplex.
# 2) Remove support for Atomistic DNA models.
import foundation.env as env
import random
from utilities.constants import darkred, blue, lightgray
from foundation.Group import Group
from utilities.Log import redmsg, greenmsg ##, orangemsg
from geometry.VQT import Q, V, angleBetween, cross, vlen, Veq
from math import pi
from model.chunk import Chunk
from utilities.constants import gensym
from dna.model.Dna_Constants import basesDict, getReverseSequence
from dna.commands.BuildDuplex_old.DnaGenHelper import B_Dna_PAM3, B_Dna_PAM5
from dna.commands.BuildDuplex_old.DnaGenHelper import basepath_ok
from command_support.GeneratorBaseClass import GeneratorBaseClass
from utilities.exception_classes import CadBug, PluginBug, UserError
from dna.commands.BuildDuplex_old.DnaGeneratorPropertyManager import DnaGeneratorPropertyManager
############################################################################
# DnaGeneratorPropertyManager must come BEFORE GeneratorBaseClass in this list
class DnaGenerator(DnaGeneratorPropertyManager, GeneratorBaseClass):
cmd = greenmsg("Build DNA: ")
sponsor_keyword = 'DNA'
prefix = 'Dna' # used for gensym
# Generators for DNA, nanotubes and graphene have their MT name
# generated (in GeneratorBaseClass) from the prefix.
create_name_from_prefix = True
# pass window arg to constructor rather than use a global, wware 051103
def __init__(self, win):
DnaGeneratorPropertyManager.__init__(self)
GeneratorBaseClass.__init__(self, win)
self._random_data = []
# ##################################################
# How to build this kind of structure, along with
# any necessary helper functions.
def change_random_seed(self):
if 0:
print "change_random_seed() called."
self._random_data = []
def _random_data_for_index(self, inIndex):
while len( self._random_data ) < (inIndex + 1):
self._random_data.append( random.randrange(12) )
return self._random_data[inIndex]
def gather_parameters(self):
"""
Return the parameters from the property manager UI.
@return: All the parameters:
- dnaSequence
- dnaType
- basesPerTurn
- chunkOption
@rtype: tuple
"""
if not basepath_ok:
raise PluginBug("The cad/plugins/DNA directory is missing.")
dnaModel = str(self.modelComboBox.currentText())
dnaType = str(self.conformationComboBox.currentText())
assert dnaType in ('B-DNA')
# Get bases per turn.
basesPerTurnString = str(self.basesPerTurnComboBox.currentText())
basesPerTurn = float(basesPerTurnString)
chunkOption = str(self.createComboBox.currentText())
resolve_random = False
# Later this flag may depend on a new checkbox in that case;
# for now it doesn't matter, since sequence info is
# discarded for reduced bases anyway.
(dnaSequence, allKnown) = \
self._getSequence( resolve_random = resolve_random)
x1 = self.x1SpinBox.value()
y1 = self.y1SpinBox.value()
z1 = self.z1SpinBox.value()
x2 = self.x2SpinBox.value()
y2 = self.y2SpinBox.value()
z2 = self.z2SpinBox.value()
endpoint1 = V(x1, y1, z1)
endpoint2 = V(x2, y2, z2)
return (dnaSequence,
dnaModel,
dnaType,
basesPerTurn,
chunkOption,
endpoint1,
endpoint2)
def checkParameters( self, inParams ):
"""
Verify that the strand sequence contains no unknown/invalid bases.
"""
theSequence, isValid = self._getSequence()
return isValid
# This is never called, which is good, because neither result, nor
# choice is defined anywhere
#def correctParameters( self, inParams):
# """
# Alert the user that the entered sequence is invalid. Give them
# some options for how to correct the sequence.
# """
# #theDialog = Ui_InvalidSequenceDialog()
#
# #optionsButtonGroup = theDialog.findChild( 'buttonbox_options' )
# #result = theDialog.exec()
# #choice = optionsButtonGroup.checkedid()
#
# if result == QDialog.Accepted:
# print 'choice: ', choice
#
# return inParams
def build_struct(self, name, params, position):
"""
Build the DNA helix based on parameters in the UI.
@param name: The name to assign the node in the model tree.
@type name: str
@param params: The list of parameters gathered from the PM.
@type params: tuple
@param position: The position in 3d model space at which to
create the DNA strand. This is always 0, 0, 0.
@type position: position
"""
# No error checking in build_struct, do all your error
# checking in gather_parameters
theSequence, \
dnaModel, \
dnaType, \
basesPerTurn, \
chunkOption, \
endpoint1, \
endpoint2 = params
if Veq(endpoint1, endpoint2):
raise CadBug("Dna endpoints cannot be the same point.")
return
if len(theSequence) < 1:
msg = redmsg("Enter a strand sequence to preview/insert DNA")
self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=False)
self.dna = None # Fixes bug 2530. Mark 2007-09-02
return None
if dnaModel == 'PAM3':
dna = B_Dna_PAM3()
else:
dna = B_Dna_PAM5()
self.dna = dna # needed for done msg
# Create the model tree group node.
rawDnaGroup = Group(self.name,
self.win.assy,
self.win.assy.part.topnode)
try:
# Make the DNA duplex. <rawDnaGroup> returns a different
# grouping arrangement for atomistic vs. PAM5. This 'issue'
# is resolved when we regroup the atoms into strand chunks
# below.
dna.make(rawDnaGroup, theSequence, basesPerTurn)
self._orientRawDnaGroup(rawDnaGroup, endpoint1, endpoint2)
# Now group the DNA atoms based on the grouping option selected
# (i.e. "Strand chunks" or "Single Chunk").
dnaGroup = self._makePAMStrandAndAxisChunks(rawDnaGroup)
if chunkOption == 'Single chunk':
return self._makeDuplexChunk(dnaGroup)
return dnaGroup
except (PluginBug, UserError):
# Why do we need UserError here? Mark 2007-08-28
rawDnaGroup.kill()
raise PluginBug("Internal error while trying to create DNA duplex.")
return None
def _orientRawDnaGroup(self, rawDnaGroup, pt1, pt2):
"""
Orients the raw DNA group based on two endpoints.
@param rawDnaGroup: The raw DNA group created by make().
@type rawDnaGroup: L{Group}
@param pt1: The first endpoint of the DNA strand.
@type pt1: L{V}
@param pt2: The second endpoint of the DNA strand.
@type pt2: L{V}
@attention: Only works for PAM5 models.
"""
a = V(0.0, 0.0, -1.0)
# <a> is the unit vector pointing down the center axis of the default
# rawDnaGroup structure which is aligned along the Z axis.
bLine = pt2 - pt1
bLength = vlen(bLine)
b = bLine/bLength
# <b> is the unit vector parallel to the line (i.e. pt1, pt2).
axis = cross(a, b)
# <axis> is the axis of rotation.
theta = angleBetween(a, b)
# <theta> is the angle (in degress) to rotate about <axis>.
scalar = self.dna.getBaseRise() * self.getSequenceLength() * 0.5
rawOffset = b * scalar
if 0: # Debugging code.
print ""
print "uVector a = ", a
print "uVector b = ", b
print "cross(a,b) =", axis
print "theta =", theta
print "baserise =", self.dna.getBaseRise()
print "seqLength =", self.getSequenceLength()
print "scalar =", scalar
print "rawOffset =", rawOffset
if theta == 0.0 or theta == 180.0:
axis = V(0, 1, 0)
# print "Now cross(a,b) =", axis
rot = (pi / 180.0) * theta # Convert to radians
qrot = Q(axis, rot) # Quat for rotation delta.
# Move and rotate the base chunks into final orientation.
for m in rawDnaGroup.members:
m.move(qrot.rot(m.center) - m.center + rawOffset + pt1)
m.rot(qrot)
def _getSequenceLength_OBS(self):
"""
Returns the number of bases of the current sequence
(from the Property Manager).
@note: This is duplicated from DnaGeneratorPropert
"""
(sequence, allKnown) = self._getSequence()
return len(sequence)
def _getSequence( self,
reverse = False,
complement = False,
resolve_random = False,
cdict = {} ):
"""
Get the current DNA sequence from the Property Manager.
This method is not fully private. It's used repeatedly to get the
same sequence when making the DNA (which means its return value
should be deterministic, even when making sequences with randomly
chosen bases [nim]), and it's also called from class
DnaGeneratorPropertyManager to return data to be stored back into the
Property Manager, for implementing the reverse and complement actions.
(Ideally it would preserve whitespace and capitalization when used
that way, but it doesn't.)
@param reverse: If true, returns the reverse sequence.
@type reverse: bool
@param complement: If true, returns the complement sequence.
@type complement: bool
@param resolve_random:
@type resolve_random: True
@param cdict:
@type cdict: dictionary
@return: (sequence, allKnown) where I{sequence} is a string in which
each letter describes one base of the sequence currently
described by the UI, as modified by the passed reverse,
complement, and resolve_random flags, and I{allKnown} is a
boolean which says whether every base in the return value
has a known identity.
@rtype: tuple
@note: All punctuation/symbols are purged from the sequence and
any bogus/unknown bases are substituted as 'N' (unknown).
"""
sequence = ''
allKnown = True
cdict = basesDict
# (Note: I think this code implies that it can no longer be a
# number of bases. [bruce 070518 comment])
currentSequence = str(self.getPlainSequence(inOmitSymbols = True))
for ch in currentSequence:
if ch in cdict.keys(): #'CGATN':
properties = cdict[ch]
if ch == 'N': ###e soon: or any other letter indicating a random base
if resolve_random: #bruce 070518 new feature
i = len(sequence)
data = self._random_data_for_index(i)
# a random int in range(12), in a lazily extended cache
ch = list(cdict)[data%4]
# modulus must agree with number of valid entries in
# cdict.
else:
allKnown = False
if complement:
try:
ch = properties['Complement']
except (KeyError):
raise KeyError("DNA dictionary doesn't have a \
'Complement' key for '%r'." % ch)
ch = 'N'
elif ch in self.validSymbols: #'\ \t\r\n':
ch = ''
else:
allKnown = False
sequence += ch
if reverse:
sequence = getReverseSequence(sequence)
return (sequence, allKnown)
def _makeDuplexChunk(self, dnaGroup):
"""
Returns a single DNA chunk given a dnaGroup containing multiple strand
chunks.
@param dnaGroup: The group object containing the DNA strand chunks.
@type dnaGroup: L{Group}
@return: The DNA chunk.
@rtype: L{Chunk}
"""
if not isinstance(dnaGroup.members[0], Chunk):
env.history.message(redmsg(
"Internal error in creating a single chunk DNA"))
return
for m in dnaGroup.members[1:]:
if isinstance(m, Chunk):
dnaGroup.members[0].merge(m)
# Rename the merged chunk
dnaGroup.members[0].name = dnaGroup.name
dnaChunk = dnaGroup.members[0]
dnaChunk.setcolor(None)
dnaGroup.ungroup()
return dnaChunk
def _getStrandName(self, strandNumber, numberOfBasesToDisplay = 0):
"""
Returns a strand name given a strand number and the number of base
letters to display in the name.
@param strandNumber: The strand number, where:
- 0 = Strand1
- 1 = Strand2
- 2 = Axis (PAM5 only)
@type strandNumber: int
@param numberOfBasesToDisplay: The number of base letters to display
in the name. The default is 0.
@type numberOfBasesToDisplay: int
@return: The strand name. (i.e. "StrandA:ATCG...")
@rtype: str
"""
assert (strandNumber >= 0) and (strandNumber <= 2), \
"strandNumber is %d. It can only be 0, 1, or 2." % strandNumber
if strandNumber == 0:
(sequence, allKnown) = self._getSequence()
strandName = 'Strand1'
elif strandNumber == 1:
(sequence, allKnown) = self._getSequence(complement=True)
strandName = 'Strand2'
else:
strandName = "Axis"
if numberOfBasesToDisplay:
# Add strand letters to MT node name.
numberOfLetters = min(len(sequence), numberOfBasesToDisplay)
strandName += ":" + sequence[0:numberOfLetters]
if len(sequence) > numberOfBasesToDisplay:
# Add "..." if the sequence is longer than
# <numberOfBasesToDisplay>.
strandName += '...'
return strandName
def _makePAMStrandAndAxisChunks(self, rawDnaGroup):
"""
Returns a group containing the three strand chunks I{StrandA},
I{StrandB} and I{Axis} of the current DNA sequence.
@param rawDnaGroup: The raw Dna group which contains the
base-pair chunks representing the sequence.
@type grawDnaGrouprp: L{Group}
@return: The new DNA group that contains the three strand chunks
I{StrandA}, I{StrandB} and I{Axis}.
@rtype: L{Group}
"""
startBasePair = rawDnaGroup.members[0]
if not isinstance(startBasePair, Chunk):
env.history.message(redmsg(
"Internal error in creating a chunks for strands and axis"
))
return rawDnaGroup
# <startAtoms> are the PAM atoms that start StrandA, StrandB and Axis.
# If the sequence is a single base, then we have 2 Pe atoms (one for
# strandA and one for StrandB.
if self.getSequenceLength() == 1:
startAtoms = ('Se3', 'Ae3', 'Pe5', 'Ae5')
else:
startAtoms = ('Se3', 'Sh3', 'Ae3', 'Pe5', 'Sh5', 'Ae5')
Pe_count = 0
tempList = []
for atm in startBasePair.atoms.values():
if atm.element.symbol in startAtoms:
tempList.append(atm)
atomList = self.win.assy.getConnectedAtoms(tempList)
tempList = []
if atm.element.symbol in ('Se3', 'Pe5'):
Pe_count += 1
if Pe_count == 1:
strandAChunk = self._makeChunkFromAtomList(atomList)
strandAChunk.name = self._getStrandName(0)
first_Pe_found = True
else: # Pe_count == 2
# Only happens if the user entered a single letter
# for the sequence.
strandBChunk = self._makeChunkFromAtomList(atomList)
strandBChunk.name = self._getStrandName(1)
elif atm.element.symbol in ('Sh3', 'Sh5'):
strandBChunk = self._makeChunkFromAtomList(atomList)
strandBChunk.name = self._getStrandName(1)
elif atm.element.symbol in ('Ae3', 'Ae5'):
axisChunk = self._makeChunkFromAtomList(atomList)
axisChunk.name = self._getStrandName(2)
# Assign default colors to strand and axis chunks.
strandAChunk.setcolor(darkred)
strandBChunk.setcolor(blue)
axisChunk.setcolor(lightgray)
# Place strand and axis chunks in this order: StrandA, StrandB, Axis.
rawDnaGroup.addmember(strandAChunk)
rawDnaGroup.addmember(strandBChunk)
rawDnaGroup.addmember(axisChunk)
self.win.win_update() # Needed?
return rawDnaGroup
def _makeChunkFromAtomList(self, atomList):
"""
Creates a new chunk from the given atom list.
@param atomList: List of atoms from which to create the chunk.
@type atomList: list
@return: The new chunk.
@rtype: L{Chunk}
@deprecated: use ops_rechunk.makeChunkFromAtomsList() instead.
"""
if not atomList:
print "bug in creating chunks from the given atom list"
return
newChunk = Chunk(self.win.assy, gensym("Chunk", self.win.assy))
for a in atomList:
# leave the moved atoms picked, so still visible
a.hopmol(newChunk)
return newChunk
###################################################
# The done message
def done_msg(self):
if not self.dna: # Mark 2007-06-01
return "No DNA added."
return "Done creating a strand of %s." % (self.dna.form)
| NanoCAD-master | cad/src/outtakes/BuildDuplex_old/DnaGenerator.py |
NanoCAD-master | cad/src/outtakes/BuildDuplex_old/__init__.py |
|
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details.
"""
DnaGenHelper.py -- DNA generator helper classes, based on empirical data.
WARNING: this file has been mostly superseded by DnaDuplex.py.
It is used only in DnaGenerator.py, also superseded.
@author: Will Ware
@version: $Id$
@copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details.
History:
Jeff 2007-06-13 (created)
- Transfered class Dna, A_Dna, A_Dna_PAM5, B_Dna, B_Dna_PAM5,
Z_Dna abd Z_Dna_PAM5 from Will Ware's DNAGenerator.py.
- Added accessor methods getBaseRise/setBaseRise
Mark 2007-08-17:
- make() creates a duplex structure only (no single strands).
- Created standard directory structure for DNA MMP files.
- PAM5 MMP files reworked and simplfied.
- A single PAM5 base-pair duplex is made correctly.
- Moved Dna constants to Dna_Constants.py.
- Changed default base to "X" (unassigned) from "N" (aNy base).
- Implemented Standard IUB Codes (see Dna_Constants.py)
Mark 2007-10-18:
- Did a major rewrite of this module, superseding it --
DnaDuplex.py.
Bruce 2008-1-1:
- renamed this from Dna.py to DnaGenHelper.py so it's
not in a way of a proposed "dna" package.
"""
# To do:
#
# 1) Atomistic and PAM5 generated models should have exact orientation
# (i.e. rotational origin).
import foundation.env as env
import os
import re
from math import sin, cos, pi
from utilities.debug import print_compact_traceback
from platform_dependent.PlatformDependent import find_plugin_dir
from files.mmp.files_mmp import readmmp
from geometry.VQT import V
from commands.Fuse.fusechunksMode import fusechunksBase
from utilities.Log import orangemsg
from utilities.exception_classes import PluginBug
from dna.model.Dna_Constants import basesDict, dnaDict
atompat = re.compile("atom (\d+) \((\d+)\) \((-?\d+), (-?\d+), (-?\d+)\)")
numberPattern = re.compile(r"^\s*(\d+)\s*$")
basepath_ok, basepath = find_plugin_dir("DNA")
if not basepath_ok:
env.history.message(orangemsg("The cad/plugins/DNA directory is missing."))
RIGHT_HANDED = -1
LEFT_HANDED = 1
class Dna:
"""
Dna base class. It is inherited by B_Dna and Z_Dna subclasses.
@ivar baseRise: The rise (spacing) between base-pairs along the helical
(Z) axis.
@type baseRise: float
@ivar handedness: Right-handed (B and A forms) or left-handed (Z form).
@type handedness: int
@ivar model: The model representation, where:
- "Atomistic" = atomistic model
- "PAM5" = PAM5 reduced model.
@type model: str
@ivar sequence: The sequence (of strand A of the duplex).
@type sequence: str
"""
def make(self, group, inSequence, basesPerTurn, position = V(0, 0, 0)):
"""
Makes a DNA duplex with the sequence I{inSequence}.
The duplex is oriented with its central axis coincident
to the Z axis.
@param assy: The assembly (part).
@type assy: L{assembly}
@param group: The group node object containing the DNA. The caller
is responsible for creating an empty group and passing
it here. When finished, this group will contain the DNA
model.
@type group: L{Group}
@param basesPerTurn: The number of bases per helical turn.
@type basesPerTurn: float
@param position: The position in 3d model space at which to create
the DNA strand. This should always be 0, 0, 0.
@type position: position
"""
self.sequence = inSequence
assy = group.assy
baseList = []
def insertBaseFromMmp(filename, subgroup, tfm, position = position):
"""
Insert the atoms for a nucleic acid base from an MMP file into
a single chunk.
- If atomistic, the atoms for each base are in a separate chunk.
- If PAM5, the pseudo atoms for each base-pair are together in a
chunk.
@param filename: The mmp filename containing the base
(or base-pair).
@type filename: str
@param subgroup: The part group to add the atoms to.
@type subgroup: L{Group}
@param tfm: Transform applied to all new base atoms.
@type tfm: V
@param position: The origin in space of the DNA duplex, where the
3' end of strand A is 0, 0, 0.
@type position: L{V}
"""
try:
ok, grouplist = readmmp(assy, filename, isInsert = True)
except IOError:
raise PluginBug("Cannot read file: " + filename)
if not grouplist:
raise PluginBug("No atoms in DNA base? " + filename)
viewdata, mainpart, shelf = grouplist
for member in mainpart.members:
# 'member' is a chunk containing a set of base-pair atoms.
for atm in member.atoms.values():
atm._posn = tfm(atm._posn) + position
if atm.element.symbol in ('Se3', 'Ss3', 'Ss5'):
if atm.getDnaBaseName() == "a":
baseLetter = currentBaseLetter
else:
try:
baseLetter = \
basesDict[currentBaseLetter]['Complement']
except:
# If complement not found, just assign same
# letter.
baseLetter = currentBaseLetter
if 0:
print "Ss(%r) being set to %r." \
% (atm.getDnaBaseName(), baseLetter)
atm.setDnaBaseName(baseLetter)
member.name = currentBaseLetter
subgroup.addchild(member)
baseList.append(member)
# Clean up.
del viewdata
shelf.kill()
def rotateTranslateXYZ(inXYZ, theta, z):
"""
Returns the new XYZ coordinate rotated by I{theta} and
translated by I{z}.
@param inXYZ: The original XYZ coordinate.
@type inXYZ: V
@param theta: The base twist angle.
@type theta: float
@param z: The base rise.
@type z: float
@return: The new XYZ coordinate.
@rtype: V
"""
c, s = cos(theta), sin(theta)
x = c * inXYZ[0] + s * inXYZ[1]
y = -s * inXYZ[0] + c * inXYZ[1]
return V(x, y, inXYZ[2] + z)
# Begin making DNA.
subgroup = group
subgroup.open = False
# Calculate the twist per base in radians.
twistPerBase = (self.handedness * 2 * pi) / basesPerTurn
theta = 0.0
z = 0.5 * self.baseRise * (len(self.sequence) - 1)
# Create PAM5 or PAM3 duplex.
for i in range(len(self.sequence)):
currentBaseLetter = self.sequence[i]
basefile, zoffset, thetaOffset = \
self._strandAinfo(currentBaseLetter, i)
def tfm(v, theta = theta + thetaOffset, z1 = z + zoffset):
return rotateTranslateXYZ(v, theta, z1)
insertBaseFromMmp(basefile, subgroup, tfm)
theta -= twistPerBase
z -= self.baseRise
# Fuse the base chunks together into continuous strands.
fcb = fusechunksBase()
fcb.tol = 1.5
for i in range(len(baseList) - 1):
fcb.find_bondable_pairs([baseList[i]], [baseList[i + 1]])
fcb.make_bonds(assy)
try:
self._postProcess(baseList)
except:
if env.debug():
print_compact_traceback(
"debug: exception in %r._postProcess(baseList = %r) \
(reraising): " % (self, baseList,))
raise
return
def _postProcess(self, baseList):
return
def _baseFileName(self, basename):
"""
Returns the full pathname to the mmp file containing the atoms
of a nucleic acid base (or base-pair).
Example: If I{basename} is "MidBasePair" and this is a PAM5 model of
B-DNA, this returns:
- "C:$HOME\cad\plugins\DNA\B-DNA\PAM5-bases\MidBasePair.mmp"
@param basename: The basename of the mmp file without the extention
(i.e. "adenine", "MidBasePair", etc.).
@type basename: str
@return: The full pathname to the mmp file.
@rtype: str
"""
form = self.form # A-DNA, B-DNA or Z-DNA
model = self.model + '-bases' # Atomistic or PAM5
return os.path.join(basepath, form, model, '%s.mmp' % basename)
def getBaseRise( self ):
"""
Get the base rise (spacing) between base-pairs.
"""
return float( self.baseRise )
def setBaseRise( self, inBaseRise ):
"""
Set the base rise (spacing) between base-pairs.
@param inBaseRise: The base rise in Angstroms.
@type inBaseRise: float
"""
self.baseRise = inBaseRise
pass
class A_Dna(Dna):
"""
Provides an atomistic model of the A form of DNA.
The geometry for A-DNA is very twisty and funky. We need to to research
the A form since it's not a simple helix (like B) or an alternating helix
(like Z).
@attention: This class is not implemented yet.
"""
form = "A-DNA"
model = "Atomistic"
baseRise = dnaDict['A-DNA']['DuplexRise']
handedness = RIGHT_HANDED
def _strandAinfo(self, baseLetter, index):
"""
Raise exception since A-DNA is not support.
"""
raise PluginBug("A-DNA is not yet implemented.")
def _strandBinfo(self, sequence, index):
"""
Raise exception since A-DNA is not support.
"""
raise PluginBug("A-DNA is not yet implemented.")
pass
class A_Dna_Atomistic(A_Dna):
"""
Provides an atomistic model of the A form of DNA.
@attention: This class is not implemented yet.
"""
pass
class A_Dna_PAM5(A_Dna):
"""
Provides a PAM5 reduced model of the B form of DNA.
@attention: This class is not implemented yet.
"""
pass
class B_Dna(Dna):
"""
Provides an atomistic model of the B form of DNA.
"""
form = "B-DNA"
baseRise = dnaDict['B-DNA']['DuplexRise']
handedness = RIGHT_HANDED
pass
class B_Dna_Atomistic(B_Dna):
"""
Provides an atomistic model of the B form of DNA.
"""
model = "Atomistic"
def _strandAinfo(self, baseLetter, index):
"""
Returns parameters needed to add a base to strand A.
@param baseLetter: The base letter.
@type baseLetter: str
@param index: Index in base sequence. This is unused.
@type index: int
"""
zoffset = 0.0
thetaOffset = 0.0
basename = basesDict[baseLetter]['Name']
basefile = self._baseFileName(basename)
return (basefile, zoffset, thetaOffset)
def _strandBinfo(self, baseLetter, index):
"""
Returns parameters needed to add a base to strand B.
@param baseLetter: The base letter.
@type baseLetter: str
@param index: Index in base sequence. This is unused.
@type index: int
"""
zoffset = 0.0
thetaOffset = 210 * (pi / 180)
basename = basesDict[baseLetter]['Name']
basefile = self._baseFileName(basename)
return (basefile, zoffset, thetaOffset)
pass
class B_Dna_PAM5(B_Dna):
"""
Provides a PAM5 reduced model of the B form of DNA.
"""
model = "PAM5"
def _isStartPosition(self, index):
"""
Returns True if I{index} points the first base position (5') of
self's sequence.
@param index: Index in base sequence.
@type index: int
@return: True if index is zero.
@rtype : bool
"""
if index == 0:
return True
else:
return False
def _isEndPosition(self, index):
"""
Returns True if I{index} points the last base position (3') of self's
sequence.
@param index: Index in base sequence.
@type index: int
@return: True if index is zero.
@rtype : bool
"""
if index == len(self.sequence) - 1:
return True
else:
return False
def _strandAinfo(self, baseLetter, index):
"""
Returns parameters needed to add a base to strand A.
@param baseLetter: The base letter.
@type baseLetter: str
@param index: Index in base sequence.
@type index: int
"""
zoffset = 0.0
thetaOffset = 0.0
basename = "MiddleBasePair"
if self._isStartPosition(index):
basename = "StartBasePair"
if self._isEndPosition(index):
basename = "EndBasePair"
if len(self.sequence) == 1:
basename = "SingleBasePair"
basefile = self._baseFileName(basename)
return (basefile, zoffset, thetaOffset)
def _postProcess(self, baseList): # bruce 070414
"""
Set bond direction on the backbone bonds.
@param baseList: List of basepair chunks that make up the duplex.
@type baseList: list
"""
# This implem depends on the specifics of how the end-representations
# are terminated. If that's changed, it might stop working or it might
# start giving wrong results. In the current representation,
# baseList[0] (a chunk) has two bonds whose directions we must set,
# which will determine the directions of their strands:
# Ss5 -> Sh5, and Ss5 <- Pe5.
# Just find those bonds and set the strand directions (until such time
# as they can be present to start with in the end1 mmp file).
# (If we were instead passed all the atoms, we could be correct if we
# just did this to the first Pe5 and Sh5 we saw, or to both of each if
# setting the same direction twice is allowed.)
atoms = baseList[0].atoms.values()
Pe_list = filter( lambda atom: atom.element.symbol in ('Pe5'), atoms)
Sh_list = filter( lambda atom: atom.element.symbol in ('Sh5'), atoms)
if len(Pe_list) == len(Sh_list) == 1:
for atom in Pe_list:
assert len(atom.bonds) == 1
atom.bonds[0].set_bond_direction_from(atom, 1, propogate = True)
for atom in Sh_list:
assert len(atom.bonds) == 1
atom.bonds[0].set_bond_direction_from(atom, -1, propogate = True)
else:
#bruce 070604 mitigate bug in above code when number of bases == 1
# by not raising an exception when it fails.
msg = "Warning: strand not terminated, bond direction not set \
(too short)"
env.history.message( orangemsg( msg))
# Note: It turns out this bug is caused by a bug in the rest of the
# generator (which I didn't try to diagnose) -- for number of
# bases == 1 it doesn't terminate the strands, so the above code
# can't find the termination atoms (which is how it figures out
# what to do without depending on intimate knowledge of the base
# mmp file contents).
# print "baseList = %r, its len = %r, atoms in [0] = %r" % \
# (baseList, len(baseList), atoms)
## baseList = [<molecule 'unknown' (11 atoms) at 0xb3d6f58>],
## its len = 1, atoms in [0] = [Ax1, X2, X3, Ss4, Pl5, X6, X7, Ss8, Pl9, X10, X11]
# It would be a mistake to fix this here (by giving it that
# intimate knowledge) -- instead we need to find and fix the bug
# in the rest of generator when number of bases == 1.
return
pass
class B_Dna_PAM3(B_Dna_PAM5):
"""
Provides a PAM3 reduced model of the B form of DNA.
"""
model = "PAM3"
def _postProcess(self, baseList): # bruce 070414
"""
Set bond direction on the backbone bonds.
@param baseList: List of basepair chunks that make up the duplex.
@type baseList: list
@note: baseList must contain at least two base-pair chunks.
"""
# This implem depends on the specifics of how the end-representations
# are terminated. If that's changed, it might stop working or it might
# start giving wrong results. In the current representation,
# baseList[0] (a chunk) is the starting end of the duplex. It has two
# bonds whose directions we should set, which will determine the
# directions of their strands: Se3 -> Ss3, and Sh3 <- Ss3.
# Just find those bonds and set the strand directions.
assert len(baseList) >= 2
basepair1_atoms = baseList[0].atoms.values() # StartBasePair.MMP
basepair2_atoms = baseList[1].atoms.values() # MiddleBasePair or EndBasePair.MMP
Se3_list = filter( lambda atom: atom.element.symbol in ('Se3'), basepair1_atoms)
Sh3_list = filter( lambda atom: atom.element.symbol in ('Sh3'), basepair1_atoms)
# To set the direction of the Se3 -> Ss3 bond, we need the Ss3 atom
# from the second base-pair (i.e. baseList[1]) that is connected to
# the Se3 atom in the first base-pair.
# Ss3_list will have only one Ss3 atom if the duplex is only two
# base-pairs long. Otherwise, Ss3_list will have two Ss3 atoms.
Ss3_list = filter( lambda atom: atom.element.symbol in ('Ss3'), basepair2_atoms)
if len(Se3_list) == len(Sh3_list) == 1:
for atom in Se3_list:
assert len(atom.bonds) == 2
# This is fragile since it is dependent on the bond order in the
# PAM3 StartBasePair.MMP file. If the order gets changed in that
# file, this will fail.
# A more robust approach would be to check for the Se3 -> Ss3
# bond, which is the one we want here. Mark 2007-09-27.
#atom.bonds[1].set_bond_direction_from(atom, 1, propogate = True)
# This implements the more robust stategy mentioned
# above. I'd like Bruce to review it and confirm it is good.
# Mark 2007-09-27.
#atom.bonds[1].set_bond_direction_from(Ss3_list[0], -1, propogate = True)
try: # Try the first Ss3 atom in Ss3_list.
atom.bonds[1].set_bond_direction_from(Ss3_list[0], -1, propogate = True)
except: # That wasn't it, so it must be the second Ss3 atom.
atom.bonds[1].set_bond_direction_from(Ss3_list[1], -1, propogate = True)
for atom in Sh3_list:
assert len(atom.bonds) == 1
atom.bonds[0].set_bond_direction_from(atom, -1, propogate = True)
else:
#bruce 070604 mitigate bug in above code when number of bases == 1
# by not raising an exception when it fails.
msg = "Warning: strand not terminated, bond direction not set \
(too short)"
env.history.message( orangemsg( msg))
return
class Z_Dna(Dna):
"""
Provides an atomistic model of the Z form of DNA.
"""
form = "Z-DNA"
baseRise = dnaDict['Z-DNA']['DuplexRise']
handedness = LEFT_HANDED
class Z_Dna_PAM5(Z_Dna):
"""
Provides an atomistic model of the Z form of DNA.
@attention: This class is not implemented yet.
"""
model = "Atomistic"
def _strandAinfo(self, baseLetter, index):
"""
Returns parameters needed to add a base to strand A.
@param baseLetter: The base letter.
@type baseLetter: str
@param index: Index in base sequence.
@type index: int
"""
thetaOffset = 0.0
basename = basesDict[baseLetter]['Name']
if (index & 1) != 0:
# Index is odd.
basename += "-outer"
zoffset = 2.045
else:
# Index is even.
basename += '-inner'
zoffset = 0.0
basefile = self._baseFileName(basename)
return (basefile, zoffset, thetaOffset)
def _strandBinfo(self, baseLetter, index):
"""
Returns parameters needed to add a base to strand B.
@param baseLetter: The base letter.
@type baseLetter: str
@param index: Index in base sequence. This is unused.
@type index: int
"""
thetaOffset = 0.5 * pi
basename = basesDict[baseLetter]['Name']
if (index & 1) != 0:
basename += '-inner'
zoffset = -0.055
else:
basename += "-outer"
zoffset = -2.1
basefile = self._baseFileName(basename)
return (basefile, zoffset, thetaOffset)
class Z_Dna_PAM5(Z_Dna):
"""
Provides a PAM5 reduced model of the Z form of DNA.
@attention: This class is not implemented yet.
"""
pass
| NanoCAD-master | cad/src/outtakes/BuildDuplex_old/DnaGenHelper.py |
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details.
"""
DnaGeneratorPropertyManager.py
WARNING: this file has been mostly superseded by DnaDuplexPropertyManager.py.
@author: Will Ware
@version: $Id$
@copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details.
History:
Ninad (Nov2006 and later): Ported it to Property manager
with further enhancements
Mark 2007-05-14:
Organized code, added docstrings and renamed variables to make code more
readable and understandable.
Jeff 2007-06-13:
- Major code cleanup (removed most abbreviations, standardized method names);
- Added helper function getDuplexRise.
- Added Duplex Length spinbox and handler methods (duplexLengthChange,
update duplex length)
- Revamped approach to sequence checking and editing.
Jeff 2007-06-19:
- Renamed class DnaPropMgr to DnaPropertyManager
Mark 2007-08-07:
- Now uses new PM module. Also renamed DnaPropertyManager to
DnaGeneratorPropertyManager.
Mark 2007-10-18:
- Major rewrite of this module, superseding it --
DnaDuplexPropertyManager.py.
"""
# To do:
# 1) <TABLED> Cursor/insertion point visibility:
# - changes to the interior (not end) of the sequence/strand length must
# be changed manually via direct selection and editing.
# - try using a blinking vertical bar via HTML to represent the cursor
# 2) Actions (reverse, complement, etc in _getSequence() should not purge
# unrecognized characters.
import foundation.env as env
from dna.model.Dna_Constants import basesDict, dnaDict
from dna.model.Dna_Constants import getComplementSequence
from dna.model.Dna_Constants import getReverseSequence
from dna.model.Dna_Constants import replaceUnrecognized
from utilities.Log import redmsg, greenmsg, orangemsg
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QRegExp
from PyQt4.Qt import QString
from PyQt4.Qt import QTextCursor
from PyQt4.Qt import QTextOption
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_SpinBox import PM_SpinBox
from PM.PM_TextEdit import PM_TextEdit
from PM.PM_Dialog import PM_Dialog
from widgets.DebugMenuMixin import DebugMenuMixin
# DNA model type variables
# (indices for model... and conformation... comboboxes).
#@REDUCED_MODEL = 0
#@ATOMISTIC_MODEL = 1
BDNA = 0
ZDNA = 1
# Do not commit with DEBUG set to True. Mark 2007-08-07
DEBUG = False
class DnaGeneratorPropertyManager( PM_Dialog, DebugMenuMixin ):
"""
The DnaGeneratorPropertyManager class provides a Property Manager
for the "Build > Atoms" command.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
@ivar validSymbols: Miscellaneous symbols that may appear in the sequence
(but are ignored). The hyphen '-' is a special case
that must be dealt with individually; it is not
included because it can confuse regular expressions.
@type validSymbols: QString
"""
title = "DNA"
pmName = title
iconPath = "ui/actions/Tools/Build Structures/DNA.png"
validSymbols = QString(' <>~!@#%&_+`=$*()[]{}|^\'"\\.;:,/?')
# The following class variables guarantee the UI's menu items
# are synchronized with their action code. The arrays should
# not be changed, unless an item is removed or inserted.
# Changes should be made via only the _action... variables.
# e.g., Change _action_Complement from "Complement"
# to "Complement Sequences". The menu item will
# change and its related code will need no update.
_action_Complement = "Complement"
_action_Reverse = "Reverse"
_action_RemoveUnrecognized = 'Remove unrecognized letters'
_action_ConvertUnrecognized = 'Convert unrecognized letters to "N"'
_actionChoices = [ "Action",
"---",
_action_Complement,
_action_Reverse,
_action_RemoveUnrecognized,
_action_ConvertUnrecognized ]
_modeltype_PAM3 = "PAM3"
_modeltype_PAM5 = "PAM5"
_modeltype_Atomistic = "Atomistic" # deprecated
_modelChoices = [ _modeltype_PAM3,
_modeltype_PAM5 ]
def __init__( self ):
"""
Constructor for the DNA Generator property manager.
"""
PM_Dialog.__init__( self, self.pmName, self.iconPath, self.title )
DebugMenuMixin._init1( self )
msg = "Edit the DNA parameters and select <b>Preview</b> to \
preview the structure. Click <b>Done</b> to insert it into \
the model."
# This causes the "Message" box to be displayed as well.
# setAsDefault=True causes this message to be reset whenever
# this PM is (re)displayed via show(). Mark 2007-06-01.
self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = True )
def _addGroupBoxes( self ):
"""
Add the DNA Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox( self, title = "Strand Sequence" )
self._loadGroupBox1( self._pmGroupBox1 )
self._pmGroupBox2 = PM_GroupBox( self, title = "DNA Parameters" )
self._loadGroupBox2( self._pmGroupBox2 )
self._pmGroupBox3 = PM_GroupBox( self, title = "Endpoints" )
self._loadGroupBox3( self._pmGroupBox3 )
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box 1.
"""
# Duplex Length
self.duplexLengthSpinBox = \
PM_DoubleSpinBox( pmGroupBox,
label = "Duplex Length: ",
value = 0,
setAsDefault = False,
minimum = 0,
maximum = 34000,
singleStep = self.getDuplexRise("B-DNA"),
decimals = 3,
suffix = ' Angstroms')
self.connect( self.duplexLengthSpinBox,
SIGNAL("valueChanged(double)"),
self.duplexLengthChanged )
# Strand Length
self.strandLengthSpinBox = \
PM_SpinBox( pmGroupBox,
label = "Strand Length :",
value = 0,
setAsDefault = False,
minimum = 0,
maximum = 10000,
suffix = ' bases' )
self.connect( self.strandLengthSpinBox,
SIGNAL("valueChanged(int)"),
self.strandLengthChanged )
# New Base choices
newBaseChoices = []
for theBase in basesDict.keys():
newBaseChoices = newBaseChoices \
+ [ theBase + ' (' \
+ basesDict[theBase]['Name'] + ')' ]
try:
defaultBaseChoice = basesDict.keys().index('N')
except:
defaultBaseChoice = 0
# Strand Sequence
self.sequenceTextEdit = \
PM_TextEdit( pmGroupBox,
label = "",
spanWidth = True )
self.sequenceTextEdit.setCursorWidth(2)
self.sequenceTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
self.connect( self.sequenceTextEdit,
SIGNAL("textChanged()"),
self.sequenceChanged )
self.connect( self.sequenceTextEdit,
SIGNAL("cursorPositionChanged()"),
self.cursorPosChanged )
# Actions
self.actionsComboBox = \
PM_ComboBox( pmGroupBox,
label = '',
choices = self._actionChoices,
index = 0,
setAsDefault = True,
spanWidth = True )
# If SIGNAL("activate(const QString&)") is used, we get a TypeError.
# This is a bug that needs Bruce. Using currentIndexChanged(int) as
# a workaround, but there is still a bug when the "Reverse" action
# is selected. Mark 2007-08-15
self.connect( self.actionsComboBox,
SIGNAL("currentIndexChanged(int)"),
self.actionsComboBoxChanged )
def _loadGroupBox2( self, pmGroupBox ):
"""
Load widgets in group box 2.
"""
self.modelComboBox = \
PM_ComboBox( pmGroupBox,
label = "Model :",
choices = self._modelChoices,
setAsDefault = True)
self.conformationComboBox = \
PM_ComboBox( pmGroupBox,
label = "Conformation :",
choices = ["B-DNA"],
setAsDefault = True)
self.connect( self.conformationComboBox,
SIGNAL("currentIndexChanged(int)"),
self.conformationComboBoxChanged )
self.basesPerTurnComboBox= \
PM_ComboBox( pmGroupBox,
label = "Bases Per Turn :",
choices = ["10.0", "10.5", "10.67"],
setAsDefault = True)
# I may decide to reintroduce "base-pair chunks" at a later time.
# Please talk to me if you have a strong feeling about including
# this. Mark 2007-08-19.
createChoices = ["Strand chunks", \
"Single chunk" ]
#@ "Base-pair chunks"]
self.createComboBox = \
PM_ComboBox( pmGroupBox,
label = "Create :",
choices = createChoices,
index = 0,
setAsDefault = True,
spanWidth = False )
def _loadGroupBox3(self, pmGroupBox):
"""
Load widgets in group box 3.
"""
self._endPoint1GroupBox = PM_GroupBox( pmGroupBox, title = "Endpoint1" )
self._endPoint2GroupBox = PM_GroupBox( pmGroupBox, title = "Endpoint2" )
# Point 1
self.x1SpinBox = \
PM_DoubleSpinBox( self._endPoint1GroupBox,
label = \
"ui/actions/Properties Manager/X_Coordinate.png",
value = 0,
setAsDefault = True,
minimum = -100.0,
maximum = 100.0,
decimals = 3,
suffix = ' Angstroms')
self.y1SpinBox = \
PM_DoubleSpinBox( self._endPoint1GroupBox,
label = \
"ui/actions/Properties Manager/Y_Coordinate.png",
value = 0,
setAsDefault = True,
minimum = -100.0,
maximum = 100.0,
decimals = 3,
suffix = ' Angstroms')
self.z1SpinBox = \
PM_DoubleSpinBox( self._endPoint1GroupBox,
label = \
"ui/actions/Properties Manager/Z_Coordinate.png",
value = 0,
setAsDefault = True,
minimum = -100.0,
maximum = 100.0,
decimals = 3,
suffix = ' Angstroms')
# Point 2
self.x2SpinBox = \
PM_DoubleSpinBox( self._endPoint2GroupBox,
label = \
"ui/actions/Properties Manager/X_Coordinate.png",
value = 10.0,
setAsDefault = True,
minimum = -100.0,
maximum = 100.0,
decimals = 3,
suffix = ' Angstroms')
self.y2SpinBox = \
PM_DoubleSpinBox( self._endPoint2GroupBox,
label = \
"ui/actions/Properties Manager/Y_Coordinate.png",
value = 0,
setAsDefault = True,
minimum = -100.0,
maximum = 100.0,
decimals = 3,
suffix = ' Angstroms')
self.z2SpinBox = \
PM_DoubleSpinBox( self._endPoint2GroupBox,
label = \
"ui/actions/Properties Manager/Z_Coordinate.png",
value = 0,
setAsDefault = True,
minimum = -100.0,
maximum = 100.0,
decimals = 3,
suffix = ' Angstroms')
def _addWhatsThisText( self ):
"""
What's This text for some of the widgets in the
DNA Property Manager.
@note: Many PM widgets are still missing their "What's This" text.
"""
self.conformationComboBox.setWhatsThis("""<b>Conformation</b>
<p>There are three DNA geometries, A-DNA, B-DNA,
and Z-DNA. Only B-DNA and Z-DNA are currently supported.</p>""")
self.sequenceTextEdit.setWhatsThis("""<b>Strand Sequence</b>
<p>Type in the strand sequence you want to generate here (5' => 3')<br>
<br>
Recognized base letters:<br>
<br>
A = Adenosine<br>
C = Cytosine<br>
G = Guanosine<br>
T = Thymidine<br>
N = aNy base<br>
X = Unassigned<br>
<br>
Other base letters currently recognized:<br>
<br>
B = C,G, or T<br>
D = A,G, or T<br>
H = A,C, or T<br>
V = A,C, or G<br>
R = A or G (puRine)<br>
Y = C or T (pYrimidine)<br>
K = G or T (Keto)<br>
M = A or C (aMino)<br>
S = G or C (Strong -3H bonds)<br>
W = A or T (Weak - 2H bonds)<br>
</p>""")
self.actionsComboBox.setWhatsThis("""<b>Action</b>
<p>Select an action to perform on the sequence.</p>""")
def conformationComboBoxChanged( self, inIndex ):
"""
Slot for the Conformation combobox. It is called whenever the
Conformation choice is changed.
@param inIndex: The new index.
@type inIndex: int
"""
self.basesPerTurnComboBox.clear()
conformation = self.conformationComboBox.currentText()
if conformation == "B-DNA":
self.basesPerTurnComboBox.insertItem(0, "10.0")
self.basesPerTurnComboBox.insertItem(1, "10.5")
self.basesPerTurnComboBox.insertItem(2, "10.67")
#10.5 is the default value for Bases per turn.
#So set the current index to 1
self.basesPerTurnComboBox.setCurrentIndex(1)
elif conformation == "Z-DNA":
self.basesPerTurnComboBox.insertItem(0, "12.0")
elif inIndex == -1:
# Caused by clear(). This is tolerable for now. Mark 2007-05-24.
conformation = "B-DNA" # Workaround for "Restore Defaults".
pass
else:
msg = redmsg("conformationComboBoxChanged(): \
Error - unknown DNA conformation. Index = "+ inIndex)
env.history.message(msg)
self.duplexLengthSpinBox.setSingleStep(
self.getDuplexRise(conformation) )
def modelComboBoxChanged( self, inIndex ):
"""
Slot for the Model combobox. It is called whenever the
Model choice is changed.
@param inIndex: The new index.
@type inIndex: int
"""
conformation = self._modelChoices[ inIndex ]
self.disconnect( self.conformationComboBox,
SIGNAL("currentIndexChanged(int)"),
self.conformationComboBoxChanged )
self.conformationComboBox.clear() # Generates signal!
if conformation == self._modeltype_PAM3:
self.conformationComboBox.addItem("B-DNA")
elif conformation == self._modeltype_PAM5:
self.conformationComboBox.addItem("B-DNA")
elif conformation == self._modeltype_Atomistic:
self.conformationComboBox.addItem("B-DNA")
self.conformationComboBox.addItem("Z-DNA")
elif inIndex == -1:
# Caused by clear(). This is tolerable for now. Mark 2007-05-24.
pass
else:
msg = "Error - unknown model representation. Index = " + inIndex
env.history.message(redmsg(msg))
self.connect( self.conformationComboBox,
SIGNAL("currentIndexChanged(int)"),
self.conformationComboBoxChanged)
# GroupBox3 slots (and other methods) supporting the Strand Sequence groupbox.
def getDuplexRise( self, inConformation ):
"""
Return the 'rise' between base pairs of the
specified DNA type (conformation).
@param inConformation: The current conformation.
@type inConformation: int
"""
return dnaDict[str(inConformation)]['DuplexRise']
def synchronizeLengths( self ):
"""
Guarantees the values of the duplex length and strand length
spinboxes agree with the strand sequence (textedit).
"""
self.updateStrandLength()
self.updateDuplexLength()
return
# Added :jbirac 20070613:
def duplexLengthChanged( self, inDuplexLength ):
"""
Slot for the duplex length spinbox, called whenever the value of the
Duplex Length spinbox changes.
@param inDuplexLength: The duplex length.
@type inDuplexLength: float
"""
conformation = self.conformationComboBox.currentText()
duplexRise = self.getDuplexRise( conformation )
newStrandLength = inDuplexLength / duplexRise + 0.5
newStrandLength = int( newStrandLength )
self.strandLengthChanged( newStrandLength )
def updateDuplexLength( self ): # Added :jbirac 20070615:
"""
Update the Duplex Length spinbox; always the length of the
strand sequence multiplied by the 'rise' of the duplex. This
method is called by slots of other controls (i.e., this itself
is not a slot.)
"""
conformation = self.conformationComboBox.currentText()
newDuplexLength = self.getDuplexRise( conformation ) \
* self.getSequenceLength()
self.disconnect( self.duplexLengthSpinBox,
SIGNAL("valueChanged(double)"),
self.duplexLengthChanged)
self.duplexLengthSpinBox.setValue( newDuplexLength )
self.connect( self.duplexLengthSpinBox,
SIGNAL("valueChanged(double)"),
self.duplexLengthChanged)
# Renamed from length_changed :jbirac 20070613:
def strandLengthChanged( self, inStrandLength ):
"""
Slot for the Strand Length spin box, called whenever the value of the
Strand Length spin box changes.
@param inStrandLength: The number of bases in the strand sequence.
@type inStrandLength: int
"""
theSequence = self.getPlainSequence()
sequenceLen = len( theSequence )
lengthChange = inStrandLength - self.getSequenceLength()
# Preserve the cursor's position/selection
cursor = self.sequenceTextEdit.textCursor()
#cursorPosition = cursor.position()
selectionStart = cursor.selectionStart()
selectionEnd = cursor.selectionEnd()
if inStrandLength < 0:
return # Should never happen.
if lengthChange < 0:
# If length is less than the previous length,
# simply truncate the current sequence.
theSequence.chop( -lengthChange )
elif lengthChange > 0:
# If length has increased, add the correct number of base
# letters to the current strand sequence.
numNewBases = lengthChange
# Get current base selected in combobox.
chosenBase = 'X' # Unassigned.
basesToAdd = chosenBase * numNewBases
theSequence.append( basesToAdd )
else:
env.history.message(
orangemsg( "strandLengthChanged(): Length has not changed." ))
self.setSequence( theSequence )
return
# Renamed from updateLength :jbirac 20070613:
def updateStrandLength( self ):
"""
Update the Strand Length spinbox; always the length of the strand
sequence.
"""
self.disconnect( self.strandLengthSpinBox,
SIGNAL("valueChanged(int)"),
self.strandLengthChanged )
self.strandLengthSpinBox.setValue( self.getSequenceLength() )
self.connect( self.strandLengthSpinBox,
SIGNAL("valueChanged(int)"),
self.strandLengthChanged )
return
def sequenceChanged( self ):
"""
Slot for the Strand Sequence textedit widget.
Assumes the sequence changed directly by user's keystroke in the
textedit. Other methods...
"""
cursorPosition = self.getCursorPosition()
theSequence = self.getPlainSequence()
# Disconnect while we edit the sequence.
self.disconnect( self.sequenceTextEdit,
SIGNAL("textChanged()"),
self.sequenceChanged )
# How has the text changed?
if theSequence.length() == 0: # There is no sequence.
self.updateStrandLength()
self.updateDuplexLength()
else:
# Insert the sequence; it will be "stylized" by setSequence().
self.setSequence( theSequence )
# Reconnect to respond when the sequence is changed.
self.connect( self.sequenceTextEdit,
SIGNAL("textChanged()"),
self.sequenceChanged )
self.synchronizeLengths()
return
def getPlainSequence( self, inOmitSymbols = False ):
"""
Returns a plain text QString (without HTML stylization)
of the current sequence. All characters are preserved (unless
specified explicitly), including valid base letters, punctuation
symbols, whitespace and invalid letters.
@param inOmitSymbols: Omits characters listed in self.validSymbols.
@type inOmitSymbols: bool
@return: The current DNA sequence in the PM.
@rtype: QString
"""
outSequence = self.sequenceTextEdit.toPlainText()
if inOmitSymbols:
# This may look like a sloppy piece of code, but Qt's QRegExp
# class makes it pretty tricky to remove all punctuation.
theString = '[<>' \
+ str( QRegExp.escape(self.validSymbols) ) \
+ ']|-'
outSequence.remove(QRegExp( theString ))
return outSequence
def stylizeSequence( self, inSequence ):
"""
Converts a plain text string of a sequence (including optional
symbols) to an HTML rich text string.
@param inSequence: A DNA sequence.
@type inSequence: QString
@return: The sequence.
@rtype: QString
"""
outSequence = str(inSequence)
# Verify that all characters (bases) in the sequence are "valid".
invalidSequence = False
basePosition = 0
sequencePosition = 0
invalidStartTag = "<b><font color=black>"
invalidEndTag = "</b>"
previousChar = chr(1) # Null character; may be revised.
# Some characters must be substituted to preserve
# whitespace and tags in HTML code.
substituteDict = { ' ':' ', '<':'<', '>':'>' }
while basePosition < len(outSequence):
theSeqChar = outSequence[basePosition]
if ( theSeqChar in basesDict
or theSeqChar in self.validSymbols ):
# Close any preceding invalid sequence segment.
if invalidSequence == True:
outSequence = outSequence[:basePosition] \
+ invalidEndTag \
+ outSequence[basePosition:]
basePosition += len(invalidEndTag)
invalidSequence = False
# Color the valid characters.
if theSeqChar != previousChar:
# We only need to insert 'color' tags in places where
# the adjacent characters are different.
if theSeqChar in basesDict:
theTag = '<font color=' \
+ basesDict[ theSeqChar ]['Color'] \
+ '>'
elif not previousChar in self.validSymbols:
# The character is a 'valid' symbol to be greyed
# out. Only one 'color' tag is needed for a
# group of adjacent symbols.
theTag = '<font color=dimgrey>'
else:
theTag = ''
outSequence = outSequence[:basePosition] \
+ theTag + outSequence[basePosition:]
basePosition += len(theTag)
# Any <space> character must be substituted with an
# ASCII code tag because the HTML engine will collapse
# whitespace to a single <space> character; whitespace
# is truncated from the end of HTML by default.
# Also, many symbol characters must be substituted
# because they confuse the HTML syntax.
#if str( outSequence[basePosition] ) in substituteDict:
if outSequence[basePosition] in substituteDict:
#theTag = substituteDict[theSeqChar]
theTag = substituteDict[ outSequence[basePosition] ]
outSequence = outSequence[:basePosition] \
+ theTag \
+ outSequence[basePosition + 1:]
basePosition += len(theTag) - 1
else:
# The sequence character is invalid (but permissible).
# Tags (e.g., <b> and </b>) must be inserted at both the
# beginning and end of a segment of invalid characters.
if invalidSequence == False:
outSequence = outSequence[:basePosition] \
+ invalidStartTag \
+ outSequence[basePosition:]
basePosition += len(invalidStartTag)
invalidSequence = True
basePosition += 1
previousChar = theSeqChar
#basePosition += 1
# Specify that theSequence is definitely HTML format, because
# Qt can get confused between HTML and Plain Text.
outSequence = "<html>" + outSequence
outSequence += "</html>"
return outSequence
def setSequence( self,
inSequence,
inStylize = True,
inRestoreCursor = True ):
"""
Replace the current strand sequence with the new sequence text.
@param inSequence: The new sequence.
@type inSequence: QString
@param inStylize: If True, inSequence will be converted from a plain
text string (including optional symbols) to an HTML
rich text string.
@type inStylize: bool
@param inRestoreCursor: Not implemented yet.
@type inRestoreCursor: bool
@attention: Signals/slots must be managed before calling this method.
The textChanged() signal will be sent to any connected widgets.
"""
cursor = self.sequenceTextEdit.textCursor()
selectionStart = cursor.selectionStart()
selectionEnd = cursor.selectionEnd()
if inStylize:
inSequence = self.stylizeSequence( inSequence )
self.sequenceTextEdit.insertHtml( inSequence )
if inRestoreCursor:
cursor.setPosition( min(selectionStart, self.getSequenceLength()),
QTextCursor.MoveAnchor )
cursor.setPosition( min(selectionEnd, self.getSequenceLength()),
QTextCursor.KeepAnchor )
self.sequenceTextEdit.setTextCursor( cursor )
return
def getSequenceLength( self ):
"""
Returns the number of characters in
the strand sequence textedit widget.
"""
theSequence = self.getPlainSequence( inOmitSymbols = True )
outLength = theSequence.length()
return outLength
def getCursorPosition( self ):
"""
Returns the cursor position in the
strand sequence textedit widget.
"""
cursor = self.sequenceTextEdit.textCursor()
return cursor.position()
def cursorPosChanged( self ):
"""
Slot called when the cursor position changes.
"""
cursor = self.sequenceTextEdit.textCursor()
if 0:
env.history.message( greenmsg( "cursorPosChanged: Selection ("
+ str(cursor.selectionStart())
+ " thru "
+ str(cursor.selectionEnd())+')' ) )
return
def actionsComboBoxChanged( self, inIndex ):
"""
Slot for the Actions combobox. It is called whenever the
Action choice is changed.
@param inIndex: The index of the selected action choice.
@type inIndex: int
"""
if inIndex == 0: # Very important.
return
actionName = str(self.actionsComboBox.currentText())
self.actionsComboBox.setCurrentIndex( 0 ) # Generates signal!
self.invokeAction( actionName )
return
def invokeAction( self, inActionName ):
"""
Applies an action on the current sequence displayed in the PM.
@param inActionName: The action name.
@type inActionName: str
@return: The sequence after the action has been applied.
@rtype: str
"""
sequence, allKnown = self._getSequence()
outResult = ""
if inActionName == self._action_Complement:
outResult = getComplementSequence(sequence)
elif inActionName == self._action_Reverse:
outResult = getReverseSequence(sequence)
elif inActionName == self._action_ConvertUnrecognized:
outResult = replaceUnrecognized(sequence, replaceBase = 'N')
self.setSequence( outResult )
elif inActionName == self._action_RemoveUnrecognized:
outResult = replaceUnrecognized(sequence, replaceBase = '')
self.setSequence( outResult )
return
| NanoCAD-master | cad/src/outtakes/BuildDuplex_old/DnaGeneratorPropertyManager.py |
NanoCAD-master | cad/src/protein/__init__.py |
|
# Copyright 2007 Nanorex, Inc. See LICENSE file for details.
"""
Ui_ProteinSequenceEditor.py
@author: Urmi
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@version:$Id$
History:
Urmi copied this from Ui_DnaSequenceEditor.py and modified it to suit the
requirements of a protein sequence editor
TODO:
- NFR: Load sequence for the current peptide from a FASTA file.
- NFR: Save sequence for the current peptide to a FASTA file.
"""
from PyQt4.Qt import QToolButton
from PyQt4.Qt import QPalette
from PyQt4.Qt import QTextOption
from PyQt4.Qt import QLabel
from PyQt4.Qt import QAction, QMenu
from PyQt4.Qt import Qt, QColor
from PyQt4.Qt import QTextCursor
from PM.PM_Colors import pmGrpBoxColor
from PM.PM_Colors import getPalette
from PM.PM_Colors import sequenceEditStrandMateBaseColor
from PM.PM_DockWidget import PM_DockWidget
from PM.PM_WidgetRow import PM_WidgetRow
from PM.PM_ToolButton import PM_ToolButton
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_TextEdit import PM_TextEdit
from PM.PM_LineEdit import PM_LineEdit
from PM.PM_PushButton import PM_PushButton
from utilities.icon_utilities import geticon, getpixmap
_superclass = PM_DockWidget
class Ui_ProteinSequenceEditor(PM_DockWidget):
"""
The Ui_DnaSequenceEditor class defines UI elements for the Sequence Editor
object. The sequence editor is usually visible while in DNA edit mode.
It is a DockWidget that is doced at the bottom of the MainWindow
"""
_title = "Sequence Editor"
_groupBoxCount = 0
_lastGroupBox = None
def __init__(self, win):
"""
Constructor for the Ui_DnaSequenceEditor
@param win: The parentWidget (MainWindow) for the sequence editor
"""
self.win = win
parentWidget = win
_superclass.__init__(self, parentWidget, title = self._title)
self._reportsDockWidget_closed_in_show_method = False
self.setFixedHeight(90)
return
def show(self):
"""
Shows the sequence editor. While doing this, it also closes the reports
dock widget (if visible) the state of the reports dockwidget will be
restored when the sequence editor is closed.
@see:self.closeEvent()
"""
self._reportsDockWidget_closed_in_show_method = False
if self.win.viewFullScreenAction.isChecked() or \
self.win.viewSemiFullScreenAction.isChecked():
pass
else:
if self.win.reportsDockWidget.isVisible():
self.win.reportsDockWidget.close()
self._reportsDockWidget_closed_in_show_method = True
_superclass.show(self)
return
def closeEvent(self, event):
"""
Overrides close event. Makes sure that the visible state of the reports
widgetis restored when the sequence editor is closed.
@see: self.show()
"""
_superclass.closeEvent(self, event)
if self.win.viewFullScreenAction.isChecked() or \
self.win.viewSemiFullScreenAction.isChecked():
pass
else:
if self._reportsDockWidget_closed_in_show_method:
self.win.viewReportsAction.setChecked(True)
self._reportsDockWidget_closed_in_show_method = False
return
def _loadWidgets(self):
"""
Overrides PM.PM_DockWidget._loadWidgets. Loads the widget in this
dockwidget.
"""
self._loadMenuWidgets()
self._loadTextEditWidget()
return
def _loadMenuWidgets(self):
"""
Load the various menu widgets (e.g. Open, save sequence options,
Find and replace widgets etc.
"""
self.loadSequenceButton = PM_ToolButton(
self,
iconPath = "ui/actions/Properties Manager/Open.png")
self.saveSequenceButton = PM_ToolButton(
self,
iconPath = "ui/actions/Properties Manager/Save_Strand_Sequence.png")
self.loadSequenceButton.setAutoRaise(True)
self.saveSequenceButton.setAutoRaise(True)
# Hide load and save buttons until they are implemented. -Mark 2008-12-20.
self.loadSequenceButton.hide()
self.saveSequenceButton.hide()
#Find and replace widgets --
self.findLineEdit = \
PM_LineEdit( self,
label = "",
spanWidth = False)
self.findLineEdit.setMaximumWidth(60)
self.replaceLineEdit = \
PM_LineEdit( self,
label = " Replace:",
spanWidth = False)
self.replaceLineEdit.setMaximumWidth(60)
self.findOptionsToolButton = PM_ToolButton(self)
self.findOptionsToolButton.setMaximumWidth(12)
self.findOptionsToolButton.setAutoRaise(True)
self.findOptionsToolButton.setPopupMode(QToolButton.MenuButtonPopup)
self._setFindOptionsToolButtonMenu()
self.findNextToolButton = PM_ToolButton(
self,
iconPath = "ui/actions/Properties Manager/Find_Next.png")
self.findNextToolButton.setAutoRaise(True)
self.findPreviousToolButton = PM_ToolButton(
self,
iconPath = "ui/actions/Properties Manager/Find_Previous.png")
self.findPreviousToolButton.setAutoRaise(True)
self.replacePushButton = PM_PushButton(self, text = "Replace")
# Hide Replace widgets until we add support for transmuting residues.
# Mark 2008-12-19
#self.replaceLabel.hide()
self.replacePushButton.hide()
self.replaceLineEdit.hide()
self.warningSign = QLabel(self)
self.warningSign.setPixmap(
getpixmap('ui/actions/Properties Manager/Warning.png'))
self.warningSign.hide()
self.phraseNotFoundLabel = QLabel(self)
self.phraseNotFoundLabel.setText("Sequence Not Found")
self.phraseNotFoundLabel.hide()
#Widgets to include in the widget row.
widgetList = [('PM_ToolButton', self.loadSequenceButton, 0),
('PM_ToolButton', self.saveSequenceButton, 1),
('QLabel', " Find:", 4),
('PM_LineEdit', self.findLineEdit, 5),
('PM_ToolButton', self.findOptionsToolButton, 6),
('PM_ToolButton', self.findPreviousToolButton, 7),
('PM_ToolButton', self.findNextToolButton, 8),
#('PM_Label', self.replaceLabel, 9),
('PM_TextEdit', self.replaceLineEdit, 9),
('PM_PushButton', self.replacePushButton, 10),
('PM_Label', self.warningSign, 11),
('PM_Label', self.phraseNotFoundLabel, 12),
('QSpacerItem', 5, 5, 13) ]
widgetRow = PM_WidgetRow(self,
title = '',
widgetList = widgetList,
label = "",
spanWidth = True )
return
def _loadTextEditWidget(self):
"""
Load the SequenceTexteditWidgets.
"""
self.aaRulerTextEdit = \
PM_TextEdit( self,
label = "",
spanWidth = False,
permit_enter_keystroke = False)
palette = getPalette(None,
QPalette.Base,
pmGrpBoxColor)
self.aaRulerTextEdit.setPalette(palette)
self.aaRulerTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
self.aaRulerTextEdit.setFixedHeight(20)
self.aaRulerTextEdit.setReadOnly(True)
self.sequenceTextEdit = \
PM_TextEdit( self,
label = " Sequence: ",
spanWidth = False,
permit_enter_keystroke = False)
#self.sequenceTextEdit.setReadOnly(True) #@@@
self.sequenceTextEdit.setCursorWidth(2)
self.sequenceTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
self.sequenceTextEdit.setFixedHeight(20)
self.secStrucTextEdit = \
PM_TextEdit( self,
label = " Secondary structure: ",
spanWidth = False,
permit_enter_keystroke = False)
palette = getPalette(None,
QPalette.Base,
sequenceEditStrandMateBaseColor)
self.secStrucTextEdit.setPalette(palette)
self.secStrucTextEdit.setWordWrapMode( QTextOption.WrapAnywhere )
self.secStrucTextEdit.setFixedHeight(20)
self.secStrucTextEdit.setReadOnly(True)
#Important to make sure that the horizontal and vertical scrollbars
#for these text edits are never displayed.
self.sequenceTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.sequenceTextEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.secStrucTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.secStrucTextEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.aaRulerTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.aaRulerTextEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
return
def _getFindLineEditStyleSheet(self):
"""
Return the style sheet for the findLineEdit. This sets the following
properties only:
- background-color
This style is set whenever the searchStrig can't be found (sets
a light red color background to the lineedit when this happens)
@return: The line edit style sheet.
@rtype: str
"""
styleSheet = "QLineEdit {"\
"background-color: rgb(255, 102, 102)"\
"}"
return styleSheet
def _setFindOptionsToolButtonMenu(self):
"""
Sets the menu for the findOptionstoolbutton that appears a small
menu button next to the findLineEdit.
"""
self.findOptionsMenu = QMenu(self.findOptionsToolButton)
self.caseSensitiveFindAction = QAction(self.findOptionsToolButton)
self.caseSensitiveFindAction.setText('Match Case')
self.caseSensitiveFindAction.setCheckable(True)
self.caseSensitiveFindAction.setChecked(False)
self.findOptionsMenu.addAction(self.caseSensitiveFindAction)
self.findOptionsMenu.addSeparator()
self.findOptionsToolButton.setMenu(self.findOptionsMenu)
return
def _addToolTipText(self):
"""
What's Tool Tip text for widgets in this Property Manager.
"""
from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_ProteinSequenceEditor
ToolTip_ProteinSequenceEditor(self)
return
def _addWhatsThisText(self):
"""
What's This text for widgets in this Property Manager.
"""
from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_ProteinSequenceEditor
whatsThis_ProteinSequenceEditor(self)
return
| NanoCAD-master | cad/src/protein/ProteinSequenceEditor/Ui_ProteinSequenceEditor.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
ProteinSequenceEditor.py
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@version: $Id$
@author: Urmi
History:
Urmi copied this from DnaSequenceEditor.py and modified it to suit the
requirements of a protein sequence editor.
"""
import foundation.env as env
import os
import re
import string
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import QTextCursor
from PyQt4.Qt import QString
from PyQt4.Qt import QFileDialog
from PyQt4.Qt import QMessageBox
from PyQt4.Qt import QRegExp
from PyQt4.Qt import QTextDocument
from PyQt4.Qt import QPalette
from PM.PM_Colors import getPalette
from PM.PM_Colors import sequenceEditorNormalColor
from PM.PM_Colors import sequenceEditorChangedColor
from utilities.prefs_constants import workingDirectory_prefs_key
from protein.ProteinSequenceEditor.Ui_ProteinSequenceEditor import Ui_ProteinSequenceEditor
from utilities import debug_flags
from utilities.debug import print_compact_stack
class ProteinSequenceEditor(Ui_ProteinSequenceEditor):
"""
Creates a dockable protein sequence editor.
"""
validSymbols = QString(' <>~!@#%&_+`=$*()[]{}|^\'"\\.;:,/?')
sequenceFileName = None
current_protein = None # The current protein chunk.
_sequence_changed = False # Set to True when the sequence has been changed by the user.
_previousSequence = "" # The previous sequence, just before the user changed it.
def __init__(self, win):
"""
Creates a dockable protein sequence editor
"""
Ui_ProteinSequenceEditor.__init__(self, win)
self.isAlreadyConnected = False
self.isAlreadyDisconnected = False
self._suppress_textChanged_signal = False
self._suppress_cursorPosChanged_signal = False
self.connect_or_disconnect_signals(True)
self.win = win
self.maxSeqLength = 0
def connect_or_disconnect_signals(self, isConnect):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
"""
if isConnect and self.isAlreadyConnected:
if debug_flags.atom_debug:
print_compact_stack("warning: attempt to connect widgets"\
"in this PM that are already connected." )
return
if not isConnect and self.isAlreadyDisconnected:
if debug_flags.atom_debug:
print_compact_stack("warning: attempt to disconnect widgets"\
"in this PM that are already disconnected.")
return
self.isAlreadyConnected = isConnect
self.isAlreadyDisconnected = not isConnect
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.loadSequenceButton,
SIGNAL("clicked()"),
self._open_FASTA_File)
change_connect(self.saveSequenceButton,
SIGNAL("clicked()"),
self._savePeptideSequence)
change_connect( self.sequenceTextEdit,
SIGNAL("textChanged()"),
self._sequenceChanged )
change_connect( self.sequenceTextEdit,
SIGNAL("editingFinished()"),
self._assignPeptideSequence )
change_connect( self.sequenceTextEdit,
SIGNAL("cursorPositionChanged()"),
self._cursorPosChanged)
change_connect( self.findLineEdit,
SIGNAL("textEdited(const QString&)"),
self.findLineEdit_textEdited)
change_connect( self.findNextToolButton,
SIGNAL("clicked()"),
self.findNext)
change_connect( self.findPreviousToolButton,
SIGNAL("clicked()"),
self.findPrevious)
change_connect( self.replacePushButton,
SIGNAL("clicked()"),
self.replace)
return
def update_state(self, bool_enable = True):
"""
Update the state of this widget by enabling or disabling it depending
upon the flag bool_enable.
@param bool_enable: If True , enables the widgets inside the sequence
editor
@type bool_enable: boolean
"""
for widget in self.children():
if hasattr(widget, 'setEnabled'):
if widget.__class__.__name__ != 'QAbstractButton':
widget.setEnabled(bool_enable)
return
def _sequenceChanged( self ):
"""
Slot for the Protein Sequence textedit widget. (private method)
Assumes the sequence changed directly by user's keystroke in the
textedit. Other methods...
"""
if self._suppress_textChanged_signal:
return
self._suppress_textChanged_signal = True
cursorPos = self.getCursorPosition()
theSequence = self.getPlainSequence()
if len(theSequence) == len(self._previousSequence):
# Replace space characters with the same character.
aa = self._previousSequence[cursorPos - 1]
theSequence.replace(" ", aa)
print "The last character was replaced with: ", aa
# Insert the sequence; it will be "stylized" by _setSequence().
self._setSequence(theSequence, inCursorPos = cursorPos)
if False: # Set to True for debugging statements.
if theSequence == self._previousSequence:
print "The sequence did not change (YOU SHOULD NEVER SEE THIS)."
elif len(theSequence) < len(self._previousSequence):
print "Character(s) were deleted from the sequence."
elif len(theSequence) == len(self._previousSequence):
print "A character was replaced. The sequence length is the same."
else:
print "Character(s) where added to the sequence."
pass
# If the sequence in the text edit (field) is different from the current
# sequence, change the sequence field bg color to pink to
# indicate that the sequence is different. If they are the same,
# change the sequence field background (back) to white.
if theSequence != self.current_protein.protein.get_sequence_string():
self._sequence_changed = True
else:
self._sequence_changed = False
self._previousSequence = theSequence
self._updateSequenceBgColor()
#Urmi 20080725: Some time later we need to have a method here which
#would allow us to set the sequence of the protein chunk. We will also
#update the secondary structure sequence or will it be the same as the
#original one?
self._suppress_textChanged_signal = False
return
def _assignPeptideSequence(self):
"""
(private)
Slot for the "editingFinished()" signal generated by the PM_TextEdit
whenever the user presses the Enter key in the sequence text edit field.
Assigns the amino acid sequence in the sequence editor text field to
the current protein.
@attention: this method is not implemented yet. If called, it will
display a messagebox warning the user that this is not implement yet.
"""
if not self.current_protein:
return
sequenceString = self.getPlainSequence()
sequenceString = str(sequenceString)
#assign sequence only if it not the same as the current sequence
seq = self.current_protein.protein.get_sequence_string()
if seq != sequenceString:
#self.current_protein.setSequence(sequenceString)
#self.updateSequence(cursorPos = self.getCursorPosition())
msg = "We are sorry. You cannot change the sequence since "\
"this feature is not yet supported."
QMessageBox.warning(self.win, "Warning!", msg)
self._suppress_textChanged_signal = False
self.updateSequence(self.current_protein)
return
def _updateSequenceBgColor(self):
"""
Updates the sequence field background color
(pink = changed, white = unchanged).
"""
if self._sequence_changed:
bgColor = sequenceEditorChangedColor
else:
bgColor = sequenceEditorNormalColor
palette = getPalette(None,
QPalette.Base,
bgColor)
self.sequenceTextEdit.setPalette(palette)
return
def getPlainSequence( self, inOmitSymbols = False ):
"""
Returns a plain text QString (without HTML stylization)
of the current sequence. All characters are preserved (unless
specified explicitly), including valid base letters, punctuation
symbols, whitespace and invalid letters.
@param inOmitSymbols: Omits characters listed in self.validSymbols.
@type inOmitSymbols: bool
@return: The current Protein sequence in the PM.
@rtype: QString
"""
outSequence = self.sequenceTextEdit.toPlainText()
outSequence = outSequence.toUpper()
if inOmitSymbols:
# This may look like a sloppy piece of code, but Qt's QRegExp
# class makes it pretty tricky to remove all punctuation.
theString = '[<>' \
+ str( QRegExp.escape(self.validSymbols) ) \
+ ']|-'
outSequence.remove(QRegExp( theString ))
return outSequence
def clear( self ):
"""
Clears the sequence editor.
"""
self.current_protein = None
self._setSequenceAndStructure("", "")
return
def _setSequenceAndStructure(self,
inSequence,
inStructure,
inCursorPos = -1):
"""
Sets the sequence, structure and ruler fields in the sequence editor.
@param inSequence: The sequence string.
@type inSequence: QString
@param inStructure: The secondary structure string.
@type inStructure: QString
@param inCursorPos: the position in the sequence in which to place the
cursor. If cursorPos is negative, the cursor position
is placed at first residue of the sequence (default).
@type inCursorPos: int
"""
#NOTE: It is important that sequence is set last so that setCursorPos()
#doesn't complain (i.e. the structure and ruler strings must be
#equal to the length of the sequence string before setting the cursor
# position). --Mark 2008-12-20
self._setSecondaryStructure(inStructure)
self._setRuler(len(inSequence))
self._setSequence(inSequence, inCursorPos = inCursorPos)
return
def _setSequence( self,
inSequence,
inStylize = True,
inCursorPos = -1
):
"""
Replace the current amino acid sequence with the new sequence text.
(private method)
Callers outside this class wishing to update the amino acid sequence
field should call updateSequence().
@param inSequence: The sequence string.
@type inSequence: QString
@param inStylize: If True, inSequence will be converted from a plain
text string (including optional symbols) to an HTML
rich text string.
@type inStylize: bool
@param inCursorPos: the position in the sequence in which to place the
cursor. If cursorPos is negative, the cursor position
is placed at first residue of the sequence (default).
@type inCursorPos: int
@see: updateSequence()
"""
seq = str(inSequence)
seq = seq.upper()
htmlSequence = self._convertProteinSequenceToColoredSequence(seq)
if inStylize:
htmlSequence = self._fixedPitchSequence(htmlSequence)
self._suppress_textChanged_signal = True
self._suppress_cursorPosChanged_signal = True
self.sequenceTextEdit.setHtml(htmlSequence) # Generates cursorPosChanged signal!
self.setCursorPosition(inCursorPos = inCursorPos)
self._suppress_textChanged_signal = False
self._suppress_cursorPosChanged_signal = False
return
def _getFormattedSequence(self, inSequence):
"""
Create formatted sequence to be used by secondary structure text edit
@param inSequence: The new sequence.
@type inSequence: QString
"""
colorList = ['Red','Blue', 'Green']
secStrucList = ['H','E', '-']
secStrucDict = dict(zip(secStrucList, colorList))
outSequence = ""
for i in range(len(inSequence)):
currentAA = inSequence[i]
color = secStrucDict[currentAA]
outSequence = outSequence + "<font color=" + color + ">"
outSequence = outSequence + currentAA + "</font>"
#Now put html tags and make everything bold
fixedPitchSequence = "<html><bold><font size=3 face=Courier New >" + outSequence
fixedPitchSequence += "</font></bold></html>"
return fixedPitchSequence
def _setSecondaryStructure(self, inStructure):
"""
Set the secondary structure of the protein. (private method)
Callers outside this class wishing to update the secondary structure
field should call updateSequence().
@param inStructure: The structure string.
@type inStructure: QString
@see: updateSequence()
"""
fixedPitchSequence = self._getFormattedSequence(inStructure)
self.secStrucTextEdit.setHtml(fixedPitchSequence)
return
def getRulerText(self, lengthOfSeq):
"""
Return the ruler text given I{lengthOfSeq} (i.e. the length of the
current sequence).
"""
rulerText = ""
i = 0
while i < lengthOfSeq:
if i == 0:
rulerText = "1"
i = i + 1
elif i % 10 == 0 and i % 5 == 0:
rulerText = rulerText + str(i+1)
if len(str(i+1)) == 2:
i = i + 2
continue
elif len(str(i+1)) == 3:
i = i + 3
else:
i = i + 1
continue
elif i % 5 == 0 and i % 10 != 0:
rulerText = rulerText + "*"
i = i + 1
else:
rulerText = rulerText + "-"
i = i + 1
return rulerText
def _setRuler(self, lengthOfSeq):
"""
Set the sequence ruler with a length of I{lengthOfSeq}.
Callers outside this class wishing to update the ruler
should call updateSequence().
@param lengthOfSeq: length of the sequence.
@type lengthOfSeq: int
@note: supports up to 3 digits (i.e. max length of 999).
"""
rulerText = self.getRulerText(lengthOfSeq)
fixedPitchSequence = "<html><bold><font size=3 face=Courier New color=green>" + rulerText
fixedPitchSequence += "</font></bold></html>"
self.aaRulerTextEdit.setHtml(fixedPitchSequence)
return
def _convertProteinSequenceToColoredSequence(self, inSequence):
"""
Create formatted sequence to be used by the sequence editor
@param inSequence: The new sequence.
@type inSequence: QString
"""
outSequence = ""
colorList = ['Crimson', 'CadetBlue', 'Coral', 'DarkCyan', 'DarkGray',
'DarkGoldenRod', 'DarkOliveGreen', 'BlueViolet', 'Red',
'Chocolate', 'DarkKhaki', 'DarkSalmon', 'DarkSeaGreen',
'FireBrick', 'HotPink', 'LawnGreen', 'IndianRed', 'Indigo',
'LightCoral', 'LightBlue', 'Khaki']
aaList = ['A', 'V', 'X', 'Y', 'W', 'T', 'S', 'P', 'F', 'M', 'K', 'L', 'I'
'H', 'G', 'Q', 'E', 'C', 'R', 'N', 'D' ]
aaDict = dict(zip(aaList, colorList))
for i in range(len(inSequence)):
currentAA = inSequence[i]
try:
color = aaDict[currentAA]
except KeyError:
color = aaDict['X']
outSequence = outSequence + "<font color=" + color + ">"
outSequence = outSequence + currentAA + "</font>"
return outSequence
def _colorExtraSequenceCharacters(self, inSequence):
"""
Returns I{inSequence} with html tags that color any extra overhang
characters gray.
@param inSequence: The sequence.
@type inSequence: QString
@return: inSequence with the html tags to color any overhang characters.
@rtype: string
"""
aaLength = self.current_protein.protein.count_amino_acids()
if len(inSequence) <= aaLength:
return inSequence
sequence = inSequence[:aaLength]
overhang = inSequence[aaLength:]
return sequence + "<font color=gray>" + overhang + "</font>"
def _fixedPitchSequence(self, sequence):
"""
Make the sequence 'fixed-pitched' i.e. width of all characters
should be constance
@param sequence: The new sequence.
@type sequence: QString
"""
fixedPitchSequence = "<html><bold><font size=3 face=Courier New >" + sequence
fixedPitchSequence += "</bold></font></html>"
return fixedPitchSequence
def getSequenceLength( self ):
"""
Returns the number of characters in the sequence textedit widget.
"""
theSequence = self.getPlainSequence( inOmitSymbols = True )
outLength = theSequence.length()
return outLength
def updateSequence(self, proteinChunk = None, inCursorPos = -1):
"""
Updates the sequence editor with the sequence of I{proteinChunk}.
@param proteinChunk: the protein chunk. If proteinChunk is None
(default), the sequence editor is cleared.
@type proteinChunk: protein Chunk
@param inCursorPos: the position in the sequence in which to place the
cursor. If cursorPos is negative, the cursor position
is placed at first residue of the sequence (default).
@type inCursorPos: int
"""
if proteinChunk:
assert isinstance(proteinChunk, self.win.assy.Chunk) and \
proteinChunk.isProteinChunk()
self.current_protein = proteinChunk
else:
# Use self.current_protein. Make sure it's not None.
#assert isinstance(self.current_protein, self.win.assy.Chunk) and \
#proteinChunk.isProteinChunk()
self.clear()
return
# We have a protein chunk. Update the editor with its sequence.
sequence = self.current_protein.protein.get_sequence_string()
structure = self.current_protein.protein.get_secondary_structure_string()
self._setSequenceAndStructure(sequence, structure, inCursorPos = inCursorPos)
# Update the bg color to white.
self._sequence_changed = False
self._previousSequence = sequence
self._updateSequenceBgColor()
# Update window title with name of current protein.
titleString = 'Sequence Editor for ' + self.current_protein.name
self.setWindowTitle(titleString)
if not self.isVisible():
#Show the sequence editor if it isn't visible.
#ATTENTION: the sequence editor will (temporarily) close the
#Reports dockwidget (if it is visible). The Reports dockwidget
#is restored when the sequence Editor is closed.
self.show()
return
def setCursorPosition(self, inCursorPos = -1):
"""
Set the cursor position to I{cursorPos} in the sequence textedit widget.
@param inCursorPos: the position in the sequence in which to place the
cursor. If cursorPos is negative, the cursor position
is placed at the beginning of the sequence (default).
@type inCursorPos: int
"""
# Make sure cursorPos is in the valid range.
if inCursorPos < 0:
cursorPos = 0
anchorPos = 1
elif inCursorPos >= self.getSequenceLength():
cursorPos = self.getSequenceLength() - 1
anchorPos = self.getSequenceLength()
else:
cursorPos = inCursorPos
anchorPos = inCursorPos + 1
# Useful print statements for debugging.
if 0:
print "setCursorPosition(): Sequence=", self.getPlainSequence()
print "Final inCursorPos=%d\ncursorPos=%d, anchorPos=%d" % \
(inCursorPos, cursorPos, anchorPos)
self._suppress_cursorPosChanged_signal = True
# Finally, set the cursor position in the sequence.
cursor = self.sequenceTextEdit.textCursor()
cursor.setPosition(anchorPos, QTextCursor.MoveAnchor)
cursor.setPosition(cursorPos, QTextCursor.KeepAnchor)
self.sequenceTextEdit.setTextCursor( cursor )
cursorMate = self.secStrucTextEdit.textCursor()
cursorMate.setPosition(anchorPos, QTextCursor.MoveAnchor)
cursorMate.setPosition(cursorPos, QTextCursor.KeepAnchor)
self.secStrucTextEdit.setTextCursor( cursorMate )
cursorMate2 = self.aaRulerTextEdit.textCursor()
cursorMate2.setPosition(anchorPos, QTextCursor.MoveAnchor)
cursorMate2.setPosition(cursorPos, QTextCursor.KeepAnchor)
self.aaRulerTextEdit.setTextCursor( cursorMate2 )
self._updateToolTip()
self._suppress_cursorPosChanged_signal = False
return
def getCursorPosition( self ):
"""
Returns the cursor position in the sequence textedit widget.
"""
cursor = self.sequenceTextEdit.textCursor()
return cursor.position()
def _cursorPosChanged( self ):
"""
Slot called when the cursor position of the sequence textEdit changes.
When this happens, this method also changes the cursor position
of the 'Mate' text edit. Because of this, both the text edit widgets
in the Sequence Editor scroll 'in sync'.
"""
if self._suppress_cursorPosChanged_signal:
return
cursor = self.sequenceTextEdit.textCursor()
cursorPos = cursor.position()
if 0:
print "_cursorPosChanged(): cursorPos=", cursorPos
self.setCursorPosition(inCursorPos = cursorPos) # sets all three.
# Provide amino acid info as cursor position changes
env.history.statusbar_msg("")
current_command = self.win.commandSequencer.currentCommand
commandSet = ('EDIT_PROTEIN', 'EDIT_RESIDUES')
if current_command.commandName not in commandSet:
return
aa_index = min(cursorPos, self.getSequenceLength() - 1)
if current_command.commandName == 'EDIT_PROTEIN':
current_command.propMgr.setCurrentAminoAcid(aa_index)
if current_command.commandName == 'EDIT_RESIDUES':
current_command.propMgr._sequenceTableCellChanged(aa_index, 0)
current_command.propMgr.sequenceTable.setCurrentCell(aa_index, 3)
self._updateToolTip()
return
def _updateToolTip(self):
"""
Update the tooltip text (and status bar) with the current residue id.
"""
aa_index = self.current_protein.protein.get_current_amino_acid_index()
aa_info = self.current_protein.protein.get_amino_acid_id(aa_index)
aa_id, residue_id = aa_info.strip().split(":")
toolTipText = residue_id
self.sequenceTextEdit.setToolTip(str(toolTipText))
env.history.statusbar_msg(toolTipText)
return
def _display_and_recenter(self, index):
"""
Display and recenter the view on the current amino acid under the cursor
in the text edit
@param index: index of amino acid under cursor in sequence text edit
@type index: int
@note: this method has no callers. It will likely be moved to
EditResidues_PM soon. -Mark 2008-12-20
"""
chunk = self.current_protein
chunk.protein.collapse_all_rotamers()
current_aa = chunk.protein.get_amino_acid_at_index(index)
if current_aa:
if self.win.commandSequencer.currentCommand.commandName == 'EDIT_RESIDUES':
checked = self.win.commandSequencer.currentCommand.propMgr.recenterViewCheckBox.isChecked()
if checked:
ca_atom = current_aa.get_c_alpha_atom()
if ca_atom:
self.win.glpane.pov = -ca_atom.posn()
self.win.glpane.gl_update()
return
def _open_FASTA_File(self):
"""
Open (read) the user specified FASTA sequence file and load it into
the sequence field.
@TODO: It only reads in the first line of the file. Also, it doesn't
handle any special cases. (Once the special cases are clearly
defined, that functionality will be added.
@attention: This is not implemented yet.
"""
#Urmi 20080714: should not this be only fasta file, for both load and save
if self.parentWidget.assy.filename:
odir = os.path.dirname(self.parentWidget.assy.filename)
else:
odir = env.prefs[workingDirectory_prefs_key]
self.sequenceFileName = \
str(QFileDialog.getOpenFileName(
self,
"Load FASTA sequence for " + self.current_protein.name,
odir,
"FASTA file (*.txt);;All Files (*.*);;"))
lines = self.sequenceFileName
try:
lines = open(self.sequenceFileName, "rU").readlines()
except:
print "Exception occurred to open file: ", self.sequenceFileName
return
sequence = lines[0]
sequence = QString(sequence)
sequence = sequence.toUpper()
self._setSequence(sequence)
return
def _write_FASTA_File(self, fileName, sequence):
"""
Writes I{sequence} in FASTA format to I{filename}.
@param fileName: full path of the file.
@type fileName: str
@param sequence: AA sequence to be saved in FASTA format.
@type sequence: str
@attention: The sequence is not written in FASTA format yet.
@TODO: Write sequence in FASTA format.
"""
try:
f = open(fileName, "w")
except:
print "Exception occurred to open file %s to write: " % fileName
return None
f.write(str(sequence))
f.close()
return
def _savePeptideSequence(self):
"""
Save the current sequence (displayed in the sequence field) in FASTA
format in the specified file.
"""
if not self.sequenceFileName:
sdir = env.prefs[workingDirectory_prefs_key]
else:
sdir = self.sequenceFileName
fileName = QFileDialog.getSaveFileName(
self,
"Save Sequence As ...",
sdir,
"FASTA File (*.txt)"
)
if fileName:
fileName = str(fileName)
if fileName[-4] != '.':
fileName += '.txt'
if os.path.exists(fileName):
# ...and if the "Save As" file exists...
# ... confirm overwrite of the existing file.
ret = QMessageBox.warning(
self,
"Save Sequence...",
"The file \"" + fileName + "\" already exists.\n"\
"Do you want to overwrite the existing file or cancel?",
"&Overwrite", "&Cancel", "",
0, # Enter == button 0
1 ) # Escape == button 1
if ret == 1:
# The user cancelled
return
# write the current set of element colors into a file
self._write_FASTA_File(
fileName,
str(self.sequenceTextEdit.toPlainText()))
return
# ==== Methods to support find and replace.
# Should this (find and replace) be in its own class? -- Ninad 2007-11-28
def findNext(self):
"""
Find the next occurence of the search string in the sequence
"""
self._findNextOrPrevious()
return
def findPrevious(self):
"""
Find the previous occurence of the search string in the sequence
"""
self._findNextOrPrevious(findPrevious = True)
return
def _findNextOrPrevious(self, findPrevious = False):
"""
Find the next or previous matching string depending on the
findPrevious flag. It also considers into account various findFlags
user might have set (e.g. case sensitive search)
@param findPrevious: If true, this method will find the previous
occurance of the search string.
@type findPrevious: boolean
"""
findFlags = QTextDocument.FindFlags()
if findPrevious:
findFlags |= QTextDocument.FindBackward
if self.caseSensitiveFindAction.isChecked():
findFlags |= QTextDocument.FindCaseSensitively
if not self.sequenceTextEdit.hasFocus():
self.sequenceTextEdit.setFocus()
searchString = self.findLineEdit.text()
cursor = self.sequenceTextEdit.textCursor()
found = self.sequenceTextEdit.find(searchString, findFlags)
#May be the cursor reached the end of the document, set it at position 0
#to redo the search. This makes sure that the search loops over as
#user executes findNext multiple times.
if not found:
if findPrevious:
sequence_QString = self.sequenceTextEdit.toPlainText()
newCursorStartPosition = sequence_QString.length()
else:
newCursorStartPosition = 0
cursor.setPosition( newCursorStartPosition,
QTextCursor.MoveAnchor)
self.sequenceTextEdit.setTextCursor(cursor)
found = self.sequenceTextEdit.find(searchString, findFlags)
#Display or hide the warning widgets (that say 'sequence not found'
#based on the boolean 'found'
self._toggleWarningWidgets(found)
return
def _toggleWarningWidgets(self, found):
"""
If the given searchString is not found in the sequence string, toggle
the display of the 'sequence not found' warning widgets. Also enable
or disable the 'Replace' button accordingly
@param found: Flag that decides whether to sho or hide warning
@type found: boolean
@see: self.findNext, self.findPrevious
"""
if not found:
self.findLineEdit.setStyleSheet(self._getFindLineEditStyleSheet())
self.phraseNotFoundLabel.show()
self.warningSign.show()
self.replacePushButton.setEnabled(False)
else:
self.findLineEdit.setStyleSheet("")
self.phraseNotFoundLabel.hide()
self.warningSign.hide()
self.replacePushButton.setEnabled(True)
return
def findLineEdit_textEdited(self, searchString):
"""
Slot method called whenever the text in the findLineEdit is edited
*by the user* (and not by the setText calls). This is useful in
dynamically searching the string as it gets typed in the findLineedit.
@param searchString: string that is searched for
@type searchString: str
"""
self.findNext()
#findNext sets the focus inside the sequenceTextEdit. So set it back to
#to the findLineEdit to permit entering more characters.
if not self.findLineEdit.hasFocus():
self.findLineEdit.setFocus()
return
def replace(self):
"""
Find a string matching the searchString given in the findLineEdit and
replace it with the string given in the replaceLineEdit.
"""
searchString = self.findLineEdit.text()
replaceString = self.replaceLineEdit.text()
sequence = self.sequenceTextEdit.toPlainText()
#Its important to set focus on the sequenceTextEdit otherwise,
#cursor.setPosition and setTextCursor won't have any effect
if not self.sequenceTextEdit.hasFocus():
self.sequenceTextEdit.setFocus()
cursor = self.sequenceTextEdit.textCursor()
selectionStart = cursor.selectionStart()
selectionEnd = cursor.selectionEnd()
sequence.replace( selectionStart,
(selectionEnd - selectionStart),
replaceString )
cursor.setPosition((selectionEnd -1), QTextCursor.MoveAnchor)
self.sequenceTextEdit.setTextCursor(cursor)
#Set the sequence in the text edit.
self._setSequence(sequence)
#Find the next occurance of the 'seqrchString' in the sequence.
self.findNext()
return
| NanoCAD-master | cad/src/protein/ProteinSequenceEditor/ProteinSequenceEditor.py |
NanoCAD-master | cad/src/protein/ProteinSequenceEditor/__init__.py |
|
NanoCAD-master | cad/src/protein/model/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
Residue.py -- Residue class implementation.
Residue class stores information on individual amino acids of a protein
chain.
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
History:
piotr 082708: Re-factored the Residue class out of Protein.py file.
Renamed this class to "Residue" (which is a proper spelling, opposite
to "Residuum", as Eric D has pointed out in his email).
"""
# 3-letter to 1-letter amino acid name conversion
# The three-letter names are used to distinguish "protein" from "non-protein"
# residues in PDB reading code.
AA_3_TO_1 = {
'ALA':'A', # 20 standard amino acids
'VAL':'V',
'PHE':'F',
'PRO':'P',
'MET':'M',
'ILE':'I',
'LEU':'L',
'ASP':'D',
'GLU':'E',
'LYS':'K',
'ARG':'R',
'SER':'S',
'THR':'T',
'TYR':'Y',
'HIS':'H',
'CYS':'C',
'ASN':'N',
'GLN':'Q',
'TRP':'W',
'GLY':'G',
'2AS':'D', # Non-standard codes encountered in the PDB.
'3AH':'H', # Usually, these codes correspond to modified residues
'5HP':'E', # and are only used by the Protein class to convert between
'ACL':'R', # three- and single- letter representations.
'AIB':'A',
'ALM':'A',
'ALO':'T',
'ALY':'K',
'ARM':'R',
'ASA':'D',
'ASB':'D',
'ASK':'D',
'ASL':'D',
'ASQ':'D',
'AYA':'A',
'BCS':'C',
'BHD':'D',
'BMT':'T',
'BNN':'A',
'BUC':'C',
'BUG':'L',
'C5C':'C',
'C6C':'C',
'CCS':'C',
'CEA':'C',
'CHG':'A',
'CLE':'L',
'CME':'C',
'CSD':'A',
'CSO':'C',
'CSP':'C',
'CSS':'C',
'CSW':'C',
'CXM':'M',
'CY1':'C',
'CY3':'C',
'CYG':'C',
'CYM':'C',
'CYQ':'C',
'DAH':'F',
'DAL':'A',
'DAR':'R',
'DAS':'D',
'DCY':'C',
'DGL':'E',
'DGN':'Q',
'DHA':'A',
'DHI':'H',
'DIL':'I',
'DIV':'V',
'DLE':'L',
'DLY':'K',
'DNP':'A',
'DPN':'F',
'DPR':'P',
'DSN':'S',
'DSP':'D',
'DTH':'T',
'DTR':'W',
'DTY':'Y',
'DVA':'V',
'EFC':'C',
'FLA':'A',
'FME':'M',
'GGL':'E',
'GLZ':'G',
'GMA':'E',
'GSC':'G',
'HAC':'A',
'HAR':'R',
'HIC':'H',
'HIP':'H',
'HMR':'R',
'HPQ':'F',
'HTR':'W',
'HYP':'P',
'IIL':'I',
'IYR':'Y',
'KCX':'K',
'LLP':'K',
'LLY':'K',
'LTR':'W',
'LYM':'K',
'LYZ':'K',
'MAA':'A',
'MEN':'N',
'MHS':'H',
'MIS':'S',
'MLE':'L',
'MPQ':'G',
'MSA':'G',
'MSE':'M',
'MVA':'V',
'NEM':'H',
'NEP':'H',
'NLE':'L',
'NLN':'L',
'NLP':'L',
'NMC':'G',
'OAS':'S',
'OCS':'C',
'OMT':'M',
'PAQ':'Y',
'PCA':'E',
'PEC':'C',
'PHI':'F',
'PHL':'F',
'PR3':'C',
'PRR':'A',
'PTR':'Y',
'SAC':'S',
'SAR':'G',
'SCH':'C',
'SCS':'C',
'SCY':'C',
'SEL':'S',
'SEP':'S',
'SET':'S',
'SHC':'C',
'SHR':'K',
'SOC':'C',
'STY':'Y',
'SVA':'S',
'TIH':'A',
'TPL':'W',
'TPO':'T',
'TPQ':'A',
'TRG':'K',
'TRO':'W',
'TYB':'Y',
'TYQ':'Y',
'TYS':'Y',
'TYY':'Y',
'AGM':'R',
'GL3':'G',
'SMC':'C',
'ASX':'B',
'CGU':'E',
'CSX':'C',
'GLX':'Z' }
# 3- TO 1-letter conversion for PDB nucleotide names
NUC_3_TO_1 = {
' DG':'G',
' DA':'A',
' DC':'C',
' DT':'T',
' DU':'U',
' DI':'I',
' G':'G',
' A':'A',
' T':'T',
' U':'U',
' C':'C',
' I':'I' }
# Types of secondary structure as defined in PDB format.
# There are various definitions of secondary structure in use.
# The most common is a three-letter code: helix (H), extended (E),
# coil (C). PDB distingushes a fourth type, turn (T) that corresponds
# to the chain fragments that rapidly change direction, have
# a hydrogen bond pattern present, and are not helices nor strands.
# Currently, the turns are not used for visualization purposes in NE1.
SS_COIL = 0
SS_HELIX = 1
SS_STRAND = 2
SS_TURN = 3
# PDB atom name sets for chiral angles for amino acid side chains
CHI_ANGLES = { "GLY" : [ None,
None,
None,
None ],
"ALA" : [ None,
None,
None,
None ],
"SER" : [ [ "N" , "CA" , "CB" , "OG" ],
None,
None,
None ],
"GLU" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "CD" ],
[ "CB" , "CG" , "CD" , "OE1" ],
None ],
"GLN" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "CD" ],
[ "CB" , "CG" , "CD" , "OE1" ],
None ],
"ASP" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "OD1" ],
None,
None ],
"ASN" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "OD1" ],
None,
None ],
"CYS" : [ [ "N" , "CA" , "CB" , "SG" ],
None,
None,
None ],
"MET" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "SD" ],
None,
None ],
"THR" : [ [ "N" , "CA" , "CB" , "CG2" ],
None,
None,
None ],
"LEU" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "CD1" ],
None,
None ],
"ILE" : [ [ "N" , "CA" , "CB" , "CG1" ],
[ "CA" , "CB" , "CG1", "CD1" ],
None,
None ],
"VAL" : [ [ "N" , "CA" , "CB" , "CG" ],
None,
None,
None ],
"TRP" : [ [ "N" , "CA" , "CB" , "CG" ],
None,
None,
None ],
"TYR" : [ [ "N" , "CA" , "CB" , "CG" ],
None,
None,
None ],
"LYS" : [ [ "N" , "CA" , "CB" , "OG" ],
None,
None,
None ],
"ARG" : [ [ "N" , "CA" , "CB" , "CG" ],
None,
None,
None ],
"HIS" : [ [ "N" , "CA" , "CB" , "CG" ],
None,
None,
None ],
"PHE" : [ [ "N" , "CA" , "CB" , "CG" ],
[ "CA" , "CB" , "CG" , "CD1" ],
None,
None ] }
# Sets of atoms excluded from chi-angle rotations.
CHI_EXCLUSIONS = { "PHE" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
None,
None ],
"THR" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ],
"GLU" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
[ "CG", "HG2", "HG3" ],
None ],
"GLN" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
[ "CG", "HG2", "HG3" ],
None ],
"ASP" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
None,
None ],
"ASN" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
None,
None ],
"CYS" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ],
"MET" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
None,
None ],
"ARG" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ],
"LYS" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ],
"HIS" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ],
"LEU" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
None,
None ],
"ILE" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3" ],
None,
None ],
"SER" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ],
"TYR" : [ [ "N", "H", "C", "O", "CA", "HA" ],
[ "CB", "HB2", "HB3"],
None,
None ],
"TRP" : [ [ "N", "H", "C", "O", "CA", "HA" ],
None,
None,
None ] }
def calc_torsion_angle(atom_list):
"""
Calculates torsional angle defined by four atoms, A1-A2-A3-A4,
Return torsional angle value between atoms A2 and A3.
@param atom_list: list of four atoms describing the torsion bond
@type atom_list: list
@return: value of the torsional angle (float)
"""
# Note: this appears to be very general and perhaps ought to be moved to a more
# general place (someday), perhaps VQT.py or nearby. [bruce 080828 comment]
from Numeric import dot
from math import atan2, pi, sqrt
from geometry.VQT import cross
if len(atom_list) != 4:
# The list has to have four members.
return 0.0
# Calculate pairwise distances
v12 = atom_list[0].posn() - atom_list[1].posn()
v43 = atom_list[3].posn() - atom_list[2].posn()
v23 = atom_list[1].posn() - atom_list[2].posn()
# p is a vector perpendicular to the plane defined by atoms 1,2,3
# p is perpendicular to v23_v12 plane
p = cross(v23, v12)
# x is a vector perpendicular to the plane defined by atoms 2,3,4.
# x is perpendicular to v23_v43 plane
x = cross(v23, v43)
# y is perpendicular to v23_x plane
y = cross(v23, x)
# Calculate lengths of the x, y vectors.
u1 = dot(x, x)
v1 = dot(y, y)
if u1 < 0.0 or \
v1 < 0.0:
return 360.0
u2 = dot(p, x) / sqrt(u1)
v2 = dot(p, y) / sqrt(v1)
if u2 != 0.0 and \
v2 != 0.0:
# calculate the angle
return atan2(v2, u2) * (180.0 / pi)
else:
return 360.0
class Residue:
"""
This class implements a Residue object. The residue is an object
describing an individual amino acid of a protein chain.
"""
def __init__(self):
"""
"""
# list of residue atoms in the same order as they occur in PDB file
self.atom_list = []
# dictionary for atom_name -> atom mapping
self.atoms = {}
# amino acid secondary structure
self.secondary_structure = SS_COIL
# True if the residue is expanded. The feature is used by "Edit
# Rotamers" command for efficient rotamer manipulation in reduced
# protein display style.
self.expanded = False
# Rotamer color, used by "Edit Protein" command.
self.color = None
# These Rosetta-related attributes should be probably moved from this
# class to some Rosetta-related structure. For now, the Residue
# and Protein classes include several methods created for Rosetta
# purposes only.
# Rosetta name of mutation range.
self.mutation_range = "NATAA"
# Rosetta mutation descriptor. If set, it is usually a string of
# 20 characters, corresponding to amino acid allowed at a given position.
# Note: the descriptor is actually used by Rosetta only if mutation
# range is set to "PIKAA". Otherwise, it is used only for informational
# purposes.
self.mutation_descriptor = ""
# True if this residue will be using backrub mode.
self.backrub = False
def get_atom_name(self, atom):
"""
For a given PDB atom, return a corresponding atom name.
"""
if atom.pdb_info and \
atom.pdb_info.has_key('atom_name'):
return atom.pdb_info['atom_name']
else:
return None
def add_atom(self, atom, pdbname):
"""
Add a new atom to the atom dictionary.
"""
self.atoms[pdbname] = atom
self.atom_list.append(atom)
def get_first_atom(self):
"""
Return a first atom of the residue, or None.
@note: this method will cause an exception if the residue is empty
(has no atoms). This should never happen.
"""
if len(self.atom_list):
return self.atom_list[0]
raise Exception("Residue object has no atoms")
def get_atom_list(self):
"""
Return a list of atoms for the residue.
"""
return self.atom_list
def get_side_chain_atom_list(self):
"""
Return a list of side chain atoms for self. Assumes standard
PDB atom names.
"""
return [atom for atom in self.atom_list \
if self.get_atom_name(atom) not in ['C', 'N', 'O', 'H', 'HA']]
def get_three_letter_code(self):
"""
Return a three-letter amino acid code (the residue name).
This method returns " " (a string composed of three spaces)
if there is no amino acid code assigned.
@note: this method should probably scan all atoms looking for a
PDB residue key, not only the first one. For example, if a new atom
is added to a residue, the method may not return a valid three-letter
code anymore. This could be a desired and expected behavior, but it is
not guaranteed in the current implementation. -- piotr 080902
@return: amino acid three-letter name, or " " if the name is unknown.
"""
atom = self.get_first_atom()
if atom and \
atom.pdb_info:
if atom.pdb_info.has_key('residue_name'):
return atom.pdb_info['residue_name'][:3]
return " "
def get_one_letter_code(self):
"""
Return a one-letter amino acid code, or "X" if the residue code
is not recognized.
@note: see docstring in get_three_letter_code
"""
if AA_3_TO_1.has_key(self.get_three_letter_code()):
return AA_3_TO_1[self.get_three_letter_code()]
return "X"
def get_id(self):
"""
Return a residue ID.
The residue ID is a string representing the residue serial number
(integer value up to 9999) and concatenated residue insertion code
(single letter character). It is represented by a five character string.
"""
# REVIEW: docstring should clarify whether serial number
# is padded on left with ' ' or '0' (when less than 1000).
# [bruce 080904 comment]
atom = self.get_first_atom()
if atom.pdb_info:
if atom.pdb_info.has_key('residue_id'):
return atom.pdb_info['residue_id']
raise Exception("Residue has no ID")
def get_index(self):
"""
Return a residue index. The residue index is a numerical equivalent
of a residue ID (less the insertion code) and is provided for user's
convenience, i.e. when it is desired for the index to be used
independently from the residue insertion code. Also, see docstring
in get_id.
"""
# REVIEW: docstring of get_id suggests that residue_id will
# have 4 chars for serial number and 1 char for insertion code.
# But this makes use of the first 3 chars only.
# Needs bugfix or explanation. [bruce 080904 comment]
residue_id = self.get_id()
return int(residue_id[:3])
def has_atom(self, atom):
"""
Check if the atom belongs to self.
@param atom: atom to be checked
@type atom: Atom
@return: True if the atom belongs to self, False otherwise
"""
if atom in self.atoms.values():
return True
else:
return False
def set_secondary_structure(self, sec):
"""
Set a secondary structure type for this residue.
@param sec: secondary structure type to be assigned
@type sec: int
"""
self.secondary_structure = sec
def get_secondary_structure(self):
"""
Retrieve a secondary structure type.
@return: secondary structure of this residue.
"""
return self.secondary_structure
def get_atom_by_name(self, name):
"""
Returns a residue atom for a given PDB atom name, or None if not found.
The PDB name corresponds to the atom label as defined in PDB file.
Peptide Builder can create proper atom labels.
This intentionally and without a warning returns None if the atom
of a given name is not found. It is caller's responsibility
to handle such case properly. --piotr 080902
@param name: name of the atom
@type name: string
@return: atom or None
@rtype: Atom
"""
if self.atoms.has_key(name):
return self.atoms[name]
else:
return None
def get_c_alpha_atom(self):
"""
Return an alpha-carbon atom atom (or None).
@return: alpha carbon atom
"""
return self.get_atom_by_name("CA")
def get_c_beta_atom(self):
"""
Return a beta carbon atom (or None).
@return: beta carbon atom
"""
return self.get_atom_by_name("CB")
def get_n_atom(self):
"""
Return a backbone nitrogen atom.
@return: backbone nitrogen atom
"""
return self.get_atom_by_name("N")
def get_c_atom(self):
"""
Return a backbone carbon atom.
@return: backbone carbonyl group carbon atom
"""
return self.get_atom_by_name("C")
def get_o_atom(self):
"""
Return a backbone oxygen atom.
@return: backbone carbonyl group oxygen atom
"""
return self.get_atom_by_name("O")
def set_mutation_range(self, range):
"""
Sets a mutation range according to Rosetta definition.
@param range: mutation range
@type range: string
"""
self.mutation_range = range
def get_mutation_range(self):
"""
Gets a mutation range according to Rosetta definition.
nie,.
@return: range
"""
return self.mutation_range
def set_mutation_descriptor(self, descriptor):
"""
Sets a mutation descriptor according to Rosetta definition.
@param descriptor: Rosetta mutation descriptor
@type descriptor: string (20-characters long)
"""
self.mutation_descriptor = descriptor
def get_mutation_descriptor(self):
"""
Returns a mutation descriptor according to Rosetta definition.
@return descriptor: string (20-characters long)
"""
return self.mutation_descriptor
def get_chi_atom_list(self, which):
"""
Create a list of four atoms for computing a given chi angle.
Return an empty list if no such angle exists for self, or if
residue name doesn't match one of the 20 standard amino acid names,
or if the specified chi angle is out of allowed range (which is 0..3).
@param which: chi angle (0=chi1, 1=chi2, and so on)
@type which: int
@return: list of four atoms, or empty list
"""
if which in range(4):
residue_name = self.get_three_letter_code()
if CHI_ANGLES.has_key(residue_name):
chi_list = CHI_ANGLES[residue_name]
if chi_list[which]:
chi_atom_names = chi_list[which]
chi_atoms = []
for name in chi_atom_names:
atom = self.get_atom_by_name(name)
if atom:
chi_atoms.append(atom)
return chi_atoms
return []
def get_chi_atom_exclusion_list(self, which):
"""
Creates a list of atoms excluded from rotation for a current amino acid.
Returns an empty list if wrong chi angle is requested.
@param which: chi angle (0=chi1, 1=chi2, and so on)
@type which: int
@return: list of atoms to be excluded from rotation
"""
ex_atoms = []
if which in range(4):
residue_name = self.get_three_letter_code()
if CHI_EXCLUSIONS.has_key(residue_name):
chi_ex_list = CHI_EXCLUSIONS[residue_name]
oxt_atom = self.get_atom_by_name("OXT")
if oxt_atom:
ex_atoms.append(oxt_atom)
for w in range(0, which + 1):
if chi_ex_list[w]:
ex_atom_names = chi_ex_list[w]
for name in ex_atom_names:
atom = self.get_atom_by_name(name)
if atom:
ex_atoms.append(atom)
return ex_atoms
def get_chi_angle(self, which):
"""
Computes the side-chain Chi angle. Returns None if the angle
doesn't exist.
@note: This method returns None if the chi angle doesn't exist.
This is intentional and callers should be aware of it.
@param which: chi angle (0=chi1, 1=chi2, and so on)
@type which: int
@return: value of the specified chi angle, or None
"""
chi_atom_list = self.get_chi_atom_list(which)
if chi_atom_list:
return calc_torsion_angle(chi_atom_list)
else:
return None
def get_atom_list_to_rotate(self, which):
"""
Create a list of atoms to be rotated around a specified chi angle.
Returns an empty list if wrong chi angle is requested, or if all
atoms are going to be excluded.
piotr 082008: This method should be rewritten in a way so it
traverses a molecular graph rather than uses a predefined
lists of atoms "excluded" and "included" from rotations.
Current implementation only works for "proper" amino acids
that have all atoms named properly and don't include any
non-standard atoms.
@param which: chi angle (0=chi1, 1=chi2, and so on)
@type which: int
@return: list of atoms to be rotated for a specified chi angle
"""
atom_list = []
chi_atom_exclusion_list = self.get_chi_atom_exclusion_list(which)
if chi_atom_exclusion_list:
all_atom_list = self.get_atom_list()
for atom in all_atom_list:
if atom not in chi_atom_exclusion_list:
atom_list.append(atom)
return atom_list
def lock(self):
"""
Locks this residue (sets Rosetta mutation range to "native rotamer").
"""
self.set_mutation_range("NATRO")
def set_chi_angle(self, which, angle):
"""
Sets a specified chi angle of this amino acid.
@param which: chi angle (0=chi1, 1=chi2, and so on)
@type which: int
@param angle: value of the chi angle to be set
@type angle:float
@note: this method intentionally returns None if it is not possible
to set the specified chi angle
@return: angle value if sucessfully completed, None if not
"""
# Note: Eric M said he factored some intrinsic coordinate code
# out of some other file to create a general function for that.
# Is this also something that could use that function?
# If so, it's enough for now to comment this saying so
# rather than to actually refactor it. [bruce 080828 comment]
#
# piotr 080902 reply:
# I think that is different than the internal-to-cartesian
# coordinate conversion. Perhaps the code Eric M re-factored from
# Peptide Builder could be adapted to be used for torsion angle
# manipulations, but I think current implementation is more
# straightforward. The "rotate point around a vector" routine
# should be split out, though (and perhaps an equivalent method
# exists somewhere in the codebase).
from geometry.VQT import norm, Q, V
from math import pi, cos, sin
# Get a list of atoms to rotate.
chi_atom_list = self.get_chi_atom_list(which)
if len(chi_atom_list) > 0:
# Calculate a current chi torsion angle.
angle0 = calc_torsion_angle(chi_atom_list)
# Calculate a difference between the current angle and
# a requested chi angle.
dangle = angle - angle0
if abs(dangle) > 0.0:
# Vector we are rotating about is the vector connecting
# two middle atoms of the chi angle atom list.
vec = norm(chi_atom_list[2].posn() - chi_atom_list[1].posn())
# Compute a list of atoms to rotate.
atom_list = self.get_atom_list_to_rotate(which)
first_atom_posn = chi_atom_list[1].posn()
for atom in atom_list:
# Move the origin to the first atom.
pos = atom.posn() - first_atom_posn
cos_a = cos(pi * (dangle / 180.0))
sin_a = sin(pi * (dangle / 180.0))
q = V(0, 0, 0)
# Rotate the point around a vector
q[0] += (cos_a + (1.0 - cos_a) * vec[0] * vec[0]) * pos[0];
q[0] += ((1.0 - cos_a) * vec[0] * vec[1] - vec[2] * sin_a) * pos[1];
q[0] += ((1.0 - cos_a) *
vec[0] * vec[2] + vec[1] * sin_a) * pos[2];
q[1] += ((1.0 - cos_a) *
vec[0] * vec[1] + vec[2] * sin_a) * pos[0];
q[1] += (cos_a + (1.0 - cos_a) * vec[1] * vec[1]) * pos[1];
q[1] += ((1.0 - cos_a) * vec[1] * vec[2] - vec[0] * sin_a) * pos[2];
q[2] += ((1.0 - cos_a) * vec[0] * vec[2] - vec[1] * sin_a) * pos[0];
q[2] += ((1.0 - cos_a) * vec[1] * vec[2] + vec[0] * sin_a) * pos[1];
q[2] += (cos_a + (1.0 - cos_a) * vec[2] * vec[2]) * pos[2];
# Move the origin back to the previous position
q += first_atom_posn
# Set the atom position.
atom.setposn(q)
return angle
return None
def expand(self):
"""
Expand a residue side chain.
"""
self.expanded = True
def collapse(self):
"""
Collapse a residue side chain.
"""
self.expanded = False
def is_expanded(self):
"""
Return True if side chain of this amino acid is expanded.
"""
return self.expanded
def set_color(self, color):
"""
Set a rotamer color for current amino acid.
"""
self.color = color
def set_backrub_mode(self, enable_backrub):
"""
Set Rosetta backrub mode (True or False).
@param enable_backrub: should backrub mode be enabled for this residue
@type enable_backrub: boolean
"""
self.backrub = enable_backrub
def get_backrub_mode(self):
"""
Get Rosetta backrub mode (True or False).
@return: is backrub enabled for this residue (boolean)
"""
return self.backrub
pass # end of class Residue
| NanoCAD-master | cad/src/protein/model/Residue.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
Protein.py -- Protein class implementation.
The Protein class stores protein-related information and provides several
methods used by Protein display style and Rosetta simulations.
Currently, the protein objects can be created by reading a protein
structure from PDB file or by using Peptide Builder.
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
History:
piotr 080707: Created a preliminary version of the Protein class.
piotr 081908: Completed docstrings and documented better the code.
piotr 082008: Better documentation of this file; code re-factoring.
To do:
- get_id_for_aa(): Add flag options for customizing the description(s) returned for aa_ids.
"""
import foundation.env as env
from utilities.debug_prefs import debug_pref, Choice_boolean_False
from utilities.prefs_constants import rosetta_backrub_enabled_prefs_key
from protein.model.Residue import Residue
from protein.model.Residue import SS_HELIX, SS_STRAND, SS_COIL, SS_TURN
from protein.model.Residue import AA_3_TO_1, NUC_3_TO_1
# Utility methods used by PDB reading code, perhaps they should be moved
# to files_pdb.py
def is_water(resName):
"""
Check if a PDB residue is a water molecule.
@param resName: PDB residue name (3-letter string)
@type resName: string
"""
water_codes = ["H2O", "HHO", "OHH", "HOH", "OH2", "SOL", "WAT", "DOD",
"DOH", "HOD", "D2O", "DDO", "ODD", "OD2", "HO1", "HO2",
"HO3", "HO4"]
if resName[:3] in water_codes:
return True
return False
def is_amino_acid(resName):
"""
Check if a PDB residue is an amino acid.
@param resName: PDB residue name (3-letter string)
@type resName: string
"""
if AA_3_TO_1.has_key(resName[:3]):
return True
return False
def is_nucleotide(resName):
"""
Check if a PDB residue is a nucleotide.
@param resName: PDB residue name (3-letter string)
@type resName: string
"""
if NUC_3_TO_1.has_key(resName[:3]):
return True
return False
class Protein:
"""
This class implements a protein model in NanoEngineer-1.
See module docstring for more info.
"""
# This class was implemented by Piotr in July 2008.
def __init__(self):
# Dictionary that maps residue names to residue objects.
self.residues = {}
# Ordered list of amino acids.
self.residues_list = []
# Ordered list of alpha carbon atoms. It should contain at least one atom.
# This could be probably pre-calculated every time
# [I can't tell what that last sentence means -- every time that what occurs?
# motivation? -- bruce 080828]
self.ca_atom_list = []
# Single-character chain identifier.
self.chainId = ''
# PDB identifier of the protein, typically, a four character string
# in the following format: "1abc"
self.pdbId = ""
# Index of "current" amino acid (used by Edit Protein command).
self.current_aa_idx = 0
# Display list for expanded rotamers, used by ProteinChunk.draw_realtime
# The purpose of this list is to speed up drawing of "expanded" rotamers,
# and avoid re-generating protein models in reduced display style
# if a modification is made to side chain atoms and not to backbone
# atoms (e.g. if a side chain chi angle was edited).
# The idea is to allow for simultaneous displaying of atomistic
# (for expanded rotamers) and reduced (for backbone) representations.
# This implementation is wrong, as the display list is never properly
# deleted. This attribute could be moved to Chunk class, or implemented
# in a different way, so the list is deleted in current OpenGL context.
# Potentially, current implementation can cause memory leaks by not
# deleting display lists.
self.residues_dl = None
def set_chain_id(self, chainId):
"""
Sets a single letter chain ID.
@param chainId: chain ID of current protein
@type chainId: character
"""
self.chainId = chainId
def get_chain_id(self):
"""
Gets a single letter chain ID.
@return: chain ID of current protein (character)
"""
return self.chainId
def set_pdb_id(self, pdbId):
"""
Set a four-letter PDB identifier.
@param pdbId: PDB ID of current protein
@type pdbId: string (four characters)
"""
self.pdbId = pdbId
def get_pdb_id(self):
"""
Return a four-letter PDB identifier.
@return: PDB ID of current protein (four-character string)
"""
return self.pdbId
def add_pdb_atom(self, atom, pdbname, resId, resName, setType = False):
"""
Adds a new atom to the protein. Returns a residue that the atom
has been added to.
@param atom: new atom to be added to the protein
@type atom: Atom
@param pdbname: PDB name (label) of the atom (up to four characters)
@type pdbname: string
@param resId: PDB residue ID (an integer, usually)
@type resId: integer
@param resName: PDB residue name
@type name: string
@param setType: if True, try to determine the atom type based on
PDB residue name and atom name
@type setType: boolean
@return: residue the atom has been added to (Residue)
"""
if self.residues.has_key(resId):
# Find an existing residue.
aa = self.residues[resId]
else:
# This is a new residue.
aa = Residue()
self.residues[resId] = aa
# Append the residue to amino acid list to have a properly ordered
# list of amino acids.
self.residues_list.append(aa)
# Add the atom to the residue.
aa.add_atom(atom, pdbname)
# If this is an alpha carbon atom, add it to the list of alpha carbons.
if pdbname == "CA":
self.ca_atom_list.append(atom)
return aa
def is_c_alpha(self, atom):
"""
Check if the atom is a C-alpha atom.
@param atom: atom to be tested
@type atom: Atom
@return: True if atom is an alpha carbon atom, False if it is not
@rtype: boolean
"""
if atom in self.ca_atom_list:
return True
else:
return False
def count_c_alpha_atoms(self):
"""
Return a total number of alpha carbon atoms in the protein
(usually equal to the protein sequence length).
@return: number of C-alpha atoms (integer)
"""
return len(self.ca_atom_list)
def get_c_alpha_atoms(self):
"""
Return a list of alpha carbon atoms.
@note: the returned list is mutable and should not be modified
outside of the Protein class.
@return: list of alpha carbon atoms
"""
return self.ca_atom_list
def is_c_beta(atom):
"""
Check if the atom is a C-beta atom.
@param atom: atom to be tested
@type atom: Atom
@return: True if atom is a carbon-beta atom, False if it is not.
@rtype: boolean
"""
if atom in self.cb_atom_list:
return True
else:
return False
def get_sequence_string(self):
"""
Create and return a protein sequence string.
@return: string corresponding to the protein sequence in 1-letter code
"""
seq = ""
for aa in self.get_amino_acids():
seq += aa.get_one_letter_code()
return seq
def set_rosetta_protein_secondary_structure(self, inProtein):
"""
Set the secondary structure of the protein outputted from rosetta to that
of the inProtein.
@param inProtein:input protein chunk
@type inProtein: L{Chunk}
"""
#Urmi 20080728: created to set the secondary structure of the rosetta
#outputted protein
#
# piotr 081908: Explanation. Rosetta fixed backbone simulation doesn't
# change the backbone atom positions, so it is safe to copy the secondary
# structure information from the input protein.
# piotr 082008: This is no longer true for flexible backbone simulations,
# i.e. when using the backrub mode. It is not going to cause major problems,
# as the backbone changes are relatively minor, but in general we need
# a secondary structure computation algorithm.
aa_list_for_rosetta = self.get_amino_acids()
i = 0
for aa in inProtein.protein.get_amino_acids():
ss = aa.get_secondary_structure()
aa_list_for_rosetta[i].set_secondary_structure(ss)
i = i + 1
def get_secondary_structure_string(self):
"""
Create and return a protein sequence string. 'H' corresponds
to helical conformation, 'E' corresponds to extended secondary
structure, '-' corresponds to coil (other types of secondary structure).
@return: secondary structure string
"""
ss_str = ""
for aa in self.get_amino_acids():
ss = aa.get_secondary_structure()
if ss == SS_HELIX:
ss_str += "H"
elif ss == SS_STRAND:
ss_str += "E"
else:
ss_str += "-"
return ss_str
# The two methods below (get_id_for_aa and get_amino_acid_id)
# should probably be renamed, the names are confusing now -- piotr 080902
def get_id_for_aa(self, aa, index):
"""
Create and return an info text describing a specified residue.
(See "get_amino_acid_id" method docstring for more information.)
@param aa: queried amino acid
@type aa: Residue
@param index: index of the queried amino acid [0, sequence_length-1]
@type index: int
@return: string describing this residue
"""
# REVIEW: should this be private? Also, I guessed "@type aa".
# [bruce 080904 comment]
aa_id = self.get_pdb_id() + \
self.get_chain_id() + \
"[" + \
repr(index+1) + \
"] : " + \
aa.get_three_letter_code() + \
"[" + \
repr(int(aa.get_id())) + \
"]"
return aa_id
def get_amino_acid_id(self, index):
"""
Create and return a descriptive text related to a residue of a given
sequence index. The text is composed of protein name, index, residue name,
residue index.
@note: this method will cause an exception if there is no residue
of the specified index
@param index: index of a queried amino acid [0, sequence_length-1]
@type index: int
@return: string describing this residue
"""
aa_list = self.get_amino_acids()
if index in range(len(aa_list)):
aa = aa_list[index]
aa_id = self.get_id_for_aa(aa, index)
return aa_id
raise Exception("Residue index is out of range: %d" % index)
def get_amino_acid_id_list(self):
"""
Create and return a list of residue descriptions. See get_amino_acid_id
for details on the description format.
@return: list of residue descriptions for all amino acids
"""
id_list = []
index = 0
for aa in self.get_amino_acids():
aa_id = self.get_id_for_aa(aa, index)
id_list.append(aa_id)
index += 1
return id_list
def get_amino_acids(self):
"""
Return a list of residues in this protein.
@note: the returned list is mutable and should not be modified
outside of the Protein class.
@return: list of residues
"""
return self.residues_list
def count_amino_acids(self):
"""
Returns the number of amino acids.
"""
return len(self.residues_list)
def assign_helix(self, resId):
"""
Assign a helical secondary structure to resId.
@note: this method will raise an exception if a residue of a
specified resId doesn't exist
@param resId: residue ID for secondary structure assignment
@type resId: int
"""
if self.residues.has_key(resId):
aa = self.residues[resId]
aa.set_secondary_structure(SS_HELIX)
raise Exception("Specified residue doesn't exist")
def assign_strand(self, resId):
"""
Assign a beta secondary structure to resId.
The proper name of this secondary structure type is
"beta strand", but names "beta", "strand", "extended" are used
interchangeably (PDB files use "STRAND" name to mark the beta
conformation fragments).
@note: this method will raise an exception if a residue of a
specified resId doesn't exist
@param resId: residue ID for secondary structure assignment
@type resId: int
"""
if self.residues.has_key(resId):
aa = self.residues[resId]
aa.set_secondary_structure(SS_STRAND)
raise Exception("Specified residue doesn't exist")
def assign_turn(self, resId):
"""
Assign a turn secondary structure to resId.
@note: this method will raise an exception if a residue of a
specified resId doesn't exist
@param resId: residue ID for secondary structure assignment
@type resId: int
"""
if self.residues.has_key(resId):
aa = self.residues[resId]
aa.set_secondary_structure(SS_TURN)
raise Exception("Specified residue doesn't exist")
def expand_rotamer(self, aa):
"""
Expand a side chain of a given residue.
@note: aa should belong to the Protein object.
@param aa: amino acid to expand
@type aa: Residue
@return: True if a given residue belongs to self, or False otherwise.
"""
if aa in self.residues_list:
self.residues_dl = None
aa.expand()
return True
return False
def is_expanded(self, aa):
"""
Check if a given amino acid's rotamer is expanded.
@param aa: amino acid to check
@type aa: Residue
@return: True if amino acid's side chain is expanded
"""
return aa.is_expanded()
def collapse_all_rotamers(self):
"""
Collapse all side chains.
"""
self.residues_dl = None
self.residues_hi_dl = None
for aa in self.residues.values():
aa.collapse()
def expand_all_rotamers(self):
"""
Expand all side chains.
"""
self.residues_dl = None
self.residues_hi_dl = None
for aa in self.residues.values():
aa.expand()
def get_residue(self, atom):
"""
For a given atom, return a residue that the atom belongs to.
@param atom: atom to look for
@type atom: Atom
@return: residue the atom belongs to, or None if not found
"""
for aa in self.residues.itervalues():
if aa.has_atom(atom):
return aa
return None
def traverse_forward(self):
"""
Increase an index of the current amino acid. The index is an
attribute of self (Protein class).
@return: True if the forward step is possible, otherwise False.
"""
if self.current_aa_idx < len(self.residues) - 1:
self.current_aa_idx += 1
return True
return False
def traverse_backward(self):
"""
Decrease an index of the current amino acid. The index is an
attribute of self (Protein class).
@return: True if the backward step is possible, otherwise False.
"""
if self.current_aa_idx > 0:
self.current_aa_idx -= 1
return True
return False
# General comment regarding the "current residue" mechanism. The purpose
# of the "current_aa_idx" attribute is to have a mechanism for selecting
# and focusing on an individual amino acid. Currently, this mechanism
# is only used by "Edit Protein" command and probably the "Edit Protein"
# command should keep track of the current residue. It would be
# better if this attribute was removed from the Protein class.
# -- piotr 080902
def get_current_amino_acid(self):
"""
Get current amino acid.
@return: current amino acid (Residue)
"""
if self.current_aa_idx in range(len(self.residues_list)):
return self.residues_list[self.current_aa_idx]
return None
def get_amino_acid_at_index(self, index):
"""
Return the amino acid at the given index.
@note: This method returns None if there is no amino acid at the
specified index. This is intentional - callers should be aware of it.
@param index: index of amino acid requested
@type index: int
@return: amino acid (Residue)
"""
#Urmi 20080728: created to do the two way connection between protein
#sequence editor and residue combo box
if index in range(len(self.residues_list)):
return self.residues_list[index]
return None
def get_current_amino_acid_index(self):
"""
Get index of current amino acid.
@return: index of current amino acid (integer)
"""
return self.current_aa_idx
def set_current_amino_acid_index(self, index):
"""
Set index of current amino acid (if it's in the allowed range).
@param index: index of current amino acid
@type index: integer
@return: True if the index is allowed, False if it is out of allowed range
@rtype: boolean
"""
if index in range(len(self.residues_list)):
self.current_aa_idx = index
return True
else:
return False
def get_number_of_backrub_aa(self):
"""
Returns a number of backrub amino acids.
@return: number of amino acids assigned as "backrub"
@rtype: integer
"""
nbr = 0
for aa in self.get_amino_acids():
if aa.get_backrub_mode():
nbr += 1
return nbr
def is_backrub_setup_correctly(self):
"""
Returns True if the backrub table is properly set up, False otherwise.
@rtype: boolean
"""
last_aa = None
# Check if at least two consecutive amino acids have backrub flag
# set as True.
for aa in self.get_amino_acids():
if last_aa and \
last_aa.get_backrub_mode() and \
aa.get_backrub_mode():
return True
last_aa = aa
return False
def edit(self, win):
"""
Edit the protein chunk.
@note: Probably this method should not reside here, since this file is for
the actual model. Maybe we'll take care of that when we move to the
new model
"""
win.commandSequencer.userEnterCommand('EDIT_PROTEIN')
return
def _getCopyOfResidues(self):
"""
Returns a (deep copy) of the residues dict.
@note: NIY
"""
for aa in self.residues.values():
print aa
return
# override abstract method of DataMixin
def _copyOfObject(self):
"""
Create and return a copy of protein.
"""
protein = Protein()
protein.set_chain_id(self.get_chain_id())
protein.set_pdb_id(self.get_pdb_id())
protein.set_current_amino_acid_index(self.get_current_amino_acid_index())
#@@@ BUG: residues_list, ca_atom_list, and residues aren't copied
# completely since they contain compound objects (i.e. Residues with
# lists, dicts, etc).
# See add_pdb_atom() code to see how residues are created for
# these lists/dicts. Need help from Bruce. --Mark 2008-12-25
if 1:
protein.residues_list = list(self.residues_list)
protein.ca_atom_list = list(self.ca_atom_list)
protein.residues = dict(self.residues)
else:
# Using copy.deepcopy also fails. Found a reference here:
# http://mail.python.org/pipermail/python-dev/2008-June/080772.html
# which states that it's possible that "residues_list" contains an
# object that cannot be copied (i.e. array.array).
# Evidently the problem was corrected with python 2.4.4.
# I am running Python 2.4. Is it worth upgrading to 2.4.4?
# --Mark 2008-12-25
import copy
protein.residues_list = copy.deepcopy(self.residues_list)
protein.ca_atom_list = copy.deepcopy(self.ca_atom_list)
protein.residues = copy.deepcopy(self.residues)
protein.residues_dl = None # DL gets rebuilt in ProteinChunks.drawchunk_realtime
print "Protein._copyOfObject(): HERE!"
return protein
# override abstract method of DataMixin.
# Ask Bruce to review. --Mark 2008-12-25
def __eq__(self, other):
"""
Compare self with other.
"""
print "Protein.__eq__(): HERE!"
if self.chain_id != other.chain_id:
return False
elif self.pdb_id != other.pdb_id:
return False
elif self.current_aa_idx != other.current_aa_idx:
return False
elif self.residues is not other.residues: # Is this right?
return False
elif self.residues_list is not other.residues_list: # Is this right?
return False
elif self.ca_atom_list is not other.ca_atom_list: # Is this right?
return False
else:
return True
pass
pass # end of class Protein
# Protein helper methods should be located here.
# Mark 2008-12-14
def getAllProteinChunksInPart(assy):
"""
Returns a list of all the protein chunks in assy.
@return: a list of all the protein chunks in assy.
@rtype: list of chunks
"""
proteinChunkList = []
for mol in assy.molecules:
if mol.isProteinChunk():
proteinChunkList.append(mol)
return proteinChunkList
# piotr 082008: This and possibly several Rosetta-related methods of the Protein
# class should be re-factored and moved to a separate file in simulations/ROSETTA.
def write_rosetta_resfile(filename, chunk):
"""
Write a Rosetta resfile for a given protein chunk. Return True
if successfully written, otherwise return False. Writes backrub
information if the backrub mode is enabled in user preferences.
Currently, we only support single-chain Rosetta simulations.
@param chunk: protein chunk to be written
"""
# Make sure this is a valid protein chunk.
if chunk is None or \
chunk.protein is None:
return False
# Check if the backrub mode is enabled.
use_backrub = env.prefs[rosetta_backrub_enabled_prefs_key]
# Get a list of amino acids.
amino_acids = chunk.protein.get_amino_acids()
# Open the output file.
f = open(filename, "w")
if not f:
return False
# Write a standard file header.
f.write(" This file specifies which residues will be varied\n")
f.write(" \n")
f.write(" Column 2: Chain \n")
f.write(" Column 4-7: sequential residue number \n")
f.write(" Column 9-12: pdb residue number \n")
f.write(" Column 14-18: id (described below) \n")
f.write(" Column 20-40: amino acids to be used \n")
f.write(" \n")
f.write(" NATAA => use native amino acid \n")
f.write(" ALLAA => all amino acids \n")
f.write(" NATRO => native amino acid and rotamer \n")
f.write(" PIKAA => select inividual amino acids \n")
f.write(" POLAR => polar amino acids \n")
f.write(" APOLA => apolar amino acids \n")
f.write(" \n")
f.write(" The following demo lines are in the proper format\n")
f.write(" \n")
f.write(" A 1 3 NATAA \n")
f.write(" A 2 4 ALLAA \n")
f.write(" A 3 6 NATRO \n")
f.write(" A 4 7 NATAA \n")
f.write(" B 5 1 PIKAA DFLM \n")
f.write(" B 6 2 PIKAA HIL \n")
f.write(" B 7 3 POLAR \n")
f.write(" -------------------------------------------------\n")
# Begin the actual data records.
f.write(" start\n")
index = 0
for aa in amino_acids:
# For each consecutive amino acid
index += 1
mut = aa.get_mutation_range()
# Write the amino acid and its mutation range name
out_str = " " + \
chunk.protein.get_chain_id() + \
"%5d" % int(index) + \
"%6s" % aa.get_id() + \
mut
if use_backrub and \
aa.backrub:
# Append "B" when in backrub mode.
out_str += "B"
if mut == "PIKAA":
out_str += " " + aa.get_mutation_descriptor().replace("_","") + "\n"
else:
out_str += "\n"
f.write(out_str)
# Close the output file.
f.close()
return True
| NanoCAD-master | cad/src/protein/model/Protein.py |
NanoCAD-master | cad/src/protein/commands/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.changes as changes
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from command_support.EditCommand import EditCommand
from utilities.constants import red
from protein.commands.ProteinDisplayStyle.ProteinDisplayStyle_PropertyManager import ProteinDisplayStyle_PropertyManager
# == GraphicsMode part
_superclass_for_GM = SelectChunks_GraphicsMode
class ProteinDisplayStyle_GraphicsMode(SelectChunks_GraphicsMode ):
"""
Graphics mode for (Protein) Display Style command.
"""
pass
# == Command part
_superclass = EditCommand
class ProteinDisplayStyle_Command(EditCommand):
#class ProteinDisplayStyle_Command(BuildProtein_Command):
"""
"""
# class constants
GraphicsMode_class = ProteinDisplayStyle_GraphicsMode
PM_class = ProteinDisplayStyle_PropertyManager
commandName = 'EDIT_PROTEIN_DISPLAY_STYLE'
featurename = "Protein Display Style"
from utilities.constants import CL_GLOBAL_PROPERTIES
command_level = CL_GLOBAL_PROPERTIES
command_should_resume_prevMode = True
command_has_its_own_PM = True
flyoutToolbar = None
def _getFlyoutToolBarActionAndParentCommand(self):
"""
See superclass for documentation.
@see: self.command_update_flyout()
"""
flyoutActionToCheck = 'displayProteinStyleAction'
parentCommandName = 'BUILD_PROTEIN'
return flyoutActionToCheck, parentCommandName
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
(and as of 2008-03-06, it is proposed that dna_updater calls this method
when needed.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
return bool_keep
| NanoCAD-master | cad/src/protein/commands/ProteinDisplayStyle/ProteinDisplayStyle_Command.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
ProteinDisplayStyle_PropertyManager.py
The ProteinDisplayStyle_PropertyManager class provides a Property Manager
for the B{Display Style} command on the flyout toolbar in the
Build > Protein mode.
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
History: Urmi copied this from DnaDisplayStyle_PropertyManager.py and modified
it to suit the needs of protein display.
To do:
- Fix bug: a single rotamer is displayed (i.e. expanded) by default.
- Change "Style" factory setting to "Trace (ball and stick)
- Block widget signals to eliminate unneccessary repaints of the model view.
(i.e. self.updateProteinDisplayStyleWidgets(blockSignals = True))
"""
import os, time, fnmatch
import foundation.env as env
from utilities.prefs_constants import getDefaultWorkingDirectory
from utilities.prefs_constants import workingDirectory_prefs_key
from utilities.Log import greenmsg
from utilities.constants import yellow, orange, red, magenta
from utilities.constants import cyan, blue, white, black, gray
from utilities.constants import diPROTEIN
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import Qt
from PyQt4.Qt import QFileDialog, QString, QMessageBox
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_CheckBox import PM_CheckBox
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_ToolButtonRow import PM_ToolButtonRow
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_ColorComboBox import PM_ColorComboBox
from utilities.prefs_constants import proteinStyle_prefs_key
from utilities.prefs_constants import proteinStyleSmooth_prefs_key
from utilities.prefs_constants import proteinStyleQuality_prefs_key
from utilities.prefs_constants import proteinStyleScaling_prefs_key
from utilities.prefs_constants import proteinStyleScaleFactor_prefs_key
from utilities.prefs_constants import proteinStyleColors_prefs_key
from utilities.prefs_constants import proteinStyleAuxColors_prefs_key
from utilities.prefs_constants import proteinStyleCustomColor_prefs_key
from utilities.prefs_constants import proteinStyleAuxCustomColor_prefs_key
from utilities.prefs_constants import proteinStyleColorsDiscrete_prefs_key
from utilities.prefs_constants import proteinStyleHelixColor_prefs_key
from utilities.prefs_constants import proteinStyleStrandColor_prefs_key
from utilities.prefs_constants import proteinStyleCoilColor_prefs_key
from utilities.Log import redmsg
from command_support.Command_PropertyManager import Command_PropertyManager
proteinDisplayStylePrefsList = \
[proteinStyle_prefs_key,
proteinStyleSmooth_prefs_key,
proteinStyleQuality_prefs_key,
proteinStyleScaling_prefs_key,
proteinStyleScaleFactor_prefs_key,
proteinStyleColors_prefs_key,
proteinStyleAuxColors_prefs_key,
proteinStyleCustomColor_prefs_key,
proteinStyleAuxCustomColor_prefs_key,
proteinStyleColorsDiscrete_prefs_key,
proteinStyleHelixColor_prefs_key,
proteinStyleStrandColor_prefs_key,
proteinStyleCoilColor_prefs_key ]
# Protein Display Style Favorite File I/O functions.
def writeProteinDisplayStyleSettingsToFavoritesFile( basename ):
"""
Writes a "favorite file" (with a .txt extension) to store all the
Protein display style settings (pref keys and their current values).
@param basename: The filename (without the .fav extension) to write.
@type basename: string
@note: The favorite file is written to the directory
$HOME/Nanorex/Favorites/ProteinDisplayStyle.
"""
if not basename:
return 0, "No name given."
# Get filename and write the favorite file.
favfilepath = getFavoritePathFromBasename(basename)
writeDnaFavoriteFile(favfilepath)
return 1, basename
def getFavoritePathFromBasename( basename ):
"""
Returns the full path to the favorite file given a basename.
@param basename: The favorite filename (without the .txt extension).
@type basename: string
@note: The (default) directory for all favorite files is
$HOME/Nanorex/Favorites/ProteinDisplayStyle.
"""
_ext = "txt"
# Make favorite filename (i.e. ~/Nanorex/Favorites/ProteinDisplayStyleFavorites/basename.txt)
from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
_dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle')
return os.path.join(_dir, "%s.%s" % (basename, _ext))
def writeDnaFavoriteFile( filename ):
"""
Writes a favorite file to I{filename}.
"""
f = open(filename, 'w')
# Write header
f.write ('!\n! Protein display style favorite file')
f.write ('\n!Created by NanoEngineer-1 on ')
timestr = "%s\n!\n" % time.strftime("%Y-%m-%d at %H:%M:%S")
f.write(timestr)
#write preference list in file without the NE version
for pref_key in proteinDisplayStylePrefsList:
val = env.prefs[pref_key]
pref_keyArray = pref_key.split("/")
pref_key = pref_keyArray[1]
if isinstance(val, int):
f.write("%s = %d\n" % (pref_key, val))
elif isinstance(val, float):
f.write("%s = %-6.2f\n" % (pref_key, val))
elif isinstance(val, bool):
f.write("%s = %d\n" % (pref_key, val))
else:
print "Not sure what pref_key '%s' is." % pref_key
f.close()
def loadFavoriteFile( filename ):
"""
Loads a favorite file from anywhere in the disk.
@param filename: The full path for the favorite file.
@type filename: string
"""
if os.path.exists(filename):
favoriteFile = open(filename, 'r')
else:
env.history.message("Favorite file to be loaded does not exist.")
return 0
# do syntax checking on the file to figure out whether this is a valid
# favorite file
line = favoriteFile.readline()
line = favoriteFile.readline()
if line != "! DNA display style favorite file\n":
env.history.message(" Not a proper favorite file")
favoriteFile.close()
return 0
while 1:
line = favoriteFile.readline()
# marks the end of file
if line == "":
break
# process each line to obtain pref_keys and their corresponding values
if line[0] != '!':
keyValuePair = line.split('=')
pref_keyString = keyValuePair[0].strip()
pref_value=keyValuePair[1].strip()
# check if pref_value is an integer or float. Booleans currently
# stored as integer as well.
try:
int(pref_value)
pref_valueToStore = int(pref_value)
except ValueError:
pref_valueToStore = float(pref_value)
# match pref_keyString with its corresponding variable name in the
# preference key list
pref_key = findPrefKey( pref_keyString )
#add preference key and its corresponding value to the dictionary
if pref_key:
env.prefs[pref_key] = pref_valueToStore
favoriteFile.close()
#check if a copy of this file exists in the favorites directory. If not make
# a copy of it in there
favName = os.path.basename(str(filename))
name = favName[0:len(favName)-4]
favfilepath = getFavoritePathFromBasename(name)
if not os.path.exists(favfilepath):
saveFavoriteFile(favfilepath, filename)
return 1
def findPrefKey( pref_keyString ):
"""
Matches prefence key in the proteinDisplayStylePrefsList with pref_keyString
from the favorte file that we intend to load.
@param pref_keyString: preference from the favorite file to be loaded.
@type pref_keyString: string
@note: very inefficient since worst case time taken is proportional to the
size of the list. If original preference strings are in a dictionary, access
can be done in constant time
"""
for keys in proteinDisplayStylePrefsList:
#split keys in dnaDisplayStylePrefList into version number and pref_key
pref_array= keys.split("/")
if pref_array[1] == pref_keyString:
return keys
return None
def saveFavoriteFile( savePath, fromPath ):
"""
Save favorite file to anywhere in the disk
@param savePath: full path for the location where the favorite file is to be saved.
@type savePath: string
@param savePath: ~/Nanorex/Favorites/DnaDisplayStyle/$FAV_NAME.txt
@type fromPath: string
"""
if savePath:
saveFile = open(savePath, 'w')
if fromPath:
fromFile = open(fromPath, 'r')
lines=fromFile.readlines()
saveFile.writelines(lines)
saveFile.close()
fromFile.close()
return
# =
_superclass = Command_PropertyManager
class ProteinDisplayStyle_PropertyManager(Command_PropertyManager):
"""
The ProteinDisplayStyle_PropertyManager class provides a Property Manager
for the B{Display Style} command on the flyout toolbar in the
Build > Protein mode.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Edit Protein Display Style"
pmName = title
iconPath = "ui/actions/Edit/EditProteinDisplayStyle.png"
def __init__( self, command ):
"""
Constructor for the property manager.
"""
self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
_superclass.__init__(self, command)
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_WHATS_THIS_BUTTON)
msg = "Modify the protein display settings below."
self.updateMessage(msg)
def connect_or_disconnect_signals(self, isConnect = True):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
"""
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
# Favorite buttons signal-slot connections.
change_connect( self.applyFavoriteButton,
SIGNAL("clicked()"),
self.applyFavorite)
change_connect( self.addFavoriteButton,
SIGNAL("clicked()"),
self.addFavorite)
change_connect( self.deleteFavoriteButton,
SIGNAL("clicked()"),
self.deleteFavorite)
change_connect( self.saveFavoriteButton,
SIGNAL("clicked()"),
self.saveFavorite)
change_connect( self.loadFavoriteButton,
SIGNAL("clicked()"),
self.loadFavorite)
#Display group box signal slot connections
change_connect(self.proteinStyleComboBox,
SIGNAL("currentIndexChanged(int)"),
self.changeProteinDisplayStyle)
change_connect(self.smoothingCheckBox,
SIGNAL("stateChanged(int)"),
self.smoothProteinDisplay)
change_connect(self.scaleComboBox,
SIGNAL("currentIndexChanged(int)"),
self.changeProteinDisplayScale)
change_connect(self.splineDoubleSpinBox,
SIGNAL("valueChanged(double)"),
self.changeProteinSplineValue)
change_connect(self.scaleFactorDoubleSpinBox,
SIGNAL("valueChanged(double)"),
self.changeProteinScaleFactor)
#color groupbox
change_connect(self.proteinComponentComboBox,
SIGNAL("currentIndexChanged(int)"),
self.chooseProteinComponent)
change_connect(self.proteinAuxComponentComboBox,
SIGNAL("currentIndexChanged(int)"),
self.chooseAuxilliaryProteinComponent)
change_connect(self.customColorComboBox,
SIGNAL("editingFinished()"),
self.chooseCustomColor)
change_connect(self.auxColorComboBox,
SIGNAL("editingFinished()"),
self.chooseAuxilliaryColor)
#change_connect(self.discColorCheckBox,
# SIGNAL("stateChanged(int)"),
# self.setDiscreteColors)
change_connect(self.helixColorComboBox,
SIGNAL("editingFinished()"),
self.chooseHelixColor)
change_connect(self.strandColorComboBox,
SIGNAL("editingFinished()"),
self.chooseStrandColor)
change_connect(self.coilColorComboBox,
SIGNAL("editingFinished()"),
self.chooseCoilColor)
#Protein Display methods
def changeProteinDisplayStyle(self, idx):
"""
Change protein display style
@param idx: index of the protein display style combo box
@type idx: int
"""
env.prefs[proteinStyle_prefs_key] = idx
return
def changeProteinDisplayQuality(self, idx):
env.prefs[proteinStyleQuality_prefs_key] = idx
return
def smoothProteinDisplay(self, state):
"""
Smoooth protein display.
@param state: state of the smooth protein display check box.
@type state: int
"""
if state == Qt.Checked:
env.prefs[proteinStyleSmooth_prefs_key] = True
else:
env.prefs[proteinStyleSmooth_prefs_key] = False
return
def changeProteinDisplayScale(self, idx):
"""
Change protein display scale
@param idx: index of the protein display scaling choices combo box
@type idx: int
"""
env.prefs[proteinStyleScaling_prefs_key] = idx
return
def changeProteinSplineValue(self, val):
"""
Change protein display resolution
@param val: value in the protein display resolution double spinbox
@type val: double
"""
env.prefs[proteinStyleQuality_prefs_key] = val
return
def changeProteinScaleFactor(self, val):
"""
Change protein display scale factor
@param val: value in the protein display scale factor double spinbox
@type val: double
"""
env.prefs[proteinStyleScaleFactor_prefs_key] = val
return
def chooseProteinComponent(self, idx):
"""
Choose protein component to set the color of
@param idx: index of the protein component choices combo box
@type idx: int
"""
env.prefs[proteinStyleColors_prefs_key] = idx
return
def chooseAuxilliaryProteinComponent(self, idx):
"""
Choose auxilliary protein component to set the color of
@param idx: index of the auxilliary protein component choices combo box
@type idx: int
"""
env.prefs[proteinStyleAuxColors_prefs_key] = idx - 1
return
def chooseCustomColor(self):
"""
Choose custom color of the chosen protein component
"""
color = self.customColorComboBox.getColor()
env.prefs[proteinStyleCustomColor_prefs_key] = color
return
def chooseAuxilliaryColor(self):
"""
Choose custom color of the chosen auxilliary protein component
"""
color = self.auxColorComboBox.getColor()
env.prefs[proteinStyleAuxCustomColor_prefs_key] = color
return
def chooseHelixColor(self):
"""
Choose helix color
"""
color = self.helixColorComboBox.getColor()
env.prefs[proteinStyleHelixColor_prefs_key] = color
return
def chooseStrandColor(self):
"""
Choose strand color
"""
color = self.strandColorComboBox.getColor()
env.prefs[proteinStyleStrandColor_prefs_key] = color
return
def chooseCoilColor(self):
"""
Choose coil color
"""
color = self.coilColorComboBox.getColor()
env.prefs[proteinStyleCoilColor_prefs_key] = color
return
def setDiscreteColors(self, state):
"""
Set discrete colors.
@param state: state of the set discrete colors check box.
@type state: int
"""
if state == Qt.Checked:
env.prefs[proteinStyleColorsDiscrete_prefs_key] = True
else:
env.prefs[proteinStyleColorsDiscrete_prefs_key] = False
return
def show_OLD(self):
"""
Shows the Property Manager.Extends superclass method.
"""
#@REVIEW: See comment in CompareProteins_PropertyManager
self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
self.sequenceEditor.hide()
self.updateProteinDisplayStyleWidgets()
_superclass.show(self)
def show(self):
"""
Shows the Property Manager. Extends superclass method
"""
_superclass.show(self)
#@REVIEW: Is it safe to do the follwoing before calling superclass.show()?
#-- Ninad 2008-10-02
# Force the Global Display Style to "DNA Cylinder" so the user
# can see the display style setting effects on any DNA in the current
# model. The current global display style will be restored when leaving
# this command (via self.close()).
self.originalDisplayStyle = self.o.displayMode
# TODO: rename that public attr of GLPane (widely used)
# from displayMode to displayStyle. [bruce 080910 comment]
self.o.setGlobalDisplayStyle(diPROTEIN)
# Update all PM widgets, .
# note: It is important to update the widgets by blocking the
# 'signals'. If done in the reverse order, it will generate signals
#when updating the PM widgets (via updateDnaDisplayStyleWidgets()),
#causing unneccessary repaints of the model view.
self.updateProteinDisplayStyleWidgets()#@@@ blockSignals = True)
return
def close(self):
"""
Closes the Property Manager. Extends superclass method.
"""
_superclass.close(self)
# Restore the original global display style.
self.o.setGlobalDisplayStyle(self.originalDisplayStyle)
return
def _addGroupBoxes( self ):
"""
Add the Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox( self,
title = "Favorites")
self._loadGroupBox1( self._pmGroupBox1 )
self._pmGroupBox2 = PM_GroupBox( self,
title = "Display")
self._loadGroupBox2( self._pmGroupBox2 )
self._pmGroupBox3 = PM_GroupBox( self,
title = "Color")
self._loadGroupBox3( self._pmGroupBox3 )
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box.
@param pmGroupBox: group box that contains various favorite buttons
@see: L{PM_GroupBox}
"""
# Other info
# Not only loads the factory default settings but also all the favorite
# files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory
favoriteChoices = ['Factory default settings']
#look for all the favorite files in the favorite folder and add them to
# the list
from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
_dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle')
for file in os.listdir(_dir):
fullname = os.path.join( _dir, file)
if os.path.isfile(fullname):
if fnmatch.fnmatch( file, "*.txt"):
# leave the extension out
favoriteChoices.append(file[0:len(file)-4])
self.favoritesComboBox = \
PM_ComboBox( pmGroupBox,
choices = favoriteChoices,
spanWidth = True)
self.favoritesComboBox.setWhatsThis(
"""<b> List of Favorites </b>
<p>
Creates a list of favorite Protein display styles. Once favorite
styles have been added to the list using the Add Favorite button,
the list will display the chosen favorites.
To change the current favorite, select a current favorite from
the list, and push the Apply Favorite button.""")
# PM_ToolButtonRow ===============
# Button list to create a toolbutton row.
# Format:
# - QToolButton, buttonId, buttonText,
# - iconPath,
# - tooltip, shortcut, column
BUTTON_LIST = [
( "QToolButton", 1, "APPLY_FAVORITE","ui/actions/Properties Manager/ApplyPeptideDisplayStyleFavorite.png",
"Apply Favorite", "", 0),
( "QToolButton", 2, "ADD_FAVORITE",
"ui/actions/Properties Manager/AddFavorite.png","Add Favorite", "", 1),
( "QToolButton", 3, "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png",
"Delete Favorite", "", 2),
( "QToolButton", 4, "SAVE_FAVORITE",
"ui/actions/Properties Manager/SaveFavorite.png",
"Save Favorite", "", 3),
( "QToolButton", 5, "LOAD_FAVORITE",
"ui/actions/Properties Manager/LoadFavorite.png",
"Load Favorite", \
"", 4)
]
self.favsButtonGroup = \
PM_ToolButtonRow( pmGroupBox,
title = "",
buttonList = BUTTON_LIST,
spanWidth = True,
isAutoRaise = False,
isCheckable = False,
setAsDefault = True,
)
self.favsButtonGroup.buttonGroup.setExclusive(False)
self.applyFavoriteButton = self.favsButtonGroup.getButtonById(1)
self.addFavoriteButton = self.favsButtonGroup.getButtonById(2)
self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3)
self.saveFavoriteButton = self.favsButtonGroup.getButtonById(4)
self.loadFavoriteButton = self.favsButtonGroup.getButtonById(5)
def _loadGroupBox2(self, pmGroupBox):
"""
Load widgets in group box.
@param pmGroupBox: group box that contains protein display choices
@see: L{PM_GroupBox}
"""
proteinStyleChoices = ['CA trace (wire)',
'CA trace (cylinders)',
'CA trace (ball and stick)',
'Tube',
'Ladder',
'Zigzag',
'Flat ribbon',
'Solid ribbon',
'Cartoons',
'Fancy cartoons',
'Peptide tiles'
]
self.proteinStyleComboBox = \
PM_ComboBox( pmGroupBox,
label = "Style:",
choices = proteinStyleChoices,
setAsDefault = True)
scaleChoices = ['Constant', 'Secondary structure', 'B-factor']
self.scaleComboBox = \
PM_ComboBox( pmGroupBox,
label = "Scaling:",
choices = scaleChoices,
setAsDefault = True)
self.scaleFactorDoubleSpinBox = \
PM_DoubleSpinBox( pmGroupBox,
label = "Scaling factor:",
value = 1.00,
setAsDefault = True,
minimum = 0.1,
maximum = 3.0,
decimals = 1,
singleStep = 0.1 )
self.splineDoubleSpinBox = \
PM_DoubleSpinBox( pmGroupBox,
label = "Resolution:",
value = 3,
setAsDefault = True,
minimum = 2,
maximum = 8,
decimals = 0,
singleStep = 1 )
self.smoothingCheckBox = \
PM_CheckBox( pmGroupBox,
text = "Smoothing",
setAsDefault = True)
def _loadGroupBox3(self, pmGroupBox):
"""
Load widgets in group box.
@param pmGroupBox: group box that contains various color choices
@see: L{PM_GroupBox}
"""
colorChoices = ['Chunk', 'Chain', 'Order', 'Hydropathy', 'Polarity',
'Acidity', 'Size', 'Character', 'Number of contacts',
'Secondary structure type', 'Secondary structure order',
'B-factor', 'Occupancy', 'Custom']
self.proteinComponentComboBox = \
PM_ComboBox( pmGroupBox,
label = "Color by:",
choices = colorChoices,
setAsDefault = True)
colorList = [orange, yellow, red, magenta,
cyan, blue, white, black, gray]
colorNames = ["Orange(default)", "Yellow", "Red", "Magenta",
"Cyan", "Blue", "White", "Black", "Other color..."]
self.customColorComboBox = \
PM_ColorComboBox(pmGroupBox,
colorList = colorList,
colorNames = colorNames,
label = "Custom:",
color = orange,
setAsDefault = True)
colorChoices1 = [ 'Same as main color', 'Lighter', 'Darker',
'Gray', 'Custom']
self.proteinAuxComponentComboBox = \
PM_ComboBox( pmGroupBox,
label = "Aux:",
choices = colorChoices1,
setAsDefault = True)
colorListAux = [orange, yellow, red, magenta,cyan, blue, white, black, gray]
colorNamesAux = ["Orange(default)", "Yellow", "Red", "Magenta", "Cyan",
"Blue", "White", "Black", "Other color..."]
self.auxColorComboBox = \
PM_ColorComboBox(pmGroupBox,
colorList = colorListAux,
colorNames = colorNamesAux,
label = "Custom aux:",
color = gray,
setAsDefault = True)
#self.discColorCheckBox = \
# PM_CheckBox( pmGroupBox,
# text = "Discretize colors",
# setAsDefault = True
# )
#
colorListHelix = [red, yellow, gray, magenta,
cyan, blue, white, black, orange]
colorNamesHelix = ["Red(default)", "Yellow", "Gray", "Magenta",
"Cyan", "Blue", "White", "Black", "Other color..."]
self.helixColorComboBox = \
PM_ColorComboBox(pmGroupBox,
colorList = colorListHelix,
colorNames = colorNamesHelix,
label = "Helix:",
color = red,
setAsDefault = True)
colorListStrand = [cyan, yellow, gray, magenta,
red, blue, white, black, orange]
colorNamesStrand = ["Cyan(default)", "Yellow", "Gray", "Magenta",
"Red", "Blue", "White", "Black", "Other color..."]
self.strandColorComboBox = \
PM_ColorComboBox(pmGroupBox,
colorList = colorListStrand,
colorNames = colorNamesStrand,
label = "Strand:",
color = cyan,
setAsDefault = True)
self.coilColorComboBox = \
PM_ColorComboBox(pmGroupBox,
colorList = colorListAux,
colorNames = colorNamesAux,
label = "Coil:",
color = orange,
setAsDefault = True)
def updateProteinDisplayStyleWidgets( self ):
"""
Updates all the Protein Display style widgets based on the current pref keys
values
"""
self.proteinStyleComboBox.setCurrentIndex(env.prefs[proteinStyle_prefs_key])
self.splineDoubleSpinBox.setValue(env.prefs[proteinStyleQuality_prefs_key])
if env.prefs[proteinStyleSmooth_prefs_key] == True:
self.smoothingCheckBox.setCheckState(Qt.Checked)
else:
self.smoothingCheckBox.setCheckState(Qt.Unchecked)
self.scaleComboBox.setCurrentIndex(env.prefs[proteinStyleScaling_prefs_key])
self.scaleFactorDoubleSpinBox.setValue(env.prefs[proteinStyleScaleFactor_prefs_key])
self.proteinComponentComboBox.setCurrentIndex(env.prefs[proteinStyleColors_prefs_key])
self.customColorComboBox.setColor(env.prefs[proteinStyleCustomColor_prefs_key])
self.proteinAuxComponentComboBox.setCurrentIndex(env.prefs[proteinStyleAuxColors_prefs_key])
self.auxColorComboBox.setColor(env.prefs[proteinStyleAuxCustomColor_prefs_key])
#if env.prefs[proteinStyleColorsDiscrete_prefs_key] == True:
# self.discColorCheckBox.setCheckState(Qt.Checked)
#else:
# self.discColorCheckBox.setCheckState(Qt.Unchecked)
self.helixColorComboBox.setColor(env.prefs[proteinStyleHelixColor_prefs_key])
self.strandColorComboBox.setColor(env.prefs[proteinStyleStrandColor_prefs_key])
self.coilColorComboBox.setColor(env.prefs[proteinStyleCoilColor_prefs_key])
return
def applyFavorite(self):
"""
Apply a favorite to the current display chosen in the favorites combo box
"""
current_favorite = self.favoritesComboBox.currentText()
if current_favorite == 'Factory default settings':
env.prefs.restore_defaults(proteinDisplayStylePrefsList)
else:
favfilepath = getFavoritePathFromBasename(current_favorite)
loadFavoriteFile(favfilepath)
self.updateProteinDisplayStyleWidgets()
return
def addFavorite(self):
"""
create and add favorite to favorites directory and favorites combo box
in PM
@note: Rules and other info:
- The new favorite is defined by the current Protein display style
settings.
- The user is prompted to type in a name for the new
favorite.
- The Protein display style settings are written to a file in a special
directory on the disk
(i.e. $HOME/Nanorex/Favorites/ProteinDisplayStyle/$FAV_NAME.txt).
- The name of the new favorite is added to the list of favorites in
the combobox, which becomes the current option.
Existence of a favorite with the same name is checked in the above
mentioned location and if a duplicate exists, then the user can either
overwrite and provide a new name.
"""
# Prompt user for a favorite name to add.
from widgets.simple_dialogs import grab_text_line_using_dialog
ok1, name = \
grab_text_line_using_dialog(
title = "Add new favorite",
label = "favorite name:",
iconPath = "ui/actions/Properties Manager/AddFavorite.png",
default = "" )
if ok1:
# check for duplicate files in the
# $HOME/Nanorex/Favorites/DnaDisplayStyle/ directory
fname = getFavoritePathFromBasename( name )
if os.path.exists(fname):
#favorite file already exists!
_ext= ".txt"
ret = QMessageBox.warning( self, "Warning!",
"The favorite file \"" + name + _ext + "\"already exists.\n"
"Do you want to overwrite the existing file?",
"&Overwrite", "&Cancel", "",
0, # Enter == button 0
1) # Escape == button 1
if ret == 0:
#overwrite favorite file
ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
indexOfDuplicateItem = self.favoritesComboBox.findText(name)
self.favoritesComboBox.removeItem(indexOfDuplicateItem)
print "Add Favorite: removed duplicate favorite item."
else:
env.history.message("Add Favorite: cancelled overwriting favorite item.")
return
else:
ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
else:
# User cancelled.
return
if ok2:
self.favoritesComboBox.addItem(name)
_lastItem = self.favoritesComboBox.count()
self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
msg = "New favorite [%s] added." % (text)
else:
msg = "Can't add favorite [%s]: %s" % (name, text) # text is reason why not
env.history.message(msg)
return
def deleteFavorite(self):
"""
Delete favorite file from the favorites directory
"""
currentIndex = self.favoritesComboBox.currentIndex()
currentText = self.favoritesComboBox.currentText()
if currentIndex == 0:
msg = "Cannot delete '%s'." % currentText
else:
self.favoritesComboBox.removeItem(currentIndex)
# delete file from the disk
deleteFile= getFavoritePathFromBasename( currentText )
os.remove(deleteFile)
msg = "Deleted favorite named [%s].\n" \
"and the favorite file [%s.txt]." \
% (currentText, currentText)
env.history.message(msg)
return
def saveFavorite(self):
"""
Save favorite file in a user chosen location
"""
cmd = greenmsg("Save Favorite File: ")
env.history.message(greenmsg("Save Favorite File:"))
current_favorite = self.favoritesComboBox.currentText()
favfilepath = getFavoritePathFromBasename(current_favorite)
formats = \
"Favorite (*.txt);;"\
"All Files (*.*)"
directory = self.currentWorkingDirectory
saveLocation = directory + "/" + current_favorite + ".txt"
fn = QFileDialog.getSaveFileName(
self,
"Save Favorite As", # caption
favfilepath, #where to save
formats, # file format options
QString("Favorite (*.txt)") # selectedFilter
)
if not fn:
env.history.message(cmd + "Cancelled")
else:
dir, fil = os.path.split(str(fn))
self.setCurrentWorkingDirectory(dir)
saveFavoriteFile(str(fn), favfilepath)
return
def setCurrentWorkingDirectory(self, dir = None):
"""
Set dir as current working diretcory
@param dir: dirname
@type dir: str
"""
if os.path.isdir(dir):
self.currentWorkingDirectory = dir
self._setWorkingDirectoryInPrefsDB(dir)
else:
self.currentWorkingDirectory = getDefaultWorkingDirectory()
return
def _setWorkingDirectoryInPrefsDB(self, workdir = None):
"""
Set workdir as current working diretcory in prefDB
@param workdir: dirname
@type workdir: str
"""
if not workdir:
return
workdir = str(workdir)
if os.path.isdir(workdir):
workdir = os.path.normpath(workdir)
env.prefs[workingDirectory_prefs_key] = workdir # Change pref in prefs db.
else:
msg = "[" + workdir + "] is not a directory. Working directory was not changed."
env.history.message( redmsg(msg))
return
def loadFavorite(self):
"""
Load a favorite file
"""
# If the file already exists in the favorites folder then the user is
# given the option of overwriting it or renaming it
env.history.message(greenmsg("Load Favorite File:"))
formats = \
"Favorite (*.txt);;"\
"All Files (*.*)"
directory = self.currentWorkingDirectory
if directory == '':
directory= getDefaultWorkingDirectory()
fname = QFileDialog.getOpenFileName(self,
"Choose a file to load",
directory,
formats)
if not fname:
env.history.message("User cancelled loading file.")
return
else:
dir, fil = os.path.split(str(fname))
self.setCurrentWorkingDirectory(dir)
canLoadFile=loadFavoriteFile(fname)
if canLoadFile == 1:
#get just the name of the file for loading into the combobox
favName = os.path.basename(str(fname))
name = favName[0:len(favName)-4]
indexOfDuplicateItem = self.favoritesComboBox.findText(name)
#duplicate exists in combobox
if indexOfDuplicateItem != -1:
ret = QMessageBox.warning( self, "Warning!",
"The favorite file \"" + name +
"\"already exists.\n"
"Do you want to overwrite the existing file?",
"&Overwrite", "&Rename", "&Cancel",
0, # Enter == button 0
1 # button 1
)
if ret == 0:
self.favoritesComboBox.removeItem(indexOfDuplicateItem)
self.favoritesComboBox.addItem(name)
_lastItem = self.favoritesComboBox.count()
self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name)
msg = "Overwrote favorite [%s]." % (text)
env.history.message(msg)
elif ret == 1:
# add new item to favorites folder as well as combobox
self.addFavorite()
else:
#reset the display setting values to factory default
factoryIndex = self.favoritesComboBox.findText(
'Factory default settings')
self.favoritesComboBox.setCurrentIndex(factoryIndex)
env.prefs.restore_defaults(proteinDisplayStylePrefsList)
env.history.message("Cancelled overwriting favorite file.")
return
else:
self.favoritesComboBox.addItem(name)
_lastItem = self.favoritesComboBox.count()
self.favoritesComboBox.setCurrentIndex(_lastItem - 1)
msg = "Loaded favorite [%s]." % (name)
env.history.message(msg)
self.updateProteinDisplayStyleWidgets()
return
def _addWhatsThisText( self ):
"""
Add what's this text for this PM
"""
from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditDnaDisplayStyle_PropertyManager
WhatsThis_EditDnaDisplayStyle_PropertyManager(self)
def _addToolTipText(self):
"""
Add tool tip text to all widgets.
"""
from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
ToolTip_EditProteinDisplayStyle_PropertyManager(self)
| NanoCAD-master | cad/src/protein/commands/ProteinDisplayStyle/ProteinDisplayStyle_PropertyManager.py |
NanoCAD-master | cad/src/protein/commands/ProteinDisplayStyle/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
EditResidues_PropertyManager.py
B{Edit Residues} is a front-end for
The EditResidues_PropertyManager class provides a Property Manager
for the B{Edit Residues} command on the flyout toolbar in the
Build > Protein mode.
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
To do:
- Auto-adjust width of PM to accomodate all widgets when entering cmd or
after selecting a new structure.
"""
import os, sys, time, fnmatch, string, re
import foundation.env as env
from widgets.prefs_widgets import connect_checkbox_with_boolean_pref
from utilities.prefs_constants import getDefaultWorkingDirectory
from utilities.prefs_constants import workingDirectory_prefs_key
from utilities.prefs_constants import proteinCustomDescriptors_prefs_key
from utilities.Log import greenmsg
from utilities.constants import yellow, orange, red, magenta
from utilities.constants import cyan, blue, white, black, gray
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import Qt
from PyQt4.Qt import QCheckBox
from PyQt4.Qt import QLabel
from PyQt4.Qt import QFont
from PyQt4.Qt import QComboBox
from PyQt4.Qt import QTableWidgetItem
from PyQt4.Qt import QSize
from PyQt4 import QtGui
from PyQt4.Qt import QFileDialog, QString, QMessageBox, QSlider
from PM.PM_PushButton import PM_PushButton
from command_support.Command_PropertyManager import Command_PropertyManager
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_LineEdit import PM_LineEdit
from PM.PM_StackedWidget import PM_StackedWidget
from PM.PM_CheckBox import PM_CheckBox
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_ToolButtonRow import PM_ToolButtonRow
from PM.PM_Slider import PM_Slider
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_ColorComboBox import PM_ColorComboBox
from PM.PM_TableWidget import PM_TableWidget
from PM.PM_WidgetGrid import PM_WidgetGrid
_superclass = Command_PropertyManager
class EditResidues_PropertyManager(Command_PropertyManager):
"""
The ProteinDisplayStyle_PropertyManager class provides a Property Manager
for the B{Display Style} command on the flyout toolbar in the
Build > Protein mode.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Edit Residues"
pmName = title
iconPath = "ui/actions/Command Toolbar/BuildProtein/Residues.png"
rosetta_all_set = "PGAVILMFWYCSTNQDEHKR"
rosetta_polar_set = "___________STNQDEHKR"
rosetta_apolar_set = "PGAVILMFWYC_________"
def __init__( self, command ):
"""
Constructor for the property manager.
"""
self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
_superclass.__init__(self, command)
self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_WHATS_THIS_BUTTON)
self.editingItem = False
return
def connect_or_disconnect_signals(self, isConnect = True):
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.applyAnyPushButton,
SIGNAL("clicked()"),
self._applyAny)
change_connect(self.applySamePushButton,
SIGNAL("clicked()"),
self._applySame)
change_connect(self.applyLockedPushButton,
SIGNAL("clicked()"),
self._applyLocked)
change_connect(self.applyPolarPushButton,
SIGNAL("clicked()"),
self._applyPolar)
change_connect(self.applyApolarPushButton,
SIGNAL("clicked()"),
self._applyApolar)
change_connect(self.selectAllPushButton,
SIGNAL("clicked()"),
self._selectAll)
change_connect(self.selectNonePushButton,
SIGNAL("clicked()"),
self._selectNone)
change_connect(self.selectInvertPushButton,
SIGNAL("clicked()"),
self._invertSelection)
change_connect(self.applyDescriptorPushButton,
SIGNAL("clicked()"),
self._applyDescriptor)
change_connect(self.removeDescriptorPushButton,
SIGNAL("clicked()"),
self._removeDescriptor)
change_connect(self.sequenceTable,
SIGNAL("cellClicked(int, int)"),
self._sequenceTableCellChanged)
change_connect(self.sequenceTable,
SIGNAL("itemChanged(QTableWidgetItem*)"),
self._sequenceTableItemChanged)
change_connect(self.descriptorsTable,
SIGNAL("itemChanged(QTableWidgetItem*)"),
self._descriptorsTableItemChanged)
change_connect(self.newDescriptorPushButton,
SIGNAL("clicked()"),
self._addNewDescriptor)
change_connect(self.showSequencePushButton,
SIGNAL("clicked()"),
self._showSeqEditor)
return
def _showSeqEditor(self):
"""
Shows sequence editor
"""
if self.showSequencePushButton.isEnabled():
self.sequenceEditor.show()
return
def show(self):
"""
Shows the Property Manager. Extends superclass method.
"""
env.history.statusbar_msg("")
#Urmi 20080728: Set the current protein and this will be used for accessing
#various properties of this protein
self.set_current_protein()
if self.current_protein:
msg = "Editing structure <b>%s</b>." % self.current_protein.name
self.showSequencePushButton.setEnabled(True)
else:
msg = "Select a single structure to edit."
self.showSequencePushButton.setEnabled(False)
self.sequenceEditor.hide()
_superclass.show(self)
self._fillSequenceTable()
self.updateMessage(msg)
return
def set_current_protein(self):
"""
Set the current protein for which all the properties are displayed to the
one chosen in the build protein combo box
"""
self.current_protein = self.win.assy.getSelectedProteinChunk()
return
def _addGroupBoxes( self ):
"""
Add the Property Manager group boxes.
"""
if sys.platform == "darwin":
# Workaround for table font size difference between Mac/Win
self.labelfont = QFont("Helvetica", 12)
self.descriptorfont = QFont("Courier New", 12)
else:
self.labelfont = QFont("Helvetica", 9)
self.descriptorfont = QFont("Courier New", 9)
self._pmGroupBox1 = PM_GroupBox( self,
title = "Descriptors")
self._loadGroupBox1( self._pmGroupBox1 )
self._pmGroupBox2 = PM_GroupBox( self,
title = "Sequence")
self._loadGroupBox2( self._pmGroupBox2 )
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in the first group box.
"""
self.headerdata_desc = ['Name', 'Descriptor']
self.set_names = ["Any", "Same", "Locked", "Apolar", "Polar"]
self.rosetta_set_names = ["ALLAA", "NATAA", "NATRO", "APOLA", "POLAR"]
self.descriptor_list = ["PGAVILMFWYCSTNQDEHKR",
"____________________",
"____________________",
"PGAVILMFWYC_________",
"___________STNQDEHKR"]
self.applyAnyPushButton = PM_PushButton( pmGroupBox,
text = "ALLAA",
setAsDefault = True)
self.applySamePushButton = PM_PushButton( pmGroupBox,
text = "NATAA",
setAsDefault = True)
self.applyLockedPushButton = PM_PushButton( pmGroupBox,
text = "NATRO",
setAsDefault = True)
self.applyPolarPushButton = PM_PushButton( pmGroupBox,
text = "APOLA",
setAsDefault = True)
self.applyApolarPushButton = PM_PushButton( pmGroupBox,
text = "POLAR",
setAsDefault = True)
#self.applyBackrubPushButton = PM_PushButton( pmGroupBox,
# text = "BACKRUB",
# setAsDefault = True)
self.applyAnyPushButton.setFixedHeight(25)
self.applyAnyPushButton.setFixedWidth(60)
self.applySamePushButton.setFixedHeight(25)
self.applySamePushButton.setFixedWidth(60)
self.applyLockedPushButton.setFixedHeight(25)
self.applyLockedPushButton.setFixedWidth(60)
self.applyPolarPushButton.setFixedHeight(25)
self.applyPolarPushButton.setFixedWidth(60)
self.applyApolarPushButton.setFixedHeight(25)
self.applyApolarPushButton.setFixedWidth(60)
applyButtonList = [
('PM_PushButton', self.applyAnyPushButton, 0, 0),
('PM_PushButton', self.applySamePushButton, 1, 0),
('PM_PushButton', self.applyLockedPushButton, 2, 0),
('PM_PushButton', self.applyPolarPushButton, 3, 0),
('PM_PushButton', self.applyApolarPushButton, 4, 0) ]
self.applyButtonGrid = PM_WidgetGrid( pmGroupBox,
label = "Apply standard set",
widgetList = applyButtonList)
self.descriptorsTable = PM_TableWidget( pmGroupBox,
label = "Custom descriptors")
self.descriptorsTable.setFixedHeight(100)
self.descriptorsTable.setRowCount(0)
self.descriptorsTable.setColumnCount(2)
self.descriptorsTable.verticalHeader().setVisible(False)
self.descriptorsTable.horizontalHeader().setVisible(True)
self.descriptorsTable.setGridStyle(Qt.NoPen)
self.descriptorsTable.setHorizontalHeaderLabels(self.headerdata_desc)
self._updateSetLists()
self._fillDescriptorsTable()
self.descriptorsTable.resizeColumnsToContents()
self.newDescriptorPushButton = PM_PushButton( pmGroupBox,
text = "New",
setAsDefault = True)
self.newDescriptorPushButton.setFixedHeight(25)
self.removeDescriptorPushButton = PM_PushButton( pmGroupBox,
text = "Remove",
setAsDefault = True)
self.removeDescriptorPushButton.setFixedHeight(25)
self.applyDescriptorPushButton = PM_PushButton( pmGroupBox,
text = "Apply",
setAsDefault = True)
self.applyDescriptorPushButton.setFixedHeight(25)
addDescriptorButtonList = [('PM_PushButton', self.newDescriptorPushButton, 0, 0),
('PM_PushButton', self.removeDescriptorPushButton, 1, 0),
('PM_PushButton', self.applyDescriptorPushButton, 2, 0) ]
self.addDescriptorGrid = PM_WidgetGrid( pmGroupBox,
alignment = "Center",
widgetList = addDescriptorButtonList)
def _loadGroupBox2(self, pmGroupBox):
"""
Load widgets in the second group box.
"""
self.headerdata_seq = ['', 'ID', 'Set', 'BR', 'Descriptor']
self.recenterViewCheckBox = \
PM_CheckBox( pmGroupBox,
text = "Re-center view on selected residue",
setAsDefault = True,
widgetColumn = 0,
state = Qt.Unchecked)
self.selectAllPushButton = PM_PushButton( pmGroupBox,
text = "All",
setAsDefault = True)
self.selectAllPushButton.setFixedHeight(25)
self.selectNonePushButton = PM_PushButton( pmGroupBox,
text = "None",
setAsDefault = True)
self.selectNonePushButton.setFixedHeight(25)
self.selectInvertPushButton = PM_PushButton( pmGroupBox,
text = "Invert",
setAsDefault = True)
self.selectInvertPushButton.setFixedHeight(25)
buttonList = [ ('PM_PushButton', self.selectAllPushButton, 0, 0),
('PM_PushButton', self.selectNonePushButton, 1, 0),
('PM_PushButton', self.selectInvertPushButton, 2, 0)]
self.buttonGrid = PM_WidgetGrid( pmGroupBox,
widgetList = buttonList)
self.sequenceTable = PM_TableWidget( pmGroupBox)
#self.sequenceTable.setModel(self.tableModel)
self.sequenceTable.resizeColumnsToContents()
self.sequenceTable.verticalHeader().setVisible(False)
#self.sequenceTable.setRowCount(0)
self.sequenceTable.setColumnCount(5)
self.checkbox = QCheckBox()
self.sequenceTable.setFixedHeight(345)
self.sequenceTable.setGridStyle(Qt.NoPen)
self.sequenceTable.setHorizontalHeaderLabels(self.headerdata_seq)
###self._fillSequenceTable()
self.showSequencePushButton = PM_PushButton( pmGroupBox,
text = "Show Sequence",
setAsDefault = True,
spanWidth = True)
def _addWhatsThisText( self ):
#from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditResidues_PropertyManager
#WhatsThis_EditResidues_PropertyManager(self)
pass
def _addToolTipText(self):
#from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditProteinDisplayStyle_PropertyManager
#ToolTip_EditProteinDisplayStyle_PropertyManager(self)
pass
def _fillSequenceTable(self):
"""
Fills in the sequence table.
"""
if not self.current_protein:
return
else:
currentProteinChunk = self.current_protein
self.editingItem = True
aa_list = currentProteinChunk.protein.get_amino_acids()
aa_list_len = len(aa_list)
self.sequenceTable.setRowCount(aa_list_len)
for index in range(aa_list_len):
# Selection checkbox column
item_widget = QTableWidgetItem("")
item_widget.setFont(self.labelfont)
item_widget.setCheckState(Qt.Checked)
item_widget.setTextAlignment(Qt.AlignLeft)
item_widget.setSizeHint(QSize(20,12))
item_widget.setFlags(Qt.ItemIsSelectable |
Qt.ItemIsEnabled |
Qt.ItemIsUserCheckable)
self.sequenceTable.setItem(index, 0, item_widget)
# Amino acid index column
item_widget = QTableWidgetItem(str(index+1))
item_widget.setFont(self.labelfont)
item_widget.setFlags(
Qt.ItemIsSelectable |
Qt.ItemIsEnabled)
item_widget.setTextAlignment(Qt.AlignCenter)
self.sequenceTable.setItem(index, 1, item_widget)
# Mutation descriptor name column
aa = self._get_aa_for_index(index)
item_widget = QTableWidgetItem(self._get_descriptor_name(aa))
item_widget.setFont(self.labelfont)
item_widget.setFlags(Qt.ItemIsSelectable |
Qt.ItemIsEnabled)
item_widget.setTextAlignment(Qt.AlignCenter)
self.sequenceTable.setItem(index, 2, item_widget)
# Backrub checkbox column
item_widget = QTableWidgetItem("")
item_widget.setFont(self.labelfont)
if aa.get_backrub_mode():
item_widget.setCheckState(Qt.Checked)
else:
item_widget.setCheckState(Qt.Unchecked)
item_widget.setTextAlignment(Qt.AlignLeft)
item_widget.setSizeHint(QSize(20,12))
item_widget.setFlags(Qt.ItemIsSelectable |
Qt.ItemIsEnabled |
Qt.ItemIsUserCheckable)
self.sequenceTable.setItem(index, 3, item_widget)
# Mutation descriptor column
aa_string = self._get_mutation_descriptor(aa)
item_widget = QTableWidgetItem(aa_string)
item_widget.setFont(self.descriptorfont)
self.sequenceTable.setItem(index, 4, item_widget)
self.sequenceTable.setRowHeight(index, 16)
self.editingItem = False
self.sequenceTable.resizeColumnsToContents()
self.sequenceTable.setColumnWidth(0, 35)
self.sequenceTable.setColumnWidth(2, 80)
self.sequenceTable.setColumnWidth(3, 35)
return
def _fillDescriptorsTable(self):
"""
Fills in the descriptors table from descriptors user pref.
"""
dstr = env.prefs[proteinCustomDescriptors_prefs_key].split(":")
for i in range(len(dstr) / 2):
self._addNewDescriptorTableRow(dstr[2*i], dstr[2*i+1])
def _selectAll(self):
"""
Select all rows in the sequence table.
"""
for row in range(self.sequenceTable.rowCount()):
self.sequenceTable.item(row, 0).setCheckState(Qt.Checked)
def _selectNone(self):
"""
Unselect all rows in the sequence table.
"""
for row in range(self.sequenceTable.rowCount()):
self.sequenceTable.item(row, 0).setCheckState(Qt.Unchecked)
def _invertSelection(self):
"""
Inverto row selection range in the sequence table.
"""
for row in range(self.sequenceTable.rowCount()):
item_widget = self.sequenceTable.item(row, 0)
if item_widget.checkState() == Qt.Checked:
item_widget.setCheckState(Qt.Unchecked)
else:
item_widget.setCheckState(Qt.Checked)
def _get_mutation_descriptor(self, aa):
"""
Get mutation descriptor string for a given amino acid.
"""
aa_string = self.rosetta_all_set
range = aa.get_mutation_range()
aa_string = self.rosetta_all_set
if range == "NATRO" or \
range == "NATAA":
code = aa.get_one_letter_code()
aa_string = re.sub("[^"+code+"]",'_', aa_string)
elif range == "POLAR":
aa_string = self.rosetta_polar_set
elif range == "APOLA":
aa_string = self.rosetta_apolar_set
elif range == "PIKAA":
aa_string = aa.get_mutation_descriptor()
return aa_string
def _get_descriptor_name(self, aa):
"""
Returns a mutation descriptor name for an amino acid.
"""
range_name = aa.get_mutation_range()
for i in range(len(self.rosetta_set_names)):
if range_name == self.rosetta_set_names[i]:
if range_name == "PIKAA":
# Find a descriptor with a list of
# custom descriptors.
dstr = self._makeProperAAString(aa.get_mutation_descriptor())
for i in range(5, len(self.descriptor_list)):
if dstr == self.descriptor_list[i]:
return self.set_names[i]
else:
return self.set_names[i]
return "Custom"
def _get_aa_for_index(self, index, expand = False):
"""
Get amino acid by index.
@return: amino acid (Residue)
"""
if not self.current_protein:
return None
else:
currentProteinChunk = self.current_protein
currentProteinChunk.protein.set_current_amino_acid_index(index)
current_aa = currentProteinChunk.protein.get_current_amino_acid()
if expand:
currentProteinChunk.protein.collapse_all_rotamers()
currentProteinChunk.protein.expand_rotamer(current_aa)
return current_aa
def _sequenceTableCellChanged(self, crow, ccol):
"""
Slot for sequence table CellChanged event.
"""
item = self.sequenceTable.item(crow, ccol)
for row in range(self.sequenceTable.rowCount()):
self.sequenceTable.removeCellWidget(row, 2)
self.sequenceTable.setRowHeight(row, 16)
if ccol == 2:
# Make the row a little bit wider.
self.sequenceTable.setRowHeight(crow, 22)
# Create and insert a Combo Box into a current cell.
self.setComboBox = QComboBox()
self.setComboBox.addItems(self.set_names)
self.win.connect(self.setComboBox,
SIGNAL("activated(int)"),
self._setComboBoxIndexChanged)
self.sequenceTable.setCellWidget(crow, 2, self.setComboBox)
current_aa = self._get_aa_for_index(crow, expand=True)
if current_aa:
# Center on the selected amino acid.
if self.recenterViewCheckBox.isChecked():
ca_atom = current_aa.get_c_alpha_atom()
if ca_atom:
self.win.glpane.pov = -ca_atom.posn()
self.win.glpane.gl_update()
# Update backrub status for selected amino acid.
if ccol == 3:
cbox = self.sequenceTable.item(crow, 3)
if cbox.checkState() == Qt.Checked:
current_aa.set_backrub_mode(True)
else:
current_aa.set_backrub_mode(False)
from PyQt4.Qt import QTextCursor
cursor = self.sequenceEditor.sequenceTextEdit.textCursor()
#boundary condition
if crow == -1:
crow = 0
cursor.setPosition(crow, QTextCursor.MoveAnchor)
cursor.setPosition(crow + 1, QTextCursor.KeepAnchor)
self.sequenceEditor.sequenceTextEdit.setTextCursor( cursor )
def _applyDescriptor(self):
"""
Apply mutation descriptor to the selected amino acids.
"""
cdes = self.descriptorsTable.currentRow()
for row in range(self.sequenceTable.rowCount()):
self._setComboBoxIndexChanged(cdes + 5, tablerow = row, selectedOnly = True)
def _setComboBoxIndexChanged( self, index, tablerow = None, selectedOnly = False):
"""
Slot for mutation descriptor combo box (in third column of the sequence
table.)
"""
if tablerow is None:
crow = self.sequenceTable.currentRow()
else:
crow = tablerow
item = self.sequenceTable.item(crow, 2)
if item:
self.editingItem = True
cbox = self.sequenceTable.item(crow, 0)
if not selectedOnly or \
cbox.checkState() == Qt.Checked:
item.setText(self.set_names[index])
item = self.sequenceTable.item(crow, 4)
aa = self._get_aa_for_index(crow)
set_name = self.rosetta_set_names[index]
aa.set_mutation_range(set_name)
if set_name == "PIKAA":
aa.set_mutation_descriptor(self.descriptor_list[index])
item.setText(self._get_mutation_descriptor(aa))
for row in range(self.sequenceTable.rowCount()):
self.sequenceTable.removeCellWidget(row, 2)
self.sequenceTable.setRowHeight(row, 16)
self.editingItem = False
def scrollToPosition(self, index):
"""
Scrolls the Sequence Table to a given sequence position.
"""
item = self.sequenceTable.item(index, 0)
if item:
self.sequenceTable.scrollToItem(item)
def _applyAny(self):
"""
Apply "ALLAA" descriptor.
"""
for row in range(self.sequenceTable.rowCount()):
self._setComboBoxIndexChanged(0, tablerow = row, selectedOnly = True)
def _applySame(self):
"""
Apply "NATAA" descriptor.
"""
for row in range(self.sequenceTable.rowCount()):
self._setComboBoxIndexChanged(1, tablerow = row, selectedOnly = True)
def _applyLocked(self):
"""
Apply "NATRO" descriptor.
"""
for row in range(self.sequenceTable.rowCount()):
self._setComboBoxIndexChanged(2, tablerow = row, selectedOnly = True)
def _applyPolar(self):
"""
Apply "POLAR" descriptor.
"""
for row in range(self.sequenceTable.rowCount()):
self._setComboBoxIndexChanged(3, tablerow = row, selectedOnly = True)
def _applyApolar(self):
"""
Apply "APOLA" descriptor.
"""
for row in range(self.sequenceTable.rowCount()):
self._setComboBoxIndexChanged(4, tablerow = row, selectedOnly = True)
def resizeEvent(self, event):
"""
Called whenever PM width has changed. Sets correct width of the
rows in descriptor and sequence tables.
"""
self.descriptorsTable.setColumnWidth(1,
self.descriptorsTable.width()-self.descriptorsTable.columnWidth(0)-20)
self.sequenceTable.setColumnWidth(4,
self.sequenceTable.width()-
(self.sequenceTable.columnWidth(0) +
self.sequenceTable.columnWidth(1) +
self.sequenceTable.columnWidth(2) +
self.sequenceTable.columnWidth(3))-20)
def _addNewDescriptorTableRow(self, name, descriptor):
"""
Adds a new row to the descriptor table.
"""
row = self.descriptorsTable.rowCount()
self.descriptorsTable.insertRow(row)
item_widget = QTableWidgetItem(name)
item_widget.setFont(self.labelfont)
item_widget.setFlags(Qt.ItemIsSelectable |
Qt.ItemIsEnabled |
Qt.ItemIsEditable)
item_widget.setTextAlignment(Qt.AlignLeft)
self.descriptorsTable.setItem(row, 0, item_widget)
self.descriptorsTable.resizeColumnToContents(0)
s = self._makeProperAAString(descriptor)
item_widget = QTableWidgetItem(s)
item_widget.setFont(self.descriptorfont)
item_widget.setFlags(Qt.ItemIsSelectable |
Qt.ItemIsEnabled |
Qt.ItemIsEditable)
item_widget.setTextAlignment(Qt.AlignLeft)
self.descriptorsTable.setItem(row, 1, item_widget)
self.descriptorsTable.setColumnWidth(1,
self.descriptorsTable.width()-self.descriptorsTable.columnWidth(0)-20)
self.descriptorsTable.setRowHeight(row, 16)
def _addNewDescriptor(self):
"""
Adds a new descriptor to the descriptor table.
"""
self._addNewDescriptorTableRow("New Set", "PGAVILMFWYCSTNQDEHKR")
self._makeDescriptorUserPref()
self._updateSetLists()
def _removeDescriptor(self):
"""
Removes a highlighted descriptor from the descriptors table.
"""
crow = self.descriptorsTable.currentRow()
if crow >= 0:
self.descriptorsTable.removeRow(crow)
self._makeDescriptorUserPref()
self._updateSetLists()
def _makeDescriptorUserPref(self):
"""
Constructs a custom descriptors string.
"""
dstr = ""
for row in range(self.descriptorsTable.rowCount()):
item0 = self.descriptorsTable.item(row, 0)
item1 = self.descriptorsTable.item(row, 1)
if item0 and \
item1:
dstr += item0.text() + \
":" + \
item1.text() + \
":"
env.prefs[proteinCustomDescriptors_prefs_key] = dstr
def _makeProperAAString(self, string):
"""
Creates a proper amino acid string from an arbitrary string.
"""
aa_string = str(string).upper()
new_aa_string = ""
for i in range(len(self.rosetta_all_set)):
if aa_string.find(self.rosetta_all_set[i]) == -1:
new_aa_string += "_"
else:
new_aa_string += self.rosetta_all_set[i]
return new_aa_string
def _sequenceTableItemChanged(self, item):
"""
Called when an item in the sequence table has changed.
"""
if self.editingItem:
return
if self.sequenceTable.column(item) == 4:
self.editingItem = True
crow = self.sequenceTable.currentRow()
dstr = self._makeProperAAString(str(item.text()).upper())
item.setText(dstr)
aa = self._get_aa_for_index(crow)
if aa:
aa.set_mutation_range("PIKAA")
aa.set_mutation_descriptor(dstr.replace("_",""))
item = self.sequenceTable.item(crow, 2)
if item:
item.setText("Custom")
self.editingItem = False
def _descriptorsTableItemChanged(self, item):
"""
Called when an item in the descriptors table has changed.
"""
if self.editingItem:
return
if self.descriptorsTable.column(item) == 1:
self.editingItem = True
item.setText(self._makeProperAAString(str(item.text()).upper()))
self.editingItem = False
self._makeDescriptorUserPref()
self._updateSetLists()
def _updateSetLists(self):
"""
Updates lists of descriptor sets and descriptor set names.
"""
self.set_names = self.set_names[:5]
self.descriptor_list = self.descriptor_list[:5]
self.rosetta_set_names = self.rosetta_set_names[:5]
dstr = env.prefs[proteinCustomDescriptors_prefs_key].split(":")
for i in range(len(dstr) / 2):
self.set_names.append(dstr[2*i])
self.descriptor_list.append(dstr[2*i+1])
self.rosetta_set_names.append("PIKAA")
#self._addNewDescriptorTableRow(dstr[2*i], dstr[2*i+1])
return
def _update_UI_do_updates_TEMP(self):
"""
Overrides superclass method.
@see: Command_PropertyManager._update_UI_do_updates()
"""
self.current_protein = self.win.assy.getSelectedProteinChunk()
if self.current_protein is self.previous_protein:
print "_update_UI_do_updates(): DO NOTHING."
return
# NOTE: Changing the display styles of the protein chunks can take some
# time. We should put up the wait (hourglass) cursor here and restore
# before returning.
# Update all PM widgets that need to be since something has changed.
print "_update_UI_do_updates(): UPDATING the PMGR."
self.update_name_field()
self.sequenceEditor.update()
self.update_residue_combobox()
if self.previous_protein:
self.previous_protein.setDisplayStyle(self.previous_protein_display_style)
self.previous_protein = self.current_protein
if self.current_protein:
self.previous_protein_display_style = self.current_protein.getDisplayStyle()
self.current_protein.setDisplayStyle(diPROTEIN)
return
| NanoCAD-master | cad/src/protein/commands/EditResidues/EditResidues_PropertyManager.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.changes as changes
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from command_support.EditCommand import EditCommand
from utilities.constants import red
from protein.commands.EditResidues.EditResidues_PropertyManager import EditResidues_PropertyManager
# == GraphicsMode part
_superclass_for_GM = SelectChunks_GraphicsMode
class EditResidues_GraphicsMode(SelectChunks_GraphicsMode ):
"""
Graphics mode for Edit Residues command.
"""
pass
# == Command part
class EditResidues_Command(EditCommand):
"""
"""
# class constants
GraphicsMode_class = EditResidues_GraphicsMode
PM_class = EditResidues_PropertyManager
commandName = 'EDIT_RESIDUES'
featurename = "Edit Residues"
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
command_should_resume_prevMode = True
command_has_its_own_PM = True
flyoutToolbar = None
def _getFlyoutToolBarActionAndParentCommand(self):
"""
See superclass for documentation.
@see: self.command_update_flyout()
"""
flyoutActionToCheck = 'editResiduesAction'
parentCommandName = 'BUILD_PROTEIN'
return flyoutActionToCheck, parentCommandName
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
(and as of 2008-03-06, it is proposed that dna_updater calls this method
when needed.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
return bool_keep
| NanoCAD-master | cad/src/protein/commands/EditResidues/EditResidues_Command.py |
NanoCAD-master | cad/src/protein/commands/EditResidues/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Piotr, Ninad
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@version: $Id$
History:
2008-07-24: Created
"""
from utilities.Log import greenmsg
from command_support.EditCommand import EditCommand
from protein.commands.InsertPeptide.PeptideGenerator import PeptideGenerator
from utilities.constants import gensym
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from protein.temporary_commands.PeptideLine_GraphicsMode import PeptideLine_GraphicsMode
from utilities.debug import print_compact_stack, print_compact_traceback
import foundation.env as env
from utilities.prefs_constants import cursorTextColor_prefs_key
from protein.commands.BuildProtein.BuildProtein_Command import BuildProtein_Command
from protein.commands.InsertPeptide.InsertPeptide_PropertyManager import InsertPeptide_PropertyManager
_superclass = EditCommand
class InsertPeptide_EditCommand(EditCommand):
PM_class = InsertPeptide_PropertyManager
cmd = greenmsg("Insert Peptide: ")
prefix = 'Peptide' # used for gensym
cmdname = 'Insert Peptide'
commandName = 'INSERT_PEPTIDE'
featurename = "Insert Peptide"
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
create_name_from_prefix = True
GraphicsMode_class = PeptideLine_GraphicsMode
#required by PeptideLine_GraphicsMode
mouseClickPoints = []
structGenerator = PeptideGenerator()
command_should_resume_prevMode = True
command_has_its_own_PM = True
def __init__(self, commandSequencer):
"""
Constructor for InsertPeptide_EditCommand
"""
_superclass.__init__(self, commandSequencer)
#Maintain a list of peptides created while this command is running.
self._peptideList = []
return
def command_entered(self):
"""
Extends superclass method.
@see: basecommand.command_entered() for documentation
"""
_superclass.command_entered(self)
#NOTE: Following code was copied from self.init_gui() that existed
#in old command API -- Ninad 2008-09-18
if isinstance(self.graphicsMode, PeptideLine_GraphicsMode):
self._setParamsForPeptideLineGraphicsMode()
self.mouseClickPoints = []
#Clear the peptideList as it may still be maintaining a list of peptides
#from the previous run of the command.
self._peptideList = []
ss_idx, self.phi, self.psi, aa_type = self._gatherParameters()
return
def command_will_exit(self):
"""
Extends superclass method.
@see: basecommand.command_will_exit() for documentation
"""
if isinstance(self.graphicsMode, PeptideLine_GraphicsMode):
self.mouseClickPoints = []
self.graphicsMode.resetVariables()
self._peptideList = []
_superclass.command_will_exit(self)
return
def _getFlyoutToolBarActionAndParentCommand(self):
"""
See superclass for documentation.
@see: self.command_update_flyout()
"""
flyoutActionToCheck = 'buildPeptideAction'
parentCommandName = 'BUILD_PROTEIN'
return flyoutActionToCheck, parentCommandName
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
(and as of 2008-03-06, it is proposed that cnt_updater calls this method
when needed.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = _superclass.keep_empty_group(self, group)
return bool_keep
def _gatherParameters(self):
"""
Return the parameters from the property manager.
"""
return self.propMgr.getParameters()
def runCommand(self):
"""
Overrides EditCommand.runCommand
"""
self.struct = None
return
def _createStructure(self):
"""
Build a peptide from the parameters in the Property Manager.
"""
# self.name needed for done message
if self.create_name_from_prefix:
# create a new name
name = self.name = gensym(self.prefix, self.win.assy) # (in _build_struct)
self._gensym_data_for_reusing_name = (self.prefix, name)
else:
# use externally created name
self._gensym_data_for_reusing_name = None
# (can't reuse name in this case -- not sure what prefix it was
# made with)
name = self.name
self.secondary, self.phi, self.psi, aa_type = self._gatherParameters()
#
self.win.assy.part.ensure_toplevel_group()
"""
struct = self.structGenerator.make(self.win.assy,
name,
params,
-self.win.glpane.pov)
"""
from geometry.VQT import V
pos1 = V(self.mouseClickPoints[0][0], \
self.mouseClickPoints[0][1], \
self.mouseClickPoints[0][2])
pos2 = V(self.mouseClickPoints[1][0], \
self.mouseClickPoints[1][1], \
self.mouseClickPoints[1][2])
struct = self.structGenerator.make_aligned(self.win.assy,
name,
aa_type,
self.phi,
self.psi,
pos1,
pos2,
fake_chain = False,
secondary = self.secondary)
self.win.assy.part.topnode.addmember(struct)
self.win.win_update()
return struct
def _modifyStructure(self, params):
"""
Modify the structure based on the parameters specified.
Overrides EditCommand._modifystructure. This method removes the old
structure and creates a new one using self._createStructure.
See more comments in this method.
"""
#@NOTE: Unlike editcommands such as Plane_EditCommand or
#DnaSegment_EditCommand this actually removes the structure and
#creates a new one when its modified.
#TODO: Change this implementation to make it similar to whats done
#iin DnaSegment resize. (see DnaSegment_EditCommand)
self._removeStructure()
self.previousParams = params
self.struct = self._createStructure()
return
def cancelStructure(self):
"""
Overrides Editcommand.cancelStructure. Calls _removePeptides which
deletes all the peptides created while this command was running.
@see: B{EditCommand.cancelStructure}
"""
_superclass.cancelStructure(self)
self._removePeptides()
return
def _removePeptides(self):
"""
Deletes all the peptides created while this command was running
@see: L{self.cancelStructure}
"""
peptideList = self._peptideList
#for peptide in peptideList:
#can peptide be None? Lets add this condition to be on the safer
#side.
# if peptide is not None:
# peptide.kill_with_contents()
# self._revertNumber()
self._peptideList = []
self.win.win_update()
return
def createStructure(self):
"""
Overrides superclass method. Creates the structure
"""
assert self.propMgr is not None
if self.struct is not None:
self.struct = None
self.win.assy.part.ensure_toplevel_group()
self.propMgr.endPoint1 = self.mouseClickPoints[0]
self.propMgr.endPoint2 = self.mouseClickPoints[1]
#ntLength = vlen(self.mouseClickPoints[0] - self.mouseClickPoints[1])
self.preview_or_finalize_structure(previewing = True)
#Now append this peptide to self._peptideList
self._peptideList.append(self.struct)
#clear the mouseClickPoints list
self.mouseClickPoints = []
self.graphicsMode.resetVariables()
return
def _finalizeStructure(self):
"""
Finalize the structure. This is a step just before calling Done method.
to exit out of this command. Subclasses may overide this method
@see: EditCommand_PM.ok_btn_clicked
"""
if len(self.mouseClickPoints) == 1:
return
else:
_superclass._finalizeStructure(self)
return
def _getStructureType(self):
"""
Subclasses override this method to define their own structure type.
Returns the type of the structure this editCommand supports.
This is used in isinstance test.
@see: EditCommand._getStructureType() (overridden here)
"""
return self.win.assy.Chunk
def _setParamsForPeptideLineGraphicsMode(self):
#"""
#Needed for PeptideLine_GraphicsMode (NanotubeLine_GM). The method names need to
#be revised (e.g. callback_xxx. The prefix callback_ was for the earlier
#implementation of CntLine mode where it just used to supply some
#parameters to the previous mode using the callbacks from the
#previous mode.
#"""
self.mouseClickLimit = None
self.jigList = self.win.assy.getSelectedJigs()
self.callbackMethodForCursorTextString = self.getCursorText
self.callbackForSnapEnabled = self.isRubberbandLineSnapEnabled
self.callback_rubberbandLineDisplay = self.getDisplayStyleForNtRubberbandLine
return
def getCursorText(self, endPoint1, endPoint2):
"""
This is used as a callback method in PeptideLineLine mode
@see: PeptideLine_GraphicsMode.setParams, PeptideLine_GraphicsMode.Draw
"""
text = ''
textColor = env.prefs[cursorTextColor_prefs_key]
if endPoint1 is None or endPoint2 is None:
return text, textColor
vec = endPoint2 - endPoint1
from geometry.VQT import vlen
peptideLength = vlen(vec)
ss_idx, phi, psi, aa_type = self._gatherParameters()
peptideLength = self.structGenerator.get_number_of_res(endPoint1, endPoint2, phi, psi)
lengthString = self._getCursorText_length(peptideLength)
thetaString = ''
#Urmi 20080804: not sure if angle will be required later
theta = self.glpane.get_angle_made_with_screen_right(vec)
thetaString = '%5.2f deg'%theta
commaString = ", "
text = lengthString
if text and thetaString:
text += commaString
text += thetaString
return text, textColor
def _getCursorText_length(self, peptideLength):
"""
Returns a string that gives the length of the Peptide for the cursor
text.
@param peptideLength: length of the peptide (number of amino acids)
@type peptideLength: int
"""
# This should be moved to more appropriate place. piotr 081308
self.secondary, self.phi, self.psi, aa_type = self._gatherParameters()
peptideLengthString = ''
lengthUnitString = 'AA'
#change the unit of length to nanometers if the length is > 10A
#fixes part of bug 2856
peptideLengthString = "%d%s"%(peptideLength, lengthUnitString)
return peptideLengthString
def getDisplayStyleForNtRubberbandLine(self):
"""
This is used as a callback method in peptideLine mode.
@return: The current display style for the rubberband line.
@rtype: string
@note: Placeholder for now
"""
return 'Ladder'
def isRubberbandLineSnapEnabled(self):
"""
This returns True or False based on the checkbox state in the PM.
This is used as a callback method in CntLine mode (NanotubeLine_GM)
@see: NanotubeLine_GM.snapLineEndPoint where the boolean value returned from
this method is used
@return: Checked state of the linesnapCheckBox in the PM
@rtype: boolean
@note: placeholder for now
"""
return True
| NanoCAD-master | cad/src/protein/commands/InsertPeptide/InsertPeptide_EditCommand.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
This is a Property Manager dialog for the "Insert Peptide" command.
@author: Piotr, Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
History:
Piotr 2008-01-11: Implemented Peptide Generator dialog using PropMgrBaseClass
(just copied most stuff from NanotubeGeneratorPropertyManager).
Piotr 2008-03-02: Re-written the Property Manager dialogs to allow it working in
the interactive mode.
Piotr 080407: Fixed minor bugs in sequence text editor window.
Urmi 20080731: Property Manager updated to support drawing proteins by
clicking on two points.
To do:
- Color amino acid buttons by class:
- hydrophobic = pink
- charged = light green
- polar = light blue
"""
import math
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import Qt
from command_support.EditCommand_PM import EditCommand_PM
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_CheckBox import PM_CheckBox
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_SpinBox import PM_SpinBox
from PM.PM_PushButton import PM_PushButton
from PM.PM_ToolButtonGrid import PM_ToolButtonGrid
from PM.PM_TextEdit import PM_TextEdit
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_Constants import PM_CANCEL_BUTTON
from PM.PM_Constants import PM_PREVIEW_BUTTON
from utilities.debug import print_compact_traceback
from utilities.Log import orangemsg, greenmsg, redmsg
import foundation.env as env
from protein.model.Residue import Residue
from protein.model.Residue import SS_HELIX, SS_COIL, SS_STRAND
# list of button descriptors for PM_ToolButtonGrid
AA_BUTTON_LIST = [
( "QToolButton", 0, "Ala", "", "Alanine", "A", 0, 0 ),
( "QToolButton", 1, "Arg", "", "Arginine", "R", 1, 0 ),
( "QToolButton", 2, "Asn", "", "Asparagine", "N", 2, 0 ),
( "QToolButton", 3, "Asp", "", "Aspartic Acid", "D", 3, 0 ),
( "QToolButton", 4, "Cys", "", "Cysteine", "C", 4, 0 ),
( "QToolButton", 5, "Glu", "", "Glutamic Acid", "E", 0, 1 ),
( "QToolButton", 6, "Gln", "", "Glutamine", "Q", 1, 1 ),
( "QToolButton", 7, "Gly", "", "Glycine", "G", 2, 1 ),
( "QToolButton", 8, "His", "", "Histidine", "H", 3, 1 ),
( "QToolButton", 9, "Ile", "", "Isoleucine", "I", 4, 1 ),
( "QToolButton", 10, "Leu", "", "Leucine", "L", 0, 2 ),
( "QToolButton", 11, "Lys", "", "Lysine", "K", 1, 2 ),
( "QToolButton", 12, "Met", "", "Methionine", "M", 2, 2 ),
( "QToolButton", 13, "Phe", "", "Phenylalanine", "F", 3, 2 ),
( "QToolButton", 14, "Pro", "", "Proline", "P", 4, 2 ),
( "QToolButton", 15, "Ser", "", "Serine", "S", 0, 3 ),
( "QToolButton", 16, "Thr", "", "Threonine", "T", 1, 3 ),
( "QToolButton", 17, "Trp", "", "Tryptophan" , "W", 2, 3 ),
( "QToolButton", 18, "Tyr", "", "Tyrosine", "Y", 3, 3 ),
( "QToolButton", 19, "Val", "", "Valine", "V", 4, 3 )
]
_superclass = EditCommand_PM
class InsertPeptide_PropertyManager(EditCommand_PM):
"""
The InsertPeptide_PropertyManager class provides a Property Manager
for the "Insert > Peptide" command.
"""
# The title that appears in the property manager header.
title = "Insert Peptide"
# The name of this property manager. This will be set to
# the name of the PropMgr (this) object via setObjectName().
pmName = title
# The relative path to PNG file that appears in the header.
iconPath = "ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png"
# phi psi angles will define the secondary structure of the peptide chain
phi = -57.0
psi = -47.0
chirality = 1
secondary = SS_HELIX
current_amino_acid = 7 # Glycine
# DEPRECATED ATTRS
#peptide_cache = []
#peptide_cache.append((0, 0, 0))
def __init__( self, command ):
"""
Construct the Property Manager.
"""
_superclass.__init__( self, command )
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_CANCEL_BUTTON | \
PM_WHATS_THIS_BUTTON)
return
def show(self):
"""
Extends superclass method.
"""
_superclass.show(self)
self.updateMessage("Choose the peptide parameters below, then click "\
"two endpoints in the graphics area to insert a "\
"peptide chain.")
return
def getParameters(self):
"""
Return the parameters from this property manager
to be used to create the peptide.
@return: A tuple containing the parameters
@rtype: tuple
@see: L{InsertPeptide_EditCommand._gatherParameters()} where this is used
"""
return (self.secondary, self.phi, self.psi, self.current_amino_acid)
def _addGroupBoxes(self):
"""
Add the group boxe to the Peptide Property Manager dialog.
"""
self.pmGroupBox1 = \
PM_GroupBox( self,
title = "Peptide Parameters" )
# Add group box widgets.
self._loadGroupBox1(self.pmGroupBox1)
return
def _loadGroupBox1(self, inPmGroupBox):
"""
Load widgets in the group box.
"""
memberChoices = ["Custom",
"Alpha helix",
"Beta strand",
"Pi helix",
"3_10 helix",
"Polyproline-II helix",
"Fully extended"]
self.aaTypeComboBox= \
PM_ComboBox( inPmGroupBox,
label = "Conformation:",
choices = memberChoices,
index = 1,
setAsDefault = True,
spanWidth = False )
self.connect( self.aaTypeComboBox,
SIGNAL("currentIndexChanged(int)"),
self._aaTypeChanged)
self.phiAngleField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "Phi angle:",
value = self.phi,
setAsDefault = True,
minimum = -180.0,
maximum = 180.0,
singleStep = 1.0,
decimals = 1,
suffix = " degrees")
self.connect( self.phiAngleField,
SIGNAL("valueChanged(double)"),
self._aaPhiAngleChanged)
self.phiAngleField.setEnabled(False)
self.psiAngleField = \
PM_DoubleSpinBox( inPmGroupBox,
label = "Psi angle:",
value = self.psi,
setAsDefault = True,
minimum = -180.0,
maximum = 180.0,
singleStep = 1.0,
decimals = 1,
suffix = " degrees" )
self.connect( self.psiAngleField,
SIGNAL("valueChanged(double)"),
self._aaPsiAngleChanged)
self.psiAngleField.setEnabled(False)
self.aaTypesButtonGroup = \
PM_ToolButtonGrid( inPmGroupBox,
buttonList = AA_BUTTON_LIST,
label = "Amino acids",
checkedId = self.current_amino_acid, # Glycine
setAsDefault = True )
self.connect( self.aaTypesButtonGroup.buttonGroup,
SIGNAL("buttonClicked(int)"),
self._setAminoAcidType)
return
def _addWhatsThisText(self):
"""
What's This text for widgets in this Property Manager.
"""
from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertPeptide_PropertyManager
whatsThis_InsertPeptide_PropertyManager(self)
return
def _addToolTipText(self):
"""
Tool Tip text for widgets in this Property Manager.
"""
from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_InsertPeptide_PropertyManager
ToolTip_InsertPeptide_PropertyManager(self)
return
def _aaChiralityChanged(self):
"""
Set chirality of the peptide chain.
"""
# This feature is currently disable as it was confusing to the users
# who expected control over chirality of amino acids (D/L conformers)
# rather than over polypeptide chain (left/right-handed structure).
self.psi *= -1
self.phi *= -1
self.phiAngleField.setValue(self.phi)
self.psiAngleField.setValue(self.psi)
return
def _aaTypeChanged(self, idx):
"""
Slot for Peptide Structure Type combo box. Changes phi/psi angles
for secondary structure.
@param idx: index of secondary structure combo box
@type idx: int
"""
self.ss_idx = idx
if idx == 0:
self.phiAngleField.setEnabled(True)
self.psiAngleField.setEnabled(True)
else:
self.phiAngleField.setEnabled(False)
self.psiAngleField.setEnabled(False)
if idx == 1: # alpha helix
self.phi = -57.0
self.psi = -47.0
self.secondary = SS_HELIX
elif idx == 2: # beta strand
self.phi = -135.0
self.psi = 135.0
self.secondary = SS_STRAND
elif idx == 3: # 3-10 helix
self.phi = -55.0
self.psi = -70.0
self.secondary = SS_HELIX
elif idx == 4: # pi helix
self.phi = -49.0
self.psi = -26.0
self.secondary = SS_HELIX
elif idx == 5: # polyprolin-II
self.phi = -75.0
self.psi = 150.0
self.secondary = SS_COIL
elif idx == 6: # fully extended
self.phi = -180.0
self.psi = 180.0
self.secondary = SS_STRAND
else:
self.phi = self.phiAngleField.value()
self.psi = self.psiAngleField.value()
self.secondary = SS_COIL
self.phi *= self.chirality
self.psi *= self.chirality
self.command.secondary = self.secondary
self.phiAngleField.setValue(self.phi)
self.psiAngleField.setValue(self.psi)
return
def _aaPhiAngleChanged(self, phi):
"""
Called when phi angle spin box has changed.
@param phi: phi angle value
@type phi: float
"""
self.phi = self.phiAngleField.value()
return
def _aaPsiAngleChanged(self, psi):
"""
Called when psi angle spin box has changed.
@param psi: psi angle value
@type psi: float
"""
self.psi = self.psiAngleField.value()
return
def _setAminoAcidType(self, index):
"""
Sets the current amino acid type to I{index}.
"""
self.current_amino_acid = index
return
# --------------------------------------------------------------------
# Deprecated methods to keep until we're certain this is working.
# --Mark 2008-12-12.
def addAminoAcid_DEPRECATED(self, index):
"""
Adds a new amino acid to the peptide molecule.
"""
# This commened out code is obsolete in interactive peptide builder.
# The interactive peptide builder creates homopeptides.
# add a new amino acid and chain conformation to the peptide cache
#self.peptide_cache.append((index,self.phi,self.psi))
#self.peptide_cache[0] = (index,self.phi,self.psi)
self.current_amino_acid = index
return
def _setAminoAcidType_DEPRECATED(self, aaTypeIndex):
"""
Adds a new amino acid to the peptide molecule.
"""
# piotr 080911: this method is obsolete as of 080911. It was used in
# the old Peptide Generator.
button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[aaTypeIndex]
if self.ss_idx==1:
aa_txt = "<font color=red>"
elif self.ss_idx==2:
aa_txt = "<font color=blue>"
elif self.ss_idx==3:
aa_txt = "<font color=green>"
elif self.ss_idx==4:
aa_txt = "<font color=orange>"
elif self.ss_idx==5:
aa_txt = "<font color=magenta>"
elif self.ss_idx==6:
aa_txt = "<font color=darkblue>"
else:
aa_txt = "<font color=black>"
aa_txt += symbol+"</font>"
#self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False)
return
| NanoCAD-master | cad/src/protein/commands/InsertPeptide/InsertPeptide_PropertyManager.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
PeptideGenerator.py
Peptide Generator can generate short polypeptide chains of arbitrarily choosen
sequence and secondary structure.
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@see http://www.nanoengineer-1.net/mediawiki/index.php?title=Peptide_generator_dialog
for notes about what's going on here.
History:
Ninad 2008-07-24: Refactoring / cleanup to port PeptideGenerator to the
EditCommand API. (see InsertPeptide_EditCommand)
"""
import foundation.env as env
from geometry.InternalCoordinatesToCartesian import InternalCoordinatesToCartesian
from model.chem import Atom
from model.chunk import Chunk
from model.bond_constants import V_DOUBLE, V_AROMATIC
from operations.bonds_from_atoms import inferBonds
from protein.model.Protein import Protein
from protein.model.Residue import Residue
from protein.model.Residue import SS_HELIX, SS_STRAND, SS_COIL, AA_3_TO_1
from Numeric import zeros, sqrt, pi, sin, cos, Float
from geometry.VQT import Q, V, norm, vlen, cross, angleBetween
from utilities.debug import print_compact_stack
# Internal coordinate sets for amino acids
# Converted from AMBER all_amino94.in file
# Fixed a few issues: conformation of phenylalanine, connectivity of serine.
# Beware of proline - it needs to be handled in a different way.
ALA_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp3", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB1", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 9, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 180.000 ),
( 10, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 11, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 12, "O ", "O", "sp2", 11, 5, 3, 1.229, 120.500, 0.000 ),
]
GLY_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA2", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "HA3", "H", "", 5, 3, 2, 1.090, 109.500, 60.000 ),
( 8, "C ", "C", "sp2", 5, 3, 2, 1.522, 110.400, 180.000 ),
( 9, "O ", "O", "sp2", 8, 5, 3, 1.229, 120.500, 0.000 )
]
SER_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "OG ", "O", "sp3", 7, 5, 3, 1.430, 109.470, 180.000 ),
( 11, "HG ", "H", "", 10, 7, 5, 0.960, 109.470, 180.000 ),
( 12, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 13, "O ", "O", "sp2", 12, 5, 3, 1.229, 120.500, 0.000 ),
]
PHE_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp2a", 7, 5, 3, 1.510, 115.000, 180.000 ),
( 11, "CD1", "C", "sp2a", 10, 7, 5, 1.400, 120.000, 180.000 ),
( 12, "HD1", "H", "", 11, 10, 7, 1.090, 120.000, 0.000 ),
( 13, "CE1", "C", "sp2a", 11, 10, 7, 1.400, 120.000, 180.000 ),
( 14, "HE1", "H", "", 13, 11, 10, 1.090, 120.000, 180.000 ),
( 15, "CZ ", "C", "sp2a", 13, 11, 10, 1.400, 120.000, 0.000 ),
( 16, "HZ ", "H", "", 15, 13, 11, 1.090, 120.000, 180.000 ),
( 17, "CE2", "C", "sp2a", 15, 13, 11, 1.400, 120.000, 0.000 ),
( 18, "HE2", "H", "", 17, 15, 13, 1.090, 120.000, 180.000 ),
( 19, "CD2", "C", "sp2a", 17, 15, 13, 1.400, 120.000, 0.000 ),
( 20, "HD2", "H", "", 19, 17, 15, 1.090, 120.000, 180.000 ),
( 21, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 22, "O ", "O", "sp2", 21, 5, 3, 1.229, 120.500, 0.000 ),
]
GLU_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp3", 7, 5, 3, 1.510, 109.470, 180.000 ),
( 11, "HG2", "H", "", 10, 7, 5, 1.090, 109.500, 300.000 ),
( 12, "HG3", "H", "", 10, 7, 5, 1.090, 109.500, 60.000 ),
( 13, "CD ", "C", "sp2", 10, 7, 5, 1.527, 109.470, 180.000 ),
( 14, "OE1", "O", "sp2", 13, 10, 7, 1.260, 117.200, 90.000 ),
( 15, "OE2", "O", "sp3", 13, 10, 7, 1.260, 117.200, 270.000 ),
( 16, "HE2", "H", "", 15, 13, 10, 0.960, 109.500, 180.000 ),
( 17, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 18, "O ", "O", "sp2", 17, 5, 3, 1.229, 120.500, 0.000 ),
]
PRO_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.337, 117.000, 180.000 ),
( 4, "CD ", "C", "sp3", 3, 2, 1, 1.458, 126.100, 356.100 ),
( 5, "HD2", "H", "", 4, 3, 2, 1.090, 109.500, 80.000 ),
( 6, "HD3", "H", "", 4, 3, 2, 1.090, 109.500, 320.000 ),
( 7, "CG ", "C", "sp3", 4, 3, 2, 1.500, 103.200, 200.100 ),
( 8, "HG2", "H", "", 7, 4, 3, 1.090, 109.500, 218.000 ),
( 9, "HG3", "H", "", 7, 4, 3, 1.090, 109.500, 98.000 ),
( 10, "CB ", "C", "sp3", 7, 4, 3, 1.510, 106.000, 338.300 ),
( 11, "HB2", "H", "", 10, 7, 4, 1.090, 109.500, 256.300 ),
( 12, "HB3", "H", "", 10, 7, 4, 1.090, 109.500, 136.300 ),
( 13, "CA ", "C", "sp3", 3, 2, 1, 1.451, 120.600, 175.200 ),
( 14, "HA ", "H", "", 13, 3, 2, 1.090, 109.500, 60.000 ),
( 15, "C ", "C", "sp2", 13, 3, 2, 1.522, 109.500, 300.000 ),
( 16, "O ", "O", "sp2", 15, 13, 3, 1.229, 120.500, 0.000 ),
]
CYS_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "SG ", "S", "sp3", 7, 5, 3, 1.810, 116.000, 180.000 ),
( 11, "HG ", "H", "", 10, 7, 5, 1.330, 96.000, 180.000 ),
( 12, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 13, "O ", "O", "sp2", 12, 5, 3, 1.229, 120.500, 0.000 ),
]
MET_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 11, "HG2", "H", "", 10, 7, 5, 1.090, 109.500, 300.000 ),
( 12, "HG3", "H", "", 10, 7, 5, 1.090, 109.500, 60.000 ),
( 13, "SD ", "S", "sp3", 10, 7, 5, 1.810, 110.000, 180.000 ),
( 14, "CE ", "C", "sp3", 13, 10, 7, 1.780, 100.000, 180.000 ),
( 15, "HE1", "H", "", 14, 13, 10, 1.090, 109.500, 60.000 ),
( 16, "HE2", "H", "", 14, 13, 10, 1.090, 109.500, 180.000 ),
( 17, "HE3", "H", "", 14, 13, 10, 1.090, 109.500, 300.000 ),
( 18, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 19, "O ", "O", "sp2", 18, 5, 3, 1.229, 120.500, 0.000 ),
]
THR_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB ", "H", "", 7, 5, 3, 1.090, 109.500, 180.000 ),
( 9, "CG2", "C", "sp3", 7, 5, 3, 1.525, 109.470, 300.000 ),
( 10, "HG2", "H", "", 9, 7, 5, 1.090, 109.500, 60.000 ),
( 11, "HG2", "H", "", 9, 7, 5, 1.090, 109.500, 180.000 ),
( 12, "HG2", "H", "", 9, 7, 5, 1.090, 109.500, 300.000 ),
( 13, "OG1", "O", "sp3", 7, 5, 3, 1.430, 109.470, 60.000 ),
( 14, "HG1", "H", "", 13, 7, 5, 0.960, 109.470, 180.000 ),
( 15, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 16, "O ", "O", "sp2", 15, 5, 3, 1.229, 120.500, 0.000 ),
]
LEU_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 11, "HG ", "H", "", 10, 7, 5, 1.090, 109.500, 300.000 ),
( 12, "CD1", "C", "sp3", 10, 7, 5, 1.525, 109.470, 60.000 ),
( 13, "HD1", "H", "", 12, 10, 7, 1.090, 109.500, 60.000 ),
( 14, "HD1", "H", "", 12, 10, 7, 1.090, 109.500, 180.000 ),
( 15, "HD1", "H", "", 12, 10, 7, 1.090, 109.500, 300.000 ),
( 16, "CD2", "C", "sp3", 10, 7, 5, 1.525, 109.470, 180.000 ),
( 17, "HD2", "H", "", 16, 10, 7, 1.090, 109.500, 60.000 ),
( 18, "HD2", "H", "", 16, 10, 7, 1.090, 109.500, 180.000 ),
( 19, "HD2", "H", "", 16, 10, 7, 1.090, 109.500, 300.000 ),
( 20, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 21, "O ", "O", "sp2", 20, 5, 3, 1.229, 120.500, 0.000 ),
]
ILE_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 109.470, 60.000 ),
( 8, "HB ", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "CG2", "C", "sp3", 7, 5, 3, 1.525, 109.470, 60.000 ),
( 10, "HG2", "H", "", 9, 7, 5, 1.090, 109.500, 60.000 ),
( 11, "HG2", "H", "", 9, 7, 5, 1.090, 109.500, 180.000 ),
( 12, "HG2", "H", "", 9, 7, 5, 1.090, 109.500, 300.000 ),
( 13, "CG1", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 14, "HG1", "H", "", 13, 7, 5, 1.090, 109.500, 300.000 ),
( 15, "HG1", "H", "", 13, 7, 5, 1.090, 109.500, 60.000 ),
( 16, "CD1", "C", "sp3", 13, 7, 5, 1.525, 109.470, 180.000 ),
( 17, "HD1", "H", "", 16, 13, 7, 1.090, 109.500, 60.000 ),
( 18, "HD1", "H", "", 16, 13, 7, 1.090, 109.500, 180.000 ),
( 19, "HD1", "H", "", 16, 13, 7, 1.090, 109.500, 300.000 ),
( 20, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 21, "O ", "O", "sp2", 20, 5, 3, 1.229, 120.500, 0.000 ),
]
VAL_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB ", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "CG1", "C", "sp3", 7, 5, 3, 1.525, 109.470, 60.000 ),
( 10, "HG1", "H", "", 9, 7, 5, 1.090, 109.500, 60.000 ),
( 11, "HG1", "H", "", 9, 7, 5, 1.090, 109.500, 180.000 ),
( 12, "HG1", "H", "", 9, 7, 5, 1.090, 109.500, 300.000 ),
( 13, "CG2", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 14, "HG2", "H", "", 13, 7, 5, 1.090, 109.500, 60.000 ),
( 15, "HG2", "H", "", 13, 7, 5, 1.090, 109.500, 180.000 ),
( 16, "HG2", "H", "", 13, 7, 5, 1.090, 109.500, 300.000 ),
( 17, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 18, "O ", "O", "sp2", 17, 5, 3, 1.229, 120.500, 0.000 ),
]
TRP_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp2", 7, 5, 3, 1.510, 115.000, 180.000 ),
( 11, "CD1", "C", "sp2", 10, 7, 5, 1.340, 127.000, 180.000 ),
( 12, "HD1", "H", "", 11, 10, 7, 1.090, 120.000, 0.000 ),
( 13, "NE1", "N", "sp3", 11, 10, 7, 1.430, 107.000, 180.000 ),
( 14, "HE1", "H", "", 13, 11, 10, 1.010, 125.500, 180.000 ),
( 15, "CE2", "C", "sp2a", 13, 11, 10, 1.310, 109.000, 0.000 ),
( 16, "CZ2", "C", "sp2a", 15, 13, 11, 1.400, 128.000, 180.000 ),
( 17, "HZ2", "H", "", 16, 15, 13, 1.090, 120.000, 0.000 ),
( 18, "CH2", "C", "sp2a", 16, 15, 13, 1.390, 116.000, 180.000 ),
( 19, "HH2", "H", "", 18, 16, 15, 1.090, 120.000, 180.000 ),
( 20, "CZ3", "C", "sp2a", 18, 16, 15, 1.350, 121.000, 0.000 ),
( 21, "HZ3", "H", "", 20, 18, 16, 1.090, 120.000, 180.000 ),
( 22, "CE3", "C", "sp2a", 20, 18, 16, 1.410, 122.000, 0.000 ),
( 23, "HE3", "H", "", 22, 20, 18, 1.090, 120.000, 180.000 ),
( 24, "CD2", "C", "sp2a", 22, 20, 18, 1.400, 117.000, 0.000 ),
( 25, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 26, "O ", "O", "sp2", 25, 5, 3, 1.229, 120.500, 0.000 ),
]
TYR_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp2a", 7, 5, 3, 1.510, 109.470, 180.000 ),
( 11, "CD1", "C", "sp2a", 10, 7, 5, 1.400, 120.000, 180.000 ),
( 12, "HD1", "H", "", 11, 10, 7, 1.090, 120.000, 0.000 ),
( 13, "CE1", "C", "sp2a", 11, 10, 7, 1.400, 120.000, 180.000 ),
( 14, "HE1", "H", "", 13, 11, 10, 1.090, 120.000, 180.000 ),
( 15, "CZ ", "C", "sp2a", 13, 11, 10, 1.400, 120.000, 0.000 ),
( 16, "OH ", "O", "sp3", 15, 13, 11, 1.360, 120.000, 180.000 ),
( 17, "HH ", "H", "", 16, 15, 13, 0.960, 113.000, 0.000 ),
( 18, "CE2", "C", "sp2a", 15, 13, 11, 1.400, 120.000, 0.000 ),
( 19, "HE2", "H", "", 18, 15, 13, 1.090, 120.000, 180.000 ),
( 20, "CD2", "C", "sp2a", 18, 15, 13, 1.400, 120.000, 0.000 ),
( 21, "HD2", "H", "", 20, 18, 15, 1.090, 120.000, 180.000 ),
( 22, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 23, "O ", "O", "sp2", 22, 5, 3, 1.229, 120.500, 0.000 ),
]
LYS_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 11, "HG2", "H", "", 10, 7, 5, 1.090, 109.500, 300.000 ),
( 12, "HG3", "H", "", 10, 7, 5, 1.090, 109.500, 60.000 ),
( 13, "CD ", "C", "sp3", 10, 7, 5, 1.525, 109.470, 180.000 ),
( 14, "HD2", "H", "", 13, 10, 7, 1.090, 109.500, 300.000 ),
( 15, "HD3", "H", "", 13, 10, 7, 1.090, 109.500, 60.000 ),
( 16, "CE ", "C", "sp3", 13, 10, 7, 1.525, 109.470, 180.000 ),
( 17, "HE2", "H", "", 16, 13, 10, 1.090, 109.500, 300.000 ),
( 18, "HE3", "H", "", 16, 13, 10, 1.090, 109.500, 60.000 ),
( 19, "NZ ", "N", "sp3", 16, 13, 10, 1.470, 109.470, 180.000 ),
( 20, "HZ1", "H", "", 19, 16, 13, 1.010, 109.470, 60.000 ),
( 21, "HZ2", "H", "", 19, 16, 13, 1.010, 109.470, 180.000 ),
( 22, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 23, "O ", "O", "sp2", 22, 5, 3, 1.229, 120.500, 0.000 ),
]
ARG_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 11, "HG2", "H", "", 10, 7, 5, 1.090, 109.500, 300.000 ),
( 12, "HG3", "H", "", 10, 7, 5, 1.090, 109.500, 60.000 ),
( 13, "CD ", "C", "sp3", 10, 7, 5, 1.525, 109.470, 180.000 ),
( 14, "HD2", "H", "", 13, 10, 7, 1.090, 109.500, 300.000 ),
( 15, "HD3", "H", "", 13, 10, 7, 1.090, 109.500, 60.000 ),
( 16, "NE ", "N", "sp3", 13, 10, 7, 1.480, 111.000, 180.000 ),
( 17, "HE ", "H", "", 16, 13, 10, 1.010, 118.500, 0.000 ),
( 18, "CZ ", "C", "sp2", 16, 13, 10, 1.330, 123.000, 180.000 ),
( 19, "NH1", "N", "sp3", 18, 16, 13, 1.330, 122.000, 0.000 ),
( 20, "HH1", "H", "", 19, 18, 16, 1.010, 119.800, 0.000 ),
( 21, "HH1", "H", "", 19, 18, 16, 1.010, 119.800, 180.000 ),
( 22, "NH2", "N", "sp2", 18, 16, 13, 1.330, 118.000, 180.000 ),
( 23, "HH2", "H", "", 22, 18, 16, 1.010, 119.800, 0.000 ),
( 24, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 25, "O ", "O", "sp2", 24, 5, 3, 1.229, 120.500, 0.000 ),
]
HIS_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp2", 7, 5, 3, 1.510, 115.000, 180.000 ),
( 11, "ND1", "N", "sp3", 10, 7, 5, 1.390, 122.000, 180.000 ),
( 12, "HD1", "H", "", 11, 10, 7, 1.010, 126.000, 0.000 ),
( 13, "CE1", "C", "sp2", 11, 10, 7, 1.320, 108.000, 180.000 ),
( 14, "HE1", "H", "", 13, 11, 10, 1.090, 120.000, 180.000 ),
( 15, "NE2", "N", "sp2s", 13, 11, 10, 1.310, 109.000, 0.000 ),
( 16, "CD2", "C", "sp2s", 15, 13, 11, 1.360, 110.000, 0.000 ),
( 17, "HD2", "H", "", 16, 15, 13, 1.090, 120.000, 180.000 ),
( 18, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 19, "O ", "O", "sp2", 18, 5, 3, 1.229, 120.500, 0.000 ),
]
ASP_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp2", 7, 5, 3, 1.527, 109.470, 180.000 ),
( 11, "OD1", "O", "sp2", 10, 7, 5, 1.260, 117.200, 90.000 ),
( 12, "OD2", "O", "sp3", 10, 7, 5, 1.260, 117.200, 270.000 ),
( 13, "HD2", "H", "", 12, 10, 7, 0.960, 109.500, 180.000 ),
( 14, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 15, "O ", "O", "sp2", 14, 5, 3, 1.229, 120.500, 0.000 ),
]
ASN_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp2", 7, 5, 3, 1.522, 111.100, 180.000 ),
( 11, "OD1", "O", "sp2", 10, 7, 5, 1.229, 120.500, 0.000 ),
( 12, "ND2", "N", "sp3", 10, 7, 5, 1.335, 116.600, 180.000 ),
( 13, "HD2", "H", "", 12, 10, 7, 1.010, 119.800, 180.000 ),
( 14, "HD2", "H", "", 12, 10, 7, 1.010, 119.800, 0.000 ),
( 15, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 16, "O ", "O", "sp2", 15, 5, 3, 1.229, 120.500, 0.000 ),
]
GLN_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "N", "sp2(graphitic)", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 1.010, 119.800, 0.000 ),
( 5, "CA ", "C", "sp3", 3, 2, 1, 1.449, 121.900, 180.000 ),
( 6, "HA ", "H", "", 5, 3, 2, 1.090, 109.500, 300.000 ),
( 7, "CB ", "C", "sp3", 5, 3, 2, 1.525, 111.100, 60.000 ),
( 8, "HB2", "H", "", 7, 5, 3, 1.090, 109.500, 300.000 ),
( 9, "HB3", "H", "", 7, 5, 3, 1.090, 109.500, 60.000 ),
( 10, "CG ", "C", "sp3", 7, 5, 3, 1.525, 109.470, 180.000 ),
( 11, "HG2", "H", "", 10, 7, 5, 1.090, 109.500, 300.000 ),
( 12, "HG3", "H", "", 10, 7, 5, 1.090, 109.500, 60.000 ),
( 13, "CD ", "C", "sp2", 10, 7, 5, 1.522, 111.100, 180.000 ),
( 14, "OE1", "O", "sp2", 13, 10, 7, 1.229, 120.500, 0.000 ),
( 15, "NE2", "N", "sp3", 13, 10, 7, 1.335, 116.600, 180.000 ),
( 16, "HE2", "H", "", 15, 13, 10, 1.010, 119.800, 180.000 ),
( 17, "HE2", "H", "", 15, 13, 10, 1.010, 119.800, 0.000 ),
( 18, "C ", "C", "sp2", 5, 3, 2, 1.522, 111.100, 180.000 ),
( 19, "O ", "O", "sp2", 18, 5, 3, 1.229, 120.500, 0.000 ),
]
NTERM_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "N ", "H", "", 2, 1, 0, 1.335, 116.600, 180.000 ),
]
# Note: this is just a fake "N " label for the _buildResidue
# to make it thinking that we are starting a new amino acid.
CTERM_ZMATRIX = [
( 0, "DUM", "", "", -1, -2, -3, 0.000, 0.000, 0.000 ),
( 1, "DUM", "", "", 0, -1, -2, 1.449, 0.000, 0.000 ),
( 2, "DUM", "", "", 1, 0, -1, 1.522, 111.100, 0.000 ),
( 3, "OXT", "O", "sp3", 2, 1, 0, 1.335, 116.600, 180.000 ),
( 4, "H ", "H", "", 3, 2, 1, 0.960, 109.500, 0.000 ),
]
# all amino acids, z-matrices and their sizes
AMINO_ACIDS = [
( "Alanine", "ALA", "A", ALA_ZMATRIX, 13 ),
( "Arginine", "ARG", "R", ARG_ZMATRIX, 26 ),
( "Asparagine", "ARG", "N", ASN_ZMATRIX, 17 ),
( "Aspartic Acid", "ARG", "D", ASP_ZMATRIX, 16 ),
( "Cysteine", "CYS", "C", CYS_ZMATRIX, 14 ),
( "Glutamic Acid", "GLU", "E", GLU_ZMATRIX, 19 ),
( "Glutamine", "GLN", "Q", GLN_ZMATRIX, 20 ),
( "Glycine", "GLY", "G", GLY_ZMATRIX, 10 ),
( "Histidine", "HIS", "H", HIS_ZMATRIX, 20 ),
( "Isoleucine", "ILE", "I", ILE_ZMATRIX, 22 ),
( "Leucine", "LEU", "L", LEU_ZMATRIX, 22 ),
( "Lysine", "LYS", "K", LYS_ZMATRIX, 24 ),
( "Methionine", "MET", "M", MET_ZMATRIX, 20 ),
( "Phenylalanine", "PHE", "F", PHE_ZMATRIX, 23 ),
( "Proline", "PRO", "P", PRO_ZMATRIX, 17 ),
( "Serine", "SER", "S", SER_ZMATRIX, 14 ),
( "Threonine", "THR", "T", THR_ZMATRIX, 17 ),
( "Tryptophan", "TRP", "W", TRP_ZMATRIX, 27 ),
( "Tyrosine", "TYR", "Y", TYR_ZMATRIX, 24 ),
( "Valine", "VAL", "V", VAL_ZMATRIX, 19 )
]
# degrees to radians conversion
DEG2RAD = (pi/180.0)
def enablePeptideGenerator(enable):
"""
This function enables/disables the Peptide Generator command by hiding or
showing it in the Command Manager toolbar and menu.
The enabling/disabling is done by the user via the "secret" NE1 debugging
menu.
To display the secret debugging menu, hold down Shift+Ctrl+Alt keys
(or Shift+Cmd+Alt on Mac) and right click over the graphics area.
Select "debug prefs submenu > Peptide Generator" and
set the value to True. The "Peptide" option will then appear on the
"Build" Command Manager toolbar/menu.
@param enable: If true, the Peptide Generator is enabled. Specifically, it
will be added to the "Build" Command Manager toolbar and
menu.
@type enable: bool
"""
win = env.mainwindow()
win.buildProteinAction.setVisible(enable)
def get_unit_length(phi, psi):
"""
Calculate a length of single amino acid in particular
secondary conformation.
"""
# All unit length values obtained via measurements by me.
# Fixes bug 2959. --Mark 2008-12-23
if phi == -57.0 and psi == -47.0:
unit_length = 1.5 # Alpha helix
elif phi == -135.0 and psi == 135.0:
unit_length = 3.4 # Beta strand
elif phi == -55.0 and psi == -70.0:
unit_length = 1.05 # Pi helix
elif phi == -49.0 and psi == -26.0:
unit_length = 1.95 # 3_10 helix
elif phi == -75.0 and psi == 150.0:
unit_length = 3.14 # Polyproline-II helix
elif phi == -180.0 and psi == 180.0:
unit_length = 3.6 # Fully extended
else:
# User chose "Custom" conformation option in the Insert Peptide PM
# which lets the user set any phi-psi angle values.
# We need a formula to estimate the proper unit_length given the
# conformational angles phi and psi. It would also be a good idea
# to check these values to confirm they are an allowed combination.
# For more info, do a google search for "Ramachandran plot".
# For now, I'm setting the unit length to 1.5. --Mark 2008-12-23
unit_length = 1.5
msg = "\nUser selected custom conformational angles: "\
"phi=%.2f, psi=%.2f.\nSetting unit_length=%.2f\n" % \
(phi, psi, unit_length)
print_compact_stack(msg)
return unit_length
class PeptideGenerator:
prev_coords = zeros([3,3], Float)
peptide_mol = None
length = 0
prev_psi = 0
# Based on analogous Nanotube Builder method.
def _orient(self, chunk, pt1, pt2):
"""
Orients the Peptide I{chunk} based on two points. I{pt1} is
the first endpoint (origin) of the Peptide. The vector I{pt1}, I{pt2}
defines the direction and central axis of the Peptide.
piotr 080801: I copied this method from Nanotube Builder.
@param pt1: The starting endpoint (origin) of the Peptide.
@type pt1: L{V}
@param pt2: The second point of a vector defining the direction
and central axis of the Peptide.
@type pt2: L{V}
"""
a = V(0.0, 0.0, -1.0)
# <a> is the unit vector pointing down the center axis of the default
# structure which is aligned along the Z axis.
bLine = pt2 - pt1
bLength = vlen(bLine)
if bLength == 0:
return
b = bLine / bLength
# <b> is the unit vector parallel to the line (i.e. pt1, pt2).
axis = cross(a, b)
# <axis> is the axis of rotation.
theta = angleBetween(a, b)
# <theta> is the angle (in degress) to rotate about <axis>.
scalar = bLength * 0.5
rawOffset = b * scalar
if theta == 0.0 or theta == 180.0:
axis = V(0, 1, 0)
# print "Now cross(a,b) =", axis
rot = (pi / 180.0) * theta # Convert to radians
qrot = Q(axis, rot) # Quat for rotation delta.
# Move and rotate the Peptide into final orientation.
chunk.move(-chunk.center)
chunk.rot(qrot)
# Bruce suggested I add this. It works here, but not if its
# before move() and rot() above. Mark 2008-04-11
chunk.full_inval_and_update()
return
def get_number_of_res(self, pos1, pos2, phi, psi):
"""
Calculate a number of residues necessary to fill
the pos1-pos2 vector.
@param pos1, pos2: vector points
@type pos1, pos2: V
@param phi, psi: peptide chain angles
@type phi, psi: float
"""
return 1 + int(vlen(pos2 - pos1) / get_unit_length(phi, psi))
def make_aligned(self,
assy,
name,
aa_idx,
phi, psi,
pos1, pos2,
secondary = SS_COIL,
fake_chain = False,
length = None):
"""
Build and return a chunk that is a homo-peptide aligned to
a pos2-pos1 vector.
@param aa_idx: amino acid type (index in AMINO_ACIDS list)
@type aa_idx: int
@param name: chunk name
@type name: string
@param phi, psi: peptide bond angles
@type phi, psi: float
@param pos1, pos2: desired peptide positions (beginning and end)
@type pos1, pos2: V
@param secondary: secondary structure class, used for visual representation
The actual peptide chain conformation is based on phi / psi angles.
@type secondary: int
@param fake_chain: if True, create only C-alpha atoms. used for drawing
peptide trace image during interactive peptide placement (used by
PeptideLine_GraphicsMode.py)
@type fake_chain: boolean
@param length: optional peptide length (number of amino acids), if
not specified, pos1 and pos2 are used to figure out the length
@type length: int
@return: A homo-polypeptide chain.
@rtype: L{Chunk}
"""
if not length:
self.length = self.get_number_of_res(pos1, pos2, phi, psi)
if self.length == 0:
return None
else:
self.length = length
# Create a molecule
mol = Chunk(assy, name)
if not fake_chain:
mol.protein = Protein()
mol.protein.set_chain_id('A')
# Generate dummy atoms positions
self.prev_coords[0][0] = pos1[0] - 1.0
self.prev_coords[0][1] = pos1[1] - 1.0
self.prev_coords[0][2] = pos1[2]
self.prev_coords[1][0] = pos1[0] - 1.0
self.prev_coords[1][1] = pos1[1]
self.prev_coords[1][2] = pos1[2]
self.prev_coords[2][0] = pos1[0]
self.prev_coords[2][1] = pos1[1]
self.prev_coords[2][2] = pos1[2]
name, short_name, symbol, zmatrix, size = AMINO_ACIDS[aa_idx]
# Add a N-terminal hydrogen
self.nterm_hydrogen = None
# Initially, the Peptide Builder was creating peptide structures
# saturated at both ends, i.e. with N-terminal hydrogen and C-terminal
# OH group present. Currently, this code is commented out to allow
# connecting multiple peptide structure be creating bonds between
# the C- and N- terminal ends of two individual structures.
"""
if not fake_chain:
atom = Atom("H", pos1, mol)
atom._is_aromatic = False
atom._is_single = False
self.nterm_hydrogen = atom
mol.protein.add_pdb_atom(atom, "H", 1, name)
atom.pdb_info = {}
atom.pdb_info['atom_name'] = "H"
atom.pdb_info['residue_name'] = short_name
atom.pdb_info['residue_id'] = " 1 "
atom.pdb_info['standard_atom'] = True
"""
self.init_ca = None
# Generate the peptide chain.
for idx in range(int(self.length)):
self._buildResidue(mol, zmatrix, size, idx+1, phi, psi, secondary, None, short_name, fake_chain=fake_chain)
# See the comment above.
"""
# Add a C-terminal OH group
self._buildResidue(mol, CTERM_ZMATRIX, 5, int(self.length), 0.0, 0.0, secondary, None, short_name, fake_chain=fake_chain)
"""
# Compute bonds (slow!)
# This should be replaced by a proper bond assignment.
if not fake_chain:
inferBonds(mol)
# Assign proper bond orders.
i = 1
for atom in mol.atoms.itervalues():
if atom.bonds:
for bond in atom.bonds:
if bond.atom1.getAtomTypeName()=="sp2" and \
bond.atom2.getAtomTypeName()=="sp2":
if (bond.atom1._is_aromatic and
bond.atom2._is_aromatic):
bond.set_v6(V_AROMATIC)
elif ((bond.atom1._is_aromatic == False and
bond.atom1._is_aromatic == False) and
not (bond.atom1._is_single and
bond.atom2._is_single)):
bond.set_v6(V_DOUBLE)
i += 1
# Remove temporary attributes.
for atom in mol.atoms.itervalues():
del atom._is_aromatic
del atom._is_single
# Axis of first selected chunk
ax = V(0.,0.,1.)
mol.rot(Q(mol.getaxis(),ax))
self._orient(mol, pos2, pos1)
if self.init_ca:
mol.move(pos1 - self.init_ca.posn())
mol_dummy = None
return mol
def _buildResidue(self, mol, zmatrix, n_atoms, idx, phi, psi, secondary, init_pos, residue_name, fake_chain=False):
"""
Builds cartesian coordinates for an amino acid from the internal
coordinates table.
@param mol: a chunk to which the amino acid will be added.
@type mol: Chunk
@param zmatrix: is an internal coordinates array corresponding to a
given amino acid.
@type zmatrix: list
@param n_atoms: size of z-matrix (a number of atoms to be build + 3
dummy atoms)
@type n_atoms: int
@param idx: is a residue index (1..length).
@type idx: integer
@param phi, psi: peptide bond phi and psi angles
@type phi, psi: float
@param init_pos: optional postions of previous CA, C and O atoms.
@type init_pos: V
@param symbol: current amino acid symbol (used to derermine proline case)
@type symbol: string
"""
# note: currently, it doesn't rebuild bonds, so inferBonds has to be
# called after this method. Unfortunately, the proper bond order can
# not be correctly recognized this way. Therefore, temporary atom flags
# _is_aromatic and _is_single are used.
#this code was re-factored by EricM and internal-to-cartesian
# conversion method was moved to geometry.InternalCoordinatesToCartesian
if mol is None:
return
if not init_pos: # assign three previous atom positions
coords = self.prev_coords
else:
# if no prev_coords are given, compute the first three atom positions
coords = zeros([3,3], Float)
num, name, atom_name, atom_type, \
atom_c, atom_b, atom_a, r, a, t = zmatrix[1]
coords[0][0] = 0.0;
coords[0][1] = 0.0;
coords[0][2] = 0.0;
coords[1][0] = r;
coords[1][1] = 0.0;
coords[1][2] = 0.0;
ccos = cos(DEG2RAD*a)
num, name, atom_name, atom_type, \
atom_c, atom_b, atom_a, r, a, t = zmatrix[2]
if atom_c == 1:
coords[2][0] = coords[0][0] + r*ccos
else:
coords[2][0] = coords[0][0] - r*ccos
coords[2][1] = r * sin(DEG2RAD*a)
coords[2][2] = 0.0
for i in range (0, 3):
self.prev_coords[i][0] = coords[i][0] + init_pos[0]
self.prev_coords[i][1] = coords[i][1] + init_pos[1]
self.prev_coords[i][2] = coords[i][2] + init_pos[2]
translator = InternalCoordinatesToCartesian(n_atoms, coords)
for n in range (3, n_atoms):
# Generate all coordinates using three previous atoms
# as a frame of reference,
num, name, atom_name, atom_type, \
atom_c, atom_b, atom_a, r, a, t = zmatrix[n]
# Apply the peptide bond conformation
if residue_name != "PRO":
if name == "N " and not init_pos:
t = self.prev_psi + 0.0
if name == "O ":
t = psi + 180.0
if name == "HA " or name == "HA2":
t = 120.0 + phi
if name == "CB " or name == "HA3":
t = 240.0 + phi
if name == "C ":
t = phi
else:
# proline
if name == "N " and not init_pos:
t = self.prev_psi + 0.0
if name == "O ":
t = psi + 180.0
if name == "CA ":
t = phi - 120.0
if name == "CD ":
t = phi + 60.0
translator.addInternal(n+1, atom_c+1, atom_b+1, atom_a+1, r, a, t)
xyz = translator.getCartesian(n+1)
if self.nterm_hydrogen:
# This is a hack for the first hydrogen atom
# to make sure the bond length is correct.
self.nterm_hydrogen.setposn(
self.nterm_hydrogen.posn() + \
0.325 * norm(xyz))
self.nterm_hydrogen = None
# Store previous coordinates for the next building step
if not init_pos:
if name=="N ":
self.prev_coords[0][0] = xyz[0]
self.prev_coords[0][1] = xyz[1]
self.prev_coords[0][2] = xyz[2]
if name=="CA ":
self.prev_coords[1][0] = xyz[0]
self.prev_coords[1][1] = xyz[1]
self.prev_coords[1][2] = xyz[2]
if name=="C ":
self.prev_coords[2][0] = xyz[0]
self.prev_coords[2][1] = xyz[1]
self.prev_coords[2][2] = xyz[2]
# Add a new atom to the molecule
if not fake_chain or \
name == "CA ":
atom = Atom(
atom_name,
xyz,
mol)
if not self.init_ca and \
name == "CA ":
self.init_ca = atom
if mol.protein:
aa = mol.protein.add_pdb_atom(atom,
name.replace(' ',''),
idx,
AA_3_TO_1[residue_name])
atom.pdb_info = {}
atom.pdb_info['atom_name'] = name.replace(' ','')
atom.pdb_info['residue_name'] = residue_name
residue_id = "%3d " % idx
atom.pdb_info['residue_id'] = residue_id
atom.pdb_info['standard_atom'] = True
atom.pdb_info['chain_id'] = True
if aa:
aa.set_secondary_structure(secondary)
# Create temporary attributes for proper bond assignment.
atom._is_aromatic = False
atom._is_single = False
if atom_type == "sp2a":
atom_type = "sp2"
atom._is_aromatic = True
if atom_type == "sp2s":
atom_type = "sp2"
atom._is_single = True
atom.set_atomtype_but_dont_revise_singlets(atom_type)
### debug - output in PDB format
### print "ATOM %5d %-3s %3s %c%4d %8.3f%8.3f%8.3f" % ( n, name, "ALA", ' ', res_num, xyz[0], xyz[1], xyz[2])
self.prev_psi = psi # Remember previous psi angle.
return
# end
| NanoCAD-master | cad/src/protein/commands/InsertPeptide/PeptideGenerator.py |
NanoCAD-master | cad/src/protein/commands/InsertPeptide/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
BuildProtein_Command.py
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
from command_support.EditCommand import EditCommand
from utilities.Log import greenmsg
from ne1_ui.toolbars.Ui_ProteinFlyout import ProteinFlyout
from protein.commands.BuildProtein.BuildProtein_PropertyManager import BuildProtein_PropertyManager
from protein.commands.BuildProtein.BuildProtein_GraphicsMode import BuildProtein_GraphicsMode
_superclass = EditCommand
class BuildProtein_Command(EditCommand):
"""
ModelAndSimulateProtein_EditCommand provides a convenient way to edit or create
or simulate a Protein object
"""
# class constants
GraphicsMode_class = BuildProtein_GraphicsMode
PM_class = BuildProtein_PropertyManager
#Flyout Toolbar
FlyoutToolbar_class = ProteinFlyout
cmd = greenmsg("Build Protein: ")
prefix = 'ProteinGroup' # used for gensym
cmdname = "Build Protein"
commandName = 'BUILD_PROTEIN'
featurename = "Build Protein"
from utilities.constants import CL_ENVIRONMENT_PROVIDING
command_level = CL_ENVIRONMENT_PROVIDING
command_should_resume_prevMode = False
command_has_its_own_PM = True
create_name_from_prefix = True
call_makeMenus_for_each_event = True
flyoutToolbar = None
_currentActiveTool = 'MODEL_PROTEIN'
def command_enter_misc_actions(self):
"""
Overrides superclass method.
@see: baseCommand.command_enter_misc_actions() for documentation
"""
self.w.buildProteinAction.setChecked(True)
return
def command_exit_misc_actions(self): #@@@
"""
Overrides superclass method.
@see: baseCommand.command_exit_misc_actions() for documentation
"""
#self.w.buildProteinAction.setChecked(False)
return
def getCurrentActiveTool(self):
return self._currentActiveTool
def setCurrentCommandMode(self, commandName):
"""
Sets the current active command: modeling or simulation
"""
self._currentActiveTool = commandName
return
def enterModelOrSimulateCommand(self, commandName = ''):
"""
Enter the given tools subcommand (e.g. Model or Simulate Protein command)
"""
if not commandName:
return
commandSequencer = self.win.commandSequencer
commandSequencer.userEnterCommand( commandName)
return
def makeMenus(self):
"""
Create context menu for this command.
"""
#Urmi 20080806: will implement later, once the basic system is up and
#working
return
def keep_empty_group(self, group): #@@@
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
if not bool_keep:
if group is self.struct:
bool_keep = True
return bool_keep
| NanoCAD-master | cad/src/protein/commands/BuildProtein/BuildProtein_Command.py |
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details.
"""
BuildProtein_PropertyManager.py
@author: Urmi, Mark
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
Mark 20081212: Heavily rewritten, modeled after BuildDna_PropertyManager.py.
To do list:
- Add "Edit Properties" menu item to GA context menu when highlighting Peptide.
- Bug: Cannot edit a peptide loaded from an MMP file.
- Read FASTA file via sequence editor (or another way).
- Debug_pref for debug print statements.
- Bug: Returning from Compare command unselects the two selected protein chunks.
The PM list widget shows them as selected and the compare button is enabled,
but they are not selected in the graphics area.
"""
import foundation.env as env
from PyQt4.Qt import SIGNAL
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_SpinBox import PM_SpinBox
from PM.PM_PushButton import PM_PushButton
from PM.PM_SelectionListWidget import PM_SelectionListWidget
from command_support.EditCommand_PM import EditCommand_PM
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_Constants import PM_CANCEL_BUTTON
from utilities.Comparison import same_vals
from protein.model.Protein import getAllProteinChunksInPart
_superclass = EditCommand_PM
class BuildProtein_PropertyManager(EditCommand_PM):
"""
The BuildProtein_PropertyManager class provides a Property Manager
for the B{Build Protein} command.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Build Protein"
pmName = title
iconPath = "ui/actions/Command Toolbar/BuildProtein/BuildProtein.png"
current_protein = "" # name of the single selected peptide. To be deprecated soon. --Mark 2008-12-14
def __init__( self, command):
"""
Constructor for the Build Protein property manager.
"""
#Attributes for self._update_UI_do_updates() to keep track of changes
#in these , since the last call of that method. These are used to
#determine whether certain UI updates are needed.
self._previousSelectionParams = None
self._previousStructureParams = None
self._previousCommandStackParams = None
#see self.connect_or_disconnect_signals for comment about this flag
self.isAlreadyConnected = False
self.isAlreadyDisconnected = False
EditCommand_PM.__init__( self, command)
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_CANCEL_BUTTON | \
PM_WHATS_THIS_BUTTON)
return
def connect_or_disconnect_signals(self, isConnect):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
"""
if isConnect and self.isAlreadyConnected:
return
if not isConnect and self.isAlreadyDisconnected:
return
self.isAlreadyConnected = isConnect
self.isAlreadyDisconnected = not isConnect
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
self.proteinListWidget.connect_or_disconnect_signals(isConnect)
change_connect(self.editPeptidePropertiesButton,
SIGNAL("clicked()"),
self._editPeptide)
change_connect(self.compareProteinsButton,
SIGNAL("clicked()"),
self._compareProteins)
return
def enable_or_disable_gui_actions(self, bool_enable = False):
"""
Enable or disable some gui actions when this property manager is
opened or closed, depending on the bool_enable.
"""
#For new command API, we will always show the exit button to check
#if Exit button really exits the subcommand and the parent command
#(earlier there were bugs) . Regaring 'whether this should be the
#default behavior', its a UI design issue and we will worry about it
#later -- Ninad 2008-08-27 (based on an email exchanged with Bruce)
pass
def _update_UI_do_updates(self):
"""
Overrides superclass method.
@see: Command_PropertyManager._update_UI_do_updates()
"""
newSelectionParams = self._currentSelectionParams()
current_struct_params = self._currentStructureParams()
selection_params_unchanged = same_vals(newSelectionParams,
self._previousSelectionParams)
#introducing self._previousStructureParams and
#adding structure_params_unchanged check to the 'if' condition below
#fixes bug 2910.
structure_params_unchanged = same_vals(self._previousStructureParams,
current_struct_params)
current_command_stack_params = self._currentCommandStackParams()
#Check if command stack params changed since last call of this
#PM update method. This is used to fix bugs like 2940
command_stack_params_unchanged = same_vals(
self._previousCommandStackParams, current_command_stack_params)
#No need to proceed if any of the selection/ structure and commandstack
#parameters remained unchanged since last call. --- [CONDITION A]
if selection_params_unchanged and structure_params_unchanged and command_stack_params_unchanged:
#This second condition above fixes bug 2888
if 0:
print "Build Protein: _update_UI_do_updates() - DO NOTHING"
return
self._previousStructureParams = current_struct_params
self._previousSelectionParams = newSelectionParams
self._previousCommandStackParams = current_command_stack_params
##if not selection_params_unchanged or not command_stack_params_unchanged and structure_params_unchanged:
if structure_params_unchanged:
#NOTE: We checked if either of the selection struct or command stack
#parameters or both changed. (this was referred as '[CONDITION A]'
#above). So, this condition (structure_params_unchanged)also means
#either selection or command stack or both parameters were changed.
if not command_stack_params_unchanged:
#update the protein list widget *before* updating the selection if
#the command stack changed. This ensures that the selection box
#appears around the list widget items that are selected.
self.updateProteinListWidget()
selectedProteins = newSelectionParams
self.proteinListWidget.updateSelection(selectedProteins)
# Enable/disable "Edit Sequence" button.
if len(selectedProteins) == 1:
self.editPeptidePropertiesButton.setEnabled(True)
else:
self.editPeptidePropertiesButton.setEnabled(False)
# Enable/disable "Compare Proteins" button.
if len(selectedProteins) == 2:
self.compareProteinsButton.setEnabled(True)
else:
self.compareProteinsButton.setEnabled(False)
return
self.updateProteinListWidget()
return
def _currentCommandStackParams(self):
"""
The return value is supposed to be used by BUILD_PROTEIN command PM ONLY
and NOT by any subclasses.
Returns a tuple containing current command stack change indicator and
the name of the command 'BUILD_PROTEIN'. These
parameters are then used to decide whether updating widgets
in this property manager is needed, when self._update_UI_do_updates()
is called.
@NOTE:
- Command_PropertyManager.update_UI() already does a check to see if
any of the global change indicators in assembly (command_stack_change,
model_change, selection_change) changed since last call and then only
calls self._update_UI_do_updates().
- But this method is just used to keep track of the
local command stack change counter in order to update the list
widgets.
- This is used to fix bug 2940
@see: self._update_UI_do_updates()
"""
commandStackCounter = self.command.assy.command_stack_change_indicator()
#Append 'BUILD_PROTEIN to the tuple to be returned. This is just to remind
#us that this method is meant for BUILD_PROTEIN command PM only. (and not
#by any subclasses) Should we assert this? I think it will slow things
#down so this comment is enough -- Ninad 2008-09-30
return (commandStackCounter, 'BUILD_PROTEIN')
def _currentSelectionParams(self):
"""
Returns a tuple containing current selection parameters. These
parameters are then used to decide whether updating widgets
in this property manager is needed when L{self.model_changed}
method is called.
@return: A tuple that contains total number of selected peptides.
@rtype: tuple
@NOTE: This method may be renamed in future.
It's possible that there are other groupboxes in the PM that need to be
updated when something changes in the glpane.
"""
selectedProteins = []
if self.command is not None: # and self.command.hasValidStructure():
selectedProteins = self.win.assy.getSelectedProteinChunks()
return (selectedProteins)
def _currentStructureParams(self):
"""
Return current structure parameters of interest to self.model_changed.
Right now it only returns the number of peptides within the structure
(or None). This is a good enough check (and no need to compare
each and every peptide within the structure with a previously stored
set of strands).
"""
#Can it happen that the total number of peptides remains the same even
#after some alterations to the peptides? Unlikely. (Example: a single
#(future) Break peptide operation will increase the number of peptides
#by one. Or Join peptides decrease it by 1)
params = None
if self.command: # and self.command.hasValidStructure():
proteinList = []
proteinList = getAllProteinChunksInPart(self.win.assy)
params = len(proteinList)
return params
def close(self):
"""
Closes the Property Manager. Overrides EditCommand_PM.close()
"""
#Clear tags, if any, due to the selection in the self.strandListWidget.
#self.proteinListWidget.clear()
env.history.statusbar_msg("")
EditCommand_PM.close(self)
return
def show(self):
"""
Show the PM. Extends superclass method.
@note: _update_UI_do_updates() gets called immediately after this and
updates PM widgets with their correct values/settings.
"""
env.history.statusbar_msg("")
EditCommand_PM.show(self)
# NOTE: Think about moving this msg to _update_UI_do_updates() where
# custom msgs can be created based on the current selection, etc.
# Mark 2008-12-14
msg = "Select <b>Insert Peptide</b> to create a peptide chain or "\
"select another modeling tool to modify an existing protein."
self.updateMessage(msg)
return
def _editPeptide(self):
"""
Slot for the "Edit Properties" button.
"""
#if not self.command.hasValidStructure():
# return
proteinChunk = self.win.assy.getSelectedProteinChunk()
if proteinChunk:
proteinChunk.protein.edit(self.win)
return
def _compareProteins(self):
"""
Slot for the "Compare Proteins" button.
"""
self.win.commandSequencer.userEnterCommand('COMPARE_PROTEINS')
return
def _addWhatsThisText( self ):
"""
What's This text for widgets in the DNA Property Manager.
"""
pass
def _addToolTipText(self):
"""
Tool Tip text for widgets in the DNA Property Manager.
"""
pass
def _addGroupBoxes(self):
"""
Add the Build Protein Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox(self, title = "Peptides")
self._loadGroupBox1(self._pmGroupBox1)
return
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in groupbox1.
"""
self.proteinListWidget = PM_SelectionListWidget(pmGroupBox,
self.win,
label = "",
heightByRows = 6 )
self.proteinListWidget.setObjectName('Peptide_list_widget')
self.proteinListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE')
self.editPeptidePropertiesButton = PM_PushButton(pmGroupBox,
label = "",
text = "Edit Properties..." )
self.editPeptidePropertiesButton.setEnabled(False)
self.compareProteinsButton = PM_PushButton(pmGroupBox,
label = "",
text = "Compare Proteins..." )
self.compareProteinsButton.setEnabled(False)
return
def updateProteinListWidget(self):
"""
Update the peptide list widget. It shows all peptides in the part.
"""
proteinChunkList = getAllProteinChunksInPart(self.win.assy)
if proteinChunkList:
self.proteinListWidget.insertItems(
row = 0,
items = proteinChunkList)
else:
self.proteinListWidget.clear()
return
| NanoCAD-master | cad/src/protein/commands/BuildProtein/BuildProtein_PropertyManager.py |
NanoCAD-master | cad/src/protein/commands/BuildProtein/__init__.py |
|
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details.
"""
BuildProtein_GraphicsMode.py
@author: Mark
@version: $Id$
@copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details.
"""
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from commands.Select.Select_GraphicsMode import DRAG_STICKINESS_LIMIT
DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND = True
_superclass = SelectChunks_GraphicsMode
class BuildProtein_GraphicsMode(SelectChunks_GraphicsMode):
"""
Graphics mode for Build Protein command.
"""
def Enter_GraphicsMode(self):
_superclass.Enter_GraphicsMode(self)
return
def chunkLeftUp(self, aChunk, event):
"""
Upon chunkLeftUp, it enters the protein edit command
This is an alternative implementation. As of 2008-03-03,
we have decided to change this implementation. Keeping the
related methods alive if, in future, we want to switch to this
implementation and/or add a user preference to do this.
"""
_superclass.chunkLeftUp(self, aChunk, event)
if self.glpane.modkeys is not None:
#Don't go further if some modkey is pressed. We will call the
#edit method of the protein only if no modifier key is
#pressed
return
if not self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT):
return
#@TODO: If the object under mouse was double clicked, don't enter the
#edit mode, instead do appropriate operation such as expand selection or
#contract selection (done in superclass)
#Note: when the object is just single clicked, it becomes editable).
if self.editObjectOnSingleClick():
if aChunk.picked:
if aChunk.isProteinChunk():
aChunk.protein.edit(self.win)
return
def editObjectOnSingleClick(self):
"""
Subclasses can override this method. If this method returns True,
when you left click on a DnaSegment or a DnaStrand, it becomes editable
(i.e. program enters the edit command of that particular object if
that object is editable)
@see: MakeCrossover_GraphicsMode.editObjectOnSingleClick()
"""
if DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND:
return True
pass
| NanoCAD-master | cad/src/protein/commands/BuildProtein/BuildProtein_GraphicsMode.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@version:$Id$
"""
from utilities.debug import print_compact_stack, print_compact_traceback
from protein.commands.BuildProtein.BuildProtein_Command import BuildProtein_Command
_superclass = BuildProtein_Command
class ModelProtein_Command(BuildProtein_Command):
"""
Class for modeling proteins
"""
FlyoutToolbar_class = None
featurename = 'Model and Simulate Protein Mode/Model Protein'
commandName = 'MODEL_PROTEIN'
command_should_resume_prevMode = True
#Urmi 20080806: We may want it to have its own PM
command_has_its_own_PM = False
_currentActiveTool = 'MODEL_PROTEIN'
from utilities.constants import CL_SUBCOMMAND
#class constants for the NEW COMMAND API -- 2008-07-30
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
def command_entered(self):
"""
Extends superclass method.
@see: baseCommand.command_entered() for documentation
"""
_superclass.command_entered(self)
msg = "Select <b>Insert Peptide</b> to create a peptide chain or "\
"select another modeling tool to modify an existing "\
"peptide/protein sequence."
self.propMgr.updateMessage(msg)
| NanoCAD-master | cad/src/protein/commands/BuildProtein/ModelProtein_Command.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
@version:$Id$
"""
from utilities.debug import print_compact_stack, print_compact_traceback
from protein.commands.BuildProtein.BuildProtein_Command import BuildProtein_Command
_superclass = BuildProtein_Command
class SimulateProtein_Command(BuildProtein_Command):
"""
Class for simulating proteins
"""
FlyoutToolbar_class = None
featurename = 'Model and Simulate Protein Mode/Simulate Protein'
commandName = 'SIMULATE_PROTEIN'
command_should_resume_prevMode = True
#Urmi 20080806: We may want it to have its own PM
command_has_its_own_PM = False
currentActiveTool = 'SIMULATE_PROTEIN'
#class constants for the NEW COMMAND API -- 2008-07-30
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
def command_entered(self):
"""
Extends superclass method.
@see: baseCommand.command_entered() for documentation
"""
_superclass.command_entered(self)
msg = "Select a Rosetta simulation tool to either design or score "\
"a peptide/protein sequence."
self.propMgr.updateMessage(msg) | NanoCAD-master | cad/src/protein/commands/BuildProtein/SimulateProtein_Command.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.changes as changes
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from command_support.EditCommand import EditCommand
from utilities.constants import red
from protein.commands.FixedBBProteinSim.FixedBBProteinSim_PropertyManager import FixedBBProteinSim_PropertyManager
# == GraphicsMode part
_superclass_for_GM = SelectChunks_GraphicsMode
class FixedBBProteinSim_GraphicsMode(SelectChunks_GraphicsMode ):
"""
Graphics mode for Fixed Backbone Protein Sequence Design command.
"""
pass
# == Command part
class FixedBBProteinSim_Command(EditCommand):
"""
Class for fixed backbone rosetta sequence design
"""
# class constants
GraphicsMode_class = FixedBBProteinSim_GraphicsMode
PM_class = FixedBBProteinSim_PropertyManager
commandName = 'FIXED_BACKBONE_PROTEIN_SEQUENCE_DESIGN'
featurename = "Fixed Backbone Sequence Design"
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
command_should_resume_prevMode = True
command_has_its_own_PM = True
flyoutToolbar = None
def _getFlyoutToolBarActionAndParentCommand(self):
"""
See superclass for documentation.
@see: self.command_update_flyout()
"""
flyoutActionToCheck = 'rosetta_fixedbb_design_Action'
parentCommandName = 'BUILD_PROTEIN'
return flyoutActionToCheck, parentCommandName
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
return bool_keep
| NanoCAD-master | cad/src/protein/commands/FixedBBProteinSim/FixedBBProteinSim_Command.py |
NanoCAD-master | cad/src/protein/commands/FixedBBProteinSim/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
FixedBBProteinSim_PropertyManager.py
The FixedBBProteinSim_PropertyManager class provides a Property Manager
for the B{Fixed Backbone protein sequence design} command on the flyout toolbar in the
Build > Protein mode.
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import string
import foundation.env as env
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import Qt
from PyQt4 import QtGui
from PyQt4.Qt import QString
from PM.PM_PushButton import PM_PushButton
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_TextEdit import PM_TextEdit
from PM.PM_CheckBox import PM_CheckBox
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_SpinBox import PM_SpinBox
from command_support.Command_PropertyManager import Command_PropertyManager
_superclass = Command_PropertyManager
class FixedBBProteinSim_PropertyManager(Command_PropertyManager):
"""
The FixedBBProteinSim_PropertyManager class provides a Property Manager
for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the
Build > Protein > Simulate mode.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Fixed Backbone Design"
pmName = title
iconPath = "ui/actions/Command Toolbar/BuildProtein/FixedBackbone.png"
def __init__( self, command ):
"""
Constructor for the property manager.
"""
_superclass.__init__(self, command)
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_WHATS_THIS_BUTTON)
msg = "Choose from the various options below to design "\
"an optimized <b>fixed backbone protein sequence</b> with Rosetta."
self.updateMessage(msg)
return
def connect_or_disconnect_signals(self, isConnect = True):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
"""
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"), self.update_ex1)
change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"), self.update_ex1aro)
change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"), self.update_ex2)
change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"), self.update_ex2aro_only)
change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"), self.update_ex3)
change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"), self.update_ex4)
change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"), self.update_rot_opt)
change_connect(self.tryBothHisTautomersCheckbox, SIGNAL("stateChanged(int)"), self.update_try_both_his_tautomers)
change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"), self.update_soft_rep_design)
change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"), self.update_use_elec_rep)
change_connect(self.norepackDisulfCheckbox, SIGNAL("stateChanged(int)"), self.update_norepack_disulf)
#signal slot connections for the push buttons
change_connect(self.okButton, SIGNAL("clicked()"), self.runRosettaFixedBBSim)
return
#Protein Display methods
def show(self):
"""
Shows the Property Manager.
"""
#@REVIEW: Why does it create sequence editor here? Also, is it
#required to be done before the superclass.show call? Similar code
#found in CompareProteins_PM and some other files --Ninad 2008-10-02
self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
self.sequenceEditor.hide()
_superclass.show(self)
return
def _addGroupBoxes( self ):
"""
Add the Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox( self,
title = "Rosetta Fixed backbone sequence design")
self._loadGroupBox1( self._pmGroupBox1 )
return
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box.
"""
self.numSimSpinBox = PM_SpinBox( pmGroupBox,
labelColumn = 0,
label = "Number of simulations:",
minimum = 1,
maximum = 999,
setAsDefault = False,
spanWidth = False)
self.ex1Checkbox = PM_CheckBox(pmGroupBox,
text = "Expand rotamer library for chi1 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex1aroCheckbox = PM_CheckBox(pmGroupBox,
text = "Use large chi1 library for aromatic residues",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex2Checkbox = PM_CheckBox(pmGroupBox,
text = "Expand rotamer library for chi2 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex2aroOnlyCheckbox = PM_CheckBox(pmGroupBox,
text = "Use large chi2 library only for aromatic residues",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex3Checkbox = PM_CheckBox(pmGroupBox,
text = "Expand rotamer library for chi3 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex4Checkbox = PM_CheckBox(pmGroupBox,
text ="Expand rotamer library for chi4 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
text ="Optimize one-body energy",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.tryBothHisTautomersCheckbox = PM_CheckBox(pmGroupBox,
text ="Try both histidine tautomers",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.softRepDesignCheckbox = PM_CheckBox(pmGroupBox,
text ="Use softer Lennard-Jones repulsive term",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.useElecRepCheckbox = PM_CheckBox(pmGroupBox,
text ="Use electrostatic repulsion",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.norepackDisulfCheckbox = PM_CheckBox(pmGroupBox,
text ="Don't re-pack disulphide bonds",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.otherCommandLineOptions = PM_TextEdit(pmGroupBox,
label = "Command line options:",
spanWidth = True)
self.otherCommandLineOptions.setFixedHeight(80)
self.okButton = PM_PushButton( pmGroupBox,
text = "Launch Rosetta",
setAsDefault = True,
spanWidth = True)
return
def _addWhatsThisText( self ):
"""
What's This text for widgets in this Property Manager.
"""
pass
def _addToolTipText(self):
"""
Tool Tip text for widgets in this Property Manager.
"""
pass
def update_ex1(self, state):
"""
Update the command text edit depending on the state of the update_ex1
checkbox
@param state:state of the update_ex1 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex1Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex1 '
else:
otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex1aro(self, state):
"""
Update the command text edit depending on the state of the update_ex1aro
checkbox
@param state:state of the update_ex1aro checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex1aroCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex1aro '
else:
otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex2(self, state):
"""
Update the command text edit depending on the state of the update_ex2
checkbox
@param state:state of the update_ex2 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex2Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex2 '
else:
otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex2aro_only(self, state):
"""
Update the command text edit depending on the state of the update_ex2aro_only
checkbox
@param state:state of the update_ex2aro_only checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex2aroOnlyCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex2aro_only '
else:
otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex3(self, state):
"""
Update the command text edit depending on the state of the update_ex3
checkbox
@param state:state of the update_ex3 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex3Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex3 '
else:
otherOptionsText = otherOptionsText.replace(' -ex3 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex4(self, state):
"""
Update the command text edit depending on the state of the update_ex4
checkbox
@param state:state of the update_ex4 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex4Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex4 '
else:
otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_rot_opt(self, state):
"""
Update the command text edit depending on the state of the update_rot_opt
checkbox
@param state:state of the update_rot_opt checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.rotOptCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -rot_opt '
else:
otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_try_both_his_tautomers(self, state):
"""
Update the command text edit depending on the state of the update_try_both_his_tautomers
checkbox
@param state:state of the update_try_both_his_tautomers checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.tryBothHisTautomersCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
else:
otherOptionsText = otherOptionsText.replace(' -try_both_his_tautomers ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_soft_rep_design(self, state):
"""
Update the command text edit depending on the state of the update_soft_rep_design
checkbox
@param state:state of the update_soft_rep_design checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.softRepDesignCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -soft_rep_design '
else:
otherOptionsText = otherOptionsText.replace(' -soft_rep_design ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_use_elec_rep(self, state):
"""
Update the command text edit depending on the state of the update_use_elec_rep
checkbox
@param state:state of the update_use_elec_rep checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.useElecRepCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
else:
otherOptionsText = otherOptionsText.replace(' -use_electrostatic_repulsion ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_norepack_disulf(self, state):
"""
Update the command text edit depending on the state of the update_no_repack
checkbox
@param state:state of the update_no_repack checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.norepackDisulfCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -norepack_disulf '
else:
otherOptionsText = otherOptionsText.replace(' -norepack_disulf ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def runRosettaFixedBBSim(self):
"""
Get all the parameters from the PM and run a rosetta simulation.
"""
proteinChunk = self.win.assy.getSelectedProteinChunk()
if not proteinChunk:
msg = "You must select a single protein to run a Rosetta <i>Fixed Backbone</i> simulation."
self.updateMessage(msg)
return
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
numSim = self.numSimSpinBox.value()
argList = [numSim, otherOptionsText, proteinChunk.name]
from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
if argList[0] > 0:
cmdrun = rosettaSetup_CommandRun(self.win, argList, "ROSETTA_FIXED_BACKBONE_SEQUENCE_DESIGN")
cmdrun.run()
return | NanoCAD-master | cad/src/protein/commands/FixedBBProteinSim/FixedBBProteinSim_PropertyManager.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
BackrubProteinSim_PropertyManager.py
The BackrubProteinSim_PropertyManager class provides a Property Manager
for the B{Backrub protein sequence design} command on the flyout toolbar in the
Build > Protein > Simulate mode.
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.env as env
from utilities.Log import redmsg
from command_support.Command_PropertyManager import Command_PropertyManager
from utilities.prefs_constants import rosetta_backrub_enabled_prefs_key
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import Qt
from PM.PM_PushButton import PM_PushButton
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_TextEdit import PM_TextEdit
from PM.PM_CheckBox import PM_CheckBox
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_SpinBox import PM_SpinBox
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_ComboBox import PM_ComboBox
_superclass = Command_PropertyManager
class BackrubProteinSim_PropertyManager(Command_PropertyManager):
"""
The BackrubProteinSim_PropertyManager class provides a Property Manager
for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the
Build > Protein > Simulate mode.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Backrub Motion"
pmName = title
iconPath = "ui/actions/Command Toolbar/BuildProtein/Backrub.png"
def __init__( self, command ):
"""
Constructor for the property manager.
"""
_superclass.__init__(self, command)
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_WHATS_THIS_BUTTON)
msg = "Choose various parameters from below to design an optimized" \
" protein sequence with Rosetta with backrub motion allowed."
self.updateMessage(msg)
def connect_or_disconnect_signals(self, isConnect = True):
"""
Connect or disconnect widget signals sent to their slot methods.
This can be overridden in subclasses. By default it does nothing.
@param isConnect: If True the widget will send the signals to the slot
method.
@type isConnect: boolean
"""
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"), self.update_ex1)
change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"), self.update_ex1aro)
change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"), self.update_ex2)
change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"), self.update_ex2aro_only)
change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"), self.update_ex3)
change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"), self.update_ex4)
change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"), self.update_rot_opt)
change_connect(self.tryBothHisTautomersCheckbox, SIGNAL("stateChanged(int)"), self.update_try_both_his_tautomers)
change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"), self.update_soft_rep_design)
change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"), self.update_use_elec_rep)
change_connect(self.norepackDisulfCheckbox, SIGNAL("stateChanged(int)"), self.update_norepack_disulf)
#signal slot connections for the push buttons
change_connect(self.okButton, SIGNAL("clicked()"), self.runRosettaBackrubSim)
return
#Protein Display methods
def show(self):
"""
Shows the Property Manager. Exends superclass method.
"""
self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
self.sequenceEditor.hide()
#update the min and max residues spinbox max values based on the length
#of the current protein
numResidues = self._getNumResiduesForCurrentProtein()
if numResidues == 0:
self.minresSpinBox.setMaximum(numResidues + 2)
self.maxresSpinBox.setMaximum(numResidues + 2)
else:
self.minresSpinBox.setMaximum(numResidues)
self.maxresSpinBox.setMaximum(numResidues)
_superclass.show(self)
return
def _addGroupBoxes( self ):
"""
Add the Property Manager group boxes.
"""
self._pmGroupBox2 = PM_GroupBox( self,
title = "Backrub Specific Parameters")
self._loadGroupBox2( self._pmGroupBox2 )
self._pmGroupBox1 = PM_GroupBox( self,
title = "Rosetta Sequence Design Parameters")
self._loadGroupBox1( self._pmGroupBox1 )
return
def _loadGroupBox2(self, pmGroupBox):
"""
Load widgets in group box.
"""
self.bondAngleWeightSimSpinBox = PM_DoubleSpinBox( pmGroupBox,
labelColumn = 0,
label = "Bond angle weight:",
minimum = 0.01,
decimals = 2,
maximum = 1.0,
singleStep = 0.01,
value = 1.0,
setAsDefault = False,
spanWidth = False)
bond_angle_param_list = ['Amber', 'Charmm']
self.bondAngleParamComboBox = PM_ComboBox( pmGroupBox,
label = "Bond angle parameters:",
choices = bond_angle_param_list,
setAsDefault = False)
self.onlybbSpinBox = PM_DoubleSpinBox( pmGroupBox,
labelColumn = 0,
label = "Only backbone rotation:",
minimum = 0.01,
maximum = 1.0,
value = 0.75,
decimals = 2,
singleStep = 0.01,
setAsDefault = False,
spanWidth = False)
self.onlyrotSpinBox = PM_DoubleSpinBox( pmGroupBox,
labelColumn = 0,
label = "Only rotamer rotation:",
minimum = 0.01,
maximum = 1.0,
decimals = 2,
value = 0.25,
singleStep = 0.01,
setAsDefault = False,
spanWidth = False)
self.mctempSpinBox = PM_DoubleSpinBox( pmGroupBox,
labelColumn = 0,
label = "MC simulation temperature:",
minimum = 0.1,
value = 0.6,
maximum = 1.0,
decimals = 2,
singleStep = 0.1,
setAsDefault = False,
spanWidth = False)
numResidues = self._getNumResiduesForCurrentProtein()
self.minresSpinBox = PM_SpinBox( pmGroupBox,
labelColumn = 0,
label = "Minimum number of residues:",
minimum = 2,
maximum = numResidues,
singleStep = 1,
setAsDefault = False,
spanWidth = False)
self.maxresSpinBox = PM_SpinBox( pmGroupBox,
labelColumn = 0,
label = "Maximum number of residues:",
minimum = 2,
maximum = numResidues,
singleStep = 1,
setAsDefault = False,
spanWidth = False)
if numResidues == 0:
self.minresSpinBox.setMaximum(numResidues + 2)
self.maxresSpinBox.setMaximum(numResidues + 2)
return
def _addWhatsThisText( self ):
"""
What's This text for widgets in this Property Manager.
"""
pass
def _addToolTipText(self):
"""
Tool Tip text for widgets in this Property Manager.
"""
pass
def _getNumResiduesForCurrentProtein(self):
"""
Get number of residues for the current protein
"""
_current_protein = self.win.assy.getSelectedProteinChunk()
if _current_protein:
return len(_current_protein.protein.get_sequence_string())
return 0
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box.
"""
self.numSimSpinBox = PM_SpinBox( pmGroupBox,
labelColumn = 0,
label = "Number of trials:",
minimum = 1000,
maximum = 1000000,
singleStep = 1000,
setAsDefault = False,
spanWidth = False)
self.ex1Checkbox = PM_CheckBox(pmGroupBox,
text = "Expand rotamer library for chi1 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex1aroCheckbox = PM_CheckBox(pmGroupBox,
text = "Use large chi1 library for aromatic residues",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex2Checkbox = PM_CheckBox(pmGroupBox,
text = "Expand rotamer library for chi2 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex2aroOnlyCheckbox = PM_CheckBox(pmGroupBox,
text = "Use large chi2 library only for aromatic residues",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex3Checkbox = PM_CheckBox(pmGroupBox,
text = "Expand rotamer library for chi3 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.ex4Checkbox = PM_CheckBox(pmGroupBox,
text ="Expand rotamer library for chi4 angle",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
text ="Optimize one-body energy",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.tryBothHisTautomersCheckbox = PM_CheckBox(pmGroupBox,
text ="Try both histidine tautomers",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.softRepDesignCheckbox = PM_CheckBox(pmGroupBox,
text ="Use softer Lennard-Jones repulsive term",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.useElecRepCheckbox = PM_CheckBox(pmGroupBox,
text ="Use electrostatic repulsion",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.norepackDisulfCheckbox = PM_CheckBox(pmGroupBox,
text ="Don't re-pack disulphide bonds",
state = Qt.Unchecked,
setAsDefault = False,
widgetColumn = 0,
spanWidth = True)
self.otherCommandLineOptions = PM_TextEdit(pmGroupBox,
label = "Command line options:",
spanWidth = True)
self.otherCommandLineOptions.setFixedHeight(80)
self.okButton = PM_PushButton( pmGroupBox,
text = "Run Rosetta",
setAsDefault = True,
spanWidth = True)
return
def update_ex1(self, state):
"""
Update the command text edit depending on the state of the update_ex1
checkbox
@param state:state of the update_ex1 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex1Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex1 '
else:
otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex1aro(self, state):
"""
Update the command text edit depending on the state of the update_ex1aro
checkbox
@param state:state of the update_ex1aro checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex1aroCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex1aro '
else:
otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex2(self, state):
"""
Update the command text edit depending on the state of the update_ex2
checkbox
@param state:state of the update_ex2 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex2Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex2 '
else:
otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex2aro_only(self, state):
"""
Update the command text edit depending on the state of the update_ex2aro_only
checkbox
@param state:state of the update_ex2aro_only checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex2aroOnlyCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex2aro_only '
else:
otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex3(self, state):
"""
Update the command text edit depending on the state of the update_ex3
checkbox
@param state:state of the update_ex3 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex3Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex3 '
else:
otherOptionsText = otherOptionsText.replace(' -ex3 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_ex4(self, state):
"""
Update the command text edit depending on the state of the update_ex4
checkbox
@param state:state of the update_ex4 checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.ex4Checkbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -ex4 '
else:
otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_rot_opt(self, state):
"""
Update the command text edit depending on the state of the update_rot_opt
checkbox
@param state:state of the update_rot_opt checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.rotOptCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -rot_opt '
else:
otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_try_both_his_tautomers(self, state):
"""
Update the command text edit depending on the state of the update_try_both_his_tautomers
checkbox
@param state:state of the update_try_both_his_tautomers checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.tryBothHisTautomersCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
else:
otherOptionsText = otherOptionsText.replace(' -try_both_his_tautomers ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_soft_rep_design(self, state):
"""
Update the command text edit depending on the state of the update_soft_rep_design
checkbox
@param state:state of the update_soft_rep_design checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.softRepDesignCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -soft_rep_design '
else:
otherOptionsText = otherOptionsText.replace(' -soft_rep_design ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_use_elec_rep(self, state):
"""
Update the command text edit depending on the state of the update_use_elec_rep
checkbox
@param state:state of the update_use_elec_rep checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.useElecRepCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
else:
otherOptionsText = otherOptionsText.replace(' -use_electrostatic_repulsion ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def update_norepack_disulf(self, state):
"""
Update the command text edit depending on the state of the update_no_repack
checkbox
@param state:state of the update_no_repack checkbox
@type state: int
"""
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
if self.norepackDisulfCheckbox.isChecked() == True:
otherOptionsText = otherOptionsText + ' -norepack_disulf '
else:
otherOptionsText = otherOptionsText.replace(' -norepack_disulf ', '')
self.otherCommandLineOptions.setText(otherOptionsText)
return
def runRosettaBackrubSim(self):
"""
Get all the parameters from the PM and run a rosetta simulation
"""
proteinChunk = self.win.assy.getSelectedProteinChunk()
if not proteinChunk:
msg = "You must select a single protein to run a Rosetta <i>Backrub</i> simulation."
self.updateMessage(msg)
return
otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
numSim = self.numSimSpinBox.value()
argList = [numSim, otherOptionsText, proteinChunk.name]
backrubSpecificArgList = self.getBackrubSpecificArgumentList()
from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
if argList[0] > 0:
env.prefs[rosetta_backrub_enabled_prefs_key] = True
cmdrun = rosettaSetup_CommandRun(self.win, argList, "BACKRUB_PROTEIN_SEQUENCE_DESIGN", backrubSpecificArgList)
cmdrun.run()
return
def getBackrubSpecificArgumentList(self):
"""
get list of backrub specific parameters from PM
"""
listOfArgs = []
bond_angle_weight = str(self.bondAngleWeightSimSpinBox.value())
listOfArgs.append('-bond_angle_weight')
listOfArgs.append( bond_angle_weight)
if self.bondAngleParamComboBox.currentIndex() == 0:
bond_angle_params = 'bond_angle_amber_rosetta'
else:
bond_angle_params = 'bond_angle_charmm_rosetta'
listOfArgs.append('-bond_angle_params')
listOfArgs.append(bond_angle_params)
only_bb = str(self.onlybbSpinBox.value())
listOfArgs.append('-only_bb')
listOfArgs.append( only_bb)
only_rot = str(self.onlyrotSpinBox.value())
listOfArgs.append('-only_rot')
listOfArgs.append( only_rot)
mc_temp = str(self.mctempSpinBox.value())
listOfArgs.append('-mc_temp')
listOfArgs.append( mc_temp)
min_res = self.minresSpinBox.value()
max_res = self.maxresSpinBox.value()
if max_res < min_res:
msg = redmsg("Maximum number of residues for rosetta simulation with backrub" \
" motion cannot be less than minimum number of residues."\
" Neglecting this parameter for this simulation.")
env.history.message("BACKRUB SIMULATION: " + msg)
else:
listOfArgs.append('-min_res')
listOfArgs.append( str(min_res))
listOfArgs.append('-max_res')
listOfArgs.append( str(max_res))
return listOfArgs | NanoCAD-master | cad/src/protein/commands/BackrubProteinSim/BackrubProteinSim_PropertyManager.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.changes as changes
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from command_support.EditCommand import EditCommand
from utilities.constants import red
from protein.commands.BackrubProteinSim.BackrubProteinSim_PropertyManager import BackrubProteinSim_PropertyManager
# == GraphicsMode part
_superclass_for_GM = SelectChunks_GraphicsMode
class BackrubProteinSim_GraphicsMode(SelectChunks_GraphicsMode ):
"""
Graphics mode for Backrub Proteins sequence design command.
"""
pass
# == Command part
class BackrubProteinSim_Command(EditCommand):
"""
Class for protein sequence design with rosetta when backrub motion is allowed
"""
# class constants
GraphicsMode_class = BackrubProteinSim_GraphicsMode
PM_class = BackrubProteinSim_PropertyManager
commandName = 'BACKRUB_PROTEIN_SEQUENCE_DESIGN'
featurename = "Backrub Protein Sequence Design"
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
command_should_resume_prevMode = True
command_has_its_own_PM = True
flyoutToolbar = None
def _getFlyoutToolBarActionAndParentCommand(self):
"""
See superclass for documentation.
@see: self.command_update_flyout()
"""
flyoutActionToCheck = 'rosetta_backrub_Action'
parentCommandName = 'BUILD_PROTEIN'
return flyoutActionToCheck, parentCommandName
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
return bool_keep
| NanoCAD-master | cad/src/protein/commands/BackrubProteinSim/BackrubProteinSim_Command.py |
NanoCAD-master | cad/src/protein/commands/BackrubProteinSim/__init__.py |
|
NanoCAD-master | cad/src/protein/commands/EditProtein/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
EditProtein_PropertyManager.py
The EditProtein_PropertyManager class provides a Property Manager
for the B{Edit Protein} command on the flyout toolbar in the
Build > Protein mode.
@author: Piotr, Mark
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
TODO:
- Better messages, especially when selecting different peptides.
- Need to implement a validator for the Name line edit field.
- Collapse all rotamers when leaving command.
NICETOHAVE:
- Some way of showing the current rotamer when all rotamers are displayed.
Ideas include:
- Dim all rotamers in the current protein except the atoms in the current rotamer.
- Highlight atoms in current rotamer for 1 second (when switching rotamers).
- Include "Show entire model" checkbox in PM (checked by default).
- Show residue label in GA of current residue, including AA and # (i.e. SER[14]).
- "Show adjacent rotamers" checkbox.
REFACTORING:
Things to discuss with Bruce include an asterisk:
- Should current_protein be renamed to command.struct everywhere? *
- Move some methods to EditProtein_Command or EditCommand class. *
- add setStructureName(name) in EditProtein_Command or in superclass EditCommand?
- other methods that edit the current protein.
"""
import os, time, fnmatch, string
import foundation.env as env
from widgets.prefs_widgets import connect_checkbox_with_boolean_pref
from utilities.prefs_constants import getDefaultWorkingDirectory
from utilities.prefs_constants import workingDirectory_prefs_key
from utilities.Log import greenmsg
from utilities.constants import yellow, orange, red, magenta
from utilities.constants import cyan, blue, white, black, gray
from utilities.constants import diPROTEIN
from PyQt4.Qt import SIGNAL
from PyQt4.Qt import Qt
from PyQt4 import QtGui
from PyQt4.Qt import QFileDialog, QString, QMessageBox, QSlider
from PM.PM_PushButton import PM_PushButton
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_ComboBox import PM_ComboBox
from PM.PM_LineEdit import PM_LineEdit
from PM.PM_StackedWidget import PM_StackedWidget
from PM.PM_CheckBox import PM_CheckBox
from PM.PM_Dial import PM_Dial
from PM.PM_ToolButtonRow import PM_ToolButtonRow
from PM.PM_Slider import PM_Slider
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from PM.PM_ColorComboBox import PM_ColorComboBox
from PyQt4.Qt import QTextCursor
from command_support.Command_PropertyManager import Command_PropertyManager
_superclass = Command_PropertyManager
class EditProtein_PropertyManager(Command_PropertyManager):
"""
The ProteinDisplayStyle_PropertyManager class provides a Property Manager
for the B{Edit Protein} command on the Build Protein command toolbar.
The selected peptide/protein is displayed in the protein reduced display
style. The user can select individual rotamers and edit their chi angles.
This is useful for certain types of protein design protocols using a
3rd party program like Rosetta.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
"""
title = "Protein Properties"
pmName = title
iconPath = "ui/actions/Command Toolbar/BuildProtein/EditProtein.png"
current_protein = None # The currently selected peptide.
previous_protein = None # The last peptide selected.
current_aa = None # The current amino acid.
def __init__( self, command ):
"""
Constructor for the property manager.
"""
self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key]
_superclass.__init__(self, command)
self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_WHATS_THIS_BUTTON)
return
def connect_or_disconnect_signals(self, isConnect = True):
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.nameLineEdit,
SIGNAL("editingFinished()"),
self._nameChanged)
change_connect(self.currentResidueComboBox,
SIGNAL("activated(int)"),
self.setCurrentAminoAcid)
change_connect(self.prevButton,
SIGNAL("clicked()"),
self._expandPreviousRotamer)
change_connect(self.nextButton,
SIGNAL("clicked()"),
self._expandNextRotamer)
change_connect(self.recenterViewCheckBox,
SIGNAL("toggled(bool)"),
self._centerViewToggled)
change_connect(self.showAllResiduesCheckBox,
SIGNAL("toggled(bool)"),
self._showAllResidues)
# Rotamer control widgets.
change_connect(self.chi1Dial,
SIGNAL("valueChanged(int)"),
self._rotateChi1)
change_connect(self.chi2Dial,
SIGNAL("valueChanged(int)"),
self._rotateChi2)
change_connect(self.chi3Dial,
SIGNAL("valueChanged(int)"),
self._rotateChi3)
# Chi4 dial is hidden.
change_connect(self.chi4Dial,
SIGNAL("valueChanged(double)"),
self._rotateChi4)
return
#==
def _nameChanged(self):
"""
Slot for "Name" field.
@TODO: Include a validator for the name field.
"""
if not self.current_protein:
return
_name = str(self.nameLineEdit.text())
if not _name: # Minimal test. Need to implement a validator.
if self.current_protein:
self.nameLineEdit.setText(self.current_protein.name)
return
self.current_protein.name = _name
msg = "Editing structure <b>%s</b>." % _name
self.updateMessage(msg)
return
def update_name_field(self):
"""
Update the name field showing the name of the currently selected protein.
clear the combobox list.
"""
if not self.current_protein:
self.nameLineEdit.setText("")
else:
self.nameLineEdit.setText(self.current_protein.name)
return
def update_length_field(self):
"""
Update the name field showing the name of the currently selected protein.
clear the combobox list.
"""
if not self.current_protein:
self.lengthLineEdit.setText("")
else:
length_str = "%d residues" % self.current_protein.protein.count_amino_acids()
self.lengthLineEdit.setText(length_str)
return
def update_residue_combobox(self):
"""
Update the residue combobox with the amino acid sequence of the
currently selected protein. If there is no currently selected protein,
clear the combobox list.
"""
self.currentResidueComboBox.clear()
if not self.current_protein:
return
aa_list = self.current_protein.protein.get_amino_acid_id_list()
for j in range(len(aa_list)):
aa_id, residue_id = aa_list[j].strip().split(":")
self.currentResidueComboBox.addItem(residue_id)
pass
self.setCurrentAminoAcid()
return
def close(self):
"""
Closes the Property Manager. Overrides EditCommand_PM.close()
"""
self.sequenceEditor.hide()
env.history.statusbar_msg("")
if self.current_protein:
self.current_protein.setDisplayStyle(self.previous_protein_display_style)
self.previous_protein = None
# Update name in case the it was changed by the user.
self.current_protein.name = str(self.nameLineEdit.text())
_superclass.close(self)
return
def show(self):
"""
Show the PM. Extends superclass method.
@note: _update_UI_do_updates() gets called immediately after this and
updates PM widgets with their correct values/settings.
"""
_superclass.show(self)
env.history.statusbar_msg("")
return
def _addGroupBoxes( self ):
"""
Add the Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox( self,
title = "Parameters")
self._loadGroupBox1( self._pmGroupBox1 )
self._pmGroupBox2 = PM_GroupBox( self,
title = "Rotamer Controls")
self._loadGroupBox2( self._pmGroupBox2 )
return
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box.
"""
self.nameLineEdit = PM_LineEdit( pmGroupBox,
label = "Name:")
self.lengthLineEdit = PM_LineEdit( pmGroupBox,
label = "Length:")
self.lengthLineEdit.setEnabled(False)
self.currentResidueComboBox = PM_ComboBox( pmGroupBox,
label = "Current residue:",
setAsDefault = False)
BUTTON_LIST = [
("QToolButton", 1, "Previous residue",
"ui/actions/Properties Manager/Previous.png",
"", "Previous residue", 0 ),
( "QToolButton", 2, "Next residue",
"ui/actions/Properties Manager/Next.png",
"", "Next residue", 1 )
]
self.prevNextButtonRow = \
PM_ToolButtonRow( pmGroupBox,
title = "",
buttonList = BUTTON_LIST,
label = 'Previous / Next:',
isAutoRaise = True,
isCheckable = False
)
self.prevButton = self.prevNextButtonRow.getButtonById(1)
self.nextButton = self.prevNextButtonRow.getButtonById(2)
self.recenterViewCheckBox = \
PM_CheckBox( pmGroupBox,
text = "Center view on current residue",
setAsDefault = True,
state = Qt.Unchecked,
widgetColumn = 0,
spanWidth = True)
self.lockEditedCheckBox = \
PM_CheckBox( pmGroupBox,
text = "Lock edited rotamers",
setAsDefault = True,
state = Qt.Checked,
widgetColumn = 0,
spanWidth = True)
self.showAllResiduesCheckBox = \
PM_CheckBox( pmGroupBox,
text = "Show all residues",
setAsDefault = False,
state = Qt.Unchecked,
widgetColumn = 0,
spanWidth = True)
return
def _loadGroupBox2(self, pmGroupBox):
"""
Load widgets in group box.
"""
self.discreteStepsCheckBox = \
PM_CheckBox( pmGroupBox,
text = "Use discrete steps",
setAsDefault = True,
state = Qt.Unchecked)
self.chi1Dial = \
PM_Dial( pmGroupBox,
label = "Chi1:",
value = 0.000,
setAsDefault = True,
minimum = -180.0,
maximum = 180.0,
wrapping = True,
suffix = "deg",
spanWidth = False)
self.chi1Dial.setEnabled(False)
self.chi2Dial = \
PM_Dial( pmGroupBox,
label = "Chi2:",
value = 0.000,
setAsDefault = True,
minimum = -180.0,
maximum = 180.0,
suffix = "deg",
spanWidth = False)
self.chi2Dial.setEnabled(False)
self.chi3Dial = \
PM_Dial( pmGroupBox,
label = "Chi3:",
value = 0.000,
setAsDefault = True,
minimum = -180.0,
maximum = 180.0,
suffix = "deg",
spanWidth = False)
self.chi3Dial.setEnabled(False)
self.chi4Dial = \
PM_Dial( pmGroupBox,
label = "Chi4:",
value = 0.000,
setAsDefault = True,
minimum = -180.0,
maximum = 180.0,
suffix = "deg",
spanWidth = False)
self.chi4Dial.setEnabled(False)
self.chi4Dial.hide()
return
def _addWhatsThisText( self ):
pass
def _addToolTipText(self):
pass
def _expandNextRotamer(self):
"""
Displays the next rotamer in the chain.
@attention: this only works when the GDS is a reduced display style.
"""
if not self.current_protein:
return
self.current_protein.protein.traverse_forward()
self.setCurrentAminoAcid()
return
def _expandPreviousRotamer(self):
"""
Displays the previous rotamer in the chain.
@attention: this only works when the GDS is a reduced display style.
"""
if not self.current_protein:
return
self.current_protein.protein.traverse_backward()
self.setCurrentAminoAcid()
return
def _centerViewToggled(self, checked):
"""
Slot for "Center view on current residue" checkbox.
"""
if checked:
self.display_and_recenter()
return
def _showAllResidues(self, show):
"""
Slot for "Show all residues" checkbox.
"""
if not self.current_protein:
return
print "Show =",show
if show:
self._expandAllRotamers()
else:
self._collapseAllRotamers()
return
def _collapseAllRotamers(self):
"""
Hides all the rotamers (except the current rotamer).
"""
self.display_and_recenter()
return
def _expandAllRotamers(self):
"""
Displays all the rotamers.
"""
if not self.current_protein:
return
self.current_protein.protein.expand_all_rotamers()
self.win.glpane.gl_update()
return
def display_and_recenter(self):
"""
Recenter the view on the current amino acid selected in the
residue combobox (or the sequence editor). All rotamers
except the current rotamer are collapsed (hidden).
"""
if not self.current_protein:
return
# Uncheck the "Show all residues" checkbox since they are being collapsed.
# Disconnect signals so that showAllResiduesCheckBox won't general a signal.
self.connect_or_disconnect_signals(isConnect = False)
self.showAllResiduesCheckBox.setChecked(False)
self.connect_or_disconnect_signals(isConnect = True)
self.current_protein.protein.collapse_all_rotamers()
# Display the current amino acid and center it in the view if the
# "Center view on current residue" is checked.
if self.current_aa:
self.current_protein.protein.expand_rotamer(self.current_aa)
self._update_chi_angles(self.current_aa)
if self.recenterViewCheckBox.isChecked():
ca_atom = self.current_aa.get_c_alpha_atom()
if ca_atom:
self.win.glpane.pov = -ca_atom.posn()
self.win.glpane.gl_update()
return
def _update_chi_angles(self, aa):
"""
"""
angle = aa.get_chi_angle(0)
if angle:
self.chi1Dial.setEnabled(True)
self.chi1Dial.setValue(angle)
else:
self.chi1Dial.setEnabled(False)
self.chi1Dial.setValue(0.0)
angle = aa.get_chi_angle(1)
if angle:
self.chi2Dial.setEnabled(True)
self.chi2Dial.setValue(angle)
else:
self.chi2Dial.setEnabled(False)
self.chi2Dial.setValue(0.0)
angle = aa.get_chi_angle(2)
if angle:
self.chi3Dial.setEnabled(True)
self.chi3Dial.setValue(angle)
else:
self.chi3Dial.setEnabled(False)
self.chi3Dial.setValue(0.0)
angle = aa.get_chi_angle(3)
if angle:
self.chi4Dial.setEnabled(True)
self.chi4Dial.setValue(angle)
else:
self.chi4Dial.setEnabled(False)
self.chi4Dial.setValue(0.0)
return
def setCurrentAminoAcid(self, aa_index = -1):
"""
Set the current amino acid to I{aa_index} and update the
"Current residue" combobox and the sequence editor.
@param aa_index: the amino acid index. If negative, update the PM and
sequence editor based on the current aa_index.
@type aa_index: int
@note: This is the slot for the "Current residue" combobox.
"""
if not self.current_protein:
return
if aa_index < 0:
aa_index = self.current_protein.protein.get_current_amino_acid_index()
if 0: # Debugging statement
print"setCurrentAminoAcid(): aa_index=", aa_index
self.currentResidueComboBox.setCurrentIndex(aa_index)
self.current_protein.protein.set_current_amino_acid_index(aa_index)
self.current_aa = self.current_protein.protein.get_current_amino_acid()
self.display_and_recenter()
self.sequenceEditor.setCursorPosition(aa_index)
return
def _rotateChiAngle(self, chi, angle):
"""
Rotate around chi1 angle.
"""
if not self.current_protein:
return
if self.current_aa:
self.current_protein.protein.expand_rotamer(self.current_aa)
self.current_aa.set_chi_angle(chi, angle)
self.win.glpane.gl_update()
return
def _rotateChi1(self, angle):
"""
Slot for Chi1 dial.
"""
self._rotateChiAngle(0, angle)
self.chi1Dial.updateValueLabel()
return
def _rotateChi2(self, angle):
"""
Slot for Chi2 dial.
"""
self._rotateChiAngle(1, angle)
self.chi2Dial.updateValueLabel()
return
def _rotateChi3(self, angle):
"""
Slot for Chi3 dial.
"""
self._rotateChiAngle(2, angle)
self.chi3Dial.updateValueLabel()
return
def _rotateChi4(self, angle):
"""
Slot for Chi4 dial.
@note: this dial is currently hidden and unused.
"""
self._rotateChiAngle(3, angle)
return
def _update_UI_do_updates(self):
"""
Overrides superclass method.
@see: Command_PropertyManager._update_UI_do_updates()
"""
self.current_protein = self.win.assy.getSelectedProteinChunk()
if self.current_protein is self.previous_protein:
if 0:
print "Edit Protein: _update_UI_do_updates() - DO NOTHING."
return
# It is common that the user will unselect the current protein.
# If so, set current_protein to previous_protein so that it
# (the previously selected protein) remains the current protein
# in the PM and sequence editor.
if not self.current_protein:
self.current_protein = self.previous_protein
return
# Update all PM widgets that need to be since something has changed.
if 0:
print "Edit Protein: _update_UI_do_updates() - UPDATING THE PMGR."
self.update_name_field()
self.update_length_field()
self.sequenceEditor.updateSequence(proteinChunk = self.current_protein)
self.update_residue_combobox()
# NOTE: Changing the display style of the protein chunks can take some
# time. We should put up the wait (hourglass) cursor and restore
# before returning.
if self.previous_protein:
self.previous_protein.setDisplayStyle(self.previous_protein_display_style)
self.previous_protein = self.current_protein
if self.current_protein:
self.previous_protein_display_style = self.current_protein.getDisplayStyle()
self.current_protein.setDisplayStyle(diPROTEIN)
if self.current_protein:
msg = "Editing structure <b>%s</b>." % self.current_protein.name
else:
msg = "Select a single structure to edit."
self.updateMessage(msg)
return
| NanoCAD-master | cad/src/protein/commands/EditProtein/EditProtein_PropertyManager.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.changes as changes
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from command_support.EditCommand import EditCommand
from utilities.constants import red
from protein.commands.EditProtein.EditProtein_PropertyManager import EditProtein_PropertyManager
# == GraphicsMode part
_superclass_for_GM = SelectChunks_GraphicsMode
class EditProtein_GraphicsMode(SelectChunks_GraphicsMode ):
"""
Graphics mode for Edit Protein command.
"""
pass
# == Command part
class EditProtein_Command(EditCommand):
"""
Command class for "Edit Protein".
"""
# class constants
GraphicsMode_class = EditProtein_GraphicsMode
PM_class = EditProtein_PropertyManager
commandName = 'EDIT_PROTEIN'
featurename = "Edit Protein"
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
command_should_resume_prevMode = True
command_has_its_own_PM = True
flyoutToolbar = None
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
(and as of 2008-03-06, it is proposed that dna_updater calls this method
when needed.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
return bool_keep
| NanoCAD-master | cad/src/protein/commands/EditProtein/EditProtein_Command.py |
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
CompareProteins_PropertyManager.py
The CompareProteins_PropertyManager class provides a Property Manager
for the B{Compare Proteins} command on the flyout toolbar in the
Build > Protein mode.
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
TODO:
- Switch display styles of selected proteins to diPROTEIN (instead of the GDS).
- PM color comboboxes to choose the "difference colors".
BUGS:
- Previously compared proteins still show differences after comparing a new set of proteins.
- "Hide differences" button should be disabled (or hidden) when there are no differences.
"""
import foundation.env as env
from command_support.Command_PropertyManager import Command_PropertyManager
from utilities.prefs_constants import workingDirectory_prefs_key
from utilities.constants import yellow
from PyQt4.Qt import SIGNAL
from PM.PM_PushButton import PM_PushButton
from PM.PM_GroupBox import PM_GroupBox
from PM.PM_LineEdit import PM_LineEdit
from PM.PM_DoubleSpinBox import PM_DoubleSpinBox
from PM.PM_Constants import PM_DONE_BUTTON
from PM.PM_Constants import PM_WHATS_THIS_BUTTON
from protein.model.Protein import getAllProteinChunksInPart
from utilities.constants import diPROTEIN
from utilities.Log import redmsg
_superclass = Command_PropertyManager
class CompareProteins_PropertyManager(Command_PropertyManager):
"""
The CompareProteins_PropertyManager class provides a Property Manager
for the B{Compare Proteins} command on the Build Protein flyout toolbar.
@ivar title: The title that appears in the property manager header.
@type title: str
@ivar pmName: The name of this property manager. This is used to set
the name of the PM_Dialog object via setObjectName().
@type name: str
@ivar iconPath: The relative path to the PNG file that contains a
22 x 22 icon image that appears in the PM header.
@type iconPath: str
@ivar proteinChunk1: The first currently selected protein to be compared.
@type proteinChunk1: protein chunk
@ivar proteinChunk2: The second currently selected protein to be compared.
@type proteinChunk2: protein chunk
"""
title = "Compare Proteins"
pmName = title
iconPath = "ui/actions/Command Toolbar/BuildProtein/Compare.png"
proteinChunk1 = None
proteinChunk2 = None
def __init__( self, command ):
"""
Constructor for the property manager.
"""
self.threshold = 10.0
_superclass.__init__(self, command)
self.showTopRowButtons( PM_DONE_BUTTON | \
PM_WHATS_THIS_BUTTON)
return
def connect_or_disconnect_signals(self, isConnect = True):
if isConnect:
change_connect = self.win.connect
else:
change_connect = self.win.disconnect
change_connect(self.comparePushButton,
SIGNAL("clicked()"),
self._compareProteins)
change_connect(self.thresholdDoubleSpinBox,
SIGNAL("valueChanged(double)"),
self._thresholdChanged)
change_connect(self.hidePushButton,
SIGNAL("clicked()"),
self._hideDifferences)
return
def close(self):
"""
Closes the Property Manager. Overrides EditCommand_PM.close()
"""
env.history.statusbar_msg("")
self._resetAminoAcids()
_superclass.close(self)
# Restore the original global display style.
self.o.setGlobalDisplayStyle(self.originalDisplayStyle)
return
def show(self):
"""
Show the PM. Extends superclass method.
@note: _update_UI_do_updates() gets called immediately after this and
updates PM widgets with their correct values/settings.
"""
_superclass.show(self)
env.history.statusbar_msg("")
# Force the Global Display Style to "Protein" since this is the only way
# to see comparisons. The global display style will be restored when leaving
# this command (via self.close()).
self.originalDisplayStyle = self.o.displayMode
self.o.setGlobalDisplayStyle(diPROTEIN)
return
def _addGroupBoxes( self ):
"""
Add the Property Manager group boxes.
"""
self._pmGroupBox1 = PM_GroupBox( self,
title = "Compare")
self._loadGroupBox1( self._pmGroupBox1 )
return
def _addWhatsThisText( self ):
"""
What's This text for widgets in this Property Manager.
"""
pass
def _addToolTipText(self):
"""
Tool Tip text for widgets in this Property Manager.
"""
pass
def _loadGroupBox1(self, pmGroupBox):
"""
Load widgets in group box.
"""
self.structure1LineEdit = \
PM_LineEdit( pmGroupBox,
label = "First structure:",
setAsDefault = False)
self.structure1LineEdit.setEnabled(False)
self.structure2LineEdit = \
PM_LineEdit( pmGroupBox,
label = "Second structure:",
setAsDefault = False)
self.structure2LineEdit.setEnabled(False)
self.thresholdDoubleSpinBox = \
PM_DoubleSpinBox( pmGroupBox,
label = "Threshold:",
value = self.threshold,
setAsDefault = True,
minimum = 0.0,
maximum = 360.0,
decimals = 1,
singleStep = 30.0,
suffix = " deg",
spanWidth = False)
self.comparePushButton = \
PM_PushButton( pmGroupBox,
text = "Compare",
setAsDefault = True)
self.hidePushButton = \
PM_PushButton( pmGroupBox,
text = "Hide differences",
setAsDefault = True)
return
def _compareProteins(self):
"""
Slot for Compare button.
Compares two selected proteins of the same length.
Amino acids that differ greater than the "threshold"
value are displayed in two colors (red for the first protein
and yellow for the second protein) and are only visible when
the two proteins are displayed in the
reduced display style.
"""
from utilities.constants import red, orange, green, cyan
if not self.proteinChunk1 or \
not self.proteinChunk2:
return
protein_1 = self.proteinChunk1.protein
protein_2 = self.proteinChunk2.protein
if protein_1 and \
protein_2:
aa_list_1 = protein_1.get_amino_acids()
aa_list_2 = protein_2.get_amino_acids()
protein_1.collapse_all_rotamers()
protein_2.collapse_all_rotamers()
if len(aa_list_1) == len(aa_list_2):
for aa1, aa2 in zip (aa_list_1, aa_list_2):
aa1.color = None
aa2.color = None
#aa1.collapse()
#aa2.collapse()
if aa1.get_one_letter_code() != aa2.get_one_letter_code():
aa1.set_color(red)
aa1.expand()
aa2.set_color(yellow)
aa2.expand()
else:
max = 0.0
for chi in range(0, 3):
angle1 = aa1.get_chi_angle(chi)
angle2 = aa2.get_chi_angle(chi)
if angle1 and \
angle2:
if angle1 < 0.0:
angle1 += 360.0
if angle2 < 0.0:
angle2 += 360.0
diff = abs(angle1 - angle2)
if diff > max:
max = diff
if max >= self.threshold:
# This be a parameter.
aa1.set_color(green)
aa1.expand()
aa2.set_color(cyan)
aa2.expand()
self.win.glpane.gl_update()
else:
msg = "The lengths of compared proteins are not equal."
self.updateMessage(msg)
env.history.redmsg(msg)
return
def _hideDifferences(self):
"""
Slot for the "Hide differences" button.
Hides amino acids that differ greater than the "threshold" value.
@warning: Untested. Code looks suspicious.
"""
if not self.proteinChunk1 or \
not self.proteinChunk2:
return
protein_1 = self.proteinChunk1.protein
protein_2 = self.proteinChunk2.protein
if protein_1 and \
protein_2:
aa_list_1 = protein_1.get_amino_acids()
aa_list_2 = protein_2.get_amino_acids()
if len(aa_list_1) == len(aa_list_2):
protein_1.collapse_all_rotamers() #@@@
protein_2.collapse_all_rotamers() #@@@
for aa1, aa2 in zip (aa_list_1, aa_list_2):
aa1.color = None
aa2.color = None
aa1.collapse()
aa2.collapse()
self.win.glpane.gl_update()
return
def _thresholdChanged(self, value):
"""
Slot for Threshold spinbox.
"""
self.threshold = value
self._compareProteins()
return
def _resetAminoAcids(self):
"""
Resets the color and collapse all amino acids of all proteins.
"""
proteinChunkList = getAllProteinChunksInPart(self.win.assy)
for proteinChunk in proteinChunkList:
proteinChunk.protein.collapse_all_rotamers()
aa_list = proteinChunk.protein.get_amino_acids()
for aa in aa_list:
aa.color = None
aa.collapse()
self.win.glpane.gl_update()
return
def _update_UI_do_updates(self):
"""
Overrides superclass method.
@see: Command_PropertyManager._update_UI_do_updates()
"""
self.proteinChunk1 = None
self.proteinChunk2 = None
self.comparePushButton.setEnabled(False)
self.hidePushButton.setEnabled(False)
selectedProteinList = self.win.assy.getSelectedProteinChunks()
if len(selectedProteinList) == 0:
self.structure1LineEdit.setText("")
self.structure2LineEdit.setText("")
msg = "Select two structures of the same length in the graphics area, "\
"then click the <b>Compare</b> button to compare them."
elif len(selectedProteinList) == 1:
self.proteinChunk1 = selectedProteinList[0]
aa1_count = " (%d)" % self.proteinChunk1.protein.count_amino_acids()
self.structure1LineEdit.setText(self.proteinChunk1.name + aa1_count)
self.structure2LineEdit.setText("")
msg = "Select one more structure in the graphics area that is the same "\
"length as <b>" + self.proteinChunk1.name + "</b>. "\
"Then click the <b>Compare</b> button to compare them."
elif len(selectedProteinList) == 2:
self.proteinChunk1 = selectedProteinList[0]
aa1_count = " (%d)" % self.proteinChunk1.protein.count_amino_acids()
self.structure1LineEdit.setText(self.proteinChunk1.name + aa1_count)
self.proteinChunk2 = selectedProteinList[1]
aa2_count = " (%d)" % self.proteinChunk2.protein.count_amino_acids()
self.structure2LineEdit.setText(self.proteinChunk2.name + aa2_count)
if aa1_count == aa2_count:
self.comparePushButton.setEnabled(True)
self.hidePushButton.setEnabled(True)
msg = "Click the <b>Compare</b> button to compare the two selected structures."
else:
msg = "<b>%s</b> and <b>%s</b> are not the same length." % \
(self.proteinChunk1.name, self.proteinChunk2.name)
msg = redmsg(msg)
else:
self.structure1LineEdit.setText("")
self.structure2LineEdit.setText("")
msg = redmsg("Too many proteins selected.")
self.updateMessage(msg)
env.history.redmsg(msg)
return
| NanoCAD-master | cad/src/protein/commands/CompareProteins/CompareProteins_PropertyManager.py |
NanoCAD-master | cad/src/protein/commands/CompareProteins/__init__.py |
|
# Copyright 2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: Piotr
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import foundation.changes as changes
from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode
from command_support.EditCommand import EditCommand
from utilities.constants import red
from protein.commands.CompareProteins.CompareProteins_PropertyManager import CompareProteins_PropertyManager
# == GraphicsMode part
_superclass_for_GM = SelectChunks_GraphicsMode
class CompareProteins_GraphicsMode(SelectChunks_GraphicsMode ):
"""
Graphics mode for Compare Proteins command.
"""
pass
# == Command part
class CompareProteins_Command(EditCommand):
"""
"""
# class constants
GraphicsMode_class = CompareProteins_GraphicsMode
PM_class = CompareProteins_PropertyManager
commandName = 'COMPARE_PROTEINS'
featurename = "Compare Proteins"
from utilities.constants import CL_SUBCOMMAND
command_level = CL_SUBCOMMAND
command_parent = 'BUILD_PROTEIN'
command_should_resume_prevMode = True
command_has_its_own_PM = True
flyoutToolbar = None
def _getFlyoutToolBarActionAndParentCommand(self):
"""
See superclass for documentation.
@see: self.command_update_flyout()
"""
flyoutActionToCheck = 'compareProteinsAction'
parentCommandName = 'BUILD_PROTEIN'
return flyoutActionToCheck, parentCommandName
def keep_empty_group(self, group):
"""
Returns True if the empty group should not be automatically deleted.
otherwise returns False. The default implementation always returns
False. Subclasses should override this method if it needs to keep the
empty group for some reasons. Note that this method will only get called
when a group has a class constant autdelete_when_empty set to True.
(and as of 2008-03-06, it is proposed that dna_updater calls this method
when needed.
@see: Command.keep_empty_group() which is overridden here.
"""
bool_keep = EditCommand.keep_empty_group(self, group)
return bool_keep
| NanoCAD-master | cad/src/protein/commands/CompareProteins/CompareProteins_Command.py |
NanoCAD-master | cad/src/protein/temporary_commands/__init__.py |
|
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details.
"""
@author: Urmi, Mark
@version: $Id$
@copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details.
@license: GPL
"""
from utilities.constants import gray, black, darkred, blue, white
from graphics.drawing.drawPeptideTrace import drawPeptideTrace ##, drawPeptideTrace_orig
from temporary_commands.LineMode.Line_Command import Line_Command
from temporary_commands.LineMode.Line_GraphicsMode import Line_GraphicsMode
from protein.commands.InsertPeptide.PeptideGenerator import PeptideGenerator, get_unit_length
# note: it would be better to move those into some other file
# so we didn't need to import them from another command
# (potential import cycle if that command ever needs to refer to this one)
# [bruce 090310 comment]
# ==
_superclass_for_GM = Line_GraphicsMode
class PeptideLine_GraphicsMode( Line_GraphicsMode ):
"""
Custom GraphicsMode used while interactively drawing a peptide chain for
the "Insert Peptide" command.
@see: InsertPeptide_EditCommand where this class is used.
"""
# The following valuse are used in drawing the 'sphere' that represent the
#first endpoint of the line. See Line_GraphicsMode.Draw_other for details.
endPoint1_sphereColor = white
endPoint1_sphereOpacity = 1.0
text = ""
structGenerator = PeptideGenerator()
def leftUp(self, event):
"""
Left up method.
"""
if self.command.mouseClickLimit is None:
if len(self.command.mouseClickPoints) == 2:
self.endPoint2 = None
self.command.createStructure()
self.glpane.gl_update()
pass
return
def snapLineEndPoint(self):
"""
Snap the line to the specified constraints.
To be refactored and expanded.
@return: The new endPoint2 i.e. the moving endpoint of the rubberband
line . This value may be same as previous or snapped so that it
lies on a specified vector (if one exists)
@rtype: B{A}
"""
if self.command.callbackForSnapEnabled() == 1:
endPoint2 = _superclass_for_GM.snapLineEndPoint(self)
else:
endPoint2 = self.endPoint2
return endPoint2
def Draw_other(self):
"""
"""
_superclass_for_GM.Draw_other(self)
if self.endPoint2 is not None and \
self.endPoint1 is not None:
# Generate a special chunk that contains only alpha carbon atoms
# that will be used to draw the peptide backbone trace.
# [by Mark, I guess?]
# Note: this chunk is used only for its (ordered) atom positions;
# it's not drawn in the usual way, and it's not part of the model.
# So this belongs in Draw_other, not Draw_model.
#
### REVIEW: this is probably very slow, compared to just generating
# the positions and passing a position-list to drawPeptideTrace.
# It's conceivable it also introduces bugs to do it this way
# (depending on whether making this chunk has any side effects
# on assy) -- I don't know of any, but didn't look closely.
#
# [bruce comments 090310]
alphaCarbonProteinChunk = \
self.structGenerator.make_aligned(
self.win.assy, "", 0,
self.command.phi,
self.command.psi,
self.endPoint1,
self.endPoint2,
fake_chain = True)
drawPeptideTrace(alphaCarbonProteinChunk)
# The original way of drawing the peptide trace.
# This function is deprecated and marked for removal.
# --Mark 2008-12-23
#drawPeptideTrace_orig(self.endPoint1,
#self.endPoint2,
#135,
#-135,
#self.glpane.scale,
#self.glpane.lineOfSight,
#beamThickness = 4.0
#)
pass
return
pass # end of class PeptideLine_GraphicsMode
# end
| NanoCAD-master | cad/src/protein/temporary_commands/PeptideLine_GraphicsMode.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
Python atoms, atom sets, diff factories, diff objects (tests)
http://tinyurl.com/rv7fx
May need changes to work in this location. Used to be in cad/src.
Probably depends on atombasehelp.c, which will likely move as the
cad/src directory is cleaned out.
@author: Will
@version: $Id$
@copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
import unittest
from atombase import *
############################################################
__key = 1
def genkey():
global __key
n = __key
__key = n + 1
return n
def resetgenkey():
global __key
__key = 1
class Atom(AtomBase):
def __init__(self):
AtomBase.__init__(self)
self.key = genkey()
class Bond(BondBase):
def __init__(self):
BondBase.__init__(self)
self.key = genkey()
class AtomDict(AtomDictBase):
def __init__(self):
AtomDictBase.__init__(self)
self.key = genkey()
class BondDict(BondDictBase):
def __init__(self):
BondDictBase.__init__(self)
self.key = genkey()
class Structure:
def __init__(self):
self.atomset = AtomDict()
self.bondset = BondDict()
def __len__(self):
return len(self.atomset.keys())
def water(x = 0.0, y = 0.0, z = 0.0):
w = Structure()
posns = (
(Numeric.array((x - 0.983, y - 0.008, z + 0.000)), # hydrogen
Numeric.array((x + 0.017, y - 0.008, z + 0.000)), # oxygen
Numeric.array((x + 0.276, y - 0.974, z + 0.000)))) # hydrogen
elts = (1, 8, 1)
atoms = [ ]
for i in range(len(posns)):
a = Atom()
a._posn = posns[i]
a._eltnum = elts[i]
a._atomtype = 1
w.atomset.add(a)
atoms.append(a)
for k1, k2 in ((atoms[0].key, atoms[1].key),
(atoms[1].key, atoms[2].key)):
b = Bond()
b.atomkey1 = k1
b.atomkey2 = k2
b.v6 = 1
w.bondset.add(b)
return w
def selectH(atom):
return atom._eltnum == 1
def selectSingle(bond):
return bond.v6 == 1
def transmuteOC(atom):
# change oxygen to carbon
if atom._eltnum == 8:
atom._eltnum = 6
def transmuteHN(atom):
# change hydrogen to nitrogen
if atom._eltnum == 1:
atom._eltnum = 7
class TestCase(unittest.TestCase):
def setUp(self):
resetgenkey()
class AtomTests(TestCase):
def test_eltnum_atombase(self):
ab = Atom()
assert ab._eltnum == 0
assert ab._atomtype == 0
ab._atomtype = 2
assert ab._atomtype == 2
def test_atoms_uniqueKeys(self):
a1 = Atom()
a1.key = 1
a2 = Atom()
a2.key = 2
assert a1.key != a2.key
class BondTests(TestCase):
def test_basic_bondbase(self):
bb = Bond()
assert bb.v6 == 0
bb.v6 = 2
assert bb.v6 == 2
def test_bondset_keysSorted(self):
"""
bondset.keys() # sorted
bondset.values() # sorted by key
bondset.items() # sorted by key
"""
bondset = BondDict()
# create them forwards
bond1 = Bond()
bond2 = Bond()
bond3 = Bond()
bond4 = Bond()
bond5 = Bond()
# add them backwards
bondset.add(bond5)
bondset.add(bond4)
bondset.add(bond3)
bondset.add(bond2)
bondset.add(bond1)
# they better come out forwards
assert bondset.keys() == [ 2, 3, 4, 5, 6 ]
assert bondset.values() == [
bond1, bond2, bond3, bond4, bond5
]
assert bondset.items() == [
(2, bond1), (3, bond2), (4, bond3),
(5, bond4), (6, bond5)
]
def test_bondset_contains(self):
"""
(bond.key in bondset) should be equivalent to, but
much faster than, (bond.key in bondset.keys())
###BUGS: bond.key is now named bond.bond_key;
# and it is not globally unique (it never was,
# but as of 080229 it collides much more often).
"""
bondset = BondDict()
# create them forwards
bond1 = Bond()
bond2 = Bond()
bond3 = Bond()
bond4 = Bond()
bond5 = Bond()
# add some, not others
bondset.add(bond1)
bondset.add(bond2)
bondset.add(bond3)
# check if they're in keys() correctly
assert bond1.key in bondset.keys()
assert bond2.key in bondset.keys()
assert bond3.key in bondset.keys()
assert bond4.key not in bondset.keys()
assert bond5.key not in bondset.keys()
# test the __contains__/sq_contains method
assert bond1.key in bondset
assert bond2.key in bondset
assert bond3.key in bondset
assert bond4.key not in bondset
assert bond5.key not in bondset
def test_bondset_gracefulRemoves(self):
"""
del bondset[bond.key]
###BUGS: bond.key is now named bond.bond_key;
# and it is not globally unique (it never was,
# but as of 080229 it collides much more often).
"""
bond1 = Bond()
bond2 = Bond()
bond3 = Bond()
bondset = BondDict()
bondset.add(bond1)
bondset.add(bond2)
bondset.add(bond3)
assert len(bondset) == 3
assert bond1.sets.tolist() == [ bondset.key ]
assert bond2.sets.tolist() == [ bondset.key ]
assert bond3.sets.tolist() == [ bondset.key ]
del bondset[bond1.key]
del bondset[bond2.key]
del bondset[bond3.key]
assert len(bondset) == 0
assert bond1.sets.tolist() == [ ]
assert bond2.sets.tolist() == [ ]
assert bond3.sets.tolist() == [ ]
def test_bondset_updateFromAnotherBondlist(self):
"""
bondset.update( bondset2 )
"""
alst = [ ]
for i in range(5):
a = Bond()
alst.append(a)
bondset = BondDict()
for a in alst:
bondset.add(a)
assert bondset.keys() == [ 1, 2, 3, 4, 5 ]
bondset2 = BondDict()
bondset2.update(bondset)
assert bondset2.keys() == [ 1, 2, 3, 4, 5 ]
def test_bondset_updateFromDict(self):
"""
bondset.update( any dict from bond.key to bond )
"""
adct = { }
for i in range(5):
a = Bond()
adct[a.key] = a
bondset = BondDict()
bondset.update(adct)
assert bondset.keys() == [ 1, 2, 3, 4, 5 ]
def test_bondset_removeFromEmpty(self):
bondset = BondDict()
a = Bond()
try:
bondset.remove(a)
self.fail("shouldn't be able to remove from an empty bondset")
except KeyError:
pass
def test_bondset_filter(self):
w = water()
bondset = BondDict()
for bond in filter(selectSingle, w.bondset.values()):
bondset.add(bond)
bondinfo = bondset.bondInfo()
assert type(bondinfo) == Numeric.arraytype
assert bondinfo.tolist() == [[3, 4, 1], [4, 5, 1]]
class AtomDictTests(TestCase):
def test_atomset_basic(self):
"""
atomset[atom.key] = atom
"""
atom1 = Atom()
atomset = AtomDict()
atomset[atom1.key] = atom1
try:
atomset[atom1.key+1] = atom1 # this should fail
raise FailureExpected
except KeyError:
pass
def test_atomset_keysIn(self):
"""
atomset.add(atm1)
atm1.key in atomset --> True
atm2.key in atomset --> False
"""
atomset = AtomDict()
# create them forwards
atom1 = Atom()
atom2 = Atom()
atomset.add(atom1)
assert atomset.has_key(atom1.key)
assert not atomset.has_key(atom2.key)
assert atom1.key in atomset
assert atom2.key not in atomset
def test_atomset_keysSorted(self):
"""
atomset.keys() # sorted
atomset.values() # sorted by key
atomset.items() # sorted by key
"""
atomset = AtomDict()
# create them forwards
atom1 = Atom()
atom2 = Atom()
atom3 = Atom()
atom4 = Atom()
atom5 = Atom()
# add them backwards
atomset.add(atom5)
atomset.add(atom4)
atomset.add(atom3)
atomset.add(atom2)
atomset.add(atom1)
# they better come out forwards
assert atomset.keys() == [ 2, 3, 4, 5, 6 ]
assert atomset.values() == [
atom1, atom2, atom3, atom4, atom5
]
assert atomset.items() == [
(2, atom1), (3, atom2), (4, atom3),
(5, atom4), (6, atom5)
]
def test_atomset_contains(self):
"""
(atm.key in atomset) should be equivalent to, but
much faster than, (atm.key in atomset.keys())
"""
atomset = AtomDict()
# create them forwards
atom1 = Atom()
atom2 = Atom()
atom3 = Atom()
atom4 = Atom()
atom5 = Atom()
# add some, not others
atomset.add(atom1)
atomset.add(atom2)
atomset.add(atom3)
# check if they're in keys() correctly
assert atom1.key in atomset.keys()
assert atom2.key in atomset.keys()
assert atom3.key in atomset.keys()
assert atom4.key not in atomset.keys()
assert atom5.key not in atomset.keys()
# test the __contains__/sq_contains method
assert atom1.key in atomset
assert atom2.key in atomset
assert atom3.key in atomset
assert atom4.key not in atomset
assert atom5.key not in atomset
def test_atomset_gracefulRemoves(self):
"""
del atomset[atom.key]
"""
atom1 = Atom()
atom2 = Atom()
atom3 = Atom()
atomset = AtomDict()
atomset.add(atom1)
atomset.add(atom2)
atomset.add(atom3)
assert len(atomset) == 3
assert atom1.sets.tolist() == [ atomset.key ]
assert atom2.sets.tolist() == [ atomset.key ]
assert atom3.sets.tolist() == [ atomset.key ]
del atomset[atom1.key]
del atomset[atom2.key]
del atomset[atom3.key]
assert len(atomset) == 0
assert atom1.sets.tolist() == [ ]
assert atom2.sets.tolist() == [ ]
assert atom3.sets.tolist() == [ ]
def test_atomset_updateFromAnotherAtomlist(self):
"""
atomset.update( atomset2 )
"""
alst = [ ]
for i in range(5):
a = Atom()
alst.append(a)
atomset = AtomDict()
for a in alst:
atomset.add(a)
assert atomset.keys() == [ 1, 2, 3, 4, 5 ]
atomset2 = AtomDict()
atomset2.update(atomset)
assert atomset2.keys() == [ 1, 2, 3, 4, 5 ]
def test_atomset_updateFromDict(self):
"""
atomset.update( any dict from atom.key to atom )
"""
adct = { }
for i in range(5):
a = Atom()
adct[a.key] = a
atomset = AtomDict()
atomset.update(adct)
assert atomset.keys() == [ 1, 2, 3, 4, 5 ]
def test_atomset_removeFromEmpty(self):
atomset = AtomDict()
a = Atom()
try:
atomset.remove(a)
self.fail("shouldn't be able to remove from an empty atomset")
except KeyError:
pass
def test_atomset_filter(self):
w = water()
atomset = AtomDict()
for atm in filter(selectH, w.atomset.values()):
atomset.add(atm)
atominfo = atomset.atomInfo()
assert type(atominfo) == Numeric.arraytype
assert atominfo.tolist() == [
[1, 1, -0.983, -0.008, 0.000],
[1, 1, 0.276, -0.974, 0.000]
]
def test_atomset_map(self):
w = water()
map(transmuteOC, w.atomset.values())
atominfo = w.atomset.atomInfo()
assert type(atominfo) == Numeric.arraytype
assert atominfo.tolist() == [
[1, 1, -0.983, -0.008, 0.000],
[6, 1, 0.017, -0.008, 0.000], # carbon
[1, 1, 0.276, -0.974, 0.000]
]
def unpack(result):
x1, x2, x3 = result
x1 = x1.tolist()
if type(x2) == Numeric.arraytype:
x2 = x2.tolist()
x3 = x3.tolist()
return (x1, x2, x3)
class DiffTests(TestCase):
def test_basicdiffs(self):
w = water()
db = DiffFactoryBase(w.atomset.values())
map(transmuteOC, w.atomset.values())
diffobj = db.snapshot()
keys, olds, news = unpack(diffobj._eltnum)
assert keys == [4]
assert olds == [8]
assert news == [6]
map(transmuteHN, w.atomset.values())
diffobj = db.snapshot()
keys, olds, news = unpack(diffobj._eltnum)
assert keys == [3, 5]
assert olds == [1, 1]
assert news == [7, 7]
for atom in w.atomset.values():
p = atom._posn
atom._posn = Numeric.array((p[0], p[1], p[2] + 1))
diffobj = db.snapshot()
keys, olds, news = unpack(diffobj._posn)
assert keys == [3, 4, 5]
assert olds == [0., 0., 0.]
assert news == [1., 1., 1.]
def test_diffDicts(self):
w = water()
db = DiffFactoryBase(w.atomset.values())
atomdict = AtomDict()
for x in w.atomset.values():
atomdict.add(x)
diffobj = db.snapshot()
keys, olds, news = unpack(diffobj.sets)
assert keys == [3, 4, 5]
assert olds == [[1], [1], [1]]
assert news == [[1, 5], [1, 5], [1, 5]]
def test_diffFactoryAddObject(self):
w = water()
db = DiffFactoryBase(w.atomset.values())
# Create a new atom and add it to the atomset
a = Atom()
db.addObject(a)
# When we add the new atom, we update the existing snapshot
# with the new atom's data
# Position it, and add it to the old structure - these changes
# will appear in the next diff
a._posn = Numeric.array((3.1416, 2.71828, 1.4707))
a._eltnum = 7 # nitrogen
a._atomtype = 1
w.atomset.add(a)
# What x coords changed? The new atom, when we positioned it
diffobj = db.snapshot()
keys, olds, news = unpack(diffobj._posn)
assert keys == [8]
assert olds[0][0] == 0.0
assert news[0][0] == 3.1416
# Move the whole structure, the diff includes all the x changes
for atm in w.atomset.values():
p = atm._posn
atm._posn = Numeric.array((p[0] + 2, p[1], p[2]))
diffobj = db.snapshot()
keys, olds, news = unpack(diffobj._posn)
assert keys == [3, 4, 5, 8]
assert map(lambda x: x[0], olds) == [-0.983, 0.017, 0.276, 3.1416]
assert map(lambda x: x[0], news) == [1.017, 2.017, 2.276, 5.1416]
class Tests(AtomTests, BondTests, AtomDictTests, DiffTests):
pass
def test():
suite = unittest.makeSuite(Tests, 'test')
#suite = unittest.makeSuite(Tests, 'test_atomset_keysSorted')
#suite = unittest.makeSuite(Tests, 'test_atomset_gracefulRemoves')
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == "__main__":
test()
| NanoCAD-master | cad/src/tests/atombasetests.py |
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details.
"""
@author: EricM
@version: $Id$
@copyright: 2008 Nanorex, Inc. See LICENSE file for details.
"""
import unittest
from samevals import same_vals, setArrayType
import Numeric
class SameValsTests(unittest.TestCase):
def test_simple(self):
assert same_vals(1, 1)
assert not same_vals(1, 2)
def test_dict1(self):
a = {}
b = {}
assert same_vals(a, b)
a["abc"] = 23 ;
assert not same_vals(a, b)
b["def"] = 45 ;
assert not same_vals(a, b)
a["def"] = 42 ;
b["abc"] = 23 ;
assert not same_vals(a, b)
a["def"] = 45 ;
assert same_vals(a, b)
def test_list1(self):
a = []
b = []
assert same_vals(a, b)
a.append("ferd")
assert not same_vals(a, b)
b.append("asdf")
assert not same_vals(a, b)
a.append("poiu")
b.append("poiu")
assert not same_vals(a, b)
a[0] = "asdf"
assert same_vals(a, b)
def test_tuple1(self):
# anyone know how to generate a zero length tuple?
assert same_vals((1,), (1,))
assert not same_vals((1, 2), (1,))
assert same_vals((1, 2), (1, 2))
assert not same_vals((1, 2), (2, 1))
def test_numericArray1(self):
a = Numeric.array((1, 2, 3))
b = Numeric.array((1, 2, 3))
assert same_vals(a, b)
b = Numeric.array((1, 2, 4))
assert not same_vals(a, b)
b = Numeric.array((1, 2))
assert not same_vals(a, b)
a = Numeric.array([[1, 2], [3, 4]])
b = Numeric.array([[1, 2], [3, 4]])
assert same_vals(a, b)
b = Numeric.array([4, 3])
c = a[1, 1::-1]
assert same_vals(b, c)
a = Numeric.array([[[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]],
[[[28, 29, 30], [31, 32, 33], [34, 35, 36]],
[[37, 38, 39], [40, 41, 42], [43, 44, 45]],
[[46, 47, 48], [49, 50, 51], [52, 53, 54]]]])
b = Numeric.array([[[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]],
[[[28, 29, 30], [31, 32, 33], [34, 35, 36]],
[[37, 38, 39], [40, 41, 42], [43, 44, 45]],
[[46, 47, 48], [49, 50, 51], [52, 53, 54]]]])
assert same_vals(a, b)
b = Numeric.array([[[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]],
[[[28, 29, 30], [31, 32, 33], [34, 35, 36]],
[[37, 38, 39], [40, 41, 42], [43, 44, 45]],
[[46, 47, 48], [49, 50, 51], [52, 53, 55]]]])
assert not same_vals(a, b)
b = Numeric.array([[[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]],
[[[28, 29, 30], [31, 30, 33], [34, 35, 36]],
[[37, 38, 39], [40, 41, 42], [43, 44, 45]],
[[46, 47, 48], [49, 50, 51], [52, 53, 54]]]])
assert not same_vals(a, b)
b = Numeric.array([[[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]]])
assert not same_vals(a, b)
a = Numeric.array(["abc", "def"], Numeric.PyObject)
b = Numeric.array(["abc", "def"], Numeric.PyObject)
assert same_vals(a, b)
b = Numeric.array(["abc", "defg"], Numeric.PyObject)
assert not same_vals(a, b)
def test():
suite = unittest.makeSuite(SameValsTests, 'test')
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == "__main__":
setArrayType(type(Numeric.array((1,2,3))))
test()
| NanoCAD-master | cad/src/tests/samevalstests.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.