예제 #1
0
class SelectNames(QDialog):  # {{{

    def __init__(self, names, txt, parent=None):
        QDialog.__init__(self, parent)
        self.l = l = QVBoxLayout(self)
        self.setLayout(l)

        self.la = la = QLabel(_('Create a Virtual Library based on %s') % txt)
        l.addWidget(la)

        self._names = QListWidget(self)
        self._names.addItems(QStringList(sorted(names, key=sort_key)))
        self._names.setSelectionMode(self._names.ExtendedSelection)
        l.addWidget(self._names)

        self._and = QCheckBox(_('Match all selected %s names')%txt)
        l.addWidget(self._and)

        self.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        l.addWidget(self.bb)

        self.resize(self.sizeHint())

    @property
    def names(self):
        for item in self._names.selectedItems():
            yield unicode(item.data(Qt.DisplayRole).toString())

    @property
    def match_type(self):
        return ' and ' if self._and.isChecked() else ' or '
예제 #2
0
class SelectNames(QDialog):  # {{{
    def __init__(self, names, txt, parent=None):
        QDialog.__init__(self, parent)
        self.l = l = QVBoxLayout(self)
        self.setLayout(l)

        self.la = la = QLabel(_("Create a Virtual Library based on %s") % txt)
        l.addWidget(la)

        self._names = QListWidget(self)
        self._names.addItems(QStringList(sorted(names, key=sort_key)))
        self._names.setSelectionMode(self._names.ExtendedSelection)
        l.addWidget(self._names)

        self._or = QRadioButton(_("Match any of the selected %s names") % txt)
        self._and = QRadioButton(_("Match all of the selected %s names") % txt)
        self._or.setChecked(True)
        l.addWidget(self._or)
        l.addWidget(self._and)

        self.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        l.addWidget(self.bb)

        self.resize(self.sizeHint())

    @property
    def names(self):
        for item in self._names.selectedItems():
            yield unicode(item.data(Qt.DisplayRole).toString())

    @property
    def match_type(self):
        return " and " if self._and.isChecked() else " or "
예제 #3
0
class SearchDialog(SizePersistedDialog):
    def __init__(self, parent=None, mm=None):
        SizePersistedDialog.__init__(self, parent,
                                     'casanova plugin:search dialog')
        self.setWindowTitle('Search Casanova:')
        self.gui = parent
        self.mm = mm

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.search_label = QLabel('Search for:')
        layout.addWidget(self.search_label)
        self.search_str = QLineEdit(self)
        self.search_str.setText('')
        layout.addWidget(self.search_str)
        self.search_label.setBuddy(self.search_str)

        self.find_button = QPushButton("&Find")
        self.search_button_box = QDialogButtonBox(Qt.Horizontal)
        self.search_button_box.addButton(self.find_button,
                                         QDialogButtonBox.ActionRole)
        self.search_button_box.clicked.connect(self._find_clicked)
        layout.addWidget(self.search_button_box)

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        layout.addWidget(self.values_list)

        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                           | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._accept_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        # Cause our dialog size to be restored from prefs or created on first usage
        self.resize_dialog()

    def _display_choices(self, choices):
        self.values_list.clear()
        for id, name in choices.items():
            item = QListWidgetItem(get_icon('images/books.png'), name,
                                   self.values_list)
            item.setData(1, (id, ))
            self.values_list.addItem(item)

    def _find_clicked(self):
        query = unicode(self.search_str.text())
        self._display_choices(self.mm.search(query))

    def _accept_clicked(self):
        #self._save_preferences()
        self.selected_texts = []
        for item in self.values_list.selectedItems():
            self.selected_texts.append(item.data(1).toPyObject()[0])
        self.accept()
예제 #4
0
class SearchDialog(SizePersistedDialog):

    def __init__(self, parent=None, mm=None):
        SizePersistedDialog.__init__(self, parent, 'casanova plugin:search dialog')
        self.setWindowTitle('Search Casanova:')
        self.gui = parent
        self.mm = mm
        
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.search_label = QLabel('Search for:')
        layout.addWidget(self.search_label)
        self.search_str = QLineEdit(self)
        self.search_str.setText('')
        layout.addWidget(self.search_str)
        self.search_label.setBuddy(self.search_str)

        self.find_button = QPushButton("&Find")
        self.search_button_box = QDialogButtonBox(Qt.Horizontal)
        self.search_button_box.addButton(self.find_button, QDialogButtonBox.ActionRole)
        self.search_button_box.clicked.connect(self._find_clicked)
        layout.addWidget(self.search_button_box)        

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        layout.addWidget(self.values_list)
        
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._accept_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        # Cause our dialog size to be restored from prefs or created on first usage
        self.resize_dialog()

    def _display_choices(self, choices):
        self.values_list.clear()
        for id, name in choices.items():
            item = QListWidgetItem(get_icon('images/books.png'), name, self.values_list)
            item.setData(1, (id,))
            self.values_list.addItem(item)

    def _find_clicked(self):
        query = unicode(self.search_str.text())
        self._display_choices(self.mm.search(query))

    def _accept_clicked(self):
        #self._save_preferences()
        self.selected_texts = []
        for item in self.values_list.selectedItems():
            self.selected_texts.append(item.data(1).toPyObject()[0])
        self.accept() 
예제 #5
0
class ChooseFormatToDownloadDialog(SizePersistedDialog):
    def __init__(self, parent=None, dm=None, casanova_id=None):
        SizePersistedDialog.__init__(self, parent,
                                     'casanova plugin:format download dialog')
        self.setWindowTitle('Select format to download:')
        self.gui = parent
        self.dm = dm
        self.casanova_id = casanova_id

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        layout.addWidget(self.values_list)

        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                           | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._accept_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        self._display_formats()

        # Cause our dialog size to be restored from prefs or created on first usage
        self.resize_dialog()

    def _display_formats(self):
        self.values_list.clear()
        formats = self.dm.get_download_info(self.casanova_id)
        if isinstance(formats, list):
            for format in formats:
                item = QListWidgetItem(get_icon('images/books.png'),
                                       format['type'], self.values_list)
                item.setData(1, (format, ))
                self.values_list.addItem(item)
        else:
            return error_dialog(self.gui,
                                'Casanova message',
                                unicode(formats),
                                show=True)

    def _accept_clicked(self):
        #self._save_preferences()
        self.selected_format = None
        for item in self.values_list.selectedItems():
            self.selected_format = item.data(1).toPyObject()[0]
        self.accept()
예제 #6
0
class ChooseFormatToDownloadDialog(SizePersistedDialog):

    def __init__(self, parent=None, dm=None, casanova_id=None):
        SizePersistedDialog.__init__(self, parent, 'casanova plugin:format download dialog')
        self.setWindowTitle('Select format to download:')
        self.gui = parent
        self.dm = dm
        self.casanova_id = casanova_id

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        layout.addWidget(self.values_list)
        
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._accept_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        self._display_formats()

        # Cause our dialog size to be restored from prefs or created on first usage
        self.resize_dialog()

    def _display_formats(self):
        self.values_list.clear()
        formats = self.dm.get_download_info(self.casanova_id)
        if isinstance(formats, list):
            for format in formats:
                item = QListWidgetItem(get_icon('images/books.png'), format['type'], self.values_list)
                item.setData(1, (format,))
                self.values_list.addItem(item)
        else:
            return error_dialog(self.gui, 'Casanova message', unicode(formats), show=True) 
        

    def _accept_clicked(self):
        #self._save_preferences()
        self.selected_format = None
        for item in self.values_list.selectedItems():
            self.selected_format = item.data(1).toPyObject()[0]
        self.accept()
예제 #7
0
class ChooseIssuesToUpdateDialog(SizePersistedDialog):
    def __init__(self, parent=None, mm=None):
        SizePersistedDialog.__init__(self, parent,
                                     'casanova plugin:issues update dialog')
        self.setWindowTitle('Select issues to update:')
        self.gui = parent
        self.mm = mm

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        layout.addWidget(self.values_list)

        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                           | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._accept_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        self._display_issues()

        # Cause our dialog size to be restored from prefs or created on first usage
        self.resize_dialog()

    def _display_issues(self):
        self.values_list.clear()
        issues = self.mm.get_all_issues(True)
        for id, issue in issues:
            item = QListWidgetItem(get_icon('images/books.png'), issue,
                                   self.values_list)
            item.setData(1, (id, ))
            self.values_list.addItem(item)

    def _accept_clicked(self):
        #self._save_preferences()
        self.selected_issues = []
        for item in self.values_list.selectedItems():
            self.selected_issues.append(item.data(1).toPyObject()[0])
        self.accept()
예제 #8
0
class ChooseIssuesToUpdateDialog(SizePersistedDialog):

    def __init__(self, parent=None, mm=None):
        SizePersistedDialog.__init__(self, parent, 'casanova plugin:issues update dialog')
        self.setWindowTitle('Select issues to update:')
        self.gui = parent
        self.mm = mm

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        layout.addWidget(self.values_list)
        
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._accept_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        self._display_issues()

        # Cause our dialog size to be restored from prefs or created on first usage
        self.resize_dialog()

    def _display_issues(self):
        self.values_list.clear()
        issues = self.mm.get_all_issues(True)
        for id, issue in issues:
            item = QListWidgetItem(get_icon('images/books.png'), issue, self.values_list)
            item.setData(1, (id,))
            self.values_list.addItem(item)

    def _accept_clicked(self):
        #self._save_preferences()
        self.selected_issues = []
        for item in self.values_list.selectedItems():
        	self.selected_issues.append(item.data(1).toPyObject()[0])
        self.accept()
class PluginObject(object):

   tabName = 'Pass Phrase Finder'
   maxVersion = '0.93.99'
   
   #############################################################################
   def __init__(self, main):
      self.searchThread = None
      self.passPhraseFinder = None
      self.isSearchOver = False
      
      def updateResults(resultStr):
         self.resultStr += resultStr
         
      def updateDisplay():
         if len(self.resultStr) > 0:
            self.resultsDisplay.append(self.resultStr)
            self.resultStr = ''
            self.resultsDisplay.moveCursor(QtGui.QTextCursor.End)
            self.resultsDisplay.repaint()
         if self.isSearchOver:
            endSearch()
      
      # Call this from another thread to end the search
      def terminateSearch():
         self.isSearchOver = True
      
      # Call this from the main thread to end the search
      def endSearch():
         self.main.extraHeartbeatAlways.remove(updateDisplay)
         self.searchButton.setEnabled(True)
         self.stopButton.setEnabled(False)
         # If the thread is still searching tell the pass phrase finder to stop
         if self.passPhraseFinder and self.searchThread  and not self.searchThread.isFinished():
            self.passPhraseFinder.isStopped = True
            
      def searchForPassphrase():
         # Get the selected wallet from the main screen
         wlt = self.getSelectedWlt()
         if wlt and not wlt.watchingOnly and wlt.isLocked:
            self.resultStr = ''
            self.passPhraseFinder = PassPhraseFinder(wlt)
            self.resultsDisplay.setText(QString(''))
            self.main.extraHeartbeatAlways.append(updateDisplay)
            if len(self.segOrdStrSet) > 0:
               # From self.segOrdStrList, create a list of lists of indexes that describe the segment orderings to search
               # In other words convert all of the strings in orderings list to lists of integers
               segOrdIntListList = []
               for ordStr in self.segOrdStrSet:
                  # The indexes provided by the users are 1 based, and the list indexes ought to be 0 based
                  segOrdIntListList.append([int(indexStr)-1 for indexStr in ordStr.split(',')])
               self.searchThread = PyBackgroundThread(self.passPhraseFinder.searchForPassPhrase, 
                  [segDef.getSegList() for segDef in self.segDefList], 
                  segOrdIntListList, 
                  updateResults,
                  terminateSearch )
               # Reset the isSearchOver flag
               self.isSearchOver = False
               self.searchThread.start()
               
               # Disable search button adn enabled stop button
               self.stopButton.setEnabled(True)
               self.searchButton.setEnabled(False)
            else:
               QMessageBox.warning(self.main, tr('Invalid'), tr("""
                  There are no valid segment combinations to search.
                  Please add at least one segment and ordering to search."""), QMessageBox.Ok)
         else:
            QMessageBox.warning(self.main, tr('Invalid'), tr("""
               No valid wallet is selected. Please select a locked
               non-watching-only from Available Wallets."""), QMessageBox.Ok)

      def addKnownSegment():
         dlgEnterSegment = DlgEnterSegment(main, main)
         if dlgEnterSegment.exec_():
            segmentText = str(dlgEnterSegment.editSegment.text())
            if len(segmentText)>0:
               self.segDefList.append(KnownSeg(segmentText))
               self.segDefTableModel.updateSegList(self.segDefList)
      
      def addUnknownCaseSegment():
         dlgEnterSegment = DlgEnterSegment(main, main)
         if dlgEnterSegment.exec_():
            segmentText = str(dlgEnterSegment.editSegment.text())
            if len(segmentText)>0:
               self.segDefList.append(UnknownCaseSeg(segmentText))
               self.segDefTableModel.updateSegList(self.segDefList)
               
      def addUnknownOrderSegment():
         dlgEnterSegment = DlgEnterSegment(main, main, isUnknownOrder=True)
         if dlgEnterSegment.exec_():
            segmentText = str(dlgEnterSegment.editSegment.text())
            minLen = int(str(dlgEnterSegment.minSelector.currentText()))
            maxLen = int(str(dlgEnterSegment.maxSelector.currentText()))
            if len(segmentText)>0:
               self.segDefList.append(UnknownSeg(segmentText, minLen, maxLen))
               self.segDefTableModel.updateSegList(self.segDefList)

      def addOrdering():
         if len(self.segDefList) > 0:
            dlgSpecifyOrdering = DlgSpecifyOrdering(main, main, len(self.segDefList))     
            if dlgSpecifyOrdering.exec_():
               self.segOrdStrSet.add(str(dlgSpecifyOrdering.parseOrderingList()).strip('[]'))
               self.updateOrderingListBox()
         else:
            QMessageBox.warning(self.main, tr('Not Ready'), tr("""
               No segments have been entered. You must enter some segments before you can order them."""), QMessageBox.Ok)

      
      self.main = main
      self.segDefList = []
      self.segOrdStrSet = set()
      segmentHeader = QRichLabel(tr("""<b>Build segments for pass phrase search: </b>"""), doWrap=False)
      self.knownButton = QPushButton("Add Known Segment")
      self.unknownCaseButton = QPushButton("Add Unknown Case Segment")
      self.unknownOrderButton = QPushButton("Add Unknown Order Segment")
      self.main.connect(self.knownButton, SIGNAL('clicked()'), addKnownSegment)
      self.main.connect(self.unknownCaseButton, SIGNAL('clicked()'), addUnknownCaseSegment)
      self.main.connect(self.unknownOrderButton, SIGNAL('clicked()'), addUnknownOrderSegment)
      topRow =  makeHorizFrame([segmentHeader, self.knownButton, self.unknownCaseButton, self.unknownOrderButton, 'stretch'])
      
      self.segDefTableModel = SegDefDisplayModel()
      self.segDefTableView = QTableView()
      self.segDefTableView.setModel(self.segDefTableModel)
      self.segDefTableView.setSelectionBehavior(QTableView.SelectRows)
      self.segDefTableView.setSelectionMode(QTableView.SingleSelection)
      self.segDefTableView.verticalHeader().setDefaultSectionSize(20)
      self.segDefTableView.verticalHeader().hide()
      
      h = tightSizeNChar(self.segDefTableView, 1)[1]
      self.segDefTableView.setMinimumHeight(2 * (1.3 * h))
      self.segDefTableView.setMaximumHeight(10 * (1.3 * h))      
      initialColResize(self.segDefTableView, [.1, .2, .4, .1, .1, .1])

      self.segDefTableView.customContextMenuRequested.connect(self.showSegContextMenu)
      self.segDefTableView.setContextMenuPolicy(Qt.CustomContextMenu)
      
      segmentOrderingsHeader = QRichLabel(tr("""<b>Specify orderings for pass phrase search: </b>"""), doWrap=False)
      self.addOrderingButton = QPushButton("Add Ordering")
      
      
      self.main.connect(self.addOrderingButton, SIGNAL('clicked()'), addOrdering)
      orderingButtonPanel = makeHorizFrame([segmentOrderingsHeader, self.addOrderingButton, 'stretch'])

      self.segOrdListBox  = QListWidget()
      
      self.segOrdListBox.customContextMenuRequested.connect(self.showOrdContextMenu)
      self.segOrdListBox.setContextMenuPolicy(Qt.CustomContextMenu)
      
      
      self.searchButton = QPushButton("Search")
      self.main.connect(self.searchButton, SIGNAL('clicked()'), searchForPassphrase)
      self.stopButton = QPushButton("Stop Searching")
      self.stopButton.setEnabled(False)
      self.main.connect(self.stopButton, SIGNAL('clicked()'), endSearch)
      totalSearchLabel = QRichLabel(tr("""<b>Total Passphrase Tries To Search: </b>"""), doWrap=False)
      self.totalSearchTriesDisplay = QLineEdit()
      self.totalSearchTriesDisplay.setReadOnly(True)
      self.totalSearchTriesDisplay.setText(QString('0'))
      self.totalSearchTriesDisplay.setFont(GETFONT('Fixed'))
      self.totalSearchTriesDisplay.setMinimumWidth(tightSizeNChar(self.totalSearchTriesDisplay, 6)[0])
      self.totalSearchTriesDisplay.setMaximumWidth(tightSizeNChar(self.totalSearchTriesDisplay, 12)[0])
      searchButtonPanel = makeHorizFrame([self.searchButton, self.stopButton, 'stretch', totalSearchLabel,  self.totalSearchTriesDisplay])
      
      self.resultsDisplay = QTextEdit()
      self.resultsDisplay.setReadOnly(True)
      self.resultsDisplay.setFont(GETFONT('Fixed'))
      self.resultsDisplay.setMinimumHeight(100)
      self.searchPanel = makeVertFrame([topRow, self.segDefTableView, orderingButtonPanel,
             self.segOrdListBox, searchButtonPanel, self.resultsDisplay, 'stretch'])
      # Now set the scrollarea widget to the layout
      self.tabToDisplay = QScrollArea()
      self.tabToDisplay.setWidgetResizable(True)
      self.tabToDisplay.setWidget(self.searchPanel)
   
   def getSelectedWlt(self):
      wlt = None
      selectedWltList = self.main.walletsView.selectedIndexes()
      if len(selectedWltList)>0:
            row = selectedWltList[0].row()
            wltID = str(self.main.walletsView.model().index(row, WLTVIEWCOLS.ID).data().toString())
            wlt = self.main.walletMap[wltID]
      return wlt
   
   def showSegContextMenu(self):
      menu = QMenu(self.segDefTableView)
      if len(self.segDefTableView.selectedIndexes())==0:
         return

      row = self.segDefTableView.selectedIndexes()[0].row()
      deleteSegMenuItem = menu.addAction("Delete Segment")
      action = menu.exec_(QCursor.pos())
      
      if action == deleteSegMenuItem:
         self.deleteSegRow(row)
         
   def showOrdContextMenu(self):
      menu = QMenu(self.segOrdListBox)
      if len(self.segOrdListBox.selectedItems())==0:
         return

      item = self.segOrdListBox.currentItem()
      deleteOrdMenuItem = menu.addAction("Delete Ordering")
      action = menu.exec_(QCursor.pos())
      
      if action == deleteOrdMenuItem:
         self.deleteOrdItem(item)
         
   def deleteSegRow(self, row):
      self.segDefList.remove(self.segDefList[row])
      self.segDefTableModel.updateSegList(self.segDefList)
      self.segOrdStrSet.clear()
      self.updateOrderingListBox()
   
         
   def deleteOrdItem(self, ordItem):
      ordText = str(ordItem.text())
      self.segOrdStrSet.remove(ordText)
      self.updateOrderingListBox()
   
   
   def getTabToDisplay(self):
      return self.tabToDisplay

   def updateOrderingListBox(self):
      self.segOrdListBox.clear()
      segOrdList = list(self.segOrdStrSet)
      segOrdList.sort()
      totalTries = 0
      for ordStr in segOrdList:
         self.segOrdListBox.addItem(QListWidgetItem(ordStr))
         totalTries += self.calculateTries(ordStr)
      if totalTries > BILLION_INT:
         self.totalSearchTriesDisplay.setText(OVER_BILLION_STR)
      else:         
         self.totalSearchTriesDisplay.setText(str(totalTries))
      
   def calculateTries(self, ordStr):
      ordIntList = [int(indexStr) for indexStr in ordStr.split(',')]
      totalTries = 1
      # Multiply each of the totals of segment instance together.
      for ordInt in ordIntList:
         totalTries *= self.segDefList[ordInt-1].getSegListLen()
      return totalTries
예제 #10
0
class IpetPbHistoryWindow(IpetMainWindow):

    NO_SELECTION_TEXT = "no selection"
    default_cmap = 'spectral'
    imagepath = osp.sep.join((osp.dirname(__file__), osp.pardir, "images"))

    DEBUG = True

    def __init__(self, testrunfiles=[], evaluationfile=None):
        QtGui.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.file_menu = QtGui.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit,
                                 QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        loadaction = self.createAction(
            "&Load",
            self.loadTestruns,
            QKeySequence.Open,
            icon="Load-icon",
            tip="Load testrun from trn file (current test run gets discarded)")
        resetaction = self.createAction(
            "&Reset selected names",
            self.resetSelectedTestrunNames,
            QKeySequence.Undo,
            icon="",
            tip="Reset names of selected test runs")
        self.file_menu.addAction(loadaction)
        self.help_menu = QtGui.QMenu('&Help', self)
        self.edit_menu = QtGui.QMenu('&Edit', self)
        self.edit_menu.addAction(resetaction)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        self.menuBar().addMenu(self.edit_menu)

        self.help_menu.addAction('&About', self.about)

        self.main_widget = QtGui.QWidget(self)

        lwframe = QFrame(self.main_widget)
        l = QtGui.QVBoxLayout(self.main_widget)
        self.sc = MyStaticMplCanvas(self.main_widget,
                                    width=5,
                                    height=4,
                                    dpi=100)
        toolbar = IpetNavigationToolBar(self.sc, self.main_widget)

        l.addWidget(toolbar)
        l.addWidget(self.sc)
        h = QtGui.QHBoxLayout(lwframe)
        l.addWidget(lwframe)

        self.trListWidget = QListWidget()
        #         for item in list("ABC"):
        #             self.trListWidget.addItem((item))
        self.trListWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        h.addWidget(self.trListWidget)
        self.connect(self.trListWidget, SIGNAL("itemSelectionChanged()"),
                     self.selectionChanged)

        self.trListWidget.itemChanged.connect(self.testrunItemChanged)

        v = QtGui.QVBoxLayout(lwframe)

        self.probListWidget = QListWidget()
        #         for item in list("12345"):
        #             self.probListWidget.addItem((item))
        self.probListWidget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        v.addWidget(self.probListWidget)
        self.connect(self.probListWidget, SIGNAL("itemSelectionChanged()"),
                     self.selectionChanged)

        self.testSetWidget = QListWidget()
        v.addWidget(self.testSetWidget)
        self.testSetWidget.addItem(self.NO_SELECTION_TEXT)
        for t in TestSets.getTestSets():
            self.testSetWidget.addItem(str(t))
        h.addLayout(v)
        self.connect(self.testSetWidget, SIGNAL("itemSelectionChanged()"),
                     self.selectionChanged)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)
        self.testruns = []
        self.testrunnames = {}

        for tr in testrunfiles:
            tr = TestRun.loadFromFile(str(tr))
            try:
                self.addTestrun(tr)
            except Exception as e:
                print(e)

        self.evaluation = None
        if evaluationfile is not None:
            self.evaluation = IPETEvaluation.fromXMLFile(evaluationfile)


#         self.primallines = {}
#         self.duallines = {}
#         self.primalpatches = {}

        self.statusBar().showMessage("Ready to load some test run data!", 5000)

    def createAction(self,
                     text,
                     slot=None,
                     shortcut=None,
                     icon=None,
                     tip=None,
                     checkable=False,
                     signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(
                QIcon(osp.sep.join((self.imagepath, "%s.png" % icon))))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)

        return action

    def getSelectedProblist(self):
        selectedprobs = [
            str(item.text()) for item in self.probListWidget.selectedItems()
        ]
        selitem = self.testSetWidget.selectedItems()[0]
        if selitem.text() != self.NO_SELECTION_TEXT:
            testsetprobs = set(TestSets.getTestSetByName(selitem.text()))
            selectedprobs = [p for p in selectedprobs if p in testsetprobs]

        return selectedprobs

    def getSelectedTestrunList(self):
        return [
            tr for idx, tr in enumerate(self.testruns)
            if self.trListWidget.isItemSelected(self.trListWidget.item(idx))
        ]

    def selectionChanged(self):
        if len(self.testruns) == 0:
            return

        problist = self.getSelectedProblist()
        if len(problist) == 0:
            return

        testruns = self.getSelectedTestrunList()
        if len(testruns) == 0:
            return

        self.update_Axis(problist, testruns)

    def testrunItemChanged(self):
        curritem = self.trListWidget.currentItem()

        if not curritem:
            return

        rowindex = self.trListWidget.currentRow()
        if rowindex < 0 or rowindex > len(self.testruns):
            return

        newtext = str(curritem.text())
        testrun = self.testruns[rowindex]

        self.setTestrunName(testrun, newtext)

    def resetSelectedTestrunNames(self):
        for tr in self.getSelectedTestrunList():
            self.resetTestrunName(tr)

    def getTestrunName(self, testrun):
        """
        returns the test run name as specified by the user
        """
        return self.testrunnames.get(testrun.getName(), testrun.getName())

    def setTestrunName(self, testrun, newname):
        self.debugMessage("Changing testrun name from %s to %s" %
                          (self.getTestrunName(testrun), newname))

        self.testrunnames[testrun.getName()] = newname

    def resetTestrunName(self, testrun):
        try:
            del self.testrunnames[testrun.getName()]
            item = self.trListWidget.item(self.testruns.index(testrun))
            item.setText((self.getTestrunName(testrun)))
        except KeyError:
            pass

    def updateStatus(self, message):
        self.statusBar().showMessage(message, 5000)

    def fileQuit(self):
        self.close()

    def addTestrun(self, tr):
        self.testruns.append(tr)
        self.probListWidget.clear()
        self.trListWidget.clear()

        for testrun in self.testruns:
            item = QListWidgetItem((self.getTestrunName(testrun)))
            self.trListWidget.addItem(item)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)

        problems = []
        if len(self.testruns) > 0:
            problems = self.testruns[0].getProblemNames()
        if len(self.testruns) > 1:
            for testrun in self.testruns[1:]:
                problems = [
                    p for p in problems if p in set(testrun.getProblemNames())
                ]

        for prob in sorted(problems):
            self.probListWidget.addItem(str(prob))

        self.trListWidget.selectAll()

    def closeEvent(self, ce):
        self.fileQuit()

    def debugMessage(self, message):
        if self.DEBUG:
            print(message)
        else:
            pass

    def loadTestruns(self):
        thedir = str(".")
        filenames = QFileDialog.getOpenFileNames(
            self,
            caption=("%s - Load testruns" % QApplication.applicationName()),
            directory=thedir,
            filter=str("Testrun files (*.trn)"))
        if filenames:
            loadedtrs = 0
            notloadedtrs = 0
            for filename in filenames:
                try:
                    print(filename)
                    tr = TestRun.loadFromFile(str(filename))
                    try:
                        self.addTestrun(tr)
                    except Exception as e:
                        print(e)

                    loadedtrs += 1
                except Exception:
                    notloadedtrs += 1

            message = "Loaded %d/%d test runs" % (loadedtrs,
                                                  loadedtrs + notloadedtrs)
            self.updateStatus(message)

        pass

    def update_Axis(self, probnames, testruns):
        """
        update method called every time a new instance was selected
        """
        #self.resetAxis()
        # make up data for plotting method
        x = {}
        y = {}
        z = {}
        zx = {}
        kws = {}
        duallinekws = {}
        dualbarkws = {}
        baseline = 0

        if len(probnames) == 1:
            self.updateStatus("Showing problem %s on %d test runs" %
                              (probnames[0], len(testruns)))
        else:
            self.updateStatus("Showing mean over %d problems on %d test runs" %
                              (len(probnames), len(testruns)))
        self.resetAxis()
        usenormalization = True
        showdualbound = True
        xmax = xmin = ymax = ymin = 0
        labelorder = []
        for testrun in testruns:
            testrunname = self.getTestrunName(testrun)

            if len(probnames) == 1:
                x[testrunname], y[testrunname] = getProcessPlotData(
                    testrun, probnames[0], usenormalization, access="name")
            else:
                x[testrunname], y[testrunname] = getMeanIntegral(testrun,
                                                                 probnames,
                                                                 access="name")
            if not usenormalization and len(probnames) == 1:
                baseline = testrun.problemGetOptimalSolution(probnames[0])
                y[testrunname] -= baseline

            xmax = max(xmax, max(x[testrunname]))
            ymax = max(ymax, max(y[testrunname]))
            ymin = min(ymin, min(y[testrunname]))
            print(y[testrunname])
            print(y[testrunname][1:] - y[testrunname][:-1] > 0)
            if numpy.any(y[testrunname][1:] - y[testrunname][:-1] > 0):
                logging.warn(
                    "Error: Increasing primal gap function on problems {}".
                    format(probnames))
            if showdualbound:
                arguments = {
                    "historytouse": Key.DualBoundHistory,
                    "boundkey": Key.DualBound
                }
                if len(probnames) == 1:
                    zx[testrunname], z[testrunname] = getProcessPlotData(
                        testrun,
                        probnames[0],
                        usenormalization,
                        access="name",
                        **arguments)
                else:
                    zx[testrunname], z[testrunname] = getMeanIntegral(
                        testrun, probnames, access="name", **arguments)

                # normalization requires negative dual gap
                if usenormalization:
                    z[testrunname] = -numpy.array(z[testrunname])

                ymin = min(ymin, min(z[testrunname]))

                duallinekws[testrunname] = dict(linestyle='dashed')
                dualbarkws = dict(alpha=0.1)

            # set special key words for the testrun
            kws[testrunname] = dict(alpha=0.1)
            labelorder.append(testrunname)
            # for now, only one color cycle exists
            #colormap = cm.get_cmap(name='spectral', lut=128)
            #self.axes.set_color_cycle([colormap(i) for i in numpy.linspace(0.1, 0.9, len(self.gui.getTestrunList()))])

            # call the plot on the collected data
        self.primalpatches, self.primallines, _ = self.axisPlotForTestrunData(
            x,
            y,
            baseline=baseline,
            legend=False,
            labelsuffix=" (primal)",
            plotkw=kws,
            barkw=kws,
            labelorder=labelorder)
        if showdualbound:
            __, self.duallines, _ = self.axisPlotForTestrunData(
                zx,
                z,
                step=False,
                baseline=0,
                legend=False,
                labelsuffix=" (dual)",
                plotkw=duallinekws,
                barkw=dualbarkws,
                labelorder=labelorder)

        # set a legend and limits
        self.sc.axes.legend(fontsize=8)
        self.sc.axes.set_xlim(
            (xmin - 0.05 * (xmax - xmin), xmax + 0.05 * (xmax - xmin)))
        self.sc.axes.set_ylim(
            (ymin - 0.1 * (ymax - ymin), ymax + 0.1 * (ymax - ymin)),
            emit=True)

        self.sc.draw()

    def axisPlotForTestrunData(self,
                               dataX,
                               dataY,
                               bars=False,
                               step=True,
                               barwidthfactor=1.0,
                               baseline=0,
                               testrunnames=None,
                               legend=True,
                               labelsuffix="",
                               colormapname="spectral",
                               plotkw=None,
                               barkw=None,
                               labelorder=[]):
        """
        create a plot for your X and Y data. The data can either be specified as matrix, or as a dictionary
        specifying containing the labels as keys.

        - returns the axes object and a dictionary {label:line} of the line plots that were added

        arguments:
        -dataX : The X data for the plot, exspected either as
                    1: A dictionary with the plot labels as keys and some iterable as value-list
                    OR
                    2: A list of some iterables which denote the X values.

        -dataY : The y plot data of the plot. Must be specified in the same way as the X data

        -testrunnames: labels for axis legend. they will overwrite the labels specified by dictionary-organized data.
                       if testrunnames == None, the primallines will either be labelled from '0' to 'len(dataX)-1',
                       or inferred from the dataX-keys().
        -ax: matplotlib axes object, will be created as new axis if not specified

        -legend: specify if legend should be created, default True
        -colormapname: name of the colormap to use in case no colors are specified by the 'colors' argument

        -kw, other keywords for the plotting function, such as transparency, etc. can be specified for every plot
            separately, either as a dictionary with the dataX-keys, or as a kw-list with the same length as the
            dataX list
        """

        # index everything by labels, either given as dictionary keys, or integer indices ranging from 0 to len(dataX) - 1
        assert type(dataX) is type(dataY)
        if type(dataX) is dict:
            labels = list(dataX.keys())
            if testrunnames is None:
                testrunnames = {label: label for label in labels}
        else:
            assert type(dataX) is list
            labels = list(range(len(dataX)))

            if testrunnames is None:
                testrunnames = {label: repr(label) for label in labels}

        # init colors if not given

        try:
            colormap = cm.get_cmap(name=colormapname, lut=128)
        except ValueError:
            print("Colormap of name ", colormapname, " does not exist")
            colormap = cm.get_cmap(name=IpetPbHistoryWindow.default_cmap,
                                   lut=128)
        colortransform = numpy.linspace(0.1, 0.9, len(labels))

        colors = {
            label: colormap(colortransform[index])
            for index, label in enumerate(labels)
        }

        patches = {}
        lines = {}

        if not labelorder:
            labelorder = sorted(labels)
        for label in labelorder:
            # retrieve special key words, or use the entire keyword dictionary
            if plotkw is not None:
                linekw = plotkw.get(testrunnames[label], plotkw)
            else:
                linekw = {}
            if barkw is not None:
                bkw = barkw.get(testrunnames[label], barkw)
            else:
                bkw = {}

            x = dataX[label]
            y = dataY[label]
            idd = testrunnames[label]
            if bars:
                patches[idd] = self.sc.axes.bar(x[:-1],
                                                y[:-1],
                                                width=barwidthfactor *
                                                (x[1:] - x[:-1]),
                                                bottom=baseline,
                                                color=colors[label],
                                                linewidth=0,
                                                **bkw)
            else:
                patches[idd] = []
            # # use step functions for primal and plot for dual plots
            plotlabel = idd + labelsuffix
            if step:
                #lines[idd], = ax.step(x, y + baseline, color=colors[label], label=idd, where='post')
                lines[idd], = self.sc.axes.step(x,
                                                y,
                                                label=plotlabel,
                                                where='post')
            else:
                #lines[idd], = ax.plot(x, y + baseline, color=colors[label], label=idd, **linekw)
                lines[idd], = self.sc.axes.plot(x,
                                                y + baseline,
                                                label=plotlabel,
                                                **linekw)

        if len(labels) > 0 and legend:
            self.sc.axes.legend(fontsize=8)
        return (patches, lines, self.sc.axes)

    def resetAxis(self):
        """
        reset axis by removing all primallines and primalpatches previously drawn.
        """
        self.sc.axes.cla()

    def about(self):
        QtGui.QMessageBox.about(
            self, "About", """embedding_in_qt4.py example
Copyright 2005 Florent Rougon, 2006 Darren Dale

This program is a simple example of a Qt4 application embedding matplotlib
canvases.

It may be used and modified with no restriction; raw copies as well as
modified versions may be distributed without limitation.""")