예제 #1
0
    def __init__(self, layoutInfo):
        """Set up a QFont object and initialize instance values.
        'layoutInfo' is a dictionary containing the required info
        """
        # Now it's a little complicated because the font needs to have a
        # special platform independent resolution/size. As Qt4 does
        # font metrics based on the display device resolution, we need
        # to know what that is. So a QFont is constructed based on a
        # QPicture, whose resolution can then be read. At first I
        # tried using QPrinter as the device, but this didn't work on
        # a Windows computer without a printer.
        global QP, fontscale
        if not QP:
            QP = QtGui.QPicture()
            # This was the first attempt, and worked well within one
            # platform, but on Linux there seems to be some inaccuracy
            # in the point size(!?)
            #            res = QP.logicalDpiX()
            #            fontscale = float(RESOLUTION) / res

            # This seems to help the inconsistency of font sizes
            # between Windows and Linux. It's not perfect, but
            # that may be impossible to attain.
            qf = QtGui.QFont()
            qf.setPointSize(1000)
            poi = QtGui.QFontInfo(qf).pointSizeF()
            qf.setPixelSize(1000)
            pix = QtGui.QFontInfo(qf).pointSizeF()

            fontscale = float(RESOLUTION) * pix / poi / 72

        family = layoutInfo[u"family"]
        QtGui.QFont.__init__(self, family)
        self.setPointSizeF(float(layoutInfo[u"points"]) * fontscale)
        self.setWeight(int(layoutInfo[u"weight"]))
        self.setStretch(int(float(layoutInfo[u"stretch"]) * 100))
        self.setItalic(layoutInfo[u"style"] == u"1")
        self.setUnderline(layoutInfo[u"underline"] == u"1")
        self.metric = QtGui.QFontMetricsF(self, QP)

        self.spWidth = self.getWidth(u" ")
        self.lineSpacing = self.metric.lineSpacing() * pts2mm \
                * float(layoutInfo[u"lineSpacing"])
        self.colour = getColour(layoutInfo[u"colour"])

        # Check whether the desired font was chosen
        fi = QtGui.QFontInfo(self)
        if (fi.family() != self.family()):
            warning(_("Font not available: '%s'") % family)
예제 #2
0
파일: util.py 프로젝트: GunioRobot/ipython
def get_font(family, fallback=None):
    """Return a font of the requested family, using fallback as alternative.

    If a fallback is provided, it is used in case the requested family isn't
    found.  If no fallback is given, no alternative is chosen and Qt's internal
    algorithms may automatically choose a fallback font.

    Parameters
    ----------
    family : str
      A font name.
    fallback : str
      A font name.

    Returns
    -------
    font : QFont object
    """
    font = QtGui.QFont(family)
    # Check whether we got what we wanted using QFontInfo, since exactMatch()
    # is overly strict and returns false in too many cases.
    font_info = QtGui.QFontInfo(font)
    if fallback is not None and font_info.family() != family:
        font = QtGui.QFont(fallback)
    return font
예제 #3
0
 def vFontFamily(self, value):
     """Check that the font family is available.
     """
     f = QtGui.QFont(value)
     fi = QtGui.QFontInfo(f)
     if (fi.family() != f.family()):
         return _("Font not available: %s") % value
     return ''
예제 #4
0
 def fontChanged(self, font):
     self.comboFont.setCurrentIndex(
         self.comboFont.findText(QtGui.QFontInfo(font).family()))
     self.comboSize.setCurrentIndex(
         self.comboSize.findText("%s" % font.pointSize()))
     self.actionTextBold.setChecked(font.bold())
     self.actionTextItalic.setChecked(font.italic())
     self.actionTextUnderline.setChecked(font.underline())
예제 #5
0
def font_resize(font, factor, minsize=None, maxsize=None):
    font = QtGui.QFont(font)
    fontinfo = QtGui.QFontInfo(font)
    size = fontinfo.pointSizeF() * factor

    if minsize is not None:
        size = max(size, minsize)
    if maxsize is not None:
        size = min(size, maxsize)

    font.setPointSizeF(size)
    return font
예제 #6
0
    def draw(self, scene, painter, rect, highlight=False):
        pen = self.select_pen(highlight)
        font = QtGui.QFont(pen.fontname, 8)

        if 0:
            qfd = QtGui.QFontDatabase()
            for x in qfd.families():
                print(x)
            font.setStyleHint(QtGui.QFont.Courier, QtGui.QFont.PreferAntialias)

            # FIXME: always see strange fonts
            qfi = QtGui.QFontInfo(font)

            print(qfi.family())
            print(qfi.styleHint())

        fm = QtGui.QFontMetrics(font)

        w = fm.width(self.t)
        h = fm.height()
        

        x = self.x - w / 2
        y = self.y

        pp = QtGui.QPainterPath()
        pp.moveTo(x, y)
        pp.addText(x, y, font, self.t)
        #print("added text " + str(self.t))
        p = QtGui.QPen(pen.color)
        p.setWidth(pen.linewidth)
        p.setCosmetic(True)
        painter.setPen(p)
        painter.fillPath(pp, QtGui.QBrush(pen.fillcolor))
        

        if 0:  # DEBUG
            # show where dot thinks the text should appear
            print("text shape debug")
            painter.set_source_rgba(1, 0, 0, .9)
            if self.j == self.LEFT:
                x = self.x
            elif self.j == self.CENTER:
                x = self.x - 0.5 * self.w
            elif self.j == self.RIGHT:
                x = self.x - self.w
            painter.moveTo(x, self.y)
            painter.line_to(x + self.w, self.y)
            painter.stroke()
예제 #7
0
파일: util.py 프로젝트: biji/qbzr
def _get_monospace_font():
    # TODO: Get font from system settings for Gnome, KDE, Mac.
    # (no windows option as far as I am aware)
    # Maybe have our own config setting.

    # Get the defaul font size
    size = QtGui.QApplication.font().pointSize()

    for font_family in ("Monospace", "Courier New"):
        font = QtGui.QFont(font_family, size)
        # check that this is really a monospace font
        if QtGui.QFontInfo(font).fixedPitch():
            return font

    # try use style hints to find font.
    font = QtGui.QFont("", size)
    font.setFixedPitch(True)
    return font
예제 #8
0
 def exportOdf(self, fileRef, nodeList, addBranches=True,
               includeRoot=True, openOnly=False):
     """Export an ODF format text file,
        fileRef is either a file path string or a file-like object
        (if it is a file-like object, fileRef.name must be defined)
        nodeList is list of nodes to export (defaults to selection),
        returns True on success, False on failure"""
     if not nodeList:
         nodeList = self.getSelectedNodes()
     fontInfo = QtGui.QFontInfo(self.mainWin.dataOutSplit.widget(0).font())
     try:
         globalref.docRef.exportOdf(fileRef, nodeList, fontInfo.family(),
                                    fontInfo.pointSize(),
                                    fontInfo.fixedPitch(), addBranches,
                                    includeRoot, openOnly)
         return True
     except IOError:
         return False
예제 #9
0
 def setFont(self, font):
     """Set the font selector to the given font"""
     fontInfo = QtGui.QFontInfo(font)
     family = fontInfo.family()
     matches = self.familyList.findItems(family, QtCore.Qt.MatchExactly)
     if matches:
         self.familyList.setCurrentItem(matches[0])
         self.familyList.scrollToItem(matches[0],
                                      QtGui.QAbstractItemView.PositionAtTop)
     style = QtGui.QFontDatabase().styleString(fontInfo)
     matches = self.styleList.findItems(style, QtCore.Qt.MatchExactly)
     if matches:
         self.styleList.setCurrentItem(matches[0])
         self.styleList.scrollToItem(matches[0])
     size = repr(fontInfo.pointSize())
     matches = self.sizeList.findItems(size, QtCore.Qt.MatchExactly)
     if matches:
         self.sizeList.setCurrentItem(matches[0])
         self.sizeList.scrollToItem(matches[0])
예제 #10
0
    def _add_list_item(self, placeholder, canvas, draw=True):
        list_item = QtGui.QListWidgetItem(placeholder)
        font = QtGui.QFont()
        font.setBold(True)
        height = QtGui.QFontInfo(font).pixelSize()
        list_item.setFont(font)
        list_item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop)
        list_item.setSizeHint(QtCore.QSize(self._item_width, self._item_height + height))

        item_label = QtGui.QLabel()
        item_label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom)

        self._listWidget.addItem(list_item)
        self._listWidget.setItemWidget(list_item, item_label)

        self._stackedLayout.addWidget(canvas)
        if draw:
            self._controller.app.processEvents()

        return item_label
예제 #11
0
 def exportFile(self, oldFileName, exportType):
     """Export file using exportType, return new filename on success"""
     if exportType == 'trl':
         fileName = self.newFileName(oldFileName, '.trl')
         self.doc.writeFile(fileName)
     elif exportType == 'html':
         fileName = self.newFileName(oldFileName, '.html')
         self.doc.exportHtml(fileName, self.doc.root, self.includeRoot,
                             False, self.indent, self.addHeader)
     elif exportType == 'dir':
         dirName = os.path.split(oldFileName)[0]
         if not dirName:
             dirName = '.'
         fileName = dirName
         self.doc.exportDir(dirName, [self.doc.root], self.addHeader)
     elif exportType == 'xslt':
         fileName = self.newFileName(oldFileName, '.xsl')
         self.doc.exportXslt(fileName, self.includeRoot, self.indent)
     elif exportType == 'tabbed':
         fileName = self.newFileName(oldFileName, '.txt')
         self.doc.exportTabbedTitles(fileName, [self.doc.root], True,
                                     self.includeRoot)
     elif exportType == 'table':
         fileName = self.newFileName(oldFileName, '.tbl')
         self.doc.exportTable(fileName, [self.doc.root])
     elif exportType == 'xbel':
         fileName = self.newFileName(oldFileName, '.xml')
         self.doc.exportXbel(fileName, [self.doc.root])
     elif exportType == 'mozilla':
         fileName = self.newFileName(oldFileName, '.html')
         self.doc.exportHtmlBookmarks(fileName, [self.doc.root])
     elif exportType == 'xml':
         fileName = self.newFileName(oldFileName, '.xml')
         self.doc.exportGenericXml(fileName, [self.doc.root])
     elif exportType == 'odf':
         fileName = self.newFileName(oldFileName, '.odt')
         fontInfo = QtGui.QFontInfo(QtGui.QApplication.font())
         self.doc.exportOdf(fileName, [self.doc.root], fontInfo.family(),
                            fontInfo.pointSize(), fontInfo.fixedPitch(), 
                            True, self.includeRoot)
     return fileName
예제 #12
0
    def __sendMessage(self):
        # TODO: Switch to this when implemented
        """ msg = self.ui.inputWidget.toHtml()
        self.ui.inputWidget.clear()
        strv = StringView()
        strv.appendElementsFromHtml(msg) """

        msg = QtCore.QString.fromUtf8(self.ui.inputWidget.toPlainText())
        self.ui.inputWidget.clear()
        color = self.color
        hex8 = "%.2x%.2x%.2x" % ((color.red()), (color.green()), (color.blue()))
        style = papyon.TextFormat.NO_EFFECT
        info = QtGui.QFontInfo(self.font)
        if info.bold(): style |= papyon.TextFormat.BOLD
        if info.italic():  style |= papyon.TextFormat.ITALIC
        if self.font.underline(): style |= papyon.TextFormat.UNDERLINE
        if self.font.strikeOut(): style |= papyon.TextFormat.STRIKETHROUGH
        font_family = str(info.family())
        format = papyon.TextFormat(font=font_family, color=hex8, style=style)
        strv = StringView()
        strv.append_text(str(msg))
        ## as we send our msg to the conversation:
        self._amsn_conversation.send_message(strv, format)
예제 #13
0
    def exportOdfText(self, filePath=''):
        """Export an ODF text file, use ExportDialog options.

        Prompt user for path if not given in argument.
        Return True on successful export.
        Arguments:
            filePath -- use if given, otherwise prompt user
        """
        if not filePath:
            filePath = self.getFileName(_('TreeLine - Export ODF Text'), 'odt')
            if not filePath:
                return False
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
        if ExportDialog.exportWhat == ExportDialog.entireTree:
            self.selectedNodes = [self.rootNode]
        addBranches = ExportDialog.exportWhat != ExportDialog.selectNode
        for prefix, uri in _odfNamespace.items():
            ElementTree.register_namespace(prefix, uri)

        versionAttr = {'office:version': '1.0'}
        fontInfo = QtGui.QFontInfo(
            globalref.mainControl.activeControl.activeWindow.editorSplitter.
            widget(0).font())
        fontAttr = {
            'style:font-pitch':
            'fixed' if fontInfo.fixedPitch() else 'variable',
            'style:name': fontInfo.family(),
            'svg:font-family': fontInfo.family()
        }
        fontElem = addOdfElement('office:font-face-decls')
        addOdfElement('style:font-face', fontElem, fontAttr)
        fontSizeDelta = 2

        contentRoot = addOdfElement('office:document-content',
                                    attr=versionAttr)
        contentRoot.append(fontElem)
        contentBodyElem = addOdfElement('office:body', contentRoot)
        contentTextElem = addOdfElement('office:text', contentBodyElem)
        maxLevel = 0
        for node in self.selectedNodes:
            level = node.exportOdf(contentTextElem, addBranches)
            maxLevel = max(level, maxLevel)

        manifestRoot = addOdfElement('manifest:manifest')
        addOdfElement(
            'manifest:file-entry', manifestRoot, {
                'manifest:media-type':
                'application/vnd.oasis.opendocument.text',
                'manifest:full-path': '/'
            })
        addOdfElement('manifest:file-entry', manifestRoot, {
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'content.xml'
        })
        addOdfElement('manifest:file-entry', manifestRoot, {
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'styles.xml'
        })

        styleRoot = addOdfElement('office:document-styles', attr=versionAttr)
        styleRoot.append(fontElem)
        stylesElem = addOdfElement('office:styles', styleRoot)
        defaultStyleElem = addOdfElement('style:default-style', stylesElem,
                                         {'style:family': 'paragraph'})
        addOdfElement('style:paragraph-properties', defaultStyleElem,
                      {'style:writing-mode': 'page'})
        addOdfElement(
            'style:text-properties', defaultStyleElem, {
                'fo:font-size': '{0}pt'.format(fontInfo.pointSize()),
                'fo:hyphenate': 'false',
                'style:font-name': fontInfo.family()
            })
        addOdfElement(
            'style:style', stylesElem, {
                'style:name': 'Standard',
                'style:class': 'text',
                'style:family': 'paragraph'
            })
        bodyStyleElem = addOdfElement(
            'style:style', stylesElem, {
                'style:name': 'Text_20_body',
                'style:display-name': 'Text body',
                'style:class': 'text',
                'style:family': 'paragraph',
                'style:parent-style-name': 'Standard'
            })
        addOdfElement('style:paragraph-properties', bodyStyleElem,
                      {'fo:margin-bottom': '6.0pt'})
        headStyleElem = addOdfElement(
            'style:style', stylesElem, {
                'style:name': 'Heading',
                'style:class': 'text',
                'style:family': 'paragraph',
                'style:next-style-name': 'Text_20_body',
                'style:parent-style-name': 'Standard'
            })
        addOdfElement(
            'style:paragraph-properties', headStyleElem, {
                'fo:keep-with-next': 'always',
                'fo:margin-bottom': '6.0pt',
                'fo:margin-top': '12.0pt'
            })
        addOdfElement(
            'style:text-properties', headStyleElem, {
                'fo:font-size':
                '{0}pt'.format(fontInfo.pointSize() + fontSizeDelta),
                'style:font-name':
                fontInfo.family()
            })
        outlineStyleElem = addOdfElement('text:outline-style')
        for level in range(1, maxLevel + 1):
            size = fontInfo.pointSize()
            if level <= 2:
                size += 2 * fontSizeDelta
            elif level <= 4:
                size += fontSizeDelta
            levelStyleElem = addOdfElement(
                'style:style', stylesElem, {
                    'style:name': 'Heading_20_{0}'.format(level),
                    'style:display-name': 'Heading {0}'.format(level),
                    'style:class': 'text',
                    'style:family': 'paragraph',
                    'style:parent-style-name': 'Heading',
                    'style:default-outline-level': '{0}'.format(level)
                })
            levelTextElem = addOdfElement(
                'style:text-properties', levelStyleElem, {
                    'fo:font-size': '{0}pt'.format(size),
                    'fo:font-weight': 'bold'
                })
            if level % 2 == 0:
                levelTextElem.set('fo:font-style', 'italic')
            addOdfElement('text:outline-level-style', outlineStyleElem, {
                'text:level': '{0}'.format(level),
                'style:num-format': ''
            })
        stylesElem.append(outlineStyleElem)
        autoStyleElem = addOdfElement('office:automatic-styles', styleRoot)
        pageLayElem = addOdfElement('style:page-layout', autoStyleElem,
                                    {'style:name': 'pm1'})
        addOdfElement(
            'style:page-layout-properties', pageLayElem, {
                'fo:margin-bottom': '0.75in',
                'fo:margin-left': '0.75in',
                'fo:margin-right': '0.75in',
                'fo:margin-top': '0.75in',
                'fo:page-height': '11in',
                'fo:page-width': '8.5in',
                'style:print-orientation': 'portrait'
            })
        masterStyleElem = addOdfElement('office:master-styles', styleRoot)
        addOdfElement('style:master-page', masterStyleElem, {
            'style:name': 'Standard',
            'style:page-layout-name': 'pm1'
        })

        with zipfile.ZipFile(filePath, 'w', zipfile.ZIP_DEFLATED) as odfZip:
            _addElemToZip(odfZip, contentRoot, 'content.xml')
            _addElemToZip(odfZip, manifestRoot, 'META-INF/manifest.xml')
            _addElemToZip(odfZip, styleRoot, 'styles.xml')
        return True
예제 #14
0
    def update(self):

        self.__updateEnvironmentDisplay()

        if not tcpip_stat.started():
            self._availableLabel.setText(
                "  tcpdump not running (no root privileges?).")
        else:
            self._availableLabel.setText("")

        if self.__processGone__ == False:
            if not (self.__reader__.hasProcess(self.__proc__)):
                self.__processGone__ = True
                self.__dialog__.setWindowTitle(self.__name__ + ":" +
                                               self.__proc__ +
                                               " Properties: dead")
                if self.__tcpStat__ != None:
                    self.__tcpStat__.doStop()
                    self.__tcpStat__.join()

            else:
                data = self.__reader__.getProcessCpuUsageHistory(self.__proc__)
                actual = data[-1:][0]
                self.__curveCpuHist__.setData(self.__y__, data)
                self.__curveCpuHistExt__.setData(self.__y__, data)

                data = self.__reader__.getProcessCpuUsageKernelHistory(
                    self.__proc__)
                self.__curveCpuKernelHist__.setData(self.__y__, data)
                self.__curveCpuKernelHistExt__.setData(self.__y__, data)

                self.__procDetails__.qwtPlotCpuHist.replot()
                self.__procDetails__.labelActualCpuUsage.setText(
                    str(actual) + "%")
                self.__procDetails__.actualCpu.setValue(actual)

                data = self.__reader__.getProcessRssUsageHistory(self.__proc__)
                actual = data[-1:][0]
                self.__curveRssHist__.setData(self.__y__, data)
                self.__curveRssHistExt__.setData(self.__y__, data)
                self.__procDetails__.qwtPlotRssHist.replot()
                self.__procDetails__.labelActualRss.setText(
                    str(actual) + " kB")
                self.__procDetails__.actualRss.setValue(actual)

                data = self.__reader__.getIOHistory(self.__proc__)
                actual = data[-1:][0]
                self.__curveIOHist__.setData(self.__y__, data)
                self.__curveIOHistExt__.setData(self.__y__, data)
                self.__procDetails__.qwtPlotIoHist.replot()
                self.__procDetails__.labelActualIo.setText(
                    str(actual) + " kB/s")
                self.__procDetails__.actualIo.setValue(actual)

                self.update_sockets()
                data = self.__TCPHist__
                try:
                    actual = self.__TCPHist__[-1:][0] / 1024
                except IndexError:
                    actual = 0
                self.__curveTcpipHist__.setData(self.__y__, data)
                self.__curveTcpipHistExt__.setData(self.__y__, data)
                self.__procDetails__.qwtPlotTcpipHist.replot()
                self.__procDetails__.labelActualTcpip.setText(
                    str(actual) + " kB/s")
                self.__procDetails__.actualTcpip.setValue(actual)

                self.__procDetails__.imagePwdLabel.setText(
                    self.__reader__.getcwd(self.__proc__))
                if str(self.__procDetails__.imageCommandLineLabel.text()
                       ) == "":
                    cmdLine = self.__reader__.getcmdline(self.__proc__)
                    if len(cmdLine) > 80:
                        cmdLine = cmdLine[:80] + "..."
                    self.__procDetails__.imageCommandLineLabel.setText(cmdLine)
                    self.__procDetails__.imagePathLabel.setText(
                        self.__reader__.getexe(self.__proc__))
                    self.__procDetails__.imagePidLabel.setText(
                        str(self.__proc__))
                    self.__procDetails__.imageStartedLabel.setText(
                        self.__reader__.getstartedtime(self.__proc__))
                    self.__procDetails__.imagePPidLabel.setText(
                        self.__reader__.getppid(self.__proc__))

                #update ldd output. Do this here: then it happens only when the user wants to see it
                #by opening a process properties window

                if self.__lddoutput__ is None:
                    try:
                        exepath = self.__reader__.getexe(self.__proc__)
                        ldd = subprocess.Popen(["ldd", exepath],
                                               stdout=subprocess.PIPE,
                                               stderr=subprocess.PIPE)
                        output = ldd.communicate()
                        err = output[1]
                        if len(err) > 0:
                            self.__lddoutput__ = err
                        else:
                            self.__lddoutput__ = output[0]
                            self.__lddoutput__ = self.__lddoutput__.replace(
                                "\t", "")
                        self.__procDetails__.libraryTextEdit.setText(
                            self.__lddoutput__)

                    except:
                        self.__lddoutput__ = "--"

                #thread information
                threadsInfo = self.__reader__.getThreads(self.__proc__)
                self.__procDetails__.threadsTableWidget.clearContents()

                fontInfo = QtGui.QFontInfo(
                    self.__procDetails__.threadsTableWidget.viewOptions().font)
                height = int(fontInfo.pixelSize() * 1.2 + 0.5)

                row = 0
                for t in threadsInfo:
                    if self.__procDetails__.threadsTableWidget.rowCount(
                    ) <= row:
                        self.__procDetails__.threadsTableWidget.insertRow(row)
                    if height != -1:
                        self.__procDetails__.threadsTableWidget.setRowHeight(
                            row, height)
                    self.__procDetails__.threadsTableWidget.setVerticalHeaderItem(
                        row, QtGui.QTableWidgetItem(""))

                    itemTid = QtGui.QTableWidgetItem(str(t))
                    itemWchan = QtGui.QTableWidgetItem(str(threadsInfo[t][0]))
                    itemWakeups = QtGui.QTableWidgetItem(str(
                        threadsInfo[t][1]))
                    self.__procDetails__.threadsTableWidget.setItem(
                        row, 0, itemTid)
                    self.__procDetails__.threadsTableWidget.setItem(
                        row, 1, itemWchan)
                    self.__procDetails__.threadsTableWidget.setItem(
                        row, 2, itemWakeups)
                    row += 1

                #show open files info
                self.__procDetails__.filesTableWidget.clearContents()
                fontInfo = QtGui.QFontInfo(
                    self.__procDetails__.filesTableWidget.viewOptions().font)
                height = int(fontInfo.pixelSize() * 1.2 + 0.5)
                fileInfo = self.__reader__.getFileInfo(self.__proc__)
                row = 0
                for fd in sorted([int(fd) for fd in fileInfo.keys()]):
                    if self.__procDetails__.filesTableWidget.rowCount() <= row:
                        self.__procDetails__.filesTableWidget.insertRow(row)
                    if height != -1:
                        self.__procDetails__.filesTableWidget.setRowHeight(
                            row, height)
                    self.__procDetails__.filesTableWidget.setVerticalHeaderItem(
                        row, QtGui.QTableWidgetItem(""))

                    itemFd = QtGui.QTableWidgetItem(str(fd))
                    itemPath = QtGui.QTableWidgetItem(
                        str(fileInfo[str(fd)]["path"]))
                    itemPos = QtGui.QTableWidgetItem(
                        str(fileInfo[str(fd)]["fdinfo"].split("\n")[0].split(
                            "\t")[1]))
                    self.__procDetails__.filesTableWidget.setItem(
                        row, 0, itemFd)
                    self.__procDetails__.filesTableWidget.setItem(
                        row, 1, itemPath)
                    self.__procDetails__.filesTableWidget.setItem(
                        row, 2, itemPos)
                    row += 1
예제 #15
0
    def update_sockets(self):
        #fill tcp/ip values
        connections, udp = self.__reader__.getAllProcessSockets(self.__proc__)
        text = []
        allConn = []
        nftotalBytesPerSecond = 0
        for conn in connections:
            ipfrom = connections[conn][1].split(":")
            ipfromport = ipfrom[1]
            ipfromaddr = ipfrom[0]
            ipfromaddrdec = str(int(ipfromaddr[6:8], 16)) + "." + str(
                int(ipfromaddr[4:6], 16)) + "." + str(int(
                    ipfromaddr[2:4], 16)) + "." + str(int(ipfromaddr[0:2], 16))

            ipto = connections[conn][2].split(":")
            iptoport = ipto[1]
            iptoaddr = ipto[0]

            iptoaddrdec = str(int(iptoaddr[6:8], 16)) + "." + str(
                int(iptoaddr[4:6], 16)) + "." + str(int(
                    iptoaddr[2:4], 16)) + "." + str(int(iptoaddr[0:2], 16))

            allConn.append(
                ((ipfromaddrdec, int(ipfromport,
                                     16)), (iptoaddrdec, int(iptoport, 16))))

            key1 = "%s.%s > %s.%s" % (ipfromaddrdec, int(
                ipfromport, 16), iptoaddrdec, int(iptoport, 16))
            bytesSentPerSecond = 0
            bytesReceivedPerSecond = 0
            if tcpip_stat.connections.has_key(key1):
                bytesSentPerSecond = tcpip_stat.connections[key1][
                    tcpip_stat.BYTESPERSECONDIDX]
                nftotalBytesPerSecond += bytesSentPerSecond
            key2 = "%s.%s > %s.%s" % (iptoaddrdec, int(
                iptoport, 16), ipfromaddrdec, int(ipfromport, 16))
            if tcpip_stat.connections.has_key(key2):
                bytesReceivedPerSecond = tcpip_stat.connections[key2][
                    tcpip_stat.BYTESPERSECONDIDX]
                nftotalBytesPerSecond += bytesReceivedPerSecond

            state = tcpstates[int(connections[conn][3], 16)]

            ipfromResolved = procutils.resolveIP(ipfromaddrdec)
            iptoResolved = procutils.resolveIP(iptoaddrdec)

            text.append(("TCPIP", ipfromResolved, str(int(ipfromport,16)), iptoResolved, str(int(iptoport,16)), state, \
                         procutils.humanReadable(bytesSentPerSecond)+"/s", procutils.humanReadable(bytesReceivedPerSecond)+"/s"))

        if nftotalBytesPerSecond > 0:
            self._availableLabel.hide()
        self.__TCPHist__.append(nftotalBytesPerSecond)
        self.__TCPHist__ = self.__TCPHist__[1:]
        for conn in udp:
            ipfrom = udp[conn][1].split(":")
            ipfromport = ipfrom[1]
            ipfromaddr = ipfrom[0]
            ipfromaddrdec = str(int(ipfromaddr[6:8], 16)) + "." + str(
                int(ipfromaddr[4:6], 16)) + "." + str(int(
                    ipfromaddr[2:4], 16)) + "." + str(int(ipfromaddr[0:2], 16))
            text.append(("UDP", ipfromaddrdec, str(int(ipfromport,
                                                       16)), "-", "-", "-"))

        self.__procDetails__.tcpipTableWidget.clearContents()
        fontInfo = QtGui.QFontInfo(
            self.__procDetails__.tcpipTableWidget.viewOptions().font)
        height = int(fontInfo.pixelSize() * 1.2 + 0.5)
        row = 0
        for line in text:
            if self.__procDetails__.tcpipTableWidget.rowCount() <= row:
                self.__procDetails__.tcpipTableWidget.insertRow(row)
            if height != -1:
                self.__procDetails__.tcpipTableWidget.setRowHeight(row, height)
            self.__procDetails__.tcpipTableWidget.setVerticalHeaderItem(
                row, QtGui.QTableWidgetItem(""))

            itemProto = QtGui.QTableWidgetItem(line[0])
            itemFrom = QtGui.QTableWidgetItem(line[1])
            itemFromPort = QtGui.QTableWidgetItem(line[2])
            itemTo = QtGui.QTableWidgetItem(line[3])
            itemToPort = QtGui.QTableWidgetItem(line[4])
            itemState = QtGui.QTableWidgetItem(line[5])
            if len(line) > 6:
                bytesSentSec = QtGui.QTableWidgetItem(str(line[6]))
                bytesReceivedSec = QtGui.QTableWidgetItem(str(line[7]))

            self.__procDetails__.tcpipTableWidget.setItem(row, 0, itemProto)
            self.__procDetails__.tcpipTableWidget.setItem(row, 1, itemFrom)
            self.__procDetails__.tcpipTableWidget.setItem(row, 2, itemFromPort)
            self.__procDetails__.tcpipTableWidget.setItem(row, 3, itemTo)
            self.__procDetails__.tcpipTableWidget.setItem(row, 4, itemToPort)
            self.__procDetails__.tcpipTableWidget.setItem(row, 5, itemState)
            if len(line) > 6:
                self.__procDetails__.tcpipTableWidget.setItem(
                    row, 6, bytesSentSec)
                self.__procDetails__.tcpipTableWidget.setItem(
                    row, 7, bytesReceivedSec)

            row += 1