def __init__(self, doc=None, fname=None): app().documentControllers.add(self) if doc != None and doc._undoStack != None: self._undoStack = doc._undoStack else: self._undoStack = QUndoStack() self._undoStack.setClean() self._undoStack.cleanChanged.connect( self.undoStackCleanStatusChangedSlot) self._filename = fname if fname else "untitled.nno" self._activePart = None self.sliceGraphicsItem = None self.pathHelixGroup = None self._hasNoAssociatedFile = fname == None self.win = DocumentWindow(docCtrlr=self) self.win.closeEvent = self.closer self.win.changeEvent = self.changed self.connectWindowEventsToSelf() self.win.show() self._document = None self.setDocument(Document() if not doc else doc) app().undoGroup.addStack(self.undoStack()) self.win.setWindowTitle(self.documentTitle() + '[*]') #self.solidHelixGrp = None if doc != None and doc.parts(): doc.parts()[0].needsFittingToView.emit()
def __init__(self, *args, **kwargs): super(HoneycombPart, self).__init__(self, *args, **kwargs) self._maxRow = kwargs.get('maxRow', app().prefs.honeycombRows) self._maxCol = kwargs.get('maxCol', app().prefs.honeycombCols) self._maxBase = int( kwargs.get('maxSteps', app().prefs.honeycombSteps) * self._step - 1)
def __init__(self, docwin, firstuse): app().documentControllers.add(self) self.win = docwin #self.win points to the class instance of the caDNAno mainwindow self.helpWin = HelpWindow(docwin) #self.helpWin points to the class instance of the help window self.createConnections() self.cmHelp = None #self.cmHelp stores the path of the help document that is associated #with an item in the main window that the user right clicks on self.win.leftToolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.win.rightToolBar.setContextMenuPolicy(Qt.CustomContextMenu) #setContextMenuPolicy enables the use of context menu signals. Note #that this is not the same as connecting the signal to a function self.win.sliceGraphicsView.mouseMoveEvent = self.sliceViewMouseMove self.win.pathGraphicsView.mouseMoveEvent = self.pathViewMouseMove #Lines 48 and 49 capture mouse move events from the QGraphicsWindows in #the main window so that the graphics items that users are dealing with #frequently can be monitored. if firstuse == True: self.win.helplabel.setText(QString("It appears as though this is your first time using CaDNAno 2, would you like to view a tutorial?")) #firstuse a boolean variable that is established right when the #application is started. If the application was started for the #first time, the message will be displayed. else: #If the application is not being used for the first time, help #prompting widgets are hidden. self.win.ignoreButton.hide() self.win.showHelpButton.hide() self.win.helplabel.hide()
def checkAgainstModel(self, indent): s = "" for num in app().v.keys(): r = "\\n".join(repr(app().v[num]).split("\n")) s = s + indent + 'refvh%d = """%s"""\n' % (num, r) s = s + indent + "self.assertEqual(refvh%d, repr(self.app.v[%d]))\n" % (num, num) return s
def __init__(self, *args, **kwargs): super(SquarePart, self).__init__(self, *args, **kwargs) self._maxRow = kwargs.get('maxRow', app().prefs.squareRows) self._maxCol = kwargs.get('maxCol', app().prefs.squareCols) self._maxBase = int( kwargs.get('maxSteps', app().prefs.squareSteps) * self._step - 1)
def __init__(self, document): """docstring for __init__""" # initialize variables self._document = document self._document.setController(self) self._file_open_path = None # will be set in _readSettings self._has_no_associated_file = True self.win = None self.fileopendialog = None self.filesavedialog = None self.settings = QSettings("cadnano.org", "cadnano2.5") self._readSettings() self._hintable_tools = [ ] # filters that display alt icon when disabled self._hintable_filters = [ ] # filters that display alt icon when disabled self._hintable_tool_action_map = { } # what buttons to hint for each filter self._hintable_filter_action_map = { } # what buttons to hint for each filter self._tool_hints_visible = False self._filter_hints_visible = False self.self_signals = [] # call other init methods self._initWindow() app().document_controllers.add(self) self.exit_when_done = False
def __init__(self, vhelix, pathHelixGroup): super(PathHelix, self).__init__() self.setAcceptHoverEvents(True) # for pathtools self._pathHelixGroup = pathHelixGroup self._scafBreakpointHandles = [] self._stapBreakpointHandles = [] self._scafXoverHandles = [] self._stapXoverHandles = [] self._preXOverHandles = None self._XOverCacheEnvironment = None self._segmentPaths = None self._endptPaths = None self._minorGridPainterPath = None self._majorGridPainterPath = None self.step = vhelix.part().crossSectionStep() self.setZValue(styles.ZPATHHELIX) self.rect = QRectF() self._vhelix = None self._handle = None self._mouseDownBase = None self.addBasesButton = SVGButton(":/pathtools/add-bases", self) self.addBasesButton.clicked.connect(self.addBasesClicked) self.removeBasesButton = SVGButton(":/pathtools/remove-bases", self) self.removeBasesButton.clicked.connect(self.removeBasesClicked) self.setVHelix(vhelix) self.setFlag(QGraphicsItem.ItemUsesExtendedStyleOption) self.setPreXOverHandlesVisible(False) if app().ph != None: # Convenience for the command line -i mode app().ph[vhelix.number()] = self
def _initWindow(self): """docstring for initWindow""" self.win = DocumentWindow(docCtrlr=self) self.win.setWindowIcon(QIcon('ui/mainwindow/images/cadnano2-app-icon.png')) app().documentWindowWasCreatedSignal.emit(self._document, self.win) self._connectWindowSignalsToSelf() self.win.show()
def _initMaya(self): """ Initialize Maya-related state. Delete Maya nodes if there is an old document left over from the same session. Set up the Maya window. """ # There will only be one document if (app().active_document and app().active_document.win and not app().active_document.win.close()): return del app().active_document app().active_document = self import maya.OpenMayaUI as OpenMayaUI import sip ptr = OpenMayaUI.MQtUtil.mainWindow() mayaWin = sip.wrapinstance(int(ptr), QMainWindow) self.windock = QDockWidget("cadnano") self.windock.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable) self.windock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.windock.setWidget(self.win) mayaWin.addDockWidget(Qt.DockWidgetArea(Qt.LeftDockWidgetArea), self.windock) self.windock.setVisible(True)
def _initWindow(self): """docstring for initWindow""" # print("new window", app().qApp.allWindows()) self.win = win = DocumentWindow(doc_ctrlr=self) app().documentWindowWasCreatedSignal.emit(self._document, win) self._connectWindowSignalsToSelf() win.show() app().active_document = self # Connect outliner with property editor o = win.outliner_widget p_e = win.property_widget o.itemSelectionChanged.connect(p_e.outlinerItemSelectionChanged) # Set Default Filter if DEFAULT_VHELIX_FILTER: self.actionFilterVirtualHelixSlot() else: self.actionFilterEndpointSlot() self.actionFilterXoverSlot() # setup tool exclusivity self.actiongroup = ag = QActionGroup(win) action_group_list = ['action_global_select', 'action_global_pencil', 'action_path_nick', 'action_path_paint', 'action_path_insertion', 'action_path_skip', 'action_path_add_seq', 'action_path_mods'] for action_name in action_group_list: ag.addAction(getattr(win, action_name)) win.action_global_select.trigger()
def _initMaya(self): """ Initialize Maya-related state. Delete Maya nodes if there is an old document left over from the same session. Set up the Maya window. """ # There will only be one document if (app().activeDocument and app().activeDocument.win and not app().activeDocument.win.close()): return del app().activeDocument app().activeDocument = self import maya.OpenMayaUI as OpenMayaUI import sip ptr = OpenMayaUI.MQtUtil.mainWindow() mayaWin = sip.wrapinstance(long(ptr), QMainWindow) self.windock = QDockWidget("cadnano") self.windock.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable) self.windock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.windock.setWidget(self.win) mayaWin.addDockWidget(Qt.DockWidgetArea(Qt.LeftDockWidgetArea), self.windock) self.windock.setVisible(True)
def _initWindow(self): """docstring for initWindow""" # print("new window", app().qApp.allWindows()) self.win = win = DocumentWindow(doc_ctrlr=self) app().documentWindowWasCreatedSignal.emit(self._document, win) self._connectWindowSignalsToSelf() win.show() app().active_document = self # Connect outliner with property editor o = win.outliner_widget p_e = win.property_widget o.itemSelectionChanged.connect(p_e.outlinerItemSelectionChanged) # Set Default Filter if DEFAULT_VHELIX_FILTER: self.actionFilterVirtualHelixSlot() else: self.actionFilterEndpointSlot() self.actionFilterXoverSlot() # setup tool exclusivity self.actiongroup = ag = QActionGroup(win) action_group_list = [ 'action_global_select', 'action_global_pencil', 'action_path_nick', 'action_path_paint', 'action_path_insertion', 'action_path_skip', 'action_path_add_seq', 'action_path_mods' ] for action_name in action_group_list: ag.addAction(getattr(win, action_name)) win.action_global_select.trigger()
def __init__(self, docwin, firstuse): app().documentControllers.add(self) self.win = docwin #self.win points to the class instance of the caDNAno mainwindow self.helpWin = HelpWindow(docwin) #self.helpWin points to the class instance of the help window self.createConnections() self.cmHelp = None #self.cmHelp stores the path of the help document that is associated #with an item in the main window that the user right clicks on self.win.leftToolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.win.rightToolBar.setContextMenuPolicy(Qt.CustomContextMenu) #setContextMenuPolicy enables the use of context menu signals. Note #that this is not the same as connecting the signal to a function self.win.sliceGraphicsView.mouseMoveEvent = self.sliceViewMouseMove self.win.pathGraphicsView.mouseMoveEvent = self.pathViewMouseMove #Lines 48 and 49 capture mouse move events from the QGraphicsWindows in #the main window so that the graphics items that users are dealing with #frequently can be monitored. if firstuse == True: self.win.helplabel.setText( QString( "It appears as though this is your first time using CaDNAno 2, would you like to view a tutorial?" )) #firstuse a boolean variable that is established right when the #application is started. If the application was started for the #first time, the message will be displayed. else: #If the application is not being used for the first time, help #prompting widgets are hidden. self.win.ignoreButton.hide() self.win.showHelpButton.hide() self.win.helplabel.hide()
def _initWindow(self): """docstring for initWindow""" self.win = DocumentWindow(doc_ctrlr=self) # self.win.setWindowIcon(app().icon) app().documentWindowWasCreatedSignal.emit(self._document, self.win) self._connectWindowSignalsToSelf() self.win.show() app().active_document = self
def _initWindow(self): """docstring for initWindow""" self.win = DocumentWindow(docCtrlr=self) self.win.setWindowIcon( QIcon('ui/mainwindow/images/cadnano2-app-icon.png')) app().documentWindowWasCreatedSignal.emit(self._document, self.win) self._connectWindowSignalsToSelf() self.win.show()
def windowCloseEventHandler(self, event): """Intercept close events when user attempts to close the window.""" if self.maybeSave(): event.accept() if app().isInMaya(): self.windock.setVisible(False) del self.windock app().documentControllers.remove(self) else: event.ignore()
def changed(self, event): if (event.type() == QEvent.ActivationChange or event.type() == QEvent.WindowActivate or event.type() == QEvent.ApplicationActivate): if self.win.isActiveWindow() and app().activeDocument != self: app().activeDocument = self if hasattr(self, 'solidHelixGrp'): if self.solidHelixGrp: self.solidHelixGrp.deleteAllMayaNodes() self.solidHelixGrp.onPersistentDataChanged()
def __init__(self): super(Document, self).__init__() self._undoStack = QUndoStack() self._parts = [] self._assemblies = [] self._controller = None self._selectedPart = None # the dictionary maintains what is selected self._selectionDict = {} # the added list is what was recently selected or deselected self._selectedChangedDict = {} cadnano.app().documentWasCreatedSignal.emit(self)
def __init__(self, numBases=21, idnum=0, incompleteArchivedDict=None): super(VirtualHelix, self).__init__() # Row, col are always owned by the parent part; # they cannot be specified in a meaningful way # for a detached helix (part==None). Only dnaparts # get to modify these. self._row = None self._col = None # If self._part exists, it owns self._number # in that only it may modify it through the # private interface. The public interface for # setNumber just routes the call to the parent # dnapart if one is present. If self._part == None # the vhelix owns self._number and may modify it. self._number = idnum # Attaching to a part via setPart gives the part ownership of # the above three properties (it asks part to set them, # self should no longer modify _row, _col, or _number) self._part = None # The base arrays are owned entirely by virtualhelix self._stapleBases = [] self._scaffoldBases = [] """ This is for loops and skips. a dictionary for loops and skips is added for loops and skips of the form { index: count } + count indicates loop - count indicates skip """ self._stapleLoops = {} self._scaffoldLoops = {} # setSandboxed(True) gives self a private undo stack # in order to insulate undo/redo on the receiver # from global undo/redo (so that if a haywire tool # using undo() and redo() to give a live preview of # tho tool's effect calls undo() a million times it # doesn't make the document disappear). setSandboxed(False) # then clears _privateUndoStack at which point self # goes back to using the part / document undo stack. self._privateUndoStack = None self._sandboxed = False # numBases is a simulated property that corresponds to the # length of _stapleBases and _scaffoldBases if incompleteArchivedDict: numBases = len(re.split('\s+',\ incompleteArchivedDict['staple'])) - 1 self.setNumBases(numBases, notUndoable=True) # Command line convenience for -i mode if app().v != None: app().v[self.number()] = self
def windowCloseEventHandler(self, event): """Intercept close events when user attempts to close the window.""" if self.maybeSave(): event.accept() # if app().isInMaya(): # self.windock.setVisible(False) # del self.windock # self.windock = None app().document_controllers.remove(self) else: event.ignore() self.actionCloseSlot()
def __init__(self, parent=None): super(Document, self).__init__(parent) self._undostack = UndoStack() self._parts = [] self._assemblies = [] self._controller = None self._selected_part = None # the dictionary maintains what is selected self._selection_dict = {} # the added list is what was recently selected or deselected self._selected_changed_dict = {} app().documentWasCreatedSignal.emit(self)
def connectWindowEventsToSelf(self): """Organizational method to collect signal/slot connectors.""" self.win.actionNewHoneycombPart.triggered.connect(self.hcombClicked) self.win.actionNewSquarePart.triggered.connect(self.squareClicked) self.win.actionNew.triggered.connect(app().newDocument) self.win.actionOpen.triggered.connect(self.openClicked) self.win.actionClose.triggered.connect(self.closeClicked) self.win.actionSave.triggered.connect(self.saveClicked) self.win.actionSVG.triggered.connect(self.svgClicked) self.win.actionAutoStaple.triggered.connect(self.autoStapleClicked) self.win.actionCSV.triggered.connect(self.exportCSV) self.win.actionPreferences.triggered.connect(app().prefsClicked) self.win.actionSave_As.triggered.connect(self.saveAsClicked)
def _initWindow(self): """docstring for initWindow""" self.win = win = DocumentWindow(doc_ctrlr=self) app().documentWindowWasCreatedSignal.emit(self._document, win) self._connectWindowSignalsToSelf() win.show() app().active_document = self # Connect outliner with property editor o = win.outliner_widget p_e = win.property_widget o.itemSelectionChanged.connect(p_e.outlinerItemSelectionChanged) # Set Default Filter if DEFAULT_VHELIX_FILTER: self.actionFilterVirtualHelixSlot() else: self.actionFilterEndpointSlot() self.actionFilterXoverSlot() # setup tool exclusivity self.actiongroup = ag = QActionGroup(win) action_group_list = [ 'action_global_select', 'action_global_create', 'action_path_break', 'action_path_paint', 'action_path_insertion', 'action_path_skip', 'action_path_add_seq', 'action_path_mods' ] for action_name in action_group_list: ag.addAction(getattr(win, action_name)) # set up tool & filter hinting self._hintable_tools = [ win.action_global_create, win.action_global_select ] self._hintable_filters = [ win.action_filter_helix, win.action_filter_strand, win.action_filter_endpoint, win.action_filter_xover ] self._hintable_tool_action_map = { 'create': [win.action_global_create], 'select': [win.action_global_select] } self._hintable_filter_action_map = { 'virtual_helix': [win.action_filter_helix], 'strand': [win.action_filter_strand], 'endpoint': [win.action_filter_endpoint], 'xover': [win.action_filter_xover] } win.action_global_select.trigger()
def windowCloseEventHandler(self, event): """Intercept close events when user attempts to close the window.""" if self.maybeSave(): event.accept() if app().isInMaya(): self.windock.setVisible(False) del self.windock self.windock = None the_app = app() self.destroyDC() if the_app.documentControllers: the_app.destroyApp() else: event.ignore() self.actionCloseSlot()
def __init__(self, doc=None, fname=None): """docstring for __init__""" # initialize variables self._document = Document() if not doc else doc self._filename = fname self.win = None self._undoStack = None self._hasNoAssociatedFile = None self._sliceViewInstance = None self._pathViewInstance = None self._solidView = None self._activePart = None # call other init methods self.initWindow() self.initMaya() app().documentControllers.add(self)
def __init__(self, parent=None): super(Document, self).__init__(parent) self._undostack = us = UndoStack( ) # notice NO parent, what does this mean? us.setUndoLimit(30) self._children = set( ) # for storing a reference to Parts (and Assemblies) self._instances = set( ) # for storing instances of Parts (and Assemblies) self._controller = None self._selected_instance = None # the dictionary maintains what is selected self._selection_dict = {} self._active_part = None self._filename = None # the added list is what was recently selected or deselected self._strand_selected_changed_dict = {} self.view_names = [] self.filter_set = set() self._mods = {} # modifications keyed by mod id this_app = app() this_app.documentWasCreatedSignal.emit(self)
def __init__(self, part,\ controller=None,\ parent=None): super(PathHelixGroup, self).__init__(parent) # Subviews, GraphicsItem business self.rect = QRectF() # Set by _setPathHelixList # self._label=None; self.label() # Poke the cache so the label actually exists # Properties self._XOverLabels = None self._pathHelixes = [] # Primary property self.activeHelix = None self._part = None self.phhSelectionGroup = SelectionItemGroup(\ boxtype=PathHelixHandleSelectionBox,\ constraint='y',\ parent=self) self.setPart(part) self._controller = controller self._activeSliceHandle = ActiveSliceHandle(self) self._stapColor = QColor(0, 72, 0) self._stapPen = QPen(self._stapColor, 2) self.floatingXover = XoverHandlePair(self, None, None) self.loopHandleGroup = LoopHandleGroup(parent=self) self.xovers = {} self.setZValue(styles.ZPATHHELIXGROUP) self.selectionLock = None self.setAcceptHoverEvents(True) app().phg = self # Convenience for the command line -i mode self._part.partRemoved.connect(self.destroy) # connect destructor self.dragging = False
def __init__(self, part,\ controller=None,\ parent=None): super(PathHelixGroup, self).__init__(parent) # Subviews, GraphicsItem business self.rect = QRectF() # Set by _set_pathHelixList self._label=None; self.label() # Poke the cache so the label actually exists # Properties self._pathHelixList = [] # Primary property self._part = None; self.setPart(part) self._controller = controller self._activeSliceHandle = ActiveSliceHandle(self) self._stapColor = QColor(0, 72, 0) self._stapPen = QPen(self._stapColor, 2) self.activeHelix = None self.loopHandleGroup = LoopHandleGroup(parent=self) self.xoverGet = XoverHandle() self.setZValue(styles.ZPATHHELIXGROUP) self.phhSelectionGroup = SelectionItemGroup(\ boxtype=PathHelixHandleSelectionBox,\ constraint='y',\ parent=self) self.selectionLock = None app().phg = self # Convenience for the command line -i mode
def maybeSave(self): """ Save on quit, check if document changes have occured. """ if app().dontAskAndJustDiscardUnsavedChanges: return True if not self.undoStack().isClean(): # document dirty? savebox = QMessageBox( QMessageBox.Warning, "Application", \ "The document has been modified.\n Do you want to save your changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, self, Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.Sheet) savebox.setWindowModality(Qt.WindowModal) save = savebox.button(QMessageBox.Save) discard = savebox.button(QMessageBox.Discard) cancel = savebox.button(QMessageBox.Cancel) save.setShortcut("Ctrl+S") discard.setShortcut(QKeySequence("D,Ctrl+D")) cancel.setShortcut(QKeySequence("C,Ctrl+C,.,Ctrl+.")) ret = savebox.exec_() del savebox # manual garbage collection to prevent hang (in osx) if ret == QMessageBox.Save: return self.controller.saveAsClicked() elif ret == QMessageBox.Cancel: return False return True
def staplePreDecoratorSelected(self, listNames): """ Callback function that is called from mayaSelectionContext when a PreDecorator geometry is called, notifies the Part Model of this event. XXX - [SB] In the future we should clean up this interaction. """ if(len(listNames) > 1): # If we have more than one PreDecorator Selected, deselect all but # the last one cmds.select(listNames[0:len(listNames) - 1], deselect=True) selectionList = [] for name in listNames: if name in self.decoratorToVirtualHelixItem: (virtualHelixItem, baseIdx, strand) = \ self.decoratorToVirtualHelixItem[name] selectionList.append((virtualHelixItem.row(), virtualHelixItem.col(), baseIdx)) if len(selectionList) == 0 and \ self.selectionCountCache == 0: # a dumb cache check to prevent deselection to be broadcasted too # many times, but could cause problems return # XXX - [SB] we want to only send the signal to "active part" but # not sure how to get that for doc in app().documentControllers: if doc.win.actionModify.isChecked(): for partItem in doc.win.solidroot.partItems(): partModel = partItem.part() partModel.selectPreDecorator(selectionList) self.selectionCountCache = len(selectionList)
def promptSaveDialog(self, exit_when_done=False): """Save on quit, check if document changes have occurred. Returns: SAVE_DIALOG_OPTIONS['CANCEL'] or SAVE_DIALOG_OPTIONS['DISCARD'] or SAVE_DIALOG_OPTIONS['SAVE'] """ if app().dontAskAndJustDiscardUnsavedChanges: return SAVE_DIALOG_OPTIONS['DISCARD'] if not self.undoStack().isClean(): # document dirty? savebox = QMessageBox( QMessageBox.Warning, "Application", "The document has been modified.\nDo you want to save your changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, self.win, Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.Sheet) savebox.setWindowModality(Qt.WindowModal) save = savebox.button(QMessageBox.Save) discard = savebox.button(QMessageBox.Discard) cancel = savebox.button(QMessageBox.Cancel) savebox.setDefaultButton(save) savebox.setEscapeButton(cancel) save.setShortcut("Ctrl+S") discard.setShortcut(QKeySequence("D,Ctrl+D")) cancel.setShortcut(QKeySequence("C,Ctrl+C,.,Ctrl+.")) ret = savebox.exec_() del savebox # manual garbage collection to prevent hang (in osx) if ret == QMessageBox.Save: self.exit_when_done = exit_when_done self.actionSaveAsSlot() return SAVE_DIALOG_OPTIONS['SAVE'] elif ret == QMessageBox.Cancel: return SAVE_DIALOG_OPTIONS['CANCEL'] return SAVE_DIALOG_OPTIONS['DISCARD']
def __init__(self, parent=None, doc_ctrlr=None): super(DocumentWindow, self).__init__(parent) self.controller = doc_ctrlr doc = doc_ctrlr.document() self.setupUi(self) self.settings = QSettings() # Appearance pref if not app().prefs.show_icon_labels: self.main_toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly) # Outliner & PropertyEditor setup self.outliner_widget.configure(window=self, document=doc) self.property_widget.configure(window=self, document=doc) self.property_buttonbox.setVisible(False) self.tool_managers = None # initialize self._initSliceview(doc) self._initGridview(doc) self._initPathview(doc) self._initPathviewToolbar() self._initEditMenu() self.path_dock_widget.setTitleBarWidget(QWidget()) self.grid_dock_widget.setTitleBarWidget(QWidget()) self.slice_dock_widget.setTitleBarWidget(QWidget()) self.inspector_dock_widget.setTitleBarWidget(QWidget()) self._restoreGeometryandState() self._finishInit() doc.setViewNames(['slice', 'path', 'inspector'])
def closer(self, event): if self.maybeSave(): if app().testRecordMode: self.win.sliceController.testRecorder.generateTest() event.accept() else: event.ignore()
def maybeSave(self): """Save on quit, check if document changes have occured.""" if app().dontAskAndJustDiscardUnsavedChanges: return True if not self.undoStack().isClean(): # document dirty? savebox = QMessageBox( QMessageBox.Warning, "Application", "The document has been modified.\nDo you want to save your changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, self.win, Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.Sheet) savebox.setWindowModality(Qt.WindowModal) save = savebox.button(QMessageBox.Save) discard = savebox.button(QMessageBox.Discard) cancel = savebox.button(QMessageBox.Cancel) save.setShortcut("Ctrl+S") discard.setShortcut(QKeySequence("D,Ctrl+D")) cancel.setShortcut(QKeySequence("C,Ctrl+C,.,Ctrl+.")) ret = savebox.exec_() del savebox # manual garbage collection to prevent hang (in osx) if ret == QMessageBox.Save: return self.actionSaveAsSlot() elif ret == QMessageBox.Cancel: return False return True
def __init__(self, mID, modelStrand, virtualHelixItem): """ The parent should be a VirtualHelixItem. Initialize function creates the Maya Node for the strand, and setups the lookup tables inside of mayaObjectManager (Mom) so that the Maya Node can be globally found given a strand, and the other way around. Also, sets up StrandItemController that is used to setup all the slots and signals between strand model and this strandItem. """ self._modelStrand = modelStrand self._virtualHelixItem = virtualHelixItem self._viewroot = app().activeDocument.win.solidroot mayaNodeInfo = () # print "solidview.StrandItem.__init__ %s" % mID if(modelStrand.strandSet().isScaffold()): mayaNodeInfo = self.createMayaHelixNodes(virtualHelixItem.x(), virtualHelixItem.y(), modelStrand.oligo().color(), StrandType.SCAFFOLD, mID) else: mayaNodeInfo = self.createMayaHelixNodes(virtualHelixItem.x(), virtualHelixItem.y(), modelStrand.oligo().color(), StrandType.STAPLE, mID) #self.onStrandDidMove(strand) m = Mom() m.cnToMaya[modelStrand] = mayaNodeInfo m.mayaToCn[mayaNodeInfo[2]] = modelStrand m.mayaToCn[mayaNodeInfo[0]] = modelStrand self.updateSize() self._controller = StrandItemController(self, modelStrand)
def setupAction(self, actionText, shortcut, actionName, rc_path, toolbutton=None): """ Creates new QAction object, sets appearance, adds to the toolbar and action group, and returns a reference to the object. """ action = QAction(self) if actionText != None and app().prefs.show_icon_labels or toolbutton: action.setText( QApplication.translate("MainWindow", actionText, None)) if rc_path != None: icon = QIcon() icon.addPixmap(QPixmap(rc_path), QIcon.Normal, QIcon.Off) action.setIcon(icon) action.setFont(_FONT) if actionName != None: action.setObjectName(actionName) if shortcut: action.setShortcut(QApplication.translate("MainWindow", shortcut)) action.setCheckable(True) if toolbutton == None: self.addAction(action) else: toolbutton.addAction(action) return action
def initMaya(self): """docstring for initMaya""" if app().isInMaya(): # There will only be one document if app().activeDocument and app().activeDocument.win and not app().activeDocument.win.close(): return del app().activeDocument app().deleteAllMayaNodes() app().activeDocument = self
def _initWindow(self): """docstring for initWindow""" self.win.updateRenderView(self) # now instantiates a document customized for AnimDNA # self.win.setWindowIcon(app().icon) # app().documentWindowWasCreatedSignal.emit(self._document, self.win) # create breakHandler, purpose unknown, probably don't need self._connectWindowSignalsToSelf() self.win.show() app().active_document = self
def addSquareHelixGroup(self): """Adds a square DNA part to the document. Dimensions are set by the Document addDnaSquarePart method.""" dnaPart = self._document.addDnaSquarePart() self.setActivePart(dnaPart) if app().testRecordMode: self.win.sliceController.testRecorder.setPart( dnaPart.crossSectionType())
def __init__(self, parent=None, docCtrlr=None): super(DocumentWindow, self).__init__(parent) self.controller = docCtrlr self.setupUi(self) # Slice setup self.slicescene = QGraphicsScene(parent=self.sliceGraphicsView) self.sliceroot = SceneRoot(rectsource=self.slicescene) self.slicescene.addItem(self.sliceroot) assert self.sliceroot.scene() == self.slicescene self.sliceGraphicsView.setScene(self.slicescene) self.sliceGraphicsView.sceneRootItem = self.sliceroot self.sliceController = slicecontroller.SliceController(self) # Path setup self.pathscene = QGraphicsScene(parent=self.pathGraphicsView) self.pathroot = SceneRoot(rectsource=self.pathscene) self.pathscene.addItem(self.pathroot) assert self.pathroot.scene() == self.pathscene # Uncomment the following block for explicit pathview GL rendering # self.pathGraphicsView.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers))) # self.pathGraphicsView.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) # self.pathGraphicsView.setAutoFillBackground ( True ) # self.pathscene.setBackgroundBrush(Qt.white) # self.pathscene.setItemIndexMethod(QGraphicsScene.NoIndex) self.pathGraphicsView.setScene(self.pathscene) self.pathGraphicsView.sceneRootItem = self.pathroot self.pathGraphicsView.setScaleFitFactor(0.9) self.pathToolbar = ColorPanel() self.pathGraphicsView.toolbar = self.pathToolbar self.pathscene.addItem(self.pathToolbar) self.pathController = pathcontroller.PathController(self) self.sliceController.pathController = self.pathController self.pathController.sliceController = self.sliceController # Test recording if app().testRecordMode: rec = TestRecorder() self.sliceController.testRecorder = rec self.pathController.testRecorder = rec self.pathController.activeToolChanged.connect(rec.activePathToolChangedSlot) # Edit menu setup self.actionUndo = docCtrlr.undoStack().createUndoAction(self) self.actionRedo = docCtrlr.undoStack().createRedoAction(self) self.actionUndo.setText(QApplication.translate("MainWindow", "Undo", None, QApplication.UnicodeUTF8)) self.actionUndo.setShortcut(QApplication.translate("MainWindow", "Ctrl+Z", None, QApplication.UnicodeUTF8)) self.actionRedo.setText(QApplication.translate("MainWindow", "Redo", None, QApplication.UnicodeUTF8)) self.actionRedo.setShortcut(QApplication.translate("MainWindow", "Ctrl+Shift+Z", None, QApplication.UnicodeUTF8)) self.sep = QAction(self) self.sep.setSeparator(True) self.menuEdit.insertAction(self.actionCut, self.sep) self.menuEdit.insertAction(self.sep, self.actionRedo) self.menuEdit.insertAction(self.actionRedo, self.actionUndo) self.splitter.setSizes([400,400]) # balance splitter size
def actionCloseSlot(self): """Called when DocumentWindow is closed""" # if util.isWindows(): # traceback.print_stack() the_app = app() self.destroyDC() if the_app.document_controllers: # check we haven't done this already # print("App Closing") the_app.destroyApp()
def __init__(self, document): """docstring for __init__""" # initialize variables self._document = document self._document.setController(self) self._file_open_path = None # will be set in _readSettings self._has_no_associated_file = True self.win = None self.fileopendialog = None self.filesavedialog = None self.settings = QSettings() self._readSettings() # call other init methods self._initWindow() app().document_controllers.add(self)
def main(): #Initialize cadnano app = cadnano.app() doc = app.document = Document() FILENAME = 'PFD_2hb_loop' INPUT_FILENAME = '../../cadnano-files/' + FILENAME + '.json' OUTPUT_FILENAME_1 = '../../cadnano-files/carbs_output/' + FILENAME + '_RB.gsd' OUTPUT_FILENAME_2 = '../../cadnano-files/carbs_output/' + FILENAME + '_CG.gsd' PICKLE_FILE = 'data/origami_relaxed.pckl' RELAX = False doc.readFile(INPUT_FILENAME) #Parse the structure for simulation new_origami = origami.Origami() new_origami.part = doc.activePart() new_origami.list_oligos() new_origami.initialize_nucleotide_matrix() new_origami.find_skips() new_origami.create_oligos_list() new_origami.get_connections() new_origami.assign_nucleotide_types() new_origami.incorporate_skips() new_origami.assign_nucleotide_connections() new_origami.cluster_into_bodies() new_origami.parse_skip_connections() new_origami.calculate_quaternions_from_positions() #Start relaxation simulation if RELAX == True: relax_simulation = RBSimulation.RigidBodySimulation() relax_simulation.origami = new_origami relax_simulation.initialize_relax_md() relax_simulation.initialize_particles() relax_simulation.create_rigid_bodies() relax_simulation.create_bonds() relax_simulation.set_initial_harmonic_bonds() relax_simulation.set_lj_potentials() relax_simulation.dump_settings(OUTPUT_FILENAME_1, 1) relax_simulation.run(1) relax_simulation.update_positions_and_quaternions() relax_simulation.save_to_pickle(PICKLE_FILE) #Start coarse-grained simulation elif RELAX == False: cg_simulation = CGSimulation.CGSimulation() cg_simulation.parse_origami_from_pickle(PICKLE_FILE) cg_simulation.initialize_cg_md() cg_simulation.initialize_particles() cg_simulation.initialize_system() cg_simulation.create_adjacent_bonds() cg_simulation.set_harmonic_bonds() cg_simulation.set_dihedral_bonds() cg_simulation.set_lj_potentials() cg_simulation.dump_settings(OUTPUT_FILENAME_2, 1) cg_simulation.run(2)
def safeScale(self, delta): current_scale_level = self.transform().m11() scale_factor = 1 + delta * (self._scale_down_rate if delta < 0 else self._scale_up_rate) * \ (app().prefs.zoom_speed/100.) new_scale_level = current_scale_level * scale_factor new_scale_level = util.clamp(current_scale_level * scale_factor, self._scale_limit_min, self._scale_limit_max) scale_change = new_scale_level / current_scale_level self.scale(scale_change, scale_change) self._resetLOD()
def safeScale(self, delta: float): current_scale_level = self.transform().m11() scale_factor = 1 + delta * (self._scale_down_rate if delta < 0 else self._scale_up_rate) * \ (app().prefs.zoom_speed/100.) new_scale_level = current_scale_level * scale_factor new_scale_level = util.clamp(current_scale_level * scale_factor, self._scale_limit_min, self._scale_limit_max) scale_change = new_scale_level / current_scale_level self.scale(scale_change, scale_change) self._resetLOD()
def actionCloseSlot(self): """This will trigger a Window closeEvent.""" #print "closing" if util.isWindows(): #print "close win" self.win.close() if not app().isInMaya(): #print "exit app" import sys sys.exit(1)
def __init__(self, doc_ctrlr: DocCtrlT, parent=None): super(DocumentWindow, self).__init__(parent) self.controller = doc_ctrlr doc = doc_ctrlr.document() self.setupUi(self) self.settings = QSettings("cadnano.org", "cadnano2.5") # Appearance pref if not app().prefs.show_icon_labels: self.main_toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly) # Outliner & PropertyEditor setup self.outliner_widget.configure(window=self, document=doc) self.property_widget.configure(window=self, document=doc) self.property_buttonbox.setVisible(False) self.tool_managers = None # initialize self.views = {} self.views[ViewSendEnum.SLICE] = self._initSliceview(doc) self.views[ViewSendEnum.GRID] = self._initGridview(doc) self.views[ViewSendEnum.PATH] = self._initPathview(doc) self._initPathviewToolbar() self._initEditMenu() self.path_dock_widget.setTitleBarWidget(QWidget()) self.grid_dock_widget.setTitleBarWidget(QWidget()) self.slice_dock_widget.setTitleBarWidget(QWidget()) self.inspector_dock_widget.setTitleBarWidget(QWidget()) self.setCentralWidget(None) if app().prefs.orthoview_style_idx == OrthoViewEnum.SLICE: self.splitDockWidget(self.slice_dock_widget, self.path_dock_widget, Qt.Horizontal) elif app().prefs.orthoview_style_idx == OrthoViewEnum.GRID: self.splitDockWidget(self.grid_dock_widget, self.path_dock_widget, Qt.Horizontal) self._restoreGeometryandState() self._finishInit() doc.setViewNames(['slice', 'path', 'inspector'])
def setupToolButton(self, actionText, shortcut, actionName, rc_path): toolbutton = QToolButton(self) toolbutton.setPopupMode(QToolButton.InstantPopup) if app().prefs.show_icon_labels: toolbutton.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) # toolbutton.setText(QApplication.translate("MainWindow", actionText, None)) icon = QIcon() icon.addPixmap(QPixmap(rc_path), QIcon.Normal, QIcon.Off) toolbutton.setIcon(icon) self.addWidget(toolbutton) return toolbutton
def doRelease(self): # print "RELEASED" self.isMouseDown = False if (self.deltaFront != 0): app().activeDocument.document().resizeSelection(self.deltaFront) if (self.deltaBack != 0): app().activeDocument.document().resizeSelection(self.deltaBack) m = Mom() m.strandsSelected(self.helicesNames, (True, True)) cmds.hide(helixManip.transformName) self.frontDistance = 0 self.backDistance = 0 return OpenMaya.kUnknownParameter
def __init__(self, doc, parent=None): super(PartToolBar, self).__init__(parent) self.doc = doc # Set the appearance _sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) _sizePolicy.setHorizontalStretch(0) _sizePolicy.setVerticalStretch(0) _sizePolicy.setHeightForWidth(_sizePolicy.hasHeightForWidth()) self.setSizePolicy(_sizePolicy) self.setOrientation(Qt.Vertical) # default is horizontal # _maxH = 40 if app().prefs.show_icon_labels else 30 # self.setMaximumHeight(_maxH) # horizontal self.setMaximumWidth(36) # vertical self.setIconSize(QSize(20, 20)) self.setLayoutDirection(Qt.LeftToRight) if app().prefs.show_icon_labels: self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) # Toolbar Label self.action_toolbar_label = self.setupLabel( "Add\nPart:", "action_new_honeycomb_part") # Origami ToolButton self.add_origamipart_button = self.setupToolButton( "Origami", None, "add_origamipart_button", ":/parttools/new-origami") # Origami Part (Honeycomb) self.action_new_honeycomb_part = self.setupAction( "Hcomb", None, "action_new_honeycomb_part", ":/parttools/new-honeycomb", self.add_origamipart_button) self.action_new_honeycomb_part.triggered.connect( self.doc.controller().actionAddHoneycombPartSlot) # Origami Part (Square) self.action_new_square_part = self.setupAction( "Square", None, "action_new_square_part", ":/parttools/new-square", self.add_origamipart_button) self.action_new_square_part.triggered.connect( self.doc.controller().actionAddSquarePartSlot) # Origami Part (H-PX) self.action_new_hpx_part = self.setupAction( "H-PX", None, "action_new_honeypx_part", ":/parttools/new-hpx", self.add_origamipart_button) self.action_new_hpx_part.triggered.connect( self.doc.controller().actionAddHpxPartSlot) # Origami Part (S-px) self.action_new_spx_part = self.setupAction( "Sq-PX", None, "action_new_squarepx_part", ":/parttools/new-spx", self.add_origamipart_button) self.action_new_spx_part.triggered.connect( self.doc.controller().actionAddSpxPartSlot)
def windowCloseEventHandler(self, event=None): """Intercept close events when user attempts to close the window.""" dialog_result = self.promptSaveDialog(exit_when_done=True) if dialog_result is SAVE_DIALOG_OPTIONS['DISCARD']: if event is not None: event.accept() the_app = app() self.destroyDC() if the_app.document_controllers: the_app.destroyApp() elif event is not None: event.ignore()