python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
#!/usr/bin/python # Copyright 2005, 2007 Nanorex, Inc. See LICENSE file for details. """Nanotube generation tool for nanoENGINEER-1 Usage: nanotube.py <n> <m> <length> where (n,m) is the chirality of the nanotube, and the length is in nanometers. The resulting MMP file is written to standard output. According to Dresselhaus et al, the bond lengths in the nanotube are all 1.421 angstroms. The nanotube is passivated with oxygens and hydrogens at the ends. """ # Some nice references on nanotube geometry and properties: # http://physicsweb.org/articles/world/11/1/9 # http://physicsweb.org/articles/world/11/1/9/1/world-11-1-9-1 import sys import string import math sqrt3 = 3 ** 0.5 def prettyClose(u,v): # floats are never perfectly equal return (u-v)**2 < 1.0e-10 def prettyClose3(x1,y1,z1,x2,y2,z2): return (prettyClose(x1, x2) and prettyClose(y1, y2) and prettyClose(z1, z2)) class Chirality: # Nanotube bond length according to Dresselhaus, M. S., # Dresselhaus, G., Eklund, P. C. "Science of Fullerenes and Carbon # Nanotubes" Academic Press: San Diego, CA, 1995; pp. 760. BONDLENGTH = 1.421 # angstroms def __init__(self, n, m): self.n, self.m = n, m x = (n + 0.5 * m) * sqrt3 y = 1.5 * m angle = math.atan2(y, x) twoPiRoverA = (x**2 + y**2) ** .5 AoverR = (2 * math.pi) / twoPiRoverA self.__cos = math.cos(angle) self.__sin = math.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 - math.cos(AoverR * (s - u))) H = (v - x)**2 J = 2 * (1 - math.cos(AoverR * (u - w))) L = self.BONDLENGTH denom = F * J - G * H self.R = (L**2 * (F - H) / denom) ** .5 self.B = (L**2 * (J - G) / denom) ** .5 self.A = self.R * AoverR class ConstError(TypeError): pass def __setattr__(self,name,value): # Don't touch my precious constants if self.__dict__.has_key(name): raise self.ConstError, "Can't reassign " + name self.__dict__[name] = value 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, y3min, y3max, n): if y3max < y3min: y3min, y3max = y3max, y3min B, c, s = self.B, self.__cos, self.__sin P = sqrt3 * B * s Q = 1.5 * B * (c - s / sqrt3) m1, m2 = (y3min + P * n) / Q, (y3max + P * n) / Q return int(m1-1.5), int(m2+1.5) def xyz(self, n, m): x1, y1 = self.x1y1(n, m) x2, y2 = self.A * x1, self.B * y1 R = self.R x3 = R * math.sin(x2/R) z3 = R * math.cos(x2/R) return (x3, y2, z3) class Molecule: def __init__(self): self.atoms = [ ] def add(self, elt, x, y, z): for a2 in self.atoms: assert not prettyClose3(x, y, z, a2.x, a2.y, a2.z) class Atom: pass a = Atom() a.element = elt a.x, a.y, a.z = x, y, z self.atoms.append(a) def bondsForAtom(self, atomIndex): # atomIndex goes from 1..N, not 0..N-1 lst = [ ] for k in range(len(self.bonds)): i, j = self.bonds[k] if i == atomIndex or j == atomIndex: lst.append(k) return lst def passivate(self): for k in range(len(self.atoms)): lst = self.bondsForAtom(k + 1) if len(lst) == 2: self.atoms[k].element = "O" elif len(lst) == 1: self.atoms[k].element = "H" def makeBonds(self, maxlen): self.bonds = [ ] n = len(self.atoms) for i in range(n): a = self.atoms[i] ax, ay, az = a.x, a.y, a.z for j in range(i+1,n): b = self.atoms[j] dist = ((ax - b.x) ** 2 + (ay - b.y) ** 2 + (az - b.z) ** 2) ** .5 if dist <= maxlen: self.bonds.append((i+1, j+1)) def mmp(self): outf = sys.stdout outf.write("""mmpformat 050920 required kelvin 300 group (View Data) info opengroup open = False egroup (View Data) group (Untitled) info opengroup open = True mol (Nanotube.1) def """) for i in range(len(self.atoms)): a = self.atoms[i] enum = {"C": 6, "O": 8, "H": 1}[a.element] outf.write("atom %d (%d) (%d, %d, %d) vdw\n" % (i+1, enum, int(1000*a.x), int(1000*a.y), int(1000*a.z))) if a.element == "C": outf.write("info atom atomtype = sp2\n") r = "bonda" elif a.element in ("O", "H"): outf.write("info atom atomtype = sp3\n") r = "bond1" else: raise Exception, "unknown element" bondlist = self.bondsForAtom(i+1) for k in bondlist: a1, a2 = self.bonds[k] if a2 < i+1: r += " " + repr(a2) elif a1 < i+1: r += " " + repr(a1) outf.write(r + "\n") outf.write("""egroup (Untitled) end1 group (Clipboard) info opengroup open = False egroup (Clipboard) end molecular machine part Untitled """) outf.close() def rasmol(self): import os filename = "/tmp/foo.xyz" outf = open(filename, "w") r = repr(len(self.atoms)) + "\n" r += "glop\n" for a in self.atoms: r += a.element + (" %g %g %g\n" % (a.x, a.y, a.z)) outf.write(r) outf.close() os.system("rasmol -xyz " + filename) def test(self): mindist = None maxdist = None for a, b in self.bonds: a, b = self.atoms[a-1], self.atoms[b-1] dist = ((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2) ** .5 if mindist == None or dist < mindist: mindist = dist if maxdist == None or dist > maxdist: maxdist = dist return (mindist, maxdist) if (__name__ == '__main__'): if len(sys.argv) < 4: sys.stderr.write(__doc__) sys.exit(1) n = string.atoi(sys.argv[1]) m = string.atoi(sys.argv[2]) length = string.atof(sys.argv[3]) chirality = Chirality(n,m) M = Molecule() for n in range(chirality.n): mmin, mmax = chirality.mlimits(-.5 * length, .5 * length, n) for m in range(mmin-1, mmax+1): x, y, z = chirality.xyz(n, m) if -.5 * length <= y <= .5 * length: M.add("C", x, y, z) x, y, z = chirality.xyz(n+1./3, m+1./3) if -.5 * length <= y <= .5 * length: M.add("C", x, y, z) M.makeBonds(Chirality.BONDLENGTH * 1.2) M.passivate() M.mmp()
NanoCAD-master
cad/tests/nanotube.py
# Copyright 2005, 2007 Nanorex, Inc. See LICENSE file for details. import unittest import chem import assembly from qt import QApplication, SIGNAL import Utility import os ######################### import undo undo._use_hcmi_hack = False ######################### import MWsemantics import startup_funcs STILL_NEED_MODULARIZATION = True if STILL_NEED_MODULARIZATION: # file functions don't work right unless I do all this first startup_funcs.before_creating_app() app = QApplication([ ]) foo = MWsemantics.MWsemantics() startup_funcs.pre_main_show(foo) foo.show() startup_funcs.post_main_show(foo) else: foo = fileSlotsMixin() # ? ? ? # we still want assembly and group and atom, # and we still want to be able to select subgroups # but we don't want QApplication and QMainWindow ################### class FileTest(unittest.TestCase): TESTDATA = { "filename": "../partlib/gears/LilGears.mmp", "numatoms": 170, "bondLines": 150, "numchunks": 1 } def extraSaveMmpTest(self): pass def setUp(self): #foo.fileNew() #foo.fileOpen("../partlib/pumps/Pump.mmp") foo.fileOpen(self.TESTDATA["filename"]) def tearDown(self): foo.fileClose() def getLines(self, searchterm, fileExt): return os.popen("egrep \"" + searchterm + "\" /tmp/foo." + fileExt).readlines() def countLines(self, searchterm, fileExt, expected): n = len(self.getLines(searchterm, fileExt)) if n != expected: print "EXPECTED", expected, "GOT", n assert n == expected def testOpenFile(self): assy = foo.assy assy.checkparts() pump = assy.current_selgroup() assert pump.__class__ == Utility.PartGroup class MyStats: pass stats = MyStats() assy.tree.init_statistics(stats) assy.tree.getstatistics(stats) assert stats.natoms == self.TESTDATA["numatoms"] assert stats.nchunks == self.TESTDATA["numchunks"] def testSavePdbFile(self): foo.saveFile("/tmp/foo.pdb") self.countLines("ATOM", "pdb", self.TESTDATA["numatoms"]) # I'd count the CONECT lines too, but for large structures # that number varies. I don't know if that's a legitimate # failure of the test, or a funny (but legit) behavior of # the file format. os.system("rm /tmp/foo.pdb") def testSaveMmpFile(self): foo.saveFile("/tmp/foo.mmp") self.countLines("atom", "mmp", self.TESTDATA["numatoms"]) self.countLines("bond", "mmp", self.TESTDATA["bondLines"]) self.extraSaveMmpTest() os.system("rm /tmp/foo.mmp") ###################### class FileTestBigStructure(FileTest): TESTDATA = { "filename": "../partlib/pumps/Pump.mmp", "numatoms": 6165, "bondLines": 4417, "numchunks": 2, } def extraSaveMmpTest(self): assert self.getLines("^mol ", "mmp") == [ "mol (Pump Casing) def\n", "mol (Pump Rotor) def\n" ] ###################### if __name__ == "__main__": runner = unittest.TextTestRunner() suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(FileTest, "test")) suite.addTest(unittest.makeSuite(FileTestBigStructure, "test")) runner.run(suite)
NanoCAD-master
cad/tests/filetest.py
import unittest from VQT import angleBetween from Numeric import array, alltrue class GeometryFunctionsTestCase(unittest.TestCase): """Unit tests for the geometry functions defined in VQT.py""" def setUp(self): """Sets up any objects needed by this test case.""" pass def tearDown(self): """Releases any resources used by this test case.""" pass def testAngleBetween(self): vector1 = array((1, 0, 0)) vector2 = array((0, 1, 0)) angle = angleBetween(vector1, vector2) assert angle == 90, "Fails sanity check" assert alltrue(vector1 == array((1, 0, 0))) and \ alltrue(vector2 == array((0, 1, 0))), \ "Arguments were modified (recurrence of bug ####)" if __name__ == "__main__": unittest.main() # Run all tests whose names begin with 'test'
NanoCAD-master
cad/tests/VQT_Test.py
# Copyright 2005, 2007 Nanorex, Inc. See LICENSE file for details. import unittest import chem import assembly import Utility import debug from elements import PeriodicTable Hydrogen = PeriodicTable.getElement(1) Carbon = PeriodicTable.getElement(6) Nitrogen = PeriodicTable.getElement(7) Oxygen = PeriodicTable.getElement(8) Singlet = PeriodicTable.getElement(0) ########################## # Avoid this: # QPaintDevice: Must construct a QApplication before a QPaintDevice class DummyPixmap: def __init__(self, iconpath): pass Utility.QPixmap = DummyPixmap ######################### # enforce API protection debug.privateMethod = debug._privateMethod # We could do this in $HOME/.atom-debug-rc and avoid the need for # the boolean altogether. ######################### if False: # Make sure the tests are really working # Passivate no longer transmutes atoms # so testPassivate should break def passivate(self): pass chem.Atom.Passivate = passivate ######################### def countElements(mol, d): """In a molecule, verify the numbers of atoms with given element names. """ for name in d.keys(): expectedCount = d[name] count = 0 for a in mol.atlist: if a.element.name == name: count += 1 assert count == expectedCount class ChemTest(unittest.TestCase): """Various tests of chemistry bookkeeping """ def setUp(self): self.assy = assy = assembly.assembly(None) self.mol = mol = chem.molecule(assy) self.a = a = chem.Atom("C", chem.V(0.0, 0.0, 0.0), mol) self.a.set_atomtype("sp3", True) def testInitialCounts(self): countElements(self.mol, {"Carbon": 1, "Hydrogen": 0, "Singlet": 4}) def testPassivate(self): self.a.Passivate() assert self.a.element.name == "Neon" def testHydrogenate(self): self.mol.Hydrogenate() countElements(self.mol, {"Carbon": 1, "Hydrogen": 4, "Singlet": 0}) def testDehydrogenate(self): self.testHydrogenate() self.mol.Dehydrogenate() self.testInitialCounts() if __name__ == "__main__": suite = unittest.makeSuite(ChemTest, "test") runner = unittest.TextTestRunner() runner.run(suite)
NanoCAD-master
cad/tests/chemtest.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ splitting_a_mode.py -- explanation/demo of how to split an old mode, while maintaining temporary compatibility with non-split methods and subclass modes. @author: Bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. This file can be deleted after all NE1 modes have been split. Status: I think it's right, but I didn't test it. """ # context & basic concepts: not described here. # terminology: C = Command, GM = GraphicsMode. # The goal is that for each old mode, we have 5 new classes -- 2 main classes # (its C and GM parts), and 3 "glue" classes that help initialize it -- # one for C-alone, one for GM-alone, and one for a mixed object that has # both C and GM parts in one instance. # # For example, for basicMode these classes are: # - basicCommand (main C class) # - Command (C-alone glue class) # - basicGraphicsMode (main GM class) # - GraphicsMode (GM-alone glue class) # - basicMode (mixed C/GM glue class) # The reason we need this is that each glue class has to inherit different # superclasses and have different __init__ methods. The main differences are # in how they set up the "cross reference attributes", command.graphicsMode # and graphicsMode.command, and in whether a command instance has to create # a new graphicsMode instance. In a mixed object, the command *is* the # graphicsMode, so it should not create a new one, and each cross-reference # attribute should be a property pointing to self. In a used-alone object, # the __init__ method should set up the cross-reference attribute to point # to another object, and in the command case, it has to create that object # as a new instance of self.GraphicsMode_class. # (One other requirement might be some superclasses just for isinstance tests, # or to revise isinstance tests in other code, probably to just look for the # basicCommand or basicGraphicsMode part depending on whether they test the # "current command" or the "current graphicsMode".) # The mixed object is only needed for compatibility with non-split subclasses # and to work around bugs from an incomplete split. When it's no longer needed, # the mixed glue class can be removed, and the other glue classes can be merged # into the corresponding main classes, with the simpler names retained. # # So when basicMode is no longer needed, we'll delete its file (modes.py), # and merge basicCommand and Command (retaining the name Command), # and merge basicGraphicsMode and GraphicsMode (retaining the name # GraphicsMode). But this can only happen when all subclasses are split, i.e. # when every mode in NE1 is split. # === # So, here is how this should be done with selectMode. # After that, we'll show how to do it with its subclass selectMolsMode. # First define classes which can work in either split C & GM form, or mixed form, # which have most of the methods for each side. Each one has an init method which # can call its superclass's init method, but which should not call any of the # "glue init methods" in the superclass. The init methods should have the same # arg signature as in their superclass. # (In real life, these would go into different files, described later. # For clarity in this demo, they are all in one file.) # We do the graphics part first since the command part has to refer to it. # # Its superclass, in general, should be another _basicGraphicsMode class. # (In fully split modes that don't need mixed versions, it can also be the # value of command_superclass.GraphicsMode_class where command_superclass # is what the corresponding Command class inherits, or it can just be a # non-basic GraphicsMode class named directly, which should be the # same one used in the command superclass. But for modes with mixed versions, # it should just be the basicGraphicsMode version of the superclass # GraphicsMode.) class Select_basicGraphicsMode(basicGraphicsMode): def __init__(self, glpane): """ """ basicGraphicsMode.__init__(self, glpane) # Now do whatever might be needed to init the graphicsMode object, # or the graphicsMode-related attrs of the mixed object. # # (Similar comments apply as for Select_basicCommand.__init__, below, # but note that for GraphicsModes, there is no Enter method. # Probably we will need to add something like an Enter_graphicsMode # method to the GraphicsMode API. In the meantime, the command's Enter # method has to initialize the graphicsMode object's attrs (which are # the graphics-related attrs of self, in the mixed case, but are # referred to as self.graphicsMode.attr so this will work in the split # case as well), which is a kluge.) return # Now put all the methods from the "graphics area half" of the original # mode -- anything related to graphics, mouse events, cursors (for use in # graphics area), key bindings or context menu (for use in graphics area). def Draw(self, args): pass def someMouseMethod(self, args): pass def someCursorMethod(self, args): pass # etc # The command part should in general inherit a _basicCommand superclass. # Since selectMode inherited basicMode, we have Select_basicCommand inherit # basicCommand; # in comparison (done below), selectMolsMode inherited selectMode, so we'd # make SelectChunks_basicCommand and inherit Select_basicCommand. class Select_basicCommand(basicCommand): def __init__(self, commandSequencer): """ ... """ basicCommand.__init__(self, commandSequencer) # Now do whatever might be needed to init the command object, # or in the mixed case, the command-related attrs of the mixed object. # That might be nothing, since most attrs can just be initialized in # Enter, since they should be reinitialized every time we enter the # command anyway. # (If it's nothing, we probably don't need this method, but it's ok # to have it for clarity, especially if there is more than one # superclass.) return # Now put all the methods from the "command half" of the original # mode -- anything related to its property manager, its settings or # state, the model operations it does (unless those are so simple # that the mouse event bindings in the _GM half can do them directly # and the code is still clean, *and* no command-half subclass needs # to override them). def Enter(self, args): pass # etc # Every method in the original mode goes into one of these halves, # or gets split into two methods (with different names), one for # each half. If a method gets split, old code that called it (perhaps # in other files) needs to call both split methods, or one of them # needs to call the other. This requires some thought in each case # when it has to be done. pass # == # Now we have to make the 3 glue classes. # Their __init__ methods and properties can each be copied # from the pattern used to split basicMode. # Note that we call a "glue" __init__ method only in the "sub-most class" # (the class we're actually instantiating); all superclass __init__ methods # we call are in one of the _basicCommand or _basicGraphicsMode superclasses. class Select_GraphicsMode( Select_basicGraphicsMode): """ Glue class for GM-alone usage only """ # Imitate the init and property code in GraphicsMode, but don't inherit it. # (Remember to replace all the occurrences of its superclass with our own.) # (When this is later merged with its superclass, most of this can go away # since we'll then be inheriting GraphicsMode here.) # (Or can we inherit GraphicsMode *after* the main superclass, and not have # to do some of this? I don't know. ### find out! [I think I did this in PanLikeMode.] # At least we'd probably still need this __init__ method. # If this pattern works, then in *our* subclasses we'd instead post-inherit # this class, Select_GraphicsMode.) def __init__(self, command): self.command = command glpane = self.command.glpane Select_basicGraphicsMode.__init__(self, glpane) return # (the rest would come from GraphicsMode if post-inheriting it worked, # or we could split it out of GraphicsMode as a post-mixin to use there and here) def _get_commandSequencer(self): return self.command.commandSequencer commandSequencer = property(_get_commandSequencer) def set_cmdname(self, name): self.command.set_cmdname(name) return def _get_hover_highlighting_enabled(self): return self.command.hover_highlighting_enabled def _set_hover_highlighting_enabled(self, val): self.command.hover_highlighting_enabled = val hover_highlighting_enabled = property(_get_hover_highlighting_enabled, _set_hover_highlighting_enabled) pass class Select_Command( Select_basicCommand): """ Glue class for C-alone usage only """ # This is needed so the init code knows what kind of GM to make. GraphicsMode_class = Select_GraphicsMode # Imitate the init and property code in Command, but don't inherit it. # (Remember to replace all the occurrences of its superclass with our own.) # (When this is later merged with its superclass, most of this can go away # since we'll then be inheriting Command here.) # (Or can we inherit Command *after* the main superclass, and not have # to do some of this? I don't know. ### find out! [I think I did this in PanLikeMode.] # At least we'd probably still need this __init__ method. # If this pattern works, then in *our* subclasses we'd instead post-inherit # this class, Select_Command.) def __init__(self, commandSequencer): Select_basicCommand.__init__(self, commandSequencer) self._create_GraphicsMode() self._post_init_modify_GraphicsMode() return # (the rest would come from Command if post-inheriting it worked, # or we could split it out of Command as a post-mixin to use there and here) def _create_GraphicsMode(self): GM_class = self.GraphicsMode_class assert issubclass(GM_class, GraphicsMode_API) args = [self] kws = {} self.graphicsMode = GM_class(*args, **kws) pass def _post_init_modify_GraphicsMode(self): pass pass class selectMode( Select_basicCommand, Select_basicGraphicsMode, anyMode): # might need more superclasses for isinstance? """ Glue class for mixed C/GM usage only """ # Imitate the init and property code in basicMode, but don't inherit it. # (Remember to replace all the occurrences of one of its two main # superclasses with the corresponding one of our own.) # (When we no longer need the mixed-C/GM case, this class can be discarded.) # (Or can we inherit basicMode *after* the main superclasses, and not have # to do some of this? I don't know. ### find out! [I think I did this in PanLikeMode.] # At least we'd still need this __init__ method. ) def __init__(self, glpane): assert GLPANE_IS_COMMAND_SEQUENCER: commandSequencer = glpane Select_basicCommand.__init__(self, commandSequencer) # was just basicCommand in original Select_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) pass # putting these into the right files: # in Select_Command we want that class, but first its basic version, Select_basicCommand. # in Select_GraphicsMode we want that class, but first, Select_basicGraphicsMode. # and in selectMode.py (same name as original mode) we want class selectMode as above. # And several imports are needed to make this work, but they should be obvious # from the NameErrors that come from forgetting them, e.g. of GLPANE_IS_COMMAND_SEQUENCER, # anyMode, other superclasses. # == # For SelectChunks, we'd make, in 3 files, and following the above pattern, # but revising all superclass occurrences: # SelectChunks_Command.py: # SelectChunks_basicCommand inheriting Select_basicCommand # SelectChunks_Command inheriting SelectChunks_basicCommand # SelectChunks_GraphicMode.py # SelectChunks_basicGraphicsMode inheriting Select_basicGraphicsMode # SelectChunks_GraphicMode inheriting SelectChunks_basicGraphicsMode # selectMolsMode.py (same name as old file): # selectMolsMode, inheriting SelectChunk_basicCommand, SelectChunks_basicGraphicsMode # == # If this all works right, then recombined versions of split/recombined mode classes will # keep working with no problem at all, and so will their non-split subclasses, # with no changes at all (except perhaps in isinstance tests). # Not covered above: # # - when you'd need to add more stuff to the glue classes than what is copied/modified from their superclasses # # - how to use debug_prefs to test either _Command or mixed classes -- basically, # maybe easiest to use a hardcoded assignment instead, to put the _Command class into the GLPane list of modes # (I think that's right -- check what's done for PanMode etc to be sure) # # - what will still not work in the split case -- uses of one part's method or attr from the other part -- # easiest fix is to change self.attr to self.command.attr for a command attr used in the GM part, # and to change self.attr to self.graphicsMode.attr for a GM attr used in the C part. # or you can use a property in a single place in the alone-case glue class. # But you have to decide where an attr belongs; it's not always obvious, # e.g. hover_highlighting_enabled belongs in C part though it's mainly used in GM part, # since C part is what wants to set it in certain circumstances. # # - I think there was something else I forgot. # == # end
NanoCAD-master
cad/doc/splitting_a_mode.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ _import_roots.py - import all toplevel files in the import dependency hierarchy @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Note: most of the files we import here are for separate main programs, never normally imported into one process; this file exists for the use of import dependency analysis tools, especially so they will not think these files are no longer needed in cad/src, and so text searches for references to these files (e.g. when renaming them) will find their entries in this list. Note: all entries in this file should be signed and dated by whoever adds or maintains them (the entries, not the imported files), with a comment which mentions why they are needed (except when it's obvious, like for main.py). When no longer needed, they should be removed. """ # Note: our toplevel package 'commands' # has the same name as a module in the Python 2.3 library. # ('commands' is Unix only (including Mac), and probably old.) # # This is a potential problem for anything which might want to # import both our package and the Python library module with # the same name, and it has impacts on ordering of sys.path # for something which wants to import either one (e.g. NE1, # or any script which imports anything from NE1, such as certain # build scripts). # # (The problem can even occur for a non-toplevel package name, # but only if NE1 itself wants to import the builtin or Python library # module of the same basename.) # # In the long run, this ought to be cleaned up, perhaps by renaming # our toplevel packages to avoid those conflicts, and/or making use # of new import features in later versions of Python, e.g. the new # more precise kinds of relative imports like "from .. import x". # # In the meantime, this situation needs to be monitored as we port # to newer versions of Python. # (It got a lot better as of 080708, when we renamed 'platform' # to 'platform_dependent'.) # # [bruce 080602 comment, revised 080710] import main # the NE1 main program file import ExecSubDir # a Python script which needs to remain in cad/src # [bruce 071008] import modelTree.Node_api #bruce 081216, unused but not yet an outtake # end
NanoCAD-master
cad/src/_import_roots.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ NE1_Build_Constants.py is intended to be a very small file which consists of only the data that is likely to change for any given release, including anything which might be changed (manually or automatically) during the process of building a release itself. None other than system imports should be used without good reason. @note: This file is updated by the NE1 installer build scripts. Do not edit this file manually. @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ NE1_RELEASE_VERSION = "1.1.1" NE1_RELEASE_DATE = "August 11, 2008" NE1_OFFICIAL_RELEASE_CANDIDATE = 0 NE1_USE_bsddb3 = False NE1_CONSOLE_REDIRECT = False
NanoCAD-master
cad/src/NE1_Build_Constants.py
#!/usr/bin/env python # Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ ExecSubDir.py This is an odd little utility that might appear to do absolutely nothing. All it does is call execfile() on its first argument. It puts more effort into validating that it has an argument than what it does to that argument. So, what is this good for? Its entire purpose is to fiddle with the module search path. All of the python source files in the program expect to be imported with the cad/src directory on the search path. If you were to load a file from a subdirectory using: python subdir/module.py, for example, then subdir would be on the search path, but its parent directory wouldn't. This would make imports of main directory modules fail (or worse, get the wrong files, if we ever permit non-unique module basenames). Instead, you can say: ./ExecSubDir.py subdir/module.py, and it will get it right. @author: Eric Messick @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. """ import sys if (__name__ == '__main__'): if (len(sys.argv) < 2): print >> sys.stderr, "usage: %s fileToRun.py" % sys.argv[0] sys.exit(1) execfile(sys.argv[1])
NanoCAD-master
cad/src/ExecSubDir.py
#! /usr/bin/python # Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ main.py -- the initial startup file for NanoEngineer-1, treated specially by the release-building process. $Id$ This file should not be imported as the "main" module -- doing so prints a warning [as of 050902] and doesn't run the contained code. If necessary, it can be imported as the __main__ module from within the NE1 process it starts, by "import __main__". Such an import doesn't rerun the contained code -- only reload(__main__) would do that, and that should not be done. Depending on the details of the package building process, this file might be renamed and/or moved to a different directory from the other modules under cad/src. As of 050902, it's always moved to a different directory (by package building on any platform), and this is detected at runtime (using __main__.__file__) as a way of distinguishing end-user runs from developer runs [by code now located somewhere inside the startup package, as of 071008]. When an end-user runs the NE1 application, OS-dependent code somehow starts the right python interpreter and has it execute this file (possibly passing command-line arguments, but that might not be implemented yet). Developers running NE1 from svn can run this script using a command line like "python main.py" or "pythonw main.py", depending on the Python installation. Some Python or Qt installations require that the absolute pathname of main.py be used, but the current directory should always be the one containing this file, when it's run manually in this way. This file then imports and starts everything else, via the function startup_script defined in main_startup.py. As of 041217 everything runs in one OS process, except for occasional temporary subprocesses it might start. History: mostly unrecorded, except in cvs/svn; originally by Josh; lots of changes by various developers at various times. renamed from atom.py to main.py before release of A9, mid-2007. bruce 070704 moved most of this file into main_startup.py. bruce 071008 moved a long comment into a new file ne1_startup/ALTERNATE_CAD_SRC_PATH-doc.txt, and enclosed our own startup code into def _start_NE1(). """ # NOTE: DON'T ADD ANY IMPORTS TO THIS FILE besides those already present # (as of 071002), since doing so would cause errors in the semantics of # the ALTERNATE_CAD_SRC_PATH feature and (possibly) in the function # before_most_imports called inside the startup script. New imports needed # by startup code, or needed (for side effects) early during startup, should # be added to the appropriate place in one of the modules in the startup # package. import sys, os, time print print "starting NanoEngineer-1 in [%s]," % os.getcwd(), time.asctime() print "using Python: " + sys.version try: print "on path: " + sys.executable except: pass if __name__ != '__main__': print print "Warning: main.py should not be imported except as the __main__ module." print " (It is now being imported under the name %r.\n" \ " This is a bug, but should cause no direct harm.)" % (__name__,) print # ALTERNATE_CAD_SRC_PATH feature: # # (WARNING: this MUST BE entirely implemented in main.py) # # for documentation and implementation notes, see # ne1_startup/ALTERNATE_CAD_SRC_PATH-doc.txt # and # http://www.nanoengineer-1.net/mediawiki/index.php?title=Using_the_Libraries_from_an_NE1_Installation_for_Mac_Development # # [bruce 070704 new feature; intended for A9.2 release; UNTESTED except on Mac] _alternateSourcePath = None try: _main_path = __file__ # REVIEW: this might fail in Windows release build _main_dir = os.path.dirname( _main_path) _path_of_alt_path_file = os.path.join( _main_dir, "ALTERNATE_CAD_SRC_PATH" ) if os.path.isfile( _path_of_alt_path_file): print "found", _path_of_alt_path_file _fp = open( _path_of_alt_path_file, "rU") _content = _fp.read().strip() _fp.close() _content = os.path.normpath( os.path.abspath( _content)) print "containing pathname %r" % (_content,) if os.path.isdir(_content): _alternateSourcePath = _content else: print "which is not a directory, so will be ignored" print pass except: print "exception (discarded) in code for supporting ALTERNATE_CAD_SRC_PATH feature" ## raise # useful for debugging ### REVIEW: remove print or fix implementation, if an exception here # happens routinely on other platforms' release builds def _start_NE1(): if _alternateSourcePath is not None: print print "WILL USE ALTERNATE_CAD_SRC_PATH = %r" % ( _alternateSourcePath,) sys.path.insert(0, _alternateSourcePath) # see ne1_startup/ALTERNATE_CAD_SRC_PATH-doc.txt for info about other # effects of this (implemented by setAlternateSourcePath below) print # NOTE: imports of NE1 source modules MUST NOT BE DONE until after the # optional sys.path change done for _alternateSourcePath, just above. import utilities.EndUser as EndUser EndUser.setAlternateSourcePath(_alternateSourcePath) _main_globals = globals() # needed by startup_script from ne1_startup.main_startup import startup_script startup_script( _main_globals ) return if __name__ == '__main__': _start_NE1() # end
NanoCAD-master
cad/src/main.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_ElementChooser.py @author: Mark Sims @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-08-03: Created. """ from PM.PM_MolecularModelingKit import PM_MolecularModelingKit from PyQt4.Qt import SIGNAL, QSpacerItem, QSizePolicy from PM.PM_ToolButtonGrid import PM_ToolButtonGrid # Elements button list to create elements tool button group. # Format: # - button type # - buttonId (element number), # - buttonText (element symbol), # - iconPath # - tooltip (element name) # - shortcut # - column # - row ELEMENTS_BUTTON_LIST = [ \ ( "QToolButton", 1, "H", "", "Hydrogen (H)", "H", 4, 0 ), ( "QToolButton", 2, "He", "", "Helium", None, 5, 0 ), ( "QToolButton", 5, "B", "", "Boron (B)", "B", 0, 1 ), ( "QToolButton", 6, "C", "", "Carbon (C)", "C", 1, 1 ), ( "QToolButton", 7, "N", "", "Nitrogen (N)", "N", 2, 1 ), ( "QToolButton", 8, "O", "", "Oxygen (O)", "O", 3, 1 ), ( "QToolButton", 9, "F", "", "Fluorine (F)", "F", 4, 1 ), ( "QToolButton", 10, "Ne", "", "Neon", None, 5, 1 ), ( "QToolButton", 13, "Al", "", "Aluminum (A)", "A", 0, 2 ), ( "QToolButton", 14, "Si", "", "Silicon (Q)", "Q", 1, 2 ), ( "QToolButton", 15, "P", "", "Phosphorus (P)", "P", 2, 2 ), ( "QToolButton", 16, "S", "", "Sulfur (S)", "S", 3, 2 ), ( "QToolButton", 17, "Cl", "", "Chlorine (L)", "L", 4, 2 ), ( "QToolButton", 18, "Ar", "", "Argon", None, 5, 2 ), ( "QToolButton", 32, "Ge", "", "Germanium", "G", 1, 3 ), ( "QToolButton", 33, "As", "", "Arsenic", None, 2, 3 ), ( "QToolButton", 34, "Se", "", "Selenium", None, 3, 3 ), ( "QToolButton", 35, "Br", "", "Bromine" , None, 4, 3 ), ( "QToolButton", 36, "Kr", "", "Krypton", None, 5, 3 ) ] ELEMENT_ATOM_TYPES = { \ 6: ("sp3", "sp2", "sp" ), 7: ("sp3", "sp2", "sp", "sp2(graphitic)"), 8: ("sp3", "sp2", "sp2(-)", "sp2(-.5)" ), 15: ("sp3", "sp3(p)" ), 16: ("sp3", "sp2" ) } ATOM_TYPES = ("sp3", "sp2", "sp", "sp2(graphitic)", "sp3(p)", "sp2(-)", "sp2(-.5)") # Atom types (hybrids) button list to create atom types tool button group. # Format: # - buttonId (hybrid number) # - buttonText (hybrid symbol) # - iconPath # - tooltip (full hybrid name) # - shortcut # - column # - row ATOM_TYPES_BUTTON_LIST = [ \ ( "QToolButton", 0, "sp3", "", "sp3", None, 0, 0 ), ( "QToolButton", 1, "sp2", "", "sp2", None, 1, 0 ), ( "QToolButton", 2, "sp", "", "sp", None, 2, 0 ), ( "QToolButton", 3, "sp2(graphitic)", "ui/actions/Properties Manager/N_graphitic.png", "Graphitic", None, 3, 0 ), ( "QToolButton", 4, "sp3(p)", "", "sp3(phosphate)", None, 4, 0 ), ( "QToolButton", 5, "sp2(-)", "", "sp2(-)", None, 5, 0 ), ( "QToolButton", 6, "sp2(-.5)", "", "sp2(-.5)", None, 6, 0 ), ] # How to add a new hybridization of an element to the UI: # First, create the hybridization in model/elements_data.py. See the # comments there for how to do this. # Next, add the hybridization to ELEMENT_ATOM_TYPES above. The # indices are the element numbers in the ELEMENTS_BUTTON_LIST. # Next, make sure the hybridization appears in the ATOM_TYPES list and # the ATOM_TYPES_BUTTON_LIST. There are two indices that should # increment by one for each line. You may wish to add an icon graphic # if the string does not fit entirely within the button. class PM_ElementChooser( PM_MolecularModelingKit ): """ The PM_ElementChooser widget provides an Element Chooser widget, contained in its own group box, for a Property Manager dialog. A PM_ElementChooser is a selection widget that displays all elements, including their atom types (atomic hybrids), supported in NE1. Methods are provided to set and get the selected element and atom type (e.g., L{setElement()}, L{getElement()}, L{getElementNumber()} and L{getElementSymbolAndAtomType()}). @cvar element: The current element. @type element: Elem @cvar atomType: The current atom type of the current element. @type atomType: str @see: B{elements.py} """ def __init__(self, parentWidget, parentPropMgr = None, title = "", element = "Carbon", elementViewer = None ): """ Appends a PM_ElementChooser widget to the bottom of I{parentWidget}, a Property Manager dialog. (or as a sub groupbox for Atom Chooser GroupBox.) @param parentWidget: The parent PM_Dialog or PM_groupBox containing this widget. @type parentWidget: PM_Dialog or PM_GroupBox @param parentPropMgr: The parent Property Manager @type parentPropMgr: PM_Dialog or None @param title: The button title on the group box containing the Element Chooser. @type title: str @param element: The initially selected element. It can be either an element symbol or name. @type element: str """ PM_MolecularModelingKit.__init__( self, parentWidget, parentPropMgr, title, element, elementViewer) def _addGroupBoxes(self): """ Add various groupboxes present inside the ElementChooser groupbox """ self._addElementsGroupBox(self) self._addAtomTypesGroupBox(self) def _addAtomTypesGroupBox(self, inPmGroupBox): """ Creates a row of atom type buttons (i.e. sp3, sp2, sp and graphitic). @param inPmGroupBox: The parent group box to contain the atom type buttons. @type inPmGroupBox: PM_GroupBox """ self._atomTypesButtonGroup = \ PM_ToolButtonGrid( inPmGroupBox, buttonList = self.getAtomTypesButtonList(), label = "Atomic hybrids:", checkedId = 0, setAsDefault = True ) #Increase the button width for atom hybrids so that # button texts such as sp3(p), sp2(-), sp2(-.5) fit. # This change can be removed once we have icons # for the buttons with long text -- Ninad 2008-09-04 self._atomTypesButtonGroup.setButtonSize(width = 44) # Horizontal spacer to keep buttons grouped close together. _hSpacer = QSpacerItem( 1, 32, QSizePolicy.Expanding, QSizePolicy.Fixed ) self._atomTypesButtonGroup.gridLayout.addItem( _hSpacer, 0, 4, 1, 1 ) self.connect( self._atomTypesButtonGroup.buttonGroup, SIGNAL("buttonClicked(int)"), self._setAtomType ) self._updateAtomTypesButtons() def _updateAtomTypesButtons(self): """ Updates the hybrid buttons based on the currently selected element button. """ currentElementNumber = self.getElementNumber() if ELEMENT_ATOM_TYPES.has_key(currentElementNumber): elementAtomTypes = ELEMENT_ATOM_TYPES[currentElementNumber] else: # Selected element has no hybrids. elementAtomTypes = [] self.atomType = "" for atomType in ATOM_TYPES: button = self._atomTypesButtonGroup.getButtonByText(atomType) if atomType in elementAtomTypes: button.show() if atomType == elementAtomTypes[0]: # Select the first atomType button. button.setChecked(True) self.atomType = atomType else: button.hide() self._updateAtomTypesTitle() def _updateAtomTypesTitle(self): """ Updates the title for the Atom Types group box. """ title = "Atomic Hybrids for " + self.element.name + ":" self._atomTypesButtonGroup.setTitle(title) def _setAtomType(self, atomTypeIndex): """ Set the current atom type. @param atomTypeIndex: The atom type index, where: 0 = sp3, 1 = sp2, 2 = sp, 3 = sp2(graphitic) @type atomTypeIndex: int @note: Calling this method does not update the atom type buttons. """ self.atomType = ATOM_TYPES[atomTypeIndex] self.updateElementViewer() def getElementsButtonList(self): """ Return the list of buttons in the Element chooser. @return: List containing information about the element tool buttons @rtype: list """ return ELEMENTS_BUTTON_LIST def getAtomTypesButtonList(self): """ Return the list of buttons for the various atom types (hybrids) of the selected atom in the Element chooser. @return: List containing information about the toolbuttons for the atom types (hybrids) of the selected atom in the element chooser. @rtype: list """ return ATOM_TYPES_BUTTON_LIST
NanoCAD-master
cad/src/PM/PM_ElementChooser.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_ComboBox.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrComboBox out of PropMgrBaseClass.py into this file and renamed it PM_ComboBox. """ from PyQt4.Qt import QComboBox from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget class PM_ComboBox( QComboBox ): """ The PM_ComboBox widget provides a combobox with a text label for a Property Manager group box. The text label can be positioned on either the left or right side of the combobox. A combobox is a combined button and popup list that provides a means of presenting a list of options to the user in a way that takes up the minimum amount of screen space. Also, a combobox is a selection widget that displays the current item, and can pop up a list of selectable items. A combobox may be editable, allowing the user to modify each item in the list. Comboboxes can contain pixmaps as well as strings; the insertItem() and changeItem() functions are suitably overloaded. For editable comboboxes, the function clearEdit() is provided, to clear the displayed string without changing the combobox's contents. There are two signals emitted if the current item of a combobox changes, currentIndexChanged() and activated(). currentIndexChanged() is always emitted regardless if the change was done programmatically or by user interaction, while activated() is only emitted when the change is caused by user interaction. The highlighted() signal is emitted when the user highlights an item in the combobox popup list. All three signals exist in two versions, one with a U{B{QString}<http://doc.trolltech.com/4/qstring.html>} argument and one with an int argument. If the user selectes or highlights a pixmap, only the int signals are emitted. Whenever the text of an editable combobox is changed the editTextChanged() signal is emitted. When the user enters a new string in an editable combobox, the widget may or may not insert it, and it can insert it in several locations. The default policy is is AtBottom but you can change this using setInsertPolicy(). It is possible to constrain the input to an editable combobox using U{B{QValidator}<http://doc.trolltech.com/4/qvalidator.html>} ; see setValidator(). By default, any input is accepted. A combobox can be populated using the insert functions, insertStringList() and insertItem() for example. Items can be changed with changeItem(). An item can be removed with removeItem() and all items can be removed with clear(). The text of the current item is returned by currentText(), and the text of a numbered item is returned with text(). The current item can be set with setCurrentIndex(). The number of items in the combobox is returned by count(); the maximum number of items can be set with setMaxCount(). You can allow editing using setEditable(). For editable comboboxes you can set auto-completion using setCompleter() and whether or not the user can add duplicates is set with setDuplicatesEnabled(). PM_ComboBox uses the model/view framework for its popup list and to store its items. By default a QStandardItemModel stores the items and a QListView subclass displays the popuplist. You can access the model and view directly (with model() and view()), but PM_ComboBox also provides functions to set and get item data (e.g., setItemData() and itemText()). You can also set a new model and view (with setModel() and setView()). For the text and icon in the combobox label, the data in the model that has the Qt.DisplayRole and Qt.DecorationRole is used. @cvar defaultChoices: The default choices of the combobox. @type defaultChoices: list @cvar defaultIndex: The default index of the combobox. @type defaultIndex: int @cvar setAsDefault: Determines whether to reset the choices to I{defaultChoices} and currentIndex to I{defaultIndex} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this combobox. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @see: U{B{QComboBox}<http://doc.trolltech.com/4/qcombobox.html>} """ defaultIndex = 0 defaultChoices = [] setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, choices = [], index = 0, setAsDefault = True, spanWidth = False ): """ Appends a QComboBox widget (with a QLabel widget) to <parentWidget>, a property manager group box. Arguments: @param parentWidget: the group box containing this PM widget. @type parentWidget: PM_GroupBox @param label: label that appears to the left of (or above) this PM widget. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param choices: list of combo box choices (strings). @type choices: list @param index: initial index (choice) of combobox. (0=first item) @type index: int (default 0) @param setAsDefault: if True, will restore <index> as the current index when the "Restore Defaults" button is clicked. @type setAsDefault: bool (default True) @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) @see: U{B{QComboBox}<http://doc.trolltech.com/4/qcombobox.html>} """ if 0: # Debugging code print "PM_ComboBox.__init__():" print " label =", label print " choices =", choices print " index =", index print " setAsDefault =", setAsDefault print " spanWidth =", spanWidth QComboBox.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Load QComboBox widget choices and set initial choice (index). for choice in choices: self.addItem(choice) self.setCurrentIndex(index) # Set default index self.defaultIndex = index self.defaultChoices = choices self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.clear() # Generates signals! for choice in self.defaultChoices: self.addItem(choice) self.setCurrentIndex(self.defaultIndex) def hide(self): """ Hides the combobox and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the combobox and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() def setCurrentIndex(self, val, blockSignals = False): """ Overrides the superclass method. @param blockSignals: Many times, the caller just wants to setCurrentIndex and don't want to send valueChanged signal. If this flag is set to True, the currentIdexChanged signal won't be emitted. The default value is False. @type blockSignals: bool @see: DnaDisplayStyle_PropertyManager.updateDnaDisplayStyleWidgets() """ #If blockSignals flag is True, the valueChanged signal won't be emitted #This is done by self.blockSignals method below. -- Ninad 2008-08-13 self.blockSignals(blockSignals) QComboBox.setCurrentIndex(self, val) #Make sure to always 'unblock' signals that might have been temporarily #blocked before calling superclass.setValue. self.blockSignals(False) # End of PM_ComboBox ############################
NanoCAD-master
cad/src/PM/PM_ComboBox.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ PM_DoubleSpinBox.py @author: Mark @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrDoubleSpinBox out of PropMgrBaseClass.py into this file and renamed it PM_DoubleSpinBox. """ from PyQt4.Qt import QDoubleSpinBox from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget from widgets.prefs_widgets import widget_connectWithState from widgets.prefs_widgets import QDoubleSpinBox_ConnectionWithState from widgets.prefs_widgets import set_metainfo_from_stateref class PM_DoubleSpinBox( QDoubleSpinBox ): """ The PM_DoubleSpinBox widget provides a QDoubleSpinBox (with an optional label) for a Property Manager group box. Detailed Description ==================== The PM_DoubleSpinBox class provides a spin box widget (with an optional label) for a U{B{Property Manager dialog}<http://www.nanoengineer-1.net/mediawiki/ index.php?title=Property_Manager>} that takes floats. PM_DoubleSpinBox allows the user to choose a value by clicking the up and down buttons or by pressing Up or Down on the keyboard to increase or decrease the value currently displayed. The user can also type the value in manually. The spin box supports float values but can be extended to use different strings with validate(), textFromValue() and valueFromText(). Every time the value changes PM_DoubleSpinBox emits the valueChanged() signal.The current value can be fetched with value() and set with setValue() Note: PM_DoubleSpinBox will round numbers so they can be displayed with the current precision. In a PM_DoubleSpinBox with decimals set to 2, calling setValue(2.555) will cause value() to return 2.56. Clicking the up and down buttons or using the keyboard accelerator's Up and Down arrows will increase or decrease the current value in steps of size singleStep(). If you want to change this behavior you can reimplement the virtual function stepBy(). The minimum and maximum value and the step size can be set using one of the constructors, and can be changed later with setMinimum(), setMaximum() and setSingleStep(). The spin box has a default precision of 2 decimal places but this can be changed using setDecimals(). Most spin boxes are directional, but PM_DoubleSpinBox can also operate as a circular spin box, i.e. if the range is 0.0-99.9 and the current value is 99.9, clicking "up" will give 0 if wrapping() is set to true. Use setWrapping() if you want circular behavior. The displayed value can be prepended and appended with arbitrary strings indicating, for example, currency or the unit of measurement. See setPrefix() and setSuffix(). The text in the spin box is retrieved with text() (which includes any prefix() and suffix()), or with cleanText() (which has no prefix(), no suffix() and no leading or trailing whitespace). It is often desirable to give the user a special (often default) choice in addition to the range of numeric values. See setSpecialValueText() for how to do this with PM_DoubleSpinBox. @see: U{B{QDoubleSpinBox}<http://doc.trolltech.com/4/qdoublespinbox.html>} @cvar defaultValue: The default value of the spin box. @type defaultValue: float @cvar setAsDefault: Determines whether to reset the value of the spin box to I{defaultValue} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this spin box. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultValue = 0.0 setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 99.0, singleStep = 1.0, decimals = 1, suffix = '', spanWidth = False ): """ Appends a QDoubleSpinBox (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the spin box. If label contains the relative path to an icon (.png) file, that icon image will be used for the label. If spanWidth is True, the label will be displayed on its own row directly above the spin box. To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param value: The initial value of the spin box. @type value: float @param setAsDefault: If True, will restore I{value} when the "Restore Defaults" button is clicked. @type setAsDefault: bool @param minimum: The minimum value of the spin box. @type minimum: float @param maximum: The maximum value of the spin box. @type maximum: float @param singleStep: When the user uses the arrows to change the spin box's value the value will be incremented/decremented by the amount of the singleStep. The default value is 1.0. Setting a singleStep value of less than 0 does nothing. @type singleStep: float @param decimals: The precision of the spin box. @type decimals: int @param suffix: The suffix is appended to the end of the displayed value. Typical use is to display a unit of measurement. The default is no suffix. The suffix is not displayed for the minimum value if specialValueText() is set. @type suffix: str @param spanWidth: If True, the spin box and its label will span the width of the group box. The label will appear directly above the spin box and is left justified. @type spanWidth: bool @see: U{B{QDoubleSpinBox}<http://doc.trolltech.com/4/qdoublespinbox.html>} @see: B{InsertNanotube_PropertyManager._chiralityFixup()} for an example use of blockSignals flag """ if 0: # Debugging code print "PropMgrSpinBox.__init__():" print " label = ", label print " labelColumn = ", labelColumn print " value = ", value print " setAsDefault = ", setAsDefault print " minimum = ", minimum print " maximum = ", maximum print " singleStep = ", singleStep print " decimals = ", decimals print " suffix = ", suffix print " spanWidth = ", spanWidth if not parentWidget: return QDoubleSpinBox.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Set QDoubleSpinBox minimum, maximum, singleStep, decimals, then value self.setRange(minimum, maximum) self.setSingleStep(singleStep) self.setDecimals(decimals) self.setValue(value) # This must come after setDecimals(). if setAsDefault: self.setDefaultValue(value) # Add suffix if supplied. if suffix: self.setSuffix(suffix) parentWidget.addPmWidget(self) def restoreDefault( self ): """ Restores the default value. """ if self.setAsDefault: self.setValue(self.defaultValue) def setDefaultValue(self, value): """ Sets the default value of the spin box to I{value}. The current spin box value is unchanged. @param value: The new default value of the spin box. @type value: float @see: L{setValue} """ self.setAsDefault = True self.defaultValue = value def setValue(self, value, setAsDefault = True, blockSignals = False): """ Sets the value of the spin box to I{value}. setValue() will emit valueChanged() if the new value is different from the old one. @param value: The new spin box value. @type value: float ## @param setAsDefault: Determines if the spin box value is reset when ## the "Restore Defaults" button is clicked. If True, ## (the default) I{value} will be used as the reset ## value. ## @type setAsDefault: bool @note: The value will be rounded so it can be displayed with the current setting of decimals. @param blockSignals: Many times, the caller just wants to setValue and don't want to send valueChanged signal. If this flag is set to True, the valueChanged signal won't be emitted. The default value is False. @type blockSignals: bool @see: L{setDefaultValue} @see: QObject.blockSignals(bool block) """ ## if setAsDefault: ### THIS IS A BUG, if the default value of this option remains True. ## # it also looks useless, so i'll zap it. btw that means i could zap the entire method, but i won't yet. ## # I verified nothing calls it with changed version... not enough to prove this zapping is ok... ## # same issue in PM_SpinBox and PropMgrBaseClass. I've discussed this with Mark & Ninad and they agree ## # it should be changed. Ninad, feel free to clean up this method & comment when you see this. ## # [bruce 070814] ## self.setDefaultValue(value) #If blockSignals flag is True, the valueChanged signal won't be emitted #This is done by self.blockSignals method below. -- Ninad 2008-08-13 self.blockSignals(blockSignals) QDoubleSpinBox.setValue(self, value) #Make sure to always 'unblock' signals that might have been temporarily #blocked before calling superclass.setValue. self.blockSignals(False) def connectWithState(self, stateref, set_metainfo = True, debug_metainfo = False): """ Connect self to the state referred to by stateref, so changes to self's value change that state's value and vice versa. By default, also set self's metainfo to correspond to what the stateref provides. @param stateref: a reference to state of type double, which meets the state-reference interface StateRef_API. @type stateref: StateRef_API @param set_metainfo: whether to also set defaultValue, minimum, and/or maximum, if these are provided by the stateref. (This list of metainfo attributes will probably be extended.) @type set_metainfo: bool @param debug_metainfo: whether to print debug messages about the actions taken by set_metainfo, when it's true. @type debug_metainfo: bool """ if set_metainfo: # Do this first, so old min/max don't prevent setting the # correct current value when we connect new state. # # REVIEW: the conventions for expressing a lack of # minimum, maximum, or defaultValue, either on self # or on the stateref, may need revision, so it's not # ambiguous whether the stateref knows the minimum (etc) # should be unset on self or doesn't care what it's set to. # Ideally, some explicit value of stateref.minimum # would correspond to "no minimum" (i.e. a minimum of # negative infinity), etc. # [bruce 070926] set_metainfo_from_stateref( self.setMinimum, stateref, 'minimum', debug_metainfo) set_metainfo_from_stateref( self.setMaximum, stateref, 'maximum', debug_metainfo) set_metainfo_from_stateref( self.setDefaultValue, stateref, 'defaultValue', debug_metainfo) widget_connectWithState( self, stateref, QDoubleSpinBox_ConnectionWithState) return def hide( self ): """ Hides the spin box and its label (if it has one). Call L{show()} to unhide the spin box. @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show( self ): """ Unhides the spin box and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_DoubleSpinBox ########################################
NanoCAD-master
cad/src/PM/PM_DoubleSpinBox.py
#Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ PM_TreeView.py The PM_TreeView class provides a partlib object (as a 'treeview' of any user specified directory) to the client code. The parts from the partlib can be pasted in the 3D Workspace. @author: Bruce, Huaicai, Mark, Ninad @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. ninad 2007-09-06: Created. """ from PyQt4.Qt import QTreeView from PyQt4.Qt import QDir from PyQt4.Qt import QDirModel from PyQt4.Qt import Qt import os import foundation.env as env import sys from utilities.Log import redmsg class PM_TreeView(QTreeView): """ The PM_TreeView class provides a partlib object (as a 'treeview' of any user specified directory) to the client code. The parts from the partlib can be pasted in the 3D Workspace. """ def __init__(self, parent): """ The constructor of PM_TreeView class that provides provides a partlib object (as a 'treeview' of any user specified directory) to the client code. The parts from the partlib can be pasted in the 3D Workspace. """ QTreeView.__init__(self, parent) self.parent = parent self.setEnabled(True) self.model = 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.setModel(self.model) self.setWindowTitle(self.tr("Tree View")) self.setItemsExpandable(True) self.setAlternatingRowColors(True) self.setColumnWidth(0, 150) self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder) self.setMinimumHeight(300) for i in range(2, 4): self.setColumnWidth(i, 4) 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.setRootPath(libDir) else: self.rootDir = None env.history.message(redmsg("The part library directory: %s doesn't"\ " exist." %libDir)) self.show() #Ninad 070326 reimplementing mouseReleaseEvent and resizeEvent #for PM_TreeView 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.parent.partChanged(self.selectedItem()) return QTreeView.mouseReleaseEvent(self, evt) def resizeEvent(self, evt): """ Reimplementation of resizeEvent method of QTreeView """ if self.selectedItem() is not None: self.parent.partChanged(self.selectedItem()) return QTreeView.resizeEvent(self, evt) def setRootPath(self, path): """ Set the root path for the tree view. @param path: The directory path to be set as a root path """ self.path = path self.setRootIndex(self.model.index(path)) def selectedItem(self): """ Returns the Item selected in the QTreeview as a L{self.FileItem} @return: The Item selected in the QTreeview converted to a L{self.FileItem} object @rtype: L{self.FileItem} """ 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: """ Class FileItem provides the filename object for class PM_TreeView """ def __init__(self, path): """ Constructor for the class """ self.path = path dummy, self.fileName = os.path.split(path) def name(self): """ Returns the file name @return: self.fileName """ return self.fileName def getFileObj(self): """ Returns file path (self.path) @return: L{self.path} """ return self.path
NanoCAD-master
cad/src/PM/PM_TreeView.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO - remove all self.command calls. """ from PM.PM_SelectionListWidget import PM_SelectionListWidget from utilities.constants import lightred_1, lightgreen_2 from PyQt4.Qt import Qt, SIGNAL from PM.PM_ToolButton import PM_ToolButton from PM.PM_WidgetRow import PM_WidgetRow from PM.PM_GroupBox import PM_GroupBox from utilities import debug_flags from utilities.debug import print_compact_stack _superclass = PM_GroupBox class PM_ObjectChooser(PM_GroupBox): def __init__(self, parentWidget, command, modelObjectType, title = '' , addIcon = "ui/actions/Properties Manager"\ "/AddSegment_To_ResizeSegmentList.png", removeIcon = "ui/actions/Properties Manager"\ "/RemoveSegment_From_ResizeSegmentList.png"): """ """ self.isAlreadyConnected = False self.isAlreadyDisconnected = False _superclass.__init__(self, parentWidget, title = title) self.command = command self.win = self.command.win self._modelObjectType = modelObjectType self._addIcon = addIcon self._removeIcon = removeIcon self._loadWidgets() def getModelObjectType(self): return self._modelObjectType def setModelObjectType(self, modelObjtype): self._modelObjectType = modelObjtype 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 """ #TODO: This is a temporary fix for a bug. When you invoke a temporary mode # entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py 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 self._listWidget.connect_or_disconnect_signals(isConnect) change_connect(self._addToolButton, SIGNAL("toggled(bool)"), self.activateAddTool) change_connect(self._removeToolButton, SIGNAL("toggled(bool)"), self.activateRemoveTool) def _loadWidgets(self): """ """ self._loadSelectionListWidget() self._loadAddRemoveButtons() def _loadSelectionListWidget(self): """ """ self._listWidget = PM_SelectionListWidget( self, self.win, label = "", heightByRows = 12) self._listWidget.setFocusPolicy(Qt.StrongFocus) self._listWidget.setFocus() self.setFocusPolicy(Qt.StrongFocus) def _loadAddRemoveButtons(self): """ """ self._addToolButton = PM_ToolButton( self, text = "Add items to the list", iconPath = self._addIcon, spanWidth = True ) self._addToolButton.setCheckable(True) self._addToolButton.setAutoRaise(True) self._removeToolButton = PM_ToolButton( self, text = "Remove items from the list", iconPath = self._removeIcon, spanWidth = True ) self._removeToolButton.setCheckable(True) self._removeToolButton.setAutoRaise(True) #Widgets to include in the widget row. widgetList = [ ('QLabel', " Add/Remove Items:", 0), ('QSpacerItem', 5, 5, 1), ('PM_ToolButton', self._addToolButton, 2), ('QSpacerItem', 5, 5, 3), ('PM_ToolButton', self._removeToolButton, 4), ('QSpacerItem', 5, 5, 5) ] widgetRow = PM_WidgetRow(self, title = '', widgetList = widgetList, label = "", spanWidth = True ) def isAddToolActive(self): """ Returns True if the add objects tool is active. """ if self._addToolButton.isChecked(): #For safety if not self._removeToolButton.isChecked(): return True return False def isRemoveToolActive(self): """ Returns True if the remove segments tool (which removes the segments from the list of segments ) is active """ if self._removeToolButton.isChecked(): if not self._addToolButton.isChecked(): #For safety return True return False def hasFocus(self): """ Checks if the list widget that lists dnasegments (that will undergo special operations such as 'resizing them at once or making crossovers between the segments etc) has the Qt focus. This is used to just remove items from the list widget (without actually 'deleting' the corresponding Dnasegment in the GLPane) @see: MultipleDnaSegment_GraphicsMode.keyPressEvent() where it is called """ if self._listWidget.hasFocus(): return True return False def activateAddTool(self,enable): """ Change the appearance of the list widget (that lists the dna segments ) so as to indicate that the add dna segments tool is active @param enable: If True, changes the appearance of list widget to indicate that the add segments tool is active. @type enable: bool """ if enable: if not self._addToolButton.isChecked(): self._addToolButton.setChecked(True) if self._removeToolButton.isChecked(): self._removeToolButton.setChecked(False) self._listWidget.setAlternatingRowColors(False) self._listWidget.setColor(lightgreen_2) ##objectType = self._modelObjectType ##objectChooserType = 'ADD' ##self.command.activateObjectChooser((objectType, objectChooserType)) ##self.command.logMessage('ADD_SEGMENTS_ACTIVATED') else: if self._addToolButton.isChecked(): self._addToolButton.setChecked(False) self._listWidget.setAlternatingRowColors(True) self._listWidget.resetColor() def activateRemoveTool(self,enable): """ Change the appearance of the list widget (that lists the dna segments ) so as to indicate that the REMOVE dna segments tool is active @param enable: If True, changes the appearance of list widget to indicate that the REMOVE segments tool is active. @type enable: bool """ if enable: if not self._removeToolButton.isChecked(): self._removeToolButton.setChecked(True) if self._addToolButton.isChecked(): self._addToolButton.setChecked(False) self._listWidget.setAlternatingRowColors(False) ##self.command.logMessage('REMOVE_SEGMENTS_ACTIVATED') self._listWidget.setColor(lightred_1) else: if self._removeToolButton.isChecked(): self._removeToolButton.setChecked(False) self._listWidget.setAlternatingRowColors(True) self._listWidget.resetColor() def _deactivateAddRemoveTools(self): """ Deactivate tools that allow adding or removing the segments to the segment list in the Property manager. This can be simply done by resetting the state of toolbuttons to False. Example: toolbuttons that add or remove segments to the segment list in the Property manager. When self.show is called these need to be unchecked. @see: self.isAddSegmentsToolActive() @see:self.isRemoveSegmentsToolActive() @see: self.show() """ self._addToolButton.setChecked(False) self._removeToolButton.setChecked(False) def removeItems(self): """ Removes selected itoms from the dna segment list widget Example: User selects a bunch of items in the list widget and hits delete key to remove the selected items from the list IMPORTANT NOTE: This method does NOT delete the correspoinging model item in the GLPane (i.e. corresponding dnasegment). It just 'removes' the item from the list widget This is intentional. """ self._listWidget.deleteSelection() itemDict = self._listWidget.getItemDictonary() self.command.setSegmentList(itemDict.values()) self.updateListWidget() self.win.win_update() def updateListWidget(self, objectList = []): """ Update the list of segments shown in the segments list widget @see: self.updateListWidgets, self.updateStrandListWidget """ self._listWidget.insertItems( row = 0, items = objectList)
NanoCAD-master
cad/src/PM/PM_ObjectChooser.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_SpinBox.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrSpinBox out of PropMgrBaseClass.py into this file and renamed it PM_SpinBox. """ from PyQt4.Qt import QLabel from PyQt4.Qt import QSpinBox from PyQt4.Qt import QWidget class PM_SpinBox( QSpinBox ): """ The PM_SpinBox widget provides a QSpinBox (with an optional label) for a Property Manager group box. Detailed Description ==================== The PM_SpinBox class provides a spin box widget (with an optional label) for a U{B{Property Manager dialog}<http://www.nanoengineer-1.net/mediawiki/ index.php?title=Property_Manager>}. PM_SpinBox is designed to handle integers and discrete sets of values (e.g., month names); use PM_DoubleSpinBox for floating point values. PM_SpinBox allows the user to choose a value by clicking the up/down buttons or pressing up/down on the keyboard to increase/decrease the value currently displayed. The user can also type the value in manually. The spin box supports integer values but can be extended to use different strings with validate(), textFromValue() and valueFromText(). Every time the value changes PM_SpinBox emits the valueChanged() signals. The current value can be fetched with value() and set with setValue(). Clicking the up/down buttons or using the keyboard accelerator's up and down arrows will increase or decrease the current value in steps of size singleStep(). If you want to change this behaviour you can reimplement the virtual function stepBy(). The minimum and maximum value and the step size can be set using one of the constructors, and can be changed later with setMinimum(), setMaximum() and setSingleStep(). Most spin boxes are directional, but PM_SpinBox can also operate as a circular spin box, i.e. if the range is 0-99 and the current value is 99, clicking "up" will give 0 if wrapping() is set to true. Use setWrapping() if you want circular behavior. The displayed value can be prepended and appended with arbitrary strings indicating, for example, currency or the unit of measurement. See setPrefix() and setSuffix(). The text in the spin box is retrieved with text() (which includes any prefix() and suffix()), or with cleanText() (which has no prefix(), no suffix() and no leading or trailing whitespace). It is often desirable to give the user a special (often default) choice in addition to the range of numeric values. See setSpecialValueText() for how to do this with QSpinBox. @see: U{B{QSpinBox}<http://doc.trolltech.com/4/qspinbox.html>} @cvar defaultValue: The default value of the spin box. @type defaultValue: int @cvar setAsDefault: Determines whether to reset the value of the spin box to I{defaultValue} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this spin box. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultValue = 0 setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, value = 0, setAsDefault = True, minimum = 0, maximum = 99, singleStep = 1, suffix = '', spanWidth = False ): """ Appends a QSpinBox (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left of (or above) the spin box. If label contains the relative path to an icon (.png) file, that icon image will be used for the label. If spanWidth is True, the label will be displayed on its own row directly above the spin box. To suppress the label, set I{label} to an empty string. @type label: str @param value: The initial value of the spin box. @type value: int @param setAsDefault: Determines if the spin box value is reset when the "Restore Defaults" button is clicked. If True, (the default) I{value} will be used as the reset value. @type setAsDefault: bool @param minimum: The minimum value of the spin box. @type minimum: int @param maximum: The maximum value of the spin box. @type maximum: int @param singleStep: When the user uses the arrows to change the spin box's value the value will be incremented/decremented by the amount of the singleStep. The default value is 1. Setting a singleStep value of less than 0 does nothing. @type singleStep: int @param suffix: The suffix is appended to the end of the displayed value. Typical use is to display a unit of measurement. The default is no suffix. The suffix is not displayed for the minimum value if specialValueText() is set. @type suffix: str @param spanWidth: If True, the spin box and its label will span the width of the group box. The label will appear directly above the spin box and is left justified. @type spanWidth: bool @see: U{B{QSpinBox}<http://doc.trolltech.com/4/qspinbox.html>} """ if 0: # Debugging code print "PM_SpinBox.__init__():" print " label = ", label print " labelColumn = ", labelColumn print " value = ", value print " setAsDefault = ", setAsDefault print " minimum = ", minimum print " maximum = ", maximum print " singleStep = ", singleStep print " suffix = ", suffix print " spanWidth = ", spanWidth QSpinBox.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth self._suppress_valueChanged_signal = False if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Set QSpinBox minimum, maximum and initial value self.setRange(minimum, maximum) self.setSingleStep(singleStep) self.setValue(value) # Set default value self.defaultValue = value self.setAsDefault = setAsDefault # Add suffix if supplied. if suffix: self.setSuffix(suffix) parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setValue(self.defaultValue) def setDefaultValue(self, value): """ Sets the default value of the spin box to I{value}. The current spin box value is unchanged. @param value: The new default value of the spin box. @type value: int @see: L{setValue} """ self.setAsDefault = True self.defaultValue = value def setValue(self, value, setAsDefault = True, blockSignals = False): """ Sets the value of the spin box to I{value}. setValue() will emit valueChanged() if the new value is different from the old one. (and if blockSignals flag is False) @param value: The new spin box value. @type value: int @param setAsDefault: Determines if the spin box value is reset when the "Restore Defaults" button is clicked. If True, (the default) I{value} will be used as the reset value. @type setAsDefault: bool @param blockSignals: Many times, the caller just wants to setValue and don't want to send valueChanged signal. If this flag is set to True, the valueChanged signal won't be emitted. The default value is False. @type blockSignals: bool @see: L{setDefaultValue} @see: QObject.blockSignals(bool block) @see: B{InsertNanotube_PropertyManager._chiralityFixup()} for an example use of blockSignals flag """ #If blockSignals flag is True, the valueChanged signal won't be emitted #This is done by self.blockSignals method below. -- Ninad 2008-08-13 self.blockSignals(blockSignals) if setAsDefault: self.setDefaultValue(value) QSpinBox.setValue(self, value) #Make sure to always 'unblock' signals that might have been temporarily #blocked before calling superclass.setValue. self.blockSignals(False) def hide(self): """ Hides the spin box and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the spin box and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_SpinBox ############################
NanoCAD-master
cad/src/PM/PM_SpinBox.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ PM_Dial.py @author: Mark @version: $Id$ @copyright: 2008 Nanorex, Inc. All rights reserved. History: piotr 2008-07-29: Created this file. """ from PyQt4.Qt import QDial from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget from widgets.prefs_widgets import widget_connectWithState from widgets.prefs_widgets import set_metainfo_from_stateref class PM_Dial( QDial ): """ The PM_Dial widget provides a QDial (with an optional label) for a Property Manager group box. """ defaultValue = 0.0 setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', suffix = '', labelColumn = 1, value = 0.0, setAsDefault = True, minimum = 0.0, maximum = 360.0, notchSize = 1, notchTarget = 10.0, notchesVisible = True, wrapping = True, spanWidth = True ): """ Appends a QDial (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @see: U{B{QDial}<http://doc.trolltech.com/4/qdial.html>} """ if not parentWidget: return QDial.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth self.suffix = suffix if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.updateValueLabel() self.labelWidget.setText(self.value_label) # Set QDial minimum, maximum, then value self.setRange(minimum, maximum) self.setValue(value) # This must come after setDecimals(). if setAsDefault: self.setDefaultValue(value) self.notchSize = notchSize self.setNotchTarget(notchTarget) self.setNotchesVisible(notchesVisible) self.setWrapping(wrapping) parentWidget.addPmWidget(self) def restoreDefault( self ): """ Restores the default value. """ if self.setAsDefault: self.setValue(self.defaultValue) def setDefaultValue(self, value): """ Sets the default value of the dial to I{value}. The current dial value is unchanged. @param value: The new default value of the dial. @type value: float @see: L{setValue} """ self.setAsDefault = True self.defaultValue = value def setValue(self, value, setAsDefault = True): """ Sets the value of the dial to I{value}. setValue() will emit valueChanged() if the new value is different from the old one. @param value: The new dial value. @type value: float ## @param setAsDefault: Determines if the dial value is reset when ## the "Restore Defaults" button is clicked. If True, ## (the default) I{value} will be used as the reset ## value. ## @type setAsDefault: bool @note: The value will be rounded so it can be displayed with the current setting of decimals. @see: L{setDefaultValue} """ QDial.setValue(self, value) self.updateValueLabel() def updateValueLabel(self): """ Updates a widget's label with a value. """ if self.label: self.value_label = " " + self.label + " " + \ "%-4d" % int(self.value()) + " " + self.suffix self.labelWidget.setText(self.value_label) def connectWithState(self, stateref, set_metainfo = True, debug_metainfo = False): """ Connect self to the state referred to by stateref, so changes to self's value change that state's value and vice versa. By default, also set self's metainfo to correspond to what the stateref provides. @param stateref: a reference to state of type double, which meets the state-reference interface StateRef_API. @type stateref: StateRef_API @param set_metainfo: whether to also set defaultValue, minimum, and/or maximum, if these are provided by the stateref. (This list of metainfo attributes will probably be extended.) @type set_metainfo: bool @param debug_metainfo: whether to print debug messages about the actions taken by set_metainfo, when it's true. @type debug_metainfo: bool """ if set_metainfo: # Do this first, so old min/max don't prevent setting the # correct current value when we connect new state. # # REVIEW: the conventions for expressing a lack of # minimum, maximum, or defaultValue, either on self # or on the stateref, may need revision, so it's not # ambiguous whether the stateref knows the minimum (etc) # should be unset on self or doesn't care what it's set to. # Ideally, some explicit value of stateref.minimum # would correspond to "no minimum" (i.e. a minimum of # negative infinity), etc. # [bruce 070926] set_metainfo_from_stateref( self.setMinimum, stateref, 'minimum', debug_metainfo) set_metainfo_from_stateref( self.setMaximum, stateref, 'maximum', debug_metainfo) set_metainfo_from_stateref( self.setDefaultValue, stateref, 'defaultValue', debug_metainfo) ###widget_connectWithState( self, stateref, ### QDoubleSpinBox_ConnectionWithState) print "PM_Dial.connectWithState: not yet implemented" #bruce 080811 added this line return def hide( self ): """ Hides the dial and its label (if it has one). Call L{show()} to unhide the dial. @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show( self ): """ Unhides the dial and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_Dial ########################################
NanoCAD-master
cad/src/PM/PM_Dial.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_PreviewGroupBox.py The PM_PreviewGroupBox widget provides a preview pane for previewing elements , clipboard items , library parts etc. from the element chooser or list provided in the property manager. (The object being previewed can then be deposited into the 3D workspace.) @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-29: Created. """ from PyQt4.Qt import QSize from graphics.widgets.ThumbView import MMKitView from PM.PM_GroupBox import PM_GroupBox class PM_PreviewGroupBox(PM_GroupBox): """ The PM_PreviewGroupBox widget provides a preview pane for previewing elements , clipboard items , library parts etc. from the element chooser or list provided in the property manager. (The object being previewed can then be deposited into the 3D workspace.) """ elementViewer = None def __init__(self, parentWidget, glpane = None, title = 'Preview' ): """ Appends a PM_PreviewGroupBox widget to I{parentWidget},a L{PM_Dialog} @param parentWidget: The parent dialog (Property manager) containing this widget. @type parentWidget: L{PM_Dialog} @param glpane: GLPane object used in construction of the L{self.elementViewer} @type glpane: L{GLPane} or None @param title: The title (button) text. @type title: str """ PM_GroupBox.__init__(self, parentWidget, title) self.glpane = glpane self.parentWidget = parentWidget self._loadPreviewGroupBox() def _loadPreviewGroupBox(self): """ Load the L{self.elementViewer} widget inside this preview groupbox. @attention: The L{self.elementViewer} widget is added to L{self.previewGroupBox.gridLayout} in L{Thumbview.__init__}. Based on tests, it takes longer cpu time to complete this operation (adding QGLWidget to a gridlayout. By doing this inside L{Thumbview.__init__}, a time gain of ~ 0.1 sec was noticed on Windows XP. """ self.elementViewer = MMKitView( self, "MMKitView glPane", self.glpane) self.elementViewer.setMinimumSize(QSize(150, 150)) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) #Append to the widget list. This is important for expand - collapse #functions (of the groupbox) to work properly. self._widgetList.append(self.elementViewer) ##self.previewGroupBox.gridLayout.addWidget(self.elementViewer, ## 0, 0, 1, 1) def expand(self): """ Expand this group box i.e. show all its contents and change the look and feel of the groupbox button. It also sets the gridlayout margin and spacing to 0. (necessary to get rid of the extra space inside the groupbox.) @see: L{PM_GroupBox.expand} """ PM_GroupBox.expand(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0)
NanoCAD-master
cad/src/PM/PM_PreviewGroupBox.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_LineEdit.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrLineEdit out of PropMgrBaseClass.py into this file and renamed it PM_LineEdit. """ from PyQt4.Qt import QLabel from PyQt4.Qt import QLineEdit from PyQt4.Qt import QWidget class PM_LineEdit( QLineEdit ): """ The PM_LineEdit widget provides a QLineEdit with a QLabel for a Property Manager group box. @cvar defaultText: The default text of the lineedit. @type defaultText: str @cvar setAsDefault: Determines whether to reset the value of the lineedit to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this lineedit. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultText = "" setAsDefault = True hidden = False labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, text = '', setAsDefault = True, spanWidth = False ): """ Appends a QLineEdit widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the checkbox. If spanWidth is True, the label will be displayed on its own row directly above the checkbox. To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param text: initial value of LineEdit widget. @type text: str @param setAsDefault: if True, will restore <val> when the "Restore Defaults" button is clicked. @type setAsDefault: bool @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool @see: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} """ if 0: # Debugging code print "PM_LineEdit.__init__():" print " label = ", label print " labelColumn = ", labelColumn print " text = ", text print " setAsDefault = ", setAsDefault print " spanWidth = ", spanWidth QLineEdit.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Set QLineEdit text self.setText(text) # Set default value self.defaultText = text self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setText(self.defaultText) def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_LineEdit ############################
NanoCAD-master
cad/src/PM/PM_LineEdit.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ PM_Dialog.py @author: Mark @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrBaseClass out of PropMgrBaseClass.py into this file and renamed it PM_Dialog. """ import foundation.env as env from utilities.debug import print_compact_traceback from utilities import debug_flags from utilities.Comparison import same_vals from utilities.icon_utilities import geticon from utilities.icon_utilities import getpixmap from PyQt4.Qt import Qt from PM.PM_Colors import pmColor from PM.PM_Colors import pmHeaderFrameColor from PM.PM_Colors import pmHeaderTitleColor from PM.PM_Constants import PM_MAINVBOXLAYOUT_MARGIN from PM.PM_Constants import PM_MAINVBOXLAYOUT_SPACING from PM.PM_Constants import PM_HEADER_FRAME_MARGIN from PM.PM_Constants import PM_HEADER_FRAME_SPACING from PM.PM_Constants import PM_HEADER_FONT from PM.PM_Constants import PM_HEADER_FONT_POINT_SIZE from PM.PM_Constants import PM_HEADER_FONT_BOLD from PM.PM_Constants import PM_SPONSOR_FRAME_MARGIN from PM.PM_Constants import PM_SPONSOR_FRAME_SPACING from PM.PM_Constants import PM_TOPROWBUTTONS_MARGIN from PM.PM_Constants import PM_TOPROWBUTTONS_SPACING from PM.PM_Constants import PM_LABEL_LEFT_ALIGNMENT from PM.PM_Constants import PM_ALL_BUTTONS from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from PM.PM_Constants import PM_RESTORE_DEFAULTS_BUTTON from PM.PM_Constants import PM_PREVIEW_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PyQt4.Qt import SIGNAL from PyQt4.Qt import QDialog from PyQt4.Qt import QFont from PyQt4.Qt import QFrame from PyQt4.Qt import QGridLayout from PyQt4.Qt import QLabel from PyQt4.Qt import QPushButton from PyQt4.Qt import QPalette from PyQt4.Qt import QToolButton from PyQt4.Qt import QSpacerItem from PyQt4.Qt import QHBoxLayout from PyQt4.Qt import QVBoxLayout from PyQt4.Qt import QSize from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QWhatsThis from PyQt4.Qt import QWidget from PM.PM_GroupBox import PM_GroupBox from PM.PM_MessageGroupBox import PM_MessageGroupBox from utilities.prefs_constants import sponsor_download_permission_prefs_key from sponsors.Sponsors import SponsorableMixin class PM_Dialog( QDialog, SponsorableMixin ): """ The PM_Dialog class is the base class for Property Manager dialogs. [To make a PM class from this superclass, subclass it to customize the widget set and add behavior. You must also provide certain methods that used to be provided by GeneratorBaseClass, 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.] """ headerTitleText = "" # The header title text. _widgetList = [] # A list of all group boxes in this PM dialog, # including the message group box # (but not header, sponsor button, etc.) _groupBoxCount = 0 # Number of PM_GroupBoxes in this PM dialog _lastGroupBox = None # The last PM_GroupBox in this PM dialog # (i.e. the most recent PM_GroupBox added) def __init__(self, name, iconPath = "", title = "" ): """ Property Manager constructor. @param name: the name to assign the property manager dialog object. @type name: str @param iconPath: the relative path for the icon (PNG image) that appears in the header. @type iconPath: str @param title: the title that appears in the header. @type title: str """ QDialog.__init__(self) self.setObjectName(name) self._widgetList = [] # Main pallete for PropMgr. self.setPalette(QPalette(pmColor)) # Main vertical layout for PropMgr. self.vBoxLayout = QVBoxLayout(self) self.vBoxLayout.setMargin(PM_MAINVBOXLAYOUT_MARGIN) self.vBoxLayout.setSpacing(PM_MAINVBOXLAYOUT_SPACING) # Add PropMgr's header, sponsor button, top row buttons and (hidden) # message group box. self._createHeader(iconPath, title) self._createSponsorButton() self._createTopRowBtns() # Create top buttons row self.MessageGroupBox = PM_MessageGroupBox(self) # Keep the line below around; it might be useful. # I may want to use it now that I understand it. # Mark 2007-05-17. #QMetaObject.connectSlotsByName(self) self._addGroupBoxes() try: self._addWhatsThisText() except: print_compact_traceback("Error loading whatsthis text for this " "property manager: ") try: self._addToolTipText() except: print_compact_traceback("Error loading tool tip text for this " "property manager: ") #The following attr is used for comparison in method #'_update_UI_wanted_as_something_changed' self._previous_all_change_indicators = None def update_UI(self): """ Update whatever is shown in this PM based on current state of the rest of the system, especially the state of self.command and of the model it shows. This is part of the PM API required by baseCommand, since it's called by baseCommand.command_update_UI. @note: Overridden in Command_PropertyManager, but should not be overridden in its subclasses. See that method's docstring for details. """ #bruce 081125 defined this here, to fix bugs in example commands return def keyPressEvent(self, event): """ Handles keyPress event. @note: Subclasses should carefully override this. Note that the default implementation doesn't permit ESC key as a way to close the PM_dialog. (This is typically desirable for Property Managers.) If any subclass needs to implement the key press, they should first call this method (i.e. superclass.keyPressEvent) and then implement specific code that closes the dialog when ESC key is pressed. """ key = event.key() # Don't use ESC key to close the PM dialog. Fixes bug 2596 if key == Qt.Key_Escape: pass else: QDialog.keyPressEvent(self, event) return def _addGroupBoxes(self): """ Add various group boxes to this PM. Subclasses should override this method. """ pass def _addWhatsThisText(self): """ Add what's this text. Subclasses should override this method. """ pass def _addToolTipText(self): """ Add Tool tip text. Subclasses should override this method. """ pass def show(self): """ Shows the Property Manager. """ self.setSponsor() # Show or hide the sponsor logo based on whether the user gave # permission to download sponsor logos. if env.prefs[sponsor_download_permission_prefs_key]: self.sponsorButtonContainer.show() else: self.sponsorButtonContainer.hide() if not self.pw or self: self.pw = self.win.activePartWindow() self.pw.updatePropertyManagerTab(self) self.pw.pwProjectTabWidget.setCurrentIndex( self.pw.pwProjectTabWidget.indexOf(self)) # Show the default message whenever we open the Property Manager. self.MessageGroupBox.MessageTextEdit.restoreDefault() def open(self, pm): """ Closes the current property manager (if any) and opens the property manager I{pm}. @param pm: The property manager to open. @type pm: L{PM_Dialog} or QDialog (of legacy PMs) @attention: This method is a temporary workaround for "Insert > Plane". The current command should always be responsible for (re)opening its own PM via self.show(). @see: L{show()} """ if 1: commandSequencer = self.win.commandSequencer #bruce 071008 commandName = commandSequencer.currentCommand.commandName # that's an internal name, but this is just for a debug print print "PM_Dialog.open(): Reopening the PM for command:", commandName # The following line of code is buggy when you, for instance, exit a PM # and reopen the previous one. It sends the disconnect signal twice to # the PM that is just closed.So disabling this line -- Ninad 2007-12-04 ##self.close() # Just in case there is another PM open. self.pw = self.win.activePartWindow() self.pw.updatePropertyManagerTab(pm) try: pm.setSponsor() except: print """PM_Dialog.open(): pm has no attribute 'setSponsor()' ignoring.""" self.pw.pwProjectTabWidget.setCurrentIndex( self.pw.pwProjectTabWidget.indexOf(pm)) def close(self): """ Closes the Property Manager. """ if not self.pw: self.pw = self.win.activePartWindow() self.pw.pwProjectTabWidget.setCurrentIndex(0) ## try: [bruce 071018 moved this lower, since errmsg only covers attr] pmWidget = self.pw.propertyManagerScrollArea.widget() if debug_flags.atom_debug: #bruce 071018 "atom_debug fyi: %r is closing %r (can they differ?)" % \ (self, pmWidget) try: pmWidget.update_props_if_needed_before_closing except AttributeError: if 1 or debug_flags.atom_debug: msg1 = "Last PropMgr %r doesn't have method" % pmWidget msg2 = " update_props_if_needed_before_closing. That's" msg3 = " OK (for now, only implemented for Plane PM). " msg4 = "Ignoring Exception: " print_compact_traceback(msg1 + msg2 + msg3 + msg4) #bruce 071018: I'll define that method in PM_Dialog # so this message should become rare or nonexistent, # so I'll make it happen whether or not atom_debug. else: pmWidget.update_props_if_needed_before_closing() self.pw.pwProjectTabWidget.removeTab( self.pw.pwProjectTabWidget.indexOf( self.pw.propertyManagerScrollArea)) if self.pw.propertyManagerTab: self.pw.propertyManagerTab = None def update_props_if_needed_before_closing(self): # bruce 071018 default implem """ Subclasses can override this to update some cosmetic properties of their associated model objects before closing self (the Property Manager). """ pass def updateMessage(self, msg = ''): """ Updates the message box with an informative message @param msg: Message to be displayed in the Message groupbox of the property manager @type msg: string """ self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault = False, minLines = 5) def _createHeader(self, iconPath, title): """ Creates the Property Manager header, which contains an icon (a QLabel with a pixmap) and white text (a QLabel with text). @param iconPath: The relative path for the icon (PNG image) that appears in the header. @type iconPath: str @param title: The title that appears in the header. @type title: str """ # Heading frame (dark gray), which contains # a pixmap and (white) heading text. self.headerFrame = QFrame(self) self.headerFrame.setFrameShape(QFrame.NoFrame) self.headerFrame.setFrameShadow(QFrame.Plain) self.headerFrame.setPalette(QPalette(pmHeaderFrameColor)) self.headerFrame.setAutoFillBackground(True) # HBox layout for heading frame, containing the pixmap # and label (title). HeaderFrameHLayout = QHBoxLayout(self.headerFrame) # 2 pixels around edges -- HeaderFrameHLayout.setMargin(PM_HEADER_FRAME_MARGIN) # 5 pixel between pixmap and label. -- HeaderFrameHLayout.setSpacing(PM_HEADER_FRAME_SPACING) # PropMgr icon. Set image by calling setHeaderIcon(). self.headerIcon = QLabel(self.headerFrame) self.headerIcon.setSizePolicy( QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed), QSizePolicy.Policy(QSizePolicy.Fixed))) self.headerIcon.setScaledContents(True) HeaderFrameHLayout.addWidget(self.headerIcon) # PropMgr header title text (a QLabel). self.headerTitle = QLabel(self.headerFrame) headerTitlePalette = self._getHeaderTitlePalette() self.headerTitle.setPalette(headerTitlePalette) self.headerTitle.setAlignment(PM_LABEL_LEFT_ALIGNMENT) # Assign header title font. self.headerTitle.setFont(self._getHeaderFont()) HeaderFrameHLayout.addWidget(self.headerTitle) self.vBoxLayout.addWidget(self.headerFrame) # Set header icon and title text. self.setHeaderIcon(iconPath) self.setHeaderTitle(title) def _getHeaderFont(self): """ Returns the font used for the header. @return: the header font @rtype: QFont """ font = QFont() font.setFamily(PM_HEADER_FONT) font.setPointSize(PM_HEADER_FONT_POINT_SIZE) font.setBold(PM_HEADER_FONT_BOLD) return font def setHeaderTitle(self, title): """ Set the Property Manager header title to string <title>. @param title: the title to insert in the header. @type title: str """ self.headerTitleText = title self.headerTitle.setText(title) def setHeaderIcon(self, iconPath): """ Set the Property Manager header icon. @param iconPath: the relative path to the PNG file containing the icon image. @type iconPath: str """ if not iconPath: return self.headerIcon.setPixmap(getpixmap(iconPath)) def _createSponsorButton(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.sponsorButtonContainer = QWidget(self) SponsorFrameGrid = QGridLayout(self.sponsorButtonContainer) SponsorFrameGrid.setMargin(PM_SPONSOR_FRAME_MARGIN) SponsorFrameGrid.setSpacing(PM_SPONSOR_FRAME_SPACING) # Has no effect. self.sponsor_btn = QToolButton(self.sponsorButtonContainer) self.sponsor_btn.setAutoRaise(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.sponsorButtonContainer) button_whatsthis_widget = self.sponsor_btn #bruce 070615 bugfix -- put tooltip & whatsthis on self.sponsor_btn, # not self. # [self.sponsorButtonContainer 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 _createTopRowBtns(self): """ Creates the Done, Cancel, Preview, Restore Defaults and What's This buttons row at the top of the Property Manager. """ topBtnSize = QSize(22, 22) # button images should be 16 x 16, though. # 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 horizontalSpacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum) # Widget containing all the buttons. self.topRowBtnsContainer = QWidget() # Create Hbox layout for main frame. topRowBtnsHLayout = QHBoxLayout(self.topRowBtnsContainer) topRowBtnsHLayout.setMargin(PM_TOPROWBUTTONS_MARGIN) topRowBtnsHLayout.setSpacing(PM_TOPROWBUTTONS_SPACING) # Set to True to center align the buttons in the PM if False: # Left aligns the buttons. topRowBtnsHLayout.addItem(horizontalSpacer) # Done (OK) button. self.done_btn = QToolButton(self.topRowBtnsContainer) self.done_btn.setIcon( geticon("ui/actions/Properties Manager/Done_16x16.png")) self.done_btn.setIconSize(topBtnSize) self.done_btn.setAutoRaise(True) self.connect(self.done_btn, SIGNAL("clicked()"), self.doneButtonClicked) self.done_btn.setToolTip("Done") topRowBtnsHLayout.addWidget(self.done_btn) # Cancel (Abort) button. self.cancel_btn = QToolButton(self.topRowBtnsContainer) self.cancel_btn.setIcon( geticon("ui/actions/Properties Manager/Abort_16x16.png")) self.cancel_btn.setIconSize(topBtnSize) self.cancel_btn.setAutoRaise(True) self.connect(self.cancel_btn, SIGNAL("clicked()"), self.cancelButtonClicked) self.cancel_btn.setToolTip("Cancel") topRowBtnsHLayout.addWidget(self.cancel_btn) #@ abort_btn deprecated. We still need it because modes use it. self.abort_btn = self.cancel_btn # Restore Defaults button. self.restore_defaults_btn = QToolButton(self.topRowBtnsContainer) self.restore_defaults_btn.setIcon( geticon("ui/actions/Properties Manager/Restore_16x16.png")) self.restore_defaults_btn.setIconSize(topBtnSize) self.restore_defaults_btn.setAutoRaise(True) self.connect(self.restore_defaults_btn, SIGNAL("clicked()"), self.restoreDefaultsButtonClicked) self.restore_defaults_btn.setToolTip("Restore Defaults") topRowBtnsHLayout.addWidget(self.restore_defaults_btn) # Preview (glasses) button. self.preview_btn = QToolButton(self.topRowBtnsContainer) self.preview_btn.setIcon( geticon("ui/actions/Properties Manager/Preview_16x16.png")) self.preview_btn.setIconSize(topBtnSize) self.preview_btn.setAutoRaise(True) self.connect(self.preview_btn, SIGNAL("clicked()"), self.previewButtonClicked) self.preview_btn.setToolTip("Preview") topRowBtnsHLayout.addWidget(self.preview_btn) # What's This (?) button. self.whatsthis_btn = QToolButton(self.topRowBtnsContainer) self.whatsthis_btn.setIcon( geticon("ui/actions/Properties Manager/WhatsThis_16x16.png")) self.whatsthis_btn.setIconSize(topBtnSize) self.whatsthis_btn.setAutoRaise(True) self.connect(self.whatsthis_btn, SIGNAL("clicked()"), self.whatsThisButtonClicked) self.whatsthis_btn.setToolTip("Enter \"What's This\" help mode") topRowBtnsHLayout.addWidget(self.whatsthis_btn) topRowBtnsHLayout.addItem(horizontalSpacer) # Create Button Row self.pmTopRowBtns.addWidget(self.topRowBtnsContainer) 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_16x16.png\"><br> Completes and/or exits the current command.</p>""") self.cancel_btn.setWhatsThis("""<b>Cancel</b> <p> <img source=\"ui/actions/Properties Manager/Abort_16x16.png\"><br> Cancels the current command.</p>""") self.restore_defaults_btn.setWhatsThis("""<b>Restore Defaults</b> <p><img source=\"ui/actions/Properties Manager/Restore_16x16.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_16x16.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_16x16.png\"><br> This invokes \"What's This?\" help mode which is part of NanoEngineer-1's online help system, and provides users with information about the functionality and usage of a particular command button or widget. </p>""") return def hideTopRowButtons(self, pmButtonFlags = None): """ Hides one or more top row buttons using <pmButtonFlags>. Button flags not set will cause the button to be shown if currently hidden. @param pmButtonFlags: This enumerator describes the which buttons to hide, where: - PM_DONE_BUTTON = 1 - PM_CANCEL_BUTTON = 2 - PM_RESTORE_DEFAULTS_BUTTON = 4 - PM_PREVIEW_BUTTON = 8 - PM_WHATS_THIS_BUTTON = 16 - PM_ALL_BUTTONS = 31 @type pmButtonFlags: int """ if pmButtonFlags & PM_DONE_BUTTON: self.done_btn.hide() else: self.done_btn.show() if pmButtonFlags & PM_CANCEL_BUTTON: self.cancel_btn.hide() else: self.cancel_btn.show() if pmButtonFlags & PM_RESTORE_DEFAULTS_BUTTON: self.restore_defaults_btn.hide() else: self.restore_defaults_btn.show() if pmButtonFlags & PM_PREVIEW_BUTTON: self.preview_btn.hide() else: self.preview_btn.show() if pmButtonFlags & PM_WHATS_THIS_BUTTON: self.whatsthis_btn.hide() else: self.whatsthis_btn.show() def showTopRowButtons(self, pmButtonFlags = PM_ALL_BUTTONS): """ Shows one or more top row buttons using <pmButtonFlags>. Button flags not set will cause the button to be hidden if currently displayed. @param pmButtonFlags: this enumerator describes which buttons to display, where: - PM_DONE_BUTTON = 1 - PM_CANCEL_BUTTON = 2 - PM_RESTORE_DEFAULTS_BUTTON = 4 - PM_PREVIEW_BUTTON = 8 - PM_WHATS_THIS_BUTTON = 16 - PM_ALL_BUTTONS = 31 @type pmButtonFlags: int """ self.hideTopRowButtons(pmButtonFlags ^ PM_ALL_BUTTONS) def _getHeaderTitlePalette(self): """ Return a palette for header title (text) label. """ palette = QPalette() palette.setColor(QPalette.WindowText, pmHeaderTitleColor) return palette def doneButtonClicked(self): # note: never overridden, as of 080815 """ Slot for the Done button. """ self.ok_btn_clicked() def cancelButtonClicked(self): # note: never overridden, as of 080815 """ Slot for the Cancel button. """ self.cancel_btn_clicked() def restoreDefaultsButtonClicked(self): """ Slot for "Restore Defaults" button in the Property Manager. It is called each time the button is clicked. """ for widget in self._widgetList: if isinstance(widget, PM_GroupBox): widget.restoreDefault() def previewButtonClicked(self): """ Slot for the Preview button. """ self.preview_btn_clicked() def whatsThisButtonClicked(self): """ Slot for the What's This button. """ QWhatsThis.enterWhatsThisMode() # default implementations for subclasses # [bruce 080815 pulled these in from subclasses] def ok_btn_clicked(self): """ Implements Done button. Called by its slot method in PM_Dialog. [subclasses can override as needed] """ self.win.toolsDone() def cancel_btn_clicked(self): """ Implements Cancel button. Called by its slot method in PM_Dialog. [subclasses can override as needed] """ # Note: many subclasses override this to call self.w.toolsDone # (rather than toolsCancel). This should be cleaned up # so those overrides are not needed. (Maybe they are already # not needed.) [bruce 080815 comment] self.win.toolsCancel() pass # end
NanoCAD-master
cad/src/PM/PM_Dialog.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_LabelGrid.py @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-14: Created. """ from PyQt4.Qt import QFont from PM.PM_WidgetGrid import PM_WidgetGrid class PM_LabelGrid( PM_WidgetGrid ): """ The PM_LabelGrid widget (a groupbox) provides a grid of labels arranged in the grid layout of the PM_LabelGrid @see: B{Ui_MovePropertyManager} for an example of how this is used. """ def __init__(self, parentWidget, title = '', labelList = [], alignment = None, isBold = False ): """ Appends a PM_LabelGrid widget ( a groupbox) to the bottom of I{parentWidget}, the Property Manager Group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param title: The group box title. @type title: str @param labelList: A list of I{label info lists}. There is one label info list for each label in the grid. The label info list contains the following items: 1. Widget Type - in this case its 'Label'(str), 2. Label text (str), 3. Column (int), 4. Row (int). @type labelList: list """ self.isBold = isBold #Empty list that will contain all the labels in this widget. self.labels = [] PM_WidgetGrid.__init__(self, parentWidget , title, labelList, alignment) def _createWidgetUsingParameters(self, widgetParams): """ Returns a label created using the parameters specified by the user @param widgetParams: A list of label parameters. This is a modified using the original list returned by L{self.getWidgetInfoList}. The modified list doesn't contain the row and column information. @type widgetParams: list @see: L{PM_WidgetGrid._createWidgetUsingParameters} (overrided in this method) @see: L{PM_WidgetGrid.loadWidgets} which calls this method. """ labelParams = list(widgetParams) label = self._createLabel(labelParams) labelFont = self.getLabelFont(self.isBold) label.setFont(labelFont) label.setUpdatesEnabled(True) self.labels.append(label) return label def getLabelFont(self, isBold = False): """ Returns the font for the labels in the grid """ # Font for labels. labelFont = QFont(self.font()) labelFont.setBold(False) return labelFont def setBold(self, isBold = True): """ Sets or unsets font of all labels in this widget to bold @param isBold: If true, sets the font of all labels in the widget to bold. @type isBold: bool @see: B{MovePropertyManager.updateRotationDeltaLabels} for an example on how this function is used. """ for label in self.labels: font = QFont(label.font()) font.setBold(isBold) label.setFont(font)
NanoCAD-master
cad/src/PM/PM_LabelGrid.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_Utilities.py $Id$ """ from PyQt4.QtGui import QSizePolicy # 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()
NanoCAD-master
cad/src/PM/PM_Utilities.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_Clipboard.py The PM_Clipboard class provides a groupbox containing a list of clipboard items that can be pasted in the 3D Workspace. The selected item in this list is shown by its elementViewer (an instance of L{PM_PreviewGroupBox}) The object being previewed can then be deposited into the 3D workspace. @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-29: Created. (Initially to support the clipboard in L{PasteFromClipboard_Command}) """ from PyQt4.Qt import QListWidget from PyQt4.Qt import SIGNAL from graphics.widgets.ThumbView import MMKitView from PM.PM_GroupBox import PM_GroupBox from utilities.constants import diTUBES class PM_Clipboard(PM_GroupBox): """ The PM_Clipboard class provides a groupbox containing a list of clipboard items that can be pasted in the 3D Workspace. The selected item in this list is shown by its elementViewer (an instance of L{PM_PreviewGroupBox}) The object being previewed can then be deposited into the 3D workspace. """ def __init__(self, parentWidget, title = 'Clipboard', win = None, elementViewer = None ): """ Appends a PM_Clipboard groupbox widget to I{parentWidget},a L{PM_Dialog} @param parentWidget: The parent dialog (Property manager) containing this widget. @type parentWidget: L{PM_Dialog} @param title: The title (button) text. @type title: str @param win: MainWindow object @type win: L{MWsemantics} or None @param elementViewer: The associated preview pane groupbox. If provided, The selected item in L{self.clipboardListWidget} is shown (previewed) by L{elementViewer}. The object being previewed can then be deposited into the 3D workspace. @type elementViewer: L{PM_PreviewGroupBox} or None """ self.w = win self.elementViewer = elementViewer self.elementViewer.setDisplay(diTUBES) self.pastableItems = None PM_GroupBox.__init__(self, parentWidget, title) self._loadClipboardGroupbox() def _loadClipboardGroupbox(self): """ Load the L{self.clipboardListWidget} widget used to display a list of clipboard items inside this clipboard groupbox. """ self.clipboardListWidget = QListWidget(self) self.gridLayout.addWidget(self.clipboardListWidget) #Append to the widget list. This is important for expand -collapse #functions (of the groupbox) to work properly. self._widgetList.append(self.clipboardListWidget) def _updateElementViewer(self, newModel = None): """ Update the view of L{self.elementViewer} @param newModel: The model correseponding to the item selected in L{self.clipboardListWidget}. @type newModel: L{molecule} or L{Group} """ if not self.elementViewer: return assert isinstance(self.elementViewer, MMKitView) self.elementViewer.resetView() if newModel: self.elementViewer.updateModel(newModel) def update(self): """ Updates the clipboard items in the L{PM_Clipboard} groupbox. Also updates its element viewer. """ PM_GroupBox.update(self) self.pastableItems = self.w.assy.shelf.getPastables() i = self.clipboardListWidget.currentRow() self.clipboardListWidget.clear() newModel = None if len(self.pastableItems): for item in self.pastableItems: self.clipboardListWidget.addItem(item.name) if i >= self.clipboardListWidget.count(): i = self.clipboardListWidget.count() - 1 if i < 0: i = 0 self.clipboardListWidget.setCurrentItem( self.clipboardListWidget.item(i)) newModel = self.pastableItems[i] self._updateElementViewer(newModel) def clipboardListItemChanged(self, currentItem = None, previousItem = None): """ Slot method. Called when user clicks on a different pastable item displayed in this groupbox @param currentItem: Current item in the L{self.clipboardListWidget} that is selected @type currentItem: U{B{QListWidgetItem} <http://doc.trolltech.com/4.2/qlistwidgetitem.html>} @param previousItem: Previously selected item in the L{self.clipboardListWidget} @type previousItem: U{B{QListWidgetItem} <http://doc.trolltech.com/4.2/qlistwidgetitem.html>} """ if not (currentItem or previousItem): return itemId = self.clipboardListWidget.row(currentItem) if itemId != -1: newChunk = self.pastableItems[itemId] self.clipboardListWidget.setCurrentRow(itemId) self._updateElementViewer(newChunk) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.w.connect else: change_connect = self.w.disconnect change_connect( self.clipboardListWidget, SIGNAL("currentItemChanged(QListWidgetItem*,QListWidgetItem*)"), self.clipboardListItemChanged ) def currentRow(self): """ Return the current row of the selected item in this groupbox's listwidget ( L{self.clipboardListWidget} ) @return: Current Row of the selected pastable item in the clipboard groupbox. @rtype: int """ currentRow = self.clipboardListWidget.currentRow() return currentRow
NanoCAD-master
cad/src/PM/PM_Clipboard.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ PM_FontComboBox.py @author: Derrick @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. """ from PyQt4.Qt import QFontComboBox from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget class PM_FontComboBox( QFontComboBox ): """ Much (practically all) of this code was taken from PM_ComboBox with only slight modifications. The PM_FontComboBox widget provides a combobox with a text label for a Property Manager group box. The text label can be positioned on either the left or right side of the combobox. For a more complete explanation of a ComboBox, refer to the definition provided in PM_ComboBox. In this case, the list of available fonts is not provided by variable, but is read from the system. @cvar defaultFont: The default font of the combobox. @type defaultFont: QFont @cvar setAsDefault: Determines whether to reset the currentFont to the defaultFont when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this combobox. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @see: U{B{QComboBox}<http://doc.trolltech.com/4/qcombobox.html>} """ defaultFont = None setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, selectFont = '', setAsDefault = True, spanWidth = False ): """ Appends a QFontComboBox widget (with a QLabel widget) to <parentWidget>, a property manager group box. Arguments: @param parentWidget: the group box containing this PM widget. @type parentWidget: PM_GroupBox @param label: label that appears to the left of (or above) this PM widget. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param selectFont: initial font of combobox. (''=default) @type selectFont: QFont object (default = '') @param setAsDefault: if True, will restore <defaultFont> as the current Font when the "Restore Defaults" button is clicked. @type setAsDefault: bool (default True) @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) @see: U{B{QComboBox}<http://doc.trolltech.com/4/qcombobox.html>} """ if 0: # Debugging code print "PM_FontComboBox.__init__():" print " label =", label print " selectFont =", selectFont print " setAsDefault =", setAsDefault print " spanWidth =", spanWidth QFontComboBox.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Set initial choice (selectFont). if selectFont != '': self.setCurrentFont(selectFont) self.defaultFont = self.currentFont() parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setCurrentFont(self.defaultFont) def hide(self): """ Hides the combobox and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the combobox and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_FontComboBox ############################
NanoCAD-master
cad/src/PM/PM_FontComboBox.py
""" The Property Manager (PM) module provides classes for creating NE1 property manager dialogs. The main class in the PM module is L{PM_Dialog}, which is a base class. It can contain one or more group boxes (L{PM_GroupBox}) that can contain one or more PM widgets. IMAGE(http://www.nanoengineer-1.net/mediawiki/images/1/1d/PM-UML.png) @see: U{B{Property Manager dialog}<http://www.nanoengineer-1.net/mediawiki/ index.php?title=Property_Manager>} """
NanoCAD-master
cad/src/PM/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_StackedWidget.py @author: Mark @version: $Id$ @copyright: 2008 Nanorex, Inc. All rights reserved. History: Mark 2008-05-07: Written for L{DnaDisplayStyle_PropertyManager} to deal with the UI requirements imposed by adding all the DNA display style preferences into a property manager. """ from PyQt4.Qt import QStackedWidget from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_ListWidget import PM_ListWidget class PM_StackedWidget( QStackedWidget ): """ The PM_StackedWidget widget provides a QStackedWidget for a Property Manager group box (PM_GroupBox). Detailed Description ==================== The PM_StackedWidget class provides a stack of widgets where only one widget is visible at a time. PM_StackedWidget can be used to create a user interface similar to the one provided by QTabWidget. It is a convenience layout widget built on top of the QStackedLayout class. PM_StackedWidget can be constructed and populated with a number of child widgets ("pages"). PM_StackedWidget can be supplied with a I{switchPageWidget} as a means for the user to switch pages. This is typically a PM_ComboBox or a PM_ListWidget that stores the titles of the PM_StackedWidget's pages. When populating a stacked widget, the widgets are added to an internal list. The indexOf() function returns the index of a widget in that list. The widgets can either be added to the end of the list using the addWidget() function, or inserted at a given index using the insertWidget() function. The removeWidget() function removes the widget at the given index from the stacked widget. The number of widgets contained in the stacked widget, can be obtained using the count() function. The widget() function returns the widget at a given index position. The index of the widget that is shown on screen is given by currentIndex() and can be changed using setCurrentIndex(). In a similar manner, the currently shown widget can be retrieved using the currentWidget() function, and altered using the setCurrentWidget() function. Whenever the current widget in the stacked widget changes or a widget is removed from the stacked widget, the currentChanged() and widgetRemoved() signals are emitted respectively. @see: U{B{QStackedWidget}<http://doc.trolltech.com/4/qstackedwidget.html>} @see: For an example, see L{DnaDisplayStyle_PropertyManager}. """ labelWidget = None # Needed by the parentWidget (PM_GroupBox). _groupBoxCount = 0 switchPageWidget = None def __init__(self, parentWidget, switchPageWidget = None, childWidgetList = [], label = '', labelColumn = 0, spanWidth = True, ): """ Appends a QStackedWidget (Qt) widget to the bottom of I{parentWidget}, which must be a Property Manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param switchPageWidget: The widget that is used to switch between pages. If None (the default), it is up to the caller to manage page switching. @type switchPageWidget: PM_ComboBox or PM_ListWidget @param childWidgetList: a list of child widgets (pages), typically a list of PM_GroupBoxes that contain multiple widgets. Each child widget will get stacked onto this stacked widget as a separate page. @type childWidgetList: PM_GroupBox (or other PM widgets). @param label: label that appears above (or to the left of) this widget. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default True) @see: U{B{QStackedWidget}<http://doc.trolltech.com/4/qstackedwidget.html>} """ QStackedWidget.__init__(self) assert isinstance(parentWidget, PM_GroupBox) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.spanWidth = spanWidth for widget in childWidgetList: self.addWidget(widget) self.setSwitchPageWidget(switchPageWidget) parentWidget.addPmWidget(self) def setSwitchPageWidget(self, switchPageWidget): """ Sets the switch page widget to I{switchPageWidget}. This is the widget that controls switching between pages (child widgets) added to self. @param switchPageWidget: The widget to control switching between pages. @type switchPageWidget: PM_ComboBox or PM_ListWidget @note: Currently, we are only allowing PM_ComboBox or PM_ListWidget widgets to be switch page widgets. It would be straight forward to add support for other widgets if needed. Talk to me. --Mark. """ if switchPageWidget: assert isinstance(switchPageWidget, PM_ComboBox) or \ isinstance(switchPageWidget, PM_ListWidget) self.connect(switchPageWidget, SIGNAL("activated(int)"), self.setCurrentIndex) self.switchPageWidget = switchPageWidget # End of PM_StackedWidget ############################
NanoCAD-master
cad/src/PM/PM_StackedWidget.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ PM_TableWidget.py Simple wrapper over Qt QtableWidget class. @author: Piotr @version: $Id$ @copyright: 2008 Nanorex, Inc. All rights reserved. History: piotr 2008-07-15: Created this file. """ from PyQt4.Qt import Qt from PyQt4.Qt import QTableWidget from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget class PM_TableWidget( QTableWidget ): """ The PM_TableWidget widget provides a table widget. """ defaultState = Qt.Unchecked setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 1, setAsDefault = True, spanWidth = True ): """ Appends a QTableWidget (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. """ QTableWidget.__init__(self) self.parentWidget = parentWidget self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth self.label = QLabel(label) parentWidget.addPmWidget(self) # End of PM_TableWidget ############################
NanoCAD-master
cad/src/PM/PM_TableWidget.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ PM_DockWidget.py @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Ninad 2007-11-20: Created to implement DnaSequenceEditor TODO: - Add more documentation NOTE: methods addPmWidget and getPmWidgetPlacementParameters are duplicated from PM_GroupBox """ from PyQt4.Qt import QDockWidget from PyQt4.Qt import QLabel, QPalette from PyQt4.Qt import Qt, QWidget, QVBoxLayout, QGridLayout from PM.PM_Colors import getPalette from PM.PM_Colors import pmGrpBoxColor from PM.PM_CheckBox import PM_CheckBox from PM.PM_Constants import PM_LABEL_LEFT_ALIGNMENT, PM_LABEL_RIGHT_ALIGNMENT from utilities.icon_utilities import getpixmap from utilities.debug import print_compact_traceback class PM_DockWidget(QDockWidget): """ PM_DockWidget class provides a dockable widget that can either be docked inside a PropertyManager OR can be docked in the MainWindow depending on the <parentWidget> . see DnaSequenceEditor.py for an example. The dockWidget has its own layout and containerwidget which makes it easy to add various children widgets similar to how its done in PM_GroupBox """ def __init__(self, parentWidget, title = "", showWidget = True): """ Constructor for PM_dockWidget @param showWidget: If true, this class will show the widget immediately in the __init__ method itself. This is the default behavior and subclasses may pass appropriate value to this flag @type showWidget: bool """ self.labelWidget = None self._title = "" self._widgetList = [] self._rowCount = 0 QDockWidget.__init__(self, parentWidget) self.parentWidget = parentWidget self._title = title self.label = '' self.labelColumn = 0 self.spanWidth = True self.labelWidget = None if self.label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(self.label) self.setEnabled(True) self.setFloating(False) self.setVisible(showWidget) self.setWindowTitle(self._title) self.setAutoFillBackground(True) self.setPalette(getPalette( None, QPalette.Window, pmGrpBoxColor)) self.parentWidget.addDockWidget(Qt.BottomDockWidgetArea, self) #Define layout self._containerWidget = QWidget() self.setWidget(self._containerWidget) # Create vertical box layout self.vBoxLayout = QVBoxLayout(self._containerWidget) self.vBoxLayout.setMargin(1) self.vBoxLayout.setSpacing(0) # Create grid layout self.gridLayout = QGridLayout() self.gridLayout.setMargin(1) self.gridLayout.setSpacing(1) # Insert grid layout in its own vBoxLayout self.vBoxLayout.addLayout(self.gridLayout) #self.parentWidget.addPmWidget(self) self._loadWidgets() try: self._addWhatsThisText() except: print_compact_traceback("Error loading whatsthis text for this " \ "property manager dock widget.") try: self._addToolTipText() except: print_compact_traceback("Error loading tool tip text for this " \ "property manager dock widget.") def _loadWidgets(self): """ Subclasses should override this method. Default implementation does nothing. @see: DnaSequenceEditor._loadWidgets """ pass def _addWhatsThisText(self): """ Add 'What's This' help text for self and child widgets. Subclasses should override this method. """ pass def _addToolTipText(self): """ Add 'Tool tip' help text for self and child widgets. Subclasses should override this method. """ pass def getPmWidgetPlacementParameters(self, pmWidget): """ NOTE: This method is duplicated from PM_GroupBox Returns all the layout parameters needed to place a PM_Widget in the group box grid layout. @param pmWidget: The PM widget. @type pmWidget: PM_Widget """ row = self._rowCount #PM_CheckBox doesn't have a label. So do the following to decide the #placement of the checkbox. (can be placed either in column 0 or 1 , #This also needs to be implemented for PM_RadioButton, but at present #the following code doesn't support PM_RadioButton. if isinstance(pmWidget, PM_CheckBox): # Set the widget's row and column parameters. widgetRow = row widgetColumn = pmWidget.widgetColumn widgetSpanCols = 1 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 #set a virtual label labelRow = row labelSpanCols = 1 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT if widgetColumn == 0: labelColumn = 1 elif widgetColumn == 1: labelColumn = 0 return (widgetRow, widgetColumn, widgetSpanCols, widgetAlignment, rowIncrement, labelRow, labelColumn, labelSpanCols, labelAlignment) label = pmWidget.label labelColumn = pmWidget.labelColumn spanWidth = pmWidget.spanWidth if not spanWidth: # This widget and its label are on the same row labelRow = row labelSpanCols = 1 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT # Set the widget's row and column parameters. widgetRow = row widgetColumn = 1 widgetSpanCols = 1 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 if labelColumn == 1: widgetColumn = 0 labelAlignment = PM_LABEL_LEFT_ALIGNMENT widgetAlignment = PM_LABEL_RIGHT_ALIGNMENT 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 # Set this widget's row and column parameters. widgetRow = row + 1 # Widget is below the label. widgetColumn = 0 widgetSpanCols = 2 rowIncrement = 2 else: # No label. Just the widget. labelRow = 0 labelColumn = 0 labelSpanCols = 0 # Set the widget's row and column parameters. widgetRow = row widgetColumn = 0 widgetSpanCols = 2 rowIncrement = 1 labelAlignment = PM_LABEL_LEFT_ALIGNMENT widgetAlignment = PM_LABEL_LEFT_ALIGNMENT return (widgetRow, widgetColumn, widgetSpanCols, widgetAlignment, rowIncrement, labelRow, labelColumn, labelSpanCols, labelAlignment) def addPmWidget(self, pmWidget): """ Add a PM widget and its label to this group box. @param pmWidget: The PM widget to add. @type pmWidget: PM_Widget """ # Get all the widget and label layout parameters. widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment = self.getPmWidgetPlacementParameters(pmWidget) if pmWidget.labelWidget: #Create Label as a pixmap (instead of text) if a valid icon path #is provided labelPath = str(pmWidget.label) if labelPath and labelPath.startswith("ui/"): #bruce 080325 revised labelPixmap = getpixmap(labelPath) if not labelPixmap.isNull(): pmWidget.labelWidget.setPixmap(labelPixmap) pmWidget.labelWidget.setText('') self.gridLayout.addWidget( pmWidget.labelWidget, labelRow, labelColumn, 1, labelSpanCols, labelAlignment ) # The following is a workaround for a Qt bug. If addWidth()'s # <alignment> argument is not supplied, the widget spans the full # column width of the grid cell containing it. If <alignment> # is supplied, this desired behavior is lost and there is no # value that can be supplied to maintain the behavior (0 doesn't # work). The workaround is to call addWidget() without the <alignment> # argument. Mark 2007-07-27. if widgetAlignment == PM_LABEL_LEFT_ALIGNMENT: self.gridLayout.addWidget( pmWidget, widgetRow, widgetColumn, 1, widgetSpanCols) # aligment = 0 doesn't work. else: self.gridLayout.addWidget( pmWidget, widgetRow, widgetColumn, 1, widgetSpanCols, widgetAlignment) self._rowCount += rowIncrement
NanoCAD-master
cad/src/PM/PM_DockWidget.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_MessageGroupBox.py The PM_MessageGroupBox widget provides a message group box with a collapse/expand button and a title. @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrMessageGroupBox out of PropMgrBaseClass.py into this file and renamed it PM_MessageGroupBox. """ from PyQt4.Qt import QTextOption from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QPalette from PyQt4.Qt import QString, QTextCursor from PyQt4.Qt import Qt from PM.PM_Colors import getPalette from PM.PM_Colors import pmMessageBoxColor from PM.PM_GroupBox import PM_GroupBox from PM.PM_TextEdit import PM_TextEdit class PM_MessageGroupBox( PM_GroupBox ): """ The PM_MessageGroupBox widget provides a message box with a collapse/expand button and a title. """ def __init__(self, parentWidget, title = "Message" ): """ PM_MessageGroupBox constructor. @param parentWidget: the PM_Dialog containing this message groupbox. @type parentWidget: PM_Dialog @param title: The title on the collapse button @type title: str """ PM_GroupBox.__init__(self, parentWidget, title) self.vBoxLayout.setMargin(0) self.vBoxLayout.setSpacing(0) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.MessageTextEdit = PM_TextEdit(self, label='', spanWidth = True, addToParent = False, ##cursorPosition = 'beginning' ) # We pass addToParent = False to suppress the usual call by # PM_TextEdit.__init__ of self.addPmWidget(new textedit widget), # since we need to add it to self in a different way (below). # [bruce 071103 refactored this from what used to be a special case # in PM_TextEdit.__init__ based on self being an instance of # PM_MessageGroupBox.] # Needed for Intel MacOS. Otherwise, the horizontal scrollbar # is displayed in the MessageGroupBox. Mark 2007-05-24. # Shouldn't be needed with _setHeight() in PM_TextEdit. #Note 2008-06-17: We now permit a vertical scrollbar in message groupbox #--Ninad self.MessageTextEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Add self.MessageTextEdit to self's vBoxLayout. self.vBoxLayout.addWidget(self.MessageTextEdit) # We should be calling the PM's getMessageTextEditPalette() method, # but that will take some extra work which I will do soon. Mark 2007-06-21 self.MessageTextEdit.setPalette(getPalette( None, QPalette.Base, pmMessageBoxColor)) self.MessageTextEdit.setReadOnly(True) #@self.MessageTextEdit.labelWidget = None # Never has one. Mark 2007-05-31 self._widgetList.append(self.MessageTextEdit) self._rowCount += 1 # 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) parentWidget.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 expand(self): """ Expand this group box i.e. show all its contents and change the look and feel of the groupbox button. It also sets the gridlayout margin and spacing to 0. (necessary to get rid of the extra space inside the groupbox.) @see: L{PM_GroupBox.expand} """ PM_GroupBox.expand(self) # 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) def insertHtmlMessage(self, text, setAsDefault = False, minLines = 4, maxLines = 10, replace = True, scrolltoTop = True): """ Insert text (HTML) into the message box. Displays the message box if it is hidden. Arguments: @param 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). @type minLines: int @param maxLines: The maximum number of lines to display in the TextEdit widget. @type maxLines: int @param replace: should be set to False if you do not wish to replace the current text. It will append <text> instead. @type replace: int @note: Displays the message box if it is hidden. """ self.MessageTextEdit.insertHtml( text, setAsDefault, minLines = minLines, maxLines = maxLines, replace = True ) if scrolltoTop: cursor = self.MessageTextEdit.textCursor() cursor.setPosition( 0, QTextCursor.MoveAnchor ) self.MessageTextEdit.setTextCursor( cursor ) self.MessageTextEdit.ensureCursorVisible() ##self.MessageTextEdit.moveCursor(QTextCursor.Start) ##self.MessageTextEdit.ensureCursorVisible() #text2 = self.MessageTextEdit.toPlainText() #print "***PM = %s, len(text) =%s"%(self.parentWidget, len(text)) #if len(text2) > 16: #anchorText = text2[:16] #print "***anchorText =", anchorText #self.MessageTextEdit.scrollToAnchor(anchorText) #self.MessageTextEdit.ensureCursorVisible() self.show() # End of PM_MessageGroupBox ############################
NanoCAD-master
cad/src/PM/PM_MessageGroupBox.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_ToolButtonGrid.py @author: Mark Sims @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-08-02: Created. ninad 2007-08-14: New superclass PM_WidgetGrid. Related refactoring and cleanup. """ import sys from PyQt4.Qt import QButtonGroup from PyQt4.Qt import QFont from PyQt4.Qt import QSize from PM.PM_WidgetGrid import PM_WidgetGrid BUTTON_FONT = "Arial" BUTTON_FONT_BOLD = True if sys.platform == "darwin": BUTTON_FONT_POINT_SIZE = 18 else: # Windows and Linux BUTTON_FONT_POINT_SIZE = 10 class PM_ToolButtonGrid( PM_WidgetGrid ): """ The PM_ToolButtonGrid widget provides a grid of tool buttons that function as an I{exclusive button group}. @see: B{PM_ElementChooser} for an example of how this is used. @todo: Fix button size issue (e.g. all buttons are sized 32 x 32). """ buttonList = [] defaultCheckedId = -1 # -1 means no checked Id setAsDefault = True def __init__(self, parentWidget, title = '', buttonList = [], alignment = None, label = '', labelColumn = 0, spanWidth = True, checkedId = -1, setAsDefault = False, isAutoRaise = False, isCheckable = True ): """ Appends a PM_ToolButtonGrid widget to the bottom of I{parentWidget}, the Property Manager Group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param title: The group box title. @type title: str @param buttonList: A list of I{button info lists}. There is one button info list for each button in the grid. The button info list contains the following items: 1. Button Type - in this case its 'ToolButton'(str), 2. Button Id (int), 3. Button text (str), 4. Button icon path (str), 5. Button tool tip (str), 6. Column (int), 7. Row (int). @type buttonList: list @param alignment: The alignment of the toolbutton row in the parent groupbox. Based on its value,spacer items is added to the grid layout of the parent groupbox. @type alignment: str @param label: The label for the toolbutton row. If present, it is added to the same grid layout as the rest of the toolbuttons, in column number E{0}. @type label: str @param labelColumn: The column in the parentWidget's grid layout to which this widget's label will be added. The labelColum can only be E{0} or E{1} @type labelColumn: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) @param checkedId: Checked button id in the button group. Default value is -1 that implies no button is checked. @type checkedId: int @param setAsDefault: If True, sets the I{checkedId} specified by the user as the default checked @type setAsDefault: boolean """ self.buttonGroup = QButtonGroup() self.buttonGroup.setExclusive(True) self.isAutoRaise = isAutoRaise self.isCheckable = isCheckable self.buttonsById = {} self.buttonsByText = {} if setAsDefault: self.setDefaultCheckedId(checkedId) PM_WidgetGrid.__init__(self, parentWidget , title, buttonList, alignment, label, labelColumn, spanWidth ) def _createWidgetUsingParameters(self, widgetParams): """ Returns a tool button created using the parameters specified by the user @param widgetParams: A list of label parameters. This is a modified using the original list returned by L{self.getWidgetInfoList}. The modified list doesn't contain the row and column information. @type widgetParams: list @see: L{PM_WidgetGrid._createWidgetUsingParameters} (overrided in this method) @see: L{PM_WidgetGrid.loadWidgets} which calls this method. """ buttonFont = self.getButtonFont() buttonParams = list(widgetParams) button = self._createToolButton(buttonParams) buttonId = buttonParams[1] if self.defaultCheckedId == buttonId: button.setChecked(True) button.setFont(buttonFont) button.setAutoRaise(self.isAutoRaise) button.setCheckable(self.isCheckable) self.buttonGroup.addButton(button, buttonId) self.buttonsById[buttonId] = button self.buttonsByText[str(button.text())] = button return button def getButtonFont(self): """ Returns the font for the tool buttons in the grid. @return: Button font. @rtype: U{B{QFont}<http://doc.trolltech.com/4/qfont.html>} """ # Font for tool buttons. buttonFont = QFont(self.font()) buttonFont.setFamily(BUTTON_FONT) buttonFont.setPointSize(BUTTON_FONT_POINT_SIZE) buttonFont.setBold(BUTTON_FONT_BOLD) return buttonFont def restoreDefault(self): """ Restores the default checkedId. """ if self.setAsDefault: for buttonInfo in self.buttonList: buttonId = buttonInfo[0] if buttonId == self.defaultCheckedId: button = self.getButtonById(buttonId) button.setChecked(True) return def setDefaultCheckedId(self, checkedId): """ Sets the default checked id (button) to I{checkedId}. The current checked button is unchanged. @param checkedId: The new default id for the tool button group. @type checkedId: int """ self.setAsDefault = True self.defaultCheckedId = checkedId def checkedButton(self): """ Returns the tool button group's checked button, or E{0} if no button is checked. @return: Checked tool button or E{0} @rtype: instance of QToolButton or int """ return self.buttonGroup.checkedButton() def checkedId(self): """ Returns the id of the checkedButton(), or -1 if no button is checked. @return: The checked button Id @rtype: int """ return self.buttonGroup.checkedId() def getButtonByText(self, text): """ Returns the button with its current text set to I{text}. @return: The button, or B{None} if no button was found. @rtype: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} @note: If multiple buttons have the same text, only the last one is returned. """ if self.buttonsByText.has_key(text): return self.buttonsByText[text] else: return None def getButtonById(self, buttonId): """ Returns the button with the button id of I{buttonId}. return: The button, or B{None} if no button was found. rtype: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ if self.buttonsById.has_key(buttonId): return self.buttonsById[buttonId] else: return None def setButtonSize(self, width = 32, height = 32): """ """ for btn in self.buttonGroup.buttons(): btn.setFixedSize(QSize(width, height)) # End of PM_ToolButtonGrid ############################
NanoCAD-master
cad/src/PM/PM_ToolButtonGrid.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_WidgetsDemoPropertyManager.py - Displays all the PM module widgets in a PM. $Id$ """ from PyQt4.Qt import Qt, SIGNAL from PM.PM_Dialog import PM_Dialog 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_ElementChooser import PM_ElementChooser from PM.PM_LineEdit import PM_LineEdit from PM.PM_ListWidget import PM_ListWidget from PM.PM_PushButton import PM_PushButton from PM.PM_RadioButton import PM_RadioButton from PM.PM_RadioButtonList import PM_RadioButtonList from PM.PM_SpinBox import PM_SpinBox from PM.PM_TextEdit import PM_TextEdit from PM.PM_ToolButton import PM_ToolButton from PM.PM_ToolButtonGrid import PM_ToolButtonGrid from command_support.GeneratorBaseClass import GeneratorBaseClass # Options for radio button list to create a PM_RadioButtonList widget. # Format: buttonId, buttonText, tooltip OPTIONS_BUTTON_LIST = [ \ ( 0, "Option 1", "Tooltip text for option 1"), ( 1, "Option 2", "Tooltip text for option 2"), ( 2, "Option 3", "Tooltip text for option 3"), ( 3, "Option 4", "Tooltip text for option 4") ] # Tool button list to create a PM_ToolButtonGrid. # Format: # - buttonId, buttonText, iconPath, column, row, tooltipText TOOL_BUTTON_LIST = [ \ ( 5, "B", "", 0, 1, "Boron" ), ( 6, "C", "", 1, 1, "Carbon" ), ( 7, "N", "", 2, 1, "Nitrogen" ), ( 8, "O", "", 3, 1, "Oxygen" ), ( 9, "F", "", 4, 1, "Fluorine" ), (10, "Ne", "", 5, 1, "Neon" ), (13, "Al", "", 0, 2, "Aluminum" ), (14, "Si", "", 1, 2, "Silicon" ), (15, "P", "", 2, 2, "Phosphorus" ), (16, "S", "", 3, 2, "Sulfur" ), (17, "Cl", "", 4, 2, "Chlorine" ), (18, "Ar", "", 5, 2, "Argon" ) ] class PM_WidgetsDemoPropertyManager(PM_Dialog, GeneratorBaseClass): """ This is a special command for testing new widgets in the PM module in their own Property Manager. It does nothing except display PM group boxes and their widgets. """ title = "PM Widget Demo" pmName = title iconPath = "ui/actions/Properties Manager/info.png" def __init__(self, win, command = None): self.win = win PM_Dialog.__init__( self, self.pmName, self.iconPath, self.title ) GeneratorBaseClass.__init__( self, win) msg = "This Property Manager (PM) is used to display and/or test new \ PM widgets avaiable in NanoEngineer-1's PM module." # This causes the "Message" box to be displayed as well. self.MessageGroupBox.insertHtmlMessage( msg, setAsDefault = False ) return def _addGroupBoxes(self): """ Add group boxes to the Property Manager. """ self.widgetSelectorGroupBox = PM_GroupBox(self, title = "PM Widget Selector" ) self._loadWidgetSelectorGroupBox(self.widgetSelectorGroupBox) self.groupBoxes = [] pmGroupBox = PM_GroupBox(self, title = "PM_CheckBox") self._loadPM_CheckBox(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_ComboBox") self._loadPM_ComboBox(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_DoubleSpinBox") self._loadPM_DoubleSpinBox(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_ElementChooser(self, title = "PM_ElementChooser") self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_LineEdit") self._loadPM_LineEdit(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_ListWidget") self._loadPM_ListWidget(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_PushButton") self._loadPM_PushButton(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_RadioButton") self._loadPM_TextEdit(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_RadioButtonList( self, title = "PM_RadioButtonList", buttonList = OPTIONS_BUTTON_LIST, checkedId = 2 ) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_SpinBox") self._loadPM_SpinBox(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_TextEdit") self._loadPM_TextEdit(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_GroupBox(self, title = "PM_ToolButton") self._loadPM_ToolButton(pmGroupBox) self.groupBoxes.append(pmGroupBox) pmGroupBox = PM_ToolButtonGrid( self, title = "PM_ToolButtonGrid", buttonList = TOOL_BUTTON_LIST, checkedId = 6, setAsDefault = True ) self.groupBoxes.append(pmGroupBox) self.widgetSelectorComboBox.clear() titles = self._getGroupBoxTitles() self.widgetSelectorComboBox.addItems(titles) self._updateGroupBoxes(0) def _loadWidgetSelectorGroupBox(self, inPmGroupBox): """ Widget selector group box. """ # The widget choices are set via self._getGroupBoxTitles() later. widgetTypeChoices = [ "PM_CheckBox" ] self.widgetSelectorComboBox = \ PM_ComboBox( inPmGroupBox, label = "Select a PM widget:", choices = widgetTypeChoices, index = 0, setAsDefault = False, spanWidth = True ) self.connect(self.widgetSelectorComboBox, SIGNAL("currentIndexChanged(int)"), self._updateGroupBoxes) def _loadPM_CheckBox(self, inPmGroupBox): """ PM_CheckBox. """ self.checkBoxGroupBox = \ PM_GroupBox( inPmGroupBox, title = "<b> PM_CheckBox examples</b>" ) self.checkBox1 = \ PM_CheckBox( self.checkBoxGroupBox, text = "Label on left:", widgetColumn = 1, state = Qt.Checked, setAsDefault = True, ) self.checkBox2 = \ PM_CheckBox( self.checkBoxGroupBox, text = ": Label on right", widgetColumn = 1, state = Qt.Checked, setAsDefault = True, ) self.checkBox3 = \ PM_CheckBox( self.checkBoxGroupBox, text = "CheckBox (spanWidth = True):", state = Qt.Unchecked, setAsDefault = False, ) def _loadPM_ComboBox(self, inPmGroupBox): """ PM_ComboBox widgets. """ choices = [ "First", "Second", "Third (Default)", "Forth" ] self.comboBox1= \ PM_ComboBox( inPmGroupBox, label = 'Choices: ', choices = choices, index = 2, setAsDefault = True, spanWidth = False ) self.comboBox2= \ PM_ComboBox( inPmGroupBox, label = ' :Choices', labelColumn = 1, choices = choices, index = 2, setAsDefault = True, spanWidth = False ) self.comboBox3= \ PM_ComboBox( inPmGroupBox, label = ' Choices (SpanWidth = True):', labelColumn = 1, choices = choices, index = 2, setAsDefault = True, spanWidth = True ) self.nestedGroupBox1 = \ PM_GroupBox( inPmGroupBox, title = "Group Box Title" ) self.comboBox4= \ PM_ComboBox( self.nestedGroupBox1, label = "Choices:", choices = choices, index = 2, setAsDefault = True, spanWidth = False ) self.nestedGroupBox2 = \ PM_GroupBox( inPmGroupBox, title = "Group Box Title" ) self.comboBox6= \ PM_ComboBox( self.nestedGroupBox2, label = "Choices:", choices = choices, index = 2, setAsDefault = True, spanWidth = True ) def _loadPM_DoubleSpinBox(self, inPmGroupBox): """ PM_DoubleSpinBox widgets. """ self.doubleSpinBox = \ PM_DoubleSpinBox( inPmGroupBox, #label="Spanning DoubleSpinBox :", label = "", # No label value = 5.0, setAsDefault = True, minimum = 1.0, maximum = 10.0, singleStep = 1.0, decimals = 1, suffix = ' Suffix', spanWidth = True ) # Add a prefix example. self.doubleSpinBox.setPrefix("Prefix ") def _loadPM_LineEdit(self, inPmGroupBox): """ PM_LineEdit widgets. """ self.lineEdit1 = \ PM_LineEdit( inPmGroupBox, label = "Name:", text = "RotaryMotor-1", setAsDefault = True, spanWidth = False) self.lineEdit2 = \ PM_LineEdit( inPmGroupBox, label = ":Name", labelColumn = 1, text = "RotaryMotor-1", setAsDefault = True, spanWidth = False) self.lineEdit3 = \ PM_LineEdit( inPmGroupBox, label = "LineEdit (spanWidth = True):", text = "RotaryMotor-1", setAsDefault = False, spanWidth = True) def _loadPM_ListWidget(self, inPmGroupBox): """ PM_ListWidget. """ items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"] self.listWidget1 = \ PM_ListWidget( inPmGroupBox, label = "Items to select (label on top):", items = items, defaultRow = 0, setAsDefault = False, heightByRows = 4, spanWidth = True ) self.listWidget2 = \ PM_ListWidget( inPmGroupBox, label = "Items:", items = items, defaultRow = 0, setAsDefault = False, heightByRows = 4, spanWidth = False ) def _loadPM_PushButton(self, inPmGroupBox): """ PM_PushButton widgets. """ self.pushButton1 = \ PM_PushButton( inPmGroupBox, label = "", text = "PushButton 1" ) self.pushButton2 = \ PM_PushButton( inPmGroupBox, label = "", text = "PushButton 2", spanWidth = True ) def _loadPM_RadioButton(self, inPmGroupBox): """ PM_RadioButton. """ self.radioButton1 = \ PM_RadioButton( inPmGroupBox, text = "Display PM_CheckBox group box") def _loadPM_SpinBox(self, inPmGroupBox): """ PM_SpinBox widgets. """ self.spinBox = \ PM_SpinBox( inPmGroupBox, label = "Spinbox:", value = 5, setAsDefault = True, minimum = 2, maximum = 10, suffix = ' things', spanWidth = True ) def _loadPM_TextEdit(self, inPmGroupBox): """ PM_TextEdit widgets. """ self.textEdit = \ PM_TextEdit( inPmGroupBox, label = "TextEdit:", spanWidth = False ) self.spanTextEdit = \ PM_TextEdit( inPmGroupBox, label = "PM_TextEdit with label on top:", spanWidth = True ) def _loadPM_ToolButton(self, inPmGroupBox): """ PM_ToolButton widgets. """ self.toolButton1 = \ PM_ToolButton( inPmGroupBox, label = "", text = "ToolButton 1" ) self.toolButton2 = \ PM_ToolButton( inPmGroupBox, label = "", text = "ToolButton 2", spanWidth = True ) def _getGroupBoxTitles(self): """ Returns all the group box titles in a list. """ titles = [] for groupBox in self.groupBoxes: titles.append(groupBox.getTitle()) return titles def _updateGroupBoxes(self, index): """ Update the group boxes displayed based index. """ count = 0 for groupBox in self.groupBoxes: if index == count: groupBox.show() else: groupBox.hide() count += 1
NanoCAD-master
cad/src/PM/PM_WidgetsDemoPropertyManager.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_ToolButtonRow.py @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-07: Created. ninad 2007-08-14: Changes due to the new superclass of PM_ToolButtonGrid. """ from PM.PM_ToolButtonGrid import PM_ToolButtonGrid class PM_ToolButtonRow( PM_ToolButtonGrid ): """ The PM_ToolButtonRow widget provides a row of tool buttons that function as an I{exclusive button group}. @see: B{Ui_MovePropertyManager} for an example of how this is used. """ def __init__(self, parentWidget, title = '', buttonList = [], alignment = None, label = '', labelColumn = 0, spanWidth = False, checkedId = -1, setAsDefault = False, isAutoRaise = True, isCheckable = True ): """ Appends a PM_ToolButtonRow widget to the bottom of I{parentWidget}, the Property Manager dialog or group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param title: The group box title. @type title: str @param buttonList: A list of I{button info lists}. There is one button info list for each button in the grid. The button info list contains the following items: (notice that this list doesn't contain the 'row' which is seen in B{PM_ToolButtonGrid}.) 1. Button Type - in this case its 'ToolButton'(str), 2. Button Id (int), 3. Button text (str), 4. Button icon path (str), 5. Button tool tip (str), 6. Column (int). @type buttonList: list @param alignment: The alignment of the toolbutton row in the parent groupbox. Based on its value,spacer items is added to the grid layout of the parent groupbox. @type alignment: str @param label: The label for the toolbutton row. If present, it is added to the same grid layout as the rest of the toolbuttons, in column number E{0}. @type label: str @param labelColumn: The column in the parentWidget's grid layout to which this widget's label will be added. The labelColum can only be E{0} or E{1} @type labelColumn: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) @param checkedId: Checked button id in the button group. Default value is -1 that implies no button is checked. @type checkedId: int @param setAsDefault: If True, sets the I{checkedId} specified by the user as the default checked @type setAsDefault: boolean """ PM_ToolButtonGrid.__init__(self, parentWidget, title, buttonList, alignment, label, labelColumn, spanWidth, checkedId, setAsDefault, isAutoRaise, isCheckable) def getWidgetInfoList(self, buttonInfo): """ Returns the button information provided by the user. Overrides the L{PM_WidgetGrid.getWidgetInfoList} This is used to set custom information (e.g. a fixed value for row) for the button. @param buttonInfo: list containing the button information @type buttonInfo: list @return: A list containing the button information. This can be same as I{buttonInfo} or can be modified further. @rtype: list @see: L{PM_WidgetGrid.getWidgetInfoList} (overrides this method) """ buttonInfoList = [] buttonType = buttonInfo[0] buttonId = buttonInfo[1] buttonText = buttonInfo[2] buttonIconPath = buttonInfo[3] buttonToolTip = buttonInfo[4] buttonShortcut = buttonInfo[5] column = buttonInfo[6] row = 0 buttonInfoList = [ buttonType, buttonId, buttonText, buttonIconPath, buttonToolTip, buttonShortcut, column, row] return buttonInfoList def _getStyleSheet(self): """ Return the style sheet for the toolbutton row. This sets the following properties only: - border style - border width - border color - border radius (on corners) @see: L{PM_GroupBox._getStyleSheet} (overrides this method) """ #For a toolbutton row, we don't (usually) need a borders . So set #the style sheet accordingly styleSheet = \ "QGroupBox {border-style:hidden; \ border-width: 0px; \ border-color: ""; \ border-radius: 0px; \ min-width: 10em; }" return styleSheet
NanoCAD-master
cad/src/PM/PM_ToolButtonRow.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ This class provides a table widget to display search results for a DnaStrand or DnaSegment. It displays node name in one column and number of nucleotides in the other. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: Created between Nov 8-12, 2008 for Mark's consulting work. Needs cleanup """ from utilities.debug import print_compact_traceback from PyQt4.Qt import Qt, SIGNAL from PyQt4.Qt import QLabel from PyQt4.Qt import QTableWidgetItem from utilities.icon_utilities import geticon from PM.PM_TableWidget import PM_TableWidget from PM.PM_Colors import pmGrpBoxColor from PM.PM_Colors import pmGrpBoxBorderColor from widgets.widget_helpers import QColor_to_Hex _superclass = PM_TableWidget class PM_DnaSearchResultTable(PM_TableWidget): def __init__(self, parentWidget, win, items = [], label = '', labelColumn = 1, setAsDefault = True, spanWidth = True ): """ """ self.win = win self.glpane = self.win.glpane self._suppress_itemChanged_signal = False self._suppress_itemSelectionChanged_signal = False self._itemDictionary = {} _superclass.__init__(self, parentWidget, label = label, labelColumn = labelColumn, setAsDefault = setAsDefault, spanWidth = spanWidth ) self.setColumnCount(2) self.setFixedHeight(200) self.setSortingEnabled(True) ##self.setAutoFillBackground(True) ##self.setStyleSheet(self._getStyleSheet()) self.insertItems(0, items) 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: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self, SIGNAL('itemSelectionChanged()'), self.tagItems) def insertItems(self, row, items): """ Insert the <items> specified items in this list widget. The list widget shows item name string , as a QListwidgetItem. This QListWidgetItem object defines a 'key' of a dictionary (self._itemDictionary) and the 'value' of this key is the object specified by the 'item' itself. Example: self._itemDictionary['C6'] = instance of class Atom. @param row: The row number for the item. @type row: int @param items: A list of objects. These objects are treated as values in the self._itemDictionary @type items: list @param setAsDefault: Not used here. See PM_ListWidget.insertItems where it is used. @see: self.renameItemValue() for a comment about self._suppress_itemChanged_signal """ #self.__init__ for a comment about this flag self._suppress_itemChanged_signal = True #Clear the previous contents of the self._itemDictionary self._itemDictionary.clear() #Clear the contents of this list widget, using QListWidget.clear() #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details self.clear() seq = ['Node name', 'Number of bases'] self.setHorizontalHeaderLabels(seq) self.setRowCount(len(items)) idx = 0 self.setSortingEnabled(False) for item in items: if hasattr(item.__class__, 'name'): itemName = item.name else: itemName = str(item) numberOfBasesString = '' if isinstance(item, self.win.assy.DnaStrand): numberOfBasesString = str(len(item.getAllAtoms())) elif isinstance(item, self.win.assy.DnaSegment): numberOfBasesString = str(item.getNumberOfBasePairs()) tableWidgetItem = QTableWidgetItem(itemName) ###When we support editing list widget items , uncomment out the ###following line . See also self.editItems -- Ninad 2008-01-16 ##tableWidgetItem.setFlags( tableWidgetItem.flags()| Qt.ItemIsEditable) if hasattr(item.__class__, 'iconPath'): try: tableWidgetItem.setIcon(geticon(item.iconPath)) except: print_compact_traceback() self._itemDictionary[tableWidgetItem] = item self.setItem(idx, 0, tableWidgetItem) tableWidgetItem_column_2 = QTableWidgetItem(numberOfBasesString) tableWidgetItem_column_2.setFlags(Qt.ItemIsEnabled) self.setItem(idx, 1, tableWidgetItem_column_2) idx += 1 #Reset the flag that temporarily suppresses itemChange signal. self._suppress_itemChanged_signal = False self.setSortingEnabled(True) def tagItems(self): """ For the selected items in the table widget, select the corresponding item in the GLPane. """ if self._suppress_itemSelectionChanged_signal: return #Unpick all list widget items in the 3D workspace #if no modifier key is pressed. Earlier implementation #used to only unpick items that were also present in the list #widgets.But if we have multiple list widgets, example like #in Build DNA mode, it can lead to confusion like in Bug 2681 #NOTE ABOUT A NEW POSSIBLE BUG: #self.glpan.modkeys not changed when focus is inside the #Property manager? Example: User holds down Shift key and starts #selecting things inside -- Ninad 2008-03-18 if self.glpane.modkeys is None: self.win.assy.unpickall_in_GLPane() #Deprecated call of _unpick_all_widgetItems_in_glpane #(deprecated on 2008-03-18 ##self._unpick_all_widgetItems_in_glpane() #Now pick the items selected in this list widget self._pick_selected_widgetItems_in_glpane() self.glpane.gl_update() def _pick_selected_widgetItems_in_glpane(self): """ If some items in the list widgets are selected (in the widget) also select (pick) them from the glpane(3D workspace) """ for key in self.selectedItems(): column = self.column(key) if column == 0: actual_key = key else: row = self.row(key) actual_key = self.item(row, 0) assert self._itemDictionary.has_key(actual_key) item = self._itemDictionary[actual_key] if not item.picked: item.pick() def updateSelection(self, selectedItemList): """ Update the selected items in this selection list widget. The items given by the parameter selectedItemList will get selected. This suppresses the 'itemSelectionChanged signal because the items are already selected in the 3D workspace and we just want to select the corresponding items (QWidgetListItems) in this list widget. @param selectedItemList: List of items provided by the client that need to be selected in this list widget @type selectedItemList: list @see: B{BuildDna_PropertyManager.model_changed} """ #The following flag suppresses the itemSelectionChanged signal , thereby #prevents self.tagItems from calling. This is done because the #items selection was changed from the 3D workspace. After this, the #selection state of the corresponding items in the list widget must be #updated. self._suppress_itemSelectionChanged_signal = True for key, value in self._itemDictionary.iteritems(): if value in selectedItemList: if not key.isSelected(): key.setSelected(True) else: if key.isSelected(): key.setSelected(False) self._suppress_itemSelectionChanged_signal = False def _zzgetStyleSheet(self): """ Return the style sheet for the groupbox. This sets the following properties only: - border style - border width - border color - border radius (on corners) - background color @return: The group box style sheet. @rtype: str """ styleSheet = \ "QTableWidget QTableButton::section{"\ "border: 2px outset #%s; "\ "background: #%s; "\ "}" % ( QColor_to_Hex(pmGrpBoxBorderColor), QColor_to_Hex(pmGrpBoxColor) ) return styleSheet
NanoCAD-master
cad/src/PM/PM_DnaSearchResultTable.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_TextEdit.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrTextEdit out of PropMgrBaseClass.py into this file and renamed it PM_TextEdit. """ from PM.PM_Constants import PM_MINIMUM_WIDTH ##from PM.PM_Colors import getPalette ##from PM.PM_Colors import pmMessageBoxColor from PyQt4.Qt import Qt from PyQt4.Qt import QLabel from PyQt4.Qt import QSize from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QTextCursor from PyQt4.Qt import QTextEdit ##from PyQt4.Qt import QPalette from PyQt4.Qt import QWidget from PyQt4.Qt import QTextCharFormat from PyQt4.Qt import SIGNAL class PM_TextEdit( QTextEdit ): """ The PM_TextEdit widget provides a QTextEdit with a QLabel for a Property Manager groupbox. @cvar defaultText: The default text of the textedit. @type defaultText: str @cvar setAsDefault: Determines whether to reset the value of the textedit to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this textedit. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultText = "" setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, spanWidth = False, addToParent = True, permit_enter_keystroke = True ): """ Appends a QTextEdit (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. The QTextEdit is empty (has no text) by default. Use insertHtml() to insert HTML text into the TextEdit. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left of (or above) the spin box. To suppress the label, set I{label} to an empty string. @type label: str @param spanWidth: If True, the spin box and its label will span the width of the group box. The label will appear directly above the spin box and is left justified. @type spanWidth: bool @param addToParent: If True (the default), self will be added to parentWidget by passing it to parentWidget.addPmWidget. If False, self will not be added to parentWidget. Typically, when this is False, the caller will add self to parent in some other way. @type addToParent: bool @param permit_enter_keystroke: If set to True, this PM_textEdit can have multiple lines. Otherwise, it will block the 'Enter' keypress within the text editor. Note that caller needs to make sure that linewrapping option is appropriately set, (in addition to this flag) so as to permit/ not permit multiple lines in the text edit. @see: U{B{QTextEdit}<http://doc.trolltech.com/4/qtextedit.html>} """ if 0: # Debugging code print "QTextEdit.__init__():" print " label =", label print " labelColumn =", labelColumn print " spanWidth =", spanWidth QTextEdit.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.spanWidth = spanWidth self._permit_enter_keystroke = permit_enter_keystroke if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) self._setHeight() # Default height is 4 lines high. ## from PM.PM_MessageGroupBox import PM_MessageGroupBox ## if isinstance(parentWidget, PM_MessageGroupBox): ## # Add to parentWidget's vBoxLayout if <parentWidget> is a MessageGroupBox. ## parentWidget.vBoxLayout.addWidget(self) ## # We should be calling the PM's getMessageTextEditPalette() method, ## # but that will take some extra work which I will do soon. Mark 2007-06-21 ## self.setPalette(getPalette( None, ## QPalette.Base, ## pmMessageBoxColor)) ## self.setReadOnly(True) ## #@self.labelWidget = None # Never has one. Mark 2007-05-31 ## parentWidget._widgetList.append(self) ## parentWidget._rowCount += 1 ## else: ## parentWidget.addPmWidget(self) # bruce 071103 refactored the above into the new addToParent option and # code added to PM_MessageGroupBox.__init__ after it calls this method. if addToParent: parentWidget.addPmWidget(self) return def keyPressEvent(self, event): """ Overrides the superclass method. """ #If user hits 'Enter' key (return key), don't do anything. if event.key() == Qt.Key_Return: #Urmi 20080724: emit a signal to indicate end of processing self.emit(SIGNAL("editingFinished()")) #there is no obvious way to allow only a single line in a #QTextEdit (we can use some methods that restrict the columnt width #, line wrapping etc but this is untested when the line contains # huge umber of characters. Anyway, the following always works #and fixes bug 2713 if not self._permit_enter_keystroke: return QTextEdit.keyPressEvent(self, event) 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 ) #Don't call _setHeight after insertHtml, it increases the height of the #text widget and thus gives an undesirable visual effect. #This was seen in DnaSequenceEditor. Also tried using 'setSizePolicy' like #done in PM_MessagegroupBox but that didn't work. ##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 PM_TextEdit 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 PM_TextEdit)=", current_width # Reset height of PM_TextEdit. self.setMinimumSize(QSize(PM_MINIMUM_WIDTH * 0.5, new_height)) self.setMaximumHeight(new_height) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.insertHtml(self.defaultText, setAsDefault = True, replace = True) def hide(self): """ Hides the tool button and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the tool button and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_TextEdit ############################
NanoCAD-master
cad/src/PM/PM_TextEdit.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ GroupButtonMixin.py $Id$ History and status: Written by Will in GeneratorBaseClass.py, but no longer used there or by anything that uses it. bruce 070619 moved this from GeneratorBaseClass.py to its own file. It is deprecated; its uses should be replaced by rewriting its callers to use the PM package. Module classification: As of 071214, it is used only by MinimizeEnergyProp and PovraySceneProp, which should be rewritten to use PM_Dialog and get things like this file provides from PM package, so I am classifying it as if it was part of the PM package. [bruce 071214] """ __author__ = "Will" from PyQt4.Qt import QPixmap, QIcon _up_arrow_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" \ "\x00\x00\x00\x10\x00\x00\x00\x10\x08\x02\x00\x00\x00\x90\x91\x68" \ "\x36\x00\x00\x00\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0" \ "\xbd\xa7\x93\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00" \ "\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45" \ "\x07\xd6\x06\x03\x03\x21\x26\xc9\x92\x21\x9b\x00\x00\x00\x10\x74" \ "\x45\x58\x74\x43\x6f\x6d\x6d\x65\x6e\x74\x00\x4e\x61\x6e\x6f\x74" \ "\x75\x62\x65\xa3\x8c\x3b\xec\x00\x00\x00\xda\x49\x44\x41\x54\x28" \ "\xcf\xb5\x92\x41\x0e\x82\x30\x10\x45\x5b\xe3\x01\x24\x14\x69\x39" \ "\x01\x3d\x83\x6c\x24\xdc\xc0\xb0\x31\x5c\x8f\x78\x8b\x76\x16\x70" \ "\x95\xb2\x01\x71\xcd\xa2\x75\x51\x6d\x1a\x40\x23\x0b\xff\x6e\x32" \ "\xef\xb7\x99\x3f\x83\x55\xa7\xd0\x16\xed\xd0\x46\xed\xfd\xa2\x69" \ "\x9b\x25\x91\x9d\xb2\x75\x43\xd3\x36\xe5\xa5\x5c\x1a\xea\x5b\x9d" \ "\x9f\x73\x57\x62\x3b\x83\xa5\x87\xfb\xe0\x1a\x24\x24\xfd\xd0\x23" \ "\x84\xa6\x69\x12\x52\xf0\x94\x33\xc6\xe6\x33\x98\xb7\x48\x48\x00" \ "\x80\x84\xc4\x18\x63\x5b\xe3\x63\x5c\x19\x5a\x6b\xad\xb5\x8e\x48" \ "\x04\x00\x08\x21\x00\x88\x48\xf4\x2d\x25\x63\x4c\x7c\x8c\x2d\x6d" \ "\x05\x00\x09\x4b\x3e\x1a\x68\x4c\x7d\xda\x79\xaa\x6b\xb5\x62\xc0" \ "\x18\x2f\x69\xe7\x29\xf2\xe2\x55\xa8\x4e\xfd\xbe\x6c\xd5\x29\xec" \ "\x68\x21\x85\x9f\xb7\x93\x90\x82\x52\x1a\x1c\x02\x1b\x2b\xf6\x9f" \ "\x17\x52\x2c\x0d\x3e\x3d\x3f\x0d\x9e\x72\x97\xb7\x93\x4f\xcf\x7f" \ "\xf8\xcb\xb5\x3e\x01\x8d\xb5\x6a\x19\xa6\x37\x6f\xd9\x00\x00\x00" \ "\x00\x49\x45\x4e\x44\xae\x42\x60\x82" _down_arrow_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" \ "\x00\x00\x00\x10\x00\x00\x00\x10\x08\x02\x00\x00\x00\x90\x91\x68" \ "\x36\x00\x00\x00\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0" \ "\xbd\xa7\x93\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00" \ "\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45" \ "\x07\xd6\x06\x03\x03\x29\x2f\x78\x97\x13\x37\x00\x00\x00\x10\x74" \ "\x45\x58\x74\x43\x6f\x6d\x6d\x65\x6e\x74\x00\x4e\x61\x6e\x6f\x74" \ "\x75\x62\x65\xa3\x8c\x3b\xec\x00\x00\x00\xba\x49\x44\x41\x54\x28" \ "\xcf\xb5\x92\x3f\x0e\x82\x30\x14\x87\x8b\x31\xcc\x32\xd9\x72\x02" \ "\x39\x83\x0c\x3f\xb8\x82\xc2\x09\x41\x2f\x41\x0a\x43\x7b\x95\x52" \ "\x26\xbc\x41\x1d\x48\xb0\xb6\x40\x64\xf0\x6d\x2f\xfd\xbe\xf4\xfd" \ "\x0b\x54\xaf\xc8\x9e\x38\x90\x9d\x71\xb4\x13\x21\x85\x4f\xa4\xd7" \ "\x74\x59\x10\x52\x14\xb7\xc2\x17\xea\x67\x9d\x67\xb9\x2b\xc4\x2c" \ "\xfe\xa5\x1e\xd5\xab\x60\x6a\x5a\x48\x51\xde\xcb\xae\xeb\xd6\x50" \ "\x00\x13\xf9\x69\xda\x18\x03\x60\x8d\x6e\x78\xb3\x30\x25\x3d\x68" \ "\xdf\x01\x50\x3d\xaa\xd5\xb1\x3a\x0e\x00\x63\x4c\x18\x86\x5b\x7b" \ "\x98\x1d\x00\x7a\xd0\x5b\x7b\xb0\x1d\x7a\xa6\x3e\x4d\x08\x09\xe6" \ "\xd3\xe0\x2d\xb7\xe7\x3d\x07\x6f\x39\xa5\x34\x3a\x45\x8c\xb1\x2f" \ "\x61\x7a\xf3\x05\x9b\x76\x4b\x4a\x2e\xc9\xf8\x1a\x1d\xc1\xa6\xdd" \ "\x1f\xfe\x72\xad\x6f\xd8\xd4\x50\x37\x09\xb5\x93\x63\x00\x00\x00" \ "\x00\x49\x45\x4e\x44\xae\x42\x60\x82" class GroupButtonMixin: """ Mixin class for providing the method toggle_groupbox_in_dialogs, suitable as part of a slot method for toggling the state of a dialog GroupBox. (Current implementation uses open/close icons which look good on Linux and Windows but don't look good on the Mac.) [DEPRECATED. New code should avoid using this, and should instead use the groupboxes provided by PropMgrBaseClass if possible.] """ # Note: this is only used by a couple of non-generator dialogs, # so it (and the strings _up_arrow_data and _down_arrow_data which nothing else uses) # should be moved into some other file. [bruce 070615 comment] def initialize(): _up_arrow = QPixmap() _up_arrow.loadFromData(_up_arrow_data) _down_arrow = QPixmap() _down_arrow.loadFromData(_down_arrow_data) initialize = staticmethod(initialize) def toggle_groupbox_in_dialogs(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[0].isVisible(): button.setIcon(QIcon(self._down_arrow)) for thing in things: thing.hide() else: button.setIcon(QIcon(self._up_arrow)) for thing in things: thing.show() return pass # end of class GroupButtonMixin # end
NanoCAD-master
cad/src/PM/GroupButtonMixin.py
#Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ PM_PartLib.py The PM_PartLib class provides a groupbox that contains the partlib (any user specified directory). The parts from the partlib can be pasted into the 3D workspace. The selected item in this list is shown by its elementViewer (an instance of L{PM_PreviewGroupBox}). The object being previewed can then be deposited into the 3D workspace. @author: Huaicai, Mark, Ninad, Bruce @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: The Partlib existed as a tab in the MMKit of Build Atoms Mode. (MMKit has been deprecated since 2007-08-29.) ninad 2007-09-06: Created. """ import os from utilities import debug_flags from utilities.constants import diTrueCPK from graphics.widgets.ThumbView import MMKitView from model.assembly import Assembly from files.mmp.files_mmp import readmmp from PM.PM_GroupBox import PM_GroupBox from PM.PM_TreeView import PM_TreeView class PM_PartLib(PM_GroupBox): """ The PM_PartLib class provides a groupbox containing a partlib directory The selected part in this list is shown by its elementViewer (an instance of L{PM_PreviewGroupBox}) The part being previewed can then be deposited into the 3D workspace. """ def __init__(self, parentWidget, title = 'Part Library', win = None, elementViewer = None ): self.w = win self.elementViewer = elementViewer # piotr 080410 changed diTUBES to diTrueCPK self.elementViewer.setDisplay(diTrueCPK) self.partLib = None self.newModel = None PM_GroupBox.__init__(self, parentWidget, title) self._loadPartLibGroupBox() def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ ##if isConnect: ## change_connect = self.w.connect ##else: ## change_connect = self.w.disconnect #Following doesn't work for some reasons so this call is disabled. #Instead , see PM_TreeView.mouseReleaseEvent where self.partChanged is #called. ##change_connect(self.partLib, ## SIGNAL("selectionChanged(QItemSelection *,\ ## QItemSelection *)"), ## self.partChanged) pass def _loadPartLibGroupBox(self): """ """ self.partLib = PM_TreeView(self) self.gridLayout.addWidget(self.partLib) #Append to the widget list. This is important for expand -collapse #functions (of the groupbox) to work properly. self._widgetList.append(self.partLib) def _updateElementViewer(self, newModel = None): """ Update the view of L{self.elementViewer} @param newModel: The model correseponding to the item selected in L{self.clipboardListWidget}. @type newModel: L{molecule} or L{Group} """ if not self.elementViewer: return assert isinstance(self.elementViewer, MMKitView) self.elementViewer.resetView() if newModel: self.elementViewer.updateModel(newModel) def partChanged(self, selectedItem): """ Method called when user changed the partlib browser tree. @param selectedItem: Item currently selected in the L{self.partLib} @type selectedItem: L{self.partLib.FileItem} @attention: This is called in the L{PM_TreeView.mouseReleaseEvent}. The 'selectionChanged' signal for self.partLib apparently was not emitted so that code has been removed. """ #Copying some old code from deprecated MMKit.py -- ninad 2007-09-06 item = selectedItem self.newModel = None if isinstance(item, self.partLib.FileItem): mmpFile = str(item.getFileObj()) if os.path.isfile(mmpFile): self.newModel = \ Assembly(self.w, os.path.normpath(mmpFile), run_updaters = True # desirable for PartLib [bruce 080403] ) self.newModel.set_glpane(self.elementViewer) # sets its .o and .glpane readmmp(self.newModel, mmpFile) self.newModel.update_parts() #k not sure if needed after readmmp self.newModel.checkparts() if self.newModel.shelf.members: 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 self._updateElementViewer(self.newModel)
NanoCAD-master
cad/src/PM/PM_PartLib.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_Colors.py -- Property Manager color theme functions and constants.. @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Created initially for PM_Dialog as part of the code cleanup and review for new coding standards. Renamed all constants to names with uppercase letters. """ import os import sys from PyQt4.Qt import QColor from PyQt4.Qt import QPalette from utilities.debug_prefs import debug_pref, Choice _iconPrefix = os.path.dirname(os.path.abspath(sys.argv[0])) _iconPrefix = os.sep.join(_iconPrefix.split(os.sep)[:-1] + ["src"]) # Directory containing icons/images for the property manager. PM_ICON_DIR = "ui/actions/Properties Manager/" def getIconPath(iconName, _iconPrefix = _iconPrefix): """ Returns the relative path to the PM icon/image file <iconName>. @param iconName: basename of the icon's PNG file @type iconName: str @param _iconPrefix: The directory path to be prepended to the icon file path @param _iconPrefix: str """ iconPath = os.path.join ( _iconPrefix, PM_ICON_DIR) iconPath = os.path.join( iconPath, iconName) iconPath = os.path.abspath(iconPath) if not os.path.exists(iconPath): iconPath = '' forwardSlash = "/" #The iconPath is used in L{PM_GroupBox._getTitleButtonStyleSheet} #the style sheet border-image attribute needs a url with only #forward slashes in the string. This creates problem on windows #because os.path.abspath returns the path with all backword slashes #in the path name(os default). the following replaces all backward #slashes with the forward slashes. Also fixes bug 2509 -- ninad 2007-08-21 if sys.platform == 'win32': iconPath = iconPath.replace(os.sep , str(forwardSlash)) return str(iconPath) def getPalette( palette, colorRole, color ): """ Assigns a color (based on color role) to palette and returns it. The color/color role is assigned to all color groups. @param palette: A palette. If palette is None, we create and return a new palette. @type palette: QPalette @param colorRole: the Qt ColorRole @type colorRole: Qt.ColorRole @param color: color @type color: QColor @return: Returns the updated palette, or a new palette if none was supplied. @rtype : QPalette @see QPalette.setColor() """ if palette: pass # Make sure palette is QPalette. else: palette = QPalette() palette.setColor(colorRole, color) return palette COLOR_THEME = "Gray" _colortheme_Choice = Choice(["Gray", "Blue"], defaultValue = COLOR_THEME) COLOR_THEME_prefs_key = "A9/Color Theme" def set_Color_Theme_from_pref(): global COLOR_THEME COLOR_THEME = debug_pref("Color Theme (next session)", _colortheme_Choice, non_debug = True, prefs_key = COLOR_THEME_prefs_key) return set_Color_Theme_from_pref() # Standard colors for all themes. pmColor = QColor(230, 231, 230) # Should get this from the main window (parent). pmGrpBoxColor = QColor(201, 203, 223) # Yellow msg box (QTextEdit widget). pmMessageTextEditColor = QColor(255, 255, 100) # Should get the following from the main window (parent). PM_COLOR = QColor(230, 231, 230) PM_GROUPBOX_COLOR = QColor(201, 203, 223) # Yellow msg box (QTextEdit widget). PM_MESSAGE_TEXT_EDIT_COLOR = QColor(255, 255, 100) # pmMessageTextEditColor to be deprecated. pmMessageBoxColor = pmMessageTextEditColor pmReferencesListWidgetColor = QColor(254, 128, 129) # Special Sequence Editor colors. sequenceEditorNormalColor = QColor(255, 255, 255) # White sequenceEditorChangedColor = QColor(255, 220, 200) # Pink sequenceEditStrandMateBaseColor = QColor(255, 255, 200) # Light yellow if COLOR_THEME == "Gray": # Dark Gray Color Theme # Colors for Property Manager widgets. pmTitleFrameColor = QColor(120, 120, 120) # pmTitleFrameColor to be deprecated. Mark 2007-07-24 pmHeaderFrameColor = pmTitleFrameColor pmTitleLabelColor = QColor(255, 255, 255) # pmTitleLabelColor to be deprecated. Mark 2007-07-24 pmHeaderTitleColor = pmTitleLabelColor pmCheckBoxTextColor = QColor(0, 0, 255) # used in MMKit pmCheckBoxButtonColor = QColor(172, 173, 190) # Property Manager group box colors. pmGrpBoxBorderColor = QColor(68, 79, 81) pmGrpBoxButtonBorderColor = QColor(147, 144, 137) pmGrpBoxButtonTextColor = QColor(40, 40, 33) # Same as pmCheckBoxTextColor pmGrpBoxButtonColor = QColor(170, 170, 170) # Locations of expanded and collapsed title button images. pmGrpBoxExpandedIconPath = getIconPath("GroupBox_Opened_Gray.png") pmGrpBoxCollapsedIconPath = getIconPath("GroupBox_Closed_Gray.png") else: # Blue Color Theme # Colors for Property Manager widgets. pmTitleFrameColor = QColor(50, 90, 230) # I like (50,90, 230). mark # pmTitleFrameColor to be deprecated. Mark 2007-07-24 pmHeaderFrameColor = pmTitleFrameColor pmTitleLabelColor = QColor(255, 255, 255) # pmTitleLabelColor to be deprecated. Mark 2007-07-24 pmHeaderTitleColor = pmTitleLabelColor pmCheckBoxTextColor = QColor(0, 0, 255) pmCheckBoxButtonColor = QColor(172, 173, 190) pmMessageTextEditColor = QColor(255, 255, 100) # Property Manager group box colors. pmGrpBoxBorderColor = QColor(0, 0, 255) # blue pmGrpBoxButtonBorderColor = QColor(127, 127, 127) pmGrpBoxButtonTextColor = QColor(0, 0, 255) pmGrpBoxButtonColor = QColor(144, 144, 200) # Locations of groupbox opened and closed images. pmGrpBoxExpandedIconPath = getIconPath("GroupBox_Opened_Blue.png") pmGrpBoxCollapsedIconPath = getIconPath("GroupBox_Closed_Blue.png")
NanoCAD-master
cad/src/PM/PM_Colors.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ PM_PAM3_AtomChooser.py @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. All rights reserved. """ from PM.PM_MolecularModelingKit import PM_MolecularModelingKit from utilities.constants import diBALL from utilities.GlobalPreferences import pref_MMKit_include_experimental_PAM_atoms # Elements button list to create PAM3 atoms toolbutton group. # Format: # - button type # - buttonId (element number), # - buttonText (element symbol), # - iconPath # - tooltip (element name) # - shortcut # - column # - row PAM3_ATOMS_BUTTON_LIST = [ #bruce 080412 revised this ( "QToolButton", 300, "Ax3", "", "PAM3-Axis", None, 0, 0 ), ( "QToolButton", 301, "Ss3", "", "PAM3-Sugar", None, 1, 0 ), ## ( "QToolButton", 303, "Sj3", "", "PAM3-Sugar-Junction", None, 1, 1 ), ## ( "QToolButton", 304, "Ae3", "", "PAM3-Axis-End", None, 1, 0 ), ## ( "QToolButton", 306, "Sh3", "", "PAM3-Sugar-Hydroxyl", None, 2, 1 ), ## ( "QToolButton", 307, "Hp3", "", "PAM3-Hairpin", None, 0, 2 ) #NOTE: Following atoms are not used for now #( "QToolButton", 302, "Pl3", "", "PAM3-Phosphate", None, 0, 2 ), #( "QToolButton", 305, "Se3", "", "PAM3-Sugar-End", None, 1, 2 ), ] PAM3_ATOMS_BUTTON_LIST_EXPERIMENTAL = [ #bruce 080412 added this ( "QToolButton", 310, "Ub3", "", "PAM3-Unpaired-base", None, 0, 1 ), ( "QToolButton", 311, "Ux3", "", "PAM3-Unpaired-base-x", None, 1, 1 ), ( "QToolButton", 312, "Uy3", "", "PAM3-Unpaired-base-y", None, 2, 1 ), ] if pref_MMKit_include_experimental_PAM_atoms(): PAM3_ATOMS_BUTTON_LIST += PAM3_ATOMS_BUTTON_LIST_EXPERIMENTAL class PM_PAM3_AtomChooser( PM_MolecularModelingKit ): """ The PM_PAM3_AtomChooser widget provides a PAM3 Atom Chooser, PAM3 stands for "Three Pseudo Atom Model " contained in its own group box, for a Property Manager dialog (or as a sub groupbox for Atom Chooser GroupBox.) A PM_PAM3_AtomChooser is a selection widget that displays all PAM3 atoms supported in NE1. @see: B{elements.py} @see: B{L{PM_MolecularModelingKit}} """ viewerDisplay = diBALL def __init__(self, parentWidget, parentPropMgr = None, title = "", element = "Ss3", elementViewer = None ): """ Appends a PM_PAM3_AtomChooser widget to the bottom of I{parentWidget}, a Property Manager dialog. (or as a sub groupbox for Atom Chooser GroupBox.) @param parentWidget: The parent PM_Dialog or PM_groupBox containing this widget. @type parentWidget: PM_Dialog or PM_GroupBox @param parentPropMgr: The parent Property Manager @type parentPropMgr: PM_Dialog or None @param title: The button title on the group box containing the Atom Chooser. @type title: str @param element: The initially selected PAM3 atom. It can be either an (PAM3) atom symbol or name. @type element: str """ PM_MolecularModelingKit.__init__( self, parentWidget, parentPropMgr, title, element, elementViewer) self._elementsButtonGroup.setButtonSize(width = 38, height = 38) def _addGroupBoxes(self): """ various groupboxes present inside the PAM3 Atom chooser groupbox. """ self._addElementsGroupBox(self) def getElementsButtonList(self): """ Return the list of buttons in the PAM3 Atom chooser. @return: List containing information about the PAM3 atom toolbuttons @rtype: list """ return PAM3_ATOMS_BUTTON_LIST
NanoCAD-master
cad/src/PM/PM_PAM3_AtomChooser.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_CoordinateSpinBoxes.py The PM_CoordinateSpinBoxes class provides a groupbox containing the three coordinate spinboxes. @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. @TODO: Need to implement connectWidgetWithState when that API is formalized. """ from PyQt4.Qt import QLabel from PM.PM_GroupBox import PM_GroupBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox class PM_CoordinateSpinBoxes(PM_GroupBox): """ The PM_CoordinateSpinBoxes class provides a groupbox containing the three coordinate spinboxes. @see: L{Ui_BuildAtomsPropertyManager._loadSelectedAtomPosGroupBox} for an example. """ def __init__(self, parentWidget, title = "", label = '', labelColumn = 0, spanWidth = True ): """ Appends a PM_CoordinateSpinBoxes groupbox widget to I{parentWidget}, a L{PM_Groupbox} or a L{PM_Dialog} @param parentWidget: The parent groupbox or dialog (Property manager) containing this widget. @type parentWidget: L{PM_GroupBox} or L{PM_Dialog} @param title: The title (button) text. @type title: str @param label: The label for the coordinate spinbox. @type label: str @param labelColumn: The column in the parentWidget's grid layout to which this widget's label will be added. The labelColum can only be E{0} or E{1} @type labelColumn: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) """ # Intializing label, labelColumn etc is needed before doing # PM_GroupBox.__init__. This is done so that # self.parentWidget.addPmWidget(self) done at the end of __init__ # works properly. # 'self.parentWidget.addPmWidget(self)' is done to avoid a bug where a # groupbox is always appended as the 'last widget' when its # parentWidget is also a groupbox. This is due to other PM widgets #(e.g. PM_PushButton)add themselves to their parent widget in their #__init__ using self.parentWidget.addPmWidget(self). So doing the #same thing here. More general fix is needed in PM_GroupBox code # --Ninad 2007-11-14 self.label = label self.labelColumn = labelColumn self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) PM_GroupBox.__init__(self, parentWidget, title) #Initialize attributes self.xSpinBox = None self.ySpinBox = None self.zSpinBox = None self._loadCoordinateSpinBoxes() self.parentWidget.addPmWidget(self) def _loadCoordinateSpinBoxes(self): """ Load the coordinateSpinboxes groupbox with the x, y, z spinboxes """ # User input to specify x-coordinate self.xSpinBox = \ PM_DoubleSpinBox( self, label = \ "ui/actions/Properties Manager/X_Coordinate.png", value = 0.0, setAsDefault = True, minimum = - 9999999, maximum = 9999999, singleStep = 1, decimals = 3, suffix = " A") # User input to specify y-coordinate self.ySpinBox = \ PM_DoubleSpinBox( self, label = \ "ui/actions/Properties Manager/Y_Coordinate.png", value = 0.0, setAsDefault = True, minimum = - 9999999, maximum = 9999999, singleStep = 1, decimals = 3, suffix = " A") # User input to specify z-coordinate self.zSpinBox = \ PM_DoubleSpinBox( self, label = \ "ui/actions/Properties Manager/Z_Coordinate.png", value = 0.0, setAsDefault = True, minimum = - 9999999, maximum = 9999999, singleStep = 1, decimals = 3, suffix = " A") def _zgetStyleSheet(self): """ Return the style sheet for the groupbox. This sets the following properties only: - border style - border width - border color - border radius (on corners) For PM_CoordinateSpinBoxes groupbox, we typically don't want the border around the groupbox. If client needs a border, it should be explicitly defined and set there. @see: L{PM_GroupBox._getStyleSheet} (overrided here) """ styleSheet = "QGroupBox {border-style:hidden;\ border-width: 0px;\ border-color: "";\ border-radius: 0px;\ min-width: 10em; }" return styleSheet
NanoCAD-master
cad/src/PM/PM_CoordinateSpinBoxes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_ToolButton.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrToolButton out of PropMgrBaseClass.py into this file and renamed it PM_ToolButton. """ import os from PyQt4.Qt import QLabel from PyQt4.Qt import QToolButton from PyQt4.Qt import QWidget from PyQt4.Qt import QSize from utilities.icon_utilities import geticon class PM_ToolButton( QToolButton ): """ The PM_ToolButton widget provides a QToolButton with a QLabel for a Property Manager group box. @cvar defaultText: The default text of the tool button. @type defaultText: str @cvar setAsDefault: Determines whether to reset the value of the tool button to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this tool button. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultText = "" setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, text = '', iconPath = '', setAsDefault = True, spanWidth = False ): """ Appends a QToolButton (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the checkbox. If spanWidth is True, the label will be displayed on its own row directly above the list widget. To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param text: The button's text. @type text: str @param iconPath: The relative path to the button's icon. @type iconPath: str @param setAsDefault: If True, will restore <text> as the button's text when the "Restore Defaults" button is clicked. @type setAsDefault: bool @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool @see: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ if 0: # Debugging code print "PM_ToolButton.__init__():" print " label = ", label print " labelColumn = ", labelColumn print " text = ", text print " iconPath = ", iconPath print " setAsDefault = ", setAsDefault print " spanWidth = ", spanWidth QToolButton.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Set text self.setText(text) # Set icon self.setIcon(geticon(iconPath)) self.setIconSize(QSize(22, 22)) # Set default text self.defaultText = text self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setText(self.defaultText) def hide(self): """ Hides the tool button and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the tool button and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_ToolButton ############################
NanoCAD-master
cad/src/PM/PM_ToolButton.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ PM_PAM5_AtomChooser.py @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. All rights reserved. """ from PM.PM_MolecularModelingKit import PM_MolecularModelingKit from utilities.constants import diBALL from utilities.GlobalPreferences import pref_MMKit_include_experimental_PAM_atoms # Elements button list to create PAM5 atoms toolbutton group. # Format: # - button type # - buttonId (element number), # - buttonText (element symbol), # - iconPath # - tooltip (element name) # - shortcut # - column # - row PAM5_ATOMS_BUTTON_LIST = [ #bruce 080412 revised this ## ( "QToolButton", 200, "Ax5", "", "PAM5-Axis", None, 0, 0 ), ( "QToolButton", 208, "Gv5", "", "PAM5-Major-Groove", None, 0, 0 ), ( "QToolButton", 201, "Ss5", "", "PAM5-Sugar", None, 1, 0 ), ( "QToolButton", 202, "Pl5", "", "PAM5-Phosphate", None, 2, 0 ), ## ( "QToolButton", 203, "Sj5", "", "PAM5-Sugar-Junction", None, 1, 1 ), ## ( "QToolButton", 204, "Ae5", "", "PAM5-Axis-End", None, 1, 0 ), ## ( "QToolButton", 205, "Pe5", "", "PAM5-Phosphate-End", None, 1, 2 ), ## ( "QToolButton", 206, "Sh5", "", "PAM5-Sugar-Hydroxyl", None, 2, 1 ), ## ( "QToolButton", 207, "Hp5", "", "PAM5-Hairpin", None, 2, 2 ) ] PAM5_ATOMS_BUTTON_LIST_EXPERIMENTAL = [ #bruce 080412 added this ( "QToolButton", 210, "Ub5", "", "PAM5-Unpaired-base", None, 0, 1 ), ( "QToolButton", 211, "Ux5", "", "PAM5-Unpaired-base-x", None, 1, 1 ), ( "QToolButton", 212, "Uy5", "", "PAM5-Unpaired-base-y", None, 2, 1 ), ] if pref_MMKit_include_experimental_PAM_atoms(): PAM5_ATOMS_BUTTON_LIST += PAM5_ATOMS_BUTTON_LIST_EXPERIMENTAL class PM_PAM5_AtomChooser( PM_MolecularModelingKit ): """ The PM_PAM5_AtomChooser widget provides a PAM5 Atom Chooser, PAM5 stands for "Five Pseudo Atom Model " contained in its own group box, for a Property Manager dialog (or as a sub groupbox for Atom Chooser GroupBox.) A PM_PAM5_AtomChooser is a selection widget that displays all PAM5 atoms supported in NE1 @see: B{elements.py} @see: B{L{PM_MolecularModelingKit}} @see: U{B{PAM5}<http://www.nanoengineer-1.net/mediawiki/index.php?title=PAM5>} """ viewerDisplay = diBALL def __init__(self, parentWidget, parentPropMgr = None, title = "", element = "Ss5", elementViewer = None ): """ Appends a PM_PAM5_AtomChooser widget to the bottom of I{parentWidget}, a Property Manager dialog. (or as a sub groupbox for Atom Chooser GroupBox.) @param parentWidget: The parent PM_Dialog or PM_groupBox containing this widget. @type parentWidget: PM_Dialog or PM_GroupBox @param parentPropMgr: The parent Property Manager @type parentPropMgr: PM_Dialog or None @param title: The button title on the group box containing the Atom Chooser. @type title: str @param element: The initially selected PAM5 atom. It can be either an PAM5 atom symbol or name. @type element: str """ PM_MolecularModelingKit.__init__( self, parentWidget, parentPropMgr, title, element, elementViewer) self._elementsButtonGroup.setButtonSize(width = 38, height = 38) def _addGroupBoxes(self): """ various groupboxes present inside the PAM5 Atom chooser groupbox. """ self._addElementsGroupBox(self) def getElementsButtonList(self): """ Return the list of buttons in the PAM5 Atom chooser. @return: List containing information about the PAM5 atom toolbuttons @rtype: list """ return PAM5_ATOMS_BUTTON_LIST
NanoCAD-master
cad/src/PM/PM_PAM5_AtomChooser.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_LabelRow.py @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-14: Created. """ from PM.PM_LabelGrid import PM_LabelGrid class PM_LabelRow( PM_LabelGrid ): """ The PM_LabelRow widget (a groupbox) provides a grid of labels arranged on the same row of the grid layout of the PM_LabelRow @see: B{Ui_MovePropertyManager} for an example of how this is used. """ def __init__(self, parentWidget, title = '', labelList = [], alignment = None, isBold = False ): """ Appends a PM_LabelRow widget ( a groupbox) to the bottom of I{parentWidget}, the Property Manager Group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param title: The group box title. @type title: str @param labelList: A list of I{label info lists}. There is one label info list for each label in the grid. The label info list contains the following items: 1. Widget Type - in this case its 'Label'(str), 2. Label text (str), 3. Column (int), @type labelList: list """ PM_LabelGrid.__init__(self, parentWidget , title, labelList, alignment, isBold) def getWidgetInfoList(self, labelInfo): """ Returns the label information provided by the user. Overrides PM_LabelGrid.getLabelInfoList if they need to provide custom information (e.g. a fixed value for row) . @param labelInfo: list containing the label information @type labelInfo: list @return : A list containing the label information. This can be same as I{labelInfo} or can be modified further. @rtype : list @see: L{PM_WidgetGrid.getWidgetInfoList (this method is overridden here) """ widgetType = labelInfo[0] labelText = labelInfo[1] column = labelInfo[2] row = 0 labelInfoList = [widgetType, labelText, column, row] return labelInfoList def _getStyleSheet(self): """ Return the style sheet for the groupbox. This sets the following properties only: - border style - border width - border color - border radius (on corners) @see: L{PM_GroupBox._getStyleSheet} (overrided here) """ styleSheet = "QGroupBox {border-style:hidden;\ border-width: 0px;\ border-color: "";\ border-radius: 0px;\ min-width: 10em; }" return styleSheet
NanoCAD-master
cad/src/PM/PM_LabelRow.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_ColorComboBox.py @author: Mark @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. To do: - Override addItem() and insertItem() methods. """ from PM.PM_ComboBox import PM_ComboBox from PyQt4.Qt import QPixmap, QIcon, QColor, QSize from PyQt4.Qt import SIGNAL from PyQt4.Qt import QColorDialog from utilities.constants import white, gray, black from utilities.constants import red, orange, yellow from utilities.constants import green, cyan, blue from utilities.constants import magenta, violet, purple from utilities.constants import darkred, darkorange, mustard from utilities.constants import darkgreen, darkblue, darkpurple from utilities.constants import lightgray from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf class PM_ColorComboBox( PM_ComboBox ): """ The PM_ColorComboBox widget provides a combobox for selecting colors in a Property Manager group box. IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_ColorComboBox1.jpg) The parent must make the following signal-slot connection to be notified when the user has selected a new color: self.connect(pmColorComboBox, SIGNAL("editingFinished()"), self.mySlotMethod) @note: Subclasses L{PM_ComboBox}. """ customColorCount = 0 color = None otherColor = lightgray otherColorList = [] # List of custom (other) colors the user has selected. colorList = [white, gray, black, red, orange, yellow, green, cyan, blue, magenta, violet, purple, darkred, darkorange, mustard, darkgreen, darkblue, darkpurple, otherColor] colorNames = ["White", "Gray", "Black", "Red", "Orange", "Yellow", "Green", "Cyan", "Blue", "Magenta", "Violet", "Purple", "Dark red", "Dark orange", "Mustard", "Dark green", "Dark blue", "Dark purple", "Other color..."] def __init__(self, parentWidget, label = 'Color:', labelColumn = 0, colorList = [], colorNames = [], color = white, setAsDefault = True, spanWidth = False, ): """ Appends a color chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the color frame (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param colorList: List of colors. @type colorList: List where each item contains 3 floats (r, g, b) @param colorNames: List of color names. @type colorNames: List of strings @param color: The initial color. White is the default. If I{color} is not in I{colorList}, then the initial color will be set to the last color item (i.e. "Other color..."). @type color: tuple of 3 floats (r, g, b) @param setAsDefault: if True, will restore L{color} when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean """ if len(colorNames) and len(colorList): assert len(colorNames) == len(colorList) self.colorNames = colorNames self.colorList = colorList self.colorDict = dict(zip(self.colorNames, self.colorList)) PM_ComboBox.__init__(self, parentWidget, label = label, labelColumn = labelColumn, choices = self.colorNames, index = 0, # Gets (re)set by setColor() setAsDefault = setAsDefault, spanWidth = spanWidth ) # Load QComboBox widget choices and set initial choice (index). idx = 0 for colorName in self.colorNames: pixmap = QPixmap(12, 12) qcolor = RGBf_to_QColor(self.colorDict[str(colorName)]) pixmap.fill(qcolor) self.setItemIcon(idx, QIcon(pixmap)) idx += 1 self.setIconSize(QSize(12, 12)) # Default is 16x16. self.setColor(color) # Sets current index. self.connect(self, SIGNAL("activated(QString)"), self._setColorFromName) return def _setColorFromName(self, colorName): """ Set the color using the color index. @param colorName: The color name string. @type colorName: str """ if colorName == "Other color...": self.openColorChooserDialog() # Sets self.color else: self.setColor(self.colorDict[str(colorName)]) return def setColor(self, color, default = False): """ Set the color. @param color: The color. @type color: tuple of 3 floats (r, g, b) @param default: If True, make I{color} the default color. Default is False. @type default: boolean """ if color == self.color: return if default: self.defaultColor = color self.setAsDefault = default self.color = color try: # Try to set the current item to a color in the combobox. self.setCurrentIndex(self.colorList.index(color)) except: # color was not in the combobox, so set current index to the last # item which is "Other color...". Also update the color icon to. otherColorIndex = len(self.colorList) - 1 self.otherColor = color self.colorList[otherColorIndex] = color pixmap = QPixmap(16, 16) qcolor = RGBf_to_QColor(color) pixmap.fill(qcolor) self.setItemIcon(otherColorIndex, QIcon(pixmap)) self.setCurrentIndex(self.colorList.index(self.otherColor)) # Finally, emit a signal so the parent knows the color has changed. self.emit(SIGNAL("editingFinished()")) return def getColor(self): """ Return the current color. @return: The current r, g, b color. @rtype: Tuple of 3 floats (r, g, b) """ return self.color def getQColor(self): """ Return the current QColor. @return: The current color. @rtype: QColor """ return RGBf_to_QColor(self.color) def openColorChooserDialog(self): """ Prompts the user to choose a color and then updates colorFrame with the selected color. Also sets self's I{color} attr to the selected color. """ qcolor = RGBf_to_QColor(self.color) if not self.color in self.colorList[0:-1]: if not self.color in self.otherColorList: QColorDialog.setCustomColor(self.customColorCount, qcolor.rgb()) self.otherColorList.append(self.color) self.customColorCount += 1 c = QColorDialog.getColor(qcolor, self) if c.isValid(): self.setColor(QColor_to_RGBf(c)) self.emit(SIGNAL("editingFinished()"))
NanoCAD-master
cad/src/PM/PM_ColorComboBox.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_GroupBox.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrGroupBox out of PropMgrBaseClass.py into this file and renamed it PM_GroupBox. """ import sys from utilities import debug_flags from PM.PM_Colors import pmGrpBoxButtonBorderColor from PM.PM_Colors import pmGrpBoxButtonTextColor from PM.PM_Colors import pmGrpBoxExpandedIconPath from PM.PM_Colors import pmGrpBoxCollapsedIconPath from PM.PM_Colors import pmGrpBoxColor from PM.PM_Colors import pmGrpBoxBorderColor from PM.PM_Colors import pmGrpBoxButtonColor from PM.PM_Constants import PM_GROUPBOX_SPACING from PM.PM_Constants import PM_GROUPBOX_VBOXLAYOUT_MARGIN from PM.PM_Constants import PM_GROUPBOX_VBOXLAYOUT_SPACING from PM.PM_Constants import PM_GROUPBOX_GRIDLAYOUT_MARGIN from PM.PM_Constants import PM_GROUPBOX_GRIDLAYOUT_SPACING from PM.PM_Constants import PM_GRIDLAYOUT_MARGIN from PM.PM_Constants import PM_GRIDLAYOUT_SPACING from PM.PM_Constants import PM_LABEL_LEFT_ALIGNMENT, PM_LABEL_RIGHT_ALIGNMENT from PyQt4.Qt import QGroupBox from PyQt4.Qt import QGridLayout from PyQt4.Qt import QLabel from PyQt4.Qt import QPushButton from PyQt4.Qt import QPalette from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QSpacerItem from PyQt4.Qt import QVBoxLayout from PyQt4.Qt import QWidget from PyQt4.Qt import SIGNAL from widgets.widget_helpers import QColor_to_Hex from utilities.icon_utilities import geticon, getpixmap from utilities.GlobalPreferences import debug_pref_support_Qt_4point2 #This import is only used in isinstance check-- from PM.PM_CheckBox import PM_CheckBox # == _SUPPORT_QT_4point2 = debug_pref_support_Qt_4point2() #bruce 080725 # == class PM_GroupBox( QGroupBox ): """ The PM_GroupBox widget provides a group box container with a collapse/expand button and a title button. PM group boxes can be nested by supplying an existing PM_GroupBox as the parentWidget of a new PM_GroupBox (as an argument to its constructor). If the parentWidget is a PM_GroupBox, no title button will be created for the new group box. @cvar setAsDefault: Determines whether to reset the value of all widgets in the group box when the user clicks the "Restore Defaults" button. If set to False, no widgets will be reset regardless thier own I{setAsDefault} value. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this group box. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar expanded: Expanded flag. @type expanded: bool @cvar _title: The group box title. @type _title: str @cvar _widgetList: List of widgets in the group box (except the title button). @type _widgetList: list @cvar _rowCount: Number of rows in the group box. @type _rowCount: int @cvar _groupBoxCount: Number of group boxes in this group box. @type _groupBoxCount: int @cvar _lastGroupBox: The last group box in this group box (i.e. the most recent PM group box added). @type _lastGroupBox: PM_GroupBox """ setAsDefault = True labelWidget = None expanded = True _title = "" _widgetList = [] _rowCount = 0 _groupBoxCount = 0 _lastGroupBox = None titleButtonRequested = True def __init__(self, parentWidget, title = '', connectTitleButton = True, setAsDefault = True ): """ Appends a PM_GroupBox widget to I{parentWidget}, a L{PM_Dialog} or a L{PM_GroupBox}. If I{parentWidget} is a L{PM_Dialog}, the group box will have a title button at the top for collapsing and expanding the group box. If I{parentWidget} is a PM_GroupBox, the title will simply be a text label at the top of the group box. @param parentWidget: The parent dialog or group box containing this widget. @type parentWidget: L{PM_Dialog} or L{PM_GroupBox} @param title: The title (button) text. If empty, no title is added. @type title: str @param connectTitleButton: If True, this class will automatically connect the title button of the groupbox to send signal to expand or collapse the groupbox. Otherwise, the caller has to connect this signal by itself. See: B{Ui_MovePropertyManager.addGroupBoxes} and B{MovePropertyManager.connect_or_disconnect_signals} for examples where the client connects this slot. @type connectTitleButton: bool @param setAsDefault: If False, no widgets in this group box will have thier default values restored when the B{Restore Defaults} button is clicked, regardless thier own I{setAsDefault} value. @type setAsDefault: bool @see: U{B{QGroupBox}<http://doc.trolltech.com/4/qgroupbox.html>} """ QGroupBox.__init__(self) self.parentWidget = parentWidget # 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. # Add self to PropMgr's vBoxLayout if parentWidget: parentWidget._groupBoxCount += 1 parentWidget.vBoxLayout.addWidget(self) parentWidget._widgetList.append(self) _groupBoxCount = 0 self._widgetList = [] self._title = title self.setAsDefault = setAsDefault self.setAutoFillBackground(True) self.setStyleSheet(self._getStyleSheet()) # Create vertical box layout which will contain two widgets: # - the group box title button (or title) on row 0. # - the container widget for all PM widgets on row 1. self._vBoxLayout = QVBoxLayout(self) self._vBoxLayout.setMargin(0) self._vBoxLayout.setSpacing(0) # _containerWidget contains all PM widgets in this group box. # Its sole purpose is to easily support the collapsing and # expanding of a group box by calling this widget's hide() # and show() methods. self._containerWidget = QWidget() self._vBoxLayout.insertWidget(0, self._containerWidget) # Create vertical box layout self.vBoxLayout = QVBoxLayout(self._containerWidget) self.vBoxLayout.setMargin(PM_GROUPBOX_VBOXLAYOUT_MARGIN) self.vBoxLayout.setSpacing(PM_GROUPBOX_VBOXLAYOUT_SPACING) # Create grid layout self.gridLayout = QGridLayout() self.gridLayout.setMargin(PM_GRIDLAYOUT_MARGIN) self.gridLayout.setSpacing(PM_GRIDLAYOUT_SPACING) # Insert grid layout in its own vBoxLayout self.vBoxLayout.addLayout(self.gridLayout) # Add title button (or just a title if the parent is not a PM_Dialog). if not parentWidget or isinstance(parentWidget, PM_GroupBox): self.setTitle(title) else: # Parent is a PM_Dialog, so add a title button. if not self.titleButtonRequested: self.setTitle(title) else: self.titleButton = self._getTitleButton(self, title) self._vBoxLayout.insertWidget(0, self.titleButton) if connectTitleButton: self.connect( self.titleButton, SIGNAL("clicked()"), self.toggleExpandCollapse) self._insertMacSpacer() # Fixes the height of the group box. Very important. Mark 2007-05-29 self.setSizePolicy( QSizePolicy(QSizePolicy.Policy(QSizePolicy.Preferred), QSizePolicy.Policy(QSizePolicy.Fixed))) self._addBottomSpacer() return def _insertMacSpacer(self, spacerHeight = 6): """ This addresses a Qt 4.3.5 layout bug on Mac OS X in which the title button will overlap with and cover the first widget in the group box. This workaround inserts a I{spacerHeight} tall spacer between the group box's title button and container widget. """ if sys.platform != "darwin": return self._macVerticalSpacer = QSpacerItem(10, spacerHeight, QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self._vBoxLayout.insertItem(1, self._macVerticalSpacer) return def _addBottomSpacer(self): """ Add a vertical spacer below this group box. Method: Assume this is going to be the last group box in the PM, so set its spacer's vertical sizePolicy to MinimumExpanding. We then set the vertical sizePolicy of the last group box's spacer to Fixed and set its height to PM_GROUPBOX_SPACING. """ # Spacers are only added to groupboxes in the PropMgr, not # nested groupboxes. ## from PM.PM_Dialog import PM_Dialog ## if not isinstance(self.parentWidget, PM_Dialog): if not self.parentWidget or isinstance(self.parentWidget, PM_GroupBox): #bruce 071103 revised test to remove import cycle; I assume that # self.parentWidget is either a PM_GroupBox or a PM_Dialog, since # comments about similar code in __init__ imply that. # # A cleaner fix would involve asking self.parentWidget whether to # do this, with instances of PM_GroupBox and PM_Dialog giving # different answers, and making them both inherit an API class # which documents the method or attr with which we ask them that # question; the API class would be inherited by any object to # which PM_GroupBox's such as self can be added. # # Or, an even cleaner fix would just call a method in # self.parentWidget to do what this code does now (implemented # differently in PM_GroupBox and PM_Dialog). self.verticalSpacer = None return if self.parentWidget._lastGroupBox: # _lastGroupBox is no longer the last one. <self> will be the # _lastGroupBox, so we must change the verticalSpacer height # and sizePolicy of _lastGroupBox to be a fixed # spacer between it and <self>. defaultHeight = PM_GROUPBOX_SPACING self.parentWidget._lastGroupBox.verticalSpacer.changeSize( 10, defaultHeight, QSizePolicy.Fixed, QSizePolicy.Fixed) self.parentWidget._lastGroupBox.verticalSpacer.defaultHeight = \ defaultHeight # Add a 1 pixel high, MinimumExpanding VSpacer below this group box. # This keeps all group boxes in the PM layout squeezed together as # group boxes are expanded, collapsed, hidden and shown again. defaultHeight = 1 self.verticalSpacer = QSpacerItem(10, defaultHeight, QSizePolicy.Fixed, QSizePolicy.MinimumExpanding) self.verticalSpacer.defaultHeight = defaultHeight self.parentWidget.vBoxLayout.addItem(self.verticalSpacer) # This groupbox is now the last one in the PropMgr. self.parentWidget._lastGroupBox = self return def restoreDefault (self): """ Restores the default values for all widgets in this group box. """ for widget in self._widgetList: if debug_flags.atom_debug: print "PM_GroupBox.restoreDefault(): widget =", \ widget.objectName() widget.restoreDefault() return def getTitle(self): """ Returns the group box title. @return: The group box title. @rtype: str """ return self._title def setTitle(self, title): """ Sets the groupbox title to <title>. @param title: The group box title. @type title: str @attention: This overrides QGroupBox's setTitle() method. """ if not title: return # Create QLabel widget. if not self.labelWidget: self.labelWidget = QLabel() self.vBoxLayout.insertWidget(0, self.labelWidget) labelAlignment = PM_LABEL_LEFT_ALIGNMENT self.labelWidget.setAlignment(labelAlignment) self._title = title self.labelWidget.setText(title) return def getPmWidgetPlacementParameters(self, pmWidget): """ Returns all the layout parameters needed to place a PM_Widget in the group box grid layout. @param pmWidget: The PM widget. @type pmWidget: PM_Widget """ row = self._rowCount #PM_CheckBox doesn't have a label. So do the following to decide the #placement of the checkbox. (can be placed either in column 0 or 1 , #This also needs to be implemented for PM_RadioButton, but at present #the following code doesn't support PM_RadioButton. if isinstance(pmWidget, PM_CheckBox): spanWidth = pmWidget.spanWidth if not spanWidth: # Set the widget's row and column parameters. widgetRow = row widgetColumn = pmWidget.widgetColumn widgetSpanCols = 1 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 #set a virtual label labelRow = row labelSpanCols = 1 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT if widgetColumn == 0: labelColumn = 1 elif widgetColumn == 1: labelColumn = 0 else: # Set the widget's row and column parameters. widgetRow = row widgetColumn = pmWidget.widgetColumn widgetSpanCols = 2 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 #no label labelRow = 0 labelColumn = 0 labelSpanCols = 0 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT return widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment label = pmWidget.label labelColumn = pmWidget.labelColumn spanWidth = pmWidget.spanWidth if not spanWidth: # This widget and its label are on the same row labelRow = row labelSpanCols = 1 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT # Set the widget's row and column parameters. widgetRow = row widgetColumn = 1 widgetSpanCols = 1 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 if labelColumn == 1: widgetColumn = 0 labelAlignment = PM_LABEL_LEFT_ALIGNMENT widgetAlignment = PM_LABEL_RIGHT_ALIGNMENT 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 # Set this widget's row and column parameters. widgetRow = row + 1 # Widget is below the label. widgetColumn = 0 widgetSpanCols = 2 rowIncrement = 2 else: # No label. Just the widget. labelRow = 0 labelColumn = 0 labelSpanCols = 0 # Set the widget's row and column parameters. widgetRow = row widgetColumn = 0 widgetSpanCols = 2 rowIncrement = 1 labelAlignment = PM_LABEL_LEFT_ALIGNMENT widgetAlignment = PM_LABEL_LEFT_ALIGNMENT return widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment def addPmWidget(self, pmWidget): """ Add a PM widget and its label to this group box. @param pmWidget: The PM widget to add. @type pmWidget: PM_Widget """ # Get all the widget and label layout parameters. widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment = \ self.getPmWidgetPlacementParameters(pmWidget) if pmWidget.labelWidget: #Create Label as a pixmap (instead of text) if a valid icon path #is provided labelPath = str(pmWidget.label) if labelPath and labelPath.startswith("ui/"): #bruce 080325 revised labelPixmap = getpixmap(labelPath) if not labelPixmap.isNull(): pmWidget.labelWidget.setPixmap(labelPixmap) pmWidget.labelWidget.setText('') self.gridLayout.addWidget( pmWidget.labelWidget, labelRow, labelColumn, 1, labelSpanCols, labelAlignment ) # The following is a workaround for a Qt bug. If addWidth()'s # <alignment> argument is not supplied, the widget spans the full # column width of the grid cell containing it. If <alignment> # is supplied, this desired behavior is lost and there is no # value that can be supplied to maintain the behavior (0 doesn't # work). The workaround is to call addWidget() without the <alignment> # argument. Mark 2007-07-27. if widgetAlignment == PM_LABEL_LEFT_ALIGNMENT: self.gridLayout.addWidget( pmWidget, widgetRow, widgetColumn, 1, widgetSpanCols) # aligment = 0 doesn't work. else: self.gridLayout.addWidget( pmWidget, widgetRow, widgetColumn, 1, widgetSpanCols, widgetAlignment ) self._widgetList.append(pmWidget) self._rowCount += rowIncrement return def getRowCount(self): """ Return the row count of gridlayout of L{PM_Groupbox} @return: The row count of L{self.gridlayout} @rtype: int """ return self._rowCount def incrementRowCount(self, increment = 1): """ Increment the row count of the gridlayout of L{PM_groupBox} @param increment: The incremental value @type increment: int """ self._rowCount += increment return def addQtWidget(self, qtWidget, column = 0, spanWidth = False): """ Add a Qt widget to this group box. @param qtWidget: The Qt widget to add. @type qtWidget: QWidget @warning: this method has not been tested yet. """ # Set the widget's row and column parameters. widgetRow = self._rowCount widgetColumn = column if spanWidth: widgetSpanCols = 2 else: widgetSpanCols = 1 self.gridLayout.addWidget( qtWidget, widgetRow, widgetColumn, 1, widgetSpanCols ) self._rowCount += 1 return def collapse(self): """ Collapse this group box i.e. hide all its contents and change the look and feel of the groupbox button. """ self.vBoxLayout.setMargin(0) self.vBoxLayout.setSpacing(0) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) # The styleSheet contains the expand/collapse. styleSheet = self._getTitleButtonStyleSheet(showExpanded = False) self.titleButton.setStyleSheet(styleSheet) self._containerWidget.hide() self.expanded = False return def expand(self): """ Expand this group box i.e. show all its contents and change the look and feel of the groupbox button. """ self.vBoxLayout.setMargin(PM_GROUPBOX_VBOXLAYOUT_MARGIN) self.vBoxLayout.setSpacing(PM_GROUPBOX_VBOXLAYOUT_SPACING) self.gridLayout.setMargin(PM_GROUPBOX_GRIDLAYOUT_MARGIN) self.gridLayout.setSpacing(PM_GROUPBOX_GRIDLAYOUT_SPACING) # The styleSheet contains the expand/collapse. styleSheet = self._getTitleButtonStyleSheet(showExpanded = True) self.titleButton.setStyleSheet(styleSheet) self._containerWidget.show() self.expanded = True return def hide(self): """ Hides the group box . @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() # Change the spacer height to zero to "hide" it unless # self is the last GroupBox in the Property Manager. if self.parentWidget._lastGroupBox is self: return if self.verticalSpacer: self.verticalSpacer.changeSize(10, 0) return def show(self): """ Unhides the group box. @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() if self.parentWidget._lastGroupBox is self: return if self.verticalSpacer: self.verticalSpacer.changeSize(10, self.verticalSpacer.defaultHeight) return # Title Button Methods ##################################### def _getTitleButton(self, parentWidget = None, title = '', showExpanded = True ): """ Return the group box title push button. The push button is customized such that it appears as a title bar at the top of the group box. If the user clicks on this 'title bar' it sends a signal to open or close the group box. @param parentWidget: The parent dialog or group box containing this widget. @type parentWidget: PM_Dialog or PM_GroupBox @param title: The button title. @type title: str @param showExpanded: dDetermines whether the expand or collapse image is displayed on the title button. @type showExpanded: bool @see: L{_getTitleButtonStyleSheet()} @Note: Including a title button should only be legal if the parentWidget is a PM_Dialog. """ button = QPushButton(title, parentWidget) button.setFlat(False) button.setAutoFillBackground(True) button.setStyleSheet(self._getTitleButtonStyleSheet(showExpanded)) return button def _getTitleButtonStyleSheet(self, showExpanded = True): """ Returns the style sheet for a group box title button (or checkbox). @param showExpanded: Determines whether to include an expand or collapse icon. @type showExpanded: bool @return: The title button style sheet. @rtype: str """ # 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: #%s; "\ "border-radius: 2px; "\ "background-color: #%s; "\ "font: bold 12px 'Arial'; "\ "color: #%s; "\ "min-width: 10em; "\ "background-image: url(%s); "\ "background-position: right; "\ "background-repeat: no-repeat; "\ "text-align: left; "\ "}" % (QColor_to_Hex(pmGrpBoxButtonBorderColor), QColor_to_Hex(pmGrpBoxButtonColor), QColor_to_Hex(pmGrpBoxButtonTextColor), pmGrpBoxExpandedIconPath ) else: # Collapsed. styleSheet = \ "QPushButton {"\ "border-style: outset; "\ "border-width: 2px; "\ "border-color: #%s; "\ "border-radius: 2px; "\ "background-color: #%s; "\ "font: bold 12px 'Arial'; "\ "color: #%s; "\ "min-width: 10em; "\ "background-image: url(%s); "\ "background-position: right; "\ "background-repeat: no-repeat; "\ "text-align: left; "\ "}" % (QColor_to_Hex(pmGrpBoxButtonBorderColor), QColor_to_Hex(pmGrpBoxButtonColor), QColor_to_Hex(pmGrpBoxButtonTextColor), pmGrpBoxCollapsedIconPath ) if _SUPPORT_QT_4point2: styleSheet = styleSheet.replace("text-align: left; ", "") return styleSheet def toggleExpandCollapse(self): """ Slot method for the title button to expand/collapse the group box. """ if self._widgetList: if self.expanded: self.collapse() else: # Expand groupbox by showing all widgets in groupbox. self.expand() else: print "Clicking on the group box button has no effect "\ "since it has no widgets." return # GroupBox stylesheet methods. ############################## def _getStyleSheet(self): """ Return the style sheet for the groupbox. This sets the following properties only: - border style - border width - border color - border radius (on corners) - background color @return: The group box style sheet. @rtype: str """ styleSheet = \ "QGroupBox {"\ "border-style: solid; "\ "border-width: 1px; "\ "border-color: #%s; "\ "border-radius: 0px; "\ "background-color: #%s; "\ "min-width: 10em; "\ "}" % ( QColor_to_Hex(pmGrpBoxBorderColor), QColor_to_Hex(pmGrpBoxColor) ) return styleSheet # End of PM_GroupBox ############################
NanoCAD-master
cad/src/PM/PM_GroupBox.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ PM_MolecularModelingKit.py - Atom Chooser widget @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. """ from model.elements import PeriodicTable from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_ToolButtonGrid import PM_ToolButtonGrid from utilities.constants import diTUBES from utilities.debug import print_compact_traceback from utilities.exception_classes import AbstractMethod class PM_MolecularModelingKit( PM_GroupBox ): """ The PM_MolecularModelingKit widget provides an Atom Chooser widget, contained in its own group box, for a Property Manager dialog. (see subclasses for details) A PM_MolecularModelingKit is a selection widget that displays all elements, pseudo-atoms supported in NE1. @cvar element: The current element. @type element: Elem @cvar atomType: The current atom type of the current element. @type atomType: str @see: B{elements.py} @see: B{PM.PM_ElementChooser} """ element = None atomType = "" _periodicTable = PeriodicTable viewerDisplay = diTUBES def __init__(self, parentWidget, parentPropMgr = None, title = "Molecular Modeling Kit", element = "", elementViewer = None, ): """ Appends a AtomChooser widget (see subclasses) to the bottom of I{parentWidget}, a Property Manager dialog. (or as a sub groupbox for Atom Chooser GroupBox.) @param parentWidget: The parent PM_Dialog or PM_groupBox containing this widget. @type parentWidget: PM_Dialog or PM_GroupBox @param parentPropMgr: The parent Property Manager @type parentPropMgr: PM_Dialog or None @param title: The button title on the group box containing the Element Chooser. @type title: str @param element: The initially selected element. It can be either an element symbol or name. @type element: str """ PM_GroupBox.__init__(self, parentWidget, title) self.element = self._periodicTable.getElement(element) self.elementViewer = elementViewer self.updateElementViewer() if parentPropMgr: self.parentPropMgr = parentPropMgr else: self.parentPropMgr = parentWidget self._addGroupBoxes() self.connect_or_disconnect_signals(True) def _addGroupBoxes(self): """ Subclasses should add various groupboxes present inside the Atom chooser groupbox. AbstractMethod """ raise AbstractMethod() def _addElementsGroupBox(self, inPmGroupBox): """ Creates a grid of tool buttons containing all elements supported in NE1. @param inPmGroupBox: The parent group box to contain the element buttons. @type inPmGroupBox: PM_GroupBox """ self._elementsButtonGroup = \ PM_ToolButtonGrid( inPmGroupBox, title = "", buttonList = self.getElementsButtonList(), checkedId = self.element.eltnum, setAsDefault = True ) self.connect( self._elementsButtonGroup.buttonGroup, SIGNAL("buttonClicked(int)"), self.setElement ) def _updateAtomTypesButtons(self): """ Updates the hybrid buttons based on the currently selected element button. Subclasses should override this method """ pass def restoreDefault(self): """ Restores the default checked (selected) element and atom type buttons. """ PM_GroupBox.restoreDefault(self) self._updateAtomTypesButtons() return def getElementNumber(self): """ Returns the element number of the currently selected element. @return: Selected element number @rtype: int """ return self._elementsButtonGroup.checkedId() def getElementSymbolAndAtomType(self): """ Returns the symbol and atom type of the currently selected element. @return: element symbol, atom type @rtype: str, str """ currentElementNumber = self.getElementNumber() element = self._periodicTable.getElement(currentElementNumber) return element.symbol, self.atomType def getElement(self): """ Get the current element. @return: element @rtype: Elem @see: B{element.py} """ return self.element def setElement(self, elementNumber): """ Set the current element in the MMKit to I{elementNumber}. @param elementNumber: Element number. (i.e. 6 = carbon) @type elementNumber: int """ self.element = self._periodicTable.getElement(elementNumber) self._updateAtomTypesButtons() self.updateElementViewer() self._updateParentPropMgr() return def updateElementViewer(self): """ Update the view in the element viewer (if present) """ if not self.elementViewer: return from graphics.widgets.ThumbView import MMKitView assert isinstance(self.elementViewer, MMKitView) self.elementViewer.resetView() self.elementViewer.changeHybridType(self.atomType) self.elementViewer.refreshDisplay(self.element, self.viewerDisplay) return def _updateParentPropMgr(self): """ Update things in the parentWidget if necessary. (The parentWidget should be a property manager, although not necessary) Example: In Build Atoms Mode, the Property manager message groupbox needs to be updated if the element is changed in the element chooser. Similarly, the selection filter list should be updated in this mode. """ parentPropMgrClass = self.parentPropMgr.__class__ if hasattr(parentPropMgrClass, 'updateMessage'): try: self.parentPropMgr.updateMessage() except AttributeError: print_compact_traceback("Error calling updateMessage()") if hasattr(parentPropMgrClass, 'update_selection_filter_list'): try: self.parentPropMgr.update_selection_filter_list() except AttributeError: msg = "Error calling update_selection_filter_list()" print_compact_traceback(msg) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ #Not implemented yet return def getElementsButtonList(self): """ Subclasses should override this and return the list of buttons in the Atom chooser. """ raise AbstractMethod()
NanoCAD-master
cad/src/PM/PM_MolecularModelingKit.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ PM_ColorChooser.py @author: Mark @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. All rights reserved. History: """ from PyQt4.Qt import QLabel from PyQt4.Qt import QFrame from PyQt4.Qt import QToolButton from PyQt4.Qt import QHBoxLayout from PyQt4.Qt import QSpacerItem from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QWidget from PyQt4.Qt import SIGNAL from PyQt4.Qt import QColorDialog from PyQt4.Qt import QPalette from PyQt4.Qt import QSize from utilities.constants import white, black from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf class PM_ColorChooser( QWidget ): """ The PM_ColorChooser widget provides a color chooser widget for a Property Manager group box. The PM_ColorChooser widget is a composite widget made from 3 other Qt widgets: - a QLabel - a QFrame and - a QToolButton (with a "..." text label). IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_ColorChooser1.jpg) The user can color using Qt's color (chooser) dialog by clicking the "..." button. The selected color will be used as the color of the QFrame widget. The parent must make the following signal-slot connection to be notified when the user has selected a new color via the color chooser dialog: self.connect(pmColorChooser.colorFrame, SIGNAL("editingFinished()"), self.mySlotMethod) @cvar setAsDefault: Determines whether to reset the value of the color to I{defaultColor} when the user clicks the "Restore Defaults" button. @type setAsDefault: boolean @cvar labelWidget: The Qt label widget of this PM widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar colorFrame: The Qt frame widget for this PM widget. @type colorFrame: U{B{QFrame}<http://doc.trolltech.com/4/qframe.html>} @cvar chooseButton: The Qt tool button widget for this PM widget. @type chooseButton: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ defaultColor = None setAsDefault = True hidden = False chooseButton = None customColorCount = 0 standardColorList = [white, black] def __init__(self, parentWidget, label = 'Color:', labelColumn = 0, color = white, setAsDefault = True, spanWidth = False, ): """ Appends a color chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the color frame (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param color: initial color. White is the default. @type color: tuple of 3 floats (r, g, b) @param setAsDefault: if True, will restore L{color} when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean @see: U{B{QColorDialog}<http://doc.trolltech.com/4/qcolordialog.html>} """ QWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.color = color self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Create the color frame (color swath) and "..." button. self.colorFrame = QFrame() self.colorFrame.setFrameShape(QFrame.Box) self.colorFrame.setFrameShadow(QFrame.Plain) # Set browse button text and make signal-slot connection. self.chooseButton = QToolButton() self.chooseButton.setText("...") self.connect(self.chooseButton, SIGNAL("clicked()"), self.openColorChooserDialog) # Add a horizontal spacer to keep the colorFrame and "..." squeezed # together, even when the PM width changes. self.hSpacer = QSpacerItem(10, 10, QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) # Create vertical box layout. self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(2) self.hBoxLayout.insertWidget(-1, self.colorFrame) self.hBoxLayout.insertWidget(-1, self.chooseButton) # Set this to False to make the colorFrame an expandable rectangle. COLORFRAME_IS_SQUARE = True if COLORFRAME_IS_SQUARE: squareSize = 20 self.colorFrame.setMinimumSize(QSize(squareSize, squareSize)) self.colorFrame.setMaximumSize(QSize(squareSize, squareSize)) self.hBoxLayout.addItem(self.hSpacer) self.setColor(color, default = setAsDefault) parentWidget.addPmWidget(self) return def setColor(self, color, default = False): """ Set the color. @param color: The color. @type color: tuple of 3 floats (r, g, b) @param default: If True, make I{color} the default color. Default is False. @type default: boolean """ if default: self.defaultColor = color self.setAsDefault = default self.color = color self._updateColorFrame() return def getColor(self): """ Return the current color. @return: The current r, g, b color. @rtype: Tuple of 3 floats (r, g, b) """ return self.color def getQColor(self): """ Return the current QColor. @return: The current color. @rtype: QColor """ return RGBf_to_QColor(self.color) def _updateColorFrame(self): """ Updates the color frame with the current color. """ colorframe = self.colorFrame try: qcolor = self.getQColor() palette = QPalette() # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here qcolorrole = QPalette.Window ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says: ## QPalette.Window 10 A general background color. palette.setColor(QPalette.Active, qcolorrole, qcolor) # used when window is in fg and has focus palette.setColor(QPalette.Inactive, qcolorrole, qcolor) # used when window is in bg or does not have focus palette.setColor(QPalette.Disabled, qcolorrole, qcolor) # used when widget is disabled colorframe.setPalette(palette) colorframe.setAutoFillBackground(True) except: print "data for following exception: ", print "colorframe %r has palette %r" % (colorframe, colorframe.palette()) pass def openColorChooserDialog(self): """ Prompts the user to choose a color and then updates colorFrame with the selected color. """ qcolor = RGBf_to_QColor(self.color) if not self.color in self.standardColorList: QColorDialog.setCustomColor(self.customColorCount, qcolor.rgb()) self.customColorCount += 1 c = QColorDialog.getColor(qcolor, self) if c.isValid(): self.setColor(QColor_to_RGBf(c)) self.colorFrame.emit(SIGNAL("editingFinished()")) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setColor(self.defaultColor) return def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() return def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() return # End of PM_ColorChooser ############################
NanoCAD-master
cad/src/PM/PM_ColorChooser.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ PM_PrefsCheckBoxes.py PM_PrefsCheckBoxes class provides a way to insert a groupbox within a Property Manager, that contains a bunch of check boxes connected to the User Preference via preference keys. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: """ from PyQt4.Qt import Qt from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from widgets.prefs_widgets import connect_checkbox_with_boolean_pref class PM_PrefsCheckBoxes(PM_GroupBox): """ PM_PrefsCheckBoxes class provides a way to insert a groupbox within a Property Manager, that contains a bunch of check boxes connected to the User Preference via preference keys. """ def __init__(self, parentWidget, paramsForCheckBoxes = (), checkBoxColumn = 1, title = ''): """ @param parentWidget: The parent dialog or group box containing this widget. @type parentWidget: L{PM_Dialog} or L{PM_GroupBox} @param title: The title (button) text. If empty, no title is added. @type title: str @param paramsForCheckBoxes: A list object that contains tuples like the following : ('checkBoxTextString' , preference_key). The checkboxes will be constucted by looping over this list. @type paramsForCheckBoxes:list @param checkBoxColumn: The widget column in which all the checkboxes will be inserted. @type checkBoxColumn: int @see: InsertDna_PropertyManager._loadDisplayOptionsGroupBox for an example use. """ PM_GroupBox.__init__(self, parentWidget, title = title) self._checkBoxColumn = checkBoxColumn #Also maintain all checkboxes created by this class in this list, #just in case the caller needs them. (need access methods for this) self.checkBoxes = [] #Create checkboxes and also connect them to their preference keys. self._addCheckBoxes(paramsForCheckBoxes) def _addCheckBoxes(self, paramsForCheckBoxes): """ Creates PM_CheckBoxes within the groupbox and also connects each one with its individual prefs key. """ for checkBoxText, prefs_key in paramsForCheckBoxes: checkBox = \ PM_CheckBox( self, text = checkBoxText, widgetColumn = self._checkBoxColumn, state = Qt.Checked) connect_checkbox_with_boolean_pref( checkBox , prefs_key) self.checkBoxes.append(checkBox)
NanoCAD-master
cad/src/PM/PM_PrefsCheckBoxes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_RadioButton.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrRadioButton out of PropMgrBaseClass.py into this file and renamed it PM_RadioButton. """ from PyQt4.Qt import QRadioButton from PyQt4.Qt import QWidget class PM_RadioButton( QRadioButton ): """ The PM_RadioButton widget provides a radio button for a Property Manager group box. """ defaultIsChecked = False setAsDefault = False labelWidget = None # Needed for PM_GroupBox.addPmWidget(). label = "" # Needed for PM_GroupBox.addPmWidget(). labelColumn = 0 # Needed for PM_GroupBox.addPmWidget(). spanWidth = False # Needed for PM_GroupBox.addPmWidget(). def __init__(self, parentWidget, text = '', isChecked = False, setAsDefault = False ): """ Appends a QRadioButton widget to <parentWidget>, a property manager group box. Appends a QCheckBox (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param text: The text that appears to the right of the radio button. @type text: str @param isChecked: Set's the radio button's check state. The default is True. @type isChecked: bool @param setAsDefault: If True, will restore I{isChecked} when the "Restore Defaults" button is clicked. @type setAsDefault: bool @see: U{B{QRadioButton}<http://doc.trolltech.com/4/qradiobutton.html>} """ QRadioButton.__init__(self) self.parentWidget = parentWidget self.setAsDefault = setAsDefault self.setText(text) self.setCheckable(True) self.setChecked(isChecked) self.defaultIsChecked = isChecked self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default check state. """ if self.setAsDefault: self.setChecked(self.defaultIsChecked) # End of PM_RadioButton ############################
NanoCAD-master
cad/src/PM/PM_RadioButton.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_Constants.py -- Property Manager constants. @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Created initially for PM_Dialog as part of the code cleanup and review for new coding standards. Renamed all constants to names with uppercase letters. To do: - search and replace all lowercase constants with uppercase constants. """ import sys from PyQt4.Qt import Qt __author__ = "Mark" # PropMgr constants (system specific). # Same as above, except these names meet our Python coding guildlines. # To do: search and replace all lowercase constants with uppercase constants. if sys.platform == "darwin": PM_MINIMUM_WIDTH = 300 # The min PropMgr width. PM_MAXIMUM_WIDTH = 450 # The max PropMgr width. PM_DEFAULT_WIDTH = PM_MINIMUM_WIDTH # Starting PropMgr width PM_HEADER_FONT = "Arial" # Font type used in PropMgr header. PM_HEADER_FONT_POINT_SIZE = 18 PM_HEADER_FONT_BOLD = False elif sys.platform == "win32": PM_MINIMUM_WIDTH = 240 # The min PropMgr width. PM_MAXIMUM_WIDTH = 400 # The max PropMgr width. PM_DEFAULT_WIDTH = PM_MINIMUM_WIDTH # Starting PropMgr width PM_HEADER_FONT = "Arial" # Font type used in PropMgr header. PM_HEADER_FONT_POINT_SIZE = 12 PM_HEADER_FONT_BOLD = True else: #Linux PM_MINIMUM_WIDTH = 250 # The min PropMgr width. PM_MAXIMUM_WIDTH = 400 # The max PropMgr width. PM_DEFAULT_WIDTH = PM_MINIMUM_WIDTH # Starting PropMgr width PM_HEADER_FONT = "Arial" # Font type used in PropMgr header. PM_HEADER_FONT_POINT_SIZE = 12 PM_HEADER_FONT_BOLD = True if 0: print "PropMgr width = ", PM_DEFAULT_WIDTH print "PropMgr Min width = ", PM_MINIMUM_WIDTH print "PropMgr Max width = ", PM_MAXIMUM_WIDTH # PropMgr constants. PM_GROUPBOX_SPACING = 4 # 4 pixels between groupboxes PM_MAINVBOXLAYOUT_MARGIN = 0 # PropMgr's master VboxLayout marging PM_MAINVBOXLAYOUT_SPACING = 0 # PropMgr's master VboxLayout spacing # Header constants. PM_HEADER_FRAME_MARGIN = 2 # margin around icon and title. PM_HEADER_FRAME_SPACING = 5 # space between icon and title. # Sponsor button constants. PM_SPONSOR_FRAME_MARGIN = 0 # margin around sponsor button. PM_SPONSOR_FRAME_SPACING = 0 # has no effect. # GroupBox Layout constants. PM_GROUPBOX_VBOXLAYOUT_MARGIN = 2 # Groupbox VboxLayout margin PM_GROUPBOX_VBOXLAYOUT_SPACING = 2 # Groupbox VboxLayout spacing PM_GROUPBOX_GRIDLAYOUT_MARGIN = 2 # Grid contains all widgets in a grpbox PM_GROUPBOX_GRIDLAYOUT_SPACING = 2 # Grid contains all widgets in a grpbox # Top Row Buttons constants PM_TOPROWBUTTONS_MARGIN = 2 # margin around buttons. PM_TOPROWBUTTONS_SPACING = 2 # space between buttons. # Top Row Button flags. PM_NO_BUTTONS = 0 PM_DONE_BUTTON = 1 PM_CANCEL_BUTTON = 2 PM_RESTORE_DEFAULTS_BUTTON = 4 PM_PREVIEW_BUTTON = 8 PM_WHATS_THIS_BUTTON = 16 PM_ALL_BUTTONS = \ PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_RESTORE_DEFAULTS_BUTTON | \ PM_PREVIEW_BUTTON | \ PM_WHATS_THIS_BUTTON # Grid layout. Grid contains all widgets in a PM_GroupBox. PM_GRIDLAYOUT_MARGIN = 1 PM_GRIDLAYOUT_SPACING = 2 # PM Label alignment constants used for layouts. PM_LABEL_RIGHT_ALIGNMENT = Qt.AlignRight | Qt.AlignVCenter PM_LABEL_LEFT_ALIGNMENT = Qt.AlignLeft | Qt.AlignVCenter # The side (column) of a PM group box. PM_LEFT_COLUMN = 0 PM_RIGHT_COLUMN = 1
NanoCAD-master
cad/src/PM/PM_Constants.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_WidgetGrid.py @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-14: Created. """ from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QSpacerItem from PyQt4.Qt import QSize from PyQt4.Qt import QLabel from PyQt4.Qt import QToolButton from PyQt4.Qt import QPushButton from utilities.debug import print_compact_traceback from utilities.icon_utilities import geticon from PM.PM_GroupBox import PM_GroupBox class PM_WidgetGrid( PM_GroupBox ): """ The B{PM_WidgetGrid} provides a convenient way to create different types of widgets (such as ToolButtons, Labels, PushButtons etc) and arrange them in the grid layout of a B{PM_Groupbox} @see: B{Ui_MovePropertyManager} that uses B{PM_ToolButtonRow}, to create custom widgets (toolbuttons) arranged in a grid layout. """ def __init__(self, parentWidget, title = '', widgetList = [], alignment = None, label = '', labelColumn = 0, spanWidth = True ): """ Appends a PM_WidgetGrid (a group box widget) to the bottom of I{parentWidget},the Property Manager Group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param title: The group box title. @type title: str @param widgetList: A list of I{widget info lists}. There is one widget info list for each widget in the grid. The widget info list contains custom information about the widget but the following items are always present: - First Item : Widget Type (str), - Second Last Item : Column (int), - Last Item : Row (int). @type widgetList: list @param alignment: The alignment of the widget row in the parent groupbox. Based on its value,spacer items is added to the grid layout of the parent groupbox. @type alignment: str @param label: The label for the widget row. . @type label: str @param labelColumn: The column in the parentWidget's grid layout to which this widget's label will be added. The labelColum can only be E{0} or E{1} @type labelColumn: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) """ self.label = label self.labelColumn = labelColumn self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) PM_GroupBox.__init__(self, parentWidget, title) # These are needed to properly maintain the height of the grid if # all labels in a row are hidden via hide(). self.vBoxLayout.setMargin(0) self.vBoxLayout.setSpacing(0) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.parentWidget = parentWidget self.widgetList = widgetList self.alignment = alignment self.loadWidgets() def loadWidgets(self): """ Creates the widgets (or spacers) in a grid layout of a B{PM_GroupBox} Then adds this group box to the grid layout of the I{parentWidget}, which is again a B{PM_GroupBox} object. """ for widgetInfo in self.widgetList: widgetInfoList = self.getWidgetInfoList(widgetInfo) widgetParams = list(widgetInfoList[0:-2]) widgetOrSpacer = self._createWidgetUsingParameters(widgetParams) column = widgetInfoList[-2] row = widgetInfoList[-1] if widgetOrSpacer.__class__.__name__ == QSpacerItem.__name__: self.gridLayout.addItem( widgetOrSpacer, row, column, 1, 1 ) else: self.gridLayout.addWidget( widgetOrSpacer, row, column, 1, 1 ) self.parentWidget.addPmWidget(self) def getWidgetInfoList(self, widgetInfo): """ Returns the widget information provided by the user. Subclasses should override this method if they need to provide custom information (e.g. a fixed value for row) . @param widgetInfo: A list containing the widget information @type widgetInfo: list @return: A list containing custom widget information. This can be same as I{widgetInfo} or can be modified further. @rtype: list @see: B{PM_ToolButtonRow.getWidgetInfoList} """ widgetInfoList = list(widgetInfo) return widgetInfoList def _createWidgetUsingParameters(self, widgetParams): """ Returns a widget based on the I{widgetType} Subclasses can override this method. @param widgetParams: A list containing widget's parameters. @type widgetParams: list @see: L{PM_ToolButtonGrid._createWidgetUsingParameters} which overrides this method. """ widgetParams = list(widgetParams) widgetType = str(widgetParams[0]) if widgetType[0:3] == "PM_": #The given widget is already defined using a class in PM_Module #so simply use the specified object #@see:Ui_BuildCrystal_PropertyManager._loadLayerPropertiesGroupBox # for an example on how it is used. widget = widgetParams[1] return widget if widgetType == QToolButton.__name__: widget = self._createToolButton(widgetParams) elif widgetType == QPushButton.__name__: widget = self._createPushButton(widgetParams) elif widgetType == QLabel.__name__: widget = self._createLabel(widgetParams) elif widgetType == QSpacerItem.__name__: widget = self._createSpacer(widgetParams) else: msg1 = "Error, unknown/unsupported widget type. " msg2 = "Widget Grid can not be created" print_compact_traceback(msg1 + msg2) widget = None return widget def _createToolButton(self, widgetParams): """ Returns a tool button created using the custom parameters. @param widgetParams: A list containing tool button parameters. @type widgetParams: list @see: L{self._createWidgetUsingParameters} where this method is called. """ buttonSize = QSize(32, 32) #@ FOR TEST ONLY buttonParams = list(widgetParams) buttonId = buttonParams[1] buttonText = buttonParams[2] buttonIconPath = buttonParams[3] buttonToolTip = buttonParams[4] buttonShortcut = buttonParams[5] button = QToolButton(self) button.setText(buttonText) if buttonIconPath: buttonIcon = geticon(buttonIconPath) if not buttonIcon.isNull(): button.setIcon(buttonIcon) button.setIconSize(QSize(22, 22)) button.setToolTip(buttonToolTip) if buttonShortcut: button.setShortcut(buttonShortcut) button.setFixedSize(buttonSize) #@ Currently fixed to 32 x 32. button.setCheckable(True) return button def _createLabel(self, widgetParams): """ Returns a label created using the custom parameters. @param widgetParams: A list containing label parameters. @type widgetParams: list @see: L{self._createWidgetUsingParameters} where this method is called. """ labelParams = list(widgetParams) labelText = labelParams[1] label = QLabel(self) label.setText(labelText) return label def _createSpacer(self, widgetParams): """ Returns a QSpacerItem created using the custom parameters. @param widgetParams: A list containing spacer parameters. @type widgetParams: list @see: L{self._createWidgetUsingParameters} where this method is called. """ spacerParams = list(widgetParams) spacerWidth = spacerParams[1] spacerHeight = spacerParams[2] spacer = QSpacerItem(spacerWidth, spacerHeight, QSizePolicy.MinimumExpanding, QSizePolicy.Minimum ) return spacer # ==== Helper methods to add widgets/ spacers to the Grid Layout ===== # NOTE: Following helper methods ARE NOT used as of 2007-08-16. These will # be deleted or modified when a new HBoxLayout is introduced to the Groupbox #-- Ninad 2007-08-16 def addWidgetToParentGridLayout(self): """ Adds this widget (groupbox) to the parent widget's grid layout. ( The parent widget should be a groupbox) Example: If user specifies this widget's alignment as 'Center' then it adds Left spacer, this widget and the right spacer to the parentWidget's grid layout, in the current row. This method also increments the row number of the parentWidget's grid layout. @see: L{self.loadWidgets} which calls this method """ row = self.parentWidget.getRowCount() column = 0 #Add Left spacer to the parentWidget's layout if self.alignment and self.alignment != 'Left': self._addAlignmentSpacer(row, column) column += 1 #Add the widget to the parentWidget's layout self.parentWidget.gridLayout.addWidget(self, row, column, 1, 1) #Add Right spacer to the parentWidget's layout if self.alignment and self.alignment != 'Right': self._addAlignmentSpacer(row, column + 1) #Increment the parent widget's row count self.parentWidget.incrementRowCount() def _addAlignmentSpacer(self, rowNumber, columnNumber): """ Adds a alignment spacer to the parent widget's grid layout which also contain this classes widget. @see: L{self.addWidgetToParentGridLayout} for an example on how it is used. """ row = rowNumber column = columnNumber spacer = QSpacerItem(10, 5, QSizePolicy.Expanding, QSizePolicy.Minimum) self.parentWidget.gridLayout.addItem( spacer, row, column, 1, 1 )
NanoCAD-master
cad/src/PM/PM_WidgetGrid.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ PM_SelectionListWidget.py @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. All rights reserved. TODO: - Probably need to revise the tag instructions. At the moment it is confusing. If a list widget item is selected from that widget, what should happen to the corresponding item in the GLPane -- Should it get selected? or should it just be tagged? or do both? Popular cad programs would just tag entities in the glpane. But, in our case (Insert DNA Duplex for Rattlesnake user story V6) we need to also select strands in the glpane when those are selected from the list widget. So, in the current implementation, this is handled by a flag 'self._tagInstructions'. It is confusing because of the overuse of the term 'select' . I have tried to resolve this by using terms 'pick' and unpick and explicitely mentioning 'glpane' . But overall, needs discussion and cleanup. see also: PM_SelectionListWidget.tagItems [-- Ninad 2007-11-12] - the attr 'iconPath' needs to be defined for various objects. Need a better name? (Example: see class Atom.iconPath that specifies the atom icon path as a string) - Review Changes to be done: (Bruce's email) As for self._tagInstruction in PM_SelectionListWidget.py -- things will be cleaner if the widget code does not know a lot of details about how to manipulate display and model info in a graphicsMode. Also, there are update issues about storing atom posns in the graphicsMode.list of tag posns and then the user moves the atoms. So, what I suggest as a refactoring at some point is for the widget to just be given a callback function, so that whenever the set of selected list items is different, it calls that function with the new list. Then the specific graphicsModes can clear whatever they stored last time, then scan that list and do whatever they want with it. No graphicsMode knowledge is needed in the widget, and whatever atom posn updates are needed is handled entirely in the graphicsMode -- either it updates the list of tag posns whenever model_changed, or it just stores a list of atoms in the first place, not a list of their positions, so it uses up to date posns each time it draws. **Comments/Questions: Implementation of this callback function -- where should this be defined? In the propMgr that initializes this list widget? If so, it needs to be defined in each propMgr that will define this listwidget (example: MotorPM and DnaDuplexPM each will need to define the callback methods. In the current implementation, they just set a 'tag instruction' for this widget.)What if propMgr.model_changed also calls a model_changed method defined in this widget? """ from PM.PM_ListWidget import PM_ListWidget from PyQt4.Qt import QListWidgetItem from PyQt4.Qt import SIGNAL from PyQt4.Qt import QPalette from PyQt4.Qt import QAbstractItemView from PyQt4.Qt import Qt from PM.PM_Colors import getPalette from widgets.widget_helpers import RGBf_to_QColor from utilities.constants import yellow, white from utilities.icon_utilities import geticon from utilities.debug import print_compact_traceback TAG_INSTRUCTIONS = ['TAG_ITEM_IN_GLPANE', 'PICK_ITEM_IN_GLPANE', 'TAG_AND_PICK_ITEM_IN_GLPANE'] class PM_SelectionListWidget(PM_ListWidget): """ Appends a QListWidget (Qt) widget to the I{parentWidget}, a Property Manager group box. This is a selection list widget, that means if you select the items in this list widget, the corresponding item in the GLPane will be tagged or picked or both depending on the 'tag instructions' @param _tagInstruction: Sets the tag instruction. Based on its value, the items selected in the List widget will be either tagged or picked or both in the glpane. @type _tagInstruction: string @param _itemDictionary: This QListWidgetItem object defines a 'key' of a dictionary and the 'value' of this key is the object specified by the 'item' itself. Example: self._itemDictionary['C6'] = instance of class Atom. @type _itemDictionary: dictionary """ def __init__(self, parentWidget, win, label = '', color = None, heightByRows = 6, spanWidth = False): """ Appends a QListWidget (Qt) widget to the I{parentWidget}, a Property Manager group box. This is a selection list widget, that means if you select the items in this list widget, the corresponding item in the GLPane will be tagged or picked or both depending on the 'tag instructions' @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param win: Mainwindow object @type win: MWSemantics @param label: The label that appears to the left or right of the checkbox. If spanWidth is True, the label will be displayed on its own row directly above the list widget. To suppress the label, set I{label} to an empty string. @type label: str @param color: color of the ListWidget @type : Array @param heightByRows: The height of the list widget. @type heightByRows: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool @see: U{B{QListWidget}<http://doc.trolltech.com/4/qlistwidget.html>} """ self.win = win self.glpane = self.win.glpane #Note: self._tagInstruction and self._itemDictionary are instance #variables and not class constants as we #have many PM_SelectionListWidget objects (e.g. in Build Dna mode, we # have Srand and Segment list widgets. Defining self._itemDictionary #as a class constant will make class objects share it and create bugs. self._tagInstruction = 'TAG_ITEM_IN_GLPANE' self._itemDictionary = {} #The following flag suppresses the itemSelectionChanged signal #see self.updateSelection for more comments. self._suppress_itemSelectionChanged_signal = False #The following flag suppresses the itemChanged signal #ItemChanged signal is emitted too frequently. We use this to know that #the data of an item has changed...example : to know that the renaming #operation of the widget is completed. When a widgetItem is renamed, #we want to rename the corresponding object in the glpane (which is #stored as a value in self._itemDictionary) As of 2008-04-16 this signal #is the most convienent way to do it (in Qt4.2.3). If this flag #is set to False, it simply returns from the method that gets called #when itemItemChanged signal is sent. The flag is set to True #while updating items in self.isertItems. When itemDoubleClicked signal #is sent, the flag is explicitely set to False -- Ninad 2008-04-16 #@see: self.renameItemValue(), #@self.editItem() (This is a QListWidget method) self._suppress_itemChanged_signal = False PM_ListWidget.__init__(self, parentWidget, label = '', heightByRows = heightByRows, spanWidth = spanWidth) self.setSelectionMode(QAbstractItemView.ExtendedSelection) #Assigning color to the widget -- to be revised. (The color should #change only when the focus is inside this widget -- the color change #will also suggest object(s) selected in glpane will be added as #items in this widget (could be a selective addition depending on # the use) -- Niand 2007-11-12 if color: self.setAutoFillBackground(True) self.setPalette(getPalette( None, QPalette.Base, color)) def deleteSelection(self): """ Remove the selected items from the list widget (and self._itemDictionary) """ for key in self.selectedItems(): assert self._itemDictionary.has_key(key) del self._itemDictionary[key] def getItemDictonary(self): """ Returns the dictonary of self's items. @see: MultipleSegments_PropertyManager.listWidget_keyPressEvent_delegate for details. """ return self._itemDictionary 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: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self, SIGNAL('itemSelectionChanged()'), self.tagItems) change_connect(self, SIGNAL('itemDoubleClicked ( QListWidgetItem *)'), self.editItem) change_connect(self, SIGNAL('itemChanged ( QListWidgetItem *)'), self.renameItemValue) def editItem(self, item): """ Edit the widget item. @see: self.insertItems for a comment @see: self.renameItemValue() @self.editItem() (This is a QListWidget method """ #explicitely set the flag to False for safety. self._suppress_itemChanged_signal = False PM_ListWidget.editItem(self, item) def renameItemValue(self, item): """ slot method that gets called when itemChanged signal is emitted. Example: 1. User double clicks an item in the strand list widget of the BuildDna mode 2. Edits the name. 3.Hits Enter key or clicks outside the selection to end rename operation. During step1, itemDoubleClicked signal is emitted which calls self.editItem and at the end of step3, it emits itemChanged signal which calls this method @self.editItem() (This is a QListWidget method) """ #See a detailed note in self.__init__ where the following flag is #declared. The flag is set to True when if self._suppress_itemChanged_signal: return if self._itemDictionary.has_key(item): val = self._itemDictionary[item] #Check if the 'val' (obj which this widgetitem represents) has an #attr name. if not hasattr(val, 'name'): if not item.text(): #don't permit empty names -- doesn't make sense. item.setText('name') return #Do the actual renaming of the 'val' if item.text(): val.name = item.text() self.win.win_update() else: #Don't allow assignment of a blank name item.setText(val.name) def insertItems(self, row, items, setAsDefault = True): """ Insert the <items> specified items in this list widget. The list widget shows item name string , as a QListwidgetItem. This QListWidgetItem object defines a 'key' of a dictionary (self._itemDictionary) and the 'value' of this key is the object specified by the 'item' itself. Example: self._itemDictionary['C6'] = instance of class Atom. @param row: The row number for the item. @type row: int @param items: A list of objects. These objects are treated as values in the self._itemDictionary @type items: list @param setAsDefault: Not used here. See PM_ListWidget.insertItems where it is used. @see: self.renameItemValue() for a comment about self._suppress_itemChanged_signal """ #delete unused argument. Should this be provided as an argument in this #class method ? del setAsDefault #self.__init__ for a comment about this flag self._suppress_itemChanged_signal = True #Clear the previous contents of the self._itemDictionary self._itemDictionary.clear() #Clear the contents of this list widget, using QListWidget.clear() #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details self.clear() for item in items: if hasattr(item.__class__, 'name'): itemName = item.name else: itemName = str(item) listWidgetItem = QListWidgetItem(itemName, self) #When we support editing list widget items , uncomment out the #following line . See also self.editItems -- Ninad 2008-01-16 listWidgetItem.setFlags( listWidgetItem.flags()| Qt.ItemIsEditable) if hasattr(item.__class__, 'iconPath'): try: listWidgetItem.setIcon(geticon(item.iconPath)) except: print_compact_traceback() self._itemDictionary[listWidgetItem] = item #Reset the flag that temporarily suppresses itemChange signal. self._suppress_itemChanged_signal = False def setColor(self, color): """ Set the color of the widget to the one given by param color @param color: new palette color of self. """ self.setAutoFillBackground(True) color = RGBf_to_QColor(color) self.setPalette(getPalette( None, QPalette.Base, color)) def resetColor(self): """ Reset the paletter color of the widget (and set it to white) """ self.setAutoFillBackground(True) color = RGBf_to_QColor(white) self.setPalette(getPalette( None, QPalette.Base, color)) def clearTags(self): """ Clear the previously drawn tags if any. """ ### TODO: this should not go through the current graphicsMode, # in case that belongs to a temporary command or to nullCommand # (which would cause bugs). Rather, it should find "this PM's graphicsMode". # [bruce 081002 comment] self.glpane.graphicsMode.setDrawTags(tagPositions = ()) def setTagInstruction(self, tagInstruction = 'TAG_ITEM_IN_GLPANE'): """ Sets the client specified tag instruction. If a list widget item is selected from that widget, what should happen to the corresponding item in the GLPane -- Should it get selected? or should it just be tagged? or do both? This is decided using the tag instruction. """ assert tagInstruction in TAG_INSTRUCTIONS self._tagInstruction = tagInstruction def tagItems(self): """ For the selected items in the list widget, tag and/or select the corresponding item in the GLPane based on the self._tagInstruction @see: self.setTagInstruction """ if self._suppress_itemSelectionChanged_signal: return graphicsMode = self.glpane.graphicsMode # TODO: fix this, in the same way as described in self.clearTags. # [bruce 081002 comment] #Clear the previous tags if any self.clearTags() if self._tagInstruction != 'TAG_ITEM_IN_GLPANE': #Unpick all list widget items in the 3D workspace #if no modifier key is pressed. Earlier implementation #used to only unpick items that were also present in the list #widgets.But if we have multiple list widgets, example like #in Build DNA mode, it can lead to confusion like in Bug 2681 #NOTE ABOUT A NEW POSSIBLE BUG: #self.glpan.modkeys not changed when focus is inside the #Property manager? Example: User holds down Shift key and starts #selecting things inside -- Ninad 2008-03-18 if self.glpane.modkeys is None: self.win.assy.unpickall_in_GLPane() #Deprecated call of _unpick_all_listWidgetItems_in_glpane #(deprecated on 2008-03-18 ##self._unpick_all_listWidgetItems_in_glpane() #Now pick the items selected in this list widget self._pick_selected_listWidgetItems_in_glpane() if self._tagInstruction != 'PICK_ITEM_IN_GLPANE': tagPositions = [] #Note: method selectedItems() is inherited from QListWidget #see: U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details for key in self.selectedItems(): assert self._itemDictionary.has_key(key) item = self._itemDictionary[key] if isinstance(item, self.win.assy.DnaSegment): end1, end2 = item.getAxisEndPoints() for endPoint in (end1, end2): if endPoint is not None: tagPositions.append(endPoint) elif hasattr(item.__class__, 'posn'): tagPositions.append(item.posn()) if tagPositions: graphicsMode.setDrawTags(tagPositions = tagPositions, tagColor = yellow) self.glpane.gl_update() def _unpick_all_listWidgetItems_in_glpane(self): """ Deselect (unpick) all the items (object) in the GLPane that correspond to the items in this list widget. Deprecated as of 2008-03-18. See a comment in self.tagItems """ for item in self._itemDictionary.values(): if item.picked: item.unpick() def _pick_selected_listWidgetItems_in_glpane(self): """ If some items in the list widgets are selected (in the widget) also select (pick) them from the glpane(3D workspace) """ for key in self.selectedItems(): assert self._itemDictionary.has_key(key) item = self._itemDictionary[key] if not item.picked: item.pick() def updateSelection(self, selectedItemList): """ Update the selected items in this selection list widget. The items given by the parameter selectedItemList will get selected. This suppresses the 'itemSelectionChanged signal because the items are already selected in the 3D workspace and we just want to select the corresponding items (QWidgetListItems) in this list widget. @param selectedItemList: List of items provided by the client that need to be selected in this list widget @type selectedItemList: list @see: B{BuildDna_PropertyManager.model_changed} """ #The following flag suppresses the itemSelectionChanged signal , thereby #prevents self.tagItems from calling. This is done because the #items selection was changed from the 3D workspace. After this, the #selection state of the corresponding items in the list widget must be #updated. self._suppress_itemSelectionChanged_signal = True for key, value in self._itemDictionary.iteritems(): if value in selectedItemList: if not key.isSelected(): key.setSelected(True) else: if key.isSelected(): key.setSelected(False) # Contrary to this method's docstring, it is possible that items # in selectedItemList() are not selected in the glpane, so (re)pick # them as a precaution. --Mark 2008-12-22 self._pick_selected_listWidgetItems_in_glpane() self._suppress_itemSelectionChanged_signal = False def clear(self): """ Clear everything inside this list widget including the contents of self._itemDictionary and tags if any. Overrides QListWidget.clear() """ self.clearTags() #Clear the previous contents of the self._itemDictionary self._itemDictionary.clear() #Clear the contents of this list widget, using QListWidget.clear() #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details PM_ListWidget.clear(self) def getPickedItem(self): """ Return the 'real' item picked (selected) inside this selection list widget. The 'real' item is the object whose name appears inside the selection list widget. (it does not return the 'QWidgetItem' but the key.value() that actually stores the NE1 object) NOTE: If there are more than one items selected, it returns only the FIRST ITEM in the list. This class is designed to select only a single item at a time , but in case this implementation changes, this method should be revised. @see: BuildDna_PropertyManager.assignStrandSequence """ #Using self.selectedItems() doesn't work for some reason! (when you # select item , go to the sequence editor and hit assign button, # it spits an error pickedItem = None selectedItemList = self.selectedItems() key = selectedItemList[0] pickedItem = self._itemDictionary[key] return pickedItem #for item in self._itemDictionary.values(): #if item.picked: #return item #return None
NanoCAD-master
cad/src/PM/PM_SelectionListWidget.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_ListWidget.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrListWidget out of PropMgrBaseClass.py into this file and renamed it PM_ListWidget. """ from PyQt4.Qt import QLabel from PyQt4.Qt import QListWidget from PyQt4.Qt import QWidget from PyQt4.Qt import Qt from PyQt4.Qt import QAbstractItemView from utilities.debug import print_compact_traceback class PM_ListWidget( QListWidget ): """ The PM_ListWidget widget provides a QListWidget with a QLabel for a Property Manager group box. @cvar defaultItems: The default list of items in the list widget. @type defaultItems: list @cvar defaultRow: The default row of the list widget. @type defaultRow: int @cvar setAsDefault: Determines whether to reset the choices to I{defaultItems} and current row to I{defaultRow} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this list widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultRow = 0 defaultItems = [] setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, items = [], defaultRow = 0, setAsDefault = True, heightByRows = 6, spanWidth = False ): """ Appends a QListWidget (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the checkbox. If spanWidth is True, the label will be displayed on its own row directly above the list widget. To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param items: list of items (strings) to be inserted in the widget. @type items: list @param defaultRow: The default row (item) selected, where 0 is the first row. @type defaultRow: int @param setAsDefault: If True, will restore <idx> as the current index when the "Restore Defaults" button is clicked. @type setAsDefault: bool @param heightByRows: The height of the list widget. @type heightByRows: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool @see: U{B{QListWidget}<http://doc.trolltech.com/4/qlistwidget.html>} """ if 0: # Debugging code print "PM_ListWidget.__init__():" print " label = ", label print " labelColumn = ", labelColumn print " items = ", items print " defaultRow = ", defaultRow print " setAsDefault = ", setAsDefault print " heightByRows = ", heightByRows print " spanWidth = ", spanWidth QListWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Load QComboBox widget choice items and set initial choice (index). self.insertItems(0, items, setAsDefault) self.setCurrentRow(defaultRow, setAsDefault) # Set height of list widget. margin = self.fontMetrics().leading() * 2 # Mark 2007-05-28 height = heightByRows * self.fontMetrics().lineSpacing() + margin self.setMaximumHeight(height) #As of 2008-04-16, the items in any list widgets won't be sorted #automatically. It can be changes by simply uncommentting the lines #below -- Ninad ##self.setSortingEnabled(True) ##self.sortItems() self.setAlternatingRowColors(True) parentWidget.addPmWidget(self) 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 = "PM_ListWidget.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 = False ): """ Select new row. @param row: The new row to select. @type row: int @param setAsDefault: If True, I{row} becomes the default row when "Restore Defaults" is clicked. """ if setAsDefault: self.setAsDefault = setAsDefault self.defaultRow = row QListWidget.setCurrentRow(self, row) def restoreDefault(self): """ Restores the default value. """ 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) def hide(self): """ Hides the list widget and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the list widget and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() # End of PM_ListWidget ############################
NanoCAD-master
cad/src/PM/PM_ListWidget.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_PushButton.py @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrPushButton out of PropMgrBaseClass.py into this file and renamed it PM_PushButton. """ from PyQt4.Qt import QLabel from PyQt4.Qt import QPushButton from PyQt4.Qt import QWidget from widgets.prefs_widgets import widget_setAction from widgets.prefs_widgets import QPushButton_ConnectionWithAction class PM_PushButton( QPushButton ): """ The PM_PushButton widget provides a QPushButton with a QLabel for a Property Manager group box. @cvar defaultText: The default text of the push button. @type defaultText: str @cvar setAsDefault: Determines whether to reset the value of the push button to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this push button. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultText = "" setAsDefault = True labelWidget = None def __init__(self, parentWidget, label = '', labelColumn = 0, text = '', setAsDefault = True, spanWidth = False ): """ Appends a QPushButton (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the checkbox. If spanWidth is True, the label will be displayed on its own row directly above the list widget. To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param text: The button's text. @type text: str @param setAsDefault: if True, will restore <text> as the button's text when the "Restore Defaults" button is clicked. @type setAsDefault: bool @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool @see: U{B{QPushButton}<http://doc.trolltech.com/4/qpushbutton.html>} """ if 0: # Debugging code print "PM_PushButton.__init__():" print " label = ", label print " labelColumn = ", labelColumn print " text = ", text print " setAsDefault = ", setAsDefault print " spanWidth = ", spanWidth QPushButton.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) # Set text self.setText(text) # Set default text self.defaultText=text self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setText(self.defaultText) def hide(self): """ Hides the push button and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the push button and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() def setAction(self, aCallable, cmdname = None): widget_setAction( self, aCallable, QPushButton_ConnectionWithAction, cmdname = cmdname) pass # End of PM_PushButton ############################
NanoCAD-master
cad/src/PM/PM_PushButton.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_Slider.py @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-21: Created. """ from PyQt4.Qt import Qt from PyQt4.Qt import QSlider from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget class PM_Slider(QSlider): labelWidget = None def __init__( self, parentWidget, orientation = None, ##Qt.Horizontal, currentValue = 0, minimum = 0, maximum = 100, label = '', labelColumn = 0, setAsDefault = True, spanWidth = True): """ Appends a Qslider widget (with a QLabel widget) to <parentWidget> a property manager group box. Arguments: @param parentWidget: the group box containing this PM widget. @type parentWidget: PM_GroupBox @param currentValue: @type currentValue: int @param minimum: minimum value the slider can get. (used to set its 'range') @type minimum: int @param maximum: maximum value the slider can get. (used to set its 'range') @type maximum: int @param label: label that appears to the left of (or above) this widget. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param setAsDefault: if True, will restore value when the "Restore Defaults" button is clicked. @type setAsDefault: bool (default True) @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty)and is left justified. @type spanWidth: bool (default True) @see: U{B{QSlider}<http://doc.trolltech.com/4/qslider.html>} """ ##QSlider.__init__(self, orientation, parentWidget) QSlider.__init__(self, parentWidget) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth #Ideally, this should be simply self.setOrientation(orientation) with the #default orientation = Qt.Horizontal in the init argument itself. But, #apparently pylint chokes up when init argument is a Qt enum. #This problem happened while running pylint 0.23 on the SEMBOT server #so comitting this temporary workaround. The pylint on my machine is #0.25 and it runs fine even before this workaround. Similar changes made #in PM_CheckBox. -- Ninad 2008-06-30 if orientation is None: self.setOrientation(Qt.Horizontal) else: self.setOrientation(orientation) if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) self.setValue(currentValue) self.setRange(minimum, maximum) self.setAsDefault = setAsDefault if self.setAsDefault: self.setDefaultValue(currentValue) parentWidget.addPmWidget(self) def hide(self): """ Hides the slider and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() def show(self): """ Unhides the slider and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setValue(self.defaultValue) def setDefaultValue(self, value): """ Sets the Default value for the slider. This value will be set if user hits Restore Defaults button in the Property Manager. """ self.defaultValue = value self.setAsDefault = True
NanoCAD-master
cad/src/PM/PM_Slider.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-08-12 created. TODO 2008-08-12: - This uses global pref keys (hardcoded) because the preference is supposed to remain in all commands. Other option is to ask the command or parentWidget for the prefs_key. If we want to support local prefs keys (e.g. turn on the labels while in certain commands only, then perhaps it should ask for prefs keys from the command. (and there needs an API method in command so that its implemented for all command classes. The latter seems unncecessary at this time, """ import foundation.env as env from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_ColorComboBox import PM_ColorComboBox from utilities.prefs_constants import dnaBaseNumberLabelColor_prefs_key from utilities.prefs_constants import dnaBaseNumberingOrder_prefs_key from utilities.prefs_constants import dnaBaseNumberLabelChoice_prefs_key from PyQt4.Qt import SIGNAL from widgets.prefs_widgets import connect_comboBox_with_pref _superclass = PM_GroupBox class PM_DnaBaseNumberLabelsGroupBox(PM_GroupBox): """ """ def __init__(self, parentWidget, command, title = 'Base Number Labels' ): """ """ self.command = command self.win = self.command.win _superclass.__init__(self, parentWidget, title = title) self._loadWidgets() def connect_or_disconnect_signals(self, isConnect): """ """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect change_connect(self._baseNumberLabelColorChooser, SIGNAL("editingFinished()"), self._colorChanged_dnaBaseNumberLabel) self._connect_widgets_with_prefs_keys() def _connect_widgets_with_prefs_keys(self): """ Connect various widgets with a prefs_key """ prefs_key = dnaBaseNumberLabelChoice_prefs_key connect_comboBox_with_pref(self._baseNumberComboBox, prefs_key ) prefs_key = dnaBaseNumberingOrder_prefs_key connect_comboBox_with_pref(self._baseNumberingOrderComboBox , prefs_key ) def _loadWidgets(self): """ Load the widgets in the Groupbox """ baseNumberChoices = ('None (default)', 'Strands and segments', 'Strands only', 'Segments only') self._baseNumberComboBox = \ PM_ComboBox( self, label = "Base numbers:", choices = baseNumberChoices, setAsDefault = True) numberingOrderChoices = ('5\' to 3\' (default)', '3\' to 5\'' ) self._baseNumberingOrderComboBox = \ PM_ComboBox( self, label = "Base numbers:", choices = numberingOrderChoices, setAsDefault = True) prefs_key = dnaBaseNumberLabelColor_prefs_key self._baseNumberLabelColorChooser = \ PM_ColorComboBox(self, color = env.prefs[prefs_key]) def _colorChanged_dnaBaseNumberLabel(self): """ Choose custom color for 5' ends """ color = self._baseNumberLabelColorChooser.getColor() prefs_key = dnaBaseNumberLabelColor_prefs_key env.prefs[prefs_key] = color self.win.glpane.gl_update() return def _updateColor_dnaBaseNumberLabel(self): """ Update the color in the base number label combobox while calling self.show() @see: self.show(). """ prefs_key = dnaBaseNumberLabelColor_prefs_key color = env.prefs[prefs_key] self._baseNumberLabelColorChooser.setColor(color) return def updateWidgets(self): """ Called in BreakorJoinstrands_PropertyManager.show() """ #@TODO: revise this. #Ideally the color combobox should be connected with state. #(e.g. 'connect_colorCombobox_with_state' , which will make the #following update call unncessary. but connecting with state #for the color combobox has some issues not resolved yet. #(e.g. the current index changed won't always allow you to set the #proper color -- because the 'Other color' can be anything) #--Ninad 2008-08-12 self._updateColor_dnaBaseNumberLabel()
NanoCAD-master
cad/src/PM/PM_DnaBaseNumberLabelsGroupBox.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ PM_CheckBox.py @author: Mark @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. History: mark 2007-07-22: Split PropMgrCheckBox out of PropMgrBaseClass.py into this file and renamed it PM_CheckBox. """ from PyQt4.Qt import Qt from PyQt4.Qt import QCheckBox from PyQt4.Qt import QLabel from PyQt4.Qt import QWidget from PM.PM_Constants import PM_LEFT_COLUMN, PM_RIGHT_COLUMN from widgets.prefs_widgets import widget_connectWithState from widgets.prefs_widgets import QCheckBox_ConnectionWithState from widgets.prefs_widgets import set_metainfo_from_stateref class PM_CheckBox( QCheckBox ): """ The PM_CheckBox widget provides a checkbox with a text label for a Property Manager group box. The text label can be positioned on the left or right side of the checkbox. A PM_CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are typically used to represent features in an application that can be enabled or disabled without affecting others, but different types of behavior can be implemented. A U{B{QButtonGroup}<http://doc.trolltech.com/4/qbuttongroup.html>} can be used to group check buttons visually. Whenever a checkbox is checked or cleared it emits the signal stateChanged(). Connect to this signal if you want to trigger an action each time the checkbox changes state. You can use isChecked() to query whether or not a checkbox is checked. In addition to the usual checked and unchecked states, PM_CheckBox optionally provides a third state to indicate "no change". This is useful whenever you need to give the user the option of neither checking nor unchecking a checkbox. If you need this third state, enable it with setTristate(), and use checkState() to query the current toggle state. Just like PM_PushButton, a checkbox displays text, and optionally a small icon. The icon is set with setIcon(). The text can be set in the constructor or with setText(). A shortcut key can be specified by preceding the preferred character with an ampersand. For example: checkbox = PM_CheckBox("C&ase sensitive") In this example the shortcut is B{Alt+A}. See the U{B{QShortcut}<http://doc.trolltech.com/4/qshortcut.html>} documentation for details (to display an actual ampersand, use '&&'). @cvar defaultState: The default state of the checkbox. @type defaultState: U{B{Qt.CheckState}<http://doc.trolltech.com/4/ qt.html#CheckState-enum>} @cvar setAsDefault: Determines whether to reset the state of the checkbox to I{defaultState} when the user clicks the "Restore Defaults" button. @type setAsDefault: bool @cvar labelWidget: The Qt label widget of this checkbox. This value is set to 'None' @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} """ defaultState = Qt.Unchecked setAsDefault = True labelWidget = None def __init__(self, parentWidget, text = '', widgetColumn = 1, state = None, ##Qt.Unchecked, setAsDefault = True, spanWidth = False ): """ Appends a QCheckBox (Qt) widget to the bottom of I{parentWidget}, a Property Manager group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox @param text: This property holds the text shown on the checkbox. @type text: str @param widgetColumn: The column number of the PM_CheckBox widget in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 1 (right column). @type widgetColumn: int @param state: Set's the check box's check state. The default is Qt.Unchecked (unchecked). @type state: U{B{Qt.CheckState}<http://doc.trolltech.com/4/ qt.html#CheckState-enum>} @param setAsDefault: If True, will restore I{state} when the "Restore Defaults" button is clicked. @type setAsDefault: bool @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool @see: U{B{QCheckBox}<http://doc.trolltech.com/4/qcheckbox.html>} """ QCheckBox.__init__(self) self.parentWidget = parentWidget self.setText(text) self.widgetColumn = widgetColumn self.setAsDefault = setAsDefault self.spanWidth = spanWidth #Ideally, this should be simply self.setCheckState(state) with the #default state = Qt.UnChecked in the ,init argument itself. But, #apparently pylint chokes up when init argument is a Qt enum. #This problem happened while running pylint 0.23 on the SEMBOT server #so comitting this temporary workaround. The pylint on my machine is #0.25 and it runs fine even before this workaround. Similar changes made #in PM_Slider. #-- Ninad 2008-06-30 if state is None: state = Qt.Unchecked if self.setAsDefault: self.setDefaultState(state) self.setCheckState(state) parentWidget.addPmWidget(self) def setDefaultState(self, state): self.setAsDefault = True self.defaultState = state pass def setCheckState(self, state, setAsDefault = False): """ Sets the check box's check state to I{state}. @param state: Set's the check box's check state. @type state: U{B{Qt.CheckState}<http://doc.trolltech.com/4/ qt.html#CheckState-enum>} @param setAsDefault: If True, will restore I{state} when the "Restore Defaults" button is clicked. @type setAsDefault: bool """ if setAsDefault: self.setAsDefault = setAsDefault self.defaultState = state QCheckBox.setCheckState(self, state) def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setCheckState(self.defaultState) def connectWithState(self, stateref, set_metainfo = True, debug_metainfo = False): """ Connect self to the state referred to by stateref, so changes to self's value change that state's value and vice versa. By default, also set self's metainfo to correspond to what the stateref provides. @param stateref: a reference to state of type boolean, which meets the state-reference interface StateRef_API @type stateref: StateRef_API @param set_metainfo: whether to also set defaultValue, if it's provided by the stateref @type set_metainfo: bool @param debug_metainfo: whether to print debug messages about the actions taken by set_metainfo @type debug_metainfo: bool """ if set_metainfo: set_metainfo_from_stateref( self.setDefaultValue, stateref, 'defaultValue', debug_metainfo) widget_connectWithState( self, stateref, QCheckBox_ConnectionWithState) # note: that class uses setChecked, not setCheckState return def setDefaultValue(self, value): #bruce 070815 guess self.setAsDefault = True if value: self.defaultState = Qt.Checked else: self.defaultState = Qt.Unchecked return def hide(self): """ Hides the checkbox and its label (if it has one). Call L{show()} to unhide the checkbox. @see: L{show} """ QWidget.hide(self) def show(self): """ Unhides the checkbox and its label (if it has one). @see: L{hide} """ QWidget.show(self) pass # End of PM_CheckBox ############################
NanoCAD-master
cad/src/PM/PM_CheckBox.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_RadioButtonList.py @author: Mark Sims @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. All rights reserved. History: mark 2007-08-05: Created. """ from PyQt4.Qt import QButtonGroup from PyQt4.Qt import QRadioButton from PM.PM_GroupBox import PM_GroupBox from PyQt4.Qt import QLabel class PM_RadioButtonList( PM_GroupBox ): """ The PM_RadioButtonList widget provides a list of radio buttons that function as an I{exclusive button group}. """ buttonList = [] defaultCheckedId = -1 # -1 means no checked Id setAsDefault = True labelWidget = None def __init__(self, parentWidget, title = '', label = '', labelColumn = 0, buttonList = [], checkedId = -1, setAsDefault = False, spanWidth = True, borders = True ): """ Appends a PM_RadioButtonList widget to the bottom of I{parentWidget}, the Property Manager dialog or group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: PM_GroupBox or PM_Dialog @param title: The group box title. @type title: str @param label: The label for the coordinate spinbox. @type label: str @param labelColumn: The column in the parentWidget's grid layout to which this widget's label will be added. The labelColum can only be E{0} or E{1} @type labelColumn: int @param buttonList: A list of I{button info lists}. There is one button info list for each radio button in the list. The button info list contains the following three items: 1). Button Id (int), 2). Button text (str), 3). Button tool tip (str). @type buttonList: list @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) @param borders: If true (default), this widget will have borders displayed. otherwise the won't be any outside borders around the set of radio buttons this class provides @type borders: boolean """ # Intializing label, labelColumn etc is needed before doing # PM_GroupBox.__init__. This is done so that # self.parentWidget.addPmWidget(self) done at the end of __init__ # works properly. # 'self.parentWidget.addPmWidget(self)' is done to avoid a bug where a # groupbox is always appended as the 'last widget' when its # parentWidget is also a groupbox. This is due to other PM widgets #(e.g. PM_PushButton)add themselves to their parent widget in their #__init__ using self.parentWidget.addPmWidget(self). So doing the #same thing here. More general fix is needed in PM_GroupBox code # --Ninad 2007-11-14 (comment copied from PM_coordinateSpinBoxes) self.label = label self.labelColumn = labelColumn self.spanWidth = spanWidth if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) PM_GroupBox.__init__(self, parentWidget, title) # These are needed to properly maintain the height of the grid if # all buttons in a row are hidden via hide(). self.vBoxLayout.setMargin(0) self.vBoxLayout.setSpacing(0) self.buttonGroup = QButtonGroup() self.buttonGroup.setExclusive(True) self.parentWidget = parentWidget self.buttonList = buttonList if setAsDefault: self.setDefaultCheckedId(checkedId) self.buttonsById = {} self.buttonsByText = {} # Create radio button list from button info. for buttonInfo in buttonList: buttonId = buttonInfo[0] buttonText = buttonInfo[1] buttonToolTip = buttonInfo[2] button = QRadioButton(self) button.setText(buttonText) button.setToolTip(buttonToolTip) # Not working. button.setCheckable(True) if checkedId == buttonId: button.setChecked(True) self.buttonGroup.addButton(button, buttonId) self.vBoxLayout.addWidget(button) self.buttonsById[buttonId] = button self.buttonsByText[buttonText] = button if isinstance(self.parentWidget, PM_GroupBox): self.parentWidget.addPmWidget(self) else: #@@ Should self be added to self.parentWidget's widgetList? #don't know. Retaining old code -- Ninad 2008-06-23 self._widgetList.append(self) self._rowCount += 1 if not borders: #reset the style sheet so that there are no borders around the #radio button set this class provides. self.setStyleSheet(self._getAlternateStyleSheet()) def restoreDefault(self): """ Restores the default checkedId. """ if self.setAsDefault: for buttonInfo in self.buttonList: buttonId = buttonInfo[0] if buttonId == self.defaultCheckedId: button = self.getButtonById(buttonId) button.setChecked(True) return def setDefaultCheckedId(self, checkedId): """ Sets the default checked id (button) to I{checkedId}. The current checked button is unchanged. @param checkedId: The new default id for the tool button group. @type checkedId: int """ self.setAsDefault = True self.defaultCheckedId = checkedId def checkedButton(self): """ Returns the tool button group's checked button, or 0 if no buttons are checked. """ return self.buttonGroup.checkedButton() def checkedId(self): """ Returns the id of the checkedButton(), or -1 if no button is checked. """ return self.buttonGroup.checkedId() def getButtonByText(self, text): """ Returns the button with its current text set to I{text}. """ if self.buttonsByText.has_key(text): return self.buttonsByText[text] else: return None def getButtonById(self, buttonId): """ Returns the button with the button id of I{buttonId}. """ if self.buttonsById.has_key(buttonId): return self.buttonsById[buttonId] else: return None def _getAlternateStyleSheet(self): """ Return the style sheet for the groupbox. This sets the following properties only: - border style - border width - border color - border radius (on corners) @see: L{PM_GroupBox._getStyleSheet} (overrided here) """ styleSheet = "QGroupBox {border-style:hidden;\ border-width: 0px;\ border-color: "";\ border-radius: 0px;\ min-width: 10em; }" return styleSheet # End of PM_RadioButtonList ############################
NanoCAD-master
cad/src/PM/PM_RadioButtonList.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ PM_FileChooser.py @author: Mark @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. All rights reserved. History: """ import os from PyQt4.Qt import QLabel from PyQt4.Qt import QLineEdit from PyQt4.Qt import QToolButton from PyQt4.Qt import QHBoxLayout from PyQt4.Qt import QWidget from PyQt4.Qt import SIGNAL from PyQt4.Qt import QFileDialog from utilities.prefs_constants import getDefaultWorkingDirectory class PM_FileChooser( QWidget ): """ The PM_FileChooser widget provides a file chooser widget for a Property Manager group box. The PM_FileChooser widget is a composite widget made from 3 other Qt widgets: - a QLabel - a QLineEdit and - a QToolButton (with a "..." text label). IMAGE(http://www.nanoengineer-1.net/mediawiki/images/e/e2/PM_FileChooser1.jpg) The user can type the path name of a file into the line edit widget or select a file using Qt's file (chooser) dialog by clicking the "..." button. The path name of the selected file will be inserted into the line edit widget. The parent must make the following signal-slot connection to be notified when the user has selected a new file via the file chooser dialog: self.connect(pmFileChooser.lineEdit, SIGNAL("editingFinished()"), self.mySlotMethod) @cvar defaultText: The default text (path) of the line edit widget. @type defaultText: string @cvar setAsDefault: Determines whether to reset the value of the lineedit to I{defaultText} when the user clicks the "Restore Defaults" button. @type setAsDefault: boolean @cvar labelWidget: The Qt label widget of this PM widget. @type labelWidget: U{B{QLabel}<http://doc.trolltech.com/4/qlabel.html>} @cvar lineEdit: The Qt line edit widget for this PM widget. @type lineEdit: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} @cvar browseButton: The Qt tool button widget for this PM widget. @type browseButton: U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>} """ defaultText = "" setAsDefault = True hidden = False lineEdit = None browseButton = None def __init__(self, parentWidget, label = '', labelColumn = 0, text = '', setAsDefault = True, spanWidth = False, caption = "Choose file", directory = '', filter = "All Files (*.*)" ): """ Appends a file chooser widget to <parentWidget>, a property manager group box. @param parentWidget: the parent group box containing this widget. @type parentWidget: PM_GroupBox @param label: The label that appears to the left or right of the file chooser lineedit (and "Browse" button). If spanWidth is True, the label will be displayed on its own row directly above the lineedit (and button). To suppress the label, set I{label} to an empty string. @type label: str @param labelColumn: The column number of the label in the group box grid layout. The only valid values are 0 (left column) and 1 (right column). The default is 0 (left column). @type labelColumn: int @param text: initial value of LineEdit widget. @type text: string @param setAsDefault: if True, will restore <val> when the "Restore Defaults" button is clicked. @type setAsDefault: boolean @param spanWidth: if True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: boolean @param caption: The caption used as the title of the file chooser dialog. "Choose file" is the default. @type caption: string @param directory: The directory that the file chooser dialog should open in when the "..." button is clicked. If blank or if directory does not exist, the current working directory is used. @type directory: string @param filter: The file type filters to use for the file chooser dialog. @type filter: string (a semicolon-separated list of file types) @see: U{B{QLineEdit}<http://doc.trolltech.com/4/qlineedit.html>} """ QWidget.__init__(self) self.parentWidget = parentWidget self.label = label self.labelColumn = labelColumn self.text = text self.setAsDefault = setAsDefault self.spanWidth = spanWidth self.caption = caption self.directory = directory self.filter = filter if label: # Create this widget's QLabel. self.labelWidget = QLabel() self.labelWidget.setText(label) else: # Create a dummy attribute for PM_GroupBox to see. This might have # needed to be fixed in PM_GroupBox, but it was done here to try to # avoid causing errors in other PM widgets. -Derrick 20080916 self.labelWidget = None self.lineEdit = QLineEdit() self.browseButton = QToolButton() # Create vertical box layout. self.hBoxLayout = QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(2) self.hBoxLayout.insertWidget(-1, self.lineEdit) self.hBoxLayout.insertWidget(-1, self.browseButton) # Set (QLineEdit) text self.setText(text) # Set browse button text and make signal-slot connection. self.browseButton.setText("...") self.connect(self.browseButton, SIGNAL("clicked()"), self.openFileChooserDialog) # Set default value self.defaultText = text self.setAsDefault = setAsDefault parentWidget.addPmWidget(self) return def setText(self, text): """ Set the line edit text. @param text: The text. @type text: string """ self.lineEdit.setText(text) self.text = text return def openFileChooserDialog(self): """ Prompts the user to choose a file from disk and inserts the full path into the lineEdit widget. """ _dir = getDefaultWorkingDirectory() if self.directory: if os.path.isdir(self.directory): _dir = self.directory fname = QFileDialog.getOpenFileName(self, self.caption, _dir, self.filter) if fname: self.setText(fname) self.lineEdit.emit(SIGNAL("editingFinished()")) return def restoreDefault(self): """ Restores the default value. """ if self.setAsDefault: self.setText(self.defaultText) return def hide(self): """ Hides the lineedit and its label (if it has one). @see: L{show} """ QWidget.hide(self) if self.labelWidget: self.labelWidget.hide() return def show(self): """ Unhides the lineedit and its label (if it has one). @see: L{hide} """ QWidget.show(self) if self.labelWidget: self.labelWidget.show() return # End of PM_FileChooser ############################
NanoCAD-master
cad/src/PM/PM_FileChooser.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ PM_WidgetRow.py @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-08-09: Created. @attention: This file is subject to heavy modifications. """ from PM.PM_WidgetGrid import PM_WidgetGrid from widgets.widget_helpers import QColor_to_Hex from PM.PM_Colors import pmGrpBoxColor class PM_WidgetRow( PM_WidgetGrid ): """ The B{PM_WidgetRow} provides a convenient way to create different types of widgets (such as ToolButtons, Labels, PushButtons etc) in a single row and add them to a groupbox. #Example of how a caller creates a PM_WidgetRow object: # Format of the widget list that is passed to the widget row -- # - Widget type, # - Middle portion of any tuple in the list is either a widget object # or some other parameters if the widget object of # given type needs to be created by the PM_WidgetRow. For example-- # If widget type is 'QLabel' , then it will be created by # PM_WidgetRow class and user just need to provide the text for the # QLabel. # - column number (the last item in a tuple) aWidgetList = [('PM_ComboBox', self.latticeTypeComboBox, 0), ('PM_PushButton', self.addLayerButton, 1), ('QLabel', "Some Label", 2) ] widgetRow = PM_WidgetRow(parentWidget, title = '', widgetList = aWidgetList, label = "Layer:", labelColumn = 0, ) @see: B{PM_WidgetGrid._createWidgetUsingParameters } @see: B{Ui_BuildCrystal_PropertyManager._loadLayerPropertiesGroupBox} that uses a B{PM_WidgetRow} """ titleButtonRequested = False def __init__(self, parentWidget, title = '', widgetList = [], alignment = None, label = '', labelColumn = 0, spanWidth = False ): """ Appends a PM_WidgetRow (a group box widget) to the bottom of I{parentWidget},the Property Manager Group box. @param parentWidget: The parent group box containing this widget. @type parentWidget: L{PM_GroupBox} @param title: The group box title. @type title: str @param widgetList: A list of I{widget info lists}. There is one widget info list for each widget in the grid. The widget info list contains custom information about the widget but the following items are always present: - First Item : Widget Type (str), - Second Last Item : Column (int), - Last Item : Row (int). @type widgetList: list @param alignment: The alignment of the widget row in the parent groupbox. Based on its value,spacer items is added to the grid layout of the parent groupbox. @type alignment: str @param label: The label for the widget row. . @type label: str @param labelColumn: The column in the parentWidget's grid layout to which this widget's label will be added. The labelColum can only be E{0} or E{1} @type labelColumn: int @param spanWidth: If True, the widget and its label will span the width of the group box. Its label will appear directly above the widget (unless the label is empty) and is left justified. @type spanWidth: bool (default False) """ PM_WidgetGrid.__init__(self, parentWidget , title, widgetList, alignment , label, labelColumn, spanWidth ) def getWidgetInfoList(self, widgetInfo): """ Returns the label information provided by the user. Overrides PM_LabelGrid.getLabelInfoList if they need to provide custom information (e.g. a fixed value for row) . @param labelInfo: list containing the label information @type labelInfo: list @return : A list containing the label information. This can be same as I{labelInfo} or can be modified further. @rtype : list @see: L{PM_WidgetGrid.getWidgetInfoList (this method is overridden here) """ row = 0 widgetInfoList = list(widgetInfo) widgetInfoList.append(row) return widgetInfoList def _getStyleSheet(self): """ Return the style sheet for the groupbox. This sets the following properties only: - border style - border width - border color - border radius (on corners) - background color @see: L{PM_GroupBox._getStyleSheet} (overrided here) """ styleSheet = "QGroupBox {border-style:hidden; "\ "border-width: 0px; "\ "border-color: ""; "\ "border-radius: 0px;"\ "min-width: 10em; "\ "background-color: #%s;"\ "}" % ( QColor_to_Hex(pmGrpBoxColor)) return styleSheet
NanoCAD-master
cad/src/PM/PM_WidgetRow.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ bond_updater.py Recompute structural bond orders when necessary. @author: Bruce @version: $Id$ @copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details. This is needed for bonds between atoms whose atomtypes make p orbitals available for bonding, to check whether pi bonds are formed, whether they're aromatic or double or triple, to check for radicals (pi systems containing unpaired electrons), and to notice graphite. (Much of the above is not yet implemented.) History: bruce 050627 started this as part of supporting higher-order bonds. bruce 071108 split out the general orchestration and registration part of this into master_model_updater.py, leaving only the bond- type- and atom-type- updating code in this file. """ from utilities.debug import print_compact_traceback from model.bond_constants import V_SINGLE from model.bond_constants import V_DOUBLE from model.bond_constants import V_AROMATIC from model.bond_constants import V_GRAPHITE from model.bond_constants import V_TRIPLE from model.bond_constants import V_CARBOMERIC # == def update_bonds_after_each_event( changed_structure_atoms): """ [should be called only from _master_model_updater, which is in turn called from env.do_post_event_updates] This should be called at the end of every user event which might affect the atomtypes or bond-sets of any atoms or singlets, which are passed as the values of the dict changed_structure_atoms, which we should not modify (and which no other code will modify while we use it). (As it happens, the caller will clear that dict after we return.) This function will either update, or record as needing update, the structural bond orders and associated data for all real atoms, real bonds, and open bonds which might be in pi systems (or which were, but aren't anymore). [And it might do more. #k if so, #doc that here.] Since it must be fast, it won't do work which leads it away from the actual atoms it's passed, and it will leave existing bond orders alone whenever they're locally consistent with the current atomtypes. That is, it will only act when there are local inconsistencies, and it will only fix them when this can be done on just the atoms it was passed (or their bonds), and in a reasonably unambiguous way; whenever it thinks a more global update is needed, it will record this fact (and the affected atoms) so the user can be advised that a global bond-update is needed. It will assume that interpart bonds (if any) have already been broken. (#e Or we might decide to extend it to break them itself.) """ ###@@@ so far this is called by update_parts (eg mode chgs), # and near the start of a GLPane repaint event (should be enough), # and only when changed_structure_atoms is nonempty. #k # It misses hearing about killed atoms or singlets, # but does hear about atoms shown only in the elt selector thumbviews! # I guess the latter is good, since that way it can update the bond orders # in those views as well! However, debug tests showed that the elt selector # thumbviews need a separate redraw to show this... that's ok, they're only # supposed to draw single-bond atypes anyway. bonds_to_fix = {} mols_changed = {} #bruce 060126, so atom._changed_structure() doesn't need # to call atom.changed() directly for atm in changed_structure_atoms.values(): #bruce 060405 precaution: itervalues -> values, # due to jig.changed_structure calls # ignore killed atoms # [bruce 071018 bugfix of old bug # "reguess_atomtype of bondpoint with no bonds"] if atm._Atom__killed: # this inlines atm.killed() for speed, since this will happen a lot continue ## if 'testing kluge': ## #bruce 071117 -- see if this breaks any of our Python versions. ## # update 071119: reported to work for Windows- python 2.4, ## # OS X- python 2.3, Ubuntu- python2.5, so we can assume it ## # works for all versions unless we find out otherwise. ## # So this test code is now disabled unless further needed. ## # I'm commenting it out entirely, so the import from chem can't ## # mess up our import analysis. Once some real code relies on ## # class-switching, we can remove this test code entirely. ## # [bruce 071119] ## from chem import Atom2, Atom ## if atm.__class__ is Atom: ## nc = Atom2 ## else: ## nc = Atom ## assert nc is not atm.__class__ ## atm.__class__ = nc ## print "testing kluge, bruce 071117: set %s.__class__ to %s" % (atm, nc) ## assert nc is atm.__class__ # for singlets, just look at their base atoms # [I'm not sure where that comment shows up in the code, or whether the # following comment was meant to be a change to it -- bruce 071115] # [as of 050707 just look at all bonds of all unkilled atoms] #e when info must be recorded for later, do this per-chunk or per-part. ##k Do we move existing such info when atoms moved or were killed?? mol = atm.molecule # might be None or nullMol; check later mols_changed[id(mol)] = mol atype = atm.atomtype # make sure this is defined; also it will tell us # the permitted bond orders for any bond on this atom for bond in atm.bonds: v6 = bond.v6 if v6 != V_SINGLE: # this test is just an optim if not atype.permits_v6(v6): # this doesn't notice things like S=S (unstable), only the # S= and =S parts (ok taken alone) bonds_to_fix[id(bond)] = bond # SOMEDAY: also check legal endcombos for aromatic, graphite # (carbomeric?) # SOMEDAY: also directly check sp-chain-lengths here, # infer double bonds when odd length and connected, etc?? # Tell perceived structures involving this atom that it changed. # (These will include sp-chains and pi-systems, and maybe more. # For Alpha6, probably only sp-chains.) # For now, these are stored in jigs; one jig might contain just one # perceived structure, or all of one kind in one set of atoms # (the following code needn't know which). if atm.jigs: # most atoms have no jigs, so initial 'if' is worthwhile for jig in atm.jigs[:]: # list copy is necessary, see below try: method = jig.changed_structure except AttributeError: pass # initial kluge so I don't need to extend class Jig #FIX else: try: method(atm) # Note: this is permitted to destroy jig # and (thereby) remove it from atm.jigs except: msg = "ignoring exception in jig.changed_atom(%r) " \ "for %r: " % (atm, jig) print_compact_traceback( msg) continue # atom-valence checks can't be done until we fix illegal bond types, # below # comments about future atom-valence checks: # #e should we also check atypes against numbonds and total bond valence # (in case no bonds need fixing or they don't change)? # note: that's the only way we'll ever notice we need to increase any # bonds from single, on sp2 atoms!!! # Do we need to separately track needed reductions (from atypes) # or certainty-increases (A no longer allowed) or increases # (from atom valence)?? # For certainty-increases, should we first figure out the rest before # seeing what to change them to? (guess: no, but not sure) # # (above cmts are obs, see paper notes about the alg) for mol in mols_changed.itervalues(): if mol is not None: mol.changed() # should be safe for nullMol (but not for None) if not bonds_to_fix: return # optim [will be wrong once we have atom valence checks below] for bond in bonds_to_fix.itervalues(): # every one of these bonds is wrong, in a direct local way # (ie due to its atoms)! # figure out what to change it to, and [someday] initiate our scan # of changes from each end of each bond. new_v6 = _best_corrected_v6(bond) ####@@@@ IMPLEM the rest of that... # actually this'll all be revised bond.set_v6(new_v6) #####@@@@@ ensure this calls _changed_structure # on both atoms -- WRONG, needs to call something different, # saying it changes bond orders but not bonds themselves # (so e.g. sp chains update geom but don't get destroyed). # [As of 050725 I think it doesn't do either of those.] # WARNING: this might add new atoms to our argument dict, # changed_structure_atoms (and furthermore, we might depend on # the fact that it does, for doing valence checks on them!) #060306 update: as of long before now, it stores these bonds # in changed_bond_types. return # from update_bonds_after_each_event ##most_permissible_v6_first = ( V_SINGLE, V_DOUBLE, V_AROMATIC, V_GRAPHITE, ## V_TRIPLE, V_CARBOMERIC ) ## # not quite true for graphite? ## # review this -- all uses should be considered suspicious [050714 comment] ## # [this seems to be no longer used as of 071108...] def _best_corrected_v6(bond): """ This bond has an illegal v6 according to its bonded atomtypes (and I guess the atomtypes are what has just changed?? ###k -- [update 060629:] NOT ALWAYS -- it might be the bond order (and then the atomtypes), changed automatically by increase_valence_noupdate when the user bonds two bondpoints to increase order of existing bond, as in bug 1951). Say how we want to fix it (or perhaps fix the atomtypes?? #e [i doubt it, they might have just changed -- 060629]). """ # Given that the set of permissible bond types (for each atomtype, # ignoring S=S prohibition and special graphite rules) # is some prefix of [single, double, aromatic/graphite, triple, carbomeric], # I think it's ok to always take the last permissible element of that list # (using relaxed rules for graphite)... # no, it depends on prior bond (presumably one the user likes, or at least # consented to), # [note 060629 -- in bug 1951 the prior bond is carbomeric, but the user # never wanted it, they just wanted to increase aromatic # by 1, which numerically gets to carbomeric, but in that bug's example # it's not a legal type and they really want double. # So I will change the weird ordering of _corrected_v6_list[V_CARBOMERIC] # to a decreasing one, to fix that bug.] # but clearly we move to the left in that list. # Like this: c -> a, 3 -> max in list? or 2? # or depends on other bonds/valences? # ... we might return a list of legal btypes in order of preference, # for inference code (see paper notes) v6 = bond.v6 try: lis = _corrected_v6_list[v6] except KeyError: # this happens for illegal v6 values return V_SINGLE atype1 = bond.atom1.atomtype # fyi, see also possible_bond_types() for similar code atype2 = bond.atom2.atomtype for v6 in lis: if v6 == V_SINGLE or atype1.permits_v6(v6) and atype2.permits_v6(v6): return v6 print "bug: no legal replacement for v6 = %r in %r" % (bond.v6, bond) return V_SINGLE # map a now-illegal v6 to the list of replacements to try (legal ones only, # of course; in the order of preference given by the list) _corrected_v6_list = { V_DOUBLE: (V_SINGLE,), V_TRIPLE: (V_DOUBLE, V_SINGLE), V_AROMATIC: (V_SINGLE,), V_GRAPHITE: (V_AROMATIC, V_SINGLE), # note: this temporarily goes up, then down. ## V_CARBOMERIC: (V_AROMATIC, V_DOUBLE, V_SINGLE), # there was a reason # for this, but it caused bug 1951, so revising it [bruce 060629] V_CARBOMERIC: (V_DOUBLE, V_AROMATIC, V_SINGLE), # This monotonic decreasing order ought to fix bug 1951, # though ideally we might depend on the last bond type # specifically chosen by the user... but at least, fractional # bond orders never show up unless the user has one # somewhere on some other bond, so always including V_AROMATIC # in this list might be ok, even if the user never explicitly # chose V_CARBOMERIC. [bruce 060629] } # == def process_changed_bond_types( changed_bond_types): """ Tell whoever needs to know that some bond types changed. For now, that means only bond.pi_bond_obj objects on those very bonds. """ for bond in changed_bond_types.values(): #bruce 060405 precaution: itervalues -> values, due to calls of code # we don't control here obj = bond.pi_bond_obj if obj is not None: obj.changed_bond_type(bond) return # end
NanoCAD-master
cad/src/model_updater/bond_updater.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ master_model_updater.py - do the post-event (or pre-checkpoint) updates necessary for all of NE1's model types, in an appropriate order (which may involve recursively running some lower-level updates to completion after higher-level ones change things). See also: update_parts method @author: Bruce @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. TODO: Once the general structure stabilizes, refactor this so that the model-type- specific updaters can register themselves, rather than being hardcoded here as they are now. The unclear part of doing that is how the higher-level ones can recursively/ repeatedly run lower-level ones, given that they're all only in a partial order; and also, the general degree of interdependence in the rules for what gets in each changedict, which related fields are derived from other ones, etc. For now, this means all the updaters have to be co-developed and called (in a hardcoded way) by one master function, which is the one in this module. (But this master updater can and does register itself with env.register_post_event_model_updater, so the env function via which these get called can remain in the model-type-independent part of the core.) History: bruce 050627 started this as part of supporting higher-order bonds. bruce 071108 split this out of bond_updater.py, in preparation for adding DNA-specific code in other specific updater modules, for this to also call. bruce 080305 added _autodelete_empty_groups. """ from model.global_model_changedicts import changed_structure_atoms from model.global_model_changedicts import changed_bond_types from model.global_model_changedicts import LAST_RUN_DIDNT_HAPPEN from model.global_model_changedicts import LAST_RUN_IS_ONGOING from model.global_model_changedicts import LAST_RUN_FAILED from model.global_model_changedicts import LAST_RUN_SUCCEEDED import model.global_model_changedicts as global_model_changedicts # for setting flags in it import foundation.env as env from utilities.Log import redmsg from utilities.GlobalPreferences import dna_updater_is_enabled from utilities.debug import print_compact_stack, print_compact_traceback from model_updater.bond_updater import update_bonds_after_each_event from model_updater.bond_updater import process_changed_bond_types # == def _master_model_updater( warn_if_needed = False ): """ This should be called at the end of every user event which might have changed anything in any loaded model which defers some updates to this function. This can also be called at the beginning of user events, such as redraws or saves, which want to protect themselves from event-processors which should have called this at the end, but forgot to. Those callers should pass warn_if_needed = True, to cause a debug-only warning to be emitted if the call was necessary. (This function is designed to be very fast when called more times than necessary.) This should also be called before taking Undo checkpoints, to make sure they correspond to legal structures, and so this function's side effects (and the effect of assy.changed, done by this function as of 060126(?)) are treated as part of the same undoable operation as the changes that required them to be made. As of 060127 this is done by those checkpoints calling update_parts, which indirectly calls this function. In practice, as of 071115, we have not yet tried to put in calls to this function at the end of user event handlers, so we rely on the other calls mentioned above, and none of them pass warn_if_needed. """ # 0. Don't run while mmp file is being read [###FIX, use one global flag] if 1: # KLUGE; the changedicts and updater should really be per-assy... # this is a temporary scheme for detecting the unanticipated # running of this in the middle of loading an mmp file, and for # preventing errors from that, # but it only works for the main assy -- not e.g. for a partlib # assy. I don't yet know if this is needed. [bruce 080117] #update 080319: just in case, I'm fixing the mmpread code # to also use the global assy to store this. kluge_main_assy = env.mainwindow().assy if not kluge_main_assy.assy_valid: global_model_changedicts.status_of_last_dna_updater_run = LAST_RUN_DIDNT_HAPPEN msg = "deferring _master_model_updater(warn_if_needed = %r) " \ "since not %r.assy_valid" % (warn_if_needed, kluge_main_assy) print_compact_stack(msg + ": ") # soon change to print... return pass env.history.emit_all_deferred_summary_messages() #bruce 080212 (3 places) _run_dna_updater() env.history.emit_all_deferred_summary_messages() _run_bond_updater( warn_if_needed = warn_if_needed) env.history.emit_all_deferred_summary_messages() _autodelete_empty_groups(kluge_main_assy) env.history.emit_all_deferred_summary_messages() return # from _master_model_updater # == def _run_dna_updater(): #bruce 080210 split this out # TODO: check some dicts first, to optimize this call when not needed? # TODO: zap the temporary function calls here #bruce 080319 added sets of status_of_last_dna_updater_run if dna_updater_is_enabled(): # never implemented sufficiently: if ...: _reload_dna_updater() _ensure_ok_to_call_dna_updater() # soon will not be needed here from dna.updater.dna_updater_main import full_dna_update # soon will be toplevel import global_model_changedicts.status_of_last_dna_updater_run = LAST_RUN_IS_ONGOING try: full_dna_update() except: global_model_changedicts.status_of_last_dna_updater_run = LAST_RUN_FAILED msg = "\n*** exception in dna updater; will attempt to continue" print_compact_traceback(msg + ": ") msg2 = "Error: exception in dna updater (see console for details); will attempt to continue" env.history.message(redmsg(msg2)) else: global_model_changedicts.status_of_last_dna_updater_run = LAST_RUN_SUCCEEDED pass else: global_model_changedicts.status_of_last_dna_updater_run = LAST_RUN_DIDNT_HAPPEN return # == def _run_bond_updater(warn_if_needed = False): #bruce 080210 split this out if not (changed_structure_atoms or changed_bond_types): # Note: this will be generalized to: # if no changes of any kind, since the last call # Note: the dna updater processes changes in other dicts, # but we don't need to check those in this function. return # some changes occurred, so this function needed to be called # (even if they turn out to be trivial) if warn_if_needed and env.debug(): # whichever user event handler made these changes forgot to call # this function when it was done! # [as of 071115 warn_if_needed is never true; see docstring] print "atom_debug: _master_model_updater should have been called " \ "before this call (since the most recent model changes), " \ "but wasn't!" #e use print_compact_stack?? pass # (other than printing this, we handle unreported changes normally) # handle and clear all changes since the last call # (in the proper order, when there might be more than one kind of change) # Note: reloading this module won't work, the way this code is currently # structured. If reloading is needed, this routine needs to be # unregistered prior to the reload, and reregistered afterwards. # Also, note that the module might be reloading itself, so be careful. if changed_structure_atoms: update_bonds_after_each_event( changed_structure_atoms) #bruce 060315 revised following comments: # Note: this can modify changed_bond_types (from bond-inference, # if we implement that in the future, or from correcting # illegal bond types, in the present code). # SOMEDAY: I'm not sure if that routine will need to use or change # other similar globals in this module; if it does, passing just # that one might be a bit silly (so we could pass none, or all # affected ones) changed_structure_atoms.clear() if changed_bond_types: # WARNING: this dict may have been modified by the above loop # which processes changed_structure_atoms... process_changed_bond_types( changed_bond_types) # REVIEW: our interface to that function needs review if it can # recursively add bonds to this dict -- if so, it should .clear, # not us! changed_bond_types.clear() return # from _run_bond_updater # == def _autodelete_empty_groups(assy): #bruce 080305 """ Safely call currentCommand.autodelete_empty_groups( part.topnode) (if a debug_pref permits) for currentCommand and current part found via assy """ if debug_pref_autodelete_empty_groups(): try: part = assy.part currentCommand = assy.w.currentCommand if part: currentCommand.autodelete_empty_groups( part.topnode) except: msg = "\n*** exception in _autodelete_empty_groups; will attempt to continue" print_compact_traceback(msg + ": ") msg2 = "Error: exception in _autodelete_empty_groups (see console for details); will attempt to continue" env.history.message(redmsg(msg2)) pass pass return # == # temporary code for use while developing dna_updater def debug_pref_autodelete_empty_groups(): from utilities.debug_prefs import debug_pref, Choice_boolean_True, Choice_boolean_False res = debug_pref("autodelete empty Dna-related groups?", #bruce 080317 revised text ##Choice_boolean_False, #autodelete empty groups by default. This looks safe so far #and soon, we will make it mainstream (not just a debug #option) -- Ninad 2008-03-07 Choice_boolean_True, ## non_debug = True, #bruce 080317 disabled prefs_key = True ) return res _initialized_dna_updater_yet = False def _ensure_ok_to_call_dna_updater(): global _initialized_dna_updater_yet if not _initialized_dna_updater_yet: from dna.updater import dna_updater_init dna_updater_init.initialize() _initialized_dna_updater_yet = True return # == def initialize(): """ Register one or more related post_event_model_updaters (in the order in which they should run). These will be run by env.do_post_event_updates(). """ if dna_updater_is_enabled(): ## from dna_updater import dna_updater_init ## dna_updater_init.initialize() _ensure_ok_to_call_dna_updater() # TODO: replace with the commented out 2 lines above env.register_post_event_model_updater( _master_model_updater) return # end
NanoCAD-master
cad/src/model_updater/master_model_updater.py
NanoCAD-master
cad/src/model_updater/__init__.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """This addresses bug 1167, where if the BROWSER environment variable is not set, nE-1 may not be able to find the web browser to do wiki help. Let's see if we can resolve that issue without putting \"export BROWSER\" in the .bashrc or /etc/bashrc file. Originally observed this bug on Linux. Try to write a fix that works on any platform. Remember to type \"export BROWSER=\" before running this script, otherwise if your bashrc file defines BROWSER, you'll get a successful result for the wrong reason. """ import webbrowser def register(pathname, key): webbrowser._tryorder += [ key ] webbrowser.register(key, None, webbrowser.GenericBrowser("%s '%%s'" % pathname)) # In order of decreasing desirability. Browser names for different # platforms can be mixed in this list. Where a browser is not # normally found on the system path (like IE on Windows), give its # full pathname. for candidate in [ 'firefox', 'safari', 'opera', 'netscape', 'konqueror', 'c:/Program Files/Internet Explorer/iexplore.exe' ]: import os.path if os.path.exists(candidate): # some candidateidates might have full pathnames register(candidate, candidate) continue for dir in os.environ['PATH'].split(':'): pathname = os.path.join(dir, candidate) if os.path.exists(pathname): register(pathname, candidate) continue webbrowser.open("http://willware.net:8080")
NanoCAD-master
cad/src/experimental/browserHack.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PreferencesDialog.ui' # # Created: Wed Aug 27 16:00:53 2008 # by: PyQt4 UI code generator 4.3.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_PreferencesDialog(object): def setupUi(self, PreferencesDialog): PreferencesDialog.setObjectName("PreferencesDialog") PreferencesDialog.resize(QtCore.QSize(QtCore.QRect(0,0,594,574).size()).expandedTo(PreferencesDialog.minimumSizeHint())) self.vboxlayout = QtGui.QVBoxLayout(PreferencesDialog) self.vboxlayout.setSpacing(4) self.vboxlayout.setMargin(2) self.vboxlayout.setObjectName("vboxlayout") self.tabWidget = QtGui.QTabWidget(PreferencesDialog) self.tabWidget.setObjectName("tabWidget") self.tab = QtGui.QWidget() self.tab.setObjectName("tab") # self.hboxlayout = QtGui.QHBoxLayout(self.tab) self.pref_splitter = QtGui.QSplitter(self.tab) # self.hboxlayout.setSpacing(4) # self.hboxlayout.setMargin(2) # self.hboxlayout.setObjectName("hboxlayout") self.pref_splitter.setObjectName("pref_splitter") self.categoriesTreeWidget = QtGui.QTreeWidget(self.pref_splitter) self.categoriesTreeWidget.setMinimumWidth(100) # self.categoriesTreeWidget.setMaximumWidth(250) self.categoriesTreeWidget.setObjectName("categoriesTreeWidget") # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # self.categoriesTreeWidget.setSizePolicy(sizePolicy) # self.hboxlayout.addWidget(self.categoriesTreeWidget) self.pref_splitter.addWidget(self.categoriesTreeWidget) self.prefsStackedWidget = QtGui.QStackedWidget(self.pref_splitter) # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # self.prefsStackedWidget.setSizePolicy(sizePolicy) self.prefsStackedWidget.setObjectName("prefsStackedWidget") # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # self.pref_splitter.setSizePolicy(sizePolicy) self.pref_splitter.addWidget(self.prefsStackedWidget) self.tabWidget.addTab(self.tab,"") self.vboxlayout.addWidget(self.tabWidget) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setObjectName("hboxlayout1") self.whatsThisToolButton = QtGui.QToolButton(PreferencesDialog) self.whatsThisToolButton.setObjectName("whatsThisToolButton") self.hboxlayout1.addWidget(self.whatsThisToolButton) spacerItem = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem) self.okButton = QtGui.QPushButton(PreferencesDialog) self.okButton.setObjectName("okButton") self.hboxlayout1.addWidget(self.okButton) self.vboxlayout.addLayout(self.hboxlayout1) self.retranslateUi(PreferencesDialog) self.tabWidget.setCurrentIndex(0) self.prefsStackedWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(PreferencesDialog) def retranslateUi(self, PreferencesDialog): PreferencesDialog.setWindowTitle(QtGui.QApplication.translate("PreferencesDialog", "Preferences", None, QtGui.QApplication.UnicodeUTF8)) self.categoriesTreeWidget.headerItem().setText(0,QtGui.QApplication.translate("PreferencesDialog", "Categories", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("PreferencesDialog", "System Options", None, QtGui.QApplication.UnicodeUTF8)) self.okButton.setText(QtGui.QApplication.translate("PreferencesDialog", "OK", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/experimental/prefs/Ui_PreferencesDialog.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ WhatsThisText_for_PreferencesDialog.py This file provides functions for setting the "What's This" and tooltip text for widgets in the NE1 Preferences dialog only. Edit WhatsThisText_for_MainWindow.py to set "What's This" and tooltip text for widgets in the Main Window. @version: $Id: WhatsThisText_for_PreferencesDialog.py 13141 2008-06-06 19:06:39Z ninadsathaye $ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ PLUGIN_TEXT = { "MegaPOV": { "checkbox" : """<p>This enables MegaPOV as a plug-in. MegaPOV is a free addon raytracing program available from http://megapov.inetart.net/. Both MegaPOV and POV-Ray must be installed on your computer before you can enable the MegaPOV plug-in. MegaPOV allows rendering to happen silently on Windows (i.e. no POV_Ray GUI is displayed while rendering).</p>""", "chooser" : """The full path to the MegaPOV executable file (megapov.exe).""", "button" : """Allows you to choose the path to the MegaPOV executable.""" }, "POV include dir": { "checkbox" : """<p>Specify a directory for where to find POV-Ray or MegaPOV include files such as transforms.inc.</p>""", "chooser" : """<p>Specify a directory for where to find POV-Ray or MegaPOV include files such as transforms.inc.</p>""", "button" : """Allows you to choose the path to the include directory.""" }, "Rosetta": { "checkbox" : """This enables the use of Rosetta as a plug-in.""", "chooser" : """The full path to the Rosetta executable file.""", "button" : """Allows you to choose the path to the Rosetta executable.""" }, "Rosetta DB": { "checkbox" : """This enables the selection of the path to the Rosetta Database.""", "chooser" : """The full path to the Rosetta Database.""", "button" : """Allows you to choose the path to the Rosetta Database.""" }, "QuteMolX" : { "checkbox" : """<p>This enables QuteMolX as a plug-in. QuteMolX is available for download from http://nanoengineer-1.com/QuteMolX. QuteMolX must be installed on your computer before you can enable this plug-in.</p>""", "chooser" : """The full path to the QuteMolX executable.""", "button" : """Allows you to choose the path to the QuteMolX executable.""" }, "GROMACS" : { "checkbox" : """<p>This enables GROMACS as a plug-in. GROMACS is a free rendering program available from http://www.gromacs.org/. GROMACS must be installed on your computer before you can enable the GROMACS plug-in. Check this and choose the the path to the mdrun executable from your GROMACS distribution.</p>""", "chooser" : """The full path to the mdrun executable file for GROMACS.""", "button" : """<p>This opens up a file chooser dialog so that you can specify the location of the GROMACS executable (mdrun).</p>""" }, "cpp" : { "checkbox" : """This enables selecting the C-preprocessor that GROMACS will use""", "chooser" : """<p>The full path to the C-preprocessor (cpp) executable file for GROMACS to use.</p>""", "button" : """<p>Allows you to choose the path to the C-preprocessor (cpp) executable file for GROMACS to use.</p>""" }, "POV-Ray" : { "checkbox" : """<p>This enables POV-Ray as a plug-in. POV-Ray is a free raytracing program available from http://www.povray.org/. POV-Ray must be installed on your computer before you can enable the POV-Ray plug-in. </p>""", "chooser" : """The full path to the POV-Ray executable.""", "button" : """Allows you to choose the path to the POV-Ray executable.""" } } import sys def whatsThis_PreferencesDialog(preferencesDialog): """ Assigning the I{What's This} text for the Preferences dialog. """ _pd = preferencesDialog setWhatsThis_General(_pd) setWhatsThis_Graphics_Area(_pd) setWhatsThis_Zoom_Pan_and_Rotate(_pd) setWhatsThis_Rulers(_pd) setWhatsThis_Atoms(_pd) setWhatsThis_Bonds(_pd) setWhatsThis_DNA(_pd) setWhatsThis_Minor_groove_error_indicator(_pd) # setWhatsThis_Base_orientation_indicator(_pd) setWhatsThis_Adjust(_pd) setWhatsThis_Plugins(_pd) setWhatsThis_Undo(_pd) setWhatsThis_Window(_pd) #setWhatsThis_Reports(_pd) #setWhatsThis_Tooltips(_pd) return def setWhatsThis_General(pd): if sys.platform == 'darwin': _keyString = "<b>(Cmd + C and Cmd + V)</b> respectively" else: _keyString = "<b>(Ctrl + C and Ctrl + V)</b> respectively" pd.logo_download_RadioButtonList.setWhatsThis( """<p><b>Always ask before downloading</b></p> <p> When sponsor logos have been updated, ask permission to download them. </p> <p><b>Never ask before downloading</b></p> <p> When sponsor logos have been updated, download them without asking permission to do so. </p> <p><b>Never download</b></p> <p> Don't ask permission to download sponsor logos and don't download them. </p>""") pd.autobondCheckBox.setWhatsThis("""<p>Default setting for <b>Autobonding</b> at startup (enabled/disabled)</p>""") pd.hoverHighlightCheckBox.setWhatsThis("""<p>Default setting for <b>Hover highlighting</b> at startup (enabled/disabled)</p>""") pd.waterCheckBox.setWhatsThis("""<p>Default setting for <b>Water (surface)</b> at startup (enabled/disabled)</p>""") pd.autoSelectAtomsCheckBox.setWhatsThis("""<b>Auto select atoms of deposited object</b> <p> When depositing atoms, clipboard chunks or library parts, their atoms will automatically be selected.""") _text = """<b>Offset scale factor for pasting chunks</b> <p>When one or more chunks, that are placed as independent nodes in the Model Tree, are copied and then pasted using the modifier keys %s, this scale factor determines the offset of the pasted chunks from the original chunks. Note that if the copied selection includes any DNA objects such as DNA segments, strands etc, the program will use an offset scale that is used for pasting the DNA objects instead of this offset scale) </p>"""%(_keyString) pd.pasteOffsetForChunks_doublespinbox.setWhatsThis(_text) pd.pasteOffsetForChunks_doublespinbox.labelWidget.setWhatsThis(_text) _text = """<b>Offset scale factor for pasting Dna objects</b> <p>When one or more DNA objects such as DNA segments, strands etc, are copied and then pasted using the modifier keys %s, this scale factor determines the offset of the pasted DNA objects from the original ones. Note that this also applies to pasting chunks within a group in the Model Tree. </p>"""%(_keyString) pd.pasteOffsetForDNA_doublespinbox.setWhatsThis(_text) pd.pasteOffsetForDNA_doublespinbox.labelWidget.setWhatsThis(_text) return def setWhatsThis_Graphics_Area(pd): pd.globalDisplayStyleStartupComboBox.setWhatsThis( """Changes the appearance of any objects in the work place.""") pd.display_compass_CheckBox.setWhatsThis("""<p><b>Display compass</b></p> <p> Shows/Hides the display compass""") _text = """Changes the location of the display compass.""" pd.compass_location_ComboBox.setWhatsThis(_text) pd.compass_location_ComboBox.labelWidget.setWhatsThis(_text) pd.display_compass_labels_checkbox.setWhatsThis( """Shows/Hides the display compass axis labels.""") pd.display_origin_axis_checkbox.setWhatsThis("""<p><b>Display origin axis</b></p> <p> Shows/Hides the origin axis""") pd.display_pov_axis_checkbox.setWhatsThis("""<p><b>Display point of view axis</b></p> <p> Shows/Hides the point of view axis""") pd.cursor_text_font_size_SpinBox.setWhatsThis("""Sets the font size for the standard cursor text.""") pd.cursor_text_reset_Button.setWhatsThis( """Resets the cursor text font size to the default value.""") _text = """Sets the color of the cursor text.""" pd.cursor_text_color_ComboBox.setWhatsThis(_text) pd.cursor_text_color_ComboBox.labelWidget.setWhatsThis(_text) pd.display_confirmation_corner_CheckBox.setWhatsThis( """Enables/Disables the display of the "Confirmation Corner" within the draw window""") pd.anti_aliasing_CheckBox.setWhatsThis( """Enables/Disables anti-aliased text. <p>This will not be in effect until the next session.</p>""") return def setWhatsThis_Zoom_Pan_and_Rotate(pd): pd.animate_views_CheckBox.setWhatsThis("""<p><b>Animate between views</b></p> <p> Enables/disables animation when switching between the current view and a new view. </p>""") pd.view_animation_speed_Slider.setWhatsThis("""<p><b>View animation speed</b></p> <p> Sets the animation speed when animating between views (i.e. Front view to Right view). It is recommended that this be set to Fast when working on large models. </p>""") pd.view_animation_speed_reset_ToolButton.setWhatsThis( """Resets the animation speed to the default value.""") pd.mouse_rotation_speed_Slider.setWhatsThis("""<p><b>Mouse rotation speed</b></p> <p> Specifies the speed factor to use when rotating the view by dragging the mouse (i.e. during the <b>Rotate</b> command or when using the middle mouse button). </p>""") pd.mouse_rotation_speed_reset_ToolButton.setWhatsThis( """Resets the mouse rotation speed to the default value.""") _text = """Sets the zoom direction for the mouse scroll wheel""" pd.zoom_directon_ComboBox.setWhatsThis(_text) pd.zoom_directon_ComboBox.labelWidget.setWhatsThis(_text) _text = """Sets where the image centers on when zooming in.""" pd.zoom_in_center_ComboBox.setWhatsThis(_text) pd.zoom_in_center_ComboBox.labelWidget.setWhatsThis(_text) _text = """Sets where the image centers on when zooming out.""" pd.zoom_out_center_ComboBox.setWhatsThis(_text) pd.zoom_out_center_ComboBox.labelWidget.setWhatsThis(_text) _text = """<p>Sets the length of time that the mouse will "hover" over an object before highlighting it.</p>""" pd.hover_highlighting_timeout_SpinBox.setWhatsThis(_text) pd.hover_highlighting_timeout_SpinBox.labelWidget.setWhatsThis(_text) return def setWhatsThis_Rulers(pd): _text = """This determines which rulers to display""" pd.display_rulers_ComboBox.setWhatsThis(_text) pd.display_rulers_ComboBox.labelWidget.setWhatsThis(_text) _text = """<p>This determines which corner of the draw area the rulers will use as their origin.</p>""" pd.origin_rulers_ComboBox.setWhatsThis(_text) pd.origin_rulers_ComboBox.labelWidget.setWhatsThis(_text) _text = """Determines the background color or the displayed rulers.""" pd.ruler_color_ColorComboBox.setWhatsThis(_text) pd.ruler_color_ColorComboBox.labelWidget.setWhatsThis(_text) _text = """Determines how opaque the rulers will look.""" pd.ruler_opacity_SpinBox.setWhatsThis(_text) pd.ruler_opacity_SpinBox.labelWidget.setWhatsThis(_text) pd.show_rulers_in_perspective_view_CheckBox.setWhatsThis( """Enables/Disables the rulers when using the perspective view.""") return def setWhatsThis_Atoms(pd): pd.change_element_colors_PushButton.setWhatsThis( """<p>This brings up another dialog which allows the user to change the colors that each of the avaliable atoms is drawn in.</p>""") #_text = """Sets the color used when highlighting atoms.""" #pd.atom_highlighting_ColorComboBox.setWhatsThis(_text) #pd.atom_highlighting_ColorComboBox.labelWidget.setWhatsThis(_text) #_text = """Sets the color used when hightlighting bondpoints.""" #pd.bondpoint_highlighting_ColorComboBox.setWhatsThis(_text) #pd.bondpoint_highlighting_ColorComboBox.labelWidget.setWhatsThis(_text) #_text = """Sets the color used when highlighting bondpoint highlights""" #pd.bondpoint_hotspots_ColorComboBox.setWhatsThis(_text) #pd.bondpoint_hotspots_ColorComboBox.labelWidget.setWhatsThis(_text) pd.restore_element_colors_PushButton.setWhatsThis( """<p>Restores the atom and bondpoint hightlighting colors to their default colors.</p>""") _text = \ """<p><b>Level of detail</b></p> <p> Sets the level of detail for atoms and bonds.<br> <br> <b>High</b> = Best graphics quality (slowest rendering speed)<br> <b>Medium</b> = Good graphics quality<br> <b>Low</b> = Poor graphics quality (fastest rendering speed) <br> <b>Variable</b> automatically switches between High, Medium and Low based on the model size (number of atoms). </p>""" pd.atoms_detail_level_ComboBox.setWhatsThis(_text) pd.atoms_detail_level_ComboBox.labelWidget.setWhatsThis(_text) _text = """<p><b>Ball and stick atom scale</b></p> <p> Sets the ball and stick atom scale factor. It is best to change the scale factor while the current model is displayed in ball and stick mode.""" pd.ball_and_stick_atom_scale_SpinBox.setWhatsThis(_text) pd.ball_and_stick_atom_scale_reset_ToolButton.setWhatsThis( """<p>Sets the ball and stick atom scale factor back to its default value</p>""") pd.CPK_atom_scale_doubleSpinBox.setWhatsThis( """<p><b>CPK atom scale</b></p> <p> Changes the CPK atom scale factor. It is best to change the scale factor while in CPK display mode so you can see the graphical effect of changing the scale.""") pd.CPK_atom_scale_reset_ToolButton.setWhatsThis( """<p>Sets the CPK atom scale factor back to its default value</p>""") #pd.overlapping_atom_indicators_CheckBox.setWhatsThis(""" """) #pd.force_to_keep_bonds_during_transmute_CheckBox.setWhatsThis(""" """) return def setWhatsThis_Bonds(pd): #pd.bond_highlighting_ColorComboBox.setWhatsThis(""" """) #pd.ball_and_stick_cylinder_ColorComboBox.setWhatsThis(""" """) #pd.bond_stretch_ColorComboBox.setWhatsThis(""" """) #pd.vane_ribbon_ColorComboBox.setWhatsThis(""" """) pd.restore_bond_colors_PushButton.setWhatsThis( """<p>Restores the colors used for bond functions to their default values.</p>""") _text = \ """<p><b>Ball and stick bond scale</b></p> <p> Set scale (size) factor for the cylinder representing bonds in ball and stick display mode""" pd.ball_and_stick_bond_scale_SpinBox.setWhatsThis(_text) pd.ball_and_stick_bond_scale_SpinBox.labelWidget.setWhatsThis(_text) _text = \ "<b>Bond line thickness</b>"\ "<p>"\ "Sets the line thickness to <i>n</i> pixels wheneven bonds "\ "are rendered as lines (i.e. when the global display style is set to "\ "<b>Lines</b> display style)."\ "</p>" pd.bond_line_thickness_SpinBox.setWhatsThis(_text) pd.bond_line_thickness_SpinBox.labelWidget.setWhatsThis(_text) _text = """<p><b>Multiple cylinders</b></p> <p> <p><b>High order bonds</b> are displayed using <b>multiple cylinders.</b></p> <p> <b>Double bonds</b> are drawn with two cylinders.<br> <b>Triple bonds</b> are drawn with three cylinders.<br> <b>Aromatic bonds</b> are drawn as a single cylinder with a short green cylinder in the middle. <p><b>Vanes</b></p> <p> <p><i>High order bonds</i> are displayed using <b>Vanes.</b></p> <p> <p>Vanes represent <i>pi systems</i> in high order bonds and are rendered as rectangular polygons. The orientation of the vanes approximates the orientation of the pi system(s).</p> <p>Create an acetylene or ethene molecule and select this option to see how vanes are rendered. </p> <p><b>Ribbons</b></p> <p> <p><i>High order bonds</i> are displayed using <b>Ribbons.</b></p> <p> <p>Ribbons represent <i>pi systems</i> in high order bonds and are rendered as ribbons. The orientation of the ribbons approximates the orientation of the pi system.</p> <p>Create an acetylene or ethene molecule and select this option to see how ribbons are rendered. </p>""" pd.high_order_bonds_RadioButtonList.setWhatsThis(_text) pd.show_bond_type_letters_CheckBox.setWhatsThis( """<p><b>Show bond type letters</b></p> <p> <p>Shows/Hides bond type letters (labels) on top of bonds.</p> <u>Bond type letters:</u><br> <b>2</b> = Double bond<br> <b>3</b> = Triple bond<br> <b>A</b> = Aromatic bond<br> <b>G</b> = Graphitic bond<br>""") pd.show_valence_errors_CheckBox.setWhatsThis( """<p><b>Show valence errors</b></p> <p> Enables/Disables valence error checker.</p> When enabled, atoms with valence errors are displayed with a pink wireframe sphere. This indicates that one or more of the atom's bonds are not of the correct order (type), or that the atom has the wrong number of bonds, or (for PAM DNA pseudoatoms) that there is some error in bond directions or in which PAM elements are bonded. The error details can be seen in the tooltip for the atom.""") pd.show_bond_stretch_indicators_CheckBox.setWhatsThis( """Enables/Disables the display of bond stretch indicators""") return def setWhatsThis_DNA(pd): # pd.conformation_ComboBox.setWhatsThis(""" """) # pd.bases_per_turn_DoubleSpinBox.setWhatsThis(""" """) # pd.rise_DoubleSpinBox.setWhatsThis(""" """) # pd.strand1_ColorComboBox.setWhatsThis(""" """) # pd.strand2_ColorComboBox.setWhatsThis(""" """) # pd.segment_ColorComboBox.setWhatsThis(""" """) pd.restore_DNA_colors_PushButton.setWhatsThis( """<p>Restores the default colors for strand 1, strand 2, and segments of DNA.</p>""") # pd.show_arrows_on_backbones_CheckBox.setWhatsThis(""" """) # pd.show_arrows_on_3prime_ends_CheckBox.setWhatsThis(""" """) # pd.show_arrows_on_5prime_ends_CheckBox.setWhatsThis(""" """) # pd.three_prime_end_custom_ColorComboBox.setWhatsThis(""" """) # pd.five_prime_end_custom_ColorComboBox.setWhatsThis(""" """) return def setWhatsThis_Minor_groove_error_indicator(pd): # pd.minor_groove_error_indicatiors_CheckBox.setWhatsThis(""" """) # pd.minor_groove_error_minimum_angle_SpinBox.setWhatsThis(""" """) # pd.minor_groove_error_maximum_angle_SpinBox.setWhatsThis(""" """) # pd.minor_groove_error_color_ColorComboBox.setWhatsThis(""" """) pd.minor_groove_error_reset_PushButton.setWhatsThis( """<p>Resets all minor groove error indicator settings to their default values.</p>""") return def setWhatsThis_Base_orientation_indicator(pd): # pd.base_orientation_indicatiors_CheckBox.setWhatsThis(""" """) # pd.plane_normal_ComboBox.setWhatsThis(""" """) # pd.indicators_color_ColorComboBox.setWhatsThis(""" """) # pd.inverse_indicators_color_ColorComboBox.setWhatsThis(""" """) # pd.enable_inverse_indicatiors_CheckBox.setWhatsThis(""" """) # pd.angle_threshold_DoubleSpinBox.setWhatsThis(""" """) # pd.terminal_base_distance_SpinBox.setWhatsThis(""" """) return def setWhatsThis_Adjust(pd): pd.physics_engine_choice_ComboBox.setWhatsThis( """This selects which physics engine to use as the default.""") #pd.enable_electrostatics_CheckBox.setWhatsThis(""" """) pd.watch_motion_in_realtime_CheckBox.setWhatsThis("""<p><b>Watch motion in real time</b></p> <p> <p>Enables/disables realtime graphical updates during adjust operations when using <b>Adjust All</b> or <b>Adjust Selection</b></p>""") #pd.animation_detail_level_RadioButtonList.setWhatsThis(""" """) pd.constant_animation_update_RadioButton.setWhatsThis( """<b>Update as fast as possible</b> <p> Update every 2 seconds, or faster (up to 20x/sec)if it doesn't slow adjustments by more than 20% </p>""") pd.update_every_RadioButton.setWhatsThis("""<b>Update every <i>n units.</u></b> <p> Specify how often to update the model during the adjustment. This allows the user to monitor results during adjustments. </p>""") pd.update_rate_SpinBox.setWhatsThis("""<b>Update every <i>n units.</u></b> <p> Specify how often to update the model during the adjustment. This allows the user to monitor results during adjustments. </p>""") # pd.animation_detail_level_ComboBox.setWhatsThis(""" """) pd.endRMS_DoubleSpinBox.setWhatsThis("""<b>EndRMS</b> <p> Continue until this RMS force is reached. </p>""") pd.endmax_DoubleSpinBox.setWhatsThis("""<b>EndMax</b> <p> Continue until no interaction exceeds this force. </p>""") pd.cutoverRMS_DoubleSpinBox.setWhatsThis("""<b>CutoverRMS</b> <p> Use steepest descent until this RMS force is reached. </p>""") pd.cutoverMax_DoubleSpinBox.setWhatsThis("""<b>CutoverMax</b> <p>Use steepest descent until no interaction exceeds this force. </p>""") return def setWhatsThis_Plugins(pd): for plugin in PLUGIN_TEXT: pd.checkboxes[plugin].setWhatsThis(PLUGIN_TEXT[plugin]["checkbox"]) pd.choosers[plugin].lineEdit.setWhatsThis( PLUGIN_TEXT[plugin]["chooser"]) pd.choosers[plugin].browseButton.setWhatsThis( PLUGIN_TEXT[plugin]["button"]) return def setWhatsThis_Undo(pd): pd.undo_restore_view_CheckBox.setWhatsThis( """<p><b>Restore view when undoing structural changes</b></p> <p> <p>When checked, the current view is stored along with each <b><i>structural change</i></b> on the undo stack. The view is then restored when the user undoes a structural change.</p> <p><b><i>Structural changes</i></b> include any operation that modifies the model. Examples include adding, deleting or moving an atom, chunk or jig. </p> <p>Selection (picking/unpicking) and view changes are examples of operations that do not modify the model (i.e. are not structural changes). </p>""") pd.undo_automatic_checkpoints_CheckBox.setWhatsThis( """<p><b>Automatic checkpoints</b></p> <p> Specifies whether <b>automatic checkpointing</b> is enabled/disabled during program startup only. It does not enable/disable <b>automatic checkpointing</b> when the program is running. <p><b>Automatic checkpointing</b> can be enabled/disabled by the user at any time from <b>Edit > Automatic checkpointing</b>. When enabled, the program maintains the undo stack automatically. When disabled, the user is required to manually set undo checkpoints using the <b>set checkpoint</b> button in the Edit Toolbar/Menu.</p> <p><b>Automatic checkpointing</b> can impact program performance. By disabling automatic checkpointing, the program will run faster.</p> <p><b><i>Remember to you must set your own undo checkpoints manually when automatic checkpointing is disabled.</i></b></p> <p>""") _text = """<p><b>Undo stack memory limit</b></p> <p>This is the maximum amount of system memory that will be assigned to handle the <b>undo stack</b>.</p>""" pd.undo_stack_memory_limit_SpinBox.setWhatsThis(_text) pd.undo_stack_memory_limit_SpinBox.labelWidget.setWhatsThis(_text) return def setWhatsThis_Window(pd): #pd.current_width_SpinBox.setWhatsThis(""" """) #pd.current_height_SpinBox.setWhatsThis(""" """) pd.current_size_save_Button.setWhatsThis( """<p>Saves the main window's current position and size for the next time the program starts.</p>""") pd.restore_saved_size_Button.setWhatsThis( """<p>Restores the main window's current position from the last time the program was closed</p>""") #pd.saved_size_label.setWhatsThis(""" """) #pd.save_size_on_quit_CheckBox.setWhatsThis(""" """) _text = """<p>Format prefix and suffix text the delimits the part name in the caption in window border.</p>""" pd.caption_prefix_LineEdit.setWhatsThis(_text) pd.caption_suffix_LineEdit.setWhatsThis(_text) # pd.caption_prefix_LineEdit.labelWidget.setWhatsThis(_text) # pd.caption_suffix_LineEdit.labelWidget.setWhatsThis(_text) pd.display_full_path_CheckBox.setWhatsThis(_text) pd.caption_prefix_save_ToolButton.setWhatsThis( """Saves the current caption prefix.""") pd.caption_suffix_save_ToolButton.setWhatsThis( """Saves the current caption suffix.""") #pd.use_custom_font_CheckBox.setWhatsThis(""" """) #pd.custom_fontComboBox.setWhatsThis(""" """) #pd.custom_font_size_SpinBox.setWhatsThis(""" """) #pd.make_default_font_PushButton.setWhatsThis(""" """) return def setWhatsThis_Reports(pd): # pd.history_include_message_serial_CheckBox.setWhatsThis(""" """) # pd.history_include_message_timestamp_CheckBox.setWhatsThis(""" """) return def setWhatsThis_Tooltips(pd): # pd.atom_chunk_information_CheckBox.setWhatsThis(""" """) # pd.atom_mass_information_CheckBox.setWhatsThis(""" """) # pd.atom_XYZ_coordinates_CheckBox.setWhatsThis(""" """) # pd.atom_XYZ_distance_CheckBox.setWhatsThis(""" """) # pd.atom_include_vdw_CheckBox.setWhatsThis(""" """) # pd.atom_distance_precision_SpinBox.setWhatsThis(""" """) # pd.atom_angle_precision_SpinBox.setWhatsThis(""" """) # pd.bond_distance_between_atoms_CheckBox.setWhatsThis(""" """) # pd.bond_chunk_information_CheckBox.setWhatsThis(""" """) return
NanoCAD-master
cad/src/experimental/prefs/WhatsThisText_for_PreferencesDialog.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ Preferences.py @author: Mark @version: $Id: Preferences.py 14197 2008-09-11 04:52:29Z brucesmith $ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. History: -Mark 2008-05-20: Created by Mark from a copy of UserPrefs.py """ import os, sys from PyQt4 import QtCore, QtGui from PyQt4.Qt import QDialog from PyQt4.Qt import QFileDialog from PyQt4.Qt import QMessageBox from PyQt4.Qt import QButtonGroup from PyQt4.Qt import QAbstractButton from PyQt4.Qt import QDoubleValidator from PyQt4.Qt import SIGNAL from PyQt4.Qt import QPalette from PyQt4.Qt import QColorDialog from PyQt4.Qt import QString from PyQt4.Qt import QFont from PyQt4.Qt import Qt from PyQt4.Qt import QWhatsThis from PyQt4.Qt import QTreeWidget from PyQt4.Qt import QSize import string from PreferencesDialog import PreferencesDialog import foundation.preferences as preferences from utilities.debug import print_compact_traceback from utilities.debug_prefs import debug_pref, Choice_boolean_False import foundation.env as env from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf from widgets.widget_helpers import double_fixup from widgets.prefs_widgets import connect_colorpref_to_colorframe, \ connect_checkbox_with_boolean_pref, connect_comboBox_with_pref, \ connect_doubleSpinBox_with_pref, connect_spinBox_with_pref from utilities import debug_flags from utilities.constants import str_or_unicode from platform_dependent.PlatformDependent import screen_pos_size from platform_dependent.PlatformDependent import get_rootdir from platform_dependent.Paths import get_default_plugin_path from utilities.icon_utilities import geticon from utilities.prefs_constants import displayCompass_prefs_key from utilities.prefs_constants import displayCompassLabels_prefs_key from utilities.prefs_constants import displayPOVAxis_prefs_key from utilities.prefs_constants import displayConfirmationCorner_prefs_key from utilities.prefs_constants import enableAntiAliasing_prefs_key from utilities.prefs_constants import animateStandardViews_prefs_key from utilities.prefs_constants import displayVertRuler_prefs_key from utilities.prefs_constants import displayHorzRuler_prefs_key from utilities.prefs_constants import rulerPosition_prefs_key from utilities.prefs_constants import rulerColor_prefs_key from utilities.prefs_constants import rulerOpacity_prefs_key from utilities.prefs_constants import showRulersInPerspectiveView_prefs_key from utilities.prefs_constants import Adjust_watchRealtimeMinimization_prefs_key from utilities.prefs_constants import Adjust_minimizationEngine_prefs_key from utilities.prefs_constants import electrostaticsForDnaDuringAdjust_prefs_key from utilities.prefs_constants import Adjust_cutoverRMS_prefs_key from utilities.prefs_constants import qutemol_enabled_prefs_key from utilities.prefs_constants import qutemol_path_prefs_key from utilities.prefs_constants import nanohive_enabled_prefs_key from utilities.prefs_constants import nanohive_path_prefs_key from utilities.prefs_constants import povray_enabled_prefs_key from utilities.prefs_constants import povray_path_prefs_key from utilities.prefs_constants import megapov_enabled_prefs_key from utilities.prefs_constants import megapov_path_prefs_key from utilities.prefs_constants import povdir_enabled_prefs_key from utilities.prefs_constants import gamess_enabled_prefs_key from utilities.prefs_constants import gmspath_prefs_key from utilities.prefs_constants import gromacs_enabled_prefs_key from utilities.prefs_constants import gromacs_path_prefs_key from utilities.prefs_constants import cpp_enabled_prefs_key from utilities.prefs_constants import cpp_path_prefs_key from utilities.prefs_constants import rosetta_enabled_prefs_key from utilities.prefs_constants import rosetta_path_prefs_key from utilities.prefs_constants import rosetta_database_enabled_prefs_key from utilities.prefs_constants import rosetta_dbdir_prefs_key from utilities.prefs_constants import nv1_enabled_prefs_key from utilities.prefs_constants import nv1_path_prefs_key from utilities.prefs_constants import startupGlobalDisplayStyle_prefs_key from utilities.prefs_constants import buildModeAutobondEnabled_prefs_key from utilities.prefs_constants import buildModeWaterEnabled_prefs_key from utilities.prefs_constants import buildModeHighlightingEnabled_prefs_key from utilities.prefs_constants import buildModeSelectAtomsOfDepositedObjEnabled_prefs_key from utilities.prefs_constants import light1Color_prefs_key from utilities.prefs_constants import light2Color_prefs_key from utilities.prefs_constants import light3Color_prefs_key from utilities.prefs_constants import atomHighlightColor_prefs_key from utilities.prefs_constants import bondpointHighlightColor_prefs_key from utilities.prefs_constants import levelOfDetail_prefs_key from utilities.prefs_constants import diBALL_AtomRadius_prefs_key from utilities.prefs_constants import cpkScaleFactor_prefs_key from utilities.prefs_constants import showBondStretchIndicators_prefs_key from utilities.prefs_constants import showValenceErrors_prefs_key #General page prefs - paste offset scale for chunk and dna pasting prefs key from utilities.prefs_constants import pasteOffsetScaleFactorForChunks_prefs_key from utilities.prefs_constants import pasteOffsetScaleFactorForDnaObjects_prefs_key # Color (page) prefs from utilities.prefs_constants import backgroundColor_prefs_key from utilities.prefs_constants import backgroundGradient_prefs_key from utilities.prefs_constants import hoverHighlightingColorStyle_prefs_key from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColorStyle_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import haloWidth_prefs_key # Mouse wheel prefs from utilities.prefs_constants import mouseWheelDirection_prefs_key from utilities.prefs_constants import zoomInAboutScreenCenter_prefs_key from utilities.prefs_constants import zoomOutAboutScreenCenter_prefs_key from utilities.prefs_constants import mouseWheelTimeoutInterval_prefs_key # DNA prefs from utilities.prefs_constants import bdnaBasesPerTurn_prefs_key from utilities.prefs_constants import bdnaRise_prefs_key from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key from utilities.prefs_constants import dnaDefaultSegmentColor_prefs_key from utilities.prefs_constants import dnaStrutScaleFactor_prefs_key from utilities.prefs_constants import arrowsOnBackBones_prefs_key from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandFivePrimeArrowheadsCustomColor_prefs_key # DNA Minor Groove Error Indicator prefs from utilities.prefs_constants import dnaDisplayMinorGrooveErrorIndicators_prefs_key from utilities.prefs_constants import dnaMinMinorGrooveAngle_prefs_key from utilities.prefs_constants import dnaMaxMinorGrooveAngle_prefs_key from utilities.prefs_constants import dnaMinorGrooveErrorIndicatorColor_prefs_key # DNA style prefs 080310 piotr from utilities.prefs_constants import dnaStyleStrandsShape_prefs_key from utilities.prefs_constants import dnaStyleStrandsColor_prefs_key from utilities.prefs_constants import dnaStyleStrandsScale_prefs_key from utilities.prefs_constants import dnaStyleStrandsArrows_prefs_key from utilities.prefs_constants import dnaStyleAxisShape_prefs_key from utilities.prefs_constants import dnaStyleAxisColor_prefs_key from utilities.prefs_constants import dnaStyleAxisScale_prefs_key from utilities.prefs_constants import dnaStyleAxisEndingStyle_prefs_key from utilities.prefs_constants import dnaStyleStrutsShape_prefs_key from utilities.prefs_constants import dnaStyleStrutsColor_prefs_key from utilities.prefs_constants import dnaStyleStrutsScale_prefs_key from utilities.prefs_constants import dnaStyleBasesShape_prefs_key from utilities.prefs_constants import dnaStyleBasesColor_prefs_key from utilities.prefs_constants import dnaStyleBasesScale_prefs_key # DNA labels and base indicators. 080325 piotr from utilities.prefs_constants import dnaStrandLabelsEnabled_prefs_key from utilities.prefs_constants import dnaStrandLabelsColor_prefs_key from utilities.prefs_constants import dnaStrandLabelsColorMode_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsEnabled_prefs_key from utilities.prefs_constants import dnaBaseInvIndicatorsEnabled_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsAngle_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsColor_prefs_key from utilities.prefs_constants import dnaBaseInvIndicatorsColor_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsDistance_prefs_key from utilities.prefs_constants import dnaStyleBasesDisplayLetters_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsPlaneNormal_prefs_key # Undo prefs from utilities.prefs_constants import undoRestoreView_prefs_key from utilities.prefs_constants import undoAutomaticCheckpoints_prefs_key from utilities.prefs_constants import undoStackMemoryLimit_prefs_key from utilities.prefs_constants import historyMsgSerialNumber_prefs_key from utilities.prefs_constants import historyMsgTimestamp_prefs_key from utilities.prefs_constants import historyHeight_prefs_key from utilities.prefs_constants import rememberWinPosSize_prefs_key from utilities.prefs_constants import captionFullPath_prefs_key from utilities.prefs_constants import dynamicToolTipAtomChunkInfo_prefs_key from utilities.prefs_constants import dynamicToolTipAtomMass_prefs_key from utilities.prefs_constants import dynamicToolTipAtomPosition_prefs_key from utilities.prefs_constants import dynamicToolTipAtomDistanceDeltas_prefs_key from utilities.prefs_constants import dynamicToolTipBondLength_prefs_key from utilities.prefs_constants import dynamicToolTipBondChunkInfo_prefs_key from utilities.prefs_constants import dynamicToolTipAtomDistancePrecision_prefs_key from utilities.prefs_constants import captionPrefix_prefs_key from utilities.prefs_constants import captionSuffix_prefs_key from utilities.prefs_constants import compassPosition_prefs_key from utilities.prefs_constants import defaultProjection_prefs_key from utilities.prefs_constants import displayOriginAsSmallAxis_prefs_key from utilities.prefs_constants import displayOriginAxis_prefs_key from utilities.prefs_constants import animateMaximumTime_prefs_key from utilities.prefs_constants import mouseSpeedDuringRotation_prefs_key from utilities.prefs_constants import Adjust_endRMS_prefs_key from utilities.prefs_constants import Adjust_endMax_prefs_key from utilities.prefs_constants import Adjust_cutoverMax_prefs_key from utilities.prefs_constants import sponsor_permanent_permission_prefs_key from utilities.prefs_constants import sponsor_download_permission_prefs_key from utilities.prefs_constants import bondpointHotspotColor_prefs_key from utilities.prefs_constants import diBALL_bondcolor_prefs_key from utilities.prefs_constants import bondHighlightColor_prefs_key from utilities.prefs_constants import bondStretchColor_prefs_key from utilities.prefs_constants import bondVaneColor_prefs_key from utilities.prefs_constants import pibondStyle_prefs_key from utilities.prefs_constants import pibondLetters_prefs_key from utilities.prefs_constants import linesDisplayModeThickness_prefs_key from utilities.prefs_constants import diBALL_BondCylinderRadius_prefs_key from utilities.prefs_constants import material_specular_highlights_prefs_key from utilities.prefs_constants import material_specular_shininess_prefs_key from utilities.prefs_constants import material_specular_brightness_prefs_key from utilities.prefs_constants import material_specular_finish_prefs_key from utilities.prefs_constants import povdir_path_prefs_key from utilities.prefs_constants import dynamicToolTipBendAnglePrecision_prefs_key from utilities.prefs_constants import dynamicToolTipVdwRadiiInAtomDistance_prefs_key from utilities.prefs_constants import displayFontPointSize_prefs_key from utilities.prefs_constants import useSelectedFont_prefs_key from utilities.prefs_constants import displayFont_prefs_key from utilities.prefs_constants import keepBondsDuringTransmute_prefs_key from utilities.prefs_constants import indicateOverlappingAtoms_prefs_key from utilities.prefs_constants import fogEnabled_prefs_key # Cursor text prefs. from utilities.prefs_constants import cursorTextFontSize_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key #global display preferences from utilities.constants import diDEFAULT ,diTrueCPK, diLINES from utilities.constants import diBALL, diTUBES, diDNACYLINDER from utilities.constants import black, white, gray from widgets.prefs_widgets import connect_doubleSpinBox_with_pref # = # Preferences widgets constants. I suggest that these be moved to another # file (i.e. prefs_constants.py or another file). Discuss with Bruce. -Mark # Setting some Qt constants just to make things more sane CHECKED = Qt.Checked UNCHECKED = Qt.Unchecked # Default Plug-in paths for all of the known plugins. Add more here. They are # indexed in the dictionary by the string value preferences key and sub indexed # by platform. This was moved here to make it easier to modify later. # Note: This and other variables like it could be moved into another module and # imported lazily to save on memory if and when it became useful to do so. DEFAULT_PLUGIN_PATHS = { gromacs_path_prefs_key : { "win32" : "C:\\GROMACS_3.3.3\\bin\\mdrun.exe", "darwin" : "/Applications/GROMACS_3.3.3/bin/mdrun", "linux" : "/usr/local/GROMCAS_3.3.3/bin/mdrun" }, cpp_path_prefs_key : { "win32" : "C:\\GROMACS_3.3.3\\MCPP\\bin\\mcpp.exe", "darwin" : "/Applications/GROMACS_3.3.3/mcpp/bin/mcpp", "linux" : "/usr/local/GROMACS_3.3.3/mcpp/bin/mcpp" }, rosetta_path_prefs_key : { "win32" : "C:\\Rosetta\\rosetta.exe", "darwin" : "/Users/marksims/Nanorex/Rosetta/rosetta++/rosetta.mactel", "linux" : "/usr/local/Rosetta/Rosetta" }, rosetta_dbdir_prefs_key : { "win32" : "C:\\Rosetta\\rosetta_database", "darwin" : "/Users/marksims/Nanorex/Rosetta/Rosetta_database", "linux" : "/usr/local/Rosetta/Rosetta_database" }, qutemol_path_prefs_key : { "win32" : "C:\\Program Files\\Nanorex\\QuteMolX\\QuteMolX.exe", "darwin" : "/Applications/Nanorex/QuteMolX 0.5.1/QuteMolX.app", "linux" : "/usr/local/Nanorex/QuteMolX 0.5.1/QuteMolX" }, povray_path_prefs_key : { "win32" : "C:\\Program Files\\POV-Ray for Windows v3.6\\bin\\pvengine.exe", "darwin" : "/usr/local/bin/pvengine", "linux" : "/usr/local/bin/pvengine" }, megapov_path_prefs_key : { "win32" : "C:\\Program Files\\POV-Ray for Windows v3.6\\bin\\megapov.exe", "darwin" : "/usr/local/bin/megapov", "linux" : "/usr/local/bin/megapov" }, povdir_path_prefs_key : { "win32" : "C:\\Program Files\\POV-Ray for Windows v3.6\\bin\\megapov.exe", "darwin" : "/usr/local/bin/megapov", "linux" : "/usr/local/bin/megapov" } } # variable for the value which denotes the variable detail level. This is # stored in the database as -1, but changed for use in the combobox VARIABLE_DETAIL_LEVEL_INDX = 3 # GDS = global display style from PreferencesDialog import GDS_NAMES, GDS_ICONS, GDS_INDEXES from PreferencesDialog import HIGH_ORDER_BOND_STYLES debug_sliders = False # Do not commit as True DEBUG = True # Do not commit as True CURSOR_TEXT_KEY = True def _fullkey(keyprefix, *subkeys): #e this func belongs in preferences.py res = keyprefix for subkey in subkeys: res += "/" + subkey return res def _size_pos_keys( keyprefix): return _fullkey(keyprefix, "geometry", "size"), _fullkey(keyprefix, "geometry", "pos") def _tupleFromQPoint(qpoint): return qpoint.x(), qpoint.y() def _tupleFromQSize(qsize): return qsize.width(), qsize.height() def _get_window_pos_size(win): size = _tupleFromQSize( win.size()) pos = _tupleFromQPoint( win.pos()) return pos, size def save_window_pos_size( win, keyprefix): #bruce 050913 removed histmessage arg """ Save the size and position of the given main window, win, in the preferences database, using keys based on the given keyprefix, which caller ought to reserve for geometry aspects of the main window. (#e Someday, maybe save more aspects like dock layout and splitter bar positions??) """ ## from preferences import prefs_context ## prefs = prefs_context() ksize, kpos = _size_pos_keys( keyprefix) pos, size = _get_window_pos_size(win) changes = { ksize: size, kpos: pos } env.prefs.update( changes) # use update so it only opens/closes dbfile once env.history.message("saved window position %r and size %r" % (pos,size)) return def load_window_pos_size( win, keyprefix, defaults = None, screen = None): #bruce 050913 removed histmessage arg; 060517 revised """ Load the last-saved size and position of the given main window, win, from the preferences database, using keys based on the given keyprefix, which caller ought to reserve for geometry aspects of the main window. (If no prefs have been stored, return reasonable or given defaults.) Then set win's actual position and size (using supplied defaults, and limited by supplied screen size, both given as ((pos_x,pos_y),(size_x,size_y)). (#e Someday, maybe restore more aspects like dock layout and splitter bar positions??) """ if screen is None: screen = screen_pos_size() ((x0, y0), (w, h)) = screen x1 = x0 + w y1 = y0 + h pos, size = _get_prefs_for_window_pos_size( win, keyprefix, defaults) # now use pos and size, within limits set by screen px, py = pos sx, sy = size if sx > w: sx = w if sy > h: sy = h if px < x0: px = x0 if py < y0: py = y0 if px > x1 - sx: px = x1 - sx if py > y1 - sy: py = y1 - sy env.history.message("restoring last-saved window position %r and size %r" \ % ((px, py),(sx, sy))) win.resize(sx, sy) win.move(px, py) return def _get_prefs_for_window_pos_size( win, keyprefix, defaults = None): """ Load and return the last-saved size and position of the given main window, win, from the preferences database, using keys based on the given keyprefix, which caller ought to reserve for geometry aspects of the main window. (If no prefs have been stored, return reasonable or given defaults.) """ #bruce 060517 split this out of load_window_pos_size if defaults is None: defaults = _get_window_pos_size(win) dpos, dsize = defaults px, py = dpos # check correctness of args, even if not used later sx, sy = dsize import foundation.preferences as preferences prefs = preferences.prefs_context() ksize, kpos = _size_pos_keys( keyprefix) pos = prefs.get(kpos, dpos) size = prefs.get(ksize, dsize) return pos, size #def get_pref_or_optval(key, val, optval): #""" #Return <key>'s value. If <val> is equal to <key>'s value, return <optval> #instead. #""" #if env.prefs[key] == val: #return optval #else: #return env.prefs[key] class Preferences(PreferencesDialog): """ The Preferences dialog used for accessing and changing user preferences. """ pagenameList = [] # List of page names in prefsStackedWidget. # def __init__(self, assy): def __init__(self): QDialog.__init__(self) super(Preferences, self).__init__() # Some important attrs. # self.glpane = assy.o # self.w = assy.w # self.assy = assy self.pagenameList = self.getPagenameList() if DEBUG: print self.pagenameList self.changeKey = 0 # Start of dialog setup. self._setupDialog_TopLevelWidgets() self._setupPage_General() self._setupPage_Graphics_Area() self._setupPage_Zoom_Pan_and_Rotate() self._setupPage_Rulers() self._setupPage_Atoms() self._setupPage_Bonds() self._setupPage_DNA() self._setupPage_DNA_Minor_Groove_Error_Indicator() self._setupPage_DNA_Base_Orientation_Indicators() self._setupPage_Adjust() self._setupPage_Plugins() self._setupPage_Undo() self._setupPage_Window() self._setupPage_Reports() self._setupPage_Tooltips() # Assign "What's This" text for all widgets. #from ne1_ui.prefs.WhatsThisText_for_PreferencesDialog import whatsThis_PreferencesDialog from WhatsThisText_for_PreferencesDialog import whatsThis_PreferencesDialog whatsThis_PreferencesDialog(self) #self._hideOrShowWidgets() self.show() return # End of _init_() # PAGE: GENERAL def _setupPage_General(self): """ Setup the General page. """ # GROUPBOX: Sponsor logos download permission if env.prefs[sponsor_permanent_permission_prefs_key]: if env.prefs[sponsor_download_permission_prefs_key]: _myID = 1 else: _myID = 2 else: _myID = 0 self.logo_download_RadioButtonList.setDefaultCheckedId(_myID) _checkedButton = self.logo_download_RadioButtonList.getButtonById(_myID) _checkedButton.setChecked(True) self.connect(self.logo_download_RadioButtonList.buttonGroup, SIGNAL("buttonClicked(int)"), self.setPrefsLogoDownloadPermissions) # GROUPBOX: Build Chunks Settings connect_checkbox_with_boolean_pref( self.autobondCheckBox, buildModeAutobondEnabled_prefs_key ) connect_checkbox_with_boolean_pref( self.hoverHighlightCheckBox, buildModeHighlightingEnabled_prefs_key ) connect_checkbox_with_boolean_pref( self.waterCheckBox, buildModeWaterEnabled_prefs_key ) connect_checkbox_with_boolean_pref( self.autoSelectAtomsCheckBox, buildModeSelectAtomsOfDepositedObjEnabled_prefs_key ) # GROUPBOX: Offset factor for pasting objects connect_doubleSpinBox_with_pref(self.pasteOffsetForChunks_doublespinbox, pasteOffsetScaleFactorForChunks_prefs_key) connect_doubleSpinBox_with_pref(self.pasteOffsetForDNA_doublespinbox, pasteOffsetScaleFactorForDnaObjects_prefs_key) return def setPrefsLogoDownloadPermissions(self, permission): """ Set the sponsor logos download permissions in the persistent user preferences database. @param permission: The permission, where: 0 = Always ask before downloading 1 = Never ask before downloading 2 = Never download @type permission: int """ _permanentValue = False _downloadValue = True if permission == 1: _permanentValue = True _downloadValue = True elif permission == 2: _permanentValue = True _downloadValue = False else: _permanentValue = False env.prefs[sponsor_permanent_permission_prefs_key] = _permanentValue env.prefs[sponsor_download_permission_prefs_key] = _downloadValue return def setGlobalDisplayStyleAtStartUp(self, junk): """ Slot method for the "Global Display Style at Start-up" combo box in the Preferences dialog (and not the combobox in the status bar of the main window). @param gdsIndexUnused: The current index of the combobox. It is unused. @type gdsIndexUnused: int @note: This changes the global display style of the glpane. """ # Get the GDS index from the current combox box index. display_style = GDS_INDEXES[self.globalDisplayStyleStartupComboBox.currentIndex()] if display_style == env.prefs[startupGlobalDisplayStyle_prefs_key]: return # set the pref env.prefs[startupGlobalDisplayStyle_prefs_key] = display_style # Set the current display style in the glpane. # (This will be noticed later by chunk.draw of affected chunks.) #UNCOMMENT LATER # self.glpane.setGlobalDisplayStyle(display_style) # self.glpane.gl_update() return # PAGE: GRAPHICS AREA def _setupPage_Graphics_Area(self): """ Setup the Graphics Area page """ display_style = env.prefs[ startupGlobalDisplayStyle_prefs_key ] self.globalDisplayStyleStartupComboBox.setCurrentIndex(GDS_INDEXES.index(display_style)) self.connect(self.globalDisplayStyleStartupComboBox, SIGNAL("currentIndexChanged(int)"), self.setGlobalDisplayStyleAtStartUp) # GROUPBOX: Compass display settings # Check if the compass is set to display if env.prefs[displayCompass_prefs_key]: self.display_compass_CheckBox.setCheckState(CHECKED) else: self.display_compass_CheckBox.setCheckState(UNCHECKED) # Call the display_compass function no matter what it know's what to do. self.display_compass(env.prefs[displayCompass_prefs_key]) self.connect(self.display_compass_CheckBox, SIGNAL("toggled(bool)"), self.display_compass) connect_comboBox_with_pref(self.compass_location_ComboBox, compassPosition_prefs_key) connect_checkbox_with_boolean_pref(self.display_compass_labels_checkbox, displayCompassLabels_prefs_key) # GROUPBOX: Axes connect_checkbox_with_boolean_pref(self.display_origin_axis_checkbox, displayOriginAxis_prefs_key) connect_checkbox_with_boolean_pref(self.display_pov_axis_checkbox, displayPOVAxis_prefs_key) # GROUPBOX: Cursor text settings self.set_cursor_text_font_size() self.connect(self.cursor_text_font_size_SpinBox, SIGNAL("valueChanged(double)"), self.set_cursor_text_font_size) self.connect(self.cursor_text_reset_Button, SIGNAL("clicked()"), self.reset_cursor_text_font_size) self.cursor_text_color_ComboBox.setColor(env.prefs[cursorTextColor_prefs_key], default = True) self.connect(self.cursor_text_color_ComboBox, SIGNAL("editingFinished()"), self.set_cursor_text_color) # GROUPBOX: Other graphics options groupbox connect_checkbox_with_boolean_pref(self.display_confirmation_corner_CheckBox, displayConfirmationCorner_prefs_key) connect_checkbox_with_boolean_pref(self.anti_aliasing_CheckBox, enableAntiAliasing_prefs_key) return def set_cursor_text_font_size(self, font_size = -1): """ Slot for cursor text font size doubleSpinBox. If passed a positive number for font_size, it sets the value of the environment pref. If called with a negative number, it sets the spinbox to the environment pref. In either case, it will then determine if the value is equal to the default and enable/disable the reset button. """ if font_size >0: env.prefs[cursorTextFontSize_prefs_key] = font_size else: self.cursor_text_font_size_SpinBox.setValue( env.prefs[cursorTextFontSize_prefs_key]) if env.prefs.has_default_value(cursorTextFontSize_prefs_key): self.cursor_text_reset_Button.setEnabled(False) else: self.cursor_text_reset_Button.setEnabled(True) def reset_cursor_text_font_size(self, test = 0): """ Slot to reset the cursor text font size. """ if not env.prefs.has_default_value(cursorTextFontSize_prefs_key): _tmp = env.prefs.get_default_value(cursorTextFontSize_prefs_key) self.cursor_text_font_size_SpinBox.setValue(_tmp) env.prefs[cursorTextFontSize_prefs_key] = _tmp self.cursor_text_reset_Button.setEnabled(False) return def set_cursor_text_color(self): """ Slot to set the cursor text color combobox. """ _newColor = self.cursor_text_color_ComboBox.getColor() env.prefs[cursorTextColor_prefs_key] = _newColor return def display_compass(self, val): """ Slot for the Display Compass checkbox, which enables/disables the Display Compass Labels checkbox. """ val = not not val # Enable or disable the appropriate things self.compass_location_ComboBox.setEnabled(val) self.compass_location_ComboBox.labelWidget.setEnabled(val) self.display_compass_labels_checkbox.setEnabled(val) # If the value is different from the saved value, then save the new one. # This method is called at startup, so this could be used simply to # set the initial state of the if val != env.prefs[displayCompass_prefs_key]: env.prefs[displayCompass_prefs_key] = val return #PAGE: ZOOM, PAN, AND ROTATE def _setupPage_Zoom_Pan_and_Rotate(self): """ Setup the Zoom, Pan and Rotate page. """ # GROUPBOX: View rotation settings connect_checkbox_with_boolean_pref(self.animate_views_CheckBox, animateStandardViews_prefs_key) self.view_animation_speed_Slider.setValue(int (env.prefs[animateMaximumTime_prefs_key] * -100)) self.mouse_rotation_speed_Slider.setValue(int (env.prefs[mouseSpeedDuringRotation_prefs_key] * 100)) if env.prefs.has_default_value(animateMaximumTime_prefs_key): self.view_animation_speed_reset_ToolButton.setEnabled(False) if env.prefs.has_default_value(mouseSpeedDuringRotation_prefs_key): self.mouse_rotation_speed_reset_ToolButton.setEnabled(False) self.connect(self.view_animation_speed_Slider, SIGNAL("sliderReleased()"), self.set_view_animation_speed) self.connect(self.view_animation_speed_reset_ToolButton, SIGNAL("clicked()"), self.reset_view_animation_speed) self.connect(self.mouse_rotation_speed_Slider, SIGNAL("sliderReleased()"), self.set_mouse_rotation_speed) self.connect(self.mouse_rotation_speed_reset_ToolButton, SIGNAL("clicked()"), self.reset_mouse_rotation_speed) # GROUPBOX: Mouse wheel zoom settings connect_comboBox_with_pref(self.zoom_directon_ComboBox, mouseWheelDirection_prefs_key) connect_comboBox_with_pref(self.zoom_in_center_ComboBox, zoomInAboutScreenCenter_prefs_key) connect_comboBox_with_pref(self.zoom_out_center_ComboBox, zoomOutAboutScreenCenter_prefs_key) connect_doubleSpinBox_with_pref(self.hover_highlighting_timeout_SpinBox, mouseWheelTimeoutInterval_prefs_key) return def set_view_animation_speed(self): """ Slot for setting the view animation speed slider. """ env.prefs[animateMaximumTime_prefs_key] = \ self.view_animation_speed_Slider.value() / -100.0 self.view_animation_speed_reset_ToolButton.setEnabled(True) return def reset_view_animation_speed(self): """ Slot for resetting the view animation speed slider through the view animation speed reset toolbutton. """ env.prefs.restore_defaults([animateMaximumTime_prefs_key]) self.view_animation_speed_Slider.setValue(int (env.prefs[animateMaximumTime_prefs_key] * -100)) self.view_animation_speed_reset_ToolButton.setEnabled(False) def set_mouse_rotation_speed(self): """ Slot for setting the mouse rotation speed slider. """ env.prefs[mouseSpeedDuringRotation_prefs_key] = \ self.mouse_rotation_speed_Slider.value() / 100.0 self.mouse_rotation_speed_reset_ToolButton.setEnabled(True) return def reset_mouse_rotation_speed(self): """ Slot for resetting the mouse rotation speed slider through the mouse rotation speed reset toolbutton. """ env.prefs.restore_defaults([mouseSpeedDuringRotation_prefs_key]) self.mouse_rotation_speed_Slider.setValue(int (env.prefs[mouseSpeedDuringRotation_prefs_key] * 100)) self.mouse_rotation_speed_reset_ToolButton.setEnabled(False) # PAGE: RULERS def _setupPage_Rulers(self): """ Setup the "Rulers" page. """ # GROUPBOX: Rulers if env.prefs[displayVertRuler_prefs_key] and env.prefs[displayHorzRuler_prefs_key]: self.display_rulers_ComboBox.setCurrentIndex(0) elif not env.prefs[displayHorzRuler_prefs_key]: self.display_rulers_ComboBox.setCurrentIndex(1) elif not env.prefs[displayVertRuler_prefs_key]: self.display_rulers_ComboBox.setCurrentIndex(2) self.connect(self.display_rulers_ComboBox, SIGNAL("currentIndexChanged(int)"), self.set_ruler_display) connect_comboBox_with_pref(self.origin_rulers_ComboBox, rulerPosition_prefs_key) self.ruler_color_ColorComboBox.setColor(env.prefs[rulerColor_prefs_key], default = True) self.connect(self.ruler_color_ColorComboBox, SIGNAL("editingFinished()"), self.set_ruler_color) self.ruler_opacity_SpinBox.setValue(int(env.prefs[rulerOpacity_prefs_key] * 100)) self.connect(self.ruler_opacity_SpinBox, SIGNAL("valueChanged(int)"), self.set_ruler_opacity) connect_checkbox_with_boolean_pref(self.show_rulers_in_perspective_view_CheckBox,\ showRulersInPerspectiveView_prefs_key) return def set_ruler_display(self, indx): """ Slot for setting which rulers should be displayed. indx == 0: verticle and horizontal are displayed. indx == 1: Just verticle is displayed indx == other (normally 2): Just horizontal is displayed """ if indx == 0: env.prefs[displayVertRuler_prefs_key] = True env.prefs[displayHorzRuler_prefs_key] = True elif indx == 1: env.prefs[displayVertRuler_prefs_key] = True env.prefs[displayHorzRuler_prefs_key] = False else: env.prefs[displayVertRuler_prefs_key] = False env.prefs[displayHorzRuler_prefs_key] = True return def set_ruler_color(self): """ Slot to set the ruler color from the ruler color colorcombobox. """ _newColor = self.ruler_color_ColorComboBox.getColor() env.prefs[rulerColor_prefs_key] = _newColor return def set_ruler_opacity(self, opacity): """ Change the ruler opacity. """ env.prefs[rulerOpacity_prefs_key] = opacity * 0.01 return # PAGE: ATOMS ============================================================ def _setupPage_Atoms(self): """ Setup the "Atoms" page. """ # GROUPBOX: Colors # "Change Element Colors" button. self.connect(self.change_element_colors_PushButton, SIGNAL("clicked()"), self.change_element_colors) # GROUPBOX: Colors sub self.atom_highlighting_ColorComboBox.setColor(env.prefs[atomHighlightColor_prefs_key], default = True) self.connect(self.atom_highlighting_ColorComboBox, SIGNAL("editingFinished()"), self.set_atom_highlighting_color) self.bondpoint_highlighting_ColorComboBox.setColor(env.prefs[bondpointHighlightColor_prefs_key], default = True) self.connect(self.bondpoint_highlighting_ColorComboBox, SIGNAL("editingFinished()"), self.set_bondpoint_highlighting_color) self.bondpoint_hotspots_ColorComboBox.setColor(env.prefs[bondpointHotspotColor_prefs_key], default = True) self.connect(self.bondpoint_hotspots_ColorComboBox, SIGNAL("editingFinished()"), self.set_bondpoint_hotspots_color) self.connect(self.restore_element_colors_PushButton, SIGNAL("clicked()"), self.reset_atom_and_bondpoint_colors) #GROUPBOX: Miscellaneous atom options lod = env.prefs[levelOfDetail_prefs_key] if lod == -1: lod = VARIABLE_DETAIL_LEVEL_INDX self.atoms_detail_level_ComboBox.setCurrentIndex(lod) self.connect(self.atoms_detail_level_ComboBox, SIGNAL("currentIndexChanged(int)"), self.set_level_of_detail) self.set_ball_and_stick_atom_scale(env.prefs[diBALL_AtomRadius_prefs_key]) self.set_CPK_atom_scale(env.prefs[cpkScaleFactor_prefs_key]) self.ball_and_stick_atom_scale_SpinBox.setValue(round(env.prefs[diBALL_AtomRadius_prefs_key] * 100.0)) self.CPK_atom_scale_doubleSpinBox.setValue(env.prefs[cpkScaleFactor_prefs_key]) self.connect(self.ball_and_stick_atom_scale_SpinBox, SIGNAL("valueChanged(int)"),self.set_ball_and_stick_atom_scale) self.connect(self.CPK_atom_scale_doubleSpinBox, SIGNAL("valueChanged(double)"),self.set_CPK_atom_scale) self.connect(self.ball_and_stick_atom_scale_reset_ToolButton, SIGNAL("clicked()"),self.reset_ball_and_stick_atom_scale) self.connect(self.CPK_atom_scale_reset_ToolButton, SIGNAL("clicked()"),self.reset_CPK_atom_scale) connect_checkbox_with_boolean_pref(self.overlapping_atom_indicators_CheckBox, indicateOverlappingAtoms_prefs_key) connect_checkbox_with_boolean_pref(self.force_to_keep_bonds_during_transmute_CheckBox, keepBondsDuringTransmute_prefs_key) return def set_atom_highlighting_color(self): """ Slot for the atom highlighting colorcombobox. """ _newColor = self.atom_highlighting_ColorComboBox.getColor() env.prefs[atomHighlightColor_prefs_key] = _newColor return def set_bondpoint_highlighting_color(self): """ Slot for the bondpoint highlighting colorcombobox. """ _newColor = self.bondpoint_highlighting_ColorComboBox.getColor() env.prefs[bondpointHighlightColor_prefs_key] = _newColor return def set_bondpoint_hotspots_color(self): """ Slot for the bondpoint hotspots colorcombobox. """ _newColor = self.bondpoint_hotspots_ColorComboBox.getColor() env.prefs[bondpointHotspotColor_prefs_key] = _newColor return def reset_atom_and_bondpoint_colors(self): """ Slot for the restore element colors pushbutton. This will reset the atom highlighting, bondpoint highlighting, and bondpoint hotspots colorcomboboxes """ env.prefs.restore_defaults([atomHighlightColor_prefs_key, bondpointHighlightColor_prefs_key, bondpointHotspotColor_prefs_key]) self.atom_highlighting_ColorComboBox.setColor(env.prefs.get_default_value(atomHighlightColor_prefs_key)) self.bondpoint_highlighting_ColorComboBox.setColor(env.prefs.get_default_value(bondpointHighlightColor_prefs_key)) self.bondpoint_hotspots_ColorComboBox.setColor(env.prefs.get_default_value(bondpointHotspotColor_prefs_key)) return def change_element_colors(self): """ Display the Element Color Settings Dialog. Note: This dialog has not been converted to using PM_Widgets """ # Since the prefs dialog is modal, the element color settings dialog must be modal. self.w.showElementColorSettings(self) return def set_level_of_detail(self, level_of_detail_item): #bruce 060215 revised this """ Change the level of detail, where <level_of_detail_item> is a value between 0 and 3 where: - 0 = low - 1 = medium - 2 = high - 3 = variable (based on number of atoms in the part) @note: the prefs db value for 'variable' is -1, to allow for higher LOD levels in the future. """ lod = level_of_detail_item if level_of_detail_item == VARIABLE_DETAIL_LEVEL_INDX: lod = -1 env.prefs[levelOfDetail_prefs_key] = lod # self.glpane.gl_update() # the redraw this causes will (as of tonight) always recompute the correct drawLevel (in Part._recompute_drawLevel), # and chunks will invalidate their display lists as needed to accomodate the change. [bruce 060215] return def set_ball_and_stick_atom_scale(self, value): """ Slot for ball_and_stick_atom_scale_SpinBox. Also enables and disables the reset button. """ if env.prefs[diBALL_AtomRadius_prefs_key] != value: env.prefs[diBALL_AtomRadius_prefs_key] = round(float(value) / 100.0, 2) if env.prefs.has_default_value(diBALL_AtomRadius_prefs_key): self.ball_and_stick_atom_scale_reset_ToolButton.setEnabled(False) else: self.ball_and_stick_atom_scale_reset_ToolButton.setEnabled(True) return def set_CPK_atom_scale(self, value): """ Slot for CPK_atom_scale_doubleSpinBox. Also enables and disables the reset button. """ if env.prefs[cpkScaleFactor_prefs_key] != value: env.prefs[cpkScaleFactor_prefs_key] = value # direct comparison with has_default_value didn't work on this level # of precision if round(env.prefs.get_default_value(cpkScaleFactor_prefs_key), 3 ) \ == round(value, 3): self.CPK_atom_scale_reset_ToolButton.setEnabled(False) else: self.CPK_atom_scale_reset_ToolButton.setEnabled(True) return def reset_ball_and_stick_atom_scale(self): """ Slot for ball_and_stick_atom_scale_reset_ToolButton. """ _resetValue = env.prefs.get_default_value(diBALL_AtomRadius_prefs_key) _resetValue = int((_resetValue + .005) * 100) self.set_ball_and_stick_atom_scale(_resetValue) self.ball_and_stick_atom_scale_SpinBox.setValue(_resetValue, blockSignals = True) return def reset_CPK_atom_scale(self): """ Slot for CPK_atom_scale_reset_ToolButton. """ _resetValue = env.prefs.get_default_value(cpkScaleFactor_prefs_key) self.set_CPK_atom_scale(_resetValue) self.CPK_atom_scale_doubleSpinBox.setValue(_resetValue, blockSignals = True) return # PAGE: BONDS ============================================================ def _setupPage_Bonds(self): """ Setup the "Bonds" page. """ # GROUPBOX Colors self.bond_highlighting_ColorComboBox.setColor(env.prefs[bondHighlightColor_prefs_key]) self.connect(self.bond_highlighting_ColorComboBox, SIGNAL("editingFinished()"), self.set_bond_highlighting_color) self.ball_and_stick_cylinder_ColorComboBox.setColor(env.prefs[diBALL_bondcolor_prefs_key]) self.connect(self.ball_and_stick_cylinder_ColorComboBox, SIGNAL("editingFinished()"), self.set_ball_and_stick_cylinder_color) self.bond_stretch_ColorComboBox.setColor(env.prefs[bondStretchColor_prefs_key]) self.connect(self.bond_stretch_ColorComboBox, SIGNAL("editingFinished()"), self.set_bond_stretch_color) self.vane_ribbon_ColorComboBox.setColor(env.prefs[bondVaneColor_prefs_key]) self.connect(self.vane_ribbon_ColorComboBox, SIGNAL("editingFinished()"), self.set_vane_ribbon_color) self.connect(self.restore_bond_colors_PushButton, SIGNAL("clicked()"), self.reset_default_colors) # GROUPBOX Miscellaneous bond settings self.set_ball_and_stick_bond_scale(env.prefs[diBALL_BondCylinderRadius_prefs_key] * 100) self.set_bond_line_thickness(env.prefs[linesDisplayModeThickness_prefs_key]) self.ball_and_stick_bond_scale_SpinBox.setValue(round(env.prefs[diBALL_BondCylinderRadius_prefs_key] * 100)) self.bond_line_thickness_SpinBox.setValue(env.prefs[linesDisplayModeThickness_prefs_key]) self.connect(self.ball_and_stick_bond_scale_SpinBox, SIGNAL("valueChanged(int)"),self.set_ball_and_stick_bond_scale) self.connect(self.bond_line_thickness_SpinBox, SIGNAL("valueChanged(int)"),self.set_bond_line_thickness) # GROUPBOX: High order bonds (sub box) if env.prefs[pibondStyle_prefs_key] == "multicyl": _myID = 0 elif env.prefs[pibondStyle_prefs_key] == "vane": _myID = 1 else: _myID = 2 _checkedButton = self.high_order_bonds_RadioButtonList.getButtonById(_myID) _checkedButton.setChecked(True) self.connect(self.high_order_bonds_RadioButtonList.buttonGroup, SIGNAL("buttonClicked(int)"), self.set_high_order_bonds) connect_checkbox_with_boolean_pref(self.show_bond_type_letters_CheckBox, pibondLetters_prefs_key) connect_checkbox_with_boolean_pref(self.show_valence_errors_CheckBox, showValenceErrors_prefs_key) connect_checkbox_with_boolean_pref(self.show_bond_stretch_indicators_CheckBox, showBondStretchIndicators_prefs_key) return def set_bond_highlighting_color(self): """ Slot for bond_highlighting_ColorComboBox """ _newColor = self.bond_highlighting_ColorComboBox.getColor() env.prefs[bondHighlightColor_prefs_key] = _newColor return def set_ball_and_stick_cylinder_color(self): """ Slot for ball_and_stick_cylinder_ColorComboBox """ _newColor = self.ball_and_stick_cylinder_ColorComboBox.getColor() env.prefs[diBALL_bondcolor_prefs_key] = _newColor return def set_bond_stretch_color(self): """ Slot for bond_stretch_ColorComboBox """ _newColor = self.bond_stretch_ColorComboBox.getColor() env.prefs[bondStretchColor_prefs_key] = _newColor return def set_vane_ribbon_color(self): """ Slot for vane_ribbon_ColorComboBox """ _newColor = self.vane_ribbon_ColorComboBox.getColor() env.prefs[bondVaneColor_prefs_key] = _newColor return def reset_default_colors(self): """ Slot for restore_bond_colors_PushButton. This will reset the preference keys and their respective colorcomboboxes back to the database default values """ env.prefs.restore_defaults([bondHighlightColor_prefs_key, bondStretchColor_prefs_key, bondVaneColor_prefs_key, diBALL_bondcolor_prefs_key]) self.bond_highlighting_ColorComboBox.setColor(env.prefs.get_default_value(bondHighlightColor_prefs_key)) self.ball_and_stick_cylinder_ColorComboBox.setColor(env.prefs.get_default_value(diBALL_bondcolor_prefs_key)) self.bond_stretch_ColorComboBox.setColor(env.prefs.get_default_value(bondStretchColor_prefs_key)) self.vane_ribbon_ColorComboBox.setColor(env.prefs.get_default_value(bondVaneColor_prefs_key)) return def set_ball_and_stick_bond_scale(self, value): """ Slot for ball_and_stick_bond_scale_SpinBox """ if env.prefs[diBALL_BondCylinderRadius_prefs_key] != value: env.prefs[diBALL_BondCylinderRadius_prefs_key] = round(float(value) / 100.0, 2) #if env.prefs.has_default_value(diBALL_BondCylinderRadius_prefs_key): #self.ball_and_stick_atom_scale_reset_ToolButton.setEnabled(False) #else: #self.ball_and_stick_atom_scale_reset_ToolButton.setEnabled(True) return def set_bond_line_thickness(self, value): """ Slot for bond_line_thickness_SpinBox """ if env.prefs[linesDisplayModeThickness_prefs_key] != value: env.prefs[linesDisplayModeThickness_prefs_key] = value #if env.prefs.has_default_value(linesDisplayModeThickness_prefs_key): #self.ball_and_stick_atom_scale_reset_ToolButton.setEnabled(False) #else: #self.ball_and_stick_atom_scale_reset_ToolButton.setEnabled(True) return def set_high_order_bonds(self, value): """ Slot for high_order_bonds_RadioButtonList """ env.prefs[pibondStyle_prefs_key] = HIGH_ORDER_BOND_STYLES[value][3] return # PAGE: DNA ============================================================== def _setupPage_DNA(self): """ Setup the "DNA" page. """ # GROUPBOX: DNA default values # Uncomment next line when a DB Pref is made for it. #connect_comboBox_with_pref(self.conformation_ComboBox, <SOME_VALUE>) connect_doubleSpinBox_with_pref(self.bases_per_turn_DoubleSpinBox, bdnaBasesPerTurn_prefs_key) connect_doubleSpinBox_with_pref(self.rise_DoubleSpinBox, bdnaRise_prefs_key) self.strand1_ColorComboBox.setColor(env.prefs[dnaDefaultStrand1Color_prefs_key]) self.connect(self.strand1_ColorComboBox, SIGNAL("editingFinished()"), self.set_strand1_color) self.strand2_ColorComboBox.setColor(env.prefs[dnaDefaultStrand2Color_prefs_key]) self.connect(self.strand1_ColorComboBox, SIGNAL("editingFinished()"), self.set_strand2_color) self.segment_ColorComboBox.setColor(env.prefs[dnaDefaultSegmentColor_prefs_key]) self.connect(self.segment_ColorComboBox, SIGNAL("editingFinished()"), self.set_segment_color) self.connect(self.restore_DNA_colors_PushButton, SIGNAL("clicked()"), self.reset_DNA_colors) # GROUPBOX: Strand arrowhead display options connect_checkbox_with_boolean_pref(self.show_arrows_on_backbones_CheckBox, arrowsOnBackBones_prefs_key) connect_checkbox_with_boolean_pref(self.show_arrows_on_3prime_ends_CheckBox, arrowsOnThreePrimeEnds_prefs_key) connect_checkbox_with_boolean_pref(self.show_arrows_on_5prime_ends_CheckBox, arrowsOnFivePrimeEnds_prefs_key) self.three_prime_end_custom_ColorComboBox.setColor(env.prefs[dnaStrandThreePrimeArrowheadsCustomColor_prefs_key]) self.connect(self.three_prime_end_custom_ColorComboBox, SIGNAL("editingFinished()"), self.set_three_prime_end_color) self.five_prime_end_custom_ColorComboBox.setColor(env.prefs[dnaStrandFivePrimeArrowheadsCustomColor_prefs_key]) self.connect(self.five_prime_end_custom_ColorComboBox, SIGNAL("editingFinished()"), self.set_five_prime_end_color) return def set_strand1_color(self): """ Slot for strand1_ColorComboBox """ _newColor = self.strand1_ColorComboBox.getColor() env.prefs[dnaDefaultStrand1Color_prefs_key] = _newColor return def set_strand2_color(self): """ Slot for strand2_ColorComboBox """ _newColor = self.strand2_ColorComboBox.getColor() env.prefs[dnaDefaultStrand2Color_prefs_key] = _newColor return def set_segment_color(self): """ Slot for segment_ColorComboBox """ _newColor = self.segment_ColorComboBox.getColor() env.prefs[dnaDefaultSegmentColor_prefs_key] = _newColor return def reset_DNA_colors(self): """ Slot for restore_DNA_colors_PushButton """ env.prefs.restore_defaults([dnaDefaultStrand1Color_prefs_key, dnaDefaultStrand2Color_prefs_key, dnaDefaultSegmentColor_prefs_key]) self.strand1_ColorComboBox.setColor(env.prefs.get_default_value(dnaDefaultStrand1Color_prefs_key)) self.strand2_ColorComboBox.setColor(env.prefs.get_default_value(dnaDefaultStrand2Color_prefs_key)) self.segment_ColorComboBox.setColor(env.prefs.get_default_value(dnaDefaultSegmentColor_prefs_key)) return def set_three_prime_end_color(self): """ Slot for three_prime_end_custom_ColorComboBox """ _newColor = self.three_prime_end_custom_ColorComboBox.getColor() env.prefs[dnaStrandThreePrimeArrowheadsCustomColor_prefs_key] = _newColor return def set_five_prime_end_color(self): """ Slot for ifive_prime_end_custom_ColorComboBox """ _newColor = self.five_prime_end_custom_ColorComboBox.getColor() env.prefs[dnaStrandFivePrimeArrowheadsCustomColor_prefs_key] = _newColor return # PAGE: DNA MINOR GROOVE ERROR INDICATOR def _setupPage_DNA_Minor_Groove_Error_Indicator(self): """ Setup the "DNA Minor_Groove Error Indicator" page. """ self.set_DNA_minor_groove_error_indicator_status() self.connect(self.minor_groove_error_indicatiors_CheckBox, SIGNAL("toggled(bool)"), self.set_DNA_minor_groove_error_indicator_status) # GROUPBOX: connect_doubleSpinBox_with_pref connect_spinBox_with_pref(self.minor_groove_error_minimum_angle_SpinBox, dnaMinMinorGrooveAngle_prefs_key) connect_spinBox_with_pref(self.minor_groove_error_maximum_angle_SpinBox, dnaMaxMinorGrooveAngle_prefs_key) self.minor_groove_error_color_ColorComboBox.setColor(env.prefs[dnaMinorGrooveErrorIndicatorColor_prefs_key]) self.connect(self.minor_groove_error_color_ColorComboBox, SIGNAL("editingFinished()"), self.set_minor_groove_error_color) self.connect(self.minor_groove_error_reset_PushButton, SIGNAL("clicked()"), self.reset_minor_groove_error_prefs) return def set_DNA_minor_groove_error_indicator_status(self, status = None): """ Slot for minor_groove_error_indicatiors_CheckBox. This also enables/disables the associated groupbox and it's child widgets. """ if (status == None and env.prefs[dnaDisplayMinorGrooveErrorIndicators_prefs_key]) \ or status: self.minor_groove_error_parameters_GroupBox.setEnabled(True) self.minor_groove_error_indicatiors_CheckBox.setCheckState(CHECKED) env.prefs[dnaDisplayMinorGrooveErrorIndicators_prefs_key] = True else: self.minor_groove_error_parameters_GroupBox.setEnabled(False) self.minor_groove_error_indicatiors_CheckBox.setCheckState(UNCHECKED) env.prefs[dnaDisplayMinorGrooveErrorIndicators_prefs_key] = False return def set_minor_groove_error_color(self): """ Slot for minor_groove_error_color_ColorComboBox """ _newColor = self.minor_groove_error_color_ColorComboBox.getColor() env.prefs[dnaMinorGrooveErrorIndicatorColor_prefs_key] = _newColor return def reset_minor_groove_error_prefs(self): """ Slot for minor_groove_error_reset_PushButton. This is a reset button for the widgets in the groupbox and their associated attributes. """ self.minor_groove_error_color_ColorComboBox.setColor(env.prefs.get_default_value(dnaMinorGrooveErrorIndicatorColor_prefs_key)) self.minor_groove_error_minimum_angle_SpinBox.setValue(env.prefs.get_default_value(dnaMinMinorGrooveAngle_prefs_key)) self.minor_groove_error_maximum_angle_SpinBox.setValue(env.prefs.get_default_value(dnaMaxMinorGrooveAngle_prefs_key)) env.prefs.restore_defaults([dnaMinorGrooveErrorIndicatorColor_prefs_key, dnaMinMinorGrooveAngle_prefs_key, dnaMaxMinorGrooveAngle_prefs_key]) return # PAGE: DNA BASE ORIENTATION INDICATORS def _setupPage_DNA_Base_Orientation_Indicators(self): self.set_DNA_base_orientation_indicator_status() self.connect(self.base_orientation_indicatiors_CheckBox, SIGNAL("toggled(bool)"), self.set_DNA_base_orientation_indicator_status) #GROUPBOX: Base orientation indicator parameters connect_comboBox_with_pref(self.plane_normal_ComboBox, dnaBaseIndicatorsPlaneNormal_prefs_key) self.indicators_color_ColorComboBox.setColor(env.prefs[dnaBaseIndicatorsColor_prefs_key]) self.connect(self.indicators_color_ColorComboBox, SIGNAL("editingFinished()"), self.set_indicators_color) self.inverse_indicators_color_ColorComboBox.setColor(env.prefs[dnaBaseInvIndicatorsColor_prefs_key]) self.connect(self.inverse_indicators_color_ColorComboBox, SIGNAL("editingFinished()"), self.set_inverse_indicators_color) connect_checkbox_with_boolean_pref(self.enable_inverse_indicatiors_CheckBox, dnaBaseInvIndicatorsEnabled_prefs_key) connect_doubleSpinBox_with_pref(self.angle_threshold_DoubleSpinBox, dnaBaseIndicatorsAngle_prefs_key) connect_spinBox_with_pref(self.terminal_base_distance_SpinBox, dnaBaseIndicatorsDistance_prefs_key) return def set_DNA_base_orientation_indicator_status(self, status = None): """ Slot for base_orientation_indicatiors_CheckBox. Also, this will enable/disable the associated groupbox and it's child widgets. """ if (status == None and env.prefs[dnaBaseIndicatorsEnabled_prefs_key]) \ or status: self.base_orientation_GroupBox.setEnabled(True) self.base_orientation_indicatiors_CheckBox.setCheckState(CHECKED) env.prefs[dnaBaseIndicatorsEnabled_prefs_key] = True else: self.base_orientation_GroupBox.setEnabled(False) self.base_orientation_indicatiors_CheckBox.setCheckState(UNCHECKED) env.prefs[dnaBaseIndicatorsEnabled_prefs_key] = False return def set_indicators_color(self): """ Slot for indicators_color_ColorComboBox """ _newColor = self.indicators_color_ColorComboBox.getColor() env.prefs[dnaBaseIndicatorsColor_prefs_key] = _newColor return def set_inverse_indicators_color(self): """ Slot for inverse_indicators_color_ColorComboBox """ _newColor = self.inverse_indicators_color_ColorComboBox.getColor() env.prefs[dnaBaseInvIndicatorsColor_prefs_key] = _newColor return # PAGE: ADJUST def _setupPage_Adjust(self): """ Setup the "Adjust" page. """ # GROUPBOX: Adjust physics engine connect_comboBox_with_pref(self.physics_engine_choice_ComboBox, Adjust_minimizationEngine_prefs_key) connect_checkbox_with_boolean_pref(self.enable_electrostatics_CheckBox, electrostaticsForDnaDuringAdjust_prefs_key) # GROUPBOX: Pysics engine animation options self.watch_motion_in_realtime_CheckBox.setChecked( env.prefs[Adjust_watchRealtimeMinimization_prefs_key]) self.set_and_enable_realtime( env.prefs[Adjust_watchRealtimeMinimization_prefs_key]) self.connect(self.watch_motion_in_realtime_CheckBox, SIGNAL("toggled(bool)"), self.set_and_enable_realtime) self.constant_animation_update_RadioButton.setChecked(True) # GROUPBOX: Convergence criteria connect_doubleSpinBox_with_pref(self.endRMS_DoubleSpinBox, Adjust_endRMS_prefs_key) connect_doubleSpinBox_with_pref(self.endmax_DoubleSpinBox, Adjust_endMax_prefs_key) connect_doubleSpinBox_with_pref(self.cutoverRMS_DoubleSpinBox, Adjust_cutoverRMS_prefs_key) connect_doubleSpinBox_with_pref(self.cutoverMax_DoubleSpinBox, Adjust_cutoverMax_prefs_key) self.endRMS_DoubleSpinBox.setSpecialValueText("Automatic") self.endmax_DoubleSpinBox.setSpecialValueText("Automatic") self.cutoverRMS_DoubleSpinBox.setSpecialValueText("Automatic") self.cutoverMax_DoubleSpinBox.setSpecialValueText("Automatic") return def set_and_enable_realtime(self, state): if env.prefs[Adjust_watchRealtimeMinimization_prefs_key] != state: env.prefs[Adjust_watchRealtimeMinimization_prefs_key] = state self.animation_detail_level_RadioButtonList.setEnabled(state) return # PAGE: PLUGINS ========================================================== def _setupPage_Plugins(self): """ Setup the "Plug-ins" page. """ # GROUPBOX: Location of executables pluginList = [ "QuteMolX", \ "POV-Ray", \ "MegaPOV", \ "POV include dir", \ "GROMACS", \ "cpp", "Rosetta", "Rosetta DB"] # signal-slot connections. for name in pluginList: _pluginFunctionName = "".join([ x for x in name.lower().replace(" ","_") \ if (x in string.ascii_letters or\ x in string.digits \ or x == "_") ]) _fname = "enable_%s" % _pluginFunctionName if hasattr(self, _fname): fcall = getattr(self, _fname) if callable(fcall): if DEBUG: print "method defined: %s" % _fname self.connect(self.checkboxes[name], \ SIGNAL("toggled(bool)"), \ fcall) else: print "Attribute %s exists, but is not a callable method." else: if DEBUG: print "method missing: %s" % _fname #_fname = "set_%s_path" % _pluginFunctionName #if hasattr(self, _fname): #fcall = getattr(self, _fname) #if callable(fcall): #if DEBUG: #print "method defined: %s" % _fname #self.connect(self.choosers[name].lineEdit,\ #SIGNAL("edtingFinished()"), \ #fcall) #else: #print "Attribute %s exists, but is not a callable method." #else: #if DEBUG: #print "method missing: %s" % _fname self.connect( self.choosers["QuteMolX"].lineEdit, SIGNAL("editingFinished()"), self.set_qutemolx_path) self.connect( self.choosers["POV-Ray"].lineEdit, SIGNAL("editingFinished()"), self.set_povray_path) self.connect( self.choosers["MegaPOV"].lineEdit, SIGNAL("editingFinished()"), self.set_megapov_path) self.connect( self.choosers["POV include dir"].lineEdit, SIGNAL("editingFinished()"), self.set_pov_include_dir) self.connect( self.choosers["GROMACS"].lineEdit, SIGNAL("editingFinished()"), self.set_gromacs_path) self.connect( self.choosers["cpp"].lineEdit, SIGNAL("editingFinished()"), self.set_cpp_path) self.connect( self.choosers["Rosetta"].lineEdit, SIGNAL("editingFinished()"), self.set_rosetta_path) self.connect( self.choosers["Rosetta DB"].lineEdit, SIGNAL("editingFinished()"), self.set_rosetta_db_path) return def _hideOrShowWidgets(self): """ Permanently hides some widgets in the Preferences dialog. This provides an easy and convenient way of hiding widgets that have been added but not fully implemented. It is also possible to show hidden widgets that have a debug pref set to enable them. """ gms_and_esp_widgetList = [self.nanohive_lbl, self.nanohive_checkbox, self.nanohive_path_lineedit, self.nanohive_choose_btn, self.gamess_checkbox, self.gamess_lbl, self.gamess_path_lineedit, self.gamess_choose_btn] for widget in gms_and_esp_widgetList: if debug_pref("Show GAMESS and ESP Image UI options", Choice_boolean_False, prefs_key = True): widget.show() else: widget.hide() # NanoVision-1 nv1_widgetList = [self.nv1_checkbox, self.nv1_label, self.nv1_path_lineedit, self.nv1_choose_btn] for widget in nv1_widgetList: widget.hide() # Rosetta rosetta_widgetList = [self.rosetta_checkbox, self.rosetta_label, self.rosetta_path_lineedit, self.rosetta_choose_btn, self.rosetta_db_checkbox, self.rosetta_db_label, self.rosetta_db_path_lineedit, self.rosetta_db_choose_btn] from utilities.GlobalPreferences import ENABLE_PROTEINS for widget in rosetta_widgetList: if ENABLE_PROTEINS: widget.show() else: widget.hide() return ########## Slot methods for "Plug-ins" page widgets ################ # GROMACS slots ####################################### def set_gromacs_path(self): """ Slot for GROMACS path line editor. """ setPath = str_or_unicode(self.choosers["GROMACS"].text) env.prefs[gromacs_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[gromacs_path_prefs_key] = setPath return setPath def enable_gromacs(self, enable = True): """ If True, GROMACS path is set in Preferences>Plug-ins @param enable: Is the path set? @type enable: bool """ state = self.checkboxes["GROMACS"].checkState() if enable: if (state != CHECKED): self.checkboxes["GROMACS"].setCheckState(CHECKED) self.choosers["GROMACS"].setEnabled(True) env.prefs[gromacs_enabled_prefs_key] = True # Sets the GROMACS (executable) path to the standard location, if it exists. if not env.prefs[gromacs_path_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[gromacs_path_prefs_key] env.prefs[gromacs_path_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["GROMACS"].setText(env.prefs[gromacs_path_prefs_key]) else: if (state != UNCHECKED): self.checkboxes["GROMACS"].setCheckState(UNCHECKED) self.choosers["GROMACS"].setEnabled(False) #self.gromacs_path_lineedit.setText("") #env.prefs[gromacs_path_prefs_key] = '' env.prefs[gromacs_enabled_prefs_key] = False # cpp slots ####################################### def set_cpp_path(self): """ Slot for cpp path line editor. """ setPath = str_or_unicode(self.choosers["cpp"].text) env.prefs[cpp_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[cpp_path_prefs_key] = setPath return setPath def enable_cpp(self, enable = True): """ Enables/disables cpp plugin. @param enable: Enabled when True. Disables when False. @type enable: bool """ state = self.checkboxes["cpp"].checkState() if enable: if (state != CHECKED): self.checkboxes["cpp"].setCheckState(CHECKED) self.choosers["cpp"].setEnabled(True) env.prefs[cpp_enabled_prefs_key] = True # Sets the cpp path to the standard location, if it exists. if not env.prefs[cpp_path_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[cpp_path_prefs_key] env.prefs[cpp_path_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["cpp"].setText(env.prefs[cpp_path_prefs_key]) else: if (state != UNCHECKED): self.checkboxes["cpp"].setCheckState(UNCHECKED) self.choosers["cpp"].setEnabled(False) #self.cpp_path_lineedit.setText("") #env.prefs[cpp_path_prefs_key] = '' env.prefs[cpp_enabled_prefs_key] = False # Rosetta slots ####################################### def set_rosetta_path(self): """ Slot for Rosetta path line editor. """ setPath = str_or_unicode(self.choosers["Rosetta"].text) env.prefs[rosetta_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[rosetta_path_prefs_key] = setPath return setPath def enable_rosetta(self, enable = True): """ If True, rosetta path is set in Preferences > Plug-ins @param enable: Is the path set? @type enable: bool """ state = self.checkboxes["Rosetta"].checkState() if enable: if (state != CHECKED): self.checkboxes["Rosetta"].setCheckState(CHECKED) self.choosers["Rosetta"].setEnabled(True) env.prefs[rosetta_enabled_prefs_key] = True # Sets the rosetta (executable) path to the standard location, if it exists. if not env.prefs[rosetta_path_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[rosetta_path_prefs_key] env.prefs[rosetta_path_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["Rosetta"].setText(env.prefs[rosetta_path_prefs_key]) else: if (state != UNCHECKED): self.checkboxes["Rosetta"].setCheckState(UNCHECKED) self.choosers["Rosetta"].setEnabled(False) env.prefs[rosetta_enabled_prefs_key] = False return # Rosetta DB slots ####################################### def set_rosetta_db_path(self): """ Slot for Rosetta db path line editor. """ setPath = str_or_unicode(self.choosers["Rosetta DB"].text) env.prefs[rosetta_dbdir_prefs_key] = setPath prefs = preferences.prefs_context() prefs[rosetta_dbdir_prefs_key] = setPath return setPath def enable_rosetta_db(self, enable = True): """ If True, rosetta db path is set in Preferences > Plug-ins @param enable: Is the path set? @type enable: bool """ state = self.checkboxes["Rosetta DB"].checkState() if enable: if (state != CHECKED): self.checkboxes["Rosetta DB"].setCheckState(CHECKED) self.choosers["Rosetta DB"].setEnabled(True) env.prefs[rosetta_database_enabled_prefs_key] = True # Sets the rosetta (executable) path to the standard location, if it exists. if not env.prefs[rosetta_dbdir_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[rosetta_dbdir_prefs_key] env.prefs[rosetta_dbdir_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["Rosetta DB"].setText(env.prefs[rosetta_dbdir_prefs_key]) else: if (state != UNCHECKED): self.checkboxes["Rosetta DB"].setCheckState(UNCHECKED) self.choosers["Rosetta DB"].setEnabled(False) env.prefs[rosetta_database_enabled_prefs_key] = False return # QuteMolX slots ####################################### def set_qutemolx_path(self): """ Slot for QuteMolX path "Choose" button. """ setPath = str_or_unicode(self.choosers["QuteMolX"].text) env.prefs[qutemol_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[qutemol_path_prefs_key] = setPath return setPath def enable_qutemolx(self, enable = True): """ Enables/disables QuteMolX plugin. @param enable: Enabled when True. Disables when False. @type enable: bool """ if enable: self.choosers["QuteMolX"].setEnabled(1) env.prefs[qutemol_enabled_prefs_key] = True # Sets the QuteMolX (executable) path to the standard location, if it exists. if not env.prefs[qutemol_path_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[qutemol_path_prefs_key] env.prefs[qutemol_path_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["QuteMolX"].setText(env.prefs[qutemol_path_prefs_key]) else: self.choosers["QuteMolX"].setEnabled(0) #env.prefs[qutemol_path_prefs_key] = '' env.prefs[qutemol_enabled_prefs_key] = False # POV-Ray slots ##################################### def set_povray_path(self): """ Slot for POV-Ray path line editor. """ setPath = str_or_unicode(self.choosers["POV-Ray"].text) env.prefs[povray_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[povray_path_prefs_key] = setPath return setPath def enable_povray(self, enable = True): """ Enables/disables POV-Ray plugin. @param enable: Enabled when True. Disables when False. @type enable: bool """ if enable: self.choosers["POV-Ray"].setEnabled(1) env.prefs[povray_enabled_prefs_key] = True # Sets the POV-Ray (executable) path to the standard location, if it exists. if not env.prefs[povray_path_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[povray_path_prefs_key] env.prefs[povray_path_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["POV-Ray"].setText(env.prefs[povray_path_prefs_key]) else: self.choosers["POV-Ray"].setEnabled(0) #self.povray_path_lineedit.setText("") #env.prefs[povray_path_prefs_key] = '' env.prefs[povray_enabled_prefs_key] = False self._update_povdir_enables() #bruce 060710 # MegaPOV slots ##################################### def set_megapov_path(self): """ Slot for MegaPOV path line editor. """ setPath = str_or_unicode(self.choosers["MegaPOV"].text) env.prefs[megapov_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[megapov_path_prefs_key] = setPath return setPath def enable_megapov(self, enable = True): """ Enables/disables MegaPOV plugin. @param enable: Enabled when True. Disables when False. @type enable: bool """ if enable: self.choosers["MegaPOV"].setEnabled(1) env.prefs[megapov_enabled_prefs_key] = True # Sets the MegaPOV (executable) path to the standard location, if it exists. if not env.prefs[megapov_path_prefs_key]: _tmppaths = DEFAULT_PLUGIN_PATHS[megapov_path_prefs_key] env.prefs[megapov_path_prefs_key] = get_default_plugin_path( \ _tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["MegaPOV"].setText(env.prefs[megapov_path_prefs_key]) else: self.choosers["MegaPOV"].setEnabled(0) #self.megapov_path_lineedit.setText("") #env.prefs[megapov_path_prefs_key] = '' env.prefs[megapov_enabled_prefs_key] = False self._update_povdir_enables() #bruce 060710 # POV-Ray include slots ####################################### # pov include directory [bruce 060710 for Mac A8; will be A8.1 in Windows, not sure about Linux] def _update_povdir_enables(self): #bruce 060710 """ [private method] Call this whenever anything changes regarding when to enable the povdir checkbox, line edit, or choose button. We enable the checkbox when either of the POV-Ray or MegaPOV plugins is enabled. We enable the line edit and choose button when that condition holds and when the checkbox is checked. We update this when any relevant checkbox changes, or when showing this page. This will work by reading prefs values, so only call it from slot methods after they have updated prefs values. """ enable_checkbox = env.prefs[povray_enabled_prefs_key] or env.prefs[megapov_enabled_prefs_key] self.checkboxes["POV include dir"].setEnabled(enable_checkbox) self.choosers["POV include dir"].setEnabled(enable_checkbox) enable_edits = enable_checkbox and env.prefs[povdir_enabled_prefs_key] # note: that prefs value should and presumably does agree with self.povdir_checkbox.isChecked() return def enable_pov_include_dir(self, enable = True): #bruce 060710 """ Slot method for povdir checkbox. povdir is enabled when enable = True. povdir is disabled when enable = False. """ env.prefs[povdir_enabled_prefs_key] = not not enable self._update_povdir_enables() if enable: self.choosers["POV include dir"].setEnabled(1) env.prefs[povdir_enabled_prefs_key] = True # Sets the MegaPOV (executable) path to the standard location, if it exists. #if not env.prefs[povdir_path_prefs_key]: #_tmppaths = DEFAULT_PLUGIN_PATHS[povdir_path_prefs_key] #env.prefs[povdir_path_prefs_key] = get_default_plugin_path( \ #_tmppaths["win32"], _tmppaths["darwin"], _tmppaths["linux"]) self.choosers["POV include dir"].setText(env.prefs[povdir_path_prefs_key]) else: self.choosers["POV include dir"].setEnabled(0) #self.megapov_path_lineedit.setText("") #env.prefs[megapov_path_prefs_key] = '' env.prefs[povdir_enabled_prefs_key] = False# self.povdir_lineedit.setText(env.prefs[povdir_path_prefs_key]) return def set_pov_include_dir(self): #bruce 060710 """ Slot for Pov include dir "Choose" button. """ setPath = str_or_unicode(self.choosers["POV include dir"].text) env.prefs[povdir_path_prefs_key] = setPath prefs = preferences.prefs_context() prefs[povdir_path_prefs_key] = setPath return setPath #povdir_path = get_dirname_and_save_in_prefs(self, povdir_path_prefs_key, 'Choose Custom POV-Ray Include directory') ## note: return value can't be ""; if user cancels, value is None; ## to set "" you have to edit the lineedit text directly, but this doesn't work since ## no signal is caught to save that into the prefs db! ## ####@@@@ we ought to catch that signal... is it returnPressed?? would that be sent if they were editing it, then hit ok? ## or if they clicked elsewhere? (currently that fails to remove focus from the lineedits, on Mac, a minor bug IMHO) ## (or uncheck the checkbox for the same effect). (#e do we want a "clear" button, for A8.1?) #if povdir_path: #self.povdir_lineedit.setText(env.prefs[povdir_path_prefs_key]) ## the function above already saved it in prefs, under the same condition #return def povdir_lineedit_textChanged(self, *args): #bruce 060710 if debug_povdir_signals(): print "povdir_lineedit_textChanged",args # this happens on programmatic changes, such as when the page is shown or the choose button slot sets the text try: # note: Ideally we'd only do this when return was pressed, mouse was clicked elsewhere (with that also removing keyfocus), # other keyfocus removals, including dialog ok or cancel. That is mostly nim, # so we have to do it all the time for now -- this is the only way for the user to set the text to "". # (This even runs on programmatic sets of the text. Hope that's ok.) env.prefs[povdir_path_prefs_key] = path = str_or_unicode( self.povdir_lineedit.text() ).strip() if debug_povdir_signals(): print "debug fyi: set pov include dir to [%s]" % (path,) except: if env.debug(): print_compact_traceback("bug, ignored: ") return #def povdir_lineedit_returnPressed(self, *args): #bruce 060710 #if debug_povdir_signals(): #print "povdir_lineedit_returnPressed",args ## this happens when return is pressed in the widget, but NOT when user clicks outside it ## or presses OK on the dialog -- which means it's useless when taken alone, ## in case user edits text and then presses ok without ever pressing return. ########## End of slot methods for "Plug-ins" page widgets ########### ########## Slot methods for "General" (former name "Caption") page widgets ################ # PAGE: UNDO def _setupPage_Undo(self): """ Setup the "Undo" page. """ connect_checkbox_with_boolean_pref(self.undo_restore_view_CheckBox, undoRestoreView_prefs_key) connect_checkbox_with_boolean_pref( self.undo_automatic_checkpoints_CheckBox, undoAutomaticCheckpoints_prefs_key) connect_spinBox_with_pref(self.undo_stack_memory_limit_SpinBox, undoStackMemoryLimit_prefs_key) return # PAGE: WINDOW def _setupPage_Window(self): """ Setup the "Window" page. """ # GROUPBOX: Window Postion and Size self.connect(self.current_size_save_Button, SIGNAL("clicked()"), self.save_window_size) self.connect(self.restore_saved_size_Button, SIGNAL("clicked()"), self.restore_saved_size) self.connect(self.current_height_SpinBox, SIGNAL("valueChanged(int)"), self.change_window_size) self.connect(self.current_width_SpinBox, SIGNAL("valueChanged(int)"), self.change_window_size) ((x0, y0), (w, h)) = screen_pos_size() self.current_width_SpinBox.setRange(1, w) self.current_height_SpinBox.setRange(1, h) if not DEBUG: pos, size = _get_window_pos_size(self.w) self.current_width_spinbox.setValue(size[0]) self.current_height_spinbox.setValue(size[1]) from utilities.prefs_constants import mainwindow_geometry_prefs_key_prefix keyprefix = mainwindow_geometry_prefs_key_prefix pos, size = _get_prefs_for_window_pos_size( self.w, keyprefix) else: self.current_width_SpinBox.setValue(640) self.current_height_SpinBox.setValue(480) size = [640, 480] self.update_saved_size(size[0], size[1]) connect_checkbox_with_boolean_pref(self.save_size_on_quit_CheckBox, rememberWinPosSize_prefs_key) # GROUPBOX: Window caption format self.caption_prefix_LineEdit.setText(env.prefs[captionPrefix_prefs_key]) self.caption_suffix_LineEdit.setText(env.prefs[captionSuffix_prefs_key]) self.connect(self.caption_prefix_save_ToolButton, SIGNAL("clicked()"), self.set_caption_prefix) self.connect(self.caption_suffix_save_ToolButton, SIGNAL("clicked()"), self.set_caption_suffix) connect_checkbox_with_boolean_pref(self.display_full_path_CheckBox, captionFullPath_prefs_key) # GROUPBOX: Custom Font self.set_use_custom_font_status() self.connect(self.use_custom_font_CheckBox, SIGNAL("toggled(bool)"), self.set_use_custom_font_status) font_family = env.prefs[displayFont_prefs_key] font_size = env.prefs[displayFontPointSize_prefs_key] font = QFont(font_family, font_size) self.custom_fontComboBox.setCurrentFont(font) self.custom_font_size_SpinBox.setValue(font_size) self.connect(self.custom_fontComboBox, SIGNAL("currentFontChanged (const QFont &)"), self.change_font) self.connect(self.custom_font_size_SpinBox, SIGNAL("valueChanged(int)"), self.set_fontsize) self.connect(self.make_default_font_PushButton, SIGNAL("clicked()"), self.change_selected_font_to_default_font) return def change_window_size(self, val = 0): """ Slot for both the width and height spinboxes that change the current window size. Also called from other slots to change the window size based on new values in spinboxes. <val> is not used. """ w = self.current_width_spinbox.value() h = self.current_height_spinbox.value() if not DEBUG: self.w.resize(w,h) return def update_saved_size(self, w, h): """ Helper function to update the "Saved size" label. """ _text = "Saved size: %d pixels x %d pixels " % (w, h) self.saved_size_label.setText(_text) return def save_window_size(self): """ Slot for current_size_save_Button """ if not DEBUG: from utilities.prefs_constants import mainwindow_geometry_prefs_key_prefix keyprefix = mainwindow_geometry_prefs_key_prefix save_window_pos_size( self.w, keyprefix) # prints history message size = self.w.size() self.update_saved_size(size.width(), size.height()) else: width = self.current_width_SpinBox.value() height = self.current_height_SpinBox.value() self.update_saved_size(width, height) return def restore_saved_size(self): """ Restore the window size, but not the position, from the prefs db. """ if not DEBUG: from utilities.prefs_constants import mainwindow_geometry_prefs_key_prefix keyprefix = mainwindow_geometry_prefs_key_prefix pos, size = _get_prefs_for_window_pos_size( self.w, keyprefix) else: size = [640, 480] w = size[0] h = size[1] self.update_saved_size(w, h) self.current_width_SpinBox.setValue(w) self.current_height_SpinBox.setValue(h) self.change_window_size() return def change_window_size(self, val = 0): """ Slot for both the width and height spinboxes that change the current window size. Also called from other slots to change the window size based on new values in spinboxes. <val> is not used. """ w = self.current_width_SpinBox.value() h = self.current_height_SpinBox.value() #UNCOMMENT before committing to normal tree # self.w.resize(w,h) return def set_caption_prefix(self): """ Slot for caption_prefix_save_ToolButton. The caption is only saved to the database if the user clicks on this button. The contents of the associated LineEdit are read and stored in the database. """ prefix = str_or_unicode(self.caption_prefix_LineEdit.text()) prefix = prefix.strip() if prefix: prefix = prefix + ' ' env.prefs[captionPrefix_prefs_key] = prefix self.caption_prefix_LineEdit.setText(env.prefs[captionPrefix_prefs_key]) return def set_caption_suffix(self): """ Slot for caption_suffix_save_ToolButton. The caption is only saved to the database if the user clicks on this button. The contents of the associated LineEdit are read and stored in the database. """ suffix = str_or_unicode(self.caption_suffix_LineEdit.text()) suffix = suffix.strip() if suffix: suffix = ' ' + suffix env.prefs[captionSuffix_prefs_key] = suffix self.caption_suffix_LineEdit.setText(env.prefs[captionSuffix_prefs_key]) return def set_use_custom_font_status(self, status = None): """ Slot for use_custom_font_CheckBox. This will enable/disable all the other widgets in this groupbox """ if (status == None and env.prefs[useSelectedFont_prefs_key]) \ or status: self.custom_fontComboBox.setEnabled(True) self.custom_font_size_SpinBox.setEnabled(True) self.custom_fontComboBox.labelWidget.setEnabled(True) self.custom_font_size_SpinBox.labelWidget.setEnabled(True) self.make_default_font_PushButton.setEnabled(True) self.use_custom_font_CheckBox.setCheckState(CHECKED) env.prefs[useSelectedFont_prefs_key] = True else: self.custom_fontComboBox.setEnabled(False) self.custom_font_size_SpinBox.setEnabled(False) self.custom_fontComboBox.labelWidget.setEnabled(False) self.custom_font_size_SpinBox.labelWidget.setEnabled(False) self.make_default_font_PushButton.setEnabled(False) self.use_custom_font_CheckBox.setCheckState(UNCHECKED) env.prefs[useSelectedFont_prefs_key] = False return def change_font(self, font): """ Slot for the Font combobox. Called whenever the font is changed. """ env.prefs[displayFont_prefs_key] = str_or_unicode(font.family()) self.set_font() return def set_font(self): """ Set the current display font using the font prefs. """ use_selected_font = env.prefs[useSelectedFont_prefs_key] if use_selected_font: font = self.custom_fontComboBox.currentFont() font_family = str_or_unicode(font.family()) fontsize = self.custom_font_size_SpinBox.value() font.setPointSize(fontsize) env.prefs[displayFont_prefs_key] = font_family env.prefs[displayFontPointSize_prefs_key] = fontsize if debug_flags.atom_debug: print "set_font(): Using selected font: ", font.family(), ", size=", font.pointSize() else: # Use default font # font = self.w.defaultFont if debug_flags.atom_debug: print "set_font(): Using default font: ", font.family(), ", size=", font.pointSize() # Set font # self.w.setFont(font) return def set_fontsize(self, pointsize): """ Slot for the Font size spinbox. """ env.prefs[displayFontPointSize_prefs_key] = pointsize # self.set_font() return def change_selected_font_to_default_font(self): """ Slot for "Make the selected font the default font" button. The default font will be displayed in the Font and Size widgets. """ font = self.w.defaultFont env.prefs[displayFont_prefs_key] = str_or_unicode(font.family()) env.prefs[displayFontPointSize_prefs_key] = font.pointSize() self.set_font_widgets(setFontFromPrefs = True) # Also sets the current display font. if debug_flags.atom_debug: print "change_selected_font_to_default_font(): " \ "Button clicked. Default font: ", font.family(), \ ", size=", font.pointSize() return def set_font_widgets(self, setFontFromPrefs = True): """ Update font widgets based on font prefs. Unconnects signals from slots, updates widgets, then reconnects slots. @param setFontFromPrefs: when True (default), sets the display font (based on font prefs). @type setFontFromPrefs: bool """ if debug_flags.atom_debug: print "set_font_widgets(): Here!" if env.prefs[displayFont_prefs_key] == "defaultFont": # Set the font and point size prefs to the application's default font. # This code only called the first time NE1 is run (or the prefs db does not exist) font = self.w.defaultFont font_family = str_or_unicode(font.family()) # Note: when this used str() rather than str_or_unicode(), # it prevented NE1 from running on some international systems # (when it had never run before and needed to initialize this # prefs value). # We can now reproduce the bug (see bug 2883 for details), # so I am using str_or_unicode to try to fix it. [bruce 080529] font_size = font.pointSize() env.prefs[displayFont_prefs_key] = font_family env.prefs[displayFontPointSize_prefs_key] = font_size if debug_flags.atom_debug: print "set_font_widgets(): No prefs db. " \ "Using default font: ", font.family(), \ ", size=", font.pointSize() else: font_family = env.prefs[displayFont_prefs_key] font_size = env.prefs[displayFontPointSize_prefs_key] font = QFont(font_family, font_size) return # PAGE: REPORTS def _setupPage_Reports(self): """ Setup the "Reports" page. """ # GROUPBOX: History Preferences connect_checkbox_with_boolean_pref( self.history_include_message_serial_CheckBox, historyMsgSerialNumber_prefs_key) connect_checkbox_with_boolean_pref( self.history_include_message_timestamp_CheckBox, historyMsgTimestamp_prefs_key) return # PAGE: TOOLTIPS def _setupPage_Tooltips(self): """ Setup the "Tooltips" page. """ # GROUPBOX: Atom tooltip options connect_checkbox_with_boolean_pref(self.atom_chunk_information_CheckBox, dynamicToolTipAtomChunkInfo_prefs_key) connect_checkbox_with_boolean_pref(self.atom_mass_information_CheckBox, dynamicToolTipAtomMass_prefs_key) connect_checkbox_with_boolean_pref(self.atom_XYZ_coordinates_CheckBox, dynamicToolTipAtomPosition_prefs_key) connect_checkbox_with_boolean_pref(self.atom_XYZ_distance_CheckBox, dynamicToolTipAtomDistanceDeltas_prefs_key) connect_checkbox_with_boolean_pref(self.atom_include_vdw_CheckBox, dynamicToolTipVdwRadiiInAtomDistance_prefs_key) connect_spinBox_with_pref(self.atom_distance_precision_SpinBox, dynamicToolTipAtomDistancePrecision_prefs_key) connect_spinBox_with_pref(self.atom_angle_precision_SpinBox, dynamicToolTipBendAnglePrecision_prefs_key) # GROUPBOX: Bond tooltip options connect_checkbox_with_boolean_pref( self.bond_distance_between_atoms_CheckBox, dynamicToolTipBondLength_prefs_key) connect_checkbox_with_boolean_pref(self.bond_chunk_information_CheckBox, dynamicToolTipBondChunkInfo_prefs_key) return ########## Slot methods for top level widgets ################ def getPagenameList(self): """ Returns a list of page names (i.e. the "stack of widgets") inside prefsStackedWidget. @return: List of page names. @rtype: List @attention: Qt Designer assigns the QStackedWidget property "currentPageName" (which is not a formal attr) to the QWidget (page) attr "objectName". @see: U{B{QStackedWidget}<http://doc.trolltech.com/4/qstackedwidget.html>}. """ _pagenameList = [] for _widgetIndex in range(self.prefsStackedWidget.count()): _widget = self.prefsStackedWidget.widget(_widgetIndex) _pagename = str(_widget.objectName()) _pagenameList.append(_pagename) return _pagenameList def accept(self): """ The slot method for the 'OK' button. """ QDialog.accept(self) return def reject(self): """ The slot method for the "Cancel" button. """ # The Cancel button has been removed, but this still gets called # when the user hits the dialog's "Close" button in the dialog's # window border (upper right X). # Since I've not implemented 'Cancel', it is safer to go ahead and # save all preferences anyway. Otherwise, any changed preferences # will not be persistent (after this session). # This will need to be removed when we implement a true cancel function. # Mark 050629. QDialog.reject(self) return pass # end of class Preferences # end if __name__ == "__main__": _iconprefix = "/Users/derrickhendricks/trunks/trunk/cad/src" app = QtGui.QApplication(sys.argv) p = Preferences() sys.exit(app.exec_())
NanoCAD-master
cad/src/experimental/prefs/Preferences.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ PreferencesDialog.py This is experimental. To run, type: python PreferencesDialog.py """ import sys, os from PyQt4.Qt import * from PyQt4 import QtCore, QtGui from Ui_PreferencesDialog import Ui_PreferencesDialog # imports for testing from PM.PM_ComboBox import PM_ComboBox from PM.PM_ColorComboBox import PM_ColorComboBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_GroupBox import PM_GroupBox from PM.PM_CoordinateSpinBoxes import PM_CoordinateSpinBoxes from PM.PM_LineEdit import PM_LineEdit from PM.PM_PushButton import PM_PushButton from PM.PM_RadioButton import PM_RadioButton from PM.PM_RadioButtonList import PM_RadioButtonList from PM.PM_Slider import PM_Slider from PM.PM_TableWidget import PM_TableWidget from PM.PM_TextEdit import PM_TextEdit from PM.PM_ToolButton import PM_ToolButton from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_Dial import PM_Dial from PM.PM_SpinBox import PM_SpinBox from PM.PM_FileChooser import PM_FileChooser from PM.PM_WidgetRow import PM_WidgetRow from PM.PM_DockWidget import PM_DockWidget from PM.PM_PushButton import PM_PushButton from PM.PM_LabelRow import PM_LabelRow from PM.PM_FontComboBox import PM_FontComboBox from PM.PM_WidgetGrid import PM_WidgetGrid from PM.PM_Constants import PM_MAINVBOXLAYOUT_MARGIN from PM.PM_Constants import PM_MAINVBOXLAYOUT_SPACING from PM.PM_Constants import PM_HEADER_FRAME_MARGIN from PM.PM_Constants import PM_HEADER_FRAME_SPACING from PM.PM_Constants import PM_HEADER_FONT from PM.PM_Constants import PM_HEADER_FONT_POINT_SIZE from PM.PM_Constants import PM_HEADER_FONT_BOLD from PM.PM_Constants import PM_SPONSOR_FRAME_MARGIN from PM.PM_Constants import PM_SPONSOR_FRAME_SPACING from PM.PM_Constants import PM_TOPROWBUTTONS_MARGIN from PM.PM_Constants import PM_TOPROWBUTTONS_SPACING from PM.PM_Constants import PM_LABEL_LEFT_ALIGNMENT, PM_LABEL_RIGHT_ALIGNMENT from PM.PM_Constants import PM_ALL_BUTTONS from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from PM.PM_Constants import PM_RESTORE_DEFAULTS_BUTTON from PM.PM_Constants import PM_PREVIEW_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from utilities.icon_utilities import geticon DEBUG = True #global display preferences from utilities.constants import diDEFAULT ,diTrueCPK, diLINES from utilities.constants import diBALL, diTUBES, diDNACYLINDER GDS_INDEXES = [diLINES, diTUBES, diBALL, diTrueCPK, diDNACYLINDER] GDS_NAMES = ["Lines", "Tubes", "Ball and Stick", "CPK", "DNA Cylinder"] GDS_ICONS = ["Lines", "Tubes", "Ball_and_Stick", "CPK", "DNACylinder" ] # currently, [x][3] is not used, if it does become used by radiobuttonlist. # if that changes, this will probably break --Derrick HIGH_ORDER_BOND_STYLES = [[ 0, "Multiple cylinders", "", "multicyl"], [ 1, "Vanes", "", "vane"], [ 2, "Ribbons", "", "ribbon"] ] class ContainerWidget(QFrame): """ The container widget class for use in PageWidget. """ _rowCount = 0 _widgetList = [] _groupBoxCount = 0 _lastGroupBox = None def __init__(self, name): """ Creates a container widget within the page widget """ QFrame.__init__(self) self.name = name self.setObjectName(name) if DEBUG: self.setFrameShape(QFrame.Box) # Create vertical box layout self.vBoxLayout = QVBoxLayout(self) self.vBoxLayout.setMargin(0) self.vBoxLayout.setSpacing(0) # Create grid layout self.gridLayout = QtGui.QGridLayout() self.gridLayout.setMargin(2) self.gridLayout.setSpacing(2) # Insert grid layout in its own vBoxLayout self.vBoxLayout.addLayout(self.gridLayout) # Vertical spacer #vSpacer = QtGui.QSpacerItem(1, 1, #QSizePolicy.Preferred, #QSizePolicy.Expanding) #self.vBoxLayout.addItem(vSpacer) return def addQtWidget(self, qtWidget, column = 0, spanWidth = False): """ Add a Qt widget to this page. @param qtWidget: The Qt widget to add. @type qtWidget: QWidget """ # Set the widget's row and column parameters. widgetRow = self._rowCount widgetColumn = column if spanWidth: widgetSpanCols = 2 else: widgetSpanCols = 1 self.gridLayout.addWidget( qtWidget, widgetRow, widgetColumn, 1, widgetSpanCols ) self._rowCount += 1 return def getPmWidgetPlacementParameters(self, pmWidget): """ Returns all the layout parameters needed to place a PM_Widget in the group box grid layout. @param pmWidget: The PM widget. @type pmWidget: PM_Widget """ row = self._rowCount #PM_CheckBox doesn't have a label. So do the following to decide the #placement of the checkbox. (can be placed either in column 0 or 1 , #This also needs to be implemented for PM_RadioButton, but at present #the following code doesn't support PM_RadioButton. if isinstance(pmWidget, PM_CheckBox): spanWidth = pmWidget.spanWidth if not spanWidth: # Set the widget's row and column parameters. widgetRow = row widgetColumn = pmWidget.widgetColumn widgetSpanCols = 1 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 #set a virtual label labelRow = row labelSpanCols = 1 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT if widgetColumn == 0: labelColumn = 1 elif widgetColumn == 1: labelColumn = 0 else: # Set the widget's row and column parameters. widgetRow = row widgetColumn = pmWidget.widgetColumn widgetSpanCols = 2 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 #no label labelRow = 0 labelColumn = 0 labelSpanCols = 0 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT return widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment label = pmWidget.label labelColumn = pmWidget.labelColumn spanWidth = pmWidget.spanWidth if not spanWidth: # This widget and its label are on the same row labelRow = row labelSpanCols = 1 labelAlignment = PM_LABEL_RIGHT_ALIGNMENT # Set the widget's row and column parameters. widgetRow = row widgetColumn = 1 widgetSpanCols = 1 widgetAlignment = PM_LABEL_LEFT_ALIGNMENT rowIncrement = 1 if labelColumn == 1: widgetColumn = 0 labelAlignment = PM_LABEL_LEFT_ALIGNMENT widgetAlignment = PM_LABEL_RIGHT_ALIGNMENT 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 # Set this widget's row and column parameters. widgetRow = row + 1 # Widget is below the label. widgetColumn = 0 widgetSpanCols = 2 rowIncrement = 2 else: # No label. Just the widget. labelRow = 0 labelColumn = 0 labelSpanCols = 0 # Set the widget's row and column parameters. widgetRow = row widgetColumn = 0 widgetSpanCols = 2 rowIncrement = 1 labelAlignment = PM_LABEL_LEFT_ALIGNMENT widgetAlignment = PM_LABEL_LEFT_ALIGNMENT return widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment def addPmWidget(self, pmWidget): """ This is a reminder to Derrick and Mark to review the PM_Group class and its addPmWidget() method, since we want to support PM widget classes. """ """ Add a PM widget and its label to this group box. @param pmWidget: The PM widget to add. @type pmWidget: PM_Widget """ # Get all the widget and label layout parameters. widgetRow, \ widgetColumn, \ widgetSpanCols, \ widgetAlignment, \ rowIncrement, \ labelRow, \ labelColumn, \ labelSpanCols, \ labelAlignment = \ self.getPmWidgetPlacementParameters(pmWidget) if pmWidget.labelWidget: #Create Label as a pixmap (instead of text) if a valid icon path #is provided labelPath = str(pmWidget.label) if labelPath and labelPath.startswith("ui/"): #bruce 080325 revised labelPixmap = getpixmap(labelPath) if not labelPixmap.isNull(): pmWidget.labelWidget.setPixmap(labelPixmap) pmWidget.labelWidget.setText('') self.gridLayout.addWidget( pmWidget.labelWidget, labelRow, labelColumn, 1, labelSpanCols, labelAlignment ) # The following is a workaround for a Qt bug. If addWidth()'s # <alignment> argument is not supplied, the widget spans the full # column width of the grid cell containing it. If <alignment> # is supplied, this desired behavior is lost and there is no # value that can be supplied to maintain the behavior (0 doesn't # work). The workaround is to call addWidget() without the <alignment> # argument. Mark 2007-07-27. if widgetAlignment == PM_LABEL_LEFT_ALIGNMENT: self.gridLayout.addWidget( pmWidget, widgetRow, widgetColumn, 1, widgetSpanCols) # aligment = 0 doesn't work. else: self.gridLayout.addWidget( pmWidget, widgetRow, widgetColumn, 1, widgetSpanCols, widgetAlignment ) self._widgetList.append(pmWidget) self._rowCount += rowIncrement return # End of ContainerWidget class class PageWidget(QWidget): """ The page widget base class. """ def __init__(self, name): """ Creates a page widget named name. param name: The page name. It will be used as the tree item """ QWidget.__init__(self) self.name = name self.setObjectName(name) self.containerList = [] # Horizontal spacer hSpacer = QtGui.QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Preferred) self.hBoxLayout = QtGui.QHBoxLayout(self) self.hBoxLayout.setMargin(0) self.hBoxLayout.setSpacing(0) self.hBoxLayout.addItem(hSpacer) # add the base container widget container = self.addContainer(name + "_1") # print container # scrollArea = QScrollArea() # scrollArea.setWidget(container) # container.scrollarea = scrollArea return def insertContainer(self, containerName = None, indx = -1): """ inserts a container class named containerName in the place specified by indx """ # set indx to append to the end of the list if indx is not passed if indx < 0: indx = len(self.containerList) # create some theoretically unique name if None is given if containerName == None: containerName = self.name + "_" + str((len(self.containerList) + 1)) # create the container and name it _containerWidget = ContainerWidget(containerName) _containerWidget.setObjectName(containerName) # add the container into the page self.containerList.insert(indx, _containerWidget) self.hBoxLayout.insertWidget(indx,_containerWidget) return _containerWidget def addContainer(self, containerName = None): """ Adds a container to the end of the list and returns the container's handle """ _groupBoxCount = 0 _containerWidget = self.insertContainer(containerName) return _containerWidget def getPageContainers(self, containerKey = None): """ Returns a list of containers which the page owns. Always returns a list for consistancy. The list can be restricted to only those that have containerKey in the name. If there's only one, the programmer can do list = list[0] """ # See if we are asking for a specific container if containerKey == None: # return the whole list containers = self.containerList else: # return only the container(s) where containerKey is in the name. # this is a list comprehension search. # Also, the condition can be modified with a startswith depending # on the implementation of naming the containers. containers = [ x for x in self.containerList \ if x.objectName().find(containerKey) >= 0 ] return containers # End of PageWidget class class PreferencesDialog(QDialog, Ui_PreferencesDialog): """ The Preferences dialog class. This is experimental. pagenameList[0] always has to be a singular item, it cannot be a list. All sub-lists are interpreted as being children of the item preceding it. """ #pagenameList = ["General", #"Graphics Area", #["Zoom, Pan and Rotate", "Rulers"], #"Atoms", #"Bonds", #"DNA", #["Minor groove error indicator", #"Base orientation indicator"], #"Adjust", #"Lighting", #"Plug-ins", #"Undo", #"Window", #"Reports", #"Tooltips"] #NOTE: when creating the function names for populating the pages with # widgets... Create the function name by replacing all spaces with # underscores and removing all characters that are not ascii # letters or numbers, and appending the result to "populate_" # ex. "Zoom, Pan and Rotate" has the function: # populate_Zoom_Pan_and_Rotate() pagenameDict = {} def __init__(self): """ Constructor for the prefs dialog. """ self.pagenameList = ["General", "Graphics Area", ["Zoom, Pan and Rotate", "Rulers"], "Atoms", "Bonds", "DNA", ["Minor groove error indicator", "Base orientation indicator"], "Adjust", # "Lighting", "Plug-ins", "Undo", "Window", "Reports", "Tooltips"] QDialog.__init__(self) self.setupUi() self._setupDialog_TopLevelWidgets() self._addPages(self.pagenameList) self.populatePages() return def setupUi(self): self.setObjectName("PreferencesDialog") self.resize(QtCore.QSize(QtCore.QRect(0,0,594,574).size()).expandedTo(self.minimumSizeHint())) self.vboxlayout = QtGui.QVBoxLayout(self) self.vboxlayout.setSpacing(4) self.vboxlayout.setMargin(2) self.vboxlayout.setObjectName("vboxlayout") self.tabWidget = QtGui.QTabWidget(self) self.tabWidget.setObjectName("tabWidget") self.tab = QtGui.QWidget() self.tab.setObjectName("tab") # self.hboxlayout = QtGui.QHBoxLayout(self.tab) self.pref_splitter = QtGui.QSplitter(self.tab) # self.hboxlayout.setSpacing(4) # self.hboxlayout.setMargin(2) # self.hboxlayout.setObjectName("hboxlayout") self.pref_splitter.setObjectName("pref_splitter") self.categoriesTreeWidget = QtGui.QTreeWidget(self.pref_splitter) self.categoriesTreeWidget.setMinimumWidth(150) self.categoriesTreeWidget.setObjectName("categoriesTreeWidget") # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # self.categoriesTreeWidget.setSizePolicy(sizePolicy) # self.hboxlayout.addWidget(self.categoriesTreeWidget) self.pref_splitter.addWidget(self.categoriesTreeWidget) self.prefsStackedWidget = QtGui.QStackedWidget(self.pref_splitter) # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # self.prefsStackedWidget.setSizePolicy(sizePolicy) self.prefsStackedWidget.setObjectName("prefsStackedWidget") # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # self.pref_splitter.setSizePolicy(sizePolicy) self.pref_splitter.addWidget(self.prefsStackedWidget) self.pref_splitter.setStretchFactor(0, 2) self.pref_splitter.setStretchFactor(1, 13) self.tabWidget.addTab(self.tab,"") self.vboxlayout.addWidget(self.tabWidget) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setObjectName("hboxlayout1") self.whatsThisToolButton = QtGui.QToolButton(self) self.whatsThisToolButton.setObjectName("whatsThisToolButton") self.hboxlayout1.addWidget(self.whatsThisToolButton) spacerItem = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem) self.okButton = QtGui.QPushButton(self) self.okButton.setObjectName("okButton") self.hboxlayout1.addWidget(self.okButton) self.vboxlayout.addLayout(self.hboxlayout1) self.retranslateUi() self.tabWidget.setCurrentIndex(0) self.prefsStackedWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(self) def retranslateUi(self): self.setWindowTitle(QtGui.QApplication.translate("PreferencesDialog", "Preferences", None, QtGui.QApplication.UnicodeUTF8)) self.categoriesTreeWidget.headerItem().setText(0,QtGui.QApplication.translate("PreferencesDialog", "Categories", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("PreferencesDialog", "System Options", None, QtGui.QApplication.UnicodeUTF8)) self.okButton.setText(QtGui.QApplication.translate("PreferencesDialog", "OK", None, QtGui.QApplication.UnicodeUTF8)) def _setupDialog_TopLevelWidgets(self): """ Setup all the main dialog widgets and their signal-slot connection(s). """ self.setWindowIcon(geticon("ui/actions/Tools/Options.png")) # This connects the "itemSelectedChanged" signal generated when the # user selects an item in the "Category" QTreeWidget on the left # side of the Preferences dialog (inside the "Systems Option" tab) # to the slot for turning to the correct page in the QStackedWidget # on the right side. self.connect(self.categoriesTreeWidget, SIGNAL("itemSelectionChanged()"), self.showPage) # Connections for OK and What's This buttons at the bottom of the dialog. self.connect(self.okButton, SIGNAL("clicked()"), self.accept) self.connect(self.whatsThisToolButton, SIGNAL("clicked()"), QWhatsThis.enterWhatsThisMode) self.whatsThisToolButton.setIcon( geticon("ui/actions/Properties Manager/WhatsThis.png")) self.whatsThisToolButton.setIconSize(QSize(22, 22)) self.whatsThisToolButton.setToolTip('Enter "What\'s This?" help mode') return #def addScrollArea(self): #self.propertyManagerScrollArea = QScrollArea(self.categoriesTreeWidget) #self.propertyManagerScrollArea.setObjectName("propertyManagerScrollArea") #self.propertyManagerScrollArea.setWidget(self.categoriesTreeWidget) #self.propertyManagerScrollArea.setWidgetResizable(True) def _addPages(self, pagenameList, myparent = None): """ Creates all page widgets in pagenameList and add them to the Preferences dialog. """ if (type(pagenameList[0]) == list or \ type(pagenameList[0]) == tuple): print "Invalid tree structure with no root page." return # Run through the list and add the pages into the tree. # This is recursive so that it interpretes nested sublists based on # the structure of the list. x=-1 while x < len(pagenameList) - 1: x = x + 1 name = pagenameList[x] if DEBUG: print name page_widget = PageWidget(name) # Create a dictionary entry for the page name and it's index self.pagenameDict[name] = len(self.pagenameDict) page_tree_slot = self.addPage(page_widget, myparent) # Check if the next level is a sub-list if x + 1 <= len(pagenameList) - 1 and \ (type(pagenameList[x+1]) == list or \ type(pagenameList[x+1]) == tuple): # If so, call addPages again using the sublist and the current # item as the parent self._addPages(pagenameList[x+1], page_tree_slot) x = x + 1 return def addPage(self, page, myparent = None): """ Adds page into this preferences dialog at position index. If index is negative, the page is added at the end. param page: Page widget. type page: L{PageWidget} """ # Add page to the stacked widget self.prefsStackedWidget.addWidget(page) # Add a QTreeWidgetItem to the categories QTreeWidget. # The label (text) of the item is the page name. if not myparent: _item = QtGui.QTreeWidgetItem(self.categoriesTreeWidget) else: _item = QtGui.QTreeWidgetItem(myparent) _item.setText(0, QtGui.QApplication.translate("PreferencesDialog", page.name, None, QtGui.QApplication.UnicodeUTF8)) return _item def _addPageTestWidgets(self, page_widget): """ This creates a set of test widgets for page_widget. """ _label = QtGui.QLabel(page_widget) _label.setText(page_widget.name) page_widget.addQtWidget(_label) _checkbox = QtGui.QCheckBox(page_widget.name, page_widget) page_widget.addQtWidget(_checkbox) _pushbutton = QtGui.QPushButton(page_widget.name, page_widget) page_widget.addQtWidget(_pushbutton) _label = QtGui.QLabel(page_widget) _choices = ['choice a', 'choice b' ] _pref_ComboBox = PM_ComboBox( page_widget, label = "choices:", choices = _choices, setAsDefault = True) _pref_color = PM_ColorComboBox(page_widget, spanWidth = True) _pref_CheckBox = PM_CheckBox(page_widget, text ="nothing interesting", \ widgetColumn = 1) #N means this PM widget currently does not work. _pmGroupBox1 = PM_GroupBox( page_widget, title = "Test of GB", connectTitleButton = False) #N _endPoint1SpinBoxes = PM_CoordinateSpinBoxes(_pmGroupBox1) # duplexLengthLineEdit = \ # PM_LineEdit(page_widget, label = "something\non the next line", # text = "default text", # setAsDefault = False) pushbtn = PM_PushButton(page_widget, label = "Click here", text = "here") radio1 = PM_RadioButton(page_widget, text = "self button1") radio2 = PM_RadioButton(page_widget, text = "self button2") radiobtns = PM_RadioButtonList (_pmGroupBox1, title = "junk", label = "junk2", buttonList = [[ 1, "btn1", "btn1"], [ 2, "btn2", "btn2"]]) slider1 = PM_Slider(page_widget, label = "slider 1:") # table1 = PM_TableWidget(page_widget, label = "table:") # TE1 = PM_TextEdit(page_widget, label = "QMX") #N TB1 = PM_ToolButton(_pmGroupBox1, label = "tb1", text = "text1") radio3 = PM_RadioButton(page_widget, text = "self button3") # SB = PM_SpinBox(page_widget, label = "SB", suffix = "x2") # DBS = PM_DoubleSpinBox(page_widget, label = "test", suffix = "x3", singleStep = .1) # Dial = PM_Dial( page_widget, label = "Direction", suffix = "degrees") return def getPage(self, pagename): """ Returns the page widget for pagename. """ if not pagename in self.pagenameDict: msg = 'Preferences page unknown: pagename =%s\n' \ 'pagename must be one of the following:\n%r\n' \ % (pagename, self.pagenameList) print_compact_traceback(msg) return return self.prefsStackedWidget.widget(self.pagenameDict[pagename]) def populatePages(self): import string for name in self.pagenameDict: # create the function name by replacing spaces with "_" and # removing everything that is not an _, ascii letter, or number # and appending that to populate_ fname = "populate_%s" % "".join([ x for x in name.replace(" ","_") \ if (x in string.ascii_letters or\ x in string.digits \ or x == "_") ]) # Make sure the class has that object defined before calling it. if hasattr(self, fname): fcall = getattr(self, fname) if callable(fcall): if DEBUG: print "method defined: %s" % fname fcall(name) else: print "Attribute %s exists, but is not a callable method." else: if DEBUG: print "method missing: %s" % fname return def showPage(self, pagename = ""): """ Show the current page of the Preferences dialog. If no page is selected from the Category tree widget, show the "General" page. @param pagename: Name of the Preferences page. Default is "General". Only names found in self.pagenameList are allowed. @type pagename: string @note: This is the slot method for the "Categories" QTreeWidget. """ if not pagename: selectedItemsList = self.categoriesTreeWidget.selectedItems() if selectedItemsList: selectedItem = selectedItemsList[0] pagename = str(selectedItem.text(0)) else: pagename = 'General' if not pagename in self.pagenameDict: msg = 'Preferences page unknown: pagename =%s\n' \ 'pagename must be one of the following:\n%r\n' \ % (pagename, self.pagenameList) print_compact_traceback(msg) try: # Show page. Use the dictionary to get the index. self.prefsStackedWidget.setCurrentIndex(self.pagenameDict[pagename]) except: print_compact_traceback("Bug in showPage() ignored.") self.setWindowTitle("Preferences - %s" % pagename) #containers = self.getPage(pagename).getPageContainers() #print containers return def populate_General(self, pagename): """ Populate the General page """ print "populate_General: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] logosGroupBox = PM_GroupBox( _pageContainer, title = "Sponsor logos download permission", connectTitleButton = False) self.logo_download_RadioButtonList = \ PM_RadioButtonList (logosGroupBox, buttonList = [[ 0, "Always ask before downloading", "Always ask permission to download sponsor logos from the Nanorex server"], [ 1, "Never ask before downloading", "Never ask permission before downloading sponsor logos from the Nanorex server"], [ 2, "Never download", "Never download sponsor logos from the Nanorex server"] ]) buildChunksGroupBox = PM_GroupBox( _pageContainer, title = "Build Chunks Settings", connectTitleButton = False) self.autobondCheckBox = PM_CheckBox(buildChunksGroupBox, text ="Autobond") self.hoverHighlightCheckBox = PM_CheckBox(buildChunksGroupBox, text ="Hover highlighting") self.waterCheckBox = PM_CheckBox(buildChunksGroupBox, text ="Water") self.autoSelectAtomsCheckBox = PM_CheckBox(buildChunksGroupBox, text ="Auto select atoms of deposited objects") offsetFactorPastingGroupBox = PM_GroupBox( _pageContainer, title = "Offset factor for pasting objects", connectTitleButton = False) self.pasteOffsetForChunks_doublespinbox = PM_DoubleSpinBox(offsetFactorPastingGroupBox, label = "Chunk Objects", singleStep = 1) self.pasteOffsetForDNA_doublespinbox = PM_DoubleSpinBox(offsetFactorPastingGroupBox, label = "DNA Objects", singleStep = 1) return def populate_Tooltips(self, pagename): print "populate_Tooltips: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] atom_tooltip_options_GroupBox = PM_GroupBox(_pageContainer, title = "Atom tooltip options", connectTitleButton = False) self.atom_chunk_information_CheckBox = PM_CheckBox(atom_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Chunk Information") self.atom_mass_information_CheckBox = PM_CheckBox(atom_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Mass information") self.atom_XYZ_coordinates_CheckBox = PM_CheckBox(atom_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="XYZ coordinates") self.atom_XYZ_distance_CheckBox = PM_CheckBox(atom_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="XYZ distance deltas") self.atom_include_vdw_CheckBox = PM_CheckBox(atom_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="include Vdw radii in atom distance tooltip") self.atom_distance_precision_SpinBox = PM_SpinBox(atom_tooltip_options_GroupBox, label = "Distance precision: ", suffix = " decimal places", singleStep = 1) self.atom_angle_precision_SpinBox = PM_SpinBox(atom_tooltip_options_GroupBox, label = "Angle precision:", suffix = " decimal places", singleStep = 1) bond_tooltip_options_GroupBox = PM_GroupBox(_pageContainer, title = "Bond tooltip options", connectTitleButton = False) self.bond_distance_between_atoms_CheckBox = PM_CheckBox(bond_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Bond distance between atoms") self.bond_chunk_information_CheckBox = PM_CheckBox(bond_tooltip_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Chunk information") return def populate_Reports(self, pagename): print "populate_Reports: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] history_preferences = PM_GroupBox(_pageContainer, title = "History preferences", connectTitleButton = False) self.history_include_message_serial_CheckBox = PM_CheckBox(history_preferences, spanWidth = True, widgetColumn = 0, text ="Include message serial number") self.history_include_message_timestamp_CheckBox = PM_CheckBox(history_preferences, spanWidth = True, widgetColumn = 0, text ="Include message timestamp") return def populate_DNA(self, pagename): print "populate_DNA: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] DNA_default_values_GroupBox = PM_GroupBox(_pageContainer, title = "DNA default values", connectTitleButton = False) _choices = ["B-DNA"] self.conformation_ComboBox = PM_ComboBox(DNA_default_values_GroupBox, label = "Conformation:", labelColumn = 0, choices = _choices, setAsDefault = False) self.bases_per_turn_DoubleSpinBox = PM_DoubleSpinBox(DNA_default_values_GroupBox, label = "Bases per turn:", suffix = "", decimals = 2, singleStep = .1) self.rise_DoubleSpinBox = PM_DoubleSpinBox(DNA_default_values_GroupBox, label = "Rise:", suffix = " Angstroms", decimals = 3, singleStep = .01) self.strand1_ColorComboBox = PM_ColorComboBox(DNA_default_values_GroupBox, label = "Strand 1:") self.strand2_ColorComboBox = PM_ColorComboBox(DNA_default_values_GroupBox, label = "Strand 2:") self.segment_ColorComboBox = PM_ColorComboBox(DNA_default_values_GroupBox, label = "Segment:") self.restore_DNA_colors_PushButton = PM_PushButton(DNA_default_values_GroupBox, text = "Restore Default Colors", spanWidth = False) strand_arrowhead_display_options_GroupBox = PM_GroupBox(_pageContainer, title = "Strand arrowhead display options", connectTitleButton = False) self.show_arrows_on_backbones_CheckBox = PM_CheckBox(strand_arrowhead_display_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Show arrows on backbones") self.show_arrows_on_3prime_ends_CheckBox = PM_CheckBox(strand_arrowhead_display_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Show arrows on 3' ends") self.show_arrows_on_5prime_ends_CheckBox = PM_CheckBox(strand_arrowhead_display_options_GroupBox, spanWidth = True, widgetColumn = 0, text ="Show arrows on 5' ends") self.three_prime_end_custom_ColorComboBox = PM_ColorComboBox(strand_arrowhead_display_options_GroupBox, label = "3' end custom color:") self.five_prime_end_custom_ColorComboBox = PM_ColorComboBox(strand_arrowhead_display_options_GroupBox, label = "5' end custom color:") return def populate_Bonds(self, pagename): print "populate_Bonds: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] bond_colors_GroupBox = PM_GroupBox(_pageContainer, title = "Colors", connectTitleButton = False) self.bond_highlighting_ColorComboBox = PM_ColorComboBox(bond_colors_GroupBox, label = "Bond highlighting:") self.ball_and_stick_cylinder_ColorComboBox = PM_ColorComboBox(bond_colors_GroupBox, label = "Ball and stick cylinder:") self.bond_stretch_ColorComboBox = PM_ColorComboBox(bond_colors_GroupBox, label = "Bond stretch:") self.vane_ribbon_ColorComboBox = PM_ColorComboBox(bond_colors_GroupBox, label = "Vane/Ribbon:") self.restore_bond_colors_PushButton = PM_PushButton(bond_colors_GroupBox, text = "Restore Default Colors", spanWidth = False) misc_bond_settings_GroupBox = PM_GroupBox(_pageContainer, title = "Miscellaneous bond settings", connectTitleButton = False) self.ball_and_stick_bond_scale_SpinBox = PM_SpinBox(misc_bond_settings_GroupBox, label = "Ball and stick bond scale:", maximum = 100, suffix = "%") self.bond_line_thickness_SpinBox = PM_SpinBox(misc_bond_settings_GroupBox, label = "Bond line thickness:", minimum = 1, suffix = "pixels") high_order_bonds_GroupBox = PM_GroupBox(misc_bond_settings_GroupBox, title = "High order bonds", connectTitleButton = False) self.high_order_bonds_RadioButtonList = PM_RadioButtonList(high_order_bonds_GroupBox, buttonList = HIGH_ORDER_BOND_STYLES) self.show_bond_type_letters_CheckBox = PM_CheckBox(misc_bond_settings_GroupBox, spanWidth = True, widgetColumn = 0, text ="Show bond type letters") self.show_valence_errors_CheckBox = PM_CheckBox(misc_bond_settings_GroupBox, spanWidth = True, widgetColumn = 0, text ="Show valence errors") self.show_bond_stretch_indicators_CheckBox = PM_CheckBox(misc_bond_settings_GroupBox, spanWidth = True, widgetColumn = 0, text ="Show bond stretch indicators") return def populate_Rulers(self, pagename): print "populate_Rules: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] rulers_GroupBox = PM_GroupBox(_pageContainer, title = "Rulers", connectTitleButton = False) _choices = ["Both rulers", "Verticle ruler only", "Horizontal ruler only"] self.display_rulers_ComboBox = PM_ComboBox(rulers_GroupBox, label = "Display:", labelColumn = 0, choices = _choices, setAsDefault = False) _choices = ["Lower left", "Upper left", "Lower right", "Upper right"] self.origin_rulers_ComboBox = PM_ComboBox(rulers_GroupBox, label = "Origin:", labelColumn = 0, choices = _choices, setAsDefault = False) self.ruler_color_ColorComboBox = PM_ColorComboBox(rulers_GroupBox, label = "Color:") self.ruler_opacity_SpinBox = PM_SpinBox(rulers_GroupBox, label = "Opacity", maximum = 100, suffix = "%") self.show_rulers_in_perspective_view_CheckBox = PM_CheckBox(rulers_GroupBox, text ="Show rulers in perspective view", spanWidth = True, widgetColumn = 0) return def populate_Plugins(self, pagename): print "populate_Plugins: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] pluginList = [ "QuteMolX", "POV-Ray", "MegaPOV", "POV include dir", "GROMACS", "cpp", "Rosetta", "Rosetta DB"] #if DEBUG: #self._addPageTestWidgets(_pageContainer) executablesGroupBox = PM_GroupBox( _pageContainer, title = "Location of Executables", connectTitleButton = False) self.checkboxes = {} self.choosers = {} aWidgetList = [] _rowNumber = 0 for name in pluginList: self.checkboxes[name] = PM_CheckBox(executablesGroupBox, text = name+': ') self.choosers[name] = PM_FileChooser(executablesGroupBox, label = '', text = '' , filter = "All Files (*.*)", spanWidth = True, labelColumn = 0) aWidgetList.append( ("PM_CheckBox", self.checkboxes[name], 0, _rowNumber) ) aWidgetList.append( ("PM_FileChooser", self.choosers[name], 1, _rowNumber) ) _rowNumber = _rowNumber + 1 _widgetGrid = PM_WidgetGrid(executablesGroupBox, widgetList = aWidgetList, labelColumn = 0) if DEBUG: print self.checkboxes print self.choosers return def populate_Adjust(self, pagename): print "populate_Adjust: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] adjust_physics_engine_GroupBox = PM_GroupBox(_pageContainer, title = "Adjust physics engine", connectTitleButton = False) _choices = ["NanoDynamics-1 (Default)", "GROMACS with ND1 Force Field", "Background GROMACS with ND1 Force Field"] self.physics_engine_choice_ComboBox = PM_ComboBox(adjust_physics_engine_GroupBox, label = "", labelColumn = 0, choices = _choices, setAsDefault = False) self.enable_electrostatics_CheckBox = PM_CheckBox(adjust_physics_engine_GroupBox, spanWidth = True, widgetColumn = 0, text ="Enable electrostatics for DNA reduced model") physics_engine_animation_GroupBox = PM_GroupBox(_pageContainer, title = "Pysics engine animation options", connectTitleButton = False) self.watch_motion_in_realtime_CheckBox = PM_CheckBox(physics_engine_animation_GroupBox, spanWidth = True, widgetColumn = 0, text = "Watch motion in real time") self.constant_animation_update_RadioButton = PM_RadioButton(physics_engine_animation_GroupBox, text = "Update as often\nas possible") self.update_every_RadioButton = PM_RadioButton(physics_engine_animation_GroupBox, text = "Update every ") self.update_rate_SpinBox = PM_SpinBox(physics_engine_animation_GroupBox, minimum = 1, label = "") _choices = ["frames", "seconds", "minutes", "hours"] self.animation_detail_level_ComboBox = PM_ComboBox(physics_engine_animation_GroupBox, label = "", choices = _choices, setAsDefault = False) aWidgetList = [ ("PM_RadioButton", self.constant_animation_update_RadioButton, 0, 0), ("PM_RadioButton", self.update_every_RadioButton, 0, 1), ("PM_SpinBox", self.update_rate_SpinBox, 1, 1), ("PM_ComboBox", self.animation_detail_level_ComboBox, 2, 1) ] self.animation_detail_level_RadioButtonList = PM_WidgetGrid( physics_engine_animation_GroupBox, widgetList = aWidgetList, spanWidth = True) convergence_criteria_GroupBox = PM_GroupBox(_pageContainer, title = "Convergence criteria", connectTitleButton = False) self.endRMS_DoubleSpinBox = PM_DoubleSpinBox(convergence_criteria_GroupBox, label = "EndRMS:", maximum = 100, suffix = " pN") self.endmax_DoubleSpinBox = PM_DoubleSpinBox(convergence_criteria_GroupBox, label = "EndMax:", maximum = 100, suffix = " pN") self.cutoverRMS_DoubleSpinBox = PM_DoubleSpinBox(convergence_criteria_GroupBox, label = "CutoverRMS:", maximum = 100, suffix = " pN") self.cutoverMax_DoubleSpinBox = PM_DoubleSpinBox(convergence_criteria_GroupBox, label = "CutoverMax:", maximum = 100, suffix = " pN") return def populate_Atoms(self, pagename): print "populate_Atoms: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] atom_colors_GroupBox = PM_GroupBox(_pageContainer, title = "Colors", connectTitleButton = False) self.change_element_colors_PushButton = PM_PushButton(atom_colors_GroupBox, text = "Change Element Colors...", spanWidth = False) atom_colors_sub_GroupBox = PM_GroupBox(atom_colors_GroupBox, connectTitleButton = False) self.atom_highlighting_ColorComboBox = PM_ColorComboBox(atom_colors_sub_GroupBox, label = "Atom Highlighting:") self.bondpoint_highlighting_ColorComboBox = PM_ColorComboBox(atom_colors_sub_GroupBox, label = "Bondpoint Highlighting:") self.bondpoint_hotspots_ColorComboBox = PM_ColorComboBox(atom_colors_sub_GroupBox, label = "Bondpoint hotspots:") self.restore_element_colors_PushButton = PM_PushButton(atom_colors_sub_GroupBox, text = "Restore Default Colors", spanWidth = False) misc_atom_settings_GroupBox = PM_GroupBox(_pageContainer, title = "Miscellaneous atom options", connectTitleButton = False) _choices = ["Low", "Medium", "High", "Variable"] self.atoms_detail_level_ComboBox = PM_ComboBox(misc_atom_settings_GroupBox, label = "Level of detail:", labelColumn = 0, choices = _choices, setAsDefault = False) self.ball_and_stick_atom_scale_SpinBox = PM_SpinBox(misc_atom_settings_GroupBox, label = "", maximum = 100, suffix = "%") self.ball_and_stick_atom_scale_reset_ToolButton = PM_ToolButton(misc_atom_settings_GroupBox, iconPath = "ui/actions/Properties Manager/restore_defaults3.png") self.CPK_atom_scale_doubleSpinBox = PM_DoubleSpinBox(misc_atom_settings_GroupBox, label = "", suffix = "", decimals = 3, singleStep = 0.005) self.CPK_atom_scale_reset_ToolButton = PM_ToolButton(misc_atom_settings_GroupBox, iconPath = "ui/actions/Properties Manager/restore_defaults3.png") aWidgetList = [ ("QLabel", "Ball and stick atom scale:", 0, 0), ("PM_SpinBox", self.ball_and_stick_atom_scale_SpinBox, 1, 0), ("PM_ToolButton", self.ball_and_stick_atom_scale_reset_ToolButton, 2, 0), ("QLabel", "CPK atom scale", 0, 1), ("PM_SpinBox", self.CPK_atom_scale_doubleSpinBox, 1, 1), ("PM_ToolButton", self.CPK_atom_scale_reset_ToolButton, 2, 1) ] widget_grid_1 = PM_WidgetGrid(misc_atom_settings_GroupBox, spanWidth = True, widgetList = aWidgetList) self.overlapping_atom_indicators_CheckBox = PM_CheckBox(misc_atom_settings_GroupBox, spanWidth = True, widgetColumn = 0, text ="Overlapping atom indicators") self.force_to_keep_bonds_during_transmute_CheckBox = PM_CheckBox(misc_atom_settings_GroupBox, spanWidth = True, widgetColumn = 0, text ="Force to keep bonds during transmute:") return def populate_Window(self, pagename): print "populate_Window: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] window_position_and_size_GroupBox = PM_GroupBox(_pageContainer, title = "Window Postion and Size", connectTitleButton = False) self.current_width_SpinBox = PM_SpinBox(window_position_and_size_GroupBox, label = "", suffix = "pixels", labelColumn = 0, singleStep = 1, ) self.current_height_SpinBox = PM_SpinBox(window_position_and_size_GroupBox, label = "", labelColumn = 0, suffix = "pixels", singleStep = 1, ) self.current_size_save_Button = PM_PushButton(window_position_and_size_GroupBox, text = "Save Current") aWidgetList = [ ("QLabel", "Current size:", 0), ("PM_SpinBox", self.current_width_SpinBox, 1), ("QLabel", " x ", 2), ("PM_SpinBox", self.current_height_SpinBox, 3), ("PM_PushButton", self.current_size_save_Button, 4) ] widgetRow = PM_WidgetRow(window_position_and_size_GroupBox, title = '', spanWidth = True, widgetList = aWidgetList) #self.saved_size_x_LineEdit = PM_LineEdit(window_position_and_size_GroupBox, #label = "") #self.saved_size_y_LineEdit = PM_LineEdit(window_position_and_size_GroupBox, #label = "") self.restore_saved_size_Button = PM_PushButton(window_position_and_size_GroupBox, text = "Restore saved", label = "Saved size: 640 x 480 ") self.saved_size_label = self.restore_saved_size_Button.labelWidget #widgetRow = PM_WidgetRow(window_position_and_size_GroupBox, #title = '', #spanWidth = False, #widgetList = aWidgetList) #self.xlabel = QtGui.QLabel(widgetRow) #self.xlabel.setText("Saved size: 640 x 480") #widgetRow.gridLayout.addWidget(self.xlabel, 0, 0, 0, 0) #widgetRow.addPmWidget(self.saved_size_save_Button) self.save_size_on_quit_CheckBox = PM_CheckBox(window_position_and_size_GroupBox, text = "Always save current position and size when quitting", widgetColumn = 0, spanWidth = True) window_caption_format_GroupBox = PM_GroupBox(_pageContainer, title = "Window caption format", connectTitleButton = False) self.caption_prefix_LineEdit = PM_LineEdit(window_caption_format_GroupBox, spanWidth = False, label = "") self.caption_suffix_LineEdit = PM_LineEdit(window_caption_format_GroupBox, spanWidth = False, label = "") self.caption_prefix_save_ToolButton = PM_ToolButton(window_caption_format_GroupBox, iconPath = "ui/actions/Properties Manager/Save.png") self.caption_suffix_save_ToolButton = PM_ToolButton(window_caption_format_GroupBox, iconPath = "ui/actions/Properties Manager/Save.png") aWidgetList = [ ("QLabel", "Window caption prefix \nfor modified file: ", 0), ("PM_LineEdit", self.caption_prefix_LineEdit, 1), ("PM_ToolButton", self.caption_prefix_save_ToolButton, 2) ] widgetRow1 = PM_WidgetRow(window_caption_format_GroupBox, title = '', spanWidth = True, widgetList = aWidgetList) aWidgetList = [ ("QLabel", "Window caption suffix \nfor modified file: ", 0), ("PM_LineEdit", self.caption_suffix_LineEdit, 1), ("PM_ToolButton", self.caption_suffix_save_ToolButton, 2) ] widgetRow2 = PM_WidgetRow(window_caption_format_GroupBox, title = '', spanWidth = True, widgetList = aWidgetList) self.display_full_path_CheckBox = PM_CheckBox(window_caption_format_GroupBox, text = "Display full path of part", widgetColumn = 0, spanWidth = True) custom_font_GroupBox = PM_GroupBox(_pageContainer, title = "Custom Font", connectTitleButton = False) self.use_custom_font_CheckBox = PM_CheckBox(custom_font_GroupBox, text = "Use custom font", spanWidth = True, widgetColumn = 0) self.custom_fontComboBox = PM_FontComboBox(custom_font_GroupBox, label = "Font:", labelColumn = 0, setAsDefault = False, spanWidth = False) self.custom_font_size_SpinBox = PM_SpinBox(custom_font_GroupBox, label = "Size: ") self.make_default_font_PushButton = PM_PushButton(custom_font_GroupBox, spanWidth = True, text = "Make selected font the default font") return def populate_Graphics_Area(self, pagename): print "populate_Graphics_Area: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] gdsIconDist = dict(zip(GDS_NAMES, GDS_ICONS)) _choices = [] self.globalDisplayStyleStartupComboBox = PM_ComboBox(_pageContainer, label = "Global display style at start-up:", choices = _choices, setAsDefault = False) for gdsName in GDS_NAMES: # gds = global display style basename = gdsIconDist[gdsName] + ".png" iconPath = os.path.join("ui/actions/View/Display/", basename) self.globalDisplayStyleStartupComboBox.addItem(geticon(iconPath), gdsName) compassGroupBox = PM_GroupBox(_pageContainer, title = "Compass display settings", connectTitleButton = False) self.display_compass_CheckBox = PM_CheckBox(compassGroupBox, text = "Display compass: ", widgetColumn = 0) _choices = ["Upper right", "Upper left", "Lower left", "Lower right"] self.compass_location_ComboBox = PM_ComboBox(compassGroupBox, label = "Compass Location:", labelColumn = 0, choices = _choices, setAsDefault = False) self.display_compass_labels_checkbox = PM_CheckBox(compassGroupBox, text = "Display compass labels ", spanWidth = True, widgetColumn = 0) axesGroupBox = PM_GroupBox(_pageContainer, title = "Axes", connectTitleButton = False) self.display_origin_axis_checkbox = PM_CheckBox(axesGroupBox, text = "Display origin axis", widgetColumn = 0) self.display_pov_axis_checkbox = PM_CheckBox(axesGroupBox, text = "Display point of view (POV) axis ", spanWidth = True, widgetColumn = 0) cursor_text_GroupBox = PM_GroupBox(_pageContainer, title = "Cursor text settings", connectTitleButton = False) #self.cursor_text_CheckBox = PM_CheckBox(cursor_text_GroupBox, #text = "Cursor text", #widgetColumn = 0) self.cursor_text_font_size_SpinBox = PM_DoubleSpinBox(cursor_text_GroupBox, label = "", suffix = "pt", singleStep = 1, ) self.cursor_text_reset_Button = PM_ToolButton(cursor_text_GroupBox, iconPath = "ui/actions/Properties Manager/restore_defaults3.png") aWidgetList = [ ("QLabel", "Font size: ", 0), ("PM_DoubleSpinBox", self.cursor_text_font_size_SpinBox, 1), ("QLabel", " ", 2), ("PM_ToolButton", self.cursor_text_reset_Button, 3), ("QSpacerItem", 0, 0, 3)] widgetRow = PM_WidgetRow(cursor_text_GroupBox, title = '', spanWidth = True, widgetList = aWidgetList) self.cursor_text_color_ComboBox = PM_ColorComboBox(cursor_text_GroupBox, label = "Cursor Text color:", spanWidth = False) misc_graphics_GroupBox = PM_GroupBox(_pageContainer, title = "Other graphics options", connectTitleButton = False) self.display_confirmation_corner_CheckBox = PM_CheckBox(misc_graphics_GroupBox, text = "Display confirmation corner", widgetColumn = 0) self.anti_aliasing_CheckBox = PM_CheckBox(misc_graphics_GroupBox, text = "Enable anti-aliasing (next session)", widgetColumn = 0) return def populate_Base_orientation_indicator(self, pagename): print "populate_Base_orientation_indicator: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] self.base_orientation_indicatiors_CheckBox = PM_CheckBox(_pageContainer, text = "Display base orientation indicators", spanWidth = True, widgetColumn = 0) self.base_orientation_GroupBox = PM_GroupBox(_pageContainer, title = "Base orientation indicator parameters", connectTitleButton = False) _choices = ["View place (up)", "View place (out)", "View place (right)"] self.plane_normal_ComboBox = PM_ComboBox(self.base_orientation_GroupBox, label = "Plane normal:", choices = _choices) self.indicators_color_ColorComboBox = PM_ColorComboBox(self.base_orientation_GroupBox, label = "Indicators color:", spanWidth = False) self.inverse_indicators_color_ColorComboBox = PM_ColorComboBox(self.base_orientation_GroupBox, label = "Color:", spanWidth = False) self.enable_inverse_indicatiors_CheckBox = PM_CheckBox(self.base_orientation_GroupBox, text = "Enable inverse indicators", spanWidth = True, widgetColumn = 0) self.angle_threshold_DoubleSpinBox = PM_DoubleSpinBox(self.base_orientation_GroupBox, label = "Angle threshold:", suffix = "", maximum = 360, spanWidth = False, singleStep = .1) self.terminal_base_distance_SpinBox = PM_SpinBox(self.base_orientation_GroupBox, label = "Terminal base distance:", suffix = "", spanWidth = False, singleStep = 1) return def populate_Undo(self, pagename): print "populate_Undo: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] self.undo_restore_view_CheckBox = PM_CheckBox(_pageContainer, text = "Restore view when undoing structural changes", widgetColumn = 0, spanWidth = True) self.undo_automatic_checkpoints_CheckBox = PM_CheckBox(_pageContainer, text = "Automatic Checkpoints", widgetColumn = 0, spanWidth = True) self.undo_stack_memory_limit_SpinBox = PM_SpinBox(_pageContainer, label = "Undo stack memory limit: ", suffix = "MB", maximum = 99999, spanWidth = False, singleStep = 1) vSpacer = QtGui.QSpacerItem(1, 1, QSizePolicy.Preferred, QSizePolicy.Expanding) _pageContainer.vBoxLayout.addItem(vSpacer) return def populate_Zoom_Pan_and_Rotate(self, pagename): print "populate_Zoom_Pan_and_Rotate: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] view_rotation_settings_GroupBox = PM_GroupBox(_pageContainer, title = "View rotation settings", connectTitleButton = False) self.animate_views_CheckBox = PM_CheckBox(view_rotation_settings_GroupBox, text = "Animate between views", widgetColumn = 0) self.view_animation_speed_Slider = PM_Slider(view_rotation_settings_GroupBox, label = "", minimum = -300, maximum = -25, spanWidth = False) self.view_animation_speed_Slider.singeleStep = .01 self.view_animation_speed_reset_ToolButton = PM_ToolButton(view_rotation_settings_GroupBox, iconPath = "ui/actions/Properties Manager/restore_defaults3.png") aWidgetList = [["QLabel", "View Animation Speed: ", 0, 0], ["PM_Slider", self.view_animation_speed_Slider, 1, 0], ["PM_PushButton", self.view_animation_speed_reset_ToolButton, 3, 0], ["QLabel", "slow ", 1, 1], ["QLabel", " fast", 1, 1]] widget_grid_1 = PM_WidgetGrid(view_rotation_settings_GroupBox, spanWidth = True, widgetList = aWidgetList) self.mouse_rotation_speed_Slider = PM_Slider(view_rotation_settings_GroupBox, label = "", minimum = 30, maximum = 100, spanWidth = True) self.mouse_rotation_speed_reset_ToolButton = PM_ToolButton(view_rotation_settings_GroupBox, iconPath = "ui/actions/Properties Manager/restore_defaults3.png") aWidgetList = [["QLabel", "Mouse rotation speed: ", 0, 0], ["PM_Slider", self.mouse_rotation_speed_Slider, 1, 0], ["PM_PushButton", self.mouse_rotation_speed_reset_ToolButton, 3, 0], ["QLabel", "slow ", 1, 1], ["QLabel", " fast", 1, 1]] widget_grid_2 = PM_WidgetGrid(view_rotation_settings_GroupBox, spanWidth = True, widgetList = aWidgetList) mouse_zoom_settings_GroupBox = PM_GroupBox(_pageContainer, title = "Mouse wheel zoom settings", connectTitleButton = False) _choices = ["Pull/push wheel to zoom in/out", "Push/pull wheel to zoom in/out"] self.zoom_directon_ComboBox = PM_ComboBox(mouse_zoom_settings_GroupBox, label = "Direction:", labelColumn = 0, choices = _choices, setAsDefault = False) _choices = ["Center about cursor postion", "Center about screen"] self.zoom_in_center_ComboBox = PM_ComboBox(mouse_zoom_settings_GroupBox, label = "Zoom in:", labelColumn = 0, choices = _choices, setAsDefault = False) _choices = ["Pull/push wheel to zoom in/out", "Push/pull wheel to zoom in/out"] self.zoom_out_center_ComboBox = PM_ComboBox(mouse_zoom_settings_GroupBox, label = "Zoom out:", labelColumn = 0, choices = _choices, setAsDefault = False) self.hover_highlighting_timeout_SpinBox = PM_DoubleSpinBox(mouse_zoom_settings_GroupBox, label = "Hover highlighting\ntimeout interval", suffix = " seconds", # spanWidth = True, singleStep = .1) return def populate_Lighting(self, pagename): print "populate_Lighting: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] self.lighting_defaults_PushButton = PM_PushButton( _pageContainer, text = "Restore Defaults") directional_lighting_GroupBox = PM_GroupBox(_pageContainer, title = "Directional light properties", connectTitleButton = False) _choices = ["1 (off)", "2 (off)", "3 (off)"] self.light_ComboBox = PM_ComboBox(directional_lighting_GroupBox, label = "", labelColumn = 0, choices = _choices, setAsDefault = False) self.light_on_CheckBox = PM_CheckBox(directional_lighting_GroupBox, text = ": On", widgetColumn = 0) aWidgetList = [ ("QLabel", "Light: ", 0), ("PM_ComboBox", self.light_ComboBox, 1), ("QLabel", " ", 2), ("PM_CheckBox", self.light_on_CheckBox, 3)] _sliderline = PM_WidgetRow(directional_lighting_GroupBox, spanWidth = True, widgetList = aWidgetList) self.light_color_ColorComboBox = PM_ColorComboBox(directional_lighting_GroupBox, label = "Color:", spanWidth = False) self.ambient_light_LineEdit = PM_LineEdit(directional_lighting_GroupBox, label = "", text = ".1") self.ambient_light_Slider = PM_Slider(directional_lighting_GroupBox) aWidgetList = [["QLabel", "Ambient:", 0], ["PM_LineEdit", self.ambient_light_LineEdit, 1], ["PM_Slider", self.ambient_light_Slider, 2]] _sliderline = PM_WidgetRow(directional_lighting_GroupBox, spanWidth = True, widgetList = aWidgetList) self.difuse_light_LineEdit = PM_LineEdit(directional_lighting_GroupBox, label = "", text = ".1") self.difuse_light_Slider = PM_Slider(directional_lighting_GroupBox) aWidgetList = [["QLabel", "Difuse:", 0], ["PM_LineEdit", self.difuse_light_LineEdit, 1], ["PM_Slider", self.difuse_light_Slider, 2]] _sliderline = PM_WidgetRow(directional_lighting_GroupBox, spanWidth = True, widgetList = aWidgetList) self.specular_light_LineEdit = PM_LineEdit(directional_lighting_GroupBox, label = "", text = ".1") self.specular_light_Slider = PM_Slider(directional_lighting_GroupBox) aWidgetList = [["QLabel", "Specular:", 0], ["PM_LineEdit", self.specular_light_LineEdit, 1], ["PM_Slider", self.specular_light_Slider, 2]] _sliderline = PM_WidgetRow(directional_lighting_GroupBox, spanWidth = True, widgetList = aWidgetList) self.X_light_LineEdit = PM_LineEdit(directional_lighting_GroupBox, label = "X:", text = ".1") self.Y_light_LineEdit = PM_LineEdit(directional_lighting_GroupBox, label = "Y:", text = ".1") self.Z_light_LineEdit = PM_LineEdit(directional_lighting_GroupBox, label = "Z:", text = ".1") material_specular_properties_GroupBox = PM_GroupBox(_pageContainer, title = "Material specular properties", connectTitleButton = False) self.material_specular_properties_on_CheckBox = PM_CheckBox(material_specular_properties_GroupBox, text = ": On", widgetColumn = 0) self.material_specular_properties_finish_LineEdit = PM_LineEdit(material_specular_properties_GroupBox, label = "Finish: ", text = ".1") self.material_specular_properties_finish_Slider = PM_Slider(material_specular_properties_GroupBox) # aWidgetList = [["QLabel", "Finish:", 0], # ["PM_LineEdit", material_specular_properties_finish_LineEdit, 1], # ["PM_Slider", material_specular_properties_finish_Slider, 2]] # _sliderline = PM_WidgetRow(material_specular_properties_GroupBox, # spanWidth = True, # widgetList = aWidgetList) labelList = [["QLabel", "Metal", 0], ["QSpacerItem", 0, 0, 1], ["QLabel", "Plastic", 2]] SF1_Label = PM_WidgetRow(material_specular_properties_GroupBox, spanWidth = True, widgetList = labelList) self.material_specular_properties_shininess_LineEdit = PM_LineEdit(material_specular_properties_GroupBox, label = "Shininess: ", text = ".1") self.material_specular_properties_shininess_Slider = PM_Slider(material_specular_properties_GroupBox) # aWidgetList = [["QLabel", "Shininess:", 0], # ["PM_LineEdit", material_specular_properties_shininess_LineEdit, 1], # ["PM_Slider", material_specular_properties_shininess_Slider, 2]] # _sliderline = PM_WidgetRow(material_specular_properties_GroupBox, # spanWidth = True, # widgetList = aWidgetList) labelList = [["QLabel", "Flat", 0], ["QSpacerItem", 0, 0, 1], ["QLabel", "Glossy", 2]] SF2_Label = PM_WidgetRow(material_specular_properties_GroupBox, spanWidth = True, widgetList = labelList) self.material_specular_properties_brightness_LineEdit = PM_LineEdit(material_specular_properties_GroupBox, label = "Brightness: ", text = ".1") self.material_specular_properties_brightness_Slider = PM_Slider(material_specular_properties_GroupBox) # aWidgetList = [["QLabel", "Brightness:", 0], # ["PM_LineEdit", material_specular_properties_brightness_LineEdit, 1], # ["PM_Slider", material_specular_properties_brightness_Slider, 2]] # _sliderline = PM_WidgetRow(material_specular_properties_GroupBox, # spanWidth = True, # widgetList = aWidgetList) labelList = [["QLabel", "Low", 0], ["QSpacerItem", 0, 0, 1], ["QLabel", "High", 2]] SF3_Label = PM_WidgetRow(material_specular_properties_GroupBox, spanWidth = True, widgetList = labelList) return def populate_Minor_groove_error_indicator(self, pagename): print "populate_Minor_groove_error_indicator: %s" % pagename page_widget = self.getPage(pagename) _pageContainer = page_widget.getPageContainers() _pageContainer = _pageContainer[0] self.minor_groove_error_indicatiors_CheckBox = PM_CheckBox(_pageContainer, text = "Display minor groove error indicators", spanWidth = True, widgetColumn = 0) self.minor_groove_error_parameters_GroupBox = PM_GroupBox(_pageContainer, title = "Error indicator parameters", connectTitleButton = False) self.minor_groove_error_minimum_angle_SpinBox = PM_SpinBox(self.minor_groove_error_parameters_GroupBox, label = "Minimum angle:", suffix = " degrees", spanWidth = False, maximum = 360, singleStep = 1) self.minor_groove_error_maximum_angle_SpinBox = PM_SpinBox(self.minor_groove_error_parameters_GroupBox, label = "Maximum angle:", suffix = " degrees", spanWidth = False, maximum = 360, singleStep = 1) self.minor_groove_error_color_ColorComboBox = PM_ColorComboBox(self.minor_groove_error_parameters_GroupBox, label = "Color:", spanWidth = False) self.minor_groove_error_reset_PushButton = PM_PushButton(self.minor_groove_error_parameters_GroupBox, text = "Reset factory defaults", spanWidth = False) return # End of PreferencesDialog class #if __name__ == "__main__": #app = QtGui.QApplication(sys.argv) #pd = PreferencesDialog() #pd.show() #sys.exit(app.exec_())
NanoCAD-master
cad/src/experimental/prefs/PreferencesDialog.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ extensions.py Note: for now, this is intentionally not imported (even indirectly or conditionally) by main.py; see comment below for why. But it should remain in this directory. [bruce 071005]. Someday: handle all our custom extension modules. For now: Python interface to experimental Pyrex code -- mainly just needs to fail gracefully if its compiled form (a Python extension) is not there, or doesn't work in a drastic way. In future, might also make sure it's up-to-date, tell you how to remake it if not, and handle all extensions instead of just one or just Pyrex extensions. $Id$ This can't be called pyrex_test.py since then "import pyrex_test" would be ambiguous. We want that to import the extension module... and this file might as well evolve to try to handle all the extensions at once, so it gets a different more general name. This fits the idea that this module contains only rarely-edited glue code, with the real development action in the Pyrex source code (.pyx file). For plans and status related to our use of Pyrex, see: http://www.nanoengineer-1.net/mediawiki/index.php?title=Integrating_Pyrex_into_the_Build_System See README-Pyrex for the list of related files and their roles. How to build: % make pyx (see also the wiki page listed above) How to test: [updated, bruce 071005, and retested on my Mac] optional: in this source file, change debug_pyrex_test to True below. But don't commit that change. In NE1's run py code debug menu item, type "import extensions"; review the console prints for whether this succeeded; then type "extensions.initialize()" and again review the console prints; then use debug menu -> other -> count bonds. If it failed, follow build instructions in README-Pyrex and/or pyrex_text.pyx. (I don't know how similar your python environment needs to be to NE1's for that to work.) Possible errors when you run "import extensions" or "extensions.initialize()": ImportError: No module named pyrex_test -- you need to build it, e.g. "make pyx" in cad/src. Fatal Python error: Interpreter not initialized (version mismatch?) -- this is a Mac-specific problem related to the old bug 1724, caused by an interaction between an Apple bug, a link error on our part, and having another Python installed on your Mac -- typically in /Library/Frameworks. When this happens to me, I can fix it by running the shell commands: % cd /Library/Frameworks/Python.framework/Versions % sudo mv 2.3 2.3-DISABLED and rerunning NE1. (That problem may occur, and the above fix works for me, whether I run NE1 directly as a developer or use the (Mac-specific) ALTERNATE_CAD_SRC_PATH feature.) """ __author__ = 'bruce' have_pyrex_test = False debug_pyrex_test = False ## was debug_flags.atom_debug, changed to 0 for A7 release by bruce 060419 import foundation.env as env from utilities.debug import register_debug_menu_command, call_func_with_timing_histmsg, print_compact_traceback # I think it's safe for the following pyrex_test import to be attempted even by # source analysis tools which import single files. Either they'll have # pyrex_test.so (or the Windows equivalent) and succeed, or not have it and fail, # but that failure won't print anything if the debug flags above have not been # modified, or cause other harm. So I'm leaving this attemped import at toplevel. # # If this causes trouble, this import can be moved inside initialize() # if nbonds and have_pyrex_test are declared as module globals. # # Note that it's NOT safe to add "import extensions" to main.py, even inside # a conditional and/or to be run only on user request, until the build # process compiles and includes pyrex_test.so (or the Windows equivalent); # otherwise py2app or py2exe might get confused about that dynamic library # being required but not present. # # [bruce 071005] try: from pyrex_test import nbonds #e verify it's up-to-date? (could ask it for version and compare to a hardcoded version number in this file...) #e run a self-test and/or run our own test on it? have_pyrex_test = True except: if debug_pyrex_test: ### this condition will become "if 1" when developers are required to have Pyrex installed print_compact_traceback("debug_pyrex_test: exception importing pyrex_test or something inside it: ") print "debug_pyrex_test: Can't import pyrex_test; we'll define stub functions for its functions," print "but trying to use them will raise an exception; see README-Pyrex for how to fix this." def nbonds(mols): # stub function; in some cases it might be useful to define a correct but slow stub instead of a NIM stub "stub function for nbonds" assert 0, "nbonds NIM, since we couldn't import pyrex_test extension module; see README-Pyrex" pass pass # whether we now have the real nbonds or a stub function, make it available for testing in a menu. 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) ) 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 def initialize(): #bruce 071005 added this wrapping function if have_pyrex_test: register_debug_menu_command("count bonds (pyrex_test)", count_bonds_cmd) else: register_debug_menu_command("count bonds (stub)", count_bonds_cmd) return # end
NanoCAD-master
cad/src/experimental/pyrex_test/extensions.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ setup.py Distutils setup file -- tells distutils how to rebuild our custom extension modules. $Id$ This file is NOT meant to be imported directly by nE-1. One way to run it might be "make extensions"; see Makefile in this directory. A more direct way is to ask your shell to do python setup.py build_ext --inplace (I don't know if that works on Windows.) Running this makes some output files and subdirectories, and prints lots of output. I think it only recompiles what needs to be recompiled (based on modtimes), but I'm not sure. (I've had a hard time finding any documentation about the internal workings of distutils, though it's easy to find basic instructions about how to use it.) == For now [051202], all our custom extension modules are written in Pyrex, and we have exactly one, which is just for testing our use of Pyrex and our integration of Pyrex code into our release-building system. For plans and status related to our use of Pyrex, see: http://www.nanoengineer-1.net/mediawiki/index.php?title=Integrating_Pyrex_into_the_Build_System See README-Pyrex for the list of related files and their roles. This is based on the Pyrex example file Pyrex-0.9.3/Demos/Setup.py. """ __author__ = 'bruce' import sys from distutils.core import setup from distutils.extension import Extension if (__name__ == '__main__'): print "running cad/src/setup.py, sys.argv is %r" % (sys.argv,) # ['setup.py', 'build_ext', '--inplace'] # note: this is NOT the same setup.py that is run during Mac release building # by autoBuild.py. That one lives in Distribution or Distribution/tmp, # whereever you run autoBuild from. (I don't know if other platforms ever run setup.py then.) # [bruce 070427 comment] 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 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) setup( name = 'xxx', #k doc says name and version are required, but it works w/o version and with this stub name. ext_modules=[ Extension("pyrex_test", ["pyrex_test.pyx"]), ], cmdclass = {'build_ext': build_ext} ) # this exit reminds people not to "import setup" from nE-1 itself! print "setup.py finished; exiting." sys.exit(0)
NanoCAD-master
cad/src/experimental/pyrex_test/setup.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ NE1 simulation-related API. """
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_Simulation/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Encapsulates all the particulars of a simulation. The L{SimSpecification} class is essentially a hierarchical parameter set that describes a cross-package compatible simulation specification. All reusable configuration is captured here including motion paths and jigs. The object model makes use of L{Parameter} objects to store most of the data. Parameter objects encapsulate information necessary for viewing and editing single parameters via some GUI. Parameter objects are instantiated via a ParameterFactory based on a given key which maps to a unique parameter in the SimSpecification keyname-space. See L{Parameter.ParameterFactory} for a description of the reserved keynames. The following is the object model of the SimSpecification module: IMAGE_1 The following is an example SimSpecification as it would appear in XML:: <simSpecification name="Dual-H abstraction"> <description> Abstraction of two hydrogens from the DC10 deposition tooltip. </description> <parameter key="timestep" value="0.1e-15" /> <parameter key="startStep" value="0" /> <parameter key="maxSteps" value="10000" /> <parameter key="stepsPerFrame" value="10" /> <parameter key="environmentTemperature" value="300.0" /> <parameter key="environmentPressure" value="100000.0" /> <input name="abstractor"> <parameter key="file" value="abstractor.mmp" /> </input> <input name="seed"> <parameter key="file" value="diamond-fragment.mmp" /> </input> <motionPath name="MotionPath1"> <interval> <parameter key="start" value="0.0" /> <parameter key="end" value="180.0e-15" /> <velocity> <parameter key="fixed" value="true" /> </velocity> </interval> <interval> <parameter key="start" value="180e-15" /> <parameter key="end" value="2345e-15" /> <linearforce> <parameter key="speed" value="200.0" /> <parameter key="componentsXYZ" value="0.0 -5.0e-9 0.0" /> </linearforce> </interval> </motionPath> <motionPath name="Anchor1"> <interval> <parameter name="start" value="0.0" /> <parameter name="end" value="3300.0e-15" /> <velocity> <parameter key="fixed" value="true" /> </velocity> </interval> </motionPath> <operation name="Force Field/Quantum Chemistry"> <parameter key="action" value="dynamics" /> <method name="ND-1"> <parameter key="engine" value="NanoDynamics-1" /> <parameter key="atomSet" value="BulkAtomSet1" /> </method> <method name="GAMESS"> <parameter key="engine" value="GAMESS" /> <parameter key="atomSet" value="Tooltip1" /> <parameter key="method" value="Hartree-Fock" /> <parameter key="basisSet" value="3-21G" /> <parameter key="functional" value="" /> <parameter key="multiplicity" value="auto" /> <parameter key="integrator" value="coarse" /> <parameter key="energyAccuracty" value="1.0e-5" /> <parameter key="maxConvergenceAttempts" value="10" /> <parameter key="unscripted" value="no" /> <parameter key="applyFrom" value="0.0" /> <parameter key="applyTo" value="20.0e-12" /> </method> <constraint> <parameter key="motion" value="MotionPath1" /> <parameter key="atomSet" value="DC10" /> </constraint> <constraint> <parameter key="motion" value="Anchor1" /> <parameter key="atomSet" value="H-abstractor" /> </constraint> <measurement> <parameter key="measure" value="Thermo1" /> <parameter key="atomSet" value="H-abstractor" /> </measurement> </operation> <preSimulationChecks> <parameter key="all" value="false" /> <parameter key="detectUnMinimized" value="true" /> <parameter key="checkJigSanity" value="true" /> <parameter key="detectUnusedJigs" value="false" /> <parameter key="detectReactionPoints" value="true" /> <parameter key="checkSpinMultiplicity" value="true" /> </preSimulationChecks> </simSpecification> Packages may add their own custom parameters and they will be stored along with the reserved-key parameters. Custom parameters can be specified with the information necessary for viewing and editing them via some GUI. Here is what a fully defined parameter would look like in XML:: <parameter key="simFlowScript" value="/Users/bh/tooltip_action.tcl"> <label>Workflow script</label> <widget>filechooser</widget> <extension>.tcl</extension> <tooltip>Simulation workflow script file</tooltip> </parameter> """ from Parameter import ParameterSet class SimInput(ParameterSet): """Simulation input files. See L{SimSpecification} for context.""" def __init__(self, name): """Constructs a SimInput with the given name.""" groupName = "Input files" def getName(self): """Returns this SimInput's name.""" pass def setName(self, name): """Sets this SimInput's name.""" pass class Action(ParameterSet): """ An external effect applied to a set of atoms. See L{SimSpecification} for context. This is an abstract/interface class and should not be instantiated. """ pass class Velocity(Action): """ A fixed velocity applied to a set of atoms. See L{SimSpecification} for context. """ def __init__(self): """Constructs a Velocity object.""" groupName = "Velocity" class LinearForce(Action): """ A force applied to a set of atoms. See L{SimSpecification} for context. """ def __init__(self): """Constructs a LinearForce object.""" groupName = "Linear force" class Torque(Action): """ A rotary force applied to a set of atoms. See L{SimSpecification} for context. """ def __init__(self): """Constructs a Torque object.""" groupName = "Torque" class Interval(ParameterSet): """ A span of time and associated Action. See L{SimSpecification} for context. """ def __init__(self): """Constructs an Interval object.""" groupName = "Interval" def getAction(self): """Returns the Action subclass for this interval.""" pass def setAction(self, Action): """ Sets the Action subclass for this interval. Clobbers any existing Action. """ pass class MotionPath(ParameterSet): """ A description of motion during simulation. See L{SimSpecification} for context. """ def __init__(self, name): """Constructs a MotionPath with the given name.""" groupName = "Motion path" def getName(self): """Returns this MotionPath's name.""" pass def setName(self, name): """Sets this MotionPath's name.""" pass def getIntervalArray(self): """Returns this MotionPath's Interval as an array.""" pass def addInterval(self, interval): """Adds the given Interval and returns an Interval index.""" pass def deleteInterval(self, intervalIndex): """Deletes the Interval with the given index from this MotionPath.""" pass class Method(ParameterSet): """A simulation scheme. See L{SimSpecification} for context.""" def __init__(self): """Constructs a Method object.""" groupName = "Method" class Constraint(ParameterSet): """Application of a Motion path on an atom set.""" def __init__(self): """Constructs a Constraint object.""" groupName = "Constraint" class Measurement(ParameterSet): """Application of a Measure on an atom set.""" def __init__(self): """Constructs a Measurement object.""" groupName = "Measurement" class Operation(ParameterSet): """Describes the components of the actual simulation process.""" def __init__(self): """Constructs an Operation object.""" groupName = "Operation" class SimSpecification(ParameterSet): """ Encapsulates all the particulars of a simulation such as input files, entity traversal, level of theory, calculation, motion, and results. """ def __init__(self, name): """Constructs a SimSpecification with the given name.""" groupName = "Simulation specification" def loadFromFile(self, filepath): """ Loads this SimSpecification from the given filepath. @return: (0=successful or non-zero error code), (error description) """ pass def writeToFile(self, filepath): """ Writes this SimSpecification to the given filepath. @return: (0=successful or non-zero error code), (error description) """ pass def getName(self): """Returns this SimSpecification's name.""" pass def setName(self, name): """Sets this SimSpecification's name.""" pass def getDescription(self): """Returns this SimSpecification's description.""" pass def setDescription(self): """Sets this SimSpecification's description.""" pass def getParameter(self, key): """ Returns the Parameter with the given key. A blank Parameter is returned if no Parameter with the given key has been set. """ pass def getParameterArray(self): """Returns this object's Parameters in an array.""" pass def setParameter(self, Parameter): """ Sets the given parameter. Any existing Parameter with the same key will be clobbered. """ pass def getSimInputArray(self): """Returns this SimSpecification's SimInputs in an array.""" pass def addSimInput(self, Input): """ Adds the given SimInput. Any existing SimInput with the same name will be clobbered. """ pass def getMotionPathArray(self): """Returns this SimSpecification's MotionPaths in an array.""" pass def addMotionPath(self, MotionPath): """ Adds the given MotionPath. Any existing MotionPath with the same name will be clobbered. """ pass def getOperation(self): """Returns this SimSpecification's Operation.""" pass def setOperation(self, Operation): """ Sets the given Operation. Any existing Operation will be clobbered. """ pass def getPreSimulationChecks(self): """ Returns this SimSpecification's pre-simulation check Parameters in an array. """ pass def addPreSimulationCheck(self, Parameter): """ Adds the given pre-simulation check Parameter. Any existing pre-check with the same key will be clobbered. """ pass
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_Simulation/SimSpecification.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Encapsulates the information necessary for viewing and editing single parameters via some GUI. The following is the object model of the Parameter module: IMAGE_2 """ class Parameter: """ A GUI editable key/value pair. When newly constructed, the value is officially un-set (see the L{getValue} method.) This is an abstract/interface class and should not be instantiated. """ def __init__(self, key): """ Constructs a Parameter object with the given key - should only be called by L{ParameterFactory}. """ hasValue = 0; def getKey(self): """ Returns the dotted descriptor of what this parameter is. """ pass def getValue(self): """ Returns whether this Parameter has a set value, and what that value is. @return: (0=no value set, 1=value set), (value) """ pass def setValue(self, value): """ Sets the value of this Parameter. """ pass def unSetValue(self): """ Un-sets this Parameter's value. """ hasValue = 0; class ParameterFactory: """ Creates fully configured Parameter subclass objects. Key names are dot-separated based on the L{SimSpecification} object model. Here is the list of reserved key names: B{simSpec.timestep} [float seconds] - The amount of time between the calculations of a system's state. Widget: lineedit, min=0.05e-15, max=5.00e-15, default=0.1e-15, suffix=s B{simSpec.startStep} [integer] - The number of the first step - usually zero, but may be non-zero when a simulation is continuing on fromwhere a previous simulation stopped. Widget: lineedit, min=0, max=-1, default=0 and etc. etc. for B{simSpec.}maxSteps, stepsPerFrame, environmentTemperature, environmentPressure, workingDirectory B{simSpec.input.}type, file B{simSpec.motionPath.interval.}start, end B{simSpec.motionPath.interval.velocity.}fixed, xyzComponents, etc. B{simSpec.operation.}action B{simSpec.operation.}engine, atomSet, method, basisSet, functional, multiplicity, integrator, energyAccuracy, maxConvergenceAttempts, unscripted, applyFrom, applyTo B{simSpec.operation.constraint.}motion, atomSet B{simSpec.operation.measurement.}measure, atomSet B{simSpec.preSimChecks.}all, detectUnMinimized, checkJigSanity, detectUnusedJigs, detectReactionPoints, checkSpinMultiplicity """ def createParameter(self, key): """Returns a fully configured Parameter subclass for the given key.""" pass class ParameterSet: """A set of Parameters.""" def getGroupName(self): """Returns this ParameterSet's group name for GUI use.""" return self.groupName def getParameter(self, key): """ Returns whether or not the Parameter with the given key is in this set, and the Parameter itself if it is. @return: (0=the Parameter for the given key is not in this set, 1=the Parameter is present), (the Parameter) """ pass def getParameterArray(self): """ Returns this object's Parameters in an array in the correct order. The correct order is determined by each Parameter's "order" attribute. """ pass def setParameter(self, Parameter): """ Sets the given parameter. Any existing Parameter with the same key will be clobbered. """ # Insert the Parameter such that the array remains sorted by # Parameter.order pass # <table> # <tr><td><b>Keyword<br>[Type Units]</b></td> # <td align="center"><b>Meaning</b></td></tr> # <tr><td>name<br>[string]</td> # <td valign="top">The simulation name.</td></tr> # <tr><td>description<br>[string]</td> # <td valign="top">A description of the simulation.</td></tr> # <tr><td nowrap >timestep<br>[float seconds]</td> # <td valign="top">The amount of time between the calculations of a system's state.</td></tr> # <tr><td>startStep<br>[integer]</td> # <td valign="top">The number of the first step - usually zero, but may be non-zero when a simulation is continuing on from where a previous simulation stopped.</td></tr> # <tr><td>maxSteps<br>[integer]</td> # <td valign="top">The maximum number of steps to simulate.</td></tr> # <tr><td>stepsPerFrame<br>[integer]</td> # <td valign="top">The number of steps to aggregate into a single frame of data.</td> # <tr><td>environmentTemperature<br>[float Kelvin]</td> # <td valign="top">The simulation environment temperature.</td> # <tr><td>environmentPressure<br>[float Pascals]</td> # <td valign="top">The simulation environment pressure.</td> # <tr><td>workflow</td> # <td valign="top">Specific configuration about the simulation workflow or process. # <table> # <tr><td>inputFiles<br>[string]</td> # <td valign="top">A list of input files. # <table> # <tr><td>filePath<br>[string]</td> # <td valign="top">The input file path.</td></tr> # <tr><td>fileType<br>[string]</td> # <td valign="top">The input file type: MMP, PDB, etc.</td></tr> # </table> # </td></tr> # <tr><td>outputFile<br>[string]</td> # <td valign="top">An output file path.</td></tr> # </table> # </td></tr> # </table>
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_Simulation/Parameter.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Adjusts the positions of the given atoms so as to minimize the structure's total energy. """ from NE1_Simulation.Parameter import Parameter class EnergyMinimizer: """ Adjusts the positions of the given atoms so as to minimize the structure's total energy. """ def minimize(self, structure, parameters): """ Minimizes the given structure with the given parameters. When NE1 starts up, it reads some description of the EnergyMinimizer plugin to load which includes a list of Parameters to use for the minimizer configuration dialog. @param structure: whatever NE1 structure object @param parameters: an array of L{NE1_Simulation.Parameter.Parameter} objects @return: the minimized structure object """ pass
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_CorePlugins/EnergyMinimizer.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Plugin APIs that interface directly with the NE1 core. """
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_CorePlugins/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ NE1 core-library-related API. """
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_Lib/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ NE1 core-library-related API. """ class NE1_Lib: """ Core NE1 methods (to support the NH1 wizard.) This API is just to give an idea - still needs to be thought through. The premise of the getXxxUI() methods is that NE1 shall provide a set of common UI for things for consistency, ie, so that the user only needs to learn one widget for model tree node selection, and the same widget for node selection is used everywhere. """ def getConstraintsSelectorUI(self): """ Returns the UI for selecting constraints. """ pass def getMeasurementsSelectorUI(self): """ Returns the UI for selecting measurements. """ pass def getAtomSetSelectorUI(self): """ Returns the UI for selecting atom set nodes from the model tree. """ pass def detectUnMinized(self): """ Detects and reports whether there are un-minimized structures in any of the simulation input files. """ pass def checkJigSanity(self): """ Checks whether there are any unreasonable jig parameters in the simulation. """ pass def detectUnusedJigs(self): """ Detects and reports whether there are any unused jigs in the input MMP files. """ pass def detectReactionPoints(self): """ Detects and reports reaction points found in the structures in the input files. """ pass def checkSpinMultiplicity(self): """ Reports on spin mulitiplicity. """ pass
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_Lib/NE1_Lib.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ A job that the NE1 Job Manager schedules and monitors. """ class NE1_Job: """ A job that the NE1 Job Manager schedules and monitors. Subclasses know how to run themselves and can be polled. This is an abstract/interface class and should not be instantiated. The subclasses know how to run themselves and can be polled, etc. The NH1_Job, when run, would communicate with the NH1 instance to launch itself. The NE1 Job Manager could poll the NH1_Job for status. The NH1_Job could provide call-backs to indicate simulation completion, failures, etc. """ def getPriority(self): """ Returns the priority of this job. @return: (0=low, 1=normal, 2=high) """ pass def setPriority(self, priority): """ Sets the priority for this job. @param priority: 0=low, 1=normal, 2=high """ pass def run(self): """ Starts this job. """ pass def pause(self, location): """ Pauses this job in-, or out-of-, memory. @param location: 0=in-memory, 1=out-of-memory """ pass def resume(self): """ Resumes this job from the paused state. """ pass def abort(self): """ Abort this job. """ pass def getStatus(self): """ Returns the status of this job. @return: (0=idle, 1=running, 2=paused, 3=aborted, 4=failure), (% complete), (text message) """ pass def getAlertEmailAddress(self): """ Returns the email address to notify when this job completes or fails. """ pass def setAlertEmailAddress(self, emailAddress): """ Sets the email address to notify when this job completes or fails. """ pass def getPopUpNE1_Alert(self): """ Returns 1 if NE1 should pop up an alert when this job completes or fails, and 0 otherwise. """ pass def setPopUpNE1_Alert(self, popUp): """ Sets whether NE1 should pop up an alert when this job completes or fails. @param popUp: (1=do pop up an alert, 0=don't pop up an alert) """ pass def getSchedule(self): """ Returns the time this job is scheduled to run. @return: (0=later, 1=now), (the later U{datetime<http://docs.python.org/lib/datetime-datetime.html>} object) """ pass def setSchedule(self, nowOrLater, laterDatetime): """ Sets the time to run the job. @param nowOrLater: 0=later, 1=now @param laterDatetime: the later U{datetime<http://docs.python.org/lib/datetime-datetime.html>} object """ pass
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_JobManagement/NE1_Job.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ NE1 job-management-related API. """
NanoCAD-master
cad/src/experimental/NH1_Integration/lib/NE1_JobManagement/__init__.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ Encapsulates a simulation results data store. The main class in this module is L{SimResultsDataStore}. The L{SimResultsBond} class is really just a container for bond information. """ class SimResultsBond: """ A chemical bond. See L{SimResultsDataStore} for context. """ def __init__(self, atomId_1, atomId_2, order): """ Constructs a SimResultsBond with the given atom identifiers and order. """ self.atomId_1 = atomId_1 self.atomId_2 = atomId_2 self.order = order class SimResultsDataStore: """ Encapsulates a simulation results data store. B{Atom Records Alignment -} The arrays of atom identifiers, positions, and velocities within a given frame are aligned. So the contents at index X of all three arrays correspond to the same atom. B{Extension Data -} Extension data can be stored in each frame. Such data could be used to plot graphs, for example. Extension data exists as named floating point numbers, integers, floating point number arrays, and integer arrays inside a named data-set. """ def openDataStore(self, directory): """ Opens the simulation results data store, found in the given directory, for read/write access. @return: (0=successful or non-zero error code), (error description) """ print 'directory=%s' % directory return 0 def getNotes(self): """Returns the user's notes for these simulation results.""" pass def setNotes(self, notes): """Sets the user's notes for these simulation results.""" pass def getName(self): """Returns the simulation name.""" pass def setName(self, name): """Sets the simulation name.""" pass def getDescription(self): """Returns the simulation description.""" pass def setDescription(self, description): """Sets the simulation description.""" pass def getTimestep(self): """Returns the simulation timestep in seconds.""" pass def setTimestep(self, timestep): """ Sets the simulation timestep. @param timestep: duration in seconds """ pass def getStartStep(self): """Returns the simulation starting step number.""" pass def setStartStep(self, startStep): """Sets the simulation starting step number.""" pass def getMaxSteps(self): """Returns the maximum number of steps to simulate.""" pass def setMaxSteps(self, maxSteps): """Sets the maximum number of steps to simulate.""" pass def getStepsPerFrame(self): """Returns the number of steps per frame.""" pass def setStepsPerFrame(self, stepsPerFrame): """Sets the number of steps per frame.""" pass def getEnvironmentTemperature(self): """Returns the simulation environment temperature in Kelvin.""" pass def setEnvironmentTemperature(self, temperature): """ Sets the simulation environment temperature. @param temperature: in Kelvin """ pass def getEnvironmentPressure(self): """Returns the simulation environment pressure in Pascals.""" pass def setEnvironmentPressure(self, pressure): """ Sets the simulation environment pressure. @param pressure: in Pascals """ pass def getFilePathKeys(self): """ Returns an array of file path keys. These file paths are for simulation specification files, simulation workflow scripts, template files, etc. """ pass def getFilePath(self, key): """Returns the file path associated with the given key.""" pass def setFilePath(self, key, filePath): """Associates the given file path with the given key.""" pass def getRunResult(self): """ Returns the simulation run's result and failure message if the simulation failed. @return: (0=success, 1=still running, 2=failure, 3=aborted), (failure message) """ pass def setRunResult(self, code, message): """ Sets the simulation run's result and failure message. @param code: 0=success, 1=still running, 2=failure, 3=aborted @param message: description of a simulation failure """ pass def getStepCount(self): """Returns the number of steps successfully simulated.""" pass def setStepCount(self, count): """Sets the number of steps successfully simulated.""" pass def getStartTime(self): """ Returns the simulation start time. @return: a U{datetime<http://docs.python.org/lib/datetime-datetime.html>} object set to the simulation's start time """ pass def setStartTime(self, startTime): """ Sets the simulation start time. @param startTime: a U{datetime<http://docs.python.org/lib/datetime-datetime.html>} object set to the simulation's start time """ pass def getCPU_RunningTime(self): """Returns the simulation CPU running time in seconds.""" pass def setCPU_RunningTime(self, cpuRunningTime): """ Set the simulation CPU running time. @param cpuRunningTime: in seconds """ pass def getWallRunningTime(self): """Returns the simulation wall running time in seconds.""" pass def setWallRunningTime(self, wallRunningTime): """ Sets the simulation wall running time. @param wallRunningTime: in seconds """ pass def getExtDataNames(self): """Returns an array of extension data-set names.""" pass def getExtDataKeys(self, extDataSetName): """ Returns an array of extension data-set keys for a given extension data-set. """ pass def getExtDataFloat(self, extDataSetName, key): """ Returns a floating point value stored in the extension data-set with the given key. """ pass def getExtDataInt(self, extDataSetName, key): """ Returns an integer value stored in the extension data-set with the given key. """ pass def getExtDataFloatArray(self, extDataSetName, key): """ Returns an array of floating point values stored in the extension data-set with the given key. """ pass def getExtDataIntArray(self, extDataSetName, key): """ Returns an array of integers stored in the extension data-set with the given key. """ pass def setExtDataFloat(self, extDataSetName, key, value): """ Sets a floating point value stored in the extension data-set with the given key. """ pass def setExtDataInt(self, extDataSetName, key, value): """ Sets an integer value stored in the extension data-set with the given key. """ pass def setExtDataFloatArray(self, extDataSetName, key, floatArray): """ Sets an array of floating point values stored in the extension data-set with the given key. """ pass def setExtDataIntArray(self, extDataSetName, key, intArray): """ Sets an array of integers stored in the extension data-set with the given key. """ pass def getFrameSetNames(self): """ Returns an array of frame-set names. These frame-set names are used to get/set frame data. """ pass def addFrameSet(self, name, aggregationMode): """ Adds a frame-set with the given name and aggregation mode. @param aggregationMode: 0=per-time-step values are averaged (default), 1=last per-time-step value is used """ pass def removeFrameSet(self, name): """Removes the frame-set with the given name.""" pass def getFrameCount(self, frameSetName): """Returns the number of frames in a frame-set.""" pass def getFrameTimes(self, frameSetName): """Returns an array of frame times (in seconds) for a frame-set.""" pass def getFrameTime(self, frameSetName, frameIndex): """Returns a specific frame time (in seconds) for a frame-set.""" pass def addFrame(self, frameSetName, time): """ Adds a frame to the specified frame-set. @param time: the frame's time in seconds """ pass def removeFrame(self, frameSetName, frameIndex): """Removes a frame from the specified frame-set.""" pass def getFrameAtomIds(self, frameSetName): """Returns an array of atom identifiers for a frame-set.""" pass def setFrameAtomIds(self, frameSetName, atomIds): """Sets the array of atom identifiers for a frame-set.""" pass def getFrameAtomPositions(self, frameSetName, frameIndex): """ Returns an array of Cartesian atom positions for a specified frame. Each position is an array of length 3 corresponding to x, y, z coordinates in meters. """ pass def setFrameAtomPositions(self, frameSetName, frameIndex, positions): """ Sets the array of Cartesian atom positions for a specified frame. @param positions: an array of arrays of length 3 corresponding to x, y, z coordinates for each atom in meters """ pass def getFrameAtomVelocities(self, frameSetName, frameIndex): """ Returns an array of atom velocities for a specified frame. Each velocity is an array of length 3 corresponding to the x, y, z components of the atom's velocity in m/s. """ pass def setFrameAtomVelocities(self, frameSetName, frameIndex, velocities): """ Sets the array of atom velocities for a specified frame. @param velocities: an array of arrays of length 3 corresponding to the x, y, z components for each atom's velocity in m/s """ pass def getFrameBonds(self, frameSetName, frameIndex): """Returns an array of SimResultsBond objects for a specified frame.""" pass def setFrameBonds(self, frameSetName, frameIndex, bonds): """Sets the array of SimResultsBond objects for a specified frame.""" pass def getFrameTotalEnergy(self, frameSetName, frameIndex): """Returns the total energy for the specified frame in Joules.""" pass def setFrameTotalEnergy(self, frameSetName, frameIndex, totalEnergy): """ Sets the total energy for the specified frame. @param totalEnergy: in Joules """ pass def getFrameIdealTemperature(self, frameSetName, frameIndex): """Returns the ideal temperature for the specified frame in Kelvin.""" pass def setFrameIdealTemperature(self, frameSetName, frameIndex, temperature): """ Sets the ideal temperature for the specified frame. @param temperature: in Kelvin """ pass def getFramePressure(self, frameSetName, frameIndex): """Returns the pressure for the specified frame in Pascals.""" pass def setFramePressure(self, frameSetName, frameIndex, pressure): """ Sets the pressure for the specified frame. @param pressure: in Pascals """ pass def getFrameExtDataNames(self, frameSetName): """Returns an array of extension data-set names for a given frame-set.""" pass def getFrameExtDataKeys(self, frameSetName, extDataSetName): """ Returns an array of extension data-set keys for a given extension data-set. """ pass def getFrameExtDataFloat(self, frameSetName, frameIndex, extDataSetName, key): """ Returns a floating point value stored in the specified frame for the given key. """ pass def getFrameExtDataInt(self, frameSetName, frameIndex, extDataSetName, key): """ Returns an integer value stored in the specified frame for the given key. """ pass def getFrameExtDataFloatArray(self, frameSetName, frameIndex, extDataSetName, key): """ Returns an array of floating point values stored in the specified frame for the given key. """ pass def getFrameExtDataIntArray(self, frameSetName, frameIndex, extDataSetName, key): """ Returns an array of integers stored in the specified frame for the given key. """ pass def setFrameExtDataFloat(self, frameSetName, frameIndex, extDataSetName, key, value): """ Sets a floating point value stored in the specified frame for the given key. """ pass def setFrameExtDataInt(self, frameSetName, frameIndex, extDataSetName, key, value): """ Sets an integer value stored in the specified frame for the given key. """ pass def setFrameExtDataFloatArray(self, frameSetName, frameIndex, extDataSetName, key, floatArray): """ Sets an array of floating point values stored in the specified frame for the given key. """ pass def setFrameExtDataIntArray(self, frameSetName, frameIndex, extDataSetName, key, intArray): """ Sets an array of integers stored in the specified frame for the given key. """ pass
NanoCAD-master
cad/src/experimental/NH1_Integration/HDF5_SimResults/lib/NE1_Simulation/SimResultsDataStore.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ NE1 simulation-related API. """
NanoCAD-master
cad/src/experimental/NH1_Integration/HDF5_SimResults/lib/NE1_Simulation/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import os, sys seq = 'gattaca' n = len(seq) strands = 2 # NAMOT seems broken for one strand? Am I using it wrong? ######################################################### # # We will need to ask Paul R to help us understand these distortions. # I can see what a few of them are doing, but not all. # # There is also a probable confusion bug between the "bu" and "pt" # parameters. See src/input.c lines 1086 and 1102, and notice that # they appear to be reversed, judging by the names of the fields they # are changing. # # Base parameters bu = 0.0 # twists the bases perpendicular to helical axis op = 0.0 pt = 0.0 # makes the inner part of each base dip by that angle # Unit parameters # These are applied to the bases and sugars, but NOT to the phosphates?? dx = 0.0 dy = 0.0 dz = 0.0 # additional space between bases, unlike x and y, this is cumulative twist = 0.0 tilt = 0.0 # does some kind of A-DNA-like twist that I don't get roll = 10.0 ################################################### def use_pynamot(): """NAMOT includes a Python interface (pynamot.so, pynamot.dll). We can use this (assuming NE-1 is able to find it), but there are possible license implications to doing it this way. """ sys.path += ['/usr/local/libexec', '/usr/local/lib'] import pynamot pynamot.Cmd('generate %s d b %s' % (" sd"[strands], seq)) if True: pynamot.Cmd('modify unit dx g 1:1 1:%d %f' % (n, dx)) pynamot.Cmd('modify unit dy g 1:1 1:%d %f' % (n, dy)) pynamot.Cmd('modify unit dz g 1:1 1:%d %f' % (n, dz)) pynamot.Cmd('modify unit twist g 1:1 1:%d %f' % (n, twist)) pynamot.Cmd('modify unit tilt g 1:1 1:%d %f' % (n, tilt)) pynamot.Cmd('modify unit roll g 1:1 1:%d %f' % (n, roll)) pynamot.Cmd('write pdb foo.pdb') def use_cmd_line(): # The '-nogui' option comes from our special version of main.c. namot = os.popen('namot -nogui', 'w') namot.write('generate %s d b %s\n' % (" sd"[strands], seq)) if False: namot.write('modify base bu 1:1:1 1:%d:%d %f\n' % (n, strands, bu)) namot.write('modify base op 1:1:1 1:%d:%d %f\n' % (n, strands, op)) namot.write('modify base pt 1:1:1 1:%d:%d %f\n' % (n, strands, pt)) if True: namot.write('modify unit dx l 1:1 1:%d %f\n' % (n, dx)) namot.write('modify unit dy l 1:1 1:%d %f\n' % (n, dy)) namot.write('modify unit dz l 1:1 1:%d %f\n' % (n, dz)) namot.write('modify unit twist l 1:1 1:%d %f\n' % (n, twist)) namot.write('modify unit tilt l 1:1 1:%d %f\n' % (n, tilt)) namot.write('modify unit roll l 1:1 1:%d %f\n' % (n, roll)) namot.write('write pdb foo.pdb\n') namot.write('quit\n') namot.close() use_cmd_line() #use_pynamot() #os.system('babel foo.pdb foo.mmp') os.system('rasmol foo.pdb')
NanoCAD-master
cad/src/experimental/namot/hack.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import sys import distutils.sysconfig import distutils.ccompiler class FakeCompiler: def __init__(self): self.compiler_type = distutils.ccompiler.get_default_compiler() def set_executables(self, **kw): for k in kw: setattr(self, k, kw[k]) mcc = FakeCompiler() distutils.sysconfig.customize_compiler(mcc) if len(sys.argv) < 2: import pprint pprint.pprint(mcc.__dict__) else: for arg in sys.argv[1:]: cmd = getattr(mcc, arg) if cmd.startswith("gcc ") or cmd.startswith("g++ "): cmd = cmd[4:] print cmd
NanoCAD-master
cad/src/experimental/pyrex-example/distutils_compile_options.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. __author__ = "Will" import sys, os, Pyrex def find_pyrexc(): if sys.platform == 'darwin': x = os.path.dirname(Pyrex.__file__).split('/') return '/'.join(x[:-4] + ['bin', 'pyrexc']) elif sys.platform == 'linux2': if os.path.exists('/usr/bin/pyrexc'): return '/usr/bin/pyrexc' if os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find pyrexc') else: # windows return 'python c:/Python' + sys.version[:3] + '/Scripts/pyrexc.py'
NanoCAD-master
cad/src/experimental/pyrex-example/findpyrex.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. __author__ = 'oleksandr' from Interval import * from Triple import * """box representation""" class Box: def __init__(self, *args): """box constructor""" self.x = Interval() self.y = Interval() self.z = Interval() if len(args) == 0: pass if len(args) == 3: self.x, self.y, self.z = args def __str__(self): """returns the box in a textual form""" s = "" s += "%s " % self.x s += "%s " % self.y s += "%s " % self.z return s def Empty(self): """clear box""" self.x.Empty() self.y.Empty() self.z.Empty() def Center(self): """calculate center""" return Triple(self.x.Center(),self.y.Center(),self.z.Center()) def Min(self): """calculate min""" return Triple(self.x.min,self.y.min,self.z.min) def Max(self): """calculate max""" return Triple(self.x.max,self.y.max,self.z.max) def Extent(self): """calculate extent""" return Triple(self.x.Extent(),self.y.Extent(),self.z.Extent()) def Contains(self, p): """box contains point""" return self.x.Contains(p.x) and self.y.Contains(p.y) and self.z.Contains(p.z) def Enclose(self, p): """adjust box""" self.x.Enclose(p.x) self.y.Enclose(p.y) self.z.Enclose(p.z)
NanoCAD-master
cad/src/experimental/oleksandr/Box.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. __author__ = 'oleksandr' """interval representation""" class Interval: def __init__(self, *args): """interval constructor""" self.min = 0 self.max = 0 if len(args) == 0: pass if len(args) == 2: self.min, self.max = args def __str__(self): """returns the interval in a textual form""" s = "" s += "%s " % self.min s += "%s " % self.max return s def Empty(self): """clear interval""" self.min = 1000000 self.max = -1000000 def Center(self): """calculate center""" return (self.max + self.min) / 2 def Extent(self): """calculate extent""" return (self.max - self.min) / 2 def Point(self, u): """calculate point""" return (1 - u) * self.min + u * self.max def Normalize(self, u): """normalization""" return (u - self.min) / (self.max - self.min) def Contains(self, p): """interval contains point""" return p >= self.min and p <= self.max def Enclose(self, p): """adjust interval""" if (p < self.min): self.min = p; if (p > self.max): self.max = p;
NanoCAD-master
cad/src/experimental/oleksandr/Interval.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import sys import distutils.sysconfig import distutils.ccompiler class FakeCompiler: def __init__(self): self.compiler_type = distutils.ccompiler.get_default_compiler() def set_executables(self, **kw): for k in kw: setattr(self, k, kw[k]) mcc = FakeCompiler() distutils.sysconfig.customize_compiler(mcc) if len(sys.argv) < 2: import pprint pprint.pprint(mcc.__dict__) else: for arg in sys.argv[1:]: cmd = getattr(mcc, arg) if cmd.startswith("gcc ") or cmd.startswith("g++ "): cmd = cmd[4:] print cmd
NanoCAD-master
cad/src/experimental/oleksandr/distutils_compile_options.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. __author__ = 'oleksandr' import types, operator, math """3D vector representation""" class Triple: def __init__(self, *args): """vector constructor""" self.x = 0 self.y = 0 self.z = 0 if len(args) == 0: pass if len(args) == 1: if isinstance(args[0], types.InstanceType): self.x = args[0].x self.y = args[0].y self.z = args[0].z elif isinstance(args[0], types.ListType): self.x = args[0][0] self.y = args[0][1] self.z = args[0][2] else: self.x = args[0] self.y = args[0] self.z = args[0] if len(args) == 2: self.x = args[1][0] - args[0][0] self.y = args[1][1] - args[0][1] self.z = args[1][2] - args[0][2] if len(args) == 3: self.x, self.y, self.z = args def __str__(self): """returns the triple in a textual form""" s = "" s += "%s " % self.x s += "%s " % self.y s += "%s " % self.z return s def Len2(self): """square of vector length""" return self.x * self.x + self.y * self.y + self.z * self.z def Len(self): """vector length""" return math.sqrt(self.Len2()) def Normalize(self): """normalizes vector to unit length""" length = self.Len(); self.x /= length self.y /= length self.z /= length return self def Greatest(self): """calculate greatest value""" if self.x > self.y: if self.x > self.z: return self.x else: return self.z else: if self.y > self.z: return self.y else: return self.z def __add__( self, rhs ): """operator a + b""" t = Triple(rhs) return Triple(self.x + t.x, self.y + t.y, self.z + t.z) def __radd__( self, lhs ): """operator b + a""" t = Triple(lhs) t.x += self.x t.y += self.y t.z += self.z return t def __sub__( self, rhs ): """operator a - b""" t = Triple(rhs) return Triple(self.x - t.x, self.y - t.y, self.z - t.z) def __rsub__( self, lhs ): """operator b - a""" t = Triple(lhs) t.x -= self.x t.y -= self.y t.z -= self.z return t def __mul__( self, rhs ): """operator a * b""" t = Triple(rhs) return Triple(self.x * t.x, self.y * t.y, self.z * t.z) def __rmul__( self, lhs ): """operator b * a""" t = Triple(lhs) t.x *= self.x t.y *= self.y t.z *= self.z return t def __div__( self, rhs ): """operator a / b""" t = Triple(rhs) return Triple(self.x / t.x, self.y / t.y, self.z / t.z) def __rdiv__( self, lhs ): """operator b / a""" t = Triple(lhs) t.x /= self.x t.y /= self.y t.z /= self.z return t def __mod__( self, rhs ): """operator a % b (scalar product)""" r = self.x * rhs.x + self.y * rhs.y + self.z * rhs.z return r def __neg__( self): """operator -a""" return Triple(-self.x, -self.y, -self.z) def Dot(lhs, rhs ): """function dot(a, b) (scalar product)""" r = lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z return r
NanoCAD-master
cad/src/experimental/oleksandr/Triple.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. __author__ = "Will" import sys, os, Pyrex def find_pyrexc(): if sys.platform == 'darwin': x = os.path.dirname(Pyrex.__file__).split('/') return '/'.join(x[:-4] + ['bin', 'pyrexc']) elif sys.platform == 'linux2': if os.path.exists('/usr/bin/pyrexc'): return '/usr/bin/pyrexc' if os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find pyrexc') else: # windows return 'python c:/Python' + sys.version[:3] + '/Scripts/pyrexc.py'
NanoCAD-master
cad/src/experimental/oleksandr/findpyrex.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ >... anything I'm doing wrong? Not overriding QGLWidget's necessary methods that draw things, paintGL, resizeGL, maybe an init method. GLPane shows the way, so does the smaller ThumbView. But it's easier and more relevant to NE1 to forget about learning (for now) to make your own GL context aka QGLWidget, and just use NE1's, like we did to demo brad's code in selectMode.py, where if some debug flag is set, we replace mode.Draw with his own drawing code. I doubt you need to override anything higher up than mode.Draw, but if you do, you can add debug flags to GLPane to call your own code instead of what it now does inside paintGL. Or patch into it at runtime, like this: # in your test code glpane = assy.w.glpane def mypaintGL(): bla glpane.paintGL = mypaintGL # this does *not* get the GLPane (self) as arg 1 # but it gets whatever other args paintGL usually gets """ import CruftDialog from qt import * from qtcanvas import * from qtgl import * from OpenGL.GL import * import Numeric import sys import random import time import foo class MyGLWidget(QGLWidget): def __init__(self, parent, name, shareWidget=None): """ """ if shareWidget: self.shareWidget = shareWidget #bruce 051212 format = shareWidget.format() QGLWidget.__init__(self, format, parent, name, shareWidget) if not self.isSharing(): print "Request of display list sharing is failed." return else: QGLWidget.__init__(self, parent, name) # point of view, and half-height of window in Angstroms self.pov = Numeric.array((0.0, 0.0, 0.0)) self.scale = 10.0 #self.quat = Q(1, 0, 0, 0) self.selectedObj = None # clipping planes, as percentage of distance from the eye self.near = 0.66 self.far = 2.0 # start in perspective mode self.ortho = False #True self.initialised = False self.backgroundColor = (0.5, 0.5, 0.5) # gray def initializeGL(self): glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) glMatrixMode(GL_MODELVIEW) glLoadIdentity() return def resetView(self): '''Subclass can override this method with different <scale>, so call this version in the overridden version. ''' self.pov = Numeric.array((0.0, 0.0, 0.0)) #self.quat = Q(1, 0, 0, 0) def resizeGL(self, width, height): """Called by QtGL when the drawing window is resized. """ self.width = width self.height = height glViewport(0, 0, self.width, self.height) if not self.initialised: self.initialised = True def _setup_projection(self, glselect = False): #bruce 050608 split this out; 050615 revised docstring """Set up standard projection matrix contents using aspect, vdist, and some attributes of self. (Warning: leaves matrixmode as GL_PROJECTION.) Optional arg glselect should be False (default) or a 4-tuple (to prepare for GL_SELECT picking). """ glMatrixMode(GL_PROJECTION) glLoadIdentity() scale = self.scale #bruce 050608 used this to clarify following code near, far = self.near, self.far if glselect: x,y,w,h = glselect gluPickMatrix( x,y, w,h, glGetIntegerv( GL_VIEWPORT ) #k is this arg needed? it might be the default... ) if self.ortho: glOrtho( - scale * self.aspect, scale * self.aspect, - scale, scale, self.vdist * near, self.vdist * far ) else: glFrustum( - scale * near * self.aspect, scale * near * self.aspect, - scale * near, scale * near, self.vdist * near, self.vdist * far) return def paintGL(self): """Called by QtGL when redrawing is needed. For every redraw, color & depth butter are cleared, view projection are reset, view location & orientation are also reset. """ if not self.initialised: return c = self.backgroundColor glClearColor(c[0], c[1], c[2], 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.aspect = (self.width + 0.0)/(self.height + 0.0) self.vdist = 6.0 * self.scale self._setup_projection() glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(0.0, 0.0, -self.vdist) #q = self.quat #glRotatef(q.angle*180.0/pi, q.x, q.y, q.z) glTranslatef(self.pov[0], self.pov[1], self.pov[2]) #self.drawModel() foo.foo() class Cruft(CruftDialog.CruftDialog): ANIMATION_DELAY = 50 # milliseconds COLOR_CHOICES = ( # Wonder Bread builds strong bodies twelve ways. # Oh wait, now these are the eBay colors. QColor(Qt.red), QColor(Qt.yellow), QColor(Qt.green), QColor(Qt.blue) ) def __init__(self, parent=None, name=None, modal=0, fl=0): CruftDialog.CruftDialog.__init__(self,parent,name,modal,fl) foo.init() glformat = QGLFormat() glformat.setStencil(True) # self.qglwidget = QGLWidget(glformat, self.frame1, "glpane") self.qglwidget = MyGLWidget(glformat, self.frame1) self.qglwidget.resizeGL(400, 400) def pushButton1_clicked(self): self.app.quit() def __paintEvent(self, e): """Draw a colorful collection of lines and circles. """ foo.foo() if False: print 'paintEvent', sys.stdout.flush() if False: # Here is how to draw stuff using PyQt p = QPainter() size = self.frame1.size() w, h = size.width(), size.height() p.begin(self.frame1) p.eraseRect(0, 0, w, h) for i in range(100): color = random.choice(self.COLOR_CHOICES) p.setPen(QPen(color)) p.setBrush(QBrush(color)) x1 = w * random.random() y1 = h * random.random() if random.random() < 0.5: x2 = w * random.random() y2 = h * random.random() p.drawLine(x1, y1, x2, y2) else: x2 = 0.05 * w * random.random() y2 = x2 p.drawEllipse(x1, y1, x2, y2) p.flush() p.end() def main(): app = QApplication(sys.argv) cr = Cruft() cr.app = app app.setMainWidget(cr) cr.show() cr.update() app.exec_loop() if __name__ == "__main__": main()
NanoCAD-master
cad/src/experimental/LearningOpenGL/Cruft.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """Try to do all the OpenGL stuff in Python, on the theory that C extensions are hard to debug. """ import CruftDialog from qt import * from qtcanvas import * from qtgl import * from OpenGL.GL import * import Numeric import sys import random import time import foo _FONT_DATA = [ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x18\x18\x00\x00\x18\x18\x18\x18\x18\x18\x18", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x36\x36\x36\x36", "\x00\x00\x00\x66\x66\xff\x66\x66\xff\x66\x66\x00\x00", "\x00\x00\x18\x7e\xff\x1b\x1f\x7e\xf8\xd8\xff\x7e\x18", "\x00\x00\x0e\x1b\xdb\x6e\x30\x18\x0c\x76\xdb\xd8\x70", "\x00\x00\x7f\xc6\xcf\xd8\x70\x70\xd8\xcc\xcc\x6c\x38", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x18\x1c\x0c\x0e", "\x00\x00\x0c\x18\x30\x30\x30\x30\x30\x30\x30\x18\x0c", "\x00\x00\x30\x18\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x18\x30", "\x00\x00\x00\x00\x99\x5a\x3c\xff\x3c\x5a\x99\x00\x00", "\x00\x00\x00\x18\x18\x18\xff\xff\x18\x18\x18\x00\x00", "\x00\x00\x30\x18\x1c\x1c\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00\x00", "\x00\x00\x00\x38\x38\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x60\x60\x30\x30\x18\x18\x0c\x0c\x06\x06\x03\x03", "\x00\x00\x3c\x66\xc3\xe3\xf3\xdb\xcf\xc7\xc3\x66\x3c", "\x00\x00\x7e\x18\x18\x18\x18\x18\x18\x18\x78\x38\x18", "\x00\x00\xff\xc0\xc0\x60\x30\x18\x0c\x06\x03\xe7\x7e", "\x00\x00\x7e\xe7\x03\x03\x07\x7e\x07\x03\x03\xe7\x7e", "\x00\x00\x0c\x0c\x0c\x0c\x0c\xff\xcc\x6c\x3c\x1c\x0c", "\x00\x00\x7e\xe7\x03\x03\x07\xfe\xc0\xc0\xc0\xc0\xff", "\x00\x00\x7e\xe7\xc3\xc3\xc7\xfe\xc0\xc0\xc0\xe7\x7e", "\x00\x00\x30\x30\x30\x30\x18\x0c\x06\x03\x03\x03\xff", "\x00\x00\x7e\xe7\xc3\xc3\xe7\x7e\xe7\xc3\xc3\xe7\x7e", "\x00\x00\x7e\xe7\x03\x03\x03\x7f\xe7\xc3\xc3\xe7\x7e", "\x00\x00\x00\x38\x38\x00\x00\x38\x38\x00\x00\x00\x00", "\x00\x00\x30\x18\x1c\x1c\x00\x00\x1c\x1c\x00\x00\x00", "\x00\x00\x06\x0c\x18\x30\x60\xc0\x60\x30\x18\x0c\x06", "\x00\x00\x00\x00\xff\xff\x00\xff\xff\x00\x00\x00\x00", "\x00\x00\x60\x30\x18\x0c\x06\x03\x06\x0c\x18\x30\x60", "\x00\x00\x18\x00\x00\x18\x18\x0c\x06\x03\xc3\xc3\x7e", "\x00\x00\x3f\x60\xcf\xdb\xd3\xdd\xc3\x7e\x00\x00\x00", "\x00\x00\xc3\xc3\xc3\xc3\xff\xc3\xc3\xc3\x66\x3c\x18", "\x00\x00\xfe\xc7\xc3\xc3\xc7\xfe\xc7\xc3\xc3\xc7\xfe", "\x00\x00\x7e\xe7\xc0\xc0\xc0\xc0\xc0\xc0\xc0\xe7\x7e", "\x00\x00\xfc\xce\xc7\xc3\xc3\xc3\xc3\xc3\xc7\xce\xfc", "\x00\x00\xff\xc0\xc0\xc0\xc0\xfc\xc0\xc0\xc0\xc0\xff", "\x00\x00\xc0\xc0\xc0\xc0\xc0\xc0\xfc\xc0\xc0\xc0\xff", "\x00\x00\x7e\xe7\xc3\xc3\xcf\xc0\xc0\xc0\xc0\xe7\x7e", "\x00\x00\xc3\xc3\xc3\xc3\xc3\xff\xc3\xc3\xc3\xc3\xc3", "\x00\x00\x7e\x18\x18\x18\x18\x18\x18\x18\x18\x18\x7e", "\x00\x00\x7c\xee\xc6\x06\x06\x06\x06\x06\x06\x06\x06", "\x00\x00\xc3\xc6\xcc\xd8\xf0\xe0\xf0\xd8\xcc\xc6\xc3", "\x00\x00\xff\xc0\xc0\xc0\xc0\xc0\xc0\xc0\xc0\xc0\xc0", "\x00\x00\xc3\xc3\xc3\xc3\xc3\xc3\xdb\xff\xff\xe7\xc3", "\x00\x00\xc7\xc7\xcf\xcf\xdf\xdb\xfb\xf3\xf3\xe3\xe3", "\x00\x00\x7e\xe7\xc3\xc3\xc3\xc3\xc3\xc3\xc3\xe7\x7e", "\x00\x00\xc0\xc0\xc0\xc0\xc0\xfe\xc7\xc3\xc3\xc7\xfe", "\x00\x00\x3f\x6e\xdf\xdb\xc3\xc3\xc3\xc3\xc3\x66\x3c", "\x00\x00\xc3\xc6\xcc\xd8\xf0\xfe\xc7\xc3\xc3\xc7\xfe", "\x00\x00\x7e\xe7\x03\x03\x07\x7e\xe0\xc0\xc0\xe7\x7e", "\x00\x00\x18\x18\x18\x18\x18\x18\x18\x18\x18\x18\xff", "\x00\x00\x7e\xe7\xc3\xc3\xc3\xc3\xc3\xc3\xc3\xc3\xc3", "\x00\x00\x18\x3c\x3c\x66\x66\xc3\xc3\xc3\xc3\xc3\xc3", "\x00\x00\xc3\xe7\xff\xff\xdb\xdb\xc3\xc3\xc3\xc3\xc3", "\x00\x00\xc3\x66\x66\x3c\x3c\x18\x3c\x3c\x66\x66\xc3", "\x00\x00\x18\x18\x18\x18\x18\x18\x3c\x3c\x66\x66\xc3", "\x00\x00\xff\xc0\xc0\x60\x30\x7e\x0c\x06\x03\x03\xff", "\x00\x00\x3c\x30\x30\x30\x30\x30\x30\x30\x30\x30\x3c", "\x00\x03\x03\x06\x06\x0c\x0c\x18\x18\x30\x30\x60\x60", "\x00\x00\x3c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x3c", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc3\x66\x3c\x18", "\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x18\x38\x30\x70", "\x00\x00\x7f\xc3\xc3\x7f\x03\xc3\x7e\x00\x00\x00\x00", "\x00\x00\xfe\xc3\xc3\xc3\xc3\xfe\xc0\xc0\xc0\xc0\xc0", "\x00\x00\x7e\xc3\xc0\xc0\xc0\xc3\x7e\x00\x00\x00\x00", "\x00\x00\x7f\xc3\xc3\xc3\xc3\x7f\x03\x03\x03\x03\x03", "\x00\x00\x7f\xc0\xc0\xfe\xc3\xc3\x7e\x00\x00\x00\x00", "\x00\x00\x30\x30\x30\x30\x30\xfc\x30\x30\x30\x33\x1e", "\x7e\xc3\x03\x03\x7f\xc3\xc3\xc3\x7e\x00\x00\x00\x00", "\x00\x00\xc3\xc3\xc3\xc3\xc3\xc3\xfe\xc0\xc0\xc0\xc0", "\x00\x00\x18\x18\x18\x18\x18\x18\x18\x00\x00\x18\x00", "\x38\x6c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x00\x00\x0c\x00", "\x00\x00\xc6\xcc\xf8\xf0\xd8\xcc\xc6\xc0\xc0\xc0\xc0", "\x00\x00\x7e\x18\x18\x18\x18\x18\x18\x18\x18\x18\x78", "\x00\x00\xdb\xdb\xdb\xdb\xdb\xdb\xfe\x00\x00\x00\x00", "\x00\x00\xc6\xc6\xc6\xc6\xc6\xc6\xfc\x00\x00\x00\x00", "\x00\x00\x7c\xc6\xc6\xc6\xc6\xc6\x7c\x00\x00\x00\x00", "\xc0\xc0\xc0\xfe\xc3\xc3\xc3\xc3\xfe\x00\x00\x00\x00", "\x03\x03\x03\x7f\xc3\xc3\xc3\xc3\x7f\x00\x00\x00\x00", "\x00\x00\xc0\xc0\xc0\xc0\xc0\xe0\xfe\x00\x00\x00\x00", "\x00\x00\xfe\x03\x03\x7e\xc0\xc0\x7f\x00\x00\x00\x00", "\x00\x00\x1c\x36\x30\x30\x30\x30\xfc\x30\x30\x30\x00", "\x00\x00\x7e\xc6\xc6\xc6\xc6\xc6\xc6\x00\x00\x00\x00", "\x00\x00\x18\x3c\x3c\x66\x66\xc3\xc3\x00\x00\x00\x00", "\x00\x00\xc3\xe7\xff\xdb\xc3\xc3\xc3\x00\x00\x00\x00", "\x00\x00\xc3\x66\x3c\x18\x3c\x66\xc3\x00\x00\x00\x00", "\xc0\x60\x60\x30\x18\x3c\x66\x66\xc3\x00\x00\x00\x00", "\x00\x00\xff\x60\x30\x18\x0c\x06\xff\x00\x00\x00\x00", "\x00\x00\x0f\x18\x18\x18\x38\xf0\x38\x18\x18\x18\x0f", "\x18\x18\x18\x18\x18\x18\x18\x18\x18\x18\x18\x18\x18", "\x00\x00\xf0\x18\x18\x18\x1c\x0f\x1c\x18\x18\x18\xf0", "\x00\x00\x00\x00\x00\x00\x06\x8f\xf1\x60\x00\x00\x00" ] useFont = True class Craft(CruftDialog.CruftDialog): def __init__(self, parent=None, name=None, modal=0, fl=0): CruftDialog.CruftDialog.__init__(self,parent,name,modal,fl) glformat = QGLFormat() print dir(glformat) print glformat.plane() # glformat.setStencil(True) self.qglwidget = qlgw = QGLWidget(glformat, self.frame1, "glpane") if useFont: # init the font in Python glShadeModel(GL_FLAT) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) self.fontOffset = fontOffset = glGenLists(len(_FONT_DATA)) for i in range(len(_FONT_DATA)): # (i + 32) is ASCII codes from 32 to 126 glNewList(i + 32 + fontOffset, GL_COMPILE) glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, _FONT_DATA[i]) glEndList() w = 200; h = 200 glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho (0.0, w, 0.0, h, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) def pushButton1_clicked(self): self.app.quit() # http://www.koders.com/python/fid96CE542E468E82FE726DC8705087F282A27A119D.aspx def paintEvent(self, e): """Draw a colorful collection of lines and circles. """ white = Numeric.array((1.0, 1.0, 1.0), Numeric.Float) # clearing works fine glClearColor(0.0, 0.5, 0.0, 0.0) glClear(GL_COLOR_BUFFER_BIT) if useFont: glColor3fv(white) glRasterPos2i(20, 100) str = "The quick brown fox jumps" glPushAttrib(GL_LIST_BIT) glListBase(self.fontOffset) # PyOpenGL's glCallLists requires a Numeric array glCallLists(Numeric.array(map(ord, str))) # glCallList(self.fontOffset + ord('A')) glPopAttrib() def main(): app = QApplication(sys.argv) cr = Craft() cr.app = app app.setMainWidget(cr) cr.show() cr.update() app.exec_loop() if __name__ == "__main__": main()
NanoCAD-master
cad/src/experimental/LearningOpenGL/Craft.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import sys import distutils.sysconfig import distutils.ccompiler class FakeCompiler: def __init__(self): self.compiler_type = distutils.ccompiler.get_default_compiler() def set_executables(self, **kw): for k in kw: setattr(self, k, kw[k]) mcc = FakeCompiler() distutils.sysconfig.customize_compiler(mcc) if len(sys.argv) < 2: import pprint pprint.pprint(mcc.__dict__) else: for arg in sys.argv[1:]: cmd = getattr(mcc, arg) if cmd.startswith("gcc ") or cmd.startswith("g++ "): cmd = cmd[4:] print cmd
NanoCAD-master
cad/src/experimental/LearningOpenGL/distutils_compile_options.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. from jelloGui import * import sys import random import time import types import string from math import cos, sin, sqrt PROFILING = True if PROFILING: import hotshot, hotshot.stats GOT_PYREX = False try: import comp GOT_PYREX = True except ImportError: pass N = 4 # milliseconds ANIMATION_DELAY = 50 """I think this is the correct way to scale stiffness and viscosity. """ RADIUS = 15 / N**.5 MASS = 3.0e-6 / N**2 DT = 3.0e-3 STIFFNESS = 1.0e-8 * N VISCOSITY = 3.0e-9 * N DTM = (DT ** 2) / MASS TIME_STEP = 0.2 MAXTIME = 1.0e20 A = 3.0e-8 def addvec(u, v): return (u[0] + v[0], u[1] + v[1]) def subvec(u, v): return (u[0] - v[0], u[1] - v[1]) def scalevec(u, k): return (u[0] * k, u[1] * k) # Keep the old, current and new versions of u # in here, along with x. class Computronium: def __init__(self, owner): self.owner = owner self.u = u = N**2 * [ (0.0, 0.0) ] self.u_old = N**2 * [ (0.0, 0.0) ] self.u_new = N**2 * [ (0.0, 0.0) ] self.x = x = [ ] # nominal positions for i in range(N): for j in range(N): x.append((1. * j / N, 1. * i / N)) self.forceTerms = [ ] # set up the force terms for i in range(N): for j in range(N - 1): self.forceTerms.append((i * N + j, i * N + j + 1)) for i in range(N - 1): for j in range(N): self.forceTerms.append((i * N + j, (i + 1) * N + j)) self.simTime = 0.0 def internalForces(self): forces = self.zeroForces() u, o = self.u, self.u_old for i1, i2 in self.forceTerms: D = subvec(u[i2], u[i1]) # relative displacement P = subvec(o[i2], o[i1]) # previous relative displacement f = addvec(scalevec(D, STIFFNESS), scalevec(subvec(D, P), VISCOSITY / DT)) forces[i1] = addvec(forces[i1], f) forces[i2] = subvec(forces[i2], f) self.applyForces(forces) def verletMomentum(self): self_u, self_uold, self_unew = self.u, self.u_old, self.u_new for i in range(N**2): self_unew[i] = subvec(scalevec(self_u[i], 2), self_uold[i]) def applyForces(self, f): self_unew = self.u_new index = 0 for i in range(N**2): unew = self_unew[i] fi = f[i] self_unew[i] = (unew[0] + DTM * fi[0], unew[1] + DTM * fi[1]) def zeroForces(self): return N**2 * [ (0.0, 0.0) ] def draw(self, cb, h, w): # x is nominal position # u is displacement p = [ ] a = 0.6 b = .5 * (1 - a) for i in range(N**2): xvec = self.x[i] uvec = self.u[i] cb(h * (a * (xvec[0] + uvec[0]) + b), w * (a * (xvec[1] + uvec[1]) + b)) def rotate(self): tmp = self.u_old self.u_old = self.u self.u = self.u_new self.u_new = tmp if GOT_PYREX: # Keep the old, current and new versions of u # in here, along with x. class ComputroniumWithPyrex(Computronium): def __init__(self, owner): self.owner = owner comp._setup(N) def internalForces(self): comp._internalForces(STIFFNESS, VISCOSITY/DT, DTM) def verletMomentum(self): comp._verletMomentum() def applyForces(self, f): comp._applyForces(f, DTM) def draw(self, cb, h, w): return comp._draw(cb, h, w) def rotate(self): return comp._rotate() Computronium = ComputroniumWithPyrex class Jello(JelloGui): COLOR_CHOICES = ( QColor(Qt.red), QColor(Qt.yellow), QColor(Qt.green), QColor(Qt.blue) ) def __init__(self): JelloGui.__init__(self, parent=None, name=None, modal=0, fl=0) size = self.frame1.size() self.width, self.height = size.width(), size.height() self.comp = Computronium(self) self.simTime = 0.0 self.timer = QTimer(self) self.connect(self.timer, SIGNAL('timeout()'), self.timeout) self.lastTime = time.time() self.timer.start(ANIMATION_DELAY) self.push = self.comp.zeroForces() for i in range(N/2): f = A * (.5*N - i) / (.5*N) self.push[i] = (-f, f) self.push[N*N-1 - i] = (f, -f) self.painter = QPainter() def pushButton1_clicked(self): self.quit() def quit(self): self.app.quit() def timeout(self): try: self.oneFrame() except AssertionError, e: import traceback traceback.print_exc() self.quit() if self.simTime > MAXTIME: self.app.quit() def oneFrame(self): # On each step we do verlet, using u_old and u to compute # u_new. Then we move each particle from u to u_new. Then # we move u to u_old, and u_new to u. for i in range(int(TIME_STEP / DT)): self.equationsOfMotion() self.paintEvent(None) def paintEvent(self, e): p = self.painter w, h = self.width, self.height p.begin(self.frame1) p.eraseRect(0, 0, w, h) p.setPen(QPen(Qt.black)) p.setBrush(QBrush(Qt.blue)) def draw(x, y, de=p.drawEllipse, r=RADIUS): de(x, y, r, r) #self.comp.draw(draw, w, h) self.comp.draw(draw, h, h) p.end() def equationsOfMotion(self): comp = self.comp t = self.simTime self.simTime += DT pushTime = 1.0 comp.verletMomentum() comp.internalForces() if t < pushTime: comp.applyForces(self.push) comp.rotate() def main(n, maxTime=1.0e20): global N, RADIUS, MAXTIME N = n RADIUS = 15 / n**.5 MAXTIME = maxTime app = QApplication(sys.argv) cr = Jello() cr.app = app app.setMainWidget(cr) cr.show() cr.update() app.exec_loop() if __name__ == "__main__": if PROFILING: prof = hotshot.Profile("jello.prof") def m(): main(4, maxTime=30.0) prof.runcall(m) prof.close() print 'Profiling run is finished, figuring out stats' stats = hotshot.stats.load("jello.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) sys.exit(0) try: n = string.atoi(sys.argv[1]) except: n = 10 main(n)
NanoCAD-master
cad/src/experimental/finite-element/jello.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import sys import distutils.sysconfig import distutils.ccompiler class FakeCompiler: def __init__(self): self.compiler_type = distutils.ccompiler.get_default_compiler() def set_executables(self, **kw): for k in kw: setattr(self, k, kw[k]) mcc = FakeCompiler() distutils.sysconfig.customize_compiler(mcc) if len(sys.argv) < 2: import pprint pprint.pprint(mcc.__dict__) else: for arg in sys.argv[1:]: cmd = getattr(mcc, arg) if cmd.startswith("gcc ") or cmd.startswith("g++ "): cmd = cmd[4:] print cmd
NanoCAD-master
cad/src/experimental/finite-element/distutils_compile_options.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. __author__ = "Will" import sys, os, Pyrex def find_pyrexc(): if sys.platform == 'darwin': x = os.path.dirname(Pyrex.__file__).split('/') return '/'.join(x[:-4] + ['bin', 'pyrexc']) elif sys.platform == 'linux2': if os.path.exists('/usr/bin/pyrexc'): return '/usr/bin/pyrexc' if os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find pyrexc') else: # windows return 'python c:/Python' + sys.version[:3] + '/Scripts/pyrexc.py'
NanoCAD-master
cad/src/experimental/finite-element/findpyrex.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ units.py - physical units for calculations $Id$ When quantities are multiplied or divided, the powers of units are correctly maintained. If one unit ends up being raised to a zeroth power, that unit is discarded in the product or ratio. If there are no units left at all, i.e. the result is dimensionless, just return a float. Many physical formulas apply transcendental functions to dimensionless ratios of quantities. For instance, the voltage across a discharging capacitor is v0*exp(-t/(R*C)), where t, R, and C have dimensions (seconds, ohms, and farads), but the ratio is dimensionless. So returning a float in such cases is a desirable behavior. There are also some handy units and conversions at the bottom of the file. """ __author__ = "Will" # see README for more info import types def isnumber(x): if type(x) in (types.IntType, types.FloatType): return 1 return 0 class UnitsMismatch(Exception): pass class Quantity: def __init__(self,coeff,units,name=None): self.coeff = 1. * coeff self.units = units.copy() if name != None: self.name = name def __repr__(self): str = '<' try: str = str + self.name + ' ' except AttributeError: pass str = str + '%g' % self.coeff for k in self.units.keys(): str = str + ' ' + k if self.units[k] != 1: str = str + '^' + repr(self.units[k]) return str + '>' def __abs__(self): return Quantity(abs(self.coeff), self.units.copy()) def __neg__(self): return Quantity(-self.coeff, self.units.copy()) def __cmp__(self,other): self.unitsMatch(other) return cmp(self.coeff, other.coeff) def __add__(self,other): self.unitsMatch(other) units = self.units.copy() return Quantity(self.coeff + other.coeff, units) def __sub__(self,other): self.unitsMatch(other) units = self.units.copy() return Quantity(self.coeff - other.coeff, units) def __mul__(self,other): if isinstance(other, Quantity): c = 1. * self.coeff * other.coeff u = self.multUnits(other, 1) if u.keys() == [ ]: return c else: return Quantity(c, u) elif isnumber(other): return Quantity(other * self.coeff, self.units) else: raise RuntimeError def __rmul__(self, other): return self.__mul__(other) def __div__(self,other): if isinstance(other, Quantity): return self * other.reciprocal() return Quantity(self.coeff / other, self.units) def __rdiv__(self, other): return other * self.reciprocal() def __pow__(self, n): if n == 0: return 1. if n < 0: return 1. / self.__pow__(-n) newcoeff = self.coeff ** n newunits = { } for k in self.units.keys(): newunits[k] = self.units[k] * n return Quantity(newcoeff, newunits) def reciprocal(self): a = 1. / self.coeff b = self.units.copy() for k in b.keys(): b[k] = -b[k] return Quantity(a, b) def inTermsOf(self, other): ratio = self / other if isnumber(ratio): str = "%g" % ratio else: str = repr(ratio) return str + " " + other.name + "s" def multUnits(self,other,n): units1 = self.units.copy() units2 = other.units.copy() for k in units1.keys(): if k in units2.keys(): units1[k] = units1[k] + n * units2[k] for k in units2.keys(): if k not in units1.keys(): units1[k] = n * units2[k] for k in units1.keys(): if units1[k] == 0: del units1[k] return units1 def unitsMatch(self,other): otherkeys = other.units.keys() for k in self.units.keys(): if k not in otherkeys: raise UnitsMismatch if k != "coeff" and self.units[k] != other.units[k]: raise UnitsMismatch # Lotsa good stuff on units and measures at: # http://aurora.rg.iupui.edu/UCUM/UCUM-tab.html ### Fundamental units meter = m = Quantity(1,{'m':1},"meter") kilogram = kg = Quantity(1,{'kg':1},"kilogram") second = sec = Quantity(1,{'sec':1},"second") coulomb = C = Quantity(1,{'C':1},"coulomb") radian = rad = Quantity(1,{'rad':1},"radian") steradian = srad = Quantity(1,{'sr':1},"steradian") Deca = 10.0 Hecto = 100.0 Kilo = 1.e3 Mega = 1.e6 Giga = 1.e9 Tera = 1.e12 Peta = 1.e15 Exa = 1.e18 Zetta = 1.e21 Yotta = 1.e24 Deci = 0.1 Centi = 0.01 Milli = 1.e-3 Micro = 1.e-6 Nano = 1.e-9 Pico = 1.e-12 Femto = 1.e-15 Atto = 1.e-18 Zepto = 1.e-21 Yocto = 1.e-24 def _make(unit,name): unit.name = name return unit ### Conveniences and metric prefixes squareMeter = _make(meter ** 2, "squareMeter") cubicMeter = _make(meter ** 3, "cubicMeter") # don't know the official metric names for these, if such exist speed = meter / second acceleration = speed / second density = kilogram / cubicMeter liter = L = _make(Milli * cubicMeter, "liter") newton = N = _make(kilogram * acceleration, "newton") joule = J = _make(newton * meter, "joule") watt = W = _make(joule / second, "watt") ampere = A = _make(coulomb / second, "ampere") volt = V = _make(joule / coulomb, "volt") ohm = _make(volt / ampere, "ohm") farad = F = _make(coulomb / volt, "farad") weber = Wb = _make(volt * second, "weber") tesla = T = _make(weber / squareMeter, "tesla") pascal = P = _make(newton / squareMeter, "pascal") henry = H = _make(weber / ampere, "henry") calorie = cal = _make(4.1868 * joule, "calorie") kilocalorie = kcal = _make(Kilo * calorie, "kcal") km = _make(Kilo * meter, "km") cm = _make(Centi * meter, "cm") mm = _make(Milli * meter, "mm") um = _make(Micro * meter, "um") nm = _make(Nano * meter, "nm") are = _make(100 * squareMeter, "are") hectare = _make(Hecto * are, "hectare") gram = g = _make(Milli * kilogram, "gram") mgram = mg = _make(Micro * kilogram, "mgram") ugram = ug = _make(Nano * kilogram, "ugram") metricTon = tonne = _make(Kilo * kilogram, "tonne") A = _make(ampere, "A") mA = _make(Milli * ampere, "mA") uA = _make(Micro * ampere, "uA") nA = _make(Nano * ampere, "nA") pA = _make(Pico * ampere, "pA") msec = _make(Milli * second, "msec") usec = _make(Micro * second, "usec") nsec = _make(Nano * second, "nsec") psec = _make(Pico * second, "psec") fsec = _make(Femto * second, "fsec") ksec = _make(Kilo * second, "ksec") Msec = _make(Mega * second, "Msec") Gsec = _make(Giga * second, "Gsec") Tsec = _make(Tera * second, "Tsec") uF = _make(Micro * farad, "uF") nF = _make(Nano * farad, "nF") pF = _make(Pico * farad, "pF") mH = _make(Milli * henry, "mH") uH = _make(Micro * henry, "uH") nH = _make(Nano * henry, "nH") Kohm = _make(Kilo * ohm, "Kohm") Mohm = _make(Mega * ohm, "Mohm") # earthGravity = 9.8 * acceleration gravitationalConstant = 6.67300e-11 * m**3 * kg**-1 * sec**-2 earthMass = 5.9742e24 * kg earthRadius = 6378.1 * km earthGravity = gravitationalConstant * earthMass / earthRadius**2 ### Electrostatics electronCharge = 1.60217733e-19 * coulomb electrostaticConstant = 8.98755e9 * (N * m**2) / (coulomb**2) ### Time minute = _make(60 * second, "minute") hour = _make(60 * minute, "hour") day = _make(24 * hour, "day") week = _make(7 * day, "week") year = _make(365.25 * day, "year") # There is some disagreement on years. These are Julian years. # Gregorian years are 365.2425 days, and tropical years are 365.24219 # days. month = _make(year / 12, "month") # 28, 29, 30, 31... obviously months must be approximate decade = _make(10 * year, "decade") century = _make(100 * year, "century") millenium = _make(1000 * year, "millenium") ### English measures inch = _make(.0254 * meter, "inch") foot = _make(12 * inch, "foot") yard = _make(3 * foot, "yard") furlong = _make(660 * foot, "furlong") mile = _make(5280 * foot, "mile") squareMile = _make(mile ** 2, "squareMile") acre = _make(43560 * foot**2, "acre") MPH = _make(mile / hour, "MPH") MPS = _make(mile / second, "MPS") gallon = _make(3.79 * liter, "gallon") quart = _make(.25 * gallon, "quart") pint = _make(.5 * quart, "pint") cup = _make(.5 * pint, "cup") fluid_ounce = _make(.125 * cup, "fluid_ounce") tablespoon = _make(.5 * fluid_ounce, "tablespoon") teaspoon = _make(tablespoon / 3., "teaspoon") # In the English system, should we express weights in terms of # masses? Or should we multiply masses by 32 feet/sec^2? ounce = oz = earthGravity * (28.35 * gram) pound = lb = 16 * ounce slug = 14.5939 * kg stone = 6.3503 * kg if __name__ == "__main__": def test1(): lists = [ [ "Length", inch, furlong, yard, mile, km ], [ "Area", squareMeter, acre, hectare, squareMile, ], [ "Volume", gallon, pint, liter, fluid_ounce, tablespoon, cubicMeter ], [ "Time", day, week, decade, century, ksec, Msec, Gsec ], [ "Random", newton, volt, ampere ] ] for lst in lists: print "----- " + lst.pop(0) + " -----" for i in range(len(lst)): for j in range(len(lst)): if i != j: print "one %s is %s" % (lst[i].name, lst[i].inTermsOf(lst[j])) print def test2(): charge = mA * hour time = 1390.0 * second print charge / time test1() # end
NanoCAD-master
cad/src/experimental/units/units.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """Convert CoNTub's PDB output to an MMP file Typical usage: python pdb2mmp.py < hetero.pdb > hetero.mmp """ import sys, string class Atom: def __init__(self, index, elem, xyz): self.index = index self.elem = elem self.xyz = xyz self.bonds = [ ] def __repr__(self): def s(x): # convert distances to int picometers return int(1000.0 * x) r = ('atom %d (%d) (%d, %d, %d) def' % (self.index, self.elem, s(self.xyz[0]), s(self.xyz[1]), s(self.xyz[2]))) if self.bonds: r += '\nbondg' for y in self.bonds: r += ' %d' % y return r atoms = { } bonds = [ ] for L in sys.stdin.readlines(): L = L.rstrip().upper() #print L fields = L.split() if fields[0] == 'HETATM': index = string.atoi(fields[1]) elem = {'C': 6, 'H': 1, 'N': 7}[fields[2]] xyz = map(string.atof, fields[-3:]) atoms[index] = Atom(index, elem, xyz) elif fields[0] == 'CONECT': fields = map(string.atoi, fields[1:]) x = fields[0] for y in fields[1:]: if y < x: bonds.append((x, y)) for x, y in bonds: atoms[x].bonds.append(y) r = '''mmpformat 050920 required; 051103 preferred kelvin 300 group (View Data) info opengroup open = True csys (HomeView) (1.000000, 0.000000, 0.000000, 0.000000) (10.000000) (0.000000, 0.000000, 0.000000) (1.000000) csys (LastView) (1.000000, 0.000000, 0.000000, 0.000000) (10.943023) (0.000000, 0.000000, 0.000000) (1.000000) egroup (View Data) group (Heterojunction) info opengroup open = True mol (Heterojunction-1) def ''' for index in atoms: r += repr(atoms[index]) + '\n' r += '''egroup (Heterojunction) end1 group (Clipboard) info opengroup open = False egroup (Clipboard) end molecular machine part 1881''' print r
NanoCAD-master
cad/src/experimental/graphene/pdb2mmp.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import os, sys, string from math import * sys.path.append("/home/wware/polosims/cad/src") from geometry.VQT import A, V, vlen class AtomType: def __init__(self, symbol, number, rcovalent): self.symbol = symbol self.number = number self.rcovalent = rcovalent def __repr__(self): return '<' + self.symbol + '>' periodicTable = [ AtomType('X', 0, 0.0), AtomType('H', 1, 0.31), AtomType('C', 6, 0.77), AtomType('N', 7, 0.73), AtomType('O', 8, 0.69), AtomType('P', 15, 1.08), ] def lookupAtomType(num): for at in periodicTable: if at.number == num: return at raise Exception("AtomType not found, num=" + repr(num)) class Atom: def __init__(self, mmpline): if mmpline != None: mmpline = mmpline.rstrip() self.mmpline = mmpline fields = mmpline.split() self.key = string.atoi(fields[1]) self.style = fields[6] self.hybridization = None self.base = None self.atomtype = lookupAtomType(string.atoi(fields[2][1:-1])) self.x = 0.001 * string.atoi(fields[3][1:-1]) self.y = 0.001 * string.atoi(fields[4][:-1]) self.z = 0.001 * string.atoi(fields[5][:-1]) else: self.mmpline = None self.key = 0 self.style = None self.hybridization = None self.base = None self.atomtype = lookupAtomType(0) self.x = 0.0 self.y = 0.0 self.z = 0.0 self.bonds = [ ] def is_singlet(self): return self.atomtype.symbol == 'X' def clone(self): a = Atom(self.mmpline) for attr in ('key', 'style', 'hybridization', 'base', 'atomtype', 'x', 'y', 'z', 'bonds'): setattr(a, attr, getattr(self, attr)) return a def hybridize(self, hybrids={ 'C': { 4: 'sp3', 3: 'sp2', 2: 'sp', }, 'O': { 2: 'sp3', 1: 'sp2', }, 'N': { 3: 'sp3', 2: 'sp2', 1: 'sp', } }): try: self.hybridization = hybrids[self.atomtype.symbol][len(self.bonds)] except KeyError: self.hybridization = None def posn(self): return V(self.x, self.y, self.z) def __repr__(self): r = "<%s %d (%g, %g, %g)" % \ (self.atomtype.symbol, self.key, self.x, self.y, self.z) r += " %s" % self.style if self.hybridization != None: r += " %s" % self.hybridization if self.base != None: r += " (base %d)" % self.base if self.bonds: r += " [" for b in self.bonds: r += " " + repr(b) r += " ]" return r + ">" class Bondpoint(Atom): def __init__(self, owner, v): Atom.__init__(self, mmpline=None) self.style = owner.style self.base = owner.base self.x = v[0] self.y = v[1] self.z = v[2] self.bonds = [ owner.key ] def __repr__(self): r = "<%s %d (%g, %g, %g)" % \ (self.atomtype.symbol, self.key, self.x, self.y, self.z) r += " %s" % self.style if self.base != None: r += " (base %d)" % self.base if self.bonds: r += " [" for b in self.bonds: r += " " + repr(b) r += " ]" return r + ">" class MakeBondpoint(Exception): pass class Base: def __init__(self, strand, key): self.key = key self.atomlist = [ ] self.phosphorusZcoord = 0. self.strand = strand atm0 = strand.atoms[key] self.style = atm0.style self.addAtom(atm0) def __cmp__(self, other): return -cmp(self.phosphorusZcoord, other.phosphorusZcoord) def keys(self): return map(lambda a: a.key, self.atomlist) def __len__(self): return len(self.atomlist) def addAtom(self, a): k = a.key if a not in self.atomlist: if a.style == self.style: a.base = self.key self.atomlist.append(a) if a.atomtype.symbol == 'P': self.phosphorusZcoord = a.z else: raise MakeBondpoint def addLayer(self): atoms = self.strand.atoms newguys = [ ] for a in self.atomlist: for k in a.bonds: if k not in newguys and k not in self.keys(): newguys.append(k) atoms[k].buddy = a newAtoms = 0 for k in newguys: a2 = atoms[k] a = a2.buddy try: self.addAtom(a2) newAtoms += 1 except MakeBondpoint: # don't make this bondpoint if it's already been made if not hasattr(a, 'gotBondpoint'): p1, p2 = a.posn(), a2.posn() r1, r2 = a.atomtype.rcovalent, a2.atomtype.rcovalent p = (r2 * p1 + r1 * p2) / (r1 + r2) bpt = Bondpoint(a, p) # pick up a new key self.strand.addAtom(bpt) self.addAtom(bpt) a.gotBondpoint = True return newAtoms def grow(self): while True: if self.addLayer() == 0: return class Strand: def __init__(self, filename=None): self.atoms = { } self.nextKey = 1 self.bases = [ ] if filename != None: for L in open(filename).readlines(): if L.startswith("atom"): self.addAtom(Atom(L)) self.assignBases() def addAtom(self, a): a.key = key = self.nextKey self.nextKey += 1 self.atoms[key] = a def transform(self, t): if t.func_code.co_argcount == 1: for a in self.atoms.values(): v = V(a.x, a.y, a.z) a.x, a.y, a.z = tuple(t(v)) else: for a in self.atoms.values(): a.x, a.y, a.z = t(a.x, a.y, a.z) def addAtomFromMmp(self, mmpline): self.addAtom(Atom(mmpline)) def inferBonds(self): maxBondLength = 2.5 def quantize(vec, maxBondLength=maxBondLength): return (int(vec[0] / maxBondLength), int(vec[1] / maxBondLength), int(vec[2] / maxBondLength)) def bond_atoms(a1, a2): if a1.key not in a2.bonds: a2.bonds.append(a1.key) if a2.key not in a1.bonds: a1.bonds.append(a2.key) buckets = { } for atom in self.atoms.values(): atom.bonds = [ ] # clear existing bonds # put this atom in one of the buckets key = quantize(atom.posn()) try: buckets[key].append(atom) except KeyError: buckets[key] = [ atom ] def region(center): lst = [ ] x0, y0, z0 = quantize(center) for x in range(x0 - 1, x0 + 2): for y in range(y0 - 1, y0 + 2): for z in range(z0 - 1, z0 + 2): key = (x, y, z) try: lst += buckets[key] except KeyError: pass return lst for atm1 in self.atoms.values(): for atm2 in region(atm1.posn()): bondLen = vlen(atm1.posn() - atm2.posn()) idealBondLen = atm1.atomtype.rcovalent + atm2.atomtype.rcovalent a = 0.2 if (1-a) * idealBondLen < bondLen < (1+a) * idealBondLen: bond_atoms(atm1, atm2) atm1.hybridize() def assignBases(self): self.inferBonds() remainingKeys = self.atoms.keys() while len(remainingKeys) > 0: baseKey = remainingKeys[0] print "Base", baseKey base = Base(self, baseKey) self.bases.append(base) remainingKeys = remainingKeys[1:] base.grow() for key in base.keys(): if key in remainingKeys: remainingKeys.remove(key) def renumberAtoms(self): # Renumber their keys, and recompute bonds with new keys atomlist = self.atoms.values() self.atoms = { } self.nextKey = 1 for i in range(len(atomlist)): self.addAtom(atomlist[i]) self.inferBonds() def filter(self, filt): s = Strand() for a in self.atoms.values(): if filt(a): s.addAtom(a.clone()) s.inferBonds() return s def writeManyMmps(self, specs, tfm0, tfm): # discard tiny "bases" and any atoms in them tinybases = filter(lambda b: len(b) < 6, self.bases) for b in tinybases: for a in b.atomlist: del self.atoms[a.key] self.bases.remove(b) self.renumberAtoms() # sort bases in order of decreasing phosphorus z coord self.bases.sort() for index, groupname, filename in specs: basekey = self.bases[index].key base = self.filter(lambda a: a.base == basekey) def tfm2(x, y, z, tfm0=tfm0, tfm=tfm, index=index): v = V(x,y,z) v = tfm0(v) while index: v = tfm(v) index -= 1 return tuple(v) base.transform(tfm2) base.writeMmp(filename, groupname) mmptext = """mmpformat 050920 required; 060421 preferred kelvin 300 group (View Data) info opengroup open = True csys (HomeView) (1.000000, 0.000000, 0.000000, 0.000000) (10.000000) (0.000000, 0.000000, 0.000000) (1.000000) csys (LastView) (1.000000, 0.000000, 0.000000, 0.000000) (8.153929) (0.000000, 0.000000, 0.000000) (1.000000) egroup (View Data) group (%(groupname)s) info opengroup open = True %(text)s egroup (%(groupname)s) end1 group (Clipboard) info opengroup open = False egroup (Clipboard) end molecular machine part %(groupname)s """ def writeMmp(self, filename, groupname=None): # Sort the atoms by what group they are in atomlist = self.atoms.values() atomlist.sort(lambda a1, a2: cmp(a1.base, a2.base)) self.renumberAtoms() # write the file s = "" thisgroup = None for a in self.atoms.values(): if groupname == None: if thisgroup != a.base: s += "mol (Strand %d) def\n" % a.base thisgroup = a.base s += ("atom %d (%d) (%d, %d, %d) def\n" % (a.key, a.atomtype.number, int(1000 * a.x), int(1000 * a.y), int(1000 * a.z))) if a.hybridization != None: s += "info atom atomtype = " + a.hybridization + "\n" bstr = "" for b in a.bonds: if b < a.key: bstr += " " + repr(b) if bstr: s += "bond1" + bstr + "\n" if groupname != None: s = "mol (" + groupname + ") def\n" + s outf = open(filename, "w") outf.write(self.mmptext % {"groupname": groupname, "text": s[:-1]}) outf.close() ######################################## if True: g = Strand('strund1.mmp') specs = [ (0, 'guanine', 'guanine.mmp'), (1, 'cytosine', 'cytosine.mmp'), (3, 'adenine', 'adenine.mmp'), (6, 'thymine', 'thymine.mmp') ] def tfm0(v): return v + V(0, 0, -18.7) def tfm(v): angle = -36 * pi / 180 x, y, z = tuple(v) c, s = cos(angle), sin(angle) x, y = c * x + s * y, -s * x + c * y return V(x, y, z + 3.391) g.writeManyMmps(specs, tfm0, tfm) else: writeMmp('groups.mmp')
NanoCAD-master
cad/src/experimental/bdna-bases/prepare.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """Arbitrary 2D surfaces in 3D space can be represented as: f(v) = 0 where f takes a 3D vector v and returns a scalar. For a sphere, where f(x,y,z) = x**2 + y**2 + z**2 - R**2. By convention, the points where f(v) < 0 are the interior of the shape, and the points where f(v) > 0 are the exterior. We can perform constructive solid geometry of such shapes using some simple operations. The union of two shapes represented by functions f1 and f2 is represented by the function f3, where f3(v) = min(f1(v), f2(v)) The intersection of two shapes is given by f3(v) = max(f1(v), f2(v)) The difference of two shapes is the intersection of the first shape's interior with the second shape's exterior: f3(v) = max(f1(v), -f2(v)) These simple operations will give sharp edges where the two shapes meet. We will sometimes want the option of smooth, beveled edges. This will be the case, for example, when we want to tile the resulting surface with graphene. I think smooth, beveled edges can be achieved by replacing max and min with maxb and minb, where ( y if y - x > C ( maxb(x,y) = ( x if y - x < -C ( ( x + (1/4C) * (y-x+C)**2 otherwise minb(x,y) = -maxb(-x, -y) The smoothness of the edge is controlled by the parameter C. When C = 0, these are the same as max and min. To build this into a really useful library, there should be a set of standard primitives where f and the combiners are implemented in C. But it should be made to work correctly first. Some primitives with example functions: Planar slab f(x,y,z) = (x-xcenter)**2 - width**2 Cylinder f(x,y,z) = x**2 + y**2 - R**2 Sphere f(x,y,z) = x**2 + y**2 + z**2 - R**2 Torus f(x,y,z) = x**2 + y**2 + z**2 + R2**2 - 2*R1*sqrt(x**2 + y**2) Saddle f(x,y,z) = x**2 - y**2 Wall f(x) = x - x0 Things shapes should always be able to give you: the gradient of the function at any point, a way to get from any point to a nearby point on the surface, the unit normal to the surface (this is just the gradient vector normalized), a bounding box (which must include representations for infinity). """ import os import random import types INFINITY = 1.0e20 class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def tuple(self): return (self.x, self.y, self.z) def __repr__(self): return ("<" + repr(self.x) + "," + repr(self.y) + "," + repr(self.z) + ">") def __len__(self): return 3 def __abs__(self): return self.magsq() ** 0.5 def magsq(self): return self.x**2 + self.y**2 + self.z**2 def scale(self, k): return Vector(k * self.x, k * self.y, k * self.z) def normalize(self): return self.scale(1.0 / abs(self)) def __add__(self, v): return Vector(self.x + v.x, self.y + v.y, self.z + v.z) def __sub__(self, v): return self + (-v) def __neg__(self): return Vector(-self.x, -self.y, -self.z) def int(self): return Vector(int(self.x), int(self.y), int(self.z)) def dot(self, v): return self.x * v.x + self.y * v.y + self.z * v.z def cross(self, v): return Vector(self.y * v.z - self.z * v.y, self.z * v.x - self.x * v.z, self.x * v.y - self.y * v.x) MININF = Vector(-INFINITY, -INFINITY, -INFINITY) MAXINF = Vector(INFINITY, INFINITY, INFINITY) class BoundingBox: def __init__(self, vec1=MININF, vec2=MAXINF): self.xmin = min(vec1.x, vec2.x) self.xmax = max(vec1.x, vec2.x) self.ymin = min(vec1.y, vec2.y) self.ymax = max(vec1.y, vec2.y) self.zmin = min(vec1.z, vec2.z) self.zmax = max(vec1.z, vec2.z) def __repr__(self): return ('<BBox %g %g %g' % (self.xmin, self.ymin, self.zmin) + ' %g %g %g>' % (self.xmax, self.ymax, self.zmax)) def union(self, other): xmin = min(self.xmin, other.xmin) ymin = min(self.xmin, other.xmin) zmin = min(self.xmin, other.xmin) xmax = max(self.xmax, other.xmax) ymax = max(self.xmax, other.xmax) zmax = max(self.xmax, other.xmax) return BoundingBox(Vector(xmin, ymin, zmin), Vector(xmax, ymax, zmax)) def intersection(self, other): xmin = max(self.xmin, other.xmin) ymin = max(self.ymin, other.ymin) zmin = max(self.zmin, other.zmin) xmax = max(min(self.xmax, other.xmax), xmin) ymax = max(min(self.ymax, other.ymax), ymin) zmax = max(min(self.zmax, other.zmax), zmin) return BoundingBox(Vector(xmin, ymin, zmin), Vector(xmax, ymax, zmax)) def difference(self, other): return BoundingBox(Vector(self.xmin, self.ymin, self.zmin), Vector(self.xmax, self.ymax, self.zmax)) def maxb(x, y, C=1.0): if C < 0.0001: return max(x, y) diff = y - x if diff < -C: return x elif diff > C: return y else: return x + (diff + C)**2 / (4 * C) def minb(x, y, C=1.0): return -maxb(-x, -y, C) class Shape: def __init__(self, f, bbox): self.f = f self.bbox = bbox def gradient(self, v): f = self.f h = 1.0e-10 e = f(v) return Vector((f(v + Vector(h, 0, 0)) - e) / h, (f(v + Vector(0, h, 0)) - e) / h, (f(v + Vector(0, 0, h)) - e) / h) def union(self, other, C=0.0): def f3(v, f1=self.f, f2=other.f, C=C): return minb(f1(v), f2(v), C) return Shape(f3, self.bbox.union(other.bbox)) def intersection(self, other, C=0.0): def f3(v, f1=self.f, f2=other.f, C=C): return maxb(f1(v), f2(v), C) return Shape(f3, self.bbox.intersection(other.bbox)) def difference(self, other, C=0.0): def f3(v, f1=self.f, f2=other.f, C=C): return maxb(f1(v), -f2(v), C) return Shape(f3, self.bbox.difference(other.bbox)) def shell(self, gridsize): print self.bbox lst = [ ] x = self.bbox.xmin while x <= self.bbox.xmax: y = self.bbox.ymin while y <= self.bbox.ymax: z = self.bbox.zmin while z <= self.bbox.zmax: if -1.0 <= self.f(Vector(x, y, z)) <= 0.0: lst.append((x, y, z)) z += gridsize y += gridsize x += gridsize return lst def ellipsoid(center, size): def f(v): return (((v.x - center.x) / size.x) ** 2 + ((v.y - center.y) / size.y) ** 2 + ((v.z - center.z) / size.z) ** 2 - 1.0) bbox = BoundingBox(center - size, center + size) return Shape(f, bbox) def rectangularSolid(center, size, C=0.0): def f(v): def fx(v, center=center, size=size): return (v.x - center.x)**2 - size.x ** 2 def fy(v, center=center, size=size): return (v.y - center.y)**2 - size.y ** 2 def fz(v, center=center, size=size): return (v.z - center.z)**2 - size.z ** 2 f = maxb(fx(v), fy(v), C) return maxb(f, fz(v), C) bbox = BoundingBox(center - size, center + size) return Shape(f, bbox) def cylinder(center, direction, radius): """This cylinder is not bounded at the ends. If the direction is along one of the coordinate axes, it's possible to have a meaningful bounding box in this case, but I'm too lazy to figure it out right now.""" def f(v, center=center, direction=direction.normalize(), radius=radius): return abs((v - center).cross(direction)) - radius return Shape(f, BoundingBox()) def closedCylinder(center, direction, radius, length): def f1(v, center=center, direction=direction.normalize(), radius=radius): return abs((v - center).cross(direction)) - radius def f2(v, center=center, direction=direction.normalize(), radius=radius): return (v - center).dot(direction)**2 - length**2 def f(v, f1=f1, f2=f2): return max(f1(v), f2(v)) k = (radius**2 + length**2)**.5 vec = Vector(-k, -k, -k) return Shape(f, BoundingBox(center - vec, center + vec)) def wall(pt, normal): def f(v, pt=pt, normal=normal): return (v - pt).dot(normal) return Shape(f, BoundingBox()) mmpfile = """mmpformat 050920 required; 051103 preferred kelvin 300 group (View Data) info opengroup open = True csys (HomeView) (1.000000, 0.000000, 0.000000, 0.000000) (10.000000) (0.000000, 0.000000, 0.000000) (1.000000) csys (LastView) (1.000000, 0.000000, 0.000000, 0.000000) (10.943023) (0.000000, 0.000000, 0.000000) (1.000000) egroup (View Data) group (Nanotube) info opengroup open = True mol (Nanotube-1) def %s egroup (Nanotube) group (Clipboard) info opengroup open = False egroup (Clipboard) end molecular machine part 1 """ def writeMmp(shape, filename): # fill the solid with densely packaged hydrogen atoms # so that we can study it in nE-1, place the atoms in # a rectangular grid every half-angstrom atoms = shape.shell(0.5) atomtext = '' i = 1 for a in atoms: atomtext += 'atom %d (1) (%d, %d, %d) def\n' % \ (i, int(1000 * a[0]), int(1000 * a[1]), int(1000 * a[2])) if (i & 1) == 0 and i > 0: atomtext += 'bond1 %d\n' % (i - 1) i += 1 open(filename, "w").write(mmpfile % atomtext[:-1]) e = ellipsoid(Vector(0.0, 0.0, 0.0), Vector(2.0, 6.0, 5.0)) e = e.union(closedCylinder(Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0), 1.3, 8.0)) w = wall(Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0)) e = e.intersection(w) writeMmp(e, '/tmp/shape.mmp')
NanoCAD-master
cad/src/experimental/tiling/shapes.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """Arbitrary 2D surfaces in 3D space can be represented as: f(v) = 0 where f takes a 3D vector v and returns a scalar. For a sphere, where f(x,y,z) = x**2 + y**2 + z**2 - R**2. We would like to take these arbitrary surfaces and tile them with graphene structures. The inputs to this process will be the function f that defines the surface, and a starting point x0. """ import os import random import types class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def tuple(self): return (self.x, self.y, self.z) def __repr__(self): return ("<" + repr(self.x) + "," + repr(self.y) + "," + repr(self.z) + ">") def __abs__(self): return self.magsq() ** 0.5 def magsq(self): return self.x**2 + self.y**2 + self.z**2 def scale(self, k): return Vector(k * self.x, k * self.y, k * self.z) def normalize(self): return self.scale(1.0 / abs(self)) def __add__(self, v): return Vector(self.x + v.x, self.y + v.y, self.z + v.z) def __sub__(self, v): return self + (-v) def __neg__(self): return Vector(-self.x, -self.y, -self.z) def int(self): return Vector(int(self.x), int(self.y), int(self.z)) def cross(self, v): return Vector(self.y * v.z - self.z * v.y, self.z * v.x - self.x * v.z, self.x * v.y - self.y * v.x) def gradient(self, f): h = 1.0e-10 e = f(self) return Vector((f(self + Vector(h, 0, 0)) - e) / h, (f(self + Vector(0, h, 0)) - e) / h, (f(self + Vector(0, 0, h)) - e) / h) def randvec(): # return a random vector of length one while True: vec = Vector(2 * random.random() - 1, 2 * random.random() - 1, 2 * random.random() - 1) if vec.magsq() > 0.001: return vec.normalize() def minimize(f, v, g=None, debug=False): """If g is not None, then it represents a direction, starting at v, along which we seek a minimum value for f. If g is None, then we are starting at v and trying to find a local minimum for f, regardless of direction. Some of the instances where we're using this, we should maybe use Newton's method instead.""" localMin = (g == None) if localMin: if debug: print "finding local minimum" g = -v.gradient(f) else: if debug: print "1D minimize" x = f(v) p = 3.0 s = 0.0 evals = 1 while p > 1.0e-15: for j in range(-10,10): ds = p * j if s + ds >= 0.0: v1 = v + g.scale(s + ds) y = f(v1) evals += 1 if y < x: s += ds if debug: print "new good s", s, y x = y if localMin: v = v + g.scale(s) g = -v.gradient(f) p *= 0.7 if debug: print evals, "evals" if localMin: return v else: return v + g.scale(s) def newtonsMethodStep(f, v): x = f(v) g = v.gradient(f) return v - g.scale(x / g.magsq()) def nearbyPoint(f, v): """Given a point xi which is pretty close to the surface defined by f, find a nearby point which lies right on the surface (within the limits of floating-point imprecision) where f is zero """ #def f2(x): # return f(x) ** 2 #return minimize(f2, v, -v.gradient(f)) for i in range(10): v = newtonsMethodStep(f, v) return v ###################### def makeRing(f, x0, side=1.42): def distances(ptlst, v): flst = [ f ] for pt, dist in ptlst: def dist(v, pt=pt, distsq=dist**2): return (v - pt).magsq() - distsq flst.append(dist) for i in range(1000): for f1 in flst: v = newtonsMethodStep(f1, v) return v def extendRing(p1, p2, p3=None): lst = [ (p1, side), (p2, (3**.5) * side) ] if p3 != None: lst.append((p3, 2 * side)) px = p1 + randvec() px = distances(lst, px) return px x0 = nearbyPoint(f, x0) x1 = x0 + randvec() x1 = distances([ (x0, side) ], x1) x2 = extendRing(x0, x1) x3 = extendRing(x1, x0, x2) print f(x1), abs(x0 - x1) print f(x2), abs(x2 - x0), abs(x2 - x1) print f(x3), abs(x3 - x0), abs(x3 - x1) x4 = extendRing(x2, x0, x1) x5 = extendRing(x3, x1, x0) print f(x4), abs(x4 - x0), abs(x4 - x3) print f(x5), abs(x5 - x1), abs(x5 - x2) print abs(x5 - x4) / side ###################### class Atom: def __init__(self, pos): self.index = -1 self.pos = pos self.bonds = [ ] def __repr__(self): return "<Atom %d %f %f %f>" % \ (self.index, self.pos.x, self.pos.y, self.pos.z) def mmp(self): r = "atom %d (6) (%d, %d, %d) def\n" % \ (self.index + 1, int(1000 * self.pos.x), int(1000 * self.pos.y), int(1000 * self.pos.z)) numBonds = 0 bonds = "bondg" for atm2 in self.bonds: if atm2.index < self.index: bonds += " " + repr(atm2.index+1) numBonds += 1 bonds += "\n" if numBonds > 3: return "" elif numBonds > 0: r += bonds return r BONDLEN = 1.42 TOOCLOSE = 0.8 * BONDLEN TOODISTANT = 1.1 * BONDLEN def bucketKey(pos): return (int(pos.x / BONDLEN), int(pos.y / BONDLEN), int(pos.z / BONDLEN)) class Buckets: def __init__(self, alst=[ ]): self.buckets = { } for a in alst: self.add(a) def add(self, atm): key = bucketKey(atm.pos) try: self.buckets[key].append(atm) except KeyError: self.buckets[key] = [ atm ] def remove(self, atm): key = bucketKey(atm.pos) try: self.buckets[key].remove(atm) except KeyError: pass def neighborhood(self, pos): ipos = pos.scale(1. / BONDLEN).int() lst = [ ] for xdiff in range(-1, 2): for ydiff in range(-1, 2): for zdiff in range(-1, 2): diff = Vector(xdiff, ydiff, zdiff) key = (ipos + diff).tuple() if self.buckets.has_key(key): lst2 = self.buckets[key] for atm2 in lst2: lst.append(atm2) return lst def findClosestAtom(self, pos, ignoreIdentical=True): closest = None smallestDistance = 1.0e20 for atm in self.neighborhood(pos): dist = abs(atm.pos - pos) if dist < smallestDistance: if not ignoreIdentical or dist > 0.00001: smallestDistance = dist closest = atm return closest class Tiling: def __init__(self): self.atoms = [ ] self.buckets = Buckets() def start(self, f, x0, x1=None): x0 = nearbyPoint(f, x0) if x1 == None: x1 = x0 + randvec() def dist(v, pt=x0, distsq=BONDLEN**2): return (v - pt).magsq() - distsq for i in range(10): x1 = newtonsMethodStep(f, x1) x1 = newtonsMethodStep(dist, x1) tiling.add(Atom(x0)) tiling.add(Atom(x1)) self.inferBonds() def moveAtom(self, atm, newpos): print "moveAtom" key1 = bucketKey(atm.pos) key2 = bucketKey(newpos) self.buckets.remove(atm) atm.pos = newpos self.buckets.add(atm) def __neighborhood(self, pos): ipos = apply(Vector, bucketKey(pos)) lst = [ ] for xdiff in range(-1, 2): for ydiff in range(-1, 2): for zdiff in range(-1, 2): diff = Vector(xdiff, ydiff, zdiff) key = (ipos + diff).tuple() if self.buckets.has_key(key): lst2 = self.buckets[key] for atm2 in lst2: lst.append(atm2) return lst def grow(self, f): while self.growLayer(f) > 0: print "layer" #for i in range(9): # self.growLayer(f) # print "layer" def growLayer(self, f): self.inferBonds() def growAtom(f, atm): def dist(v, pt=atm.pos, distsq=BONDLEN**2): return (v - pt).magsq() - distsq if len(atm.bonds) == 0: print "no bonds " + repr(a) return [ ] elif len(atm.bonds) == 1: g = atm.pos.gradient(f) u = (atm.pos - atm.bonds[0].pos).normalize() v = u.cross(g.normalize()) A = BONDLEN * (3**.5)/2 B = BONDLEN * 0.5 x2 = atm.pos + v.scale(A) + u.scale(B) x3 = atm.pos - v.scale(A) + u.scale(B) for i in range(10): x2 = newtonsMethodStep(f, x2) x2 = newtonsMethodStep(dist, x2) x3 = newtonsMethodStep(f, x3) x3 = newtonsMethodStep(dist, x3) x2, x3 = Atom(x2), Atom(x3) return [ x2, x3 ] elif len(atm.bonds) == 2: u = atm.pos - atm.bonds[0].pos v = atm.pos - atm.bonds[1].pos x2 = u + v for i in range(10): x2 = newtonsMethodStep(f, x2) x2 = newtonsMethodStep(dist, x2) x2 = Atom(x2) return [ x2 ] else: return [ ] oldsize = len(self.atoms) newatoms = [ ] for a in self.atoms: newatoms += growAtom(f, a) # first eliminate redundancies in the new layer itself i = 0 while i < len(newatoms): b = Buckets(newatoms) atm = newatoms[i] atm2 = b.findClosestAtom(atm.pos) if atm2 != None and abs(atm.pos - atm2.pos) < TOOCLOSE: newpos = (atm.pos + atm2.pos).scale(0.5) newatoms.remove(atm) atm2.pos = newpos else: i = i + 1 # next eliminate any redundancies with atoms already in the structure for atm in newatoms: atm2 = self.buckets.findClosestAtom(atm.pos) if abs(atm.pos - atm2.pos) < TOOCLOSE: newatoms.remove(atm) self.moveAtom(atm2, (atm.pos + atm2.pos).scale(0.5)) for a in newatoms: self.add(a) return len(self.atoms) - oldsize def add(self, atm): print 'add', atm self.atoms.append(atm) self.buckets.add(atm) def remove(self, atm): print 'remove', atm self.atoms.remove(atm) self.buckets.remove(atm) def closestAtom(self, pos): return self.buckets.findClosestAtom(pos) def inferBondsForAtom(self, atm): def closeEnough(atm1, atm2): return abs(atm1.pos - atm2.pos) < 2 nbhd = self.buckets.neighborhood(atm.pos) for atm2 in nbhd: if atm2 != atm and atm2 not in atm.bonds and \ 0.8 * BONDLEN < abs(atm.pos - atm2.pos) < 1.2 * BONDLEN: atm.bonds.append(atm2) def inferBonds(self): for atm in self.atoms: self.inferBondsForAtom(atm) def writeMmp(self, filename): self.inferBonds() for i in range(len(self.atoms)): self.atoms[i].index = i mmpfile = """mmpformat 050920 required; 051103 preferred kelvin 300 group (View Data) info opengroup open = True csys (HomeView) (1.000000, 0.000000, 0.000000, 0.000000) (10.000000) (0.000000, 0.000000, 0.000000) (1.000000) csys (LastView) (1.000000, 0.000000, 0.000000, 0.000000) (10.943023) (0.000000, 0.000000, 0.000000) (1.000000) egroup (View Data) group (Nanotube) info opengroup open = True mol (Nanotube-1) def """ for a in self.atoms: mmpfile += a.mmp() mmpfile += """egroup (Nanotube) group (Clipboard) info opengroup open = False egroup (Clipboard) end molecular machine part 1 """ open(filename, "w").write(mmpfile) #################### # makeRing(f, x0) def growAtom(f, atm): def dist(v, pt=atm.pos, distsq=BONDLEN**2): return (v - pt).magsq() - distsq if len(atm.bonds) == 0: raise Exception("no bonds") elif len(atm.bonds) == 1: g = atm.pos.gradient(f) u = (atm.pos - atm.bonds[0].pos).normalize() v = u.cross(g.normalize()) A = BONDLEN * (3**.5)/2 B = BONDLEN * 0.5 x2 = atm.pos + v.scale(A) + u.scale(B) x3 = atm.pos - v.scale(A) + u.scale(B) for i in range(10): x2 = newtonsMethodStep(f, x2) x2 = newtonsMethodStep(dist, x2) x3 = newtonsMethodStep(f, x3) x3 = newtonsMethodStep(dist, x3) x2, x3 = Atom(x2), Atom(x3) return [ x2, x3 ] elif len(atm.bonds) == 2: u = atm.pos - atm.bonds[0].pos v = atm.pos - atm.bonds[1].pos x2 = u + v for i in range(10): x2 = newtonsMethodStep(f, x2) x2 = newtonsMethodStep(dist, x2) x2 = Atom(x2) return [ x2 ] else: return [ ] # def joinY def firstTwo(mmpf, f, x0, x1=None): x0 = nearbyPoint(f, x0) if x1 == None: x1 = x0 + randvec() def dist(v, pt=x0, distsq=BONDLEN**2): return (v - pt).magsq() - distsq for i in range(10): x1 = newtonsMethodStep(f, x1) x1 = newtonsMethodStep(dist, x1) x0, x1 = Atom(x0), Atom(x1) return [ x0, x1 ] ################################### def bevelMax(x, y, C=1.0): if y - x < -C: return x elif y - x > C: return y else: return x + (1/(4.*C)) * (y - x + C)**2 def f(v): f1 = v.x**2 + v.y**2 + (3 * v.z)**2 - 10.0**2 f2 = (v.x-50)**2 + v.y**2 + v.z**2 - 50.0**2 #return bevelMax(f1, f2) return max(f1, f2) tiling = Tiling() tiling.start(f, randvec()) tiling.grow(f) tiling.writeMmp('/tmp/nt.mmp') # os.system("/home/wware/polosims/cad/src/atom.py /tmp/nt.mmp")
NanoCAD-master
cad/src/experimental/tiling/foo.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. # Think about the set sizes for which this scheme is memory efficient. import time import unittest import Numeric stuff = None #stuff = [ ] N = 10**4 #N = 1000 ## Verifying Bruce's suspicion that the 9/9/9/5 scheme was a memory ## hog... #def waste(setsize): # idealmem = int(setsize / 8.0) # numleaves = (setsize + 16383) / 16384 # leafmem = numleaves * 512 * 4 # nummiddles = (numleaves + 511) / 512 # middlemem = nummiddles * 512 * 4 # rootmem = 512 * 4 # totalmem = rootmem + middlemem + leafmem # efficiency = (1.0 * idealmem) / totalmem # return (totalmem, idealmem, efficiency) #for i in range(30): # setsize = int(8 * 1.6**i) # print setsize, waste(setsize) """The present scheme uses a doubly linked list of node. Each node holds a block of 128 words, or 4096 bits, and represents the set membership states of 4096 consecutive integers. Each node has a 20-bit prefix for the upper 20 bits of the integers in its block. We search the blocks for some operations (add, remove, contains), and we assume that we'll be doing those operations in consecutive ranges most of the time. Therefore this scheme tries to be efficient when each search is close to the previous search. We do this by bubbling nodes to the top of the linked list when their blocks get searched, so that they will be found faster on the next linked list traversal. This will not be an efficient scheme for random searches, for two reasons. One is that we'll have to search the linked list in a non-optimal order. The other is that we'll waste time bubbling nodes toward the top when it doesn't help. To avoid the latter, we save the prefix for the previous search, and only bubble up if it matches the present prefix. """ class NodeStruct: """ /* (3 + 128) * 4 = 524 bytes */ struct node { struct node *next; int prefix; unsigned int data[128]; }; """ def __init__(self, prefix): self.prefix = prefix # next initialized to NULL self.next = None # all membership bits initially zero self.data = 128 * [ 0 ] class Set: """ /* 3 * 4 = 12 bytes */ struct set { struct node *root; unsigned int population; }; """ def __init__(self): self.root = None self.population = 0 def __len__(self): return self.population def findNodeWithPrefix(self, p): A = None B = self.root while True: if B == None: return None if B.prefix == p: # bubble B up toward the top if A != None: A.next = B B.next = self.root self.root = B return B A = B B = B.next def bubbleUp(self, C): # bubble this node up toward the top of the list, but only # if we match the previous prefix B = C.previous # If C has no previous, then it's already at the top. if B != None: A = B.previous D = C.next if A != None: A.next = C else: self.root = C if D != None: D.previous = B B.next = D B.previous = C C.next = B C.previous = A def add(self, x): x0, x1, x2 = (x >> 12) & 0xfffff, (x >> 5) & 0x7f, x & 0x1f C = self.findNodeWithPrefix(x0) if C == None: # create a new node C = NodeStruct(x0) if self.root != None: self.root.previous = C C.next = self.root self.root = C # Set the bit in C's data z = C.data[x1] if (z & (1 << x2)) == 0: C.data[x1] = z | (1 << x2) self.population += 1 def asArray(self): z = Numeric.zeros(self.population, 'u') lst = [ ] r = self.root while r != None: lst.append(r) r = r.next def sortOrder(x1, x2): return cmp(x1.prefix, x2.prefix) lst.sort(sortOrder) i = 0 for node in lst: for j in range(128): w = node.data[j] for k in range(32): if (w & (1 << k)) != 0: z[i] = (node.prefix << 12) + (j << 5) + k i += 1 return z def remove(self, x): x0, x1, x2 = (x >> 12) & 0xfffff, (x >> 5) & 0x7f, x & 0x1f C = self.findNodeWithPrefix(x0) if C == None: return # Set the bit in C's data z = C.data[x1] if (z & (1 << x2)) != 0: C.data[x1] = z & ~(1 << x2) self.population -= 1 def contains(self, x): x0, x1, x2 = (x >> 12) & 0xfffff, (x >> 5) & 0x7f, x & 0x1f C = self.findNodeWithPrefix(x0) if C == None: return False # Set the bit in C's data z = C.data[x1] return (z & (1 << x2)) != 0 ################################################ class SetWithTestMethods(Set): ADD_ELEMENT_TIME = 13.0e-6 CONTAINS_ELEMENT_TIME = 12.0e-6 ASARRAY_ELEMENT_TIME = 2.5e-6 def __init__(self): Set.__init__(self) def __len__(self): return self.population def efficiency(self): # assume 1 bit per element, ideally idealMemUsage = (self.population + 7) / 8.0 return idealMemUsage / self.memUsage() def memUsage(self): total = 2 * 4 # root, population, both ints r = self.root while r != None: total += (3 + 128) * 4 r = r.next return total def addRange(self, m, n): while m != n: self.add(m) m += 1 def performanceTest(self, f, n=100): t1 = time.time() for i in range(n): f() t2 = time.time() return (t2 - t1) / n def add_performance(self): def f(): self.addRange(0, N) t = self.performanceTest(f, 1) return t / N def contains_performance(self): self.addRange(0, N) def f(): for i in range(N): self.contains(i) t = self.performanceTest(f, 1) return t / N def asarray_performance(self): self.addRange(0, N) t = self.performanceTest(self.asArray, 1) return t / N class Tests(unittest.TestCase): # FUNCTIONAL TESTS def test_Functionality(self): # # Test general set functionality, make sure it does # the right things. # x = SetWithTestMethods() for i in range(2 * N): if (i & 1) == 0: x.add(i) assert len(x) == N assert not x.contains(-2) assert not x.contains(-1) assert x.contains(0) assert not x.contains(1) assert x.contains(2) assert not x.contains(3) assert x.contains(4) if (N % 2) == 0: assert x.contains(N-4) assert not x.contains(N-3) assert x.contains(N-2) assert not x.contains(N-1) assert x.contains(N) assert not x.contains(N+1) assert x.contains(N+2) else: assert not x.contains(N-4) assert x.contains(N-3) assert not x.contains(N-2) assert x.contains(N-1) assert not x.contains(N) assert x.contains(N+1) assert not x.contains(N+2) assert x.contains(2*N-4) assert not x.contains(2*N-3) assert x.contains(2*N-2) assert not x.contains(2*N-1) assert not x.contains(2*N) assert not x.contains(2*N+1) def test_AsArray(self): x = SetWithTestMethods() a = Numeric.array(range(N), Numeric.UInt32) x.addRange(0, N) assert len(x) == len(a) assert len(x) == N xa = x.asArray() a = a - xa assert Numeric.vdot(a, a) == 0 # MEMORY TEST def test_MemoryUsage(self): # # A very small set should occupy a small memory footprint. # It works out to 536 bytes for very small sets. # x = SetWithTestMethods() x.add(1) x.add(3) x.add(1800) if stuff != None: stuff.append(("memusage", x.memUsage())) assert x.memUsage() < 540 # PERFORMANCE TESTS def test_AddPerformance(self): x = SetWithTestMethods() T = x.add_performance() if stuff != None: stuff.append(("test_AddPerformance", T)) assert T <= x.ADD_ELEMENT_TIME def test_ContainsPerformance(self): x = SetWithTestMethods() T = x.contains_performance() if stuff != None: stuff.append(("test_ContainsPerformance", T)) assert T <= x.CONTAINS_ELEMENT_TIME def test_AsArrayPerformance(self): x = SetWithTestMethods() T = x.asarray_performance() if stuff != None: stuff.append(("test_AsArrayPerformance", T)) assert T <= x.ASARRAY_ELEMENT_TIME def test(): suite = unittest.makeSuite(Tests, 'test') runner = unittest.TextTestRunner() runner.run(suite) if __name__ == "__main__": test() if stuff != None: for x in stuff: print x
NanoCAD-master
cad/src/experimental/pyrex-atoms-bonds/smallerFootprint.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. import time import unittest import random import Numeric from bases import * N = int(10**6) #N = int(10**6) class PerformanceLog: def __init__(self): self.records = [ ] def __setitem__(self, name, time): self.records.append("%s: %.2f nanoseconds per element" % (name, time)) def dump(self): print "Performance information" for x in self.records: print x PL = PerformanceLog() class Tests(unittest.TestCase): def test_AtomSetFunctionality(self): x = AtomSet() x.quickFill(N, 2) assert len(x) == N assert not x.contains(-2) assert not x.contains(-1) assert x.contains(0) assert not x.contains(1) assert x.contains(2) assert not x.contains(3) assert x.contains(4) if (N & 1) == 0: assert x.contains(N-4) assert not x.contains(N-3) assert x.contains(N-2) assert not x.contains(N-1) assert x.contains(N) assert not x.contains(N+1) else: assert not x.contains(N-4) assert x.contains(N-3) assert not x.contains(N-2) assert x.contains(N-1) assert not x.contains(N) assert x.contains(N+1) assert x.contains(2*N-4) assert not x.contains(2*N-3) assert x.contains(2*N-2) assert not x.contains(2*N-1) assert not x.contains(2*N) assert not x.contains(2*N+1) del x[2*N-4] del x[2*N-2] assert len(x) == N - 2 assert not x.contains(2*N-4) assert not x.contains(2*N-2) def test_AtomSetAsArrayMethod(self): x = AtomSet() a = Numeric.array(range(N), Numeric.UInt32) x.quickFill(N) assert len(x) == len(a) assert len(x) == N xa = x.asArray() # only way to test equality of two arrays a = a - xa assert Numeric.vdot(a, a) == 0 def test_AtomSetContainsPerformance(self): x = AtomSet() T = x.contains_performance(N) PL["contains()"] = T def test_AtomSetSetPerformance(self): x = AtomSet() T = x.set_performance(N) PL["set()"] = T def test_AtomSetAsarrayPerformance(self): x = AtomSet() x.quickFill(N) T = x.asarray_performance(N) PL["asarray()"] = T def test_chunkBase(self): cb = ChunkBase() n = 2 for i in range(n): tp = random.randrange(10) x = random.random() y = random.random() z = random.random() ab = AtomBase() cb.addatom(ab, tp, x, y, z) def test(): suite = unittest.makeSuite(Tests, 'test') runner = unittest.TextTestRunner() runner.run(suite) PL.dump() if __name__ == "__main__": test()
NanoCAD-master
cad/src/experimental/pyrex-atoms-bonds/tryit.py