Exemple #1
0
 def _createBrowserWindow(self):
     """
     Create the browser window with a I{QTextBrowser}. This display component is chosen over I{QWebView} because
     WebKit is not included in the standard PySide installation as distributed with IDA Pro.
     """
     self.browser_window = QTextBrowser()
     self.browser_window.anchorClicked.connect(self._browserAnchorClicked)
Exemple #2
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.resultList = QTextBrowser()
        self.resultInput = QLineEdit(
            "Enter an expression and press Return key")

        layout = QVBoxLayout()
        layout.addWidget(self.resultList)
        layout.addWidget(self.resultInput)
        self.setLayout(layout)

        self.resultInput.selectAll()
        self.resultInput.setFocus()

        # New way of Connect the signal
        self.resultInput.returnPressed.connect(self.compute)
        # Old Way of connect signal. Does not throw any error
        #self.connect(self.resultInput,SIGNAL("returnPressed()"),self.compute)

    def compute(self):
        try:
            text = self.resultInput.text()
            self.resultList.append("{0} = <b> {1} </b>".format(
                text, eval(text)))
        except:
            self.resultList.append(
                "<font color=red /><b> Expression invalid </b>")
Exemple #3
0
class HelpForm(QDialog):
	def __init__(self, page, parent=None):
		super(HelpForm, self).__init__(parent)
		self.pageLabel = QLabel("<font color=purple size=30><b>Help Contents</b></font>")
		self.pageLabel.setMinimumSize(400, 50)
		self.pageLabel.setAlignment(Qt.AlignCenter)
		appicom = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appicom)
		toolBar = QToolBar()

		pixmap = QPixmap(":/icons/njnlogo.png")
		lbl = QLabel(self)
		lbl.setPixmap(pixmap)
		lbl.setFixedSize(70, 70)
		toolBar.setMinimumHeight(70)
		toolBar.setMaximumHeight(80)
		toolBar.addWidget(lbl)
		toolBar.addWidget(self.pageLabel)

		self.textBrowser = QTextBrowser()

		layout = QVBoxLayout()
		layout.addWidget(toolBar)
		layout.addWidget(self.textBrowser, 1)
		self.setLayout(layout)

		self.textBrowser.setSource(QUrl(page))
		self.setMinimumSize(650, 650)
		self.setMaximumSize(650, 660)
		self.setWindowTitle("Nigandu English to Tamil Dictionary | HELP")
class Form(QDialog):

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resultsLists = QTextBrowser()
        self.resultsInput = QLineEdit('Enter an expression and press return key')

        # Layout the application - vertical order
        layout = QVBoxLayout()
        layout.addWidget(self.resultsLists)
        layout.addWidget(self.resultsInput)

        self.setLayout(layout)


        # Define signal - signal for pressing enter
        # When the signal is set it calls the method compute
        self.resultsInput.returnPressed.connect(self.compute)

        # Force window to stay on top when start
        # self.setFocusPolicy(Qt.StrongFocus)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        self.resultsInput.selectAll()
        self.resultsInput.setFocus()


    def compute(self):
        try:
            text = self.resultsInput.text()
            self.resultsLists.append('{0} = <b>{1}</b>'.format(text, eval(text)))

        except:
            self.resultsLists.append('<font color=red><b>Expression invalid</b></font>')
Exemple #5
0
    def createWidgets(self):
        self.browser = QTextBrowser()
        self.tooltips.append((self.browser, """<p><b>Information</b></p>
<p>Show basic information about the current index.</p>"""))
        self.browser.zoomIn(1)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
        self.tooltips.append((self.closeButton, """<p><b>Close</b></p>
<p>Close the dialog.</p>"""))
        self.closeButton.clicked.connect(self.reject)
Exemple #6
0
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.resultList = QTextBrowser()
        self.resultInput = QLineEdit(
            "Enter an expression and press Return key")

        layout = QVBoxLayout()
        layout.addWidget(self.resultList)
        layout.addWidget(self.resultInput)
        self.setLayout(layout)

        self.resultInput.selectAll()
        self.resultInput.setFocus()

        # New way of Connect the signal
        self.resultInput.returnPressed.connect(self.compute)
Exemple #7
0
 def createWidgets(self, eids, name):
     self.browser = QTextBrowser()
     self.browser.setOpenExternalLinks(False)
     self.browser.setOpenLinks(False)
     text = ["<html>"]
     if not eids:
         text.append("<font color=darkgreen>No entries match the "
                     "“{}” check.</font>".format(name))
     else:
         self.loadSaveSize = True
         text.append("<p><font color=navy>{:,} entries match the "
                     "“{}” check.</font></p>".format(len(eids), name))
         for eid in eids:
             entry = self.state.model.entry(eid)
             if entry:
                 term = Lib.elidePatchHtml(entry.term, self.state)
                 prefix = "{} ".format(MAIN_INDICATOR if entry.peid ==
                                       ROOT else SUB_INDICATOR)
                 text.append('{}<a href="{}">{}</a><br>'.format(
                     prefix, eid, term))
     text.append("</html>")
     self.browser.setHtml("".join(text))
     self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
Exemple #8
0
 def __init__(self, title, message, parent=None):
     super().__init__(parent)
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
     self.setWindowTitle("{} — {}".format(title,
                                          QApplication.applicationName()))
     self.browser = QTextBrowser()
     self.browser.setOpenExternalLinks(False)
     self.browser.setOpenLinks(False)
     self.browser.setHtml(message)
     self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
     layout = QVBoxLayout()
     hbox = QHBoxLayout()
     hbox.addStretch()
     hbox.addWidget(self.closeButton)
     hbox.addStretch()
     layout.addWidget(self.browser)
     layout.addLayout(hbox)
     widget = QWidget()
     widget.setLayout(layout)
     self.setCentralWidget(widget)
     self.browser.setFocus()
     self.closeButton.clicked.connect(self.close)
    def __init__(self, client, method):
        super(Tab, self).__init__(None)

        self.client = client
        self.method = method

        horiz = QHBoxLayout(self)
        
        left = QWidget()
        
        horiz.addWidget(left)
        
        layout = QFormLayout(left)
        
        self.fields = []
        for param in method[1]:
            field = QLineEdit()
            self.fields.append(field)
            layout.addRow(param[0], field)

        button = QPushButton("Execute Web Service")
        button.clicked.connect(self.execute)
        layout.addWidget(button)
        
        display = QTabWidget()
        
        self.result = QTextBrowser()
        display.addTab(self.result, "Result")
        
        self.request = QTextBrowser()
        display.addTab(self.request, "Request", )
        
        self.response = QTextBrowser()
        display.addTab(self.response, "Response")
        
        horiz.addWidget(display)
Exemple #10
0
class Form(QDialog):
    def __init__(self, title, message, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.setWindowTitle("{} — XindeX".format(title))
        self.create_widgets(message)
        self.layout_widgets()
        self.create_connections()

    def create_widgets(self, message):
        self.label = QTextBrowser()
        self.label.setStyleSheet("QTextBrowser { background: #eee; }")
        self.label.setText(message)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)

    def layout_widgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.label, 2)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def create_connections(self):
        self.buttonBox.rejected.connect(self.close)
        self.buttonBox.accepted.connect(self.close)
Exemple #11
0
class ErrorDialog(QDialog):

    def __init__(self, files_not_processed, parent=None):
        super(ErrorDialog, self).__init__(parent)

        self.files_not_processed = files_not_processed
        self.setMinimumWidth(600)
        self.setWindowTitle(u'Kaikkia tiedostoja ei pystytty mittaamaan')
        icon = QIcon()
        icon.addPixmap(
            QPixmap(":/Images/aktools_48x48.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.text_browser = QTextBrowser()
        self.label = QLabel(u'Seuraavissa tiedostoissa havaittiin virheitä:')
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.text_browser)
        self.setLayout(self.layout)
        self.list_files_not_processed()

    def list_files_not_processed(self):

        for i in self.files_not_processed:
            self.text_browser.append(i)
 def __init__(self):
     super(HighwayAnalyzeWidget,self).__init__()
     self.averageSimulationTime = 325.0
     mainLayout = QVBoxLayout()
     mainLayout.setAlignment(Qt.AlignTop|Qt.AlignHCenter)
     mainLayout.setSpacing(0)
     self.setLayout(mainLayout)
     topWidget = QWidget()
     self.topLayout = QHBoxLayout()
     self.topLayout.setSpacing(0)
     topWidget.setLayout(self.topLayout)
     topLeftWidget = QWidget()
     self.topLeftLayout = QVBoxLayout()
     topLeftWidget.setLayout(self.topLeftLayout)
     self.setupTopGroup()
     self.setupFilterGroup()
     self.topLayout.addWidget(topLeftWidget)
     self.layout().addWidget(topWidget)
     # Button and log
     buttonAndLogWidget = QWidget()
     buttonAndLogWidget.setLayout(QVBoxLayout())
     # Analyze the results BUTTON
     self.analyzeResultsButton = QPushButton('Analyze the results')
     self.analyzeResultsButton.clicked.connect(self.analyzeResults)
     self.analyzeResultsButton.setEnabled(False)
     buttonAndLogWidget.layout().addWidget(self.analyzeResultsButton)
     # LOG
     self.logText = QTextBrowser()
     self.logText.setFont(QFont('Century Gothic', 7))
     self.logText.setWordWrapMode(QTextOption.NoWrap)
     buttonAndLogWidget.layout().addWidget(self.logText)
     self.topLayout.addWidget(buttonAndLogWidget)
     self.results = []
     self.logFile = os.path.join(self.resultsPath(), 'analyze_'+os.uname()[1]+'.log')
     # Image
     self.picLabel = QLabel()
     self.picLabel.setAlignment(Qt.AlignHCenter)
     #self.picLabel.resize(800,600)
     self.picLabel.setMinimumSize(800,600)
     self.layout().addWidget(self.picLabel)
class Tab(QWidget):
    def __init__(self, client, method):
        super(Tab, self).__init__(None)

        self.client = client
        self.method = method

        horiz = QHBoxLayout(self)
        
        left = QWidget()
        
        horiz.addWidget(left)
        
        layout = QFormLayout(left)
        
        self.fields = []
        for param in method[1]:
            field = QLineEdit()
            self.fields.append(field)
            layout.addRow(param[0], field)

        button = QPushButton("Execute Web Service")
        button.clicked.connect(self.execute)
        layout.addWidget(button)
        
        display = QTabWidget()
        
        self.result = QTextBrowser()
        display.addTab(self.result, "Result")
        
        self.request = QTextBrowser()
        display.addTab(self.request, "Request", )
        
        self.response = QTextBrowser()
        display.addTab(self.response, "Response")
        
        horiz.addWidget(display)
        
    def execute(self):
        service_method = getattr(self.client.service, self.method[0])
        args = [field.text() for field in self.fields]
        result = service_method(*args)
        self.result.setText(str(result))
        self.request.setText(str(self.client.last_sent()))
        self.response.setText(str(self.client.last_received()))
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resultsLists = QTextBrowser()
        self.resultsInput = QLineEdit('Enter an expression and press return key')

        # Layout the application - vertical order
        layout = QVBoxLayout()
        layout.addWidget(self.resultsLists)
        layout.addWidget(self.resultsInput)

        self.setLayout(layout)


        # Define signal - signal for pressing enter
        # When the signal is set it calls the method compute
        self.resultsInput.returnPressed.connect(self.compute)

        # Force window to stay on top when start
        # self.setFocusPolicy(Qt.StrongFocus)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        self.resultsInput.selectAll()
        self.resultsInput.setFocus()
Exemple #15
0
    def __init__(self,parent):
        super(HelpDialog,self).__init__(parent)

        title = _("A bit of help")
        self.setWindowTitle(title)
        top_layout = QVBoxLayout()
        self.title_widget = TitleWidget(title,self)
        top_layout.addWidget(self.title_widget)

        browser = QTextBrowser()

        import os.path
        from koi.Configurator import resource_dir

        with open( os.path.join(resource_dir,"manual.html"), encoding='utf-8') as input:
            html = input.read()
        browser.setHtml(html)

        # browser.setLineWrapMode(QTextEdit.NoWrap)
        #         browser.setHtml("""<h1>Tables</h1>
        #
        # In tables you can edit, don't forget these few useful shortcuts :
        # <ul>
        # <li><b>F5</b> : will insert a line under your cursor</li>
        # <li><b>Shift + F5</b> : will append a line at the end of the table</li>
        # <li><b>F8</b> : will delete the line under your cursor (if you're allowed to)</li>
        # <li><b>F1</b> and <b>Shift + F1</b> : will allow you to move up/move down a row </li>
        # </ul>
        # """)
        # browser.setMinimumWidth(browser.document().documentLayout().documentSize().toSize().width())
        browser.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        top_layout.addWidget(browser)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton( QDialogButtonBox.Ok)

        top_layout.addWidget(self.buttons)
        self.setLayout(top_layout)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
class HighwayAnalyzeWidget(QWidget):
    def __init__(self):
        super(HighwayAnalyzeWidget,self).__init__()
        self.averageSimulationTime = 325.0
        mainLayout = QVBoxLayout()
        mainLayout.setAlignment(Qt.AlignTop|Qt.AlignHCenter)
        mainLayout.setSpacing(0)
        self.setLayout(mainLayout)
        topWidget = QWidget()
        self.topLayout = QHBoxLayout()
        self.topLayout.setSpacing(0)
        topWidget.setLayout(self.topLayout)
        topLeftWidget = QWidget()
        self.topLeftLayout = QVBoxLayout()
        topLeftWidget.setLayout(self.topLeftLayout)
        self.setupTopGroup()
        self.setupFilterGroup()
        self.topLayout.addWidget(topLeftWidget)
        self.layout().addWidget(topWidget)
        # Button and log
        buttonAndLogWidget = QWidget()
        buttonAndLogWidget.setLayout(QVBoxLayout())
        # Analyze the results BUTTON
        self.analyzeResultsButton = QPushButton('Analyze the results')
        self.analyzeResultsButton.clicked.connect(self.analyzeResults)
        self.analyzeResultsButton.setEnabled(False)
        buttonAndLogWidget.layout().addWidget(self.analyzeResultsButton)
        # LOG
        self.logText = QTextBrowser()
        self.logText.setFont(QFont('Century Gothic', 7))
        self.logText.setWordWrapMode(QTextOption.NoWrap)
        buttonAndLogWidget.layout().addWidget(self.logText)
        self.topLayout.addWidget(buttonAndLogWidget)
        self.results = []
        self.logFile = os.path.join(self.resultsPath(), 'analyze_'+os.uname()[1]+'.log')
        # Image
        self.picLabel = QLabel()
        self.picLabel.setAlignment(Qt.AlignHCenter)
        #self.picLabel.resize(800,600)
        self.picLabel.setMinimumSize(800,600)
        self.layout().addWidget(self.picLabel)
    def setupTopGroup(self):
        topGroup = QGroupBox("Simulation Results")
        self.resultsPathLineEdit = SimpleOption('resultsPath','Results Path','/home/thomas/Dropbox/Keio/research/results/')
        topGroupLayout = QVBoxLayout()
        topGroupLayout.setSpacing(0)
        topGroupLayout.setAlignment(Qt.AlignTop)
        topGroupLayout.addWidget(self.resultsPathLineEdit)
        self.loadResultsLabel = QLabel()
        self.loadResultsLabel.setAlignment(Qt.AlignHCenter)
        topGroupLayout.addWidget(self.loadResultsLabel)
        self.loadResultsButton = QPushButton("Load the results")
        self.loadResultsButton.clicked.connect(self.loadResults)
        topGroupLayout.addWidget(self.loadResultsButton)
        topGroup.setLayout(topGroupLayout)
        self.topLeftLayout.addWidget(topGroup)
    def resultsPath(self):
        return self.resultsPathLineEdit.getValue()
    def setupFilterGroup(self):
        filterGroup = QGroupBox('Filter the results')
        filterGroupLayout = QVBoxLayout()
        filterGroupLayout.setSpacing(0)
        filterGroupLayout.setAlignment(Qt.AlignTop)
        # Distribution Model
        self.filterDistribution = SimpleComboboxOption('dis','Speed Distribution Model',3, True, 'Uniform','Exponential','Normal','Log Normal')
        filterGroupLayout.addWidget(self.filterDistribution)
        self.filterDistribution.setVisible(False)
        # Number of results per point
        self.filterNb = SimpleSpinOption('simuNbMin', 'Minimum results for a given setting', 10, integer=True, checkable=True)
        self.filterNb.checkBox.setChecked(True)
        filterGroupLayout.addWidget(self.filterNb)
        # Filter the date
        dateWidget = QWidget()
        dateWidget.setLayout(QHBoxLayout())
        self.filterDate = QCheckBox('After')
        self.filterDate.setChecked(QSettings().value('filterDate','0')=='1')
        dateWidget.layout().addWidget(self.filterDate)
        self.filterDateYear = QComboBox()
        for m in xrange(2010,2012):
            self.filterDateYear.addItem(str(m))
        self.filterDateYear.setCurrentIndex(int(QSettings().value('dateYear', 1)))
        dateWidget.layout().addWidget(self.filterDateYear)
        dateWidget.layout().addWidget(QLabel('Year'))
        self.filterDateMonth = QComboBox()
        for m in xrange(1,13):
            self.filterDateMonth.addItem(str(m))
        self.filterDateMonth.setCurrentIndex(int(QSettings().value('dateMonth', 4)))
        dateWidget.layout().addWidget(self.filterDateMonth)
        dateWidget.layout().addWidget(QLabel('Month'))
        self.filterDateDay = QComboBox()
        for d in xrange(1,32):
            self.filterDateDay.addItem(str(d))
        self.filterDateDay.setCurrentIndex(int(QSettings().value('dateDay', 0)))
        dateWidget.layout().addWidget(self.filterDateDay)
        dateWidget.layout().addWidget(QLabel('Day'))
        filterGroupLayout.addWidget(dateWidget)
        filterGroup.setLayout(filterGroupLayout)
        self.topLeftLayout.addWidget(filterGroup)
        # Filter the scenario
        self.filterScenar = SimpleComboboxOption('scenar','Scenario',1, True, 'vanet-highway-test-thomas','vanet-highway-scenario2')
        filterGroupLayout.addWidget(self.filterScenar)
        # Filter gap
        self.filterGap = SimpleSpinOption('avgdistanalyze','Average Distance (m)',100, checkable=True)
        filterGroupLayout.addWidget(self.filterGap)
    def loadResults(self):
        self.loadResultsButton.setText('Loading the results...')
        self.loadResultsButton.setEnabled(False)
        self.results = []
        self.resultsThread = LoadResults(resultsPath=self.resultsPath())
        self.resultsThread.done.connect(self.loadResultsDone)
        self.resultsThread.error.connect(self.loadResultsError)
        self.resultsThread.start()
    @Slot(str)
    def loadResultsError(self, errorMsg):
        QMessageBox.critical(self, 'Error!', errorMsg)
        self.analyzeResultsButton.setEnabled(False)
    @Slot(dict)
    def loadResultsDone(self, results):
        self.results = results
        resultsNb = len(self.results)
        msg= 'Found %d Simulation Results\n(%d invalid files, %d simulations failed)' % (resultsNb, self.resultsThread.fileUnloadable, self.resultsThread.simulationFailed)
        self.loadResultsLabel.setText(msg)
        #self.calculateAverageSimulationTime()
        self.loadResultsButton.setText('Reload the results')
        self.loadResultsButton.setEnabled(True)
        self.analyzeResultsButton.setEnabled(True)
        if resultsNb>0:
            self.analyzeResults()
    def calculateAverageSimulationTime(self):
        totalTime = 0
        nb = 0
        for r in self.results:
            if 'simulationTime' in r:
                #print 'simu time: %s' % r['simulationTime']
                totalTime += int(r['simulationTime'])
                nb += 1
            #print 'from %s: [%3.3f,%3.3f]' % (r['filename'], r['settings']['prate'],r['results']['timeToReachDest'])
        if nb<=0:
            errorMsg= 'No simulation found with simulationTime'
            QMessageBox.critical(self, 'Error!', errorMsg)
            self.averageSimulationTime = 290.0
        else:
            self.averageSimulationTime= totalTime/nb
            self.loadResultsLabel.setText(self.loadResultsLabel.text()+'\nAverage simulation time: %3.0f'%self.averageSimulationTime)
    def fil(self, r):
        return self.checkDis(r) and self.checkDate(r) and self.checkGap(r) and self.checkScenario(r)
    def checkDis(self,r):
        return (not self.filterDistribution.checkBox.isChecked()) or r['settings']['dis']==self.filterDistribution.getValue()
    def checkDate(self, r):
        return (not self.filterDate.isChecked()) or (r['date'] >= datetime(int(self.filterDateYear.currentText()), int(self.filterDateMonth.currentText()), int(self.filterDateDay.currentText())))
    def checkScenario(self, r):
        return (not self.filterScenar.checkBox.isChecked()) or r['scenario']==self.filterScenar.getName()
    def checkGap(self, r):
        return (not self.filterGap.checkBox.isChecked()) or float(r['settings']['avgdist'])==float(self.filterGap.getValue())
    def analyzeResults(self):
        self.saveSettings()
        if len(self.results)<=0:
            QMessageBox.critical(self, 'Error!', 'No results loaded :s')
            return
        self.log("=== ANALYZING RESULTS ===")
        self.logText.clear()
        p=0
        meanValues = {}
        uniqueName = dateToFilename()
        gnuPlotDataFile =os.path.join(self.resultsPath(),'graphs/' + uniqueName+'.dat')
        with open(gnuPlotDataFile,'w') as data:
            while p<=100:
                nb = 0
                totalTimeToReachDest = 0
                totalSimulationTime  = 0
                for result in filter(lambda x: x['settings']['prate']==p and self.fil(x), self.results):
                    totalSimulationTime  += float(result['simulationTime'])
                    totalTimeToReachDest += float(result['results']['timeToReachDest'])
                    nb += 1
                if self.filterNb.checkBox.isChecked():
                    minNb = self.filterNb.getValue()
                else:
                    minNb = 0
                if nb>minNb:
                    meanSimulationTime  = float(1.0*totalSimulationTime/nb)
                    meanTimeToReachDest = float(1.0*totalTimeToReachDest/nb)
                    meanValues[p] = {'prate':p,
                                     'simuLationTime':meanSimulationTime,
                                     'simulationsNb':nb,
                                     'timeToReachDest':meanTimeToReachDest}
                    self.log(meanValues[p])
                    toPlot = '%s %s' % (p, meanValues[p]['timeToReachDest'])
                    #print toPlot
                    data.write(toPlot+'\n')
                p += 1
            data.close()
        if len(meanValues)>0:
            outputPic = 'graphs/' + uniqueName
            s = subprocess.Popen(['./toPlot.sh', outputPic, gnuPlotDataFile], cwd=self.resultsPath())
            s.wait()
            outputPicPath = os.path.join(self.resultsPath(),outputPic+'.svg')
            pic = QImage(outputPicPath)
            #pic = pic.scaled(QSize(640,480))
            self.picLabel.setPixmap(QPixmap(pic))
            #os.system(os.path.join(self.resultsPath(),'toPlot.sh'))
        else:
            QMessageBox.critical(self, 'Error!', 'No simulation satisfies the criteria...')
    def log(self, txt):
        toLog = str(txt)
        toLogFile = '%s | %s' % (datetime.now(), txt)
        with open(self.logFile, 'a') as logFile:
            logFile.write(toLogFile+'\n')
        self.logText.append(toLog)
    def saveSettings(self):
        QSettings().setValue('simuNbMin', self.filterNb.getValue())
        QSettings().setValue('avgdistanalyze', self.filterGap.getValue())
        QSettings().setValue('scenar', self.filterScenar.getValue())
        QSettings().setValue('dis', self.filterDistribution.getValue())
        QSettings().setValue('dateDay', self.filterDateDay.currentIndex())
        QSettings().setValue('dateMonth', self.filterDateMonth.currentIndex())
        QSettings().setValue('dateYear', self.filterDateYear.currentIndex())
        if self.filterDate.isChecked():
            QSettings().setValue('filterDate', '1')
        else:
            QSettings().setValue('filterDate', '0')
Exemple #17
0
class WinApiWidget(QtGui.QWidget):
    """
    A widget for allowing easy access to Windows API information. Front-end to the I{idascope.core.WinApiProvider}.
    """

    def __init__(self, parent):
        QtGui.QWidget.__init__(self)
        print "[|] loading WinApiWidget"
        self.parent = parent
        self.name = "WinAPI Browsing"
        self.icon = QIcon(self.parent.config.icon_file_path + "winapi.png")
        self.search_icon = QIcon(self.parent.config.icon_file_path + "search.png")
        self.back_icon = QIcon(self.parent.config.icon_file_path + "back.png")
        self.forward_icon = QIcon(self.parent.config.icon_file_path + "forward.png")
        self.online_icon = QIcon(self.parent.config.icon_file_path + "online.png")
        self.ida_proxy = self.parent.ida_proxy
        self.QtGui = QtGui
        self.QtCore = QtCore
        self.winapi = self.parent.winapi_provider
        self.old_keyword_initial = ""
        self.winapi.registerDataReceiver(self.populateBrowserWindow)
        self._createGui()
        self._updateAvailability()
        self._registerHotkeys()

    def _updateAvailability(self):
        """
        Adjust the availability of this widget by checking if the keyword database has been loaded or
        online mode is enabled.
        """
        if not self.winapi.hasOfflineMsdnAvailable() and \
            not self.winapi.hasOnlineMsdnAvailable():
            self.browser_window.setHtml("<p><font color=\"#FF0000\">Offline MSDN database is not available. To use " \
                + "it, have a look at the installation instructions located in the manual: " \
                + "IDAscope/documentation/manual.html. Online mode is deactivated as well.</font></p>")
            self.search_button.setEnabled(False)
            self.api_chooser_lineedit.setEnabled(False)
        else:
            self.browser_window.setHtml("<p>Enter a search term in the above field to search offline/online MSDN.</p>")
            self.search_button.setEnabled(True)
            self.api_chooser_lineedit.setEnabled(True)

    def _registerHotkeys(self):
        """
        Register hotkeys with IDAscope in order to ease the use of this widget.
        """
        self.parent.registerHotkey(self.parent.config.winapi_shortcut, self._navigateToHighlightedIdentifier)

    def _createGui(self):
        """
        Create the GUI for this widget and all of its components.
        """
        self._createBackButton()
        self._createNextButton()
        self._createOnlineButton()
        self._createApiChooserLineedit()
        self._createSearchButton()
        self._createBrowserWindow()

        winapi_layout = QtGui.QVBoxLayout()
        selection_widget = QtGui.QWidget()
        selection_layout = QtGui.QHBoxLayout()
        selection_layout.addWidget(self.online_button)
        selection_layout.addWidget(self.back_button)
        selection_layout.addWidget(self.next_button)
        selection_layout.addWidget(self.api_chooser_lineedit)
        selection_layout.addWidget(self.search_button)
        selection_widget.setLayout(selection_layout)
        winapi_layout.addWidget(selection_widget)
        winapi_layout.addWidget(self.browser_window)
        self.setLayout(winapi_layout)

    def _createBackButton(self):
        """
        Create a back button to allow easier browsing
        """
        self.back_button = QtGui.QPushButton(self.back_icon, "", self)
        self.back_button.setToolTip("Go back to previously accessed content.")
        self.back_button.resize(self.back_button.sizeHint())
        self.back_button.setEnabled(False)
        self.back_button.clicked.connect(self._onBackButtonClicked)

    def _createNextButton(self):
        """
        Create a next button to allow easier browsing
        """
        self.next_button = QtGui.QPushButton(self.forward_icon, "", self)
        self.next_button.setToolTip("Go forward to previously accessed content.")
        self.next_button.resize(self.next_button.sizeHint())
        self.next_button.setEnabled(False)
        self.next_button.clicked.connect(self._onNextButtonClicked)

    def _createOnlineButton(self):
        """
        Create a next button to allow easier browsing
        """
        self.online_button = QtGui.QPushButton(self.online_icon, "", self)
        self.online_button.setCheckable(True)
        if self.winapi.hasOnlineMsdnAvailable():
            self.online_button.setChecked(QtCore.Qt.Checked)
        self.online_button.setToolTip("Enable/disable MSDN online lookup.")
        self.online_button.resize(self.online_button.sizeHint())
        self.online_button.clicked.connect(self._onOnlineButtonClicked)

    def _createApiChooserLineedit(self):
        """
        Create the I{QLineEdit }used for selecting API names. This includes a QCompleter to make suggestions based on
        the keyword database.
        """
        self.api_chooser_lineedit = QLineEdit()
        self.api_chooser_lineedit.returnPressed.connect(self.populateBrowserWindow)
        self.api_chooser_lineedit.textChanged.connect(self._updateCompleterModel)

        completer = QCompleter()
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setModelSorting(QCompleter.CaseSensitivelySortedModel)
        self.completer_model = QStringListModel([])
        completer.setModel(self.completer_model)
        self.api_chooser_lineedit.setCompleter(completer)

    def _createSearchButton(self):
        """
        Create a search button besides the QLineEdit.
        """
        self.search_button = QtGui.QPushButton(self.search_icon, "", self)
        self.search_button.setToolTip("Search for the chosen API name, structure or whatever WinAPI documentation " \
            + "might have for you.")
        self.search_button.resize(self.search_button.sizeHint())
        self.search_button.clicked.connect(self._onSearchButtonClicked)

    def _createBrowserWindow(self):
        """
        Create the browser window with a I{QTextBrowser}. This display component is chosen over I{QWebView} because
        WebKit is not included in the standard PySide installation as distributed with IDA Pro.
        """
        self.browser_window = QTextBrowser()
        self.browser_window.anchorClicked.connect(self._browserAnchorClicked)

    def _updateCompleterModel(self):
        """
        Update the completer model used to make suggestions. The model is only updated if anything is entered into the
        search line and the initial character differs from the previous initial character.
        """
        keyword_data = []
        api_chooser_text = self.api_chooser_lineedit.text()
        if len(api_chooser_text) > 0:
            keyword_initial = api_chooser_text[0].lower()
            if keyword_initial != self.old_keyword_initial:
                self.old_keyword_initial = keyword_initial
                keyword_data = self.winapi.getKeywordsForInitial(keyword_initial)
                self.completer_model.setStringList(keyword_data)

    def populateBrowserWindow(self, content=""):
        """
        Populate the browser window based upon the entered term in the search line.
        @param content: the content to render in the browser
        @type content: str
        """
        if content == "":
            api_chooser_text = self.api_chooser_lineedit.text()
            if len(api_chooser_text) > 0:
                content = self.winapi.getKeywordContent(api_chooser_text)
        self.browser_window.setHtml(content)
        self._updateHistoryButtonState()

    def _onSearchButtonClicked(self):
        """
        Action that is performed when the search button is clicked. This will populate the browser window.
        """
        self.populateBrowserWindow()

    def _onBackButtonClicked(self):
        """
        Action that is performed when the search button is clicked. This will populate the browser window.
        """
        document_content, anchor = self.winapi.getPreviousDocumentContent()
        if document_content != "":
            self.browser_window.setHtml(document_content)
        self.browser_window.scrollToAnchor(anchor)
        self._updateHistoryButtonState()

    def _onNextButtonClicked(self):
        """
        Action that is performed when the search button is clicked. This will populate the browser window.
        """
        document_content, anchor = self.winapi.getNextDocumentContent()
        if document_content != "":
            self.browser_window.setHtml(document_content)
        self.browser_window.scrollToAnchor(anchor)
        self._updateHistoryButtonState()

    def _onOnlineButtonClicked(self):
        """
        Action that is performed when the search button is clicked. This will populate the browser window.
        """
        self.winapi.setOnlineMsdnEnabled(not self.winapi.hasOnlineMsdnAvailable())
        self._updateAvailability()

    def _browserAnchorClicked(self, url):
        """
        Callback for the case an anchor (or any link) within the browser window is clicked. This will fetch
        document content and anchor based on the URL of the link and update the browser window.
        @param url: a URL as triggered by the callback
        @type url: QUrl
        """
        document_content, anchor = self.winapi.getLinkedDocumentContent(url)
        if document_content != "":
            self.browser_window.setHtml(document_content)
        self.browser_window.scrollToAnchor(anchor)
        self._updateHistoryButtonState()

    def navigate(self, api_name):
        """
        A function exposed in order to allow the widget to be navigated to an arbitrary API name.
        @param api_name: the API name to navigate the widget to.
        @type api_name: str
        """
        self.api_chooser_lineedit.setText(api_name)
        self.populateBrowserWindow()

    def _navigateToHighlightedIdentifier(self):
        """
        A function exposed to allow navigating the widget to the currently highlighted identifier from the IDA view.
        """
        if self.winapi.hasOfflineMsdnAvailable():
            highlighted_identifier = Misc.cleanCountingSuffix(self.ida_proxy.get_highlighted_identifier())
            highlighted_identifier = self.parent.semantic_identifier.lookupDisplayApiName(highlighted_identifier)
            self.navigate(highlighted_identifier)
            self.parent.setTabFocus(self.name)

    def _updateHistoryButtonState(self):
        """
        Update the button state (enabled/disabled) according to availability of history information from the
        WinApiProvider
        """
        self.back_button.setEnabled(self.winapi.hasBackwardHistory())
        self.next_button.setEnabled(self.winapi.hasForwardHistory())
Exemple #18
0
    def __init__(self, parent=None):
        """
        Default class constructor.

        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(AboutDialog, self).__init__(parent)

        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        if parent:
            self.gImgDir = parent.gImgDir
            self.gIconDir = parent.gIconDir
        elif __name__ == '__main__':
            self.gImgDir = gAppDir + os.sep + 'images'
            self.gIconDir = gAppDir + os.sep + 'icons' + os.sep + 'default'

        # The tiled theme background texture.
        self.bgLogo = QPixmap(self.gImgDir + os.sep + 'texture-spirals.png')
        self.bgBrush = QBrush(self.bgLogo)
        self.setWhatsThis(
            self.tr("""\
The background is a tiled image of an actual design that was stitched out during the pre-alpha stage.
It was created by Nina Paley and Theodore Gray using Mathematica in conjunction with our software.
They have graciously allowed us to use it for the project in whichever way we wish.
We thought it looked so good, that it has become the new theme for Embroidermodder 2.
To check out some of the more interesting embroidery projects they are working on,
visit http://blog.ninapaley.com/"""))

        self.imgLbl = EmbroidermodderLogo(self)

        aboutLbl = QTextBrowser(self)
        aboutLbl.setReadOnly(True)
        aboutLbl.setOpenExternalLinks(True)

        aboutLbl.setText('<b>%s</b>' % '<br>'.join(ABOUT.split('\n')))
        aboutLbl.setWhatsThis(
            self.
            tr('This is the AWESOME people that brought Embroidermodder 2 to life.'
               ))

        # We want very slight opacity of the white background
        # so the seamless texture shows slightly through.
        opacityStyleSheet = """\
        QTextEdit:read-only {
            color: rgb(50, 50, 50);
            font-size: 12px;
            font-weight: bold;
            background-color: rgba(255, 255, 255, 240);
            border: 1px solid rgba(0, 0, 0, 255);
            }
            """

        aboutLbl.setStyleSheet(opacityStyleSheet)
        op = QGraphicsOpacityEffect(aboutLbl)
        op.setOpacity(0.95)
        aboutLbl.setGraphicsEffect(op)

        self.notebook = QTabWidget(self)
        self.notebook.setMinimumWidth(500)
        self.notebook.addTab(aboutLbl, self.tr('About'))
        self.notebook.setTabIcon(0, QIcon(self.gIconDir + os.sep + 'app.png'))
        self.notebook.setTabIcon(
            1, QIcon(self.gImgDir + os.sep + 'kickstarter-logo-k-color.png'))

        notebookStyleSheet = """\
            QTabWidget::pane { /* The tab widget frame */
                border-top: 1px solid #000000;
                position: absolute;
                top: -0.5em;
            }

            QTabWidget::tab-bar {
                alignment: center;
            }

            /* Style the tab using the tab sub-control. Note that
                it reads QTabBar _not_ QTabWidget */
            QTabBar::tab {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                            stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                            stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
                border: 1px solid #000000;
                /* border-bottom-color: #C2C7CB; */ /* same as the pane color */
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                min-width: 40ex;
                min-height: 5ex;
                padding: 3px;
            }

            QTabBar::tab:selected {
                margin-top: 0px;
                font-size: 16px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #0C6AB0, stop: 0.15 #55C4E6,
                                            stop: 0.15 #55C4E6, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #55C4E6,
                                            stop: 0.85 #55C4E6, stop: 1.0 #0C6AB0);
                border: 1px solid #000000;
            }

            QTabBar::tab:!selected:hover {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #888888, stop: 0.15 #BBBBBB,
                                            stop: 0.15 #BBBBBB, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #BBBBBB,
                                            stop: 0.85 #BBBBBB, stop: 1.0 #888888);
                border: 1px solid #000000;
            }

            QTabBar::tab:selected {
                border-color: #000000;
                border-bottom-color: #000000; /* same as pane color */
            }
            """

        self.notebook.setStyleSheet(notebookStyleSheet)
        self.notebook.currentChanged.connect(self.CurrentTabChanged)

        buttonbox = QDialogButtonBox(Qt.Horizontal, self)
        button = QPushButton(self)
        button.setText(self.tr("Oh, Yeah!"))
        button.setWhatsThis(
            self.tr('This is the Oh, Yeah! button!') + '\n' +
            self.tr('Oh, Yeah!'))
        buttonbox.addButton(button, QDialogButtonBox.AcceptRole)
        buttonbox.setCenterButtons(True)
        buttonbox.accepted.connect(self.accept)

        hbLayout1 = QHBoxLayout()
        hbLayout2 = QHBoxLayout()
        vbLayout = QVBoxLayout()
        hbLayout1.addStretch()
        hbLayout1.addWidget(self.imgLbl)
        hbLayout1.addStretch()
        hbLayout2.addStretch()
        hbLayout2.addWidget(self.notebook)
        hbLayout2.addStretch()
        vbLayout.addLayout(hbLayout1)
        vbLayout.addLayout(hbLayout2)
        vbLayout.addWidget(buttonbox)
        self.setLayout(vbLayout)

        self.setWindowTitle(self.tr('About Embroidermodder Version 2.0'))

        QApplication.restoreOverrideCursor(
        )  # TODO/???/PORT# don't mess with the window resize cursors.
class HighwaySimulatorGui(QMainWindow):
    def __init__(self):
        super(HighwaySimulatorGui, self).__init__()
        centralTab = QTabWidget()
        mainWidget = QWidget()
        self.resultsWidget = HighwayAnalyzeWidget()
        centralTab.addTab(mainWidget, 'Run')
        centralTab.addTab(self.resultsWidget, 'Analyze')
        self.setCentralWidget(centralTab)
        centralLayout = QVBoxLayout()
        #centralLayout.setSpacing(0)
        centralLayout.setAlignment(Qt.AlignTop)
        gridWidget = QWidget()
        gridLayout = QGridLayout()
        gridLayout.setSpacing(0)
        gridWidget.setLayout(gridLayout)
        mainWidget.setLayout(centralLayout)
        self.options = dict()
        # GENERAL
        generalGroup = QGroupBox('General Settings')
        generalGroup.setLayout(QVBoxLayout())
        generalGroup.layout().setSpacing(0)
        self.pathOption = SimpleOption('path','Output Path','/home/thomas/Dropbox/Keio/research/results/')
        generalGroup.layout().addWidget(self.pathOption)
        self.scenarioOption = SimpleComboboxOption('scenario','Scenario',1, False, 'vanet-highway-test-thomas','vanet-highway-scenario2')
        self.scenarioOption.combo.currentIndexChanged[int].connect(self.scenarioChanged)
        generalGroup.layout().addWidget(self.scenarioOption)
        self.options['time'] = SimpleSpinOption('time','Simulation Time (sec.)',1500,True)
        self.options['time'].setRange(0,3000)
        self.options['mix'] = SimpleSpinOption('mix','Percentage of cars compare to trucks (%)',80,True)
        self.options['mix'].setRange(0,100)
        self.options['gap'] = SimpleSpinOption('gap','Average Gap (m.)',5)
        self.options['gap'].setRange(1,2000)
        self.options['lane'] = SimpleSpinOption('lane','Number of Lanes',2,True)
        self.options['lane'].setRange(2,4)
        self.options['spl'] = SimpleSpinOption('spl','Speed Limit (km/h)',130,True)
        self.options['spl'].setRange(1,200)
        for widget in ('time','mix','gap','lane','spl'):
            generalGroup.layout().addWidget(self.options[widget])
        gridLayout.addWidget(generalGroup,0,0)
        # TRAFFIC
        trafficGroup = QGroupBox('Traffic Settings')
        trafficGroup.setLayout(QVBoxLayout())
        trafficGroup.layout().setSpacing(0)
        # m/s = (km/h)*1000/3600
        self.options['vel1'] = SimpleSpinOption('vel1','Average Speed (km/h)',105,True)
        self.options['vel1'].setRange(5,150)
        self.options['dis'] = SimpleComboboxOption('dis','Speed Distribution Model',3, False, 'Uniform','Exponential','Normal','Log Normal')
        self.options['spstd'] = SimpleSpinOption('spstd','Speed Distribution Variance',1.0)
        self.options['spstd'].setRange(0,50)
        self.options['flow1'] = SimpleSpinOption('flow1','Traffic Flow Mean (veh/s)',1.0)
        self.options['flow1'].setRange(0.1,50.0)
        self.options['std1'] = SimpleSpinOption('std1','Traffic Flow Variance',0.8)
        self.options['std1'].setRange(0.1,50.0)
        self.options['maxflow'] = SimpleSpinOption('maxflow','Traffic Maximum Flow (veh/s)',5)
        self.options['maxflow'].setRange(0.1,50.0)
        # Scenar 2
        self.options['avgdist'] = SimpleSpinOption('avgdist','Average Distance (m)',100)
        self.options['avgdist'].setRange(1,10000)
        self.options['avgspeed'] = SimpleSpinOption('avgspeed','Average Speed (km/h)',105)
        self.options['avgspeed'].setRange(1,10000)
        self.options['despeed'] = SimpleSpinOption('despeed','Desired Speed (km/h)',130)
        self.options['despeed'].setRange(1,10000)
        self.options['ambumaxspeed'] = SimpleSpinOption('ambumaxspeed','Ambu Max Speed (km/h)',165)
        self.options['ambumaxspeed'].setRange(1,10000)
        self.options['ambuinitspeed'] = SimpleSpinOption('ambuinitspeed','Ambu Initial Speed (km/h)',130)
        self.options['ambuinitspeed'].setRange(1,10000)
        for widget in ('vel1','dis','spstd','flow1','std1','maxflow',
                       'avgdist', 'avgspeed', 'despeed', 'ambumaxspeed', 'ambuinitspeed'):
            trafficGroup.layout().addWidget(self.options[widget])
        self.scenarioChanged(self.scenarioOption.combo.currentIndex())
        gridLayout.addWidget(trafficGroup,0,1)
        # VANET
        vanetGroup = QGroupBox('VANET Settings')
        vanetGroup.setLayout(QVBoxLayout())
        vanetGroup.layout().setSpacing(0)
#        self.options['prate'] = SimpleSpinOption('prate','Penetration Rate of VANET (%)',100,True)
#        self.options['prate'].setRange(0,100)
        self.options['prate'] = 0 # start with 0
        self.options['pw'] = SimpleSpinOption('pw','Transmission Power (dBm)',21.5)
        self.options['pw'].setRange(10,50)
        #for widget in ('prate','pw'):
        for widget in ('pw',):
            vanetGroup.layout().addWidget(self.options[widget])
        gridLayout.addWidget(vanetGroup,1,0)
        # BATCH SETTINGS
        batchGroup = QGroupBox("Batch Settings")
        batchGroup.setLayout(QVBoxLayout())
        self.gapPrateOption = SimpleSpinOption('gapPrate', 'VANET percentage rate gap', 10, integer=True)
        self.sameSimuTimesOption = SimpleSpinOption('sameSimuTimes', 'How many times the same simulation', 100, integer=True)
        batchGroup.layout().setSpacing(0)
        batchGroup.layout().addWidget(self.gapPrateOption)
        batchGroup.layout().addWidget(self.sameSimuTimesOption)
        gridLayout.addWidget(batchGroup,1,1)
        # START SIMU
        centralLayout.addWidget(gridWidget)
        self.startButton = QPushButton('START')
        self.startButton.clicked.connect(self.startSimu)
        centralLayout.addWidget(self.startButton)
        self.progressBar    = QProgressBar()
        centralLayout.addWidget(self.progressBar)
        self.shutdownWhenDone = QCheckBox('Shutdown when done')
        self.actionWhenDone = QComboBox()
        self.actionWhenDone.addItems(['When finished... do nothing', 'When finished... shutdown the computer', 'When finished... Re-run the simulations!'])
        self.actionWhenDone.setCurrentIndex(int(QSettings().value('actionWhenDone', 0)))
        centralLayout.addWidget(self.actionWhenDone)
        self.infoLabel = QLabel()
        centralLayout.addWidget(self.infoLabel)
        # LOG
        self.logText = QTextBrowser()
        self.logText.setFont(QFont('Century Gothic', 7))
        centralLayout.addWidget(self.logText)
        self.setWindowTitle('Nishimura Lab | Highway Simulation')
        #self.resize(520,len(self.options)*60+100)
        #self.resultFile = open('/home/thomas/Dropbox/Keio/research/results/summary.txt', 'a')
        #self.resultFile = os.path.join(self.pathOption.getValue(), 'summary.txt')
        self.logFile = os.path.join(self.pathOption.getValue(), 'results_'+os.uname()[1]+'.log')
    @Slot(int)
    def scenarioChanged(self, index):
        #print index
        scenar1options = ['gap', 'vel1', 'dis', 'flow1', 'std1','spstd', 'maxflow']
        scenar2options = ['avgdist', 'avgspeed', 'despeed', 'ambumaxspeed', 'ambuinitspeed']
        if index==0: # first scenario
            scenar1 = True
            scenar2 = False
        else:
            scenar1 = False
            scenar2 = True
        for option in scenar1options:
            self.options[option].setVisible(scenar1)
        for option in scenar2options:
            self.options[option].setVisible(scenar2)
    def log(self, txt):
        toLog = '%s | %s' % (datetime.now(), txt)
        with open(self.logFile, 'a') as logFile:
            logFile.write(toLog+'\n')
        self.logText.append(toLog)
    def blockUi(self):
        self.startButton.setEnabled(False)
        self.scenarioOption.setEnabled(False)
        for option in self.options:
            if option!='prate':
                self.options[option].setEnabled(False)
    def releaseUi(self):
        self.startButton.setEnabled(True)
        self.scenarioOption.setEnabled(True)
        self.startButton.setText('START')
        for option in self.options:
            if option!='prate':
                self.options[option].setEnabled(True)
    def startSimu(self):
        self.log("=== SIMULATIONS START ===")
        self.logText.clear()
        self.startTime = datetime.now()
        self.simulations = []
        #self.nextPrate = 0
        self.gapPrate  = self.gapPrateOption.getValue()
        self.sameSimuTimes = self.sameSimuTimesOption.getValue()
        #self.nextSimu   = 0
        self.blockUi()
        self.simulationsDone = 0
        #output = self.pathOption.getValue() + dateToFilename(d) + '_results.txt'
        pRate = 0
        self.simulationsTotal = 0
#        print 'sameSimuTimes: %d'%self.sameSimuTimes
#        print 'gapPrate: %d'%self.gapPrate
        while pRate <= 100:
            simu = 0
            self.options['prate'] = pRate
            while simu<self.sameSimuTimes:
                waf = WafThread(self.options, self.pathOption.getValue(), self.scenarioOption.getName())
                waf.setAutoDelete(True)
                waf.simuDone.connect(self.wafDone)
                self.simulations.append(waf)
                QThreadPool.globalInstance().start(waf)
                self.simulationsTotal += 1
                simu += 1
            pRate += self.gapPrate
        runningSimulations = 'Running %d Simulations...' % self.simulationsTotal
        self.startButton.setText(runningSimulations)
        self.log(runningSimulations)
        self.progressBar.setRange(0,self.simulationsTotal)
        self.progressBar.setValue(0)
        # 300 seconds per task average
        roughTime = self.simulationsTotal*self.resultsWidget.averageSimulationTime/QThreadPool.globalInstance().maxThreadCount()
        self.infoLabel.setText('Rough time estimation: %s' % formatTimeLeft(roughTime))
    @Slot(str)
    def wafDone(self, outputPath):
        #print 'thread done!\nReceived:'
        self.simulationsDone += 1
        simulationsLeft = self.simulationsTotal-self.simulationsDone
        with open(outputPath,'r') as out:
            r = json.loads(out.read())
            out.close()
            if 'timeToReachDest' in r['results']:
                try:
                    result = "%3.3d\t%f" % (int(r['settings']['prate']),float(r['results']['timeToReachDest']))
                except TypeError, e:
                    result = 'PYTHON ERROR: %s | File: %s' % (e, outputPath)
                    print result
                    print r
            else:
    def __init__(self):
        super(HighwaySimulatorGui, self).__init__()
        centralTab = QTabWidget()
        mainWidget = QWidget()
        self.resultsWidget = HighwayAnalyzeWidget()
        centralTab.addTab(mainWidget, 'Run')
        centralTab.addTab(self.resultsWidget, 'Analyze')
        self.setCentralWidget(centralTab)
        centralLayout = QVBoxLayout()
        #centralLayout.setSpacing(0)
        centralLayout.setAlignment(Qt.AlignTop)
        gridWidget = QWidget()
        gridLayout = QGridLayout()
        gridLayout.setSpacing(0)
        gridWidget.setLayout(gridLayout)
        mainWidget.setLayout(centralLayout)
        self.options = dict()
        # GENERAL
        generalGroup = QGroupBox('General Settings')
        generalGroup.setLayout(QVBoxLayout())
        generalGroup.layout().setSpacing(0)
        self.pathOption = SimpleOption('path','Output Path','/home/thomas/Dropbox/Keio/research/results/')
        generalGroup.layout().addWidget(self.pathOption)
        self.scenarioOption = SimpleComboboxOption('scenario','Scenario',1, False, 'vanet-highway-test-thomas','vanet-highway-scenario2')
        self.scenarioOption.combo.currentIndexChanged[int].connect(self.scenarioChanged)
        generalGroup.layout().addWidget(self.scenarioOption)
        self.options['time'] = SimpleSpinOption('time','Simulation Time (sec.)',1500,True)
        self.options['time'].setRange(0,3000)
        self.options['mix'] = SimpleSpinOption('mix','Percentage of cars compare to trucks (%)',80,True)
        self.options['mix'].setRange(0,100)
        self.options['gap'] = SimpleSpinOption('gap','Average Gap (m.)',5)
        self.options['gap'].setRange(1,2000)
        self.options['lane'] = SimpleSpinOption('lane','Number of Lanes',2,True)
        self.options['lane'].setRange(2,4)
        self.options['spl'] = SimpleSpinOption('spl','Speed Limit (km/h)',130,True)
        self.options['spl'].setRange(1,200)
        for widget in ('time','mix','gap','lane','spl'):
            generalGroup.layout().addWidget(self.options[widget])
        gridLayout.addWidget(generalGroup,0,0)
        # TRAFFIC
        trafficGroup = QGroupBox('Traffic Settings')
        trafficGroup.setLayout(QVBoxLayout())
        trafficGroup.layout().setSpacing(0)
        # m/s = (km/h)*1000/3600
        self.options['vel1'] = SimpleSpinOption('vel1','Average Speed (km/h)',105,True)
        self.options['vel1'].setRange(5,150)
        self.options['dis'] = SimpleComboboxOption('dis','Speed Distribution Model',3, False, 'Uniform','Exponential','Normal','Log Normal')
        self.options['spstd'] = SimpleSpinOption('spstd','Speed Distribution Variance',1.0)
        self.options['spstd'].setRange(0,50)
        self.options['flow1'] = SimpleSpinOption('flow1','Traffic Flow Mean (veh/s)',1.0)
        self.options['flow1'].setRange(0.1,50.0)
        self.options['std1'] = SimpleSpinOption('std1','Traffic Flow Variance',0.8)
        self.options['std1'].setRange(0.1,50.0)
        self.options['maxflow'] = SimpleSpinOption('maxflow','Traffic Maximum Flow (veh/s)',5)
        self.options['maxflow'].setRange(0.1,50.0)
        # Scenar 2
        self.options['avgdist'] = SimpleSpinOption('avgdist','Average Distance (m)',100)
        self.options['avgdist'].setRange(1,10000)
        self.options['avgspeed'] = SimpleSpinOption('avgspeed','Average Speed (km/h)',105)
        self.options['avgspeed'].setRange(1,10000)
        self.options['despeed'] = SimpleSpinOption('despeed','Desired Speed (km/h)',130)
        self.options['despeed'].setRange(1,10000)
        self.options['ambumaxspeed'] = SimpleSpinOption('ambumaxspeed','Ambu Max Speed (km/h)',165)
        self.options['ambumaxspeed'].setRange(1,10000)
        self.options['ambuinitspeed'] = SimpleSpinOption('ambuinitspeed','Ambu Initial Speed (km/h)',130)
        self.options['ambuinitspeed'].setRange(1,10000)
        for widget in ('vel1','dis','spstd','flow1','std1','maxflow',
                       'avgdist', 'avgspeed', 'despeed', 'ambumaxspeed', 'ambuinitspeed'):
            trafficGroup.layout().addWidget(self.options[widget])
        self.scenarioChanged(self.scenarioOption.combo.currentIndex())
        gridLayout.addWidget(trafficGroup,0,1)
        # VANET
        vanetGroup = QGroupBox('VANET Settings')
        vanetGroup.setLayout(QVBoxLayout())
        vanetGroup.layout().setSpacing(0)
#        self.options['prate'] = SimpleSpinOption('prate','Penetration Rate of VANET (%)',100,True)
#        self.options['prate'].setRange(0,100)
        self.options['prate'] = 0 # start with 0
        self.options['pw'] = SimpleSpinOption('pw','Transmission Power (dBm)',21.5)
        self.options['pw'].setRange(10,50)
        #for widget in ('prate','pw'):
        for widget in ('pw',):
            vanetGroup.layout().addWidget(self.options[widget])
        gridLayout.addWidget(vanetGroup,1,0)
        # BATCH SETTINGS
        batchGroup = QGroupBox("Batch Settings")
        batchGroup.setLayout(QVBoxLayout())
        self.gapPrateOption = SimpleSpinOption('gapPrate', 'VANET percentage rate gap', 10, integer=True)
        self.sameSimuTimesOption = SimpleSpinOption('sameSimuTimes', 'How many times the same simulation', 100, integer=True)
        batchGroup.layout().setSpacing(0)
        batchGroup.layout().addWidget(self.gapPrateOption)
        batchGroup.layout().addWidget(self.sameSimuTimesOption)
        gridLayout.addWidget(batchGroup,1,1)
        # START SIMU
        centralLayout.addWidget(gridWidget)
        self.startButton = QPushButton('START')
        self.startButton.clicked.connect(self.startSimu)
        centralLayout.addWidget(self.startButton)
        self.progressBar    = QProgressBar()
        centralLayout.addWidget(self.progressBar)
        self.shutdownWhenDone = QCheckBox('Shutdown when done')
        self.actionWhenDone = QComboBox()
        self.actionWhenDone.addItems(['When finished... do nothing', 'When finished... shutdown the computer', 'When finished... Re-run the simulations!'])
        self.actionWhenDone.setCurrentIndex(int(QSettings().value('actionWhenDone', 0)))
        centralLayout.addWidget(self.actionWhenDone)
        self.infoLabel = QLabel()
        centralLayout.addWidget(self.infoLabel)
        # LOG
        self.logText = QTextBrowser()
        self.logText.setFont(QFont('Century Gothic', 7))
        centralLayout.addWidget(self.logText)
        self.setWindowTitle('Nishimura Lab | Highway Simulation')
        #self.resize(520,len(self.options)*60+100)
        #self.resultFile = open('/home/thomas/Dropbox/Keio/research/results/summary.txt', 'a')
        #self.resultFile = os.path.join(self.pathOption.getValue(), 'summary.txt')
        self.logFile = os.path.join(self.pathOption.getValue(), 'results_'+os.uname()[1]+'.log')
Exemple #21
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.state = state
        self.createWidgets()
        self.layoutWidgets()
        self.initialize()
        if parent is not None:
            self.resize(max(400,
                            parent.width() // 2), max(400,
                                                      parent.height() // 3))
        self.setWindowTitle("Information — {}".format(
            QApplication.applicationName()))
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        self.browser = QTextBrowser()
        self.tooltips.append((self.browser, """<p><b>Information</b></p>
<p>Show basic information about the current index.</p>"""))
        self.browser.zoomIn(1)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
        self.tooltips.append((self.closeButton, """<p><b>Close</b></p>
<p>Close the dialog.</p>"""))
        self.closeButton.clicked.connect(self.reject)

    def layoutWidgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.browser, 1)
        hbox = QHBoxLayout()
        hbox.addStretch()
        hbox.addWidget(self.closeButton)
        hbox.addStretch()
        layout.addLayout(hbox)
        self.setLayout(layout)

    def initialize(self):
        locale = QLocale()
        model = self.state.model
        if not bool(model):
            self.browser.setHtml("<font color=red>Information can only "
                                 "be shown if an index is open</font>")
            return

        top, total, _ = self.state.indicatorCounts()
        fullname = QDir.toNativeSeparators(os.path.abspath(model.filename))
        creator = model.config(Gconf.Key.Creator)
        created = model.config("Created")
        created = locale.toString(
            QDateTime.fromString(created, "yyyy-MM-dd HH:mm:ss"))
        updated = locale.toString(QFileInfo(model.filename).lastModified())
        size = os.path.getsize(model.filename)
        KB = 1024
        MB = KB * KB
        if size < MB:
            size = "~{:,} KB ({:,} bytes)".format(round(size / KB), size)
        else:
            size = "~{:,} MB ({:,} bytes)".format(round(size / MB), size)
        filename = re.sub(r"\.xix$", "", os.path.basename(fullname),
                          re.IGNORECASE)
        version = str(model.version())
        secs = self.state.workTime + int(time.monotonic() -
                                         self.state.startTime)
        hours, secs = divmod(secs, 3600)
        if hours:
            worktime = "{:,}h{}'".format(hours, secs // 60)
        else:
            worktime = "{}'".format(secs // 60)
        uuid = model.config(UUID)
        LEFT_STYLE = """ style="
margin-right: 0;
padding-right: 0;
spacing-right: 0;
border-right: 0;
"
"""
        RIGHT_STYLE = """ style="
margin-left: 0;
padding-left: 0;
spacing-left: 0;
border-left: 0;
"
"""
        color1 = "#DDDDFF"
        color2 = "#EEEEFF"
        STYLE = ' style="background-color: {};"'
        texts = [
            """<html><table border=0 style="
background-color: {};
">""".format(color1)
        ]
        for i, (name, value, right, debug) in enumerate((
            ("Index", filename, False, False),
            ("Creator", creator, False, False),
            ("Filename", fullname, False, False),
            ("Size", size, False, False),
            ("Created", created, False, False),
            ("Updated", updated, False, False),
            ("Total Entries", "{:,}".format(total), True, False),
            ("Main Entries", "{:,}".format(top), True, False),
            ("Subentries", "{:,}".format(total - top), True, False),
            ("Worktime", worktime, True, False),
            (None, None, False, False),
            ("Index Format", version, True, False),
            ("Index UUID", uuid, True, True),
        )):
            if debug and not self.state.window.debug:
                continue
            if name is None:
                color1 = "#EEEEEE"
                color2 = "#DDDDDD"
                continue
            style = STYLE.format(color1 if i % 2 == 0 else color2)
            align = " align=right" if right else ""
            texts.append("""<tr{}><td{}>{}&nbsp;&nbsp;</td>
<td{}{}>{}</td></tr>""".format(style, LEFT_STYLE, html.escape(name), align,
                               RIGHT_STYLE, html.escape(value)))
        texts.append("</table></html>")
        self.browser.setHtml("".join(texts))
Exemple #22
0
 def create_widgets(self, message):
     self.label = QTextBrowser()
     self.label.setStyleSheet("QTextBrowser { background: #eee; }")
     self.label.setText(message)
     self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
Exemple #23
0
	def __init__(self, parent=None):
		super(mainwin, self).__init__(parent)
		self.setWindowTitle("Nigandu English to Tamil Dictionary")
		self.setGeometry(200, 50, 650, 600)
		self.setMinimumHeight(620)
		self.setMinimumWidth(650)
		self.setMaximumHeight(660)
		self.setMaximumWidth(800)
		#Setting up status bar
		self.myStatusBar = QStatusBar()
		self.myStatusBar.showMessage('Ready', 7000)
		self.setStatusBar(self.myStatusBar)
		#Setting up application icon
		appIcon = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appIcon)

		# defining the central widget
		self.central = QWidget(self)

		#combobox plus search button
		self.whole = QVBoxLayout(self.central)
		self.gridlayout = QGridLayout()
		self.comboBox = QLineEdit(self)
		#self.comboBox.setEditable(True)
		self.comboBox.setObjectName("comboBox")
		self.completer = QCompleter(self.comboBox)
		self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
		self.completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.completer.setMaxVisibleItems(10)
		self.comboBox.setCompleter(self.completer)
		#self.comboBox.setCompleter()
		self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2)

		self.searchbtn = QPushButton()
		self.searchbtn.setObjectName("searchbtn")
		self.searchbtn.setText("&Search")
		self.gridlayout.addWidget(self.searchbtn, 1, 3)

		vbox = QVBoxLayout()
		self.tamtext = QTextBrowser()
		self.listview = QListWidget(self)
		#self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.listview.setWindowTitle("Suggested words")
		self.tamtext.setMinimumHeight(100)
		self.tamtext.setMaximumHeight(150)
		vbox.addWidget(self.tamtext)
		self.suglbl = QLabel(self)
		self.suglbl.setText("Suggested Words:")
		vbox.addWidget(self.suglbl)
		vbox.addWidget(self.listview)

		self.whole.addLayout(self.gridlayout)
		self.whole.addLayout(vbox)
		self.setCentralWidget(self.central)

		#setting docks
		self.histdockwidg = QDockWidget("History", self)
		self.bkmdockwidg = QDockWidget("Book Marks", self)
		self.histdockwidg.setObjectName("self.histdockwidg")
		self.bkmdockwidg.setObjectName("self.bkmdockwidg")

		#self.histdockwidg.setMaximumWidth(histwidth)
		self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.histdockwidg.setMaximumWidth(250)
		self.bkmdockwidg.setMaximumWidth(250)
		self.histdockwidg.setMinimumWidth(200)
		self.bkmdockwidg.setMinimumWidth(200)

		#self.bkmdockwidg.setMaximumWidth(histwidth)
		self.histli = QListWidget()
		self.bkmli = QListWidget()
		self.histlis = [0]
		self.bkmlistfromfile = []
		self.histdockwidg.setWidget(self.histli)
		self.bkmdockwidg.setWidget(self.bkmli)
		self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg)
		self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg)

		#file menu
		fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png",
		                               "Add a word to the dictionary. . .")
		fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png",
		                                "Change the default settings. . .")
		fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png",
		                             "Help contents. . .")
		fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png",
		                             "Close the application. . .")
		fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size")
		fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size")
		#list of file actions
		fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit)

		#go menu
		self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png",
		                                  "Previous Word")
		self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word")
		self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png",
		                                  "Select a random word")
		#list of go actions
		go_menu = (self.go_prev, self.go_next, self.go_rand )
		self.go_next.setEnabled(False)
		self.go_prev.setEnabled(False)

		#book mark menu
		self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png",
		                                     "Book mark this word")
		self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png",
		                                      "View bookmarked words")
		#list of book mark items
		bkm_menu = (self.bkm_addfav, self.bkm_viewbkm)

		#help menu
		hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About")
		hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png",
		                                   "Visit our blog")
		hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents")
		#list of help menu items
		hlp_menu = (hlp_about, hlp_visitblog, hlp_help)

		#Setting up the menubar
		filemenu = self.menuBar().addMenu("&File")
		self.addmenu(filemenu, fi_menu)
		gomenu = self.menuBar().addMenu("&Go")
		self.addmenu(gomenu, go_menu)
		bkmmenu = self.menuBar().addMenu("&Book Mark")
		self.addmenu(bkmmenu, bkm_menu)
		helpmenu = self.menuBar().addMenu("&Help")
		self.addmenu(helpmenu, hlp_menu)
		intn = QSize(40, 40)
		self.setIconSize(intn)
		#Setting up the tool bar
		filetools = self.addToolBar("File")
		filetools.setObjectName("filetools")
		self.addmenu(filetools, (fi_addwrd, fplus, fminus))

		gotools = self.addToolBar("Go")
		gotools.setObjectName("gotools")
		self.addmenu(gotools, go_menu)

		bkmtools = self.addToolBar("Bkm")
		bkmtools.setObjectName("bkmtools")
		self.addmenu(bkmtools, bkm_menu)

		hlptools = self.addToolBar("Help")
		hlptools.setObjectName("helptools")
		self.addmenu(hlptools, hlp_menu)

		self.loadfiles()
		self.returncount = 0
		self.bkm_addfav.setEnabled(False)

		#clipboard function
		if self.clipauto:
			clip = QApplication.clipboard()
			cliptxt = clip.text()
			self.comboBox.setText(cliptxt)
			self.setevent()

		#connections
		self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search)
		self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent)
		self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter)
		self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
Exemple #24
0
class mainwin(QMainWindow):
	def __init__(self, parent=None):
		super(mainwin, self).__init__(parent)
		self.setWindowTitle("Nigandu English to Tamil Dictionary")
		self.setGeometry(200, 50, 650, 600)
		self.setMinimumHeight(620)
		self.setMinimumWidth(650)
		self.setMaximumHeight(660)
		self.setMaximumWidth(800)
		#Setting up status bar
		self.myStatusBar = QStatusBar()
		self.myStatusBar.showMessage('Ready', 7000)
		self.setStatusBar(self.myStatusBar)
		#Setting up application icon
		appIcon = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appIcon)

		# defining the central widget
		self.central = QWidget(self)

		#combobox plus search button
		self.whole = QVBoxLayout(self.central)
		self.gridlayout = QGridLayout()
		self.comboBox = QLineEdit(self)
		#self.comboBox.setEditable(True)
		self.comboBox.setObjectName("comboBox")
		self.completer = QCompleter(self.comboBox)
		self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
		self.completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.completer.setMaxVisibleItems(10)
		self.comboBox.setCompleter(self.completer)
		#self.comboBox.setCompleter()
		self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2)

		self.searchbtn = QPushButton()
		self.searchbtn.setObjectName("searchbtn")
		self.searchbtn.setText("&Search")
		self.gridlayout.addWidget(self.searchbtn, 1, 3)

		vbox = QVBoxLayout()
		self.tamtext = QTextBrowser()
		self.listview = QListWidget(self)
		#self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.listview.setWindowTitle("Suggested words")
		self.tamtext.setMinimumHeight(100)
		self.tamtext.setMaximumHeight(150)
		vbox.addWidget(self.tamtext)
		self.suglbl = QLabel(self)
		self.suglbl.setText("Suggested Words:")
		vbox.addWidget(self.suglbl)
		vbox.addWidget(self.listview)

		self.whole.addLayout(self.gridlayout)
		self.whole.addLayout(vbox)
		self.setCentralWidget(self.central)

		#setting docks
		self.histdockwidg = QDockWidget("History", self)
		self.bkmdockwidg = QDockWidget("Book Marks", self)
		self.histdockwidg.setObjectName("self.histdockwidg")
		self.bkmdockwidg.setObjectName("self.bkmdockwidg")

		#self.histdockwidg.setMaximumWidth(histwidth)
		self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.histdockwidg.setMaximumWidth(250)
		self.bkmdockwidg.setMaximumWidth(250)
		self.histdockwidg.setMinimumWidth(200)
		self.bkmdockwidg.setMinimumWidth(200)

		#self.bkmdockwidg.setMaximumWidth(histwidth)
		self.histli = QListWidget()
		self.bkmli = QListWidget()
		self.histlis = [0]
		self.bkmlistfromfile = []
		self.histdockwidg.setWidget(self.histli)
		self.bkmdockwidg.setWidget(self.bkmli)
		self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg)
		self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg)

		#file menu
		fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png",
		                               "Add a word to the dictionary. . .")
		fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png",
		                                "Change the default settings. . .")
		fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png",
		                             "Help contents. . .")
		fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png",
		                             "Close the application. . .")
		fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size")
		fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size")
		#list of file actions
		fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit)

		#go menu
		self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png",
		                                  "Previous Word")
		self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word")
		self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png",
		                                  "Select a random word")
		#list of go actions
		go_menu = (self.go_prev, self.go_next, self.go_rand )
		self.go_next.setEnabled(False)
		self.go_prev.setEnabled(False)

		#book mark menu
		self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png",
		                                     "Book mark this word")
		self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png",
		                                      "View bookmarked words")
		#list of book mark items
		bkm_menu = (self.bkm_addfav, self.bkm_viewbkm)

		#help menu
		hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About")
		hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png",
		                                   "Visit our blog")
		hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents")
		#list of help menu items
		hlp_menu = (hlp_about, hlp_visitblog, hlp_help)

		#Setting up the menubar
		filemenu = self.menuBar().addMenu("&File")
		self.addmenu(filemenu, fi_menu)
		gomenu = self.menuBar().addMenu("&Go")
		self.addmenu(gomenu, go_menu)
		bkmmenu = self.menuBar().addMenu("&Book Mark")
		self.addmenu(bkmmenu, bkm_menu)
		helpmenu = self.menuBar().addMenu("&Help")
		self.addmenu(helpmenu, hlp_menu)
		intn = QSize(40, 40)
		self.setIconSize(intn)
		#Setting up the tool bar
		filetools = self.addToolBar("File")
		filetools.setObjectName("filetools")
		self.addmenu(filetools, (fi_addwrd, fplus, fminus))

		gotools = self.addToolBar("Go")
		gotools.setObjectName("gotools")
		self.addmenu(gotools, go_menu)

		bkmtools = self.addToolBar("Bkm")
		bkmtools.setObjectName("bkmtools")
		self.addmenu(bkmtools, bkm_menu)

		hlptools = self.addToolBar("Help")
		hlptools.setObjectName("helptools")
		self.addmenu(hlptools, hlp_menu)

		self.loadfiles()
		self.returncount = 0
		self.bkm_addfav.setEnabled(False)

		#clipboard function
		if self.clipauto:
			clip = QApplication.clipboard()
			cliptxt = clip.text()
			self.comboBox.setText(cliptxt)
			self.setevent()

		#connections
		self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search)
		self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent)
		self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter)
		self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)

	def writehistlis(self, lis):
		if len(lis) >= 2:
			for i in range(1, len(lis)):
				cur.execute("insert into HISTORY values(?)", (lis[i], ))

	def writebkmlis(self, lis):
		cur.execute("delete from BOOKMARKS")
		if len(lis) > 0:
			for i in range(len(lis)):
				cur.execute("insert into BOOKMARKS values(?)", (lis[i], ))

	def listwidcall(self, item):
		self.comboBox.setText(item.text())
		self.setevent()

	def search(self, text, *args):
		li = []
		tplus = text + "%"
		cur.execute("select ENGW from ENGTAM where ENGW like ? limit 20", (tplus, ))
		cuf = cur.fetchall()
		model = QStringListModel()
		for i in range(len(cuf)):
			k = cuf[i][0]
			li.append(k)
		model.setStringList(li)
		self.completer.setModel(model)

	def returnpressedevent(self, *args):
		self.comboBox.selectAll()
		self.returncount += 1
		if self.returncount % 2 == 0:
			self.setevent()
		else:
			self.comboBox.selectAll()

	def setevent(self):
		self.comboBox.selectAll()
		self.bkm_addfav.setEnabled(True)
		lis = []
		eng = self.comboBox.text()
		cur.execute("SELECT rowid, TAMW FROM ENGTAM WHERE ENGW like ? limit 1", (eng,))
		cuf = cur.fetchall()
		if len(cuf) == 0:
			self.tamtext.setText("No words found. . . ")
			self.listview.addItem("No Suggestions. . .")
		else:
			for i in range(len(cuf)):
				tam = cuf[0][1]
				rowid = cuf[0][0]
				self.tamtext.setText(tam)
				if rowid <= 25:
					start = 0
					end = 50
				elif rowid >= 190513:
					start = rowid - 190487
					end = rowid + 190537
				else:
					start = rowid - 25
					end = rowid + 25
				cur.execute("SELECT ENGW FROM ENGTAM WHERE rowid>=? and rowid<=?", (start, end, ))
				cuff = cur.fetchall()
				for i in range(len(cuff)):
					engw = cuff[i][0]
					lis.append(engw)
				if self.listview.count() is not None:
					self.listview.clear()
				self.listview.addItems(lis)
				self.addtoli(eng, self.histlis)
				if self.histlis[0] >= 2:
					self.go_prev.setEnabled(True)
				self.comboBox.setFocus()
				if self.histdock:
					self.histli.addItem(eng)

	def addtoli(self, addw, lis, c=1):
		if len(lis) > 0:
			if type(lis[0]) == int:
				if len(lis) >= 2:
					for i in range(1, len(lis)):
						if lis[i] == addw:
							c = 0
							pass
					if c == 1:
						lis.append(addw)
				else:
					lis.append(addw)
				lis[0] = len(lis) - 1

	def addtobkmli(self, addw, lis, nc=1):
		for i in range(len(lis)):
			if lis[i] == addw:
				nc = 0
				pass
		if nc == 1:
			lis.append(addw)

	def onenter(self, *args):
		self.comboBox.selectAll()
		self.setevent()

	def loadfiles(self):
		self.loadsettings()
		self.loadhistlis()
		self.loadbkm()
		self.setfontsize(int(self.fontsize))
		self.setdocks()


	def setdocks(self):
		ist = str(self.histdock)
		jst = str(self.bkmdock)

		if ist == "False":
			self.removedock(self.histdockwidg)
		else:
			self.adddock(self.histdockwidg)

		if jst == "False":
			self.removedock(self.bkmdockwidg)
		else:
			self.adddock(self.bkmdockwidg)

	def loadsettings(self):
		cur.execute("select * from SETTINGS")
		cuffun = cur.fetchall()
		fn = int(cuffun[0][1])
		self.fontsize = fn
		self.clipauto = cuffun[1][1]
		self.histdock = cuffun[2][1]
		self.savehist = cuffun[3][1]
		self.bkmdock = cuffun[4][1]
		self.delhist = cuffun[5][1]
		self.delbkm = cuffun[6][1]

	def loadhistlis(self):
		histtodockli = []
		cur.execute("select * from HISTORY")
		historyfetch = cur.fetchall()
		for i in range(len(historyfetch)):
				self.addtobkmli(historyfetch[i][0], histtodockli)
		for i in histtodockli:
			self.histli.addItem(i)

	def loadbkm(self):
		cur.execute("select * from BOOKMARKS")
		bkmfetch = cur.fetchall()
		for i in range(len(bkmfetch)):
				self.addtobkmli(bkmfetch[i][0], self.bkmlistfromfile)
		for i in self.bkmlistfromfile:
			self.bkmli.addItem(i)

	def createactions(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(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 addmenu(self, target, actions):
		for action in actions:
			if action is None:
				target.addSeparator()
			else:
				target.addAction(action)

	#Actions
	def addwrdf(self):
		self.dlg = addawrd()
		self.dlg.show()
		self.connect(self.dlg.buttonBox, SIGNAL("rejected()"), self.dlg.close)
		self.connect(self.dlg.buttonBox, SIGNAL("accepted()"), self.addawordtodb)


	def addawordtodb(self):
		eng = self.dlg.lineEdit.text()
		tam = self.dlg.lineEdit_2.text()
		if len(eng) != 0 and len(tam) != 0:
			cur.execute("INSERT INTO ENGTAM(ENGW, TAMW) VALUES(?, ?)", (eng, tam, ))
			self.dlg.close()
			QMessageBox.information(self, "Nigandu Eng -> Tam Dictionary", "Added Successfully. . .")
		else:
			self.dlg.lineEdit.setFocus()
			self.dlg.close()
			QMessageBox.warning(self, "Nigandu Eng -> Tam Dictionary", "Invalid Entry. . .")

	def optionsf(self):
		self.opt = optdlg(self)
		self.opt.spinBox.setProperty("value", int(self.fontsize))
		font = QFont()
		font.setPixelSize(int(self.fontsize))
		self.opt.sampletxt.setFont(font)

		if str(self.clipauto) == "True":
			self.opt.checkclip.setChecked(True)
		elif str(self.clipauto) == "False":
			self.opt.checkclip.setChecked(False)

		if str(self.histdock) == "True":
			self.opt.checkshowhistdock.setChecked(True)
		elif str(self.histdock) == "False":
			self.opt.checkshowhistdock.setChecked(False)

		if str(self.bkmdock) == "True":
			self.opt.checkshowbkmdock.setChecked(True)
		elif str(self.bkmdock) == "False":
			self.opt.checkshowbkmdock.setChecked(False)

		self.opt.show()
		self.connect(self.opt.buttonBox, SIGNAL("accepted()"), self.optok)
		self.connect(self.opt.buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.optapply)
		self.connect(self.opt.checkdelhist, SIGNAL("stateChanged(int)"), self.deleteallhist)
		self.connect(self.opt.checkshowhistdock, SIGNAL("stateChanged(int)"), self.shownexttime)
		self.connect(self.opt.checkshowbkmdock, SIGNAL("stateChanged(int)"), self.shownexttime)

	def shownexttime(self, i):
		if i == 0:
			pass
		if i == 2:
			QMessageBox.information(self, self.windowTitle(), "Click Apply or Ok \n The Dock window will be added, \n the next time you start the application. . .")

	def optok(self):
		self.optapply()
		self.opt.close()

	def optapply(self):
		self.updatesettings()
		self.applyopt()

	def updatesettings(self):
		self.fontsize = self.opt.spinBox.value()
		self.clipauto = self.opt.checkclip.isChecked()
		self.histdock = self.opt.checkshowhistdock.isChecked()
		self.bkmdock = self.opt.checkshowbkmdock.isChecked()
		self.delhist = self.opt.checkdelhist.isChecked()

		for i, j in [("fontsize", self.fontsize),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)),
		             ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]:
			cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, ))


	def applyopt(self):
		self.loadsettings()
		self.setfontsize(int(self.fontsize))
		if str(self.bkmdock) == "False" or str(self.histdock) == "False":
			self.setdocks()

	def removedock(self, dock):
		self.removeDockWidget(dock)

	def adddock(self, dock):
		self.addDockWidget(Qt.RightDockWidgetArea, dock)

	def deleteallhist(self, i):
		if i == 0:
			pass
		elif i == 2:
			self.histli.clear()
			self.histlis = [0]
			cur.execute("delete from HISTORY")
			QMessageBox.information(self, self.windowTitle(), "All the History Records are deleted. . .")

	def setfontsize(self, i):
		if i >= 8 or i <= 24:
			font = QFont()
			font.setPixelSize(i)
			self.comboBox.setFont(font)
			self.searchbtn.setFont(font)
			self.bkmli.setFont(font)
			self.histli.setFont(font)
			self.listview.setFont(font)
			self.tamtext.setFont(font)

	def helpf(self):
		form = helpform.HelpForm("index.html", self)
		form.show()

	def closeEvent(self, *args, **kwargs):
		self.writehistlis(self.histlis)
		self.writebkmlis(self.bkmlistfromfile)

		for i, j in [("fontsize", int(self.fontsize)),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)),
		             ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]:
			cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, ))

		con.commit()
		con.close()

	def fplusf(self):
		self.fontsize += 1
		if self.fontsize <= 24:
			self.setfontsize(self.fontsize)

	def fminusf(self):
		self.fontsize -= 1
		if self.fontsize >= 10:
			self.setfontsize(self.fontsize)

	def prevf(self):
		pr = self.histlis[0] - 1
		if pr > 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_next.setEnabled(True)
		elif pr == 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_next.setEnabled(True)
			self.go_prev.setEnabled(False)
		else:
			pass

	def nextf(self):
		pr = self.histlis[0] + 1
		if pr < len(self.histlis) - 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_prev.setEnabled(True)
		elif pr == len(self.histlis) - 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_prev.setEnabled(True)
			self.go_next.setEnabled(False)
		else:
			pass

	def randf(self):
		import random

		n = random.randrange(190538)
		cur.execute("select ENGW from ENGTAM where rowid = ?", (n, ))
		cuf = cur.fetchone()
		self.comboBox.setText(cuf[0])
		self.setevent()

	def addfavf(self):
		txt = self.comboBox.text()
		if len(txt) != 0:
			self.addtobkmli(txt, self.bkmlistfromfile)
			self.writetolistwidget(self.bkmlistfromfile, self.bkmli)


	def sortit(self):
		self.bkmlistfromfile.sort()
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		self.writetolistwidget(self.bkmlistfromfile, self.bkmli)
		cur.execute("delete from BOOKMARKS")


	def writetolistwidget(self, lis, liswid):
		liswid.clear()
		for i in lis:
			liswid.addItem(i)

	def deletecurrentbkm(self):
		ct = self.form.listWidget.currentItem().text()
		self.bkmlistfromfile.remove(ct)
		self.writetolistwidget(self.bkmlistfromfile, self.bkmli)
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		cur.execute("delete from BOOKMARKS")

	def deleteallbkm(self):
		self.form.listWidget.clear()
		self.bkmli.clear()
		self.bkmlistfromfile = []
		cur.execute("delete from BOOKMARKS")

	def viewbkmf(self):
		self.form = managebkm(self)
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		self.form.show()
		self.connect(self.form.closebtn, SIGNAL("clicked()"), self.form.close)
		self.connect(self.form.sortbtn, SIGNAL("clicked()"), self.sortit)
		self.connect(self.form.deletebtn, SIGNAL("clicked()"), self.deletecurrentbkm)
		self.connect(self.form.deleteallbtn, SIGNAL("clicked()"), self.deleteallbkm)

	def aboutf(self):
		QMessageBox.about(self, "About Nigandu English to Tamil Dictionary",
		                  """<b>Nigandu English to Tamil Dictionary</b> v %s
			                  <p>This is the first corss-platform English to Tamil
			                  bilingual dictionary; Free to use.</p>
			                  <p>Copyright &copy; 2014 NJN Private Ltd.
	                             All rights reserved.</p>
	                          <p>Thanks to Python and PySide Project.</p>
	                          <p>Using Python 3.3, Qt 4.8 and PySide 1.2.1</p>""" % (__version__))

	def visitblogf(self):
		webbrowser.open("http://www.e-nool.blogspot.com")
Exemple #25
0
class Form(QMainWindow):

    requestGotoEid = Signal(str, int)  # uuid, eid

    def __init__(self, state, eids, uuid, name, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.setWindowTitle("Check “{}” — {}".format(
            name, QApplication.applicationName()))
        self.state = state
        self.uuid = uuid
        self.loadSaveSize = False
        self.createWidgets(eids, name)
        self.layoutWidgets()
        self.createConnections()
        self.browser.setFocus()

    def createWidgets(self, eids, name):
        self.browser = QTextBrowser()
        self.browser.setOpenExternalLinks(False)
        self.browser.setOpenLinks(False)
        text = ["<html>"]
        if not eids:
            text.append("<font color=darkgreen>No entries match the "
                        "“{}” check.</font>".format(name))
        else:
            self.loadSaveSize = True
            text.append("<p><font color=navy>{:,} entries match the "
                        "“{}” check.</font></p>".format(len(eids), name))
            for eid in eids:
                entry = self.state.model.entry(eid)
                if entry:
                    term = Lib.elidePatchHtml(entry.term, self.state)
                    prefix = "{} ".format(MAIN_INDICATOR if entry.peid ==
                                          ROOT else SUB_INDICATOR)
                    text.append('{}<a href="{}">{}</a><br>'.format(
                        prefix, eid, term))
        text.append("</html>")
        self.browser.setHtml("".join(text))
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")

    def layoutWidgets(self):
        layout = QVBoxLayout()
        hbox = QHBoxLayout()
        hbox.addStretch()
        hbox.addWidget(self.closeButton)
        hbox.addStretch()
        layout.addWidget(self.browser)
        layout.addLayout(hbox)
        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)
        if self.loadSaveSize:
            settings = QSettings()
            self.resize(
                QSize(
                    settings.value(Gopt.Key.CheckForm_Size,
                                   Gopt.Default.CheckForm_Size)))

    def createConnections(self):
        self.browser.anchorClicked.connect(self.gotoEid)
        self.closeButton.clicked.connect(self.close)

    def closeEvent(self, event=None):
        if self.loadSaveSize:
            settings = QSettings()
            settings.setValue(Gopt.Key.CheckForm_Size, self.size())
        super().closeEvent(event)

    def gotoEid(self, link):
        self.requestGotoEid.emit(self.uuid, int(link.toString()))
Exemple #26
0
 def __init__(self, parent=None):
     super(ErrorWidget, self).__init__(parent)
     self.hbox = QVBoxLayout(self)
     self.textBrowser = QTextBrowser(self)
     self.hbox.addWidget(self.textBrowser)
Exemple #27
0
class Ui_MainWindow(QMainWindow):
    """Cette classe contient tous les widgets de notre application."""
    
    defaultPalette = QPalette()
    defaultPalette.setColor(QPalette.Base, QColor("#151515"))
    defaultPalette.setColor(QPalette.Text, Qt.white)

    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        # initialise la GUI avec un exemple
        self.text = "Ceci est un petit texte d'exemple."
        # les variables sont en place, initialise la GUI
        self.initUI()
        # exécute l'exemple
        self.orgText.setText(self.text)
        self.encode_text(False)
        self.logLab.setText(
            u"Saisir du texte ou importer un fichier, puis pousser \n"
            u"le bouton correspondant à l'opération souhaitée.")

    def initUI(self):
        """Met en place les éléments de l'interface."""
        # -+++++++------------------- main window -------------------+++++++- #
        self.setWindowTitle(u"Encodage / Décodage de Huffman")
        self.centerAndResize()
        centralwidget = QWidget(self)
        mainGrid = QGridLayout(centralwidget)
        mainGrid.setColumnMinimumWidth(0, 450)
        # -+++++++------------------ groupe analyse -----------------+++++++- #
        analysGroup = QGroupBox(u"Analyse", centralwidget)
        self.analysGrid = QGridLayout(analysGroup)
        #         ----------- groupe de la table des codes ----------         #
        codeTableGroup = QGroupBox(u"Table des codes", analysGroup)
        codeTableGrid = QGridLayout(codeTableGroup)
        # un tableau pour les codes
        self.codesTableModel = MyTableModel()
        self.codesTable = QTableView(codeTableGroup)
        self.codesTable.setModel(self.codesTableModel)
        self.codesTable.setFont(QFont("Mono", 8))
        self.codesTable.resizeColumnsToContents()
        self.codesTable.setSortingEnabled(True)
        codeTableGrid.addWidget(self.codesTable, 0, 0, 1, 1)
        self.analysGrid.addWidget(codeTableGroup, 1, 0, 1, 1)
        #        ----------- label du ratio de compression ----------         #
        self.ratioLab = QLabel(u"Ratio de compression: ", analysGroup)
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        font.setKerning(True)
        self.ratioLab.setFont(font)
        self.analysGrid.addWidget(self.ratioLab, 2, 0, 1, 1)
        # -+++++++-------- groupe de la table de comparaison --------+++++++- #
        self.compGroup = QGroupBox(analysGroup)
        self.compGroup.setTitle(u"Comparaisons")
        compGrid = QGridLayout(self.compGroup)
        # un tableau pour le ratio
        self.compTable = QTableWidget(self.compGroup)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.compTable.sizePolicy().hasHeightForWidth())
        self.compTable.setSizePolicy(sizePolicy)
        self.compTable.setBaseSize(QSize(0, 0))
        font = QFont()
        font.setWeight(50)
        self.compTable.setFont(font)
        self.compTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.compTable.setShowGrid(True)
        self.compTable.setGridStyle(Qt.SolidLine)
        # lignes / colonnes
        self.compTable.setColumnCount(2)
        self.compTable.setRowCount(3)
        self.compTable.setVerticalHeaderItem(0, QTableWidgetItem("Taille (bits)"))
        self.compTable.setVerticalHeaderItem(1, QTableWidgetItem("Entropie"))
        self.compTable.setVerticalHeaderItem(2, QTableWidgetItem("Taille moy. (bits)"))
        for i in range(2):
            self.compTable.verticalHeaderItem(i).setTextAlignment(
                Qt.AlignRight)
        self.compTable.setHorizontalHeaderItem(0, QTableWidgetItem("ASCII"))
        self.compTable.setHorizontalHeaderItem(1, QTableWidgetItem("Huffman"))
        
        # nom des items
        self.compTabASCIIMem = QTableWidgetItem()
        self.compTable.setItem(0, 0, self.compTabASCIIMem)
        self.compTabASCIIEnt = QTableWidgetItem()
        self.compTable.setItem(1, 0, self.compTabASCIIEnt)
        self.compTabASCIIAvg = QTableWidgetItem()
        self.compTable.setItem(2, 0, self.compTabASCIIAvg)
        self.compTabHuffMem = QTableWidgetItem()
        self.compTable.setItem(0, 1, self.compTabHuffMem)
        self.compTabHuffEnt = QTableWidgetItem()
        self.compTable.setItem(1, 1, self.compTabHuffEnt)
        self.compTabHuffAvg = QTableWidgetItem()
        self.compTable.setItem(2, 1, self.compTabHuffAvg)
        # parem du tableau
        self.compTable.horizontalHeader().setCascadingSectionResizes(False)
        self.compTable.verticalHeader().setVisible(True)
        font = QFont("Mono", 8)
        self.compTable.setFont(font)
        compGrid.addWidget(self.compTable, 1, 0, 1, 1)
        self.analysGrid.addWidget(self.compGroup, 0, 0, 1, 1)
        mainGrid.addWidget(analysGroup, 0, 1, 1, 1)
        # -+++++++----------------- groupe du texte -----------------+++++++- #
        groupBox = QGroupBox(u"Texte", centralwidget)
        textGrid = QGridLayout(groupBox)
        # -+++++++------------- groupe du texte original ------------+++++++- #
        orgTextGroup = QGroupBox(u"Texte original (Ctrl+T)", groupBox)
        orgTextGrid = QGridLayout(orgTextGroup)
        self.orgText = QTextEdit(orgTextGroup)
        self.orgText.setPalette(self.defaultPalette)
        orgTextGrid.addWidget(self.orgText, 0, 0, 1, 1)
        textGrid.addWidget(orgTextGroup, 0, 0, 1, 2)
        # -+++++++------------ groupe du texte compressé ------------+++++++- #
        compressedTextGroup = QGroupBox(u"Texte compressé (Ctrl+H)", groupBox)
        compressedTextGrid = QGridLayout(compressedTextGroup)
        self.compressedText = QTextEdit(compressedTextGroup)
        self.compressedText.setPalette(self.defaultPalette)
        compressedTextGrid.addWidget(self.compressedText, 0, 0, 1, 1)
        textGrid.addWidget(compressedTextGroup, 1, 0, 1, 2)
        # -+++++++------------ groupe pour le texte ascii -----------+++++++- #
        asciiTextGroup = QGroupBox(u"Texte ASCII", groupBox)
        asciiTextGrid = QGridLayout(asciiTextGroup)
        self.asciiText = QTextBrowser(asciiTextGroup)
        self.asciiText.setPalette(self.defaultPalette)
        asciiTextGrid.addWidget(self.asciiText, 0, 0, 1, 1)
        textGrid.addWidget(asciiTextGroup, 2, 0, 1, 2)
        # -+++++++-------------------- label de log -----------------+++++++- #
        self.logLab = QLabel(analysGroup)
        textGrid.addWidget(self.logLab, 3, 0, 1, 2)
        # -+++++++----------- bouton pour encoder le texte ----------+++++++- #
        self.encodeBut = QPushButton(groupBox)
        self.encodeBut.setStatusTip(
            u"Cliquez sur ce bouton pour encoder le texte original.")
        self.encodeBut.setText(u"ENCODER")
        self.encodeBut.clicked.connect(self.encode_text)
        textGrid.addWidget(self.encodeBut, 4, 0, 1, 1)
        # -+++++++----------- bouton pour décoder le texte ----------+++++++- #
        self.decodeBut = QPushButton(groupBox)
        self.decodeBut.setStatusTip(
            u"Cliquez sur ce bouton pour décoder le texte compressé.")
        self.decodeBut.setText(u"DÉCODER")
        self.decodeBut.clicked.connect(self.decode_text)
        textGrid.addWidget(self.decodeBut, 4, 1, 1, 1)
        mainGrid.addWidget(groupBox, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        # -+++++++--------------- une barre de statut ---------------+++++++- #
        self.setStatusBar(QStatusBar(self))
        # -+++++++--------------------- le menu ---------------------+++++++- #
        self.fileMenu = QMenu(u"Fichier")
        self.fileMenu.addAction(u"Importer un texte...", self.open_text)
        self.fileMenu.addAction(
            u"Importer un texte encodé...", lambda: self.open_text(True))
        self.fileMenu.addAction(u"Importer un dictionnaire...", self.open_dict)
        self.fileMenu.addAction(u"Enregistrer le dictionnaire...", self.save_dict)
        self.fileMenu.addAction(u"Quitter", self.close)
        self.menuBar().addMenu(self.fileMenu)
        QMetaObject.connectSlotsByName(self)

    def open_text(self, compressed=False):
        """Ouvrir un fichier contenant un texte compressé ou non."""
        fname, _ = QFileDialog.getOpenFileName(self, u'Ouvrir')
        f = open(fname, 'r')
        with f:
            data = f.read()
            if compressed:
                self.compressedText.setText(data)
            else:
                self.orgText.setText(data)

    def open_dict(self):
        """Ouvrir un dictionnaire de codes Huffman."""
        fname, _ = QFileDialog.getOpenFileName(self, u'Ouvrir')
        self.occ = {}
        self.hCodes = {}
        self.aCodes = {}
        self.hCost = {}
        self.aCost = {}
        self.hCodes = create_dict_from_file(fname)
        self.update_codes_table()
        self.logLab.setText(u"Dictionnaire de Huffman importé.")
        return self.hCodes

    def save_dict(self):
        """Enregistrer le dictionnaire de codes Huffman."""
        fname, _ = QFileDialog.getSaveFileName(self, "Enregistrer sous")
        save_dict_to_file(fname, self.hCodes)

    def make_tab_rows(self):
        """Génère le remplissage des lignes du tableau des codes."""
        dictList = [self.occ, self.aCodes, self.hCodes, self.aCost, self.hCost]
        tabList = []
        charList = self.hCodes.keys() if self.hCodes else self.occ.keys()
        for char in charList:
            l = ["'" + char + "'"]
            for dic in dictList:
                try:
                    l.append(dic[char])
                except KeyError:
                    l.append('')
            tabList.append(l)
        return tabList

    def encode_text(self, wizard=True):
        """Encode le texte original."""
        self.text = self.orgText.toPlainText().encode('utf-8')
        if not self.text:
            self.compressedText.setText(u"")
            self.asciiText.setText(u"")
            self.logLab.setText(
                u"<font color=#A52A2A>Rien à compresser.</font>")
            return
        self.occ = {}
        self.tree = ()
        self.hCodes = {}
        self.aCodes = {}
        self.hCost = {}
        self.aCost = {}
        self.hSqueezed = []
        self.aSqueezed = []
        self.stringHSqueezed = ''
        self.stringASqueezed = ''
        if wizard:
            self.launch_wizard(
                EncodeWizard(self),
                u"<font color=#008000>Compression achevée.</font>")
        else:
            self.make_occ()
            self.make_tree()
            self.make_codes()
            self.make_cost()
            self.make_encoded_text()
            self.make_comp()

    def decode_text(self, wizard=True):
        """Décode le texte compressé."""
        self.codeString = str(
            self.compressedText.toPlainText().replace(' ', ''))
        if not self.codeString or not self.hCodes:
            self.orgText.setText(u"")
            self.asciiText.setText(u"")
            if not self.codeString:
                self.logLab.setText(
                    u"<font color=#A52A2A>Rien à décompresser.</font>")
            if not self.hCodes:
                self.logLab.setText(
                    u"<font color=#A52A2A>Dictionnaire indisponible pour la décompression.</font>")
            return
        self.text = ''
        self.stringASqueezed = ''
        if wizard:
            self.launch_wizard(
                DecodeWizard(self),
                u"<font color=#008000>Texte décompressé.</font>")
        else:
            self.make_code_map()
            self.make_decoded_text()

    def launch_wizard(self, wizard, finishString):
        """Lance l'assistant d'en/décodage pour guider l'utilisateur.
        Cache les options inaccessibles pendant l'assistant.
        """
        self.logLab.setText(
            u"<font color=#9E6A00>Opération en cours. "
            u"Suivre les indications.</font>")
        disItems = [self.orgText, self.compressedText, self.encodeBut,
                    self.decodeBut, self.fileMenu.actions()[1],
                    self.fileMenu.actions()[2], self.fileMenu.actions()[3]]
        for item in disItems:
            item.setEnabled(False)
        self.compGroup.setVisible(False)
        self.analysGrid.addWidget(wizard, 0, 0, 1, 1)
        res = wizard.exec_()
        if res:
            self.logLab.setText(finishString)
        else:
            self.logLab.setText(
                u"<font color=#A52A2A>Opération interrompue.</font>")
        for item in disItems:
            item.setEnabled(True)
        self.compGroup.setVisible(True)

    def update_ratio_lab(self):
        """Replace la valeur du label du ratio de compression."""
        if not self.stringASqueezed:
            val = '/'
        else:
            val = (len(self.stringHSqueezed.replace(' ', '')) /
                   float(len(self.stringASqueezed.replace(' ', ''))))
        self.ratioLab.setText(unicode('Taux de compression:  ' + str(val)))

    def update_comp_table(self):
        """Met à jour le tableau de comparaison ASCII VS Huffman."""
        self.compTabASCIIMem.setText(unicode(len(''.join(self.aSqueezed))))
        self.compTabHuffMem.setText(unicode(len(''.join(self.hSqueezed))))
        # entropie ?
        self.compTabASCIIEnt.setText('0')
        self.compTabHuffEnt.setText('0')
        self.compTabASCIIAvg.setText(unicode(8))
        self.compTabHuffAvg.setText(unicode(
            average_code_length(self.hSqueezed)))
        self.compTable.resizeColumnsToContents()

    def update_codes_table(self, hlRow=[]):
        """Met à jour le tableau des codes et surligne les lignes de hlRow."""
        self.codesTableModel.hlRow = hlRow
        self.codesTableModel.emptyTable()
        self.codesTableModel.fillTable(self.make_tab_rows())
        self.codesTable.resizeColumnsToContents()

    def centerAndResize(self):
        """Centre et redimmensionne le widget.""" 
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 1.6, screen.height() / 1.4)
        size = self.geometry()
        self.move(
            (screen.width() - size.width()) / 2,
            (screen.height() - size.height()) / 2)

    #===================== METHODS FOR EN/DECODE WIZARDS =====================#
    def make_encode_init(self):
        self.compressedText.setText(unicode(self.stringHSqueezed))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.orgText.setTextColor(QColor(Qt.darkGreen))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.update_codes_table()

    def make_occ(self):
        self.orgText.setTextColor(QColor(Qt.white))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.occ = occurences(self.text)
        self.update_codes_table([0, 1])

    def make_tree(self):
        self.tree = make_trie(self.occ)
        self.update_codes_table()

    def make_codes(self):
        self.hCodes = make_codes(self.tree, {})
        self.aCodes = make_ascii_codes(self.occ.keys(), {})
        self.update_codes_table([2, 3])

    def make_cost(self):
        self.hCost = tree_cost(self.hCodes, self.occ)
        self.aCost = tree_cost(self.aCodes, self.occ)
        self.update_codes_table([4, 5])

    def make_encoded_text(self):
        self.hSqueezed = squeeze(self.text, self.hCodes)
        self.aSqueezed = squeeze(self.text, self.aCodes)
        self.stringHSqueezed = ' '.join(self.hSqueezed)
        self.stringASqueezed = ' '.join(self.aSqueezed)
        self.compressedText.setTextColor(QColor(Qt.darkGreen))
        self.asciiText.setTextColor(QColor(Qt.darkYellow))
        self.compressedText.setText(unicode(self.stringHSqueezed))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table()

    def make_comp(self):
        self.compressedText.setTextColor(QColor(Qt.white))
        self.asciiText.setTextColor(QColor(Qt.white))
        self.compressedText.setText(unicode(self.stringHSqueezed))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table()
        self.update_comp_table()
        self.update_ratio_lab()

    def make_decode_init(self):
        self.orgText.setText(unicode(self.text))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.compressedText.setTextColor(QColor(Qt.darkGreen))
        self.compressedText.setText(self.compressedText.toPlainText())

    def make_code_map(self):
        self.compressedText.setTextColor(QColor(Qt.white))
        self.compressedText.setText(self.compressedText.toPlainText())
        self.orgText.setText(unicode(self.text))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.codeMap = dict(zip(self.hCodes.values(), self.hCodes.keys()))
        self.update_codes_table([0, 3])

    def make_decoded_text(self):
        self.unSqueezed = unsqueeze(self.codeString, self.codeMap)
        self.text = ''.join(self.unSqueezed)
        self.orgText.setTextColor(QColor(Qt.darkGreen))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table()

    def make_ascii_decode(self):
        self.orgText.setTextColor(QColor(Qt.white))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.aCodes = make_ascii_codes(self.codeMap.values(), {})
        self.aSqueezed = squeeze(self.text, self.aCodes)
        self.stringASqueezed = ' '.join(self.aSqueezed)
        self.occ = occurences(self.text)
        self.hCost = tree_cost(self.hCodes, self.occ)
        self.aCost = tree_cost(self.aCodes, self.occ)
        self.asciiText.setTextColor(QColor(Qt.darkGreen))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table([1, 2, 4, 5])
Exemple #28
0
    def __init__(self, parent):
        super(AboutDialog, self).__init__(parent)

        title = _("About {}...").format(configuration.get("Globals", "name"))
        self.setWindowTitle(title)
        top_layout = QVBoxLayout()
        self.title_widget = TitleWidget(title, self)
        top_layout.addWidget(self.title_widget)

        text = QLabel(u"{}<br/>Version : {}<br/><br/>".format(
            copyright(), str(configuration.this_version)) +
                      _("""This program is given to you with a few important
freedoms and duties as specified in the license below. <b>We believe they will help to make a better world</b>. They are
also <b>legally binding</b> (see Free Software Foundation's website), so make sure you read the license
carefully. We give you the right to
<ul>
<li>run the program,</li>
<li>inspect it to make sure it is safe to use,</li>
<li>modify it to suit your needs,</li>
<li>distribute copies of it,</li>
</ul>
as long as you give those freedoms and duties to anybody you give this program to.
"""))
        text.setTextFormat(Qt.RichText)
        text.setWordWrap(True)
        # text.setMaximumWidth(400)
        top_layout.addWidget(text)

        browser = QTextBrowser()
        browser.setLineWrapMode(QTextEdit.NoWrap)
        browser.setPlainText(license())
        browser.setMinimumWidth(browser.document().documentLayout().
                                documentSize().toSize().width())
        browser.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        top_layout.addWidget(browser)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton(QDialogButtonBox.Ok)

        top_layout.addWidget(self.buttons)
        self.setLayout(top_layout)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
    def __init__(self, parent=None):
        """Default class constructor."""
        super(AboutDialog, self).__init__(parent)

        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        if parent:
            self.gImgDir = parent.gImgDir
            self.gIconDir = parent.gIconDir
        elif __name__ == '__main__':
            self.gImgDir = gAppDir + os.sep + 'images'
            self.gIconDir = gAppDir + os.sep + 'icons' + os.sep + 'default'

        # The tiled theme background texture.
        self.bgLogo = QPixmap(self.gImgDir + os.sep + 'texture-spirals.png')
        self.bgBrush = QBrush(self.bgLogo)
        self.setWhatsThis(self.tr("""\
The background is a tiled image of an actual design that was stitched out during the pre-alpha stage.
It was created by Nina Paley and Theodore Gray using Mathematica in conjunction with our software.
They have graciously allowed us to use it for the project in whichever way we wish.
We thought it looked so good, that it has become the new theme for Embroidermodder 2.
To check out some of the more interesting embroidery projects they are working on,
visit http://blog.ninapaley.com/"""))

        self.imgLbl = EmbroidermodderLogo(self)

        aboutLbl = QTextBrowser(self)
        aboutLbl.setReadOnly(True)
        aboutLbl.setOpenExternalLinks(True)
        aboutLbl.setText('<b>%s</b>' % '<br>'.join(__doc__.split('\n')))
        aboutLbl.setWhatsThis(self.tr('This is the AWESOME people that brought Embroidermodder 2 to life.'))

        # We want very slight opacity of the white background
        # so the seamless texture shows slightly through.
        opacityStyleSheet = """\
        QTextEdit:read-only {
            color: rgb(50, 50, 50);
            font-size: 12px;
            font-weight: bold;
            background-color: rgba(255, 255, 255, 240);
            border: 1px solid rgba(0, 0, 0, 255);
            }
            """

        aboutLbl.setStyleSheet(opacityStyleSheet)
        op = QGraphicsOpacityEffect(aboutLbl)
        op.setOpacity(0.95)
        aboutLbl.setGraphicsEffect(op)

        self.notebook = QTabWidget(self)
        self.notebook.setMinimumWidth(500)
        self.notebook.addTab(aboutLbl, self.tr('About'))
        self.notebook.setTabIcon(0, QIcon(self.gIconDir + os.sep + 'app.png'))
        self.notebook.setTabIcon(1, QIcon(self.gImgDir + os.sep + 'kickstarter-logo-k-color.png'))

        notebookStyleSheet = """\
            QTabWidget::pane { /* The tab widget frame */
                border-top: 1px solid #000000;
                position: absolute;
                top: -0.5em;
            }

            QTabWidget::tab-bar {
                alignment: center;
            }

            /* Style the tab using the tab sub-control. Note that
                it reads QTabBar _not_ QTabWidget */
            QTabBar::tab {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                            stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                            stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
                border: 1px solid #000000;
                /* border-bottom-color: #C2C7CB; */ /* same as the pane color */
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                min-width: 40ex;
                min-height: 5ex;
                padding: 3px;
            }

            QTabBar::tab:selected {
                margin-top: 0px;
                font-size: 16px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #0C6AB0, stop: 0.15 #55C4E6,
                                            stop: 0.15 #55C4E6, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #55C4E6,
                                            stop: 0.85 #55C4E6, stop: 1.0 #0C6AB0);
                border: 1px solid #000000;
            }

            QTabBar::tab:!selected:hover {
                margin-top: 2px; /* make non-selected tabs look smaller */
                font-size: 14px;
                font-weight: bold;
                background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,
                                            stop: 0 #888888, stop: 0.15 #BBBBBB,
                                            stop: 0.15 #BBBBBB, stop: 0.5 #FFFFFF,
                                            stop: 0.5 #FFFFFF, stop: 0.85 #BBBBBB,
                                            stop: 0.85 #BBBBBB, stop: 1.0 #888888);
                border: 1px solid #000000;
            }

            QTabBar::tab:selected {
                border-color: #000000;
                border-bottom-color: #000000; /* same as pane color */
            }
            """

        self.notebook.setStyleSheet(notebookStyleSheet)
        self.notebook.currentChanged.connect(self.CurrentTabChanged)

        buttonbox = QDialogButtonBox(Qt.Horizontal, self)
        button = QPushButton(self)
        button.setText(self.tr("Oh, Yeah!"))
        button.setWhatsThis(self.tr('This is the Oh, Yeah! button!') + '\n' + self.tr('Oh, Yeah!'))
        buttonbox.addButton(button, QDialogButtonBox.AcceptRole)
        buttonbox.setCenterButtons(True)
        buttonbox.accepted.connect(self.accept)

        hbLayout1 = QHBoxLayout()
        hbLayout2 = QHBoxLayout()
        vbLayout = QVBoxLayout()
        hbLayout1.addStretch()
        hbLayout1.addWidget(self.imgLbl)
        hbLayout1.addStretch()
        hbLayout2.addStretch()
        hbLayout2.addWidget(self.notebook)
        hbLayout2.addStretch()
        vbLayout.addLayout(hbLayout1)
        vbLayout.addLayout(hbLayout2)
        vbLayout.addWidget(buttonbox)
        self.setLayout(vbLayout)

        self.setWindowTitle(self.tr('About Embroidermodder Version 2.0'))

        QApplication.restoreOverrideCursor() # TODO/???/PORT# don't mess with the window resize cursors.
Exemple #30
0
 def initUI(self):
     """Met en place les éléments de l'interface."""
     # -+++++++------------------- main window -------------------+++++++- #
     self.setWindowTitle(u"Encodage / Décodage de Huffman")
     self.centerAndResize()
     centralwidget = QWidget(self)
     mainGrid = QGridLayout(centralwidget)
     mainGrid.setColumnMinimumWidth(0, 450)
     # -+++++++------------------ groupe analyse -----------------+++++++- #
     analysGroup = QGroupBox(u"Analyse", centralwidget)
     self.analysGrid = QGridLayout(analysGroup)
     #         ----------- groupe de la table des codes ----------         #
     codeTableGroup = QGroupBox(u"Table des codes", analysGroup)
     codeTableGrid = QGridLayout(codeTableGroup)
     # un tableau pour les codes
     self.codesTableModel = MyTableModel()
     self.codesTable = QTableView(codeTableGroup)
     self.codesTable.setModel(self.codesTableModel)
     self.codesTable.setFont(QFont("Mono", 8))
     self.codesTable.resizeColumnsToContents()
     self.codesTable.setSortingEnabled(True)
     codeTableGrid.addWidget(self.codesTable, 0, 0, 1, 1)
     self.analysGrid.addWidget(codeTableGroup, 1, 0, 1, 1)
     #        ----------- label du ratio de compression ----------         #
     self.ratioLab = QLabel(u"Ratio de compression: ", analysGroup)
     font = QFont()
     font.setBold(True)
     font.setWeight(75)
     font.setKerning(True)
     self.ratioLab.setFont(font)
     self.analysGrid.addWidget(self.ratioLab, 2, 0, 1, 1)
     # -+++++++-------- groupe de la table de comparaison --------+++++++- #
     self.compGroup = QGroupBox(analysGroup)
     self.compGroup.setTitle(u"Comparaisons")
     compGrid = QGridLayout(self.compGroup)
     # un tableau pour le ratio
     self.compTable = QTableWidget(self.compGroup)
     sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     sizePolicy.setHorizontalStretch(0)
     sizePolicy.setVerticalStretch(0)
     sizePolicy.setHeightForWidth(
         self.compTable.sizePolicy().hasHeightForWidth())
     self.compTable.setSizePolicy(sizePolicy)
     self.compTable.setBaseSize(QSize(0, 0))
     font = QFont()
     font.setWeight(50)
     self.compTable.setFont(font)
     self.compTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
     self.compTable.setShowGrid(True)
     self.compTable.setGridStyle(Qt.SolidLine)
     # lignes / colonnes
     self.compTable.setColumnCount(2)
     self.compTable.setRowCount(3)
     self.compTable.setVerticalHeaderItem(0, QTableWidgetItem("Taille (bits)"))
     self.compTable.setVerticalHeaderItem(1, QTableWidgetItem("Entropie"))
     self.compTable.setVerticalHeaderItem(2, QTableWidgetItem("Taille moy. (bits)"))
     for i in range(2):
         self.compTable.verticalHeaderItem(i).setTextAlignment(
             Qt.AlignRight)
     self.compTable.setHorizontalHeaderItem(0, QTableWidgetItem("ASCII"))
     self.compTable.setHorizontalHeaderItem(1, QTableWidgetItem("Huffman"))
     
     # nom des items
     self.compTabASCIIMem = QTableWidgetItem()
     self.compTable.setItem(0, 0, self.compTabASCIIMem)
     self.compTabASCIIEnt = QTableWidgetItem()
     self.compTable.setItem(1, 0, self.compTabASCIIEnt)
     self.compTabASCIIAvg = QTableWidgetItem()
     self.compTable.setItem(2, 0, self.compTabASCIIAvg)
     self.compTabHuffMem = QTableWidgetItem()
     self.compTable.setItem(0, 1, self.compTabHuffMem)
     self.compTabHuffEnt = QTableWidgetItem()
     self.compTable.setItem(1, 1, self.compTabHuffEnt)
     self.compTabHuffAvg = QTableWidgetItem()
     self.compTable.setItem(2, 1, self.compTabHuffAvg)
     # parem du tableau
     self.compTable.horizontalHeader().setCascadingSectionResizes(False)
     self.compTable.verticalHeader().setVisible(True)
     font = QFont("Mono", 8)
     self.compTable.setFont(font)
     compGrid.addWidget(self.compTable, 1, 0, 1, 1)
     self.analysGrid.addWidget(self.compGroup, 0, 0, 1, 1)
     mainGrid.addWidget(analysGroup, 0, 1, 1, 1)
     # -+++++++----------------- groupe du texte -----------------+++++++- #
     groupBox = QGroupBox(u"Texte", centralwidget)
     textGrid = QGridLayout(groupBox)
     # -+++++++------------- groupe du texte original ------------+++++++- #
     orgTextGroup = QGroupBox(u"Texte original (Ctrl+T)", groupBox)
     orgTextGrid = QGridLayout(orgTextGroup)
     self.orgText = QTextEdit(orgTextGroup)
     self.orgText.setPalette(self.defaultPalette)
     orgTextGrid.addWidget(self.orgText, 0, 0, 1, 1)
     textGrid.addWidget(orgTextGroup, 0, 0, 1, 2)
     # -+++++++------------ groupe du texte compressé ------------+++++++- #
     compressedTextGroup = QGroupBox(u"Texte compressé (Ctrl+H)", groupBox)
     compressedTextGrid = QGridLayout(compressedTextGroup)
     self.compressedText = QTextEdit(compressedTextGroup)
     self.compressedText.setPalette(self.defaultPalette)
     compressedTextGrid.addWidget(self.compressedText, 0, 0, 1, 1)
     textGrid.addWidget(compressedTextGroup, 1, 0, 1, 2)
     # -+++++++------------ groupe pour le texte ascii -----------+++++++- #
     asciiTextGroup = QGroupBox(u"Texte ASCII", groupBox)
     asciiTextGrid = QGridLayout(asciiTextGroup)
     self.asciiText = QTextBrowser(asciiTextGroup)
     self.asciiText.setPalette(self.defaultPalette)
     asciiTextGrid.addWidget(self.asciiText, 0, 0, 1, 1)
     textGrid.addWidget(asciiTextGroup, 2, 0, 1, 2)
     # -+++++++-------------------- label de log -----------------+++++++- #
     self.logLab = QLabel(analysGroup)
     textGrid.addWidget(self.logLab, 3, 0, 1, 2)
     # -+++++++----------- bouton pour encoder le texte ----------+++++++- #
     self.encodeBut = QPushButton(groupBox)
     self.encodeBut.setStatusTip(
         u"Cliquez sur ce bouton pour encoder le texte original.")
     self.encodeBut.setText(u"ENCODER")
     self.encodeBut.clicked.connect(self.encode_text)
     textGrid.addWidget(self.encodeBut, 4, 0, 1, 1)
     # -+++++++----------- bouton pour décoder le texte ----------+++++++- #
     self.decodeBut = QPushButton(groupBox)
     self.decodeBut.setStatusTip(
         u"Cliquez sur ce bouton pour décoder le texte compressé.")
     self.decodeBut.setText(u"DÉCODER")
     self.decodeBut.clicked.connect(self.decode_text)
     textGrid.addWidget(self.decodeBut, 4, 1, 1, 1)
     mainGrid.addWidget(groupBox, 0, 0, 1, 1)
     self.setCentralWidget(centralwidget)
     # -+++++++--------------- une barre de statut ---------------+++++++- #
     self.setStatusBar(QStatusBar(self))
     # -+++++++--------------------- le menu ---------------------+++++++- #
     self.fileMenu = QMenu(u"Fichier")
     self.fileMenu.addAction(u"Importer un texte...", self.open_text)
     self.fileMenu.addAction(
         u"Importer un texte encodé...", lambda: self.open_text(True))
     self.fileMenu.addAction(u"Importer un dictionnaire...", self.open_dict)
     self.fileMenu.addAction(u"Enregistrer le dictionnaire...", self.save_dict)
     self.fileMenu.addAction(u"Quitter", self.close)
     self.menuBar().addMenu(self.fileMenu)
     QMetaObject.connectSlotsByName(self)