Ejemplo n.º 1
0
def _qcolorFromRGBString(color):
    color = "".join([c for c in color if c in "1234567890,"])
    r, g, b = color.split(",")
    return QColor(int(r), int(g), int(b))
Ejemplo n.º 2
0
    cmap = cm.get_cmap(cmap_name, N)
    cmap=cmap(np.arange(N))[:,:-1]    
    colortable = []
    for el in cmap:
        r,g,b = el*255
        colortable.append(QColor(r,g,b).rgba())
    return colortable

def jet(N=256):
    ###This makes a jet colormap with 256 spaces
    return matplotlib_to_qt4_colortable("jet",N=N)




default16 = [QColor(0, 0, 255).rgba(),
            QColor(255, 255, 0).rgba(),
            QColor(255, 0, 0).rgba(),
            QColor(0, 255, 0).rgba(),
            QColor(0, 255, 255).rgba(),
            QColor(255, 0, 255).rgba(),
            QColor(255, 105, 180).rgba(), #hot pink
            QColor(102, 205, 170).rgba(), #dark aquamarine
            QColor(165,  42,  42).rgba(), #brown        
            QColor(0, 0, 128).rgba(),     #navy
            QColor(255, 165, 0).rgba(),   #orange
            QColor(173, 255,  47).rgba(), #green-yellow
            QColor(128,0, 128).rgba(),    #purple
            QColor(192, 192, 192).rgba(), #silver
            QColor(240, 230, 140).rgba(), #khaki
            QColor(69, 69, 69).rgba()]    # dark grey
Ejemplo n.º 3
0
    def setupLayers( self ):
        logger.debug( "setupLayers" )
        
        layers = []

        def onButtonsEnabled(slot, roi):
            currObj = self.topLevelOperatorView.CurrentObjectName.value
            hasSeg  = self.topLevelOperatorView.HasSegmentation.value
            
            self.labelingDrawerUi.currentObjectLabel.setText(currObj)
            self.labelingDrawerUi.save.setEnabled(hasSeg)

        self.topLevelOperatorView.CurrentObjectName.notifyDirty(onButtonsEnabled)
        self.topLevelOperatorView.HasSegmentation.notifyDirty(onButtonsEnabled)
        self.topLevelOperatorView.opLabelArray.NonzeroBlocks.notifyDirty(onButtonsEnabled)
        
        # Labels
        labellayer, labelsrc = self.createLabelLayer(direct=True)
        if labellayer is not None:
            labellayer._allowToggleVisible = False
            layers.append(labellayer)
            # Tell the editor where to draw label data
            self.editor.setLabelSink(labelsrc)

        #uncertainty
        #if self._showUncertaintyLayer:
        #    uncert = self.topLevelOperatorView.Uncertainty
        #    if uncert.ready():
        #        colortable = []
        #        for i in range(256-len(colortable)):
        #            r,g,b,a = i,0,0,i
        #            colortable.append(QColor(r,g,b,a).rgba())
        #        layer = ColortableLayer(LazyflowSource(uncert), colortable, direct=True)
        #        layer.name = "Uncertainty"
        #        layer.visible = True
        #        layer.opacity = 0.3
        #        layers.append(layer)
       
        #segmentation 
        seg = self.topLevelOperatorView.Segmentation
        
        #seg = self.topLevelOperatorView.MST.value.segmentation
        #temp = self._done_lut[self.MST.value.supervoxelUint32[sl[1:4]]]
        if seg.ready():
            #source = RelabelingArraySource(seg)
            #source.setRelabeling(numpy.arange(256, dtype=numpy.uint8))
            colortable = [QColor(0,0,0,0).rgba(), QColor(0,0,0,0).rgba(), QColor(0,255,0).rgba()]
            for i in range(256-len(colortable)):
                r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
                colortable.append(QColor(r,g,b).rgba())

            layer = ColortableLayer(LazyflowSource(seg), colortable, direct=True)
            layer.name = "Segmentation"
            layer.setToolTip("This layer displays the <i>current</i> segmentation. Simply add foreground and background " \
                             "labels, then press <i>Segment</i>.")
            layer.visible = True
            layer.opacity = 0.3
            layers.append(layer)
        
        #done 
        done = self.topLevelOperatorView.DoneObjects
        if done.ready(): 
            colortable = [QColor(0,0,0,0).rgba(), QColor(0,0,255).rgba()]
            #have to use lazyflow because it provides dirty signals
            layer = ColortableLayer(LazyflowSource(done), colortable, direct=True)
            layer.name = "Completed segments (unicolor)"
            layer.setToolTip("In order to keep track of which objects you have already completed, this layer " \
                             "shows <b>all completed object</b> in one color (<b>blue</b>). " \
                             "The reason for only one color is that for finding out which " \
                              "objects to label next, the identity of already completed objects is unimportant " \
                              "and destracting.")
            layer.visible = False
            layer.opacity = 0.5
            layers.append(layer)

        #done seg
        doneSeg = self.topLevelOperatorView.DoneSegmentation
        if doneSeg.ready():
            layer = ColortableLayer(LazyflowSource(doneSeg), self._doneSegmentationColortable, direct=True)
            layer.name = "Completed segments (one color per object)"
            layer.setToolTip("<html>In order to keep track of which objects you have already completed, this layer " \
                             "shows <b>all completed object</b>, each with a random color.</html>")
            layer.visible = False
            layer.opacity = 0.5
            self._doneSegmentationLayer = layer
            layers.append(layer)

        #supervoxel
        sv = self.topLevelOperatorView.Supervoxels
        if sv.ready():
            colortable = []
            for i in range(256):
                r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
                colortable.append(QColor(r,g,b).rgba())
            layer = ColortableLayer(LazyflowSource(sv), colortable, direct=True)
            layer.name = "Supervoxels"
            layer.setToolTip("<html>This layer shows the partitioning of the input image into <b>supervoxels</b>. The carving " \
                             "algorithm uses these tiny puzzle-piceces to piece together the segmentation of an " \
                             "object. Sometimes, supervoxels are too large and straddle two distinct objects " \
                             "(undersegmentation). In this case, it will be impossible to achieve the desired " \
                             "segmentation. This layer helps you to understand these cases.</html>")
            layer.visible = False
            layer.opacity = 1.0
            layers.append(layer)

        #raw data
        rawSlot = self.topLevelOperatorView.RawData
        if rawSlot.ready():
            raw5D = self.topLevelOperatorView.RawData.value
            layer = GrayscaleLayer(ArraySource(raw5D), direct=True)
            #layer = GrayscaleLayer( LazyflowSource(rawSlot) )
            layer.visible = True
            layer.name = 'Raw Data'
            layer.opacity = 1.0
            layers.append(layer)

        inputSlot = self.topLevelOperatorView.InputData
        if inputSlot.ready():
            layer = GrayscaleLayer( LazyflowSource(inputSlot), direct=True )
            layer.name = "Input Data"
            layer.setToolTip("<html>The data originally loaded into ilastik (unprocessed).</html>")
            #layer.visible = not rawSlot.ready()
            layer.visible = True
            layer.opacity = 1.0
            # if the flag window_leveling is set the contrast 
            # of the layer is adjustable
            layer.window_leveling = True
            layers.append(layer)

            if layer.window_leveling:
                self.labelingDrawerUi.thresToolButton.show()
            else:
                self.labelingDrawerUi.thresToolButton.hide()

        filteredSlot = self.topLevelOperatorView.FilteredInputData
        if filteredSlot.ready():
            layer = GrayscaleLayer( LazyflowSource(filteredSlot) )
            layer.name = "Filtered Input"
            layer.visible = False
            layer.opacity = 1.0
            layers.append(layer)

        return layers
Ejemplo n.º 4
0
    def paint(self, painter, option, index):
        """draw the individual lines in the layers control
        """
        painter.save()

        color = QColor(187, 213, 255, 255) if index.row() % 2 == 0 else QColor(
            177, 223, 255, 255)
        # color = QColor(187, 213, 255, 255)
        painter.setPen(QPen(color))
        painter.setFont(self.font)
        value = index.data(Qt.UserRole)
        text = index.data(Qt.DisplayRole)
        rect = option.rect

        # if we have a value, break out the animation order and other info
        animation_order = None
        if value:
            value, animation_order = value

        # if we have a point probe value, draw the filled bar to represent where it is in that layer's data range
        if value:
            value, bar, fmtd_str = value
            w = bar * float(rect.width())
            r = QRect(rect.left(), rect.top(), int(w), rect.height())
            painter.fillRect(r, color)

        super(LayerWidgetDelegate, self).paint(painter, option, index)

        # if this layer is selected, draw a colored rectangle to highlight it
        if option.state & QStyle.State_Selected and value:
            painter.fillRect(r, QColor(213, 187, 255, 96))

        # draw the name of the layer
        painter.setPen(QPen(Qt.black))
        painter.setFont(self.font)
        bounds = painter.drawText(
            rect.left() + LEFT_OFFSET,
            rect.top() + TOP_OFFSET,
            rect.width() - LEFT_OFFSET,
            CELL_HEIGHT / 2 - TOP_OFFSET,
            Qt.AlignLeft,
            text,
        )

        # also draw the animation order
        if animation_order is not None:
            painter.setPen(QPen(Qt.white))
            ao_rect = QRect(
                bounds.right(),
                rect.top() + TOP_OFFSET,
                rect.width() - bounds.right(),
                CELL_HEIGHT / 2 - TOP_OFFSET,
            )
            # draw the text once to get the bounding rectangle
            bounds = painter.drawText(
                ao_rect,
                Qt.AlignRight,
                str(animation_order + 1),
            )
            painter.fillRect(bounds, Qt.black)
            # draw the text a second time to make sure it appears in the rectangle
            painter.drawText(
                ao_rect,
                Qt.AlignRight,
                str(animation_order + 1),
            )

        # if we have a point probe value, draw text with it's value
        if value:
            painter.setPen(Qt.darkBlue)
            theight = CELL_HEIGHT / 2
            t = rect.top() + rect.height() - theight
            if w < rect.width(
            ) / 3:  # place the text to the right of the bar instead of inside
                l = max(int(w), LEFT_OFFSET)
                r = rect.width()
                align = Qt.AlignLeft
            else:
                l = 0
                r = w
                align = Qt.AlignRight
            painter.drawText(l, t, r - l, theight, align, fmtd_str)

        painter.restore()
Ejemplo n.º 5
0
    def __init__(self, scatter_widget, parent=None, _="None"):
        gui.OWComponent.__init__(self, scatter_widget)
        self.view_box = InteractiveViewBox(self)
        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,
                                         background="w")
        self.plot_widget.getPlotItem().buttonsHidden = True
        self.plot_widget.setAntialiasing(True)
        self.plot_widget.sizeHint = lambda: QtCore.QSize(500, 500)

        self.replot = self.plot_widget.replot
        ScaleScatterPlotData.__init__(self)
        self.density_img = None
        self.scatterplot_item = None
        self.scatterplot_item_sel = None

        self.labels = []

        self.master = scatter_widget
        self.master.Warning.add_message(
            "missing_coords",
            "Plot cannot be displayed because '{}' or '{}' is missing for "
            "all data points")
        self.master.Information.add_message(
            "missing_coords",
            "Points with missing '{}' or '{}' are not displayed")
        self.master.Information.add_message(
            "missing_size",
            "Points with undefined '{}' are shown in smaller size")
        self.master.Information.add_message(
            "missing_shape",
            "Points with undefined '{}' are shown as crossed circles")
        self.shown_attribute_indices = []
        self.shown_x = ""
        self.shown_y = ""
        self.pen_colors = self.brush_colors = None

        self.valid_data = None  # np.ndarray
        self.selection = None  # np.ndarray
        self.n_points = 0

        self.gui = OWPlotGUI(self)
        self.continuous_palette = ContinuousPaletteGenerator(
            QColor(255, 255, 0), QColor(0, 0, 255), True)
        self.discrete_palette = ColorPaletteGenerator()

        self.selection_behavior = 0

        self.legend = self.color_legend = None
        self.__legend_anchor = (1, 0), (1, 0)
        self.__color_legend_anchor = (1, 1), (1, 1)

        self.scale = None  # DiscretizedScale

        self.subset_indices = None

        # self.setMouseTracking(True)
        # self.grabGesture(QPinchGesture)
        # self.grabGesture(QPanGesture)

        self.update_grid()

        self._tooltip_delegate = HelpEventDelegate(self.help_event)
        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)
Ejemplo n.º 6
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext",
                                       "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(
            QColor(
                self.settings.value("pythonConsole/defaultFontColor",
                                    QColor(Qt.black))))
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/commentFontColor",
                                    QColor(Qt.gray))), 1)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/keywordFontColor",
                                    QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/classFontColor",
                                    QColor(Qt.blue))), 8)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/methodFontColor",
                                    QColor(Qt.darkGray))), 9)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/decorFontColor",
                                    QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/commentBlockFontColor",
                                    QColor(Qt.gray))), 12)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/singleQuoteFontColor",
                                    QColor(Qt.blue))), 4)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/doubleQuoteFontColor",
                                    QColor(Qt.blue))), 3)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/tripleSingleQuoteFontColor",
                                    QColor(Qt.blue))), 6)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/tripleDoubleQuoteFontColor",
                                    QColor(Qt.blue))), 7)
        self.lexer.setColor(QColor(Qt.red), 14)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 2)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(
                self.settings.value("pythonConsole/paperBackgroundColor",
                                    QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.setLexer(self.lexer)
Ejemplo n.º 7
0
    def draw_statistics(self):
        """Draw lines that represent standard deviation or quartiles"""
        if self.show_statistics and self.have_data:
            n_attr = len(self.attributes)
            data = []
            for attr_idx in self.attribute_indices:
                if not isinstance(self.data_domain[attr_idx], ContinuousVariable):
                    data.append([()])
                    continue  # only for continuous attributes

                if not self.data_has_class or self.data_has_continuous_class:    # no class
                    attr_values = self.no_jittering_scaled_data[attr_idx]
                    attr_values = attr_values[~np.isnan(attr_values)]

                    if self.show_statistics == MEANS:
                        m = attr_values.mean()
                        dev = attr_values.std()
                        data.append([(m - dev, m, m + dev)])
                    elif self.show_statistics == MEDIAN:
                        sorted_array = np.sort(attr_values)
                        if len(sorted_array) > 0:
                            data.append([(sorted_array[int(len(sorted_array) / 4.0)],
                                          sorted_array[int(len(sorted_array) / 2.0)],
                                          sorted_array[int(len(sorted_array) * 0.75)])])
                        else:
                            data.append([(0, 0, 0)])
                else:
                    curr = []
                    class_values = get_variable_values_sorted(self.data_domain.class_var)
                    for c in range(len(class_values)):
                        attr_values = self.scaled_data[attr_idx, self.original_data[self.data_class_index] == c]
                        attr_values = attr_values[~np.isnan(attr_values)]

                        if len(attr_values) == 0:
                            curr.append((0, 0, 0))
                            continue
                        if self.show_statistics == MEANS:
                            m = attr_values.mean()
                            dev = attr_values.std()
                            curr.append((m - dev, m, m + dev))
                        elif self.show_statistics == MEDIAN:
                            sorted_array = np.sort(attr_values)
                            curr.append((sorted_array[int(len(attr_values) / 4.0)],
                                         sorted_array[int(len(attr_values) / 2.0)],
                                         sorted_array[int(len(attr_values) * 0.75)]))
                    data.append(curr)

            # draw vertical lines
            for i in range(len(data)):
                for c in range(len(data[i])):
                    if data[i][c] == ():
                        continue
                    x = i - 0.03 * (len(data[i]) - 1) / 2.0 + c * 0.03
                    col = QColor(self.discrete_palette[c])
                    col.setAlpha(self.alpha_value_2)
                    self.add_curve("", col, col, 3, OWCurve.Lines, OWPoint.NoSymbol, xData=[x, x, x],
                                   yData=[data[i][c][0], data[i][c][1], data[i][c][2]], lineWidth=4)
                    self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03],
                                   yData=[data[i][c][0], data[i][c][0]], lineWidth=4)
                    self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03],
                                   yData=[data[i][c][1], data[i][c][1]], lineWidth=4)
                    self.add_curve("", col, col, 1, OWCurve.Lines, OWPoint.NoSymbol, xData=[x - 0.03, x + 0.03],
                                   yData=[data[i][c][2], data[i][c][2]], lineWidth=4)

            # draw lines with mean/median values
            if not self.data_has_class or self.data_has_continuous_class:
                class_count = 1
            else:
                class_count = len(self.data_domain.class_var.values)
            for c in range(class_count):
                diff = - 0.03 * (class_count - 1) / 2.0 + c * 0.03
                ys = []
                xs = []
                for i in range(len(data)):
                    if data[i] != [()]:
                        ys.append(data[i][c][1])
                        xs.append(i + diff)
                    else:
                        if len(xs) > 1:
                            col = QColor(self.discrete_palette[c])
                            col.setAlpha(self.alpha_value_2)
                            self.add_curve("", col, col, 1, OWCurve.Lines,
                                           OWPoint.NoSymbol, xData=xs, yData=ys, lineWidth=4)
                        xs = []
                        ys = []
                col = QColor(self.discrete_palette[c])
                col.setAlpha(self.alpha_value_2)
                self.add_curve("", col, col, 1, OWCurve.Lines,
                               OWPoint.NoSymbol, xData=xs, yData=ys, lineWidth=4)
def main(argv=None):
    if argv is None:
        argv = sys.argv

    usage = "usage: %prog [options] [scheme_file]"
    parser = optparse.OptionParser(usage=usage)

    parser.add_option("--no-discovery",
                      action="store_true",
                      help="Don't run widget discovery "
                      "(use full cache instead)")

    parser.add_option("--force-discovery",
                      action="store_true",
                      help="Force full widget discovery "
                      "(invalidate cache)")
    parser.add_option("--no-welcome",
                      action="store_true",
                      help="Don't show welcome dialog.")
    parser.add_option("--no-splash",
                      action="store_true",
                      help="Don't show splash screen.")
    parser.add_option("-l",
                      "--log-level",
                      help="Logging level (0, 1, 2, 3, 4)",
                      type="int",
                      default=1)
    parser.add_option("--no-redirect",
                      action="store_true",
                      help="Do not redirect stdout/err to canvas output view.")
    parser.add_option("--style",
                      help="QStyle to use",
                      type="str",
                      default=None)
    parser.add_option("--stylesheet",
                      help="Application level CSS style sheet to use",
                      type="str",
                      default="orange.qss")
    parser.add_option("--qt",
                      help="Additional arguments for QApplication",
                      type="str",
                      default=None)

    (options, args) = parser.parse_args(argv[1:])

    levels = [
        logging.CRITICAL, logging.ERROR, logging.WARN, logging.INFO,
        logging.DEBUG
    ]

    logging.basicConfig(level=levels[options.log_level])

    fix_win_pythonw_std_stream()

    log.info("Starting 'Orange Canvas' application.")

    qt_argv = argv[:1]

    if options.style is not None:
        qt_argv += ["-style", options.style]

    if options.qt is not None:
        qt_argv += shlex.split(options.qt)

    qt_argv += args

    log.debug("Starting CanvasApplicaiton with argv = %r.", qt_argv)
    app = CanvasApplication(qt_argv)

    # intercept any QFileOpenEvent requests until the main window is
    # fully initialized.
    # NOTE: The QApplication must have the executable ($0) and filename
    # arguments passed in argv otherwise the FileOpen events are
    # triggered for them (this is done by Cocoa, but QApplicaiton filters
    # them out if passed in argv)

    open_requests = []

    def onrequest(url):
        log.info("Received an file open request %s", url)
        open_requests.append(url)

    app.fileOpenRequest.connect(onrequest)

    # Note: config.init must be called after the QApplication constructor
    config.init()
    settings = QSettings()

    stylesheet = options.stylesheet
    stylesheet_string = None

    if stylesheet != "none":
        if os.path.isfile(stylesheet):
            stylesheet_string = open(stylesheet, "rb").read()
        else:
            if not os.path.splitext(stylesheet)[1]:
                # no extension
                stylesheet = os.path.extsep.join([stylesheet, "qss"])

            pkg_name = OrangeCanvas.__name__
            resource = "styles/" + stylesheet

            if pkg_resources.resource_exists(pkg_name, resource):
                stylesheet_string = \
                    pkg_resources.resource_string(pkg_name, resource)

                base = pkg_resources.resource_filename(pkg_name, "styles")

                pattern = re.compile(
                    r"^\s@([a-zA-Z0-9_]+?)\s*:\s*([a-zA-Z0-9_/]+?);\s*$",
                    flags=re.MULTILINE)

                matches = pattern.findall(stylesheet_string)

                for prefix, search_path in matches:
                    QDir.addSearchPath(prefix, os.path.join(base, search_path))
                    log.info("Adding search path %r for prefix, %r",
                             search_path, prefix)

                stylesheet_string = pattern.sub("", stylesheet_string)

            else:
                log.info("%r style sheet not found.", stylesheet)

    if stylesheet_string is not None:
        app.setStyleSheet(stylesheet_string)

    # Add the default canvas_icons search path
    dirpath = os.path.abspath(os.path.dirname(OrangeCanvas.__file__))
    QDir.addSearchPath("canvas_icons", os.path.join(dirpath, "icons"))

    canvas_window = CanvasMainWindow()

    if not options.force_discovery:
        reg_cache = cache.registry_cache()
    else:
        reg_cache = None

    widget_discovery = qt.QtWidgetDiscovery(cached_descriptions=reg_cache)

    widget_registry = qt.QtWidgetRegistry()

    widget_discovery.found_category.connect(widget_registry.register_category)
    widget_discovery.found_widget.connect(widget_registry.register_widget)

    want_splash = \
        settings.value("startup/show-splash-screen", True, type=bool) and \
        not options.no_splash

    if want_splash:
        pm, rect = config.splash_screen()
        splash_screen = SplashScreen(pixmap=pm, textRect=rect)
        splash_screen.setFont(QFont("Helvetica", 12))
        color = QColor("#FFD39F")

        def show_message(message):
            splash_screen.showMessage(message, color=color)

        widget_discovery.discovery_start.connect(splash_screen.show)
        widget_discovery.discovery_process.connect(show_message)
        widget_discovery.discovery_finished.connect(splash_screen.hide)

    log.info("Running widget discovery process.")

    cache_filename = os.path.join(cache_dir(), "widget-registry.pck")
    if options.no_discovery:
        widget_registry = cPickle.load(open(cache_filename, "rb"))
        widget_registry = qt.QtWidgetRegistry(widget_registry)
    else:
        widget_discovery.run(config.widgets_entry_points())
        # Store cached descriptions
        cache.save_registry_cache(widget_discovery.cached_descriptions)
        cPickle.dump(WidgetRegistry(widget_registry),
                     open(cache_filename, "wb"))
    set_global_registry(widget_registry)
    canvas_window.set_widget_registry(widget_registry)
    canvas_window.show()
    canvas_window.raise_()

    want_welcome = \
        settings.value("startup/show-welcome-screen", True, type=bool) \
        and not options.no_welcome

    # Process events to make sure the canvas_window layout has
    # a chance to activate (the welcome dialog is modal and will
    # block the event queue, plus we need a chance to receive open file
    # signals when running without a splash screen)
    app.processEvents()

    app.fileOpenRequest.connect(canvas_window.open_scheme_file)

    if want_welcome and not args and not open_requests:
        canvas_window.welcome_dialog()

    elif args:
        log.info("Loading a scheme from the command line argument %r", args[0])
        canvas_window.load_scheme(args[0])
    elif open_requests:
        log.info("Loading a scheme from an `QFileOpenEvent` for %r",
                 open_requests[-1])
        canvas_window.load_scheme(open_requests[-1].toLocalFile())

    stdout_redirect = \
        settings.value("output/redirect-stdout", True, type=bool)

    stderr_redirect = \
        settings.value("output/redirect-stderr", True, type=bool)

    # cmd line option overrides settings / no redirect is possible
    # under ipython
    if options.no_redirect or running_in_ipython():
        stderr_redirect = stdout_redirect = False

    output_view = canvas_window.output_view()

    if stdout_redirect:
        stdout = TextStream()
        stdout.stream.connect(output_view.write)
        # also connect to original fd
        stdout.stream.connect(sys.stdout.write)
    else:
        stdout = sys.stdout

    if stderr_redirect:
        error_writer = output_view.formated(color=Qt.red)
        stderr = TextStream()
        stderr.stream.connect(error_writer.write)
        # also connect to original fd
        stderr.stream.connect(sys.stderr.write)
    else:
        stderr = sys.stderr

    if stderr_redirect:
        sys.excepthook = ExceptHook()
        sys.excepthook.handledException.connect(output_view.parent().show)

    with nested(redirect_stdout(stdout), redirect_stderr(stderr)):
        log.info("Entering main event loop.")
        try:
            status = app.exec_()
        except BaseException:
            log.error("Error in main event loop.", exc_info=True)

    canvas_window.deleteLater()
    app.processEvents()
    app.flush()
    del canvas_window

    # Collect any cycles before deleting the QApplication instance
    gc.collect()

    del app
    return status
Ejemplo n.º 9
0
    def set_results(self, results):
        """Set the input results."""

        self.clear()
        self.warning([0, 1])

        data = None
        if results is not None:
            if results.data is not None:
                data = results.data

        if data is not None and not data.domain.has_discrete_class:
            data = None
            results = None
            self.warning(
                0, "Confusion Matrix cannot be used for regression results.")

        self.results = results
        self.data = data

        if data is not None:
            class_values = data.domain.class_var.values
        elif results is not None:
            raise NotImplementedError

        if results is not None:
            nmodels, ntests = results.predicted.shape
            self.headers = class_values + \
                           [unicodedata.lookup("N-ARY SUMMATION")]

            # NOTE: The 'learner_names' is set in 'Test Learners' widget.
            if hasattr(results, "learner_names"):
                self.learners = results.learner_names
            else:
                self.learners = ["Learner #%i" % (i + 1)
                                 for i in range(nmodels)]

            item = self._item(0, 2)
            item.setData("Predicted", Qt.DisplayRole)
            item.setTextAlignment(Qt.AlignCenter)
            item.setFlags(Qt.NoItemFlags)

            self._set_item(0, 2, item)
            item = self._item(2, 0)
            item.setData("Actual", Qt.DisplayRole)
            item.setTextAlignment(Qt.AlignHCenter | Qt.AlignBottom)
            item.setFlags(Qt.NoItemFlags)
            self.tableview.setItemDelegateForColumn(
                0, gui.VerticalItemDelegate())
            self._set_item(2, 0, item)
            self.tableview.setSpan(0, 2, 1, len(class_values))
            self.tableview.setSpan(2, 0, len(class_values), 1)

            for i in (0, 1):
                for j in (0, 1):
                    item = self._item(i, j)
                    item.setFlags(Qt.NoItemFlags)
                    self._set_item(i, j, item)

            for p, label in enumerate(self.headers):
                for i, j in ((1, p + 2), (p + 2, 1)):
                    item = self._item(i, j)
                    item.setData(label, Qt.DisplayRole)
                    item.setData(QBrush(QColor(208, 208, 208)),
                                 Qt.BackgroundColorRole)
                    item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    item.setFlags(Qt.ItemIsEnabled)
                    self._set_item(i, j, item)

            hor_header = self.tableview.horizontalHeader()
            if len(' '.join(self.headers)) < 120:
                hor_header.setResizeMode(QHeaderView.ResizeToContents)
            else:
                hor_header.setDefaultSectionSize(60)
            self.tablemodel.setRowCount(len(class_values) + 3)
            self.tablemodel.setColumnCount(len(class_values) + 3)
            self.selected_learner = [0]
            self._update()
Ejemplo n.º 10
0
    def updateDisplay(self):
        ''' Add map(s) of all QF components to the canvas based on what's selected in self.lstTimes'''
        timestamps = [
            pd.datetime.strptime(newItem.text(), '%Y-%m-%d %H:%M')
            for newItem in self.lstTimes.selectedItems()
        ]

        for t in timestamps:
            outs = pd.read_csv(self.model.getFileList()[t],
                               header=0,
                               index_col=0)
            outLayer = self.outputLayer
            # Make sure the output file is properly appended (this gets evaluated for non-extra-disaggregated datasets)
            # because I didn't set an output shapefile path properly

            if os.path.split(self.outputLayer)[0] == '':
                outLayer = os.path.join(self.model.downscaledPath,
                                        os.path.split(self.outputLayer)[1])

            fileToPopulate = self.outputLayer
            new_layer = populateShapefileFromTemplate(
                outs,
                self.featureIdField,
                outLayer,
                int(self.outputEPSG),
                title=t.strftime(' %Y-%m-%d %H:%M UTC'))

            # Set ranges suited to all the different QF types
            range_minima = [0, 0.000001, 0.1, 1, 10, 100]
            range_maxima = [0.000001, 0.1, 1, 10, 100, 1000]
            colours = [
                '#CECECE', '#FEE6CE', '#FDAE6B', '#F16913', '#D94801',
                '#7F2704'
            ]
            opacity = 1
            for component in self.componentTranslation.values():
                layerName = component + t.strftime(' %Y-%m-%d %H:%M UTC')
                if component == self.componentTranslation.values()[0]:
                    colourRanges(new_layer, component, opacity, range_minima,
                                 range_maxima, colours)
                    new_layer.setLayerName(layerName)
                    layerId = new_layer.id()
                    QgsMapLayerRegistry.instance().addMapLayer(new_layer)
                    proportion = new_layer.extent().height(
                    ) / new_layer.extent().width()

                else:
                    # Have to clone. Can't seem to duplicate a map layer...
                    layer = duplicateVectorLayer(new_layer)
                    layer.setLayerName(layerName)
                    colourRanges(layer, component, opacity, range_minima,
                                 range_maxima, colours)
                    layerId = layer.id()
                    QgsMapLayerRegistry.instance().addMapLayer(layer)
                    proportion = layer.extent().height() / layer.extent(
                    ).width()

                maxSize = 2000  # Max size of output image
                if proportion > 1:
                    hSize = maxSize / proportion
                    vSize = maxSize
                else:
                    hSize = maxSize
                    vSize = maxSize * proportion

                # create image in proportion with layer
                img = QImage(QSize(hSize, vSize),
                             QImage.Format_ARGB32_Premultiplied)

                # set image's background color
                color = QColor(255, 255, 255)
                img.fill(color.rgb())

                # create painter
                p = QPainter()
                p.begin(img)
                p.setRenderHint(QPainter.Antialiasing)

                render = QgsMapRenderer()

                # set layer set
                lst = [layerId]  # add ID of every layer
                render.setLayerSet(lst)

                # set extent
                rect = QgsRectangle(render.fullExtent())
                rect.scale(1.1)
                render.setExtent(rect)

                # set output size
                render.setOutputSize(img.size(), img.logicalDpiX())

                # do the rendering
                render.render(p)
                p.end()

                # save image
                img.save(
                    os.path.join(
                        self.model.renderPath,
                        component + t.strftime('_%Y-%m-%d_%H-%M_UTC.png')),
                    "png")
Ejemplo n.º 11
0
        return not self._table.isColumnHidden(self.model.ColumnID.FixIcon)

    @allowFixIcon.setter
    def allowFixIcon(self, allow):
        self._table.setColumnHidden(self.model.ColumnID.FixIcon, not allow)

    
if __name__=="__main__":
    from boxListModel import BoxListModel,BoxLabel
    import numpy
    import sys
    from PyQt4.QtGui import QApplication

    app = QApplication(sys.argv)

    red   = QColor(255,0,0)
    green = QColor(0,255,0)
    blue  = QColor(0,0,255)
    #model = LabelListModel([Label("Label 1", red),
    #                        Label("Label 2", green),
    #                        Label("Label 3", blue)])
    model = BoxListModel()

    l = QVBoxLayout()
    w = QWidget(None)
    w.setLayout(l)
    addButton = QPushButton("Add random label")
    l.addWidget(addButton)


    
Ejemplo n.º 12
0
    def updateConfig(self):
        qs = Qsci.QsciScintilla
        c = self.distributedObjects.editorController.config
        self.setWhitespaceVisibility(
            qs.WsVisible if c.showWhiteSpaces.value else qs.WsInvisible)
        self.setIndentationGuides(c.showIndentationGuides.value)
        self.setTabWidth(int(c.tabWidth.value))
        self.setWrapMode(qs.WrapWord if c.wrapLines.value else qs.WrapNone)
        self.setFolding(
            qs.BoxedTreeFoldStyle if c.folding.value else qs.NoFoldStyle,
            self.MARGIN_MARKER_FOLD)
        self.lexer.setPaper(QColor(c.backgroundColor.value))
        self.lexer.setColor(QColor(c.identifierColor.value),
                            self.lexer.Identifier)
        self.lexer.setColor(QColor(c.identifierColor.value),
                            self.lexer.Operator)
        self.setCaretForegroundColor(QColor(c.identifierColor.value))
        self.lexer.setColor(QColor(c.keywordColor.value), self.lexer.Keyword)
        self.lexer.setColor(QColor(c.stringColor.value),
                            self.lexer.SingleQuotedString)
        self.lexer.setColor(QColor(c.stringColor.value),
                            self.lexer.DoubleQuotedString)
        self.lexer.setColor(QColor(c.numberColor.value), self.lexer.Number)
        self.lexer.setColor(QColor(c.preprocessorColor.value),
                            self.lexer.PreProcessor)
        self.lexer.setColor(QColor(c.commentColor.value), self.lexer.Comment)
        self.lexer.setColor(QColor(c.commentColor.value),
                            self.lexer.CommentLine)
        self.lexer.setColor(QColor(c.commentColor.value),
                            self.lexer.CommentDoc)
        self.setIndicatorForegroundColor(QColor(c.tooltipIndicatorColor.value))
        self.setMarkerBackgroundColor(QColor(c.highlightColor.value),
                                      self.MARKER_HIGHLIGHTED_LINE)

        # check whether we're supposed to use overlays and reload everything
        # that uses them
        self.__useBreakpointOverlays = c.useBreakpointOverlays.value
        self.getBreakpointsFromModel()
Ejemplo n.º 13
0
# coding=utf-8
"""Styles and colors which are used in InaSAFE."""

from PyQt4.QtGui import QColor

__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "*****@*****.**"
__revision__ = 'b2d0c787b7d956ae517d9245e8cb7b285d71ce74'

transparent = QColor(0, 0, 0, 0)

# Hazard classes as specified in reporting standards :
# https://github.com/inasafe/inasafe/issues/2920#issuecomment-229874044
grey = QColor('#8C8C8C')  # Used for not exposed.
green = QColor('#1A9641')
light_green = QColor('#A6D96A')
yellow = QColor('#FFFFB2')
orange = QColor('#FEB24C')
red = QColor('#F03B20')
dark_red = QColor('#BD0026')
very_dark_red = QColor('#710017')

# Colors for each MMI levels.
MMI_1 = QColor('#ffffff')
MMI_2 = QColor('#209fff')
MMI_3 = QColor('#00cfff')
MMI_4 = QColor('#55ffff')
MMI_5 = QColor('#aaffff')
MMI_6 = QColor('#fff000')
MMI_7 = QColor('#ffa800')
Ejemplo n.º 14
0
 def paint(self, painter, option, index):
     painter.save()
     painter.setPen(QColor(212, 212, 212))
     painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
     painter.restore()
     QStyledItemDelegate.paint(self, painter, option, index)
Ejemplo n.º 15
0
Archivo: button.py Proyecto: utsdab/sww
class DT_Button(qg.QPushButton, base.Base):
    _gradient = {NORMAL: {}, DOWN: {}, DISABLED: {}}

    inner_gradient = QLinearGradient(0, 3, 0, 24)
    inner_gradient.setColorAt(0, QColor(53, 57, 60))
    inner_gradient.setColorAt(1, QColor(33, 34, 36))
    _gradient[NORMAL][INNER] = QBrush(inner_gradient)

    outer_gradient = QLinearGradient(0, 2, 0, 25)
    outer_gradient.setColorAt(0, QColor(69, 73, 76))
    outer_gradient.setColorAt(1, QColor(17, 18, 20))
    _gradient[NORMAL][OUTER] = QBrush(outer_gradient)

    inner_gradient_down = QLinearGradient(0, 3, 0, 24)
    inner_gradient_down.setColorAt(0, QColor(20, 21, 23))
    inner_gradient_down.setColorAt(1, QColor(48, 49, 51))
    _gradient[DOWN][INNER] = QBrush(inner_gradient_down)

    outer_gradient_down = QLinearGradient(0, 2, 0, 25)
    outer_gradient_down.setColorAt(0, QColor(36, 37, 39))
    outer_gradient_down.setColorAt(1, QColor(32, 33, 35))
    _gradient[DOWN][OUTER] = QBrush(outer_gradient_down)

    inner_gradient_disabled = QLinearGradient(0, 3, 0, 24)
    inner_gradient_disabled.setColorAt(0, QColor(33, 37, 40))
    inner_gradient_disabled.setColorAt(1, QColor(13, 14, 16))
    _gradient[DISABLED][INNER] = QBrush(inner_gradient_disabled)

    outer_gradient_disabled = QLinearGradient(0, 2, 0, 25)
    outer_gradient_disabled.setColorAt(0, QColor(49, 53, 56))
    outer_gradient_disabled.setColorAt(1, QColor(9, 10, 12))
    _gradient[DISABLED][OUTER] = QBrush(outer_gradient_disabled)

    def __init__(self, *args, **kwargs):
        qg.QPushButton.__init__(self, *args, **kwargs)
        base.Base.__init__(self)
        self.setFixedHeight(27)

        self._radius = 5

        self.font_metrics = qg.QFontMetrics(self.font())

    def paintEvent(self, event):
        painter = qg.QStylePainter(self)
        option = qg.QStyleOption()
        option.initFrom(self)

        x = option.rect.x()
        y = option.rect.y()
        height = option.rect.height() - 1
        width = option.rect.width() - 1

        painter.setRenderHint(qg.QPainter.Antialiasing)

        radius = self._radius

        gradient = self._gradient[NORMAL]
        offset = 0
        if self.isDown():
            gradient = self._gradient[DOWN]
            offset = 1
        elif not self.isEnabled():
            gradient = self._gradient[DISABLED]

        painter.setBrush(self._brush_border)
        painter.setPen(self._pens_border)
        painter.drawRoundedRect(qc.QRect(x + 1, y + 1, width - 1, height - 1),
                                radius, radius)

        painter.setPen(self._pens_clear)

        painter.setBrush(gradient[OUTER])
        painter.drawRoundedRect(qc.QRect(x + 2, y + 2, width - 3, height - 3),
                                radius, radius)

        painter.setBrush(gradient[INNER])
        painter.drawRoundedRect(qc.QRect(x + 3, y + 3, width - 5, height - 5),
                                radius - 1, radius - 1)

        painter.setBrush(self._brush_clear)

        # draw text
        #
        text = self.text()
        font = self.font()

        text_width = self.font_metrics.width(text)
        text_height = font.pointSize()

        text_path = qg.QPainterPath()
        text_path.addText((width - text_width) / 2,
                          height - ((height - text_height) / 2) - 1 + offset,
                          font, text)

        glow_index = self._glow_index
        glow_pens = self._glow_pens

        alignment = (qc.Qt.AlignHCenter | qc.Qt.AlignVCenter)

        if self.isEnabled():
            painter.setPen(self._pens_shadow)
            painter.drawPath(text_path)

            painter.setPen(self._pens_text)
            painter.drawText(x, y + offset, width, height, alignment, text)

            if glow_index > 0:
                for index in range(3):
                    painter.setPen(glow_pens[glow_index][index])
                    painter.drawPath(text_path)

                painter.setPen(glow_pens[glow_index][3])
                painter.drawText(x, y + offset, width, height, alignment, text)

        else:
            painter.setPen(self._pens_shadow_disabled)
            painter.drawPath(text_path)

            painter.setPen(self._pens_text_disabled)
            painter.drawText(x, y + offset, width, height, alignment, text)
def print_text(image,
               text,
               scene_mode=common.SCENE_MODES.normal,
               format=TextFormat(),
               mangle=True):

    img_w = IMG_W
    img_h = IMG_H

    if image:
        img_w = image.width()
        img_h = image.height()

    out = QImage(img_w, img_h, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())

    painter = QPainter(out)
    # This is a better representation of how the game handles text.
    painter.setCompositionMode(QPainter.CompositionMode_DestinationOver)
    painter.setRenderHint(QPainter.Antialiasing, True)

    lines, lengths, clt_changes = process_text(text, scene_mode, format,
                                               mangle)

    base_x = format.x
    base_y = format.y
    line_height = format.h

    x, y = base_x, base_y
    cur_clt = 0

    text_height = len(lines) * line_height
    while text_height + y > img_h:
        y -= line_height

    center_x = format.x + (format.w / 2.0)
    right_x = format.x + format.w

    for i, line in enumerate(lines):
        # Only bother if we actually see the line.
        if y > -line_height and y < img_h:
            line_length = sum(lengths[i])

            if format.orient == TEXT_ORIENT.hor:
                if format.align == TEXT_ALIGN.left:
                    x = base_x
                elif format.align == TEXT_ALIGN.right:
                    x = right_x - line_length
                elif format.align == TEXT_ALIGN.center:
                    x = center_x - (line_length / 2.0)
                elif format.align == TEXT_ALIGN.offcenter:
                    x = center_x - (line_length / 2.0) - 7

            for j in range(len(line)):
                char = line[j]

                if j in clt_changes[i]:
                    cur_clt = clt_changes[i][j]

                letter, (xshift, yshift, final_w,
                         final_h) = get_letter(cur_clt, char)

                final_x = (x + xshift)
                final_y = (y + yshift) + max(
                    0, (line_height - final_h)) + CLT_STYLES[cur_clt].y_shift

                painter.drawImage(QRect(final_x, final_y, final_w, final_h),
                                  letter, letter.rect())

                if format.orient == TEXT_ORIENT.hor:
                    x += lengths[i][j]
                elif format.orient == TEXT_ORIENT.ver:
                    y += lengths[i][j]

        if format.orient == TEXT_ORIENT.hor:
            y += line_height
        elif format.orient == TEXT_ORIENT.ver:
            y = base_y
            x -= line_height

    # And, last but not least, draw the image underneath everything.
    if image:
        painter.drawImage(out.rect(), image, image.rect())

    painter.end()
    return out
Ejemplo n.º 17
0
    def findTables(self):
        self.ui.testBT.setEnabled(True)

        cl = CartoDBAPIKey(self.currentApiKey, self.currentUser)
        try:
            if not str(self.currentMultiuser) in ['true', '1', 'True']:
                sqlTables = "SELECT CDB_UserTables() table_name"
                res = cl.sql("WITH usertables AS (" + sqlTables + ") \
                        SELECT ut.table_name, c.column_name, c.data_type column_type \
                          FROM usertables ut \
                          JOIN information_schema.columns c ON c.table_name = ut.table_name \
                        WHERE c.data_type != 'USER-DEFINED' \
                        ORDER BY ut.table_name, c.column_name")
            else:
                sqlTables = "SELECT string_agg(privilege_type, ', ') AS privileges, table_schema, table_name \
                                FROM information_schema.role_table_grants tg \
                                JOIN ( \
                                    SELECT DISTINCT u.usename \
                                    FROM information_schema.tables t \
                                    JOIN pg_catalog.pg_class c ON (t.table_name = c.relname) \
                                    JOIN pg_catalog.pg_user u ON (c.relowner = u.usesysid) \
                                    WHERE t.table_schema = '" + self.currentUser + "') u ON u.usename = tg.grantee \
                            WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'cartodb', 'public', 'cdb_importer') \
                            GROUP BY table_schema, table_name \
                            ORDER BY table_schema, table_name"

                res = cl.sql("WITH usertables AS (" + sqlTables + ") \
                     SELECT ut.table_name, c.column_name, c.data_type column_type, ut.privileges \
                        FROM usertables ut \
                        JOIN information_schema.columns c ON c.table_name = ut.table_name \
                     WHERE c.data_type != 'USER-DEFINED' \
                     ORDER BY ut.table_name, c.column_name")

            tables = []
            oldTableName = None
            parentTableItem = None
            for table in res['rows']:

                if table['table_name'] != oldTableName:
                    parentTableItem = QTreeWidgetItem()
                    oldTableName = table['table_name']
                    parentTableItem.setText(0, self.tr(oldTableName))
                    parentTableItem.setIcon(
                        0,
                        QIcon(
                            ":/plugins/qgis-cartodb/images/icons/layers.png"))
                    if str(self.currentMultiuser) in [
                            'true', '1', 'True'
                    ] and table['privileges'] == 'SELECT':
                        parentTableItem.setTextColor(0, QColor('#999999'))
                    tables.append(parentTableItem)

                tableItem = QTreeWidgetItem(parentTableItem)
                tableItem.setText(0, self.tr(table['column_name']))
                if str(self.currentMultiuser) in [
                        'true', '1', 'True'
                ] and table['privileges'] == 'SELECT':
                    tableItem.setTextColor(0, QColor('#999999'))
                tableItem.setToolTip(0, self.tr(table['column_type']))
                tableItem.setIcon(
                    0, QIcon(":/plugins/qgis-cartodb/images/icons/text.png"))
                if table['column_type'] == 'integer' or table[
                        'column_type'] == 'double precision':
                    tableItem.setIcon(
                        0,
                        QIcon(
                            ":/plugins/qgis-cartodb/images/icons/number.png"))
                elif table['column_type'] == 'timestamp with time zone':
                    tableItem.setIcon(
                        0,
                        QIcon(
                            ":/plugins/qgis-cartodb/images/icons/calendar.png")
                    )
            self.setTablesListItems(tables)
        except CartoDBException as e:
            QgsMessageLog.logMessage(
                'Some error ocurred getting tables: ' + str(e.args),
                'CartoDB Plugin', QgsMessageLog.CRITICAL)
            QMessageBox.information(
                self, QApplication.translate('CartoDBPlugin', 'Error'),
                QApplication.translate('CartoDBPlugin',
                                       'Error getting tables'), QMessageBox.Ok)
            self.ui.tablesTree.clear()
def draw_scene(scene_info, text=None):
    bg = None
    max_length = 0
    kill_blanks = False

    if scene_info.mode in [
            common.SCENE_MODES.normal, common.SCENE_MODES.normal_flat
    ]:
        bg = get_normal(scene_info)

        if scene_info.box_type == common.BOX_TYPES.flat:
            scene_info.mode = common.SCENE_MODES.normal_flat
        else:
            scene_info.mode = common.SCENE_MODES.normal

    elif scene_info.mode == common.SCENE_MODES.trial:
        bg = get_trial(scene_info)

    elif scene_info.mode == common.SCENE_MODES.novel:
        scene_info.box_type = common.BOX_TYPES.novel
        bg = get_normal(scene_info)

    elif scene_info.mode == common.SCENE_MODES.rules:
        bg = QImage(os.path.join(MENU_DIR, "rules.png"))

    elif scene_info.mode == common.SCENE_MODES.ammo:
        bg = QImage(os.path.join(MENU_DIR, "ammo-desc.png"))
        overlay = get_ammo(scene_info.file_id, 254, 117)

        if not bg.format() is QImage.Format_ARGB32_Premultiplied:
            bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(bg)
        painter.setCompositionMode(QPainter.CompositionMode_DestinationOver)
        painter.drawImage(bg.rect(), overlay, overlay.rect())
        painter.end()

        name = get_ammo_name(scene_info.file_id)
        if name:
            bg = print_text(bg, name, common.SCENE_MODES.ammoname,
                            TEXT_FORMATS[common.SCENE_MODES.ammoname], False)

    elif scene_info.mode == common.SCENE_MODES.ammoname:
        bg = QImage(os.path.join(MENU_DIR, "ammo-list.png"))
        overlay = get_ammo(scene_info.file_id, 254, 61)

        if not bg.format() is QImage.Format_ARGB32_Premultiplied:
            bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(bg)
        painter.setCompositionMode(QPainter.CompositionMode_DestinationOver)
        painter.drawImage(bg.rect(), overlay, overlay.rect())
        painter.end()

    elif scene_info.mode == common.SCENE_MODES.present:
        bg = QImage(os.path.join(MENU_DIR, "present-desc.png"))
        overlay = get_present(scene_info.file_id, 248, 96)

        if not bg.format() is QImage.Format_ARGB32_Premultiplied:
            bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(bg)
        painter.drawImage(bg.rect(), overlay, overlay.rect())
        painter.end()

        name = get_present_name(scene_info.file_id)
        if name:
            bg = print_text(bg, name, common.SCENE_MODES.presentname,
                            TEXT_FORMATS[common.SCENE_MODES.presentname],
                            False)

    elif scene_info.mode == common.SCENE_MODES.presentname:
        bg = QImage(os.path.join(MENU_DIR, "present-list.png"))
        overlay = get_present(scene_info.file_id, 248, 46)

        if not bg.format() is QImage.Format_ARGB32_Premultiplied:
            bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(bg)
        painter.drawImage(bg.rect(), overlay, overlay.rect())
        painter.end()

    elif scene_info.mode == common.SCENE_MODES.menu:
        bg = QImage(os.path.join(MENU_DIR, "menu.png"))

    elif scene_info.mode == common.SCENE_MODES.report or scene_info.mode == common.SCENE_MODES.report2:
        bg = QImage(os.path.join(MENU_DIR, "report.png"))

    elif scene_info.mode == common.SCENE_MODES.skill or scene_info.mode == common.SCENE_MODES.skill2:
        bg = QImage(os.path.join(MENU_DIR, "skills.png"))

    elif scene_info.mode == common.SCENE_MODES.map:
        bg = QImage(os.path.join(MENU_DIR, "map.png"))

    elif scene_info.mode == common.SCENE_MODES.music:
        bg = QImage(os.path.join(MENU_DIR, "soundtest.png"))

    elif scene_info.mode in [
            common.SCENE_MODES.eventname, common.SCENE_MODES.moviename,
            common.SCENE_MODES.artworkname
    ]:
        bg = QImage(os.path.join(MENU_DIR, "gallery.png"))

        if scene_info.mode == common.SCENE_MODES.eventname:
            overlay = get_event_icon(scene_info.file_id)
        elif scene_info.mode == common.SCENE_MODES.moviename:
            overlay = get_movie_icon(scene_info.file_id)
        elif scene_info.mode == common.SCENE_MODES.artworkname:
            overlay = get_artwork_icon(scene_info.file_id)

        if not bg.format() is QImage.Format_ARGB32_Premultiplied:
            bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(bg)
        painter.drawImage(bg.rect(), overlay, overlay.rect())
        painter.end()

    elif scene_info.mode == common.SCENE_MODES.theatre:
        bg = get_normal(scene_info)

    elif scene_info.mode == common.SCENE_MODES.debate or scene_info.mode == common.SCENE_MODES.hanron:
        bg = get_trial(scene_info, show_box=False)

    else:
        bg = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
        bg.fill(QColor(0, 0, 0, 255).rgba())

    if not bg.format() is QImage.Format_ARGB32_Premultiplied:
        bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied)

    if scene_info.cutin != -1:
        cutin = get_cutin(scene_info.cutin)

        painter = QPainter(bg)
        painter.drawImage(bg.rect(), cutin, cutin.rect())
        painter.end()

    if scene_info.ammo != -1:
        ammo = get_ammo_ingame(scene_info.ammo)

        painter = QPainter(bg)
        painter.drawImage(bg.rect(), ammo, ammo.rect())
        painter.end()

    if scene_info.present != -1:
        present = get_present_ingame(scene_info.present)

        painter = QPainter(bg)
        painter.drawImage(bg.rect(), present, present.rect())
        painter.end()

    if scene_info.special == common.SCENE_SPECIAL.option:
        overlay = QImage(os.path.join(TEXTBOX_DIR, "option_bar.png"))
        painter = QPainter(bg)
        painter.drawImage(bg.rect(), overlay, overlay.rect())
        painter.end()

        if not text == None and not text == "":
            bg = print_text(bg, text, common.SCENE_SPECIAL.option,
                            TEXT_FORMATS[common.SCENE_SPECIAL.option], False)

    if not text == None and not text == "":
        bg = print_text(bg, text, scene_info.mode,
                        TEXT_FORMATS[scene_info.mode])

    return bg
Ejemplo n.º 19
0
    def __init__(self, parent=None):
        super(ShellOutputScintilla, self).__init__(parent)
        self.parent = parent
        self.shell = self.parent.shell

        self.settings = QSettings()

        # Creates layout for message bar
        self.layout = QGridLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # messageBar instance
        self.infoBar = QgsMessageBar()
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # Enable non-ascii chars for editor
        self.setUtf8(True)

        sys.stdout = writeOut(self, sys.stdout)
        sys.stderr = writeOut(self, sys.stderr, "_traceback")

        self.insertInitText()
        self.refreshSettingsOutput()
        self.setReadOnly(True)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        # Margin 0 is used for line numbers
        self.setMarginWidth(0, 0)
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 0)
        #fm = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(1, "00000")
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor("#3E3EE3"))
        self.setMarginsBackgroundColor(QColor("#f9f9f9"))
        self.setCaretLineVisible(True)
        self.setCaretWidth(0)

        self.setMinimumHeight(120)

        self.setWrapMode(QsciScintilla.WrapCharacter)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self)
        self.runScut.setContext(Qt.WidgetShortcut)
        self.runScut.activated.connect(self.enteredSelected)
        # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view
        self.copyShortcut = QShortcut(QKeySequence.Copy, self)
        self.copyShortcut.activated.connect(self.copy)
        self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self)
        self.selectAllShortcut.activated.connect(self.selectAll)
def get_box(scene_info):

    mode = scene_info.mode
    box_color = scene_info.box_color
    box_type = scene_info.box_type
    speaking = scene_info.speaking
    speaker_id = scene_info.speaker
    headshot = scene_info.headshot
    chapter = scene_info.chapter

    if box_color != common.BOX_COLORS.yellow and box_color != common.BOX_COLORS.green and box_color != common.BOX_COLORS.blue:
        box_color = common.BOX_COLORS.yellow

    out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())

    painter = QPainter(out)
    painter.setRenderHint(QPainter.Antialiasing, True)

    # Some commonality between the boxes.
    box = QImage()
    button = QImage()

    nametag_x = 0
    nametag_y = 0
    nametag_color = QColor(255, 255, 255, 255)
    nametag_vert = False

    if box_type == common.BOX_TYPES.flat:
        box = QImage(os.path.join(TEXTBOX_DIR, "box_gray.png"))
        button = QImage(os.path.join(TEXTBOX_DIR, "button_%s.png" % box_color))

        nametag_x = 10
        nametag_y = 176
        nametag_color = QColor(255, 255, 255, 255)
        nametag_vert = False

    elif box_type == common.BOX_TYPES.novel:
        box = QImage(os.path.join(TEXTBOX_DIR, "box_novel.png"))

    elif box_type == common.BOX_TYPES.normal:

        if mode == common.SCENE_MODES.normal:

            box = QImage(os.path.join(TEXTBOX_DIR, "box.png"))
            button = QImage(
                os.path.join(TEXTBOX_DIR, "button_%s.png" % box_color))

            nametag_x = 0
            nametag_y = 220
            nametag_color = QColor(50, 50, 50, 255)
            nametag_vert = True

            if not box.format() is QImage.Format_ARGB32_Premultiplied:
                box = box.convertToFormat(QImage.Format_ARGB32_Premultiplied)

            box_painter = QPainter(box)
            box_painter.setRenderHint(QPainter.Antialiasing, True)

            if speaker_id == 0:  # Main character gets a special text box.
                namebox = QImage(
                    os.path.join(TEXTBOX_DIR, "name_%s_mc.png" % box_color))
            else:
                namebox = QImage(
                    os.path.join(TEXTBOX_DIR, "name_%s.png" % box_color))

            box_painter.drawImage(box.rect(), namebox, namebox.rect())

            box_painter.end()

        elif mode == common.SCENE_MODES.trial:

            box_base = QImage(os.path.join(TRIAL_DIR, "trial_box.png"))
            banner = QImage(os.path.join(TRIAL_DIR, "trial_banner.png"))

            if speaker_id == 0:  # Main character gets a special text box.
                namebox = QImage(os.path.join(TRIAL_DIR, "trial_name_mc.png"))
            else:
                namebox = QImage(os.path.join(TRIAL_DIR, "trial_name.png"))

            if not headshot == None:
                case_num = QImage(
                    os.path.join(TRIAL_DIR, "case_%02d.png" % chapter))
                headshot = QImage(
                    os.path.join(TRIAL_DIR, "headshot", "%02d.png" % headshot))
                underlay = QImage(os.path.join(TRIAL_DIR,
                                               "trial_headshot.png"))
            else:
                case_num = QImage()
                underlay = QImage()
                headshot = QImage()

            button = QImage(os.path.join(TRIAL_DIR, "button.png"))
            nametag_x = 12
            nametag_y = 168
            nametag_color = QColor(255, 255, 255, 255)
            nametag_vert = False

            box = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
            box.fill(QColor(0, 0, 0, 0).rgba())

            box_painter = QPainter(box)
            box_painter.setRenderHint(QPainter.Antialiasing, True)

            box_painter.drawImage(box.rect(), banner, banner.rect())
            box_painter.drawImage(box.rect(), namebox, namebox.rect())
            box_painter.drawImage(box.rect(), box_base, box_base.rect())
            box_painter.drawImage(box.rect(), underlay, underlay.rect())
            box_painter.drawImage(box.rect(), headshot, headshot.rect())
            box_painter.drawImage(box.rect(), case_num, case_num.rect())

            box_painter.end()

        else:
            box = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
            box.fill(QColor(0, 0, 0, 0).rgba())

    painter.drawImage(out.rect(), box, box.rect())
    painter.drawImage(out.rect(), button, button.rect())

    if not speaker_id == None:
        nametag = get_nametag(speaker_id, nametag_x, nametag_y, nametag_color,
                              nametag_vert)
        painter.drawImage(out.rect(), nametag, nametag.rect())

    painter.end()

    return out
Ejemplo n.º 21
0
# base, form = uic.loadUiType('test.ui')

# class WindowTest(base, form):

#     def __init__(self, parent=None):
#         super().__init__(parent)
#         self.setupUi(self)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setStyle('plastique')
    with open('test.ui', 'r') as stylesheet:
        app.setStyleSheet(stylesheet.read())

    red = QColor(255, 0, 0)
    green = QColor(0, 255, 0)
    blue = QColor(0, 0, 255)

    rowCount = 4
    columnCount = 6

    headers = ['Palette0', 'Colors', 'Brushes', 'Omg', 'Technical', 'Artist']
    table_data = [[QColor('#FFFF00') for i in range(columnCount)]
                  for j in range(rowCount)]

    # w = QWidget()
    # w.show()

    # listView = QListView()
    # model = PaletteListModel([red, green, blue])
Ejemplo n.º 22
0
def getRandColor():
    k = random.choice(matplotcolor.keys())
    if k in ignoreColor:
        return getRandColor()
    else:
        return QColor(matplotcolor[k])
Ejemplo n.º 23
0
    def init(self, volumina):
        self.editor = volumina

        self.hudsShown = [True] * 3

        def onViewFocused():
            axis = self.editor._lastImageViewFocus
            self.toggleSelectedHUD.setChecked(
                self.editor.imageViews[axis]._hud.isVisible())

        self.editor.newImageView2DFocus.connect(onViewFocused)

        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.setLayout(self.layout)

        # setup quadview
        axisLabels = ["X", "Y", "Z"]
        axisColors = [QColor("#dc143c"), QColor("green"), QColor("blue")]
        for i, v in enumerate(self.editor.imageViews):
            v.hud = ImageView2DHud(v)
            #connect interpreter
            v.hud.createImageView2DHud(axisLabels[i], 0, axisColors[i],
                                       QColor("white"))
            v.hud.sliceSelector.valueChanged.connect(
                partial(self.editor.navCtrl.changeSliceAbsolute, axis=i))

        self.quadview = QuadView(self, self.editor.imageViews[2],
                                 self.editor.imageViews[0],
                                 self.editor.imageViews[1], self.editor.view3d)
        self.quadview.installEventFilter(self)
        self.quadViewStatusBar = QuadStatusBar()
        self.quadViewStatusBar.createQuadViewStatusBar(QColor("#dc143c"),
                                                       QColor("white"),
                                                       QColor("green"),
                                                       QColor("white"),
                                                       QColor("blue"),
                                                       QColor("white"))
        self.quadview.addStatusBar(self.quadViewStatusBar)
        self.layout.addWidget(self.quadview)

        ## Why do we have to prevent TimerEvents reaching the SpinBoxes?
        #
        # Sometimes clicking a SpinBox once caused the value to increase by
        # two. This is why:
        #
        # When a MouseClicked event is received by the SpinBox it fires a timerevent to control
        # the repeated increase of the value as long as the mouse button is pressed. The timer
        # is killed when it receives a MouseRelease event. If a slot connected to the valueChanged
        # signal of the SpinBox takes to long to process the signal the mouse release
        # and timer events get queued up and sometimes the timer event reaches the widget before
        # the mouse release event. That's why it increases the value by another step. To prevent
        # this we are blocking the timer events at the cost of no autorepeat anymore.
        #
        # See also:
        # http://lists.trolltech.com/qt-interest/2002-04/thread00137-0.html
        # http://www.qtcentre.org/threads/43078-QSpinBox-Timer-Issue
        # http://qt.gitorious.org/qt/qt/blobs/4.8/src/gui/widgets/qabstractspinbox.cpp#line1195
        self.quadview.statusBar.timeSpinBox.installEventFilter(_timerEater)

        def setTime(t):
            if t == self.editor.posModel.time:
                return
            self.editor.posModel.time = t

        self.quadview.statusBar.timeSpinBox.valueChanged.connect(setTime)

        def getTime(newT):
            self.quadview.statusBar.timeSpinBox.setValue(newT)

        self.editor.posModel.timeChanged.connect(getTime)

        def toggleSliceIntersection(state):
            self.editor.navCtrl.indicateSliceIntersection = (
                state == Qt.Checked)

        self.quadview.statusBar.positionCheckBox.stateChanged.connect(
            toggleSliceIntersection)

        self.editor.posModel.cursorPositionChanged.connect(
            self._updateInfoLabels)

        def onShapeChanged():
            singletonDims = filter(
                lambda (i, dim): dim == 1,
                enumerate(self.editor.posModel.shape5D[1:4]))
            if len(singletonDims) == 1:
                # Maximize the slicing view for this axis
                axis = singletonDims[0][0]
                self.quadview.ensureMaximized(axis)
                self.hudsShown[axis] = self.editor.imageViews[axis].hudVisible(
                )
                self.editor.imageViews[axis].setHudVisible(False)
                self.quadViewStatusBar.showXYCoordinates()

                self.quadview.statusBar.positionCheckBox.setVisible(False)
            else:
                self.quadViewStatusBar.showXYZCoordinates()
                for i in range(3):
                    self.editor.imageViews[i].setHudVisible(self.hudsShown[i])
                self.quadview.statusBar.positionCheckBox.setVisible(True)

            self._setupVolumeExtent()

        self.editor.shapeChanged.connect(onShapeChanged)

        self.updateGeometry()
        self.update()
        self.quadview.update()

        if hasattr(self.editor.view3d, 'bUndock'):
            self.editor.view3d.bUndock.clicked.connect(
                partial(self.quadview.on_dock,
                        self.quadview.dock2_ofSplitHorizontal2))

        # shortcuts
        self._initShortcuts()
Ejemplo n.º 24
0
def getRandColor1():
    color = (np.random.randint(low=0, high=255, size=3)).tolist()
    if not all((x <= 65 or x >= 105) for x in (color[0], color[1], color[2])):
        return QColor(color[0], color[1], color[2])
    else:
        return getRandColor()
Ejemplo n.º 25
0
    def compute_colors(self, keep_colors=False):
        if not keep_colors:
            self.pen_colors = self.brush_colors = None
        color_index = self.get_color_index()

        def make_pen(color, width):
            p = QPen(color, width)
            p.setCosmetic(True)
            return p

        subset = None
        if self.subset_indices:
            subset = np.array([ex.id in self.subset_indices
                               for ex in self.raw_data[self.valid_data]])

        if color_index == -1:  # same color
            color = self.plot_widget.palette().color(OWPalette.Data)
            pen = [make_pen(color, 1.5)] * self.n_points
            if subset is not None:
                brush = [(QBrush(QColor(128, 128, 128, 0)),
                          QBrush(QColor(128, 128, 128, self.alpha_value)))[s]
                         for s in subset]
            else:
                brush = [QBrush(QColor(128, 128, 128, self.alpha_value))] \
                        * self.n_points
            return pen, brush

        c_data = self.original_data[color_index, self.valid_data]
        if self.data_domain[color_index].is_continuous:
            if self.pen_colors is None:
                self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))
                c_data -= self.scale.offset
                c_data /= self.scale.width
                c_data = np.floor(c_data) + 0.5
                c_data /= self.scale.bins
                c_data = np.clip(c_data, 0, 1)
                palette = self.continuous_palette
                self.pen_colors = palette.getRGB(c_data)
                self.brush_colors = np.hstack(
                    [self.pen_colors,
                     np.full((self.n_points, 1), self.alpha_value)])
                self.pen_colors *= 100 // self.DarkerValue
                self.pen_colors = [make_pen(QColor(*col), 1.5)
                                   for col in self.pen_colors.tolist()]
            if subset is not None:
                self.brush_colors[:, 3] = 0
                self.brush_colors[subset, 3] = self.alpha_value
            else:
                self.brush_colors[:, 3] = self.alpha_value
            pen = self.pen_colors
            brush = np.array([QBrush(QColor(*col))
                              for col in self.brush_colors.tolist()])
        else:
            if self.pen_colors is None:
                palette = self.discrete_palette
                n_colors = palette.number_of_colors
                c_data = c_data.copy()
                c_data[np.isnan(c_data)] = n_colors
                c_data = c_data.astype(int)
                colors = np.r_[palette.getRGB(np.arange(n_colors)),
                               [[128, 128, 128]]]
                pens = np.array(
                    [make_pen(QColor(*col).darker(self.DarkerValue), 1.5)
                     for col in colors])
                self.pen_colors = pens[c_data]
                self.brush_colors = np.array([
                    [QBrush(QColor(0, 0, 0, 0)),
                     QBrush(QColor(col[0], col[1], col[2], self.alpha_value))]
                    for col in colors])
                self.brush_colors = self.brush_colors[c_data]
            if subset is not None:
                brush = np.where(
                    subset,
                    self.brush_colors[:, 1], self.brush_colors[:, 0])
            else:
                brush = self.brush_colors[:, 1]
            pen = self.pen_colors
        return pen, brush
Ejemplo n.º 26
0
 def set_default_project(self, item):
     item.setForeground(0, QBrush(QColor(0, 204, 82)))
     if self._actualProject:
         item.setForeground(0, QBrush(QColor(255, 165, 0)))
     self._actualProject = item
Ejemplo n.º 27
0
class QSignalDetectorWidget(QSignalVisualizerWidget):
    """
    This widget performs the detections operations on a signal.
    Provide methods to interact with the detected segments: Highlight it, remove it, etc
    """

    # region SIGNALS

    # signal raised when a detected element is clicked
    # raise the index of the clicked element
    elementClicked = QtCore.pyqtSignal(int)

    # endregion

    # region CONSTANTS

    # the pen for no visible items groups draw
    NO_VISIBLE_ELEMENTS_PEN = pg.mkPen(QColor(255, 0, 0, 255), width=3)

    visual_items_cache = None

    # the brush that is used to draw the selected region or Element
    SELECTED_ELEMENT_BRUSH = pg.mkBrush(QtGui.QColor(255, 0, 0, 220))

    # the min size in pixels that must have an element to be visualized
    MIN_ELEMENT_WIDTH_PIXELS = 3

    # endregion

    def __init__(self, parent):
        # items to highlight elements or regions in the graph
        self.oscSelectionRegion = pg.LinearRegionItem(
            [0, 0], movable=False, brush=self.SELECTED_ELEMENT_BRUSH)

        if QSignalDetectorWidget.visual_items_cache is None:
            QSignalDetectorWidget.visual_items_cache = VisualItemsCache()

        # the visual items for segmentation
        self.segmentation_visual_items = []

        # the list of visual parameter items of every element.
        # Are stored separated because the elements are loaded lazy and
        # maybe the parameter for an element is supplied when its instance are not yet computed
        self.parameters_items = []

        # the items for no visible elements list of tuples (item, visibility)
        self.no_visible_items = []

        # list of detected sound lab elements.
        self._elements = []

        # the visual items types visibility
        self.visual_items_visibility = VisualItemsVisibility()

        QSignalVisualizerWidget.__init__(self, parent)

    # region Elements Property

    @property
    def sorted_elements_start_indexes(self):
        """
        :return: the list of sorted start indexes of elements as list of ints
        """

        # Each object in self.elements could be a tuple (start, end) of signal data indexes
        # or a DetectedSoundLabElement instance (if that elements is been visualized on the widget)

        return [
            x.indexFrom if isinstance(x, DetectedSoundLabElement) else x[0]
            for x in self.elements
        ]

    @property
    def elements(self):
        return self._elements

    @elements.setter
    def elements(self, elements_list):
        # release the resources of visual items to be available for future use
        self.release_items()
        self.deselect_element()

        # just keep a list opf tuples start, end for lightweight
        self._elements = [(e.indexFrom, e.indexTo) for e in elements_list]
        self.parameters_items = [[] for _ in self._elements]

    def get_element(self, index):
        """
        Return a detected element as DetectedSoundLab instance.
        The objects on list of detected elements could be tuples or detected elements
        this method is a wrapper to get the detected sound lab instance by lazy load.
        :param index: the index of the element to get
        :return:
        """
        if not 0 <= index < len(self.elements):
            raise IndexError()

        # if the element is not a DetectedSoundLab instance then create it
        if not isinstance(self.elements[index], DetectedSoundLabElement):
            start_index, end_index = self.elements[index][0], self.elements[
                index][1]
            self.elements[index] = self.get_visual_item(
                self.signal, start_index, end_index, index + 1,
                self.elementClicked)

            # add parameter items if any
            for param in self.parameters_items[index]:
                self.elements[index].add_visual_item(param)

        return self.elements[index]

    def get_visual_item(self,
                        signal,
                        index_from,
                        index_to,
                        number=0,
                        signal_callback=None):
        """
        Wrapper method to simplify expressions.
        Obtains a new visual item from the cache.
        """
        return QSignalDetectorWidget.visual_items_cache.get_visual_item(
            signal, index_from, index_to, number, signal_callback)

    # endregion

    # region Elements Visibility

    def _is_element_visible(self, element):
        """
        Computes the visibility of the element supplied. An element is visible if
        is inside the visible interval on the widget graph and its size in pixels
        is greater than the min size in pixels approved.
        :param element: the element to compute visibility rule
        :return: True if the supplied detected object (tuple or DetectedSoundLab)
        satisfy the visibility requirements False otherwise.
        """
        # current visible area interval
        start, end = self.mainCursor.min, self.mainCursor.max

        # get the element interval
        index_from, index_to = (element.indexFrom, element.indexTo) if isinstance(element, DetectedSoundLabElement) \
            else (element[0], element[1])

        # if the elem is in the visible range of the widget graph
        interval_visible = (start <= index_from <= end) or (start <= index_to
                                                            <= end)

        # if the elem size in pixels is greater than minimum required
        widget_scene_width, widget_pixel_width = self.axesOscilogram.viewRect(
        ).width(), self.axesOscilogram.width() * 1.0
        pixel_visible = (
            index_to - index_from
        ) * widget_pixel_width / widget_scene_width > self.MIN_ELEMENT_WIDTH_PIXELS

        return interval_visible and pixel_visible

    def get_visible_elements(self):
        """
        :return: The visible elements that match the visibility rules (pixel size and interval)
        """
        # get the visible elements
        return [
            self.get_element(i) for i in xrange(len(self.elements))
            if self._is_element_visible(self.elements[i])
        ]

    # endregion

    # region Elements Draw and Visual Items

    def get_sound_lab_elements(self, elements):
        """
        Extracts the instances of sound lab elements that are on the list.
        Make a filter on the list just selecting the instances of DetectedSoundLabElement
        :param elements: List to search the elements in
        :return:
        """
        return [e for e in elements if isinstance(e, DetectedSoundLabElement)]

    def _update_elements_numbers(self):
        """
        Updates the numbers for all the elements on the detected elements list
        :return:
        """
        for i in xrange(len(self.elements)):
            if isinstance(self.elements[i], DetectedSoundLabElement):
                self.elements[i].setNumber(i + 1)

    def _get_no_visible_visual_items_tuples(self, elements):
        """
        Computes the start, end of the no visible elements group representation
        to visualize
        :param elements: The current visible elements
        :return: List of tuples (start, end) in indexes of detected elements with the positions of the
        elements indexes that are not visible Ej [(0,5),(9,11)]
        means that elements from 0 to 5  and from 9 to 11 are invisible
        """
        # if no detected elements
        if len(self.elements) == 0:
            return []

        elems = self.sorted_elements_start_indexes
        elems = [
            i for i in xrange(len(elems))
            if self.mainCursor.min <= elems[i] <= self.mainCursor.max
        ]
        if len(elems) == 0:
            return []

        first_visible_elem_index = elems[0]
        last_visible_elem_index = elems[len(elems) - 1]

        # if no visible elements
        if len(elements) == 0:
            return [(first_visible_elem_index + 1, last_visible_elem_index - 1)
                    ]

        visible_elements_indexes = [e.number - 1 for e in elements]

        no_visible_elements_items_tuples = [
            (visible_elements_indexes[i - 1] + 1,
             visible_elements_indexes[i] - 1)
            for i in xrange(1, len(elements)) if visible_elements_indexes[i] -
            visible_elements_indexes[i - 1] > 1
        ]

        # include the interval of start if the first element is no visible
        if visible_elements_indexes[0] > first_visible_elem_index:
            no_visible_elements_items_tuples.append(
                (first_visible_elem_index + 1, visible_elements_indexes[0]))

        # include the interval of end if the last element is no visible
        if visible_elements_indexes[len(visible_elements_indexes) -
                                    1] < last_visible_elem_index:
            no_visible_elements_items_tuples.append(
                (visible_elements_indexes[-1] + 1,
                 last_visible_elem_index - 1))

        return no_visible_elements_items_tuples

    def get_no_visible_visual_item(self, start, end):
        """
        Computes and returns the visual items to represents the groups of no visible elements
        :param start: index of the start elements on invisible region
        :param end: index of the end elements on invisible region
        :return: tuple of (list, list) with the visual elements for the group
        of no visible elements in the range [start, end] for oscilogram
        and spectrogram widgets respectively
        """
        osc_items, spec_items = [], []

        # viewRange of plotWidget [[xmin, xmax], [ymin, ymax]]
        x_max = self.axesOscilogram.viewRange()[0][1]

        start_position = self.get_element(start).indexTo if start > 0 else 0
        end_position = self.get_element(
            end).indexFrom if end < len(self.elements) - 1 else x_max

        max_value = self.signal.maximumValue

        widget_scene_width, widget_pixel_width = self.axesOscilogram.viewRect(
        ).width(), self.axesOscilogram.width() * 1.0

        # pixel_visible_text
        if (end_position -
                start_position) * widget_pixel_width / widget_scene_width > 30:
            text = u"(" + unicode(start + 1) + u"..." + unicode(end + 1) + u")" \
                if end > start else u"(" + unicode(start + 1) + u")"
            text_item = pg.TextItem(text,
                                    color=(255, 255, 255),
                                    anchor=(0.5, 0.5))
            text_item.setPos(start_position / 2.0 + end_position / 2.0,
                             0.75 * max_value)
            osc_items.append(text_item)

        graph_item = pg.GraphItem()

        # Define positions of nodes
        graph_pos = np.array([[start_position, max_value * 0.8],
                              [start_position, max_value * 0.85],
                              [end_position, max_value * 0.85],
                              [end_position, max_value * 0.8]])

        graph_adj = np.array([[0, 1], [1, 2], [2, 3]])
        options = dict(size=1,
                       symbol='d',
                       pxMode=False,
                       pen=self.NO_VISIBLE_ELEMENTS_PEN)
        graph_item.setData(pos=graph_pos, adj=graph_adj, **options)
        osc_items.append(graph_item)

        return osc_items, spec_items

    def draw_elements(self,
                      draw_oscilogram=True,
                      draw_specgram=True,
                      elements=None):
        """
        Add to the visual gui widgets the visible elements of the detected segments
        :type elements: the elements to be draw. If no specified all the visible elements would be updated
        :param oscilogramItems: true if draw elements in oscilogram false for spectrogram
        None for both
        """
        elements = elements if elements is not None else self.get_visible_elements(
        )

        self.remove_visual_elements(oscilogram=draw_oscilogram,
                                    specgram=draw_specgram,
                                    elements=elements)

        self.no_visible_items = [
            item for start, end in self._get_no_visible_visual_items_tuples(
                elements)
            for item in self.get_no_visible_visual_item(start, end)[0]
        ]

        self.add_visual_elements(elements, draw_oscilogram, draw_specgram)

        # translate the coord of the visible added items
        for e in self.get_sound_lab_elements(self.elements):
            e.spectral_element.translate_time_freq_coords(
                self.from_osc_to_spec, self.get_freq_index)

    def release_items(self,
                      index_from=None,
                      index_to=None,
                      parameter_items=True,
                      elements_items=True):
        """
        Release the visual items of the elements list
        between the indexes supplied
        :param indexFrom: inclusive lower bound
        :param indexTo: inclusive upper bound
        :return:
        """

        # the elements of the list could be a tuple or a DetectedSoundLab
        index_from = index_from if index_from is not None else 0
        index_to = index_to if index_to is not None else len(
            self._elements) - 1

        self.remove_visual_elements(elements=self.get_sound_lab_elements(
            self.elements[index_from:index_to + 1]))

        # release items
        for i in xrange(index_from, index_to + 1):
            if not isinstance(self.elements[i], DetectedSoundLabElement):
                continue

            if parameter_items:
                # remove parameter visual items of the released element
                self.elements[i].release_parameter_items()
                self.parameters_items[i] = []

            if elements_items:
                QSignalDetectorWidget.visual_items_cache.release_visual_item(
                    self.elements[i])
                self.elements[i] = (self.elements[i].indexFrom,
                                    self.elements[i].indexTo)

    def remove_visual_elements(self,
                               oscilogram=True,
                               specgram=True,
                               elements=None):
        """
        Method that remove the visual representation of the elements in the widget.
        Used for remove selected elements or a group of them.
        :param oscilogram: Removes the oscilogram visual elements
        :param specgram: Removes the spectrogram visual elements
        :param elements: the elements that would be (visually) removed.
        all the self.elements if None
        """
        # get the elements to remove
        elements = self.get_sound_lab_elements(
            self.elements) if elements is None else elements

        # get the osc and spec visual items of the elements to remove them
        osc_items = [
            item for elem in elements
            for item in elem.time_element.visual_widgets()
            if item in self.axesOscilogram.items()
        ] if oscilogram else []

        osc_items.extend(self.no_visible_items)

        spec_items = [
            item for elem in elements
            for item in elem.spectral_element.visual_widgets()
            if item in self.axesSpecgram.viewBox.allChildren()
        ] if specgram else []

        for item in osc_items:
            self.axesOscilogram.removeItem(item)

        for item in spec_items:
            self.axesSpecgram.viewBox.removeItem(item)

    def add_visual_elements(self, elements, osc, spec):
        """
        Adds the elements visual representation into the widgets.
        :param elements: the list of elements to draw
        :param osc: True if oscilogram elements must be updated False otherwise
        :param spec: True if spectrogram elements must be updated False otherwise
        :return:
        """

        osc_items = self.segmentation_visual_items + self.no_visible_items

        # add oscilogram items if visible
        if osc and self.visual_items_visibility.oscilogram_items_visible:

            if self.visual_items_visibility.oscilogram_text_visible:
                osc_items.extend(
                    [x for e in elements for x in e.time_element.visual_text])

            if self.visual_items_visibility.oscilogram_figures_visible:
                osc_items.extend([
                    x for e in elements for x in e.time_element.visual_figures
                ])

            if self.visual_items_visibility.oscilogram_parameters_visible:
                osc_items.extend([
                    x.get_item() for e in elements
                    for x in e.time_element.visual_parameters_items
                    if x.get_item()
                ])

        spec_items = []

        # add spectrogram items if visible
        if spec and self.visual_items_visibility.spectrogram_items_visible:

            if self.visual_items_visibility.spectrogram_text_visible:
                spec_items.extend([
                    x for e in elements for x in e.spectral_element.visual_text
                ])

            if self.visual_items_visibility.spectrogram_figures_visible:
                spec_items.extend([
                    x for e in elements
                    for x in e.spectral_element.visual_figures
                ])

            if self.visual_items_visibility.spectrogram_parameters_visible:
                spec_items.extend([
                    x.get_item() for e in elements
                    for x in e.spectral_element.visual_parameters_items
                    if x.get_item()
                ])

        osc_items, spec_items = set(osc_items), set(spec_items)

        osc_items_to_add = osc_items.difference(
            set(self.axesOscilogram.items()))

        spec_items_to_add = spec_items.difference(
            set(self.axesSpecgram.viewBox.allChildren()))

        for item in osc_items_to_add:
            self.axesOscilogram.addItem(item)

        for item in spec_items_to_add:
            self.axesSpecgram.viewBox.addItem(item)

    def add_parameter_visual_items(self, element_index, parameter_items):
        """
        Add a new visual item of a parameter measurement.
        :param element_index: the index of the segment measured
        :param parameter_items: the list of parameter items to visualize
        :return:
        """
        if not 0 <= element_index < len(self.elements):
            return
        print(element_index, " param items added ", len(parameter_items),
              parameter_items)
        self.parameters_items[element_index].extend(parameter_items)

        # if the element at index is visible as detected sound la elements add the items
        if isinstance(self.elements[element_index], DetectedSoundLabElement):
            for item in parameter_items:
                self._elements[element_index].add_visual_item(item)

    def add_segmentation_items(self, items):
        """
        Add a group of visual items that illustrates
        the segmentation process and settings
        :param items: the visual items of segmentation
        :return:
        """
        # visualize the segmentation items !!JUST ON OSCILOGRAM BY NOW!!
        for item in self.segmentation_visual_items:
            self.axesOscilogram.removeItem(item)

        self.segmentation_visual_items = items

        for item in self.segmentation_visual_items:
            self.axesOscilogram.addItem(item)

        self.axesOscilogram.update()

    # endregion

    # region Elements Selection-Deselection

    def select_element(self, index=-1):
        """
        Method that select an element in the widget
        by highlighting it. If index is in the xrange of [0, number_of_elements] then the
        the element at index "index" would be selected.
        Otherwise the selection would be cleared.
        :type update_graph: True if the widget graph would be updated False otherwise
        :param index: the element index
        """
        if index < 0 or index >= len(self.elements):
            self.oscSelectionRegion.setRegion((0, 0))
            self.axesOscilogram.update()
            return

        index_from, index_to = self.get_element(
            index).indexFrom, self.get_element(index).indexTo
        self.oscSelectionRegion.setRegion((index_from, index_to))
        self.axesOscilogram.update()

        # update the interval of visualization if the element is outside the current visible region
        if index_from < self.mainCursor.min or index_to > self.mainCursor.max:
            interval_size = self.mainCursor.max - self.mainCursor.min

            # move the interval to make completely visible the element selected
            self.mainCursor.min = max(0, index_from - interval_size / 2)
            self.mainCursor.max = min(self.signal.length,
                                      index_to + interval_size / 2)

            self.graph()

    def deselect_element(self):
        """
        Deselect (if any) the selected element on the widget
        :return:
        """
        self.select_element()

    def selected_element_signal(self):
        """
        :return: The (Audio) signal slice of the selected element region
        """
        start, end = self.oscSelectionRegion.getRegion()
        if end <= start:
            return None

        return self.signal.copy(start, end)

    def selected_elements_interval(self):
        """
        :return: tuple of int (start, end) with the indexes of start and end
        selected elements or None if no selection is made.
        """
        # check if there is a selected element
        selected_rgn_start, selected_rgn_end = self.oscSelectionRegion.getRegion(
        )

        # if no selected element
        if selected_rgn_end <= selected_rgn_start:
            start, end = self.selectedRegion
        else:
            start, end = selected_rgn_start, selected_rgn_end

        # if no area is selected
        if end == start or len(
                self.elements) == 0 or (start == self.mainCursor.min
                                        and end == self.mainCursor.max):
            return None

        # create a list with start index of each element
        sorted_arr = np.array(self.sorted_elements_start_indexes)

        # binary search of the interval
        index_from, index_to = np.searchsorted(sorted_arr,
                                               start), np.searchsorted(
                                                   sorted_arr, end)

        # if the region selected starts before the previous element finish then include it
        index_from -= 1 if index_from > 0 and start <= self.get_element(
            index_from - 1).indexTo else 0

        if index_to < index_from or index_to > len(self.elements):
            return None

        return index_from, index_to - 1

    # endregion

    # region Elements Add-Delete-Save

    def delete_selected_elements(self):
        """
        Delete selected element if any. If no element is selected then deletes the
        elements between the zoom selection if any. If no zoom selection is made
        then delete the elements on the visible interval
        """

        selection = self.selected_elements_interval()

        if selection is None:
            return

        # remove the selected region Element if is contained on the removed elements region
        selected_rgn_start, selected_rgn_end = self.oscSelectionRegion.getRegion(
        )

        start, end = self.selectedRegion
        if start <= selected_rgn_start <= end or start <= selected_rgn_end <= end:
            self.deselect_element()

        index_from, index_to = selection
        self.release_items(index_from, index_to)

        # do not call the property to avoid recompute the unnecessary visualization release items
        self._elements = self.elements[0:index_from] + self.elements[index_to +
                                                                     1:]

        # release the items
        self.parameters_items = self.parameters_items[
            0:index_from] + self.parameters_items[index_to + 1:]
        self._update_elements_numbers()
        self.draw_elements()

    def mark_region_as_element(self, interval=None):
        """
        Try to add a new element manually using the interval supplied
        if None is supplied use the current selected region as delimiters from start and end in time
        domain.
        :type update: variable used for efficiency when add multiple elements
        :return: index of the new element inserted if success None otherwise.
        Could fail because there is no selected region or the region
        overlaps with others elements
        """
        start, end = self.selectedRegion if interval is None else interval
        # if no selected region return
        if end <= start or (self.mainCursor.min == start
                            and self.mainCursor.max == end):
            return None

        # get the index of insertion on the sorted array of elements
        sorted_arr = np.array(self.sorted_elements_start_indexes)
        index_from, index_to = np.searchsorted(sorted_arr,
                                               start), np.searchsorted(
                                                   sorted_arr, end)
        index_from -= 1 if index_from > 0 and start <= self.get_element(
            index_from - 1).indexTo else 0

        # insert the new element
        element = self.get_visual_item(self.signal, start, end, 0,
                                       self.elementClicked)
        self.elements.insert(index_from, element)
        self.parameters_items.insert(index_from, [])

        # update the widget
        self._update_elements_numbers()
        self.draw_elements()

        return index_from

    def save_segments_into_signal(self):
        """
        Store the list of (start, end) indexes of detected elements into the
        signal extra data.
        :return:
        """
        self.signal.extraData = [
            (x.indexFrom,
             x.indexTo) if isinstance(x, DetectedSoundLabElement) else x
            for x in self.elements
        ]

    # endregion

    # region Widgets synchronization

    def updateOscillogram(self, x1, x2):
        """
        Method invoked when the oscilogram xrange change
        :param x1: start index of the interval changed
        :param x2: end index of the interval changed
        :return:
        """
        QSignalVisualizerWidget.updateOscillogram(self, x1, x2)
        self.graph_elements()

    def updateSpecgram(self, x1, x2):
        """
        Method invoked when the spectrogram xrange change
        :param x1: start index of the interval changed
        :param x2: end index of the interval changed
        :return:
        """
        QSignalVisualizerWidget.updateSpecgram(self, x1, x2)
        self.graph_elements()

    def update_widget_range(self, widget, x1, x2):
        QSignalVisualizerWidget.update_widget_range(self, widget, x1, x2)
        self.graph_elements()

    # endregion

    def get_signal_segmentation_data(self):
        """
        return the list of segments previously stored on the signal.
        :return: list of tuples (start, end) of every segment in signal data indexes
        """
        if not self.signal.extraData:
            return []

        data = self.signal.extraData

        # try to add the detected elements from the extra data (list of tuples (start,end) )
        if not isinstance(data, list):
            return []

        return [
            e for e in data if isinstance(e, tuple) and len(e) == 2
            and isinstance(e[0], int) and isinstance(e[1], int)
        ]

    def get_visible_region(self):
        """
        :return: The region that is visible in signal oscilogram coordinates
        """
        return self.mainCursor.min, self.mainCursor.max

    def graph(self):
        """
        Refresh the widgets visual elements and graphs
        :return:
        """
        QSignalVisualizerWidget.graph(self)
        self.graph_elements()

    def graph_elements(self):
        """
        Execute the logic of update the visual representation of the detected elements
        :return:
        """
        # add the region items because the parent method clears the widget
        if self.oscSelectionRegion not in self.axesOscilogram.items():
            self.axesOscilogram.addItem(self.oscSelectionRegion)

        self.draw_elements()
Ejemplo n.º 28
0
def default_palette():
    """
    Create and return a default palette for a node.
    """
    return create_palette(QColor(NAMED_COLORS["light-yellow"]),
                          QColor(NAMED_COLORS["yellow"]))
Ejemplo n.º 29
0
    def notifyReceived(self, data, fromLocal=False):
        """
        Dispatch events

        @param data:
        @type data: dict
        """
        if 'task-uuid' in data:
            self.taskUuid = data['task-uuid']

        # normalize test id to str
        if 'script_id' in data:
            data['script_id'] = "%s" % data['script_id']
        if 'tc_id' in data:
            data['tc_id'] = "%s" % data['tc_id']
        if 'test-internal-id' in data:
            data['test-internal-id'] = "%s" % data['test-internal-id']

        ############# Global events
        if data['event'] == 'script-started':
            self.parent.showMessageTray(msg='Test %s starting...' % self.name)
            self.isRunning = True
            #self.logsItem.activeReplay()
            self.parent.updateTabColor(self, color=QColor(Qt.darkCyan))

        elif data['event'] == 'script-stopped':
            self.isRunning = False
            self.logsItem.deactiveKill()
            self.parent.updateTabColor(self, color=QColor(Qt.blue))

            self.addGlobalTime(duration=float(data['duration']))

            self.parent.showMessageTray(msg='Test %s terminated.' % self.name)
            # show the app
            if QtHelper.str2bool(Settings.instance().readValue(
                    key='TestRun/show-test-terminated')):
                self.parent.setVisible(True)

        ############# test global events
        elif data['event'] == 'testglobal-started':
            self.isTp = True
            self.logsItem.activeKill()

            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.resumeView.reset()
                self.logsView.reset()
            self.tpTreeItem = self.logsItem.createRootItem(
                event=data, typeItem='testglobal')
            self.script[data['script_id']] = self.tpTreeItem
        elif data['event'] == 'testglobal-stopped':
            self.logsItem.deactiveKill()
            if self.isTp:
                self.logsItem.activeReplay()
            if not data['script_id'] in self.script:
                return  # error
            rootTreeItem = self.script[data['script_id']]
            # new in 3.0.0
            duration = None
            if 'duration' in data:
                duration = "%.3f" % float(data['duration'])
            self.logsItem.finishRootItem(rootItem=rootTreeItem,
                                         duration=duration,
                                         typeItem='testglobal',
                                         event=data)
        elif data['event'] == 'testglobal':
            if not data['script_id'] in self.scriptEvents:
                self.scriptEvents[data['script_id']] = [data]
            else:
                self.scriptEvents[data['script_id']].append(data)
            if not data['script_id'] in self.script:
                return

            itemsSelected = self.logsItem.logs.selectedItems()
            rootTreeItem = self.script[data['script_id']]
            if len(itemsSelected) > 1:
                rootTreeItem.setSelected(False)
            if rootTreeItem.isSelected():
                self.logsView.setExpectedEventId(data['script_id'])
                row_pos = self.logsView.addEvent(event=data)
                self.resumeView.addEvent(event=data,
                                         rowp=row_pos,
                                         ihmId=row_pos)

        ############# test plan events
        elif data['event'] == 'testplan-separator-terminated':
            duration = "%.3f" % float(data['duration'])

            itemSeparator = self.separators[data['test-internal-id']]
            self.logsItem.finishTestplanSeparator(itemSep=itemSeparator,
                                                  duration=duration)

        elif data['event'] == 'testplan-separator':
            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.logsView.reset()
            itemSeparator = self.logsItem.createTestplanSeparator(event=data)
            self.separators[data['test-internal-id']] = itemSeparator

        elif data['event'] == 'testplan-started':
            self.isTp = True
            self.logsItem.activeKill()

            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.resumeView.reset()
                self.logsView.reset()
            self.tpTreeItem = self.logsItem.createRootItem(event=data,
                                                           typeItem='testplan')
            self.script[data['script_id']] = self.tpTreeItem
        elif data['event'] == 'testplan-stopped':
            self.logsItem.deactiveKill()
            if self.isTp:
                self.logsItem.activeReplay()
            if not data['script_id'] in self.script:
                return  # error
            rootTreeItem = self.script[data['script_id']]
            # new in 3.0.0
            duration = None
            if 'duration' in data:
                duration = "%.3f" % float(data['duration'])
            self.logsItem.finishRootItem(rootItem=rootTreeItem,
                                         duration=duration,
                                         typeItem='testplan',
                                         event=data)
        elif data['event'] == 'testplan':
            if not data['script_id'] in self.scriptEvents:
                self.scriptEvents[data['script_id']] = [data]
            else:
                self.scriptEvents[data['script_id']].append(data)
            if not data['script_id'] in self.script:
                return

            itemsSelected = self.logsItem.logs.selectedItems()
            rootTreeItem = self.script[data['script_id']]
            if len(itemsSelected) > 1:
                rootTreeItem.setSelected(False)
            if rootTreeItem.isSelected():
                self.logsView.setExpectedEventId(data['script_id'])
                row_pos = self.logsView.addEvent(event=data)
                self.resumeView.addEvent(event=data,
                                         rowp=row_pos,
                                         ihmId=row_pos)

        ############# test abstract events
        elif data['event'] == 'testabstract-started':
            self.logsItem.activeKill()
            if self.tpTreeItem is not None:
                self.tpTreeItem.setSelected(False)

            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.resumeView.reset()
                self.logsView.reset()
            rootTreeItem = self.logsItem.createRootItem(
                event=data, typeItem='testabstract')
            self.script[data['script_id']] = rootTreeItem
        elif data['event'] == 'testabstract-stopped':
            if not self.isTp:
                self.logsItem.activeReplay()
            if not data['script_id'] in self.script:
                return  # error
            rootTreeItem = self.script[data['script_id']]
            # new in 3.0.0
            duration = None
            if 'duration' in data:
                duration = "%.3f" % float(data['duration'])
            self.logsItem.finishRootItem(rootItem=rootTreeItem,
                                         duration=duration,
                                         typeItem='testabstract',
                                         event=data)
        elif data['event'] == 'testabstract':
            if not data['script_id'] in self.scriptEvents:
                self.scriptEvents[data['script_id']] = [data]
            else:
                self.scriptEvents[data['script_id']].append(data)
            if not data['script_id'] in self.script:
                return
            rootTreeItem = self.script[data['script_id']]
            if rootTreeItem.isSelected():
                self.logsView.setExpectedEventId(data['script_id'])
                row_pos = self.logsView.addEvent(event=data)
                self.resumeView.addEvent(event=data,
                                         rowp=row_pos,
                                         ihmId=row_pos)

        ############# test unit events
        elif data['event'] == 'testunit-started':
            self.logsItem.activeKill()
            if self.tpTreeItem is not None:
                self.tpTreeItem.setSelected(False)

            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.resumeView.reset()
                self.logsView.reset()
            rootTreeItem = self.logsItem.createRootItem(event=data,
                                                        typeItem='testunit')
            self.script[data['script_id']] = rootTreeItem
        elif data['event'] == 'testunit-stopped':
            if not self.isTp:
                self.logsItem.activeReplay()
            if not data['script_id'] in self.script:
                return  # error
            rootTreeItem = self.script[data['script_id']]
            # new in 3.0.0
            duration = None
            if 'duration' in data:
                duration = "%.3f" % float(data['duration'])
            self.logsItem.finishRootItem(rootItem=rootTreeItem,
                                         duration=duration,
                                         typeItem='testunit',
                                         event=data)
        elif data['event'] == 'testunit':
            if not data['script_id'] in self.scriptEvents:
                self.scriptEvents[data['script_id']] = [data]
            else:
                self.scriptEvents[data['script_id']].append(data)
            if not data['script_id'] in self.script:
                return

            itemsSelected = self.logsItem.logs.selectedItems()
            rootTreeItem = self.script[data['script_id']]
            if len(itemsSelected) > 1:
                rootTreeItem.setSelected(False)
            if rootTreeItem.isSelected():
                self.logsView.setExpectedEventId(data['script_id'])
                row_pos = self.logsView.addEvent(event=data)
                self.resumeView.addEvent(event=data,
                                         rowp=row_pos,
                                         ihmId=row_pos)

        ############# test suite events
        elif data['event'] == 'testsuite-started':
            self.logsItem.activeKill()
            if self.tpTreeItem is not None:
                self.tpTreeItem.setSelected(False)

            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.resumeView.reset()
                self.logsView.reset()
            rootTreeItem = self.logsItem.createRootItem(event=data)
            self.script[data['script_id']] = rootTreeItem
        elif data['event'] == 'testsuite-stopped':
            if not self.isTp:
                self.logsItem.activeReplay()
            if not data['script_id'] in self.script:
                return  # error
            rootTreeItem = self.script[data['script_id']]
            # new in 3.0.0
            duration = None
            if 'duration' in data:
                duration = "%.3f" % float(data['duration'])
            self.logsItem.finishRootItem(rootItem=rootTreeItem,
                                         duration=duration,
                                         event=data)
        elif data['event'] == 'testsuite':
            if not data['script_id'] in self.scriptEvents:
                self.scriptEvents[data['script_id']] = [data]
            else:
                self.scriptEvents[data['script_id']].append(data)
            if not data['script_id'] in self.script:
                return

            itemsSelected = self.logsItem.logs.selectedItems()
            rootTreeItem = self.script[data['script_id']]
            if len(itemsSelected) > 1:
                rootTreeItem.setSelected(False)
            if rootTreeItem.isSelected():
                self.logsView.setExpectedEventId(data['script_id'])
                row_pos = self.logsView.addEvent(event=data)
                self.resumeView.addEvent(event=data,
                                         rowp=row_pos,
                                         ihmId=row_pos)

        ############# test case events
        elif data['event'] == 'testcase-started':
            if not data['script_id'] in self.script:
                return  # error
            #
            rootTreeItem = self.script[data['script_id']]
            rootTreeItem.setSelected(False)

            itemsSelected = self.logsItem.logs.selectedItems()
            if not len(itemsSelected):
                self.graphView.reset()
                self.resumeView.reset()
                self.logsView.reset()

            testcaseTreeItem = self.logsItem.createTestcase(
                rootItem=rootTreeItem, event=data, fromLocal=fromLocal)
            self.testcases[data['tc_id']] = testcaseTreeItem
        elif data['event'] == 'testcase-stopped':
            if not data['tc_id'] in self.testcases:
                return  # error
            #
            testcaseItem = self.testcases[data['tc_id']]
            testcaseItem.setSelected(False)
            # new in 3.0.0
            duration = None
            if 'duration' in data:
                duration = "%.3f" % float(data['duration'])
            self.logsItem.finishTestcase(testcaseItem=testcaseItem,
                                         result=data['result'],
                                         duration=duration,
                                         event=data)
        elif data['event'] == 'testcase':
            # Issue 41: incorrect event displayed in test result
            # ignore invalid events
            if not data['script_id'] in self.script:
                return  # error
            #
            if not data['tc_id'] in self.scriptEvents:
                self.scriptEvents[data['tc_id']] = [data]
            else:
                self.scriptEvents[data['tc_id']].append(data)
            if not data['tc_id'] in self.testcases:
                return
            itemsSelected = self.logsItem.logs.selectedItems()
            testcaseItem = self.testcases[data['tc_id']]

            if len(itemsSelected) > 1:
                testcaseItem.setSelected(False)
            if testcaseItem.isSelected():
                self.logsView.setExpectedEventId(data['tc_id'])
                row_pos = self.logsView.addEvent(event=data)
                self.resumeView.addEvent(event=data,
                                         rowp=row_pos,
                                         ihmId=row_pos)
    def paintEvent(self, event):
        font = QFont(self.font())
        font.setPointSize(font.pointSize() - 1)
        fm = QFontMetricsF(font)

        fractWidth = fm.width(FractionSlider.WSTRING)
        indent = fm.boundingRect("9").width() / 2.0

        if not X11:
            fractWidth *= 1.5

        span = self.width() - (FractionSlider.XMARGIN * 2)
        value = self.__numerator / float(self.__denominator)

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.TextAntialiasing)
        painter.setPen(self.palette().color(QPalette.Mid))
        painter.setBrush(self.palette().brush(QPalette.AlternateBase))
        painter.drawRect(self.rect())

        segColor = QColor(Qt.green).dark(120)
        segLineColor = segColor.dark()
        painter.setPen(segLineColor)
        painter.setBrush(segColor)
        painter.drawRect(FractionSlider.XMARGIN, FractionSlider.YMARGIN, span,
                         fm.height())

        textColor = self.palette().color(QPalette.Text)
        segWidth = span / self.__denominator
        segHeight = fm.height() * 2
        nRect = fm.boundingRect(FractionSlider.WSTRING)
        x = FractionSlider.XMARGIN
        yOffset = segHeight + fm.height()

        for i in range(self.__denominator + 1):

            painter.setPen(segLineColor)
            painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight)

            painter.setPen(textColor)
            y = segHeight
            rect = QRectF(nRect)
            rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
            painter.drawText(rect, Qt.AlignCenter, QString.number(i))

            y = yOffset
            rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
            painter.drawText(rect, Qt.AlignCenter,
                             QString.number(self.__denominator))
            painter.drawLine(QPointF(rect.left() + indent, y),
                             QPointF(rect.right() - indent, y))

            x += segWidth

        span = int(span)
        y = FractionSlider.YMARGIN - 0.5

        triangle = [
            QPointF(value * span, y),
            QPointF((value * span) + (2 * FractionSlider.XMARGIN), y),
            QPointF((value * span) + FractionSlider.XMARGIN, fm.height())
        ]

        painter.setPen(Qt.yellow)
        painter.setBrush(Qt.darkYellow)
        painter.drawPolygon(QPolygonF(triangle))