Ejemplo n.º 1
0
 def dropEvent(self, event):
     label_dropeado = event.source()
     pos_global = label_dropeado.mapToGlobal(QPoint(0, 0))
     pos_global_drop = self.mapToGlobal(event.pos())
     colider_drop = QRect(pos_global_drop, label_dropeado.size())
     if label_dropeado.tipo == "choza":
         for id_nodo in self.labels_nodos:
             label_nodo = self.labels_nodos[id_nodo]
             pos_global_nodo = label_nodo.mapToGlobal(QPoint(0, 0))
             colider_nodo = QRect(pos_global_nodo, label_nodo.size())
             if colider_drop.intersects(colider_nodo):
                 self.senal_casa_dropeada.emit(id_nodo)
                 self.deshabilitar_interfaz()
                 return
         self.alerta("Posicion invalida")
     elif label_dropeado.tipo == "ladron":
         for id_hexagono in self.labels_hexagonos:
             label_hexagono = self.labels_hexagonos[id_hexagono]
             pos_global_hexagono = label_hexagono.mapToGlobal(QPoint(0, 0))
             colider_hexagono = QRect(pos_global_hexagono,
                                      label_hexagono.size())
             if colider_drop.intersects(colider_hexagono):
                 self.senal_ladron_dropeado.emit(id_hexagono)
                 self.ladron.movible = False
                 return
         self.alerta("Posicion invalida")
Ejemplo n.º 2
0
    def verificar_compra(self, e, labels, miuenzo, dimensiones_mapa):
        ''' to-do: verificar compra en backend '''
        tipo, width, height = e.mimeData().text().split(',')
        qrect_drop = QRect(e.pos().x(), e.pos().y(), int(width), int(height))
        valido = True

        if (tipo == 'chef' and self.dccafe.dinero < PRECIO_CHEF) or (tipo == 'mesa'
            and self.dccafe.dinero < PRECIO_MESA):
            valido = False

        if not dimensiones_mapa.contains(qrect_drop):
            valido = False

        elif qrect_drop.intersects(miuenzo.geometry()):
            valido = False

        else:
            for label in labels:
                if label.geometry().intersects(qrect_drop):
                    valido = False

        if valido:
            data = {'tipo': tipo,
                    'pos': e.pos()}
            if tipo == 'chef':
                self.dccafe.dinero -= PRECIO_CHEF
            else:
                self.dccafe.dinero -= PRECIO_MESA
            self.senal_compra_verificada.emit(data)
            self.senal_dinero.emit(self.dccafe.dinero)
Ejemplo n.º 3
0
 def render(self, painter: QPainter, rect: QRect) -> None:
     for x in range(self.m_tilesRect.width() + 1):
         for y in range(self.m_tilesRect.height() + 1):
             tp = QPoint(x + self.m_tilesRect.left(), y + self.m_tilesRect.top())
             box = self.tileRect(tp)
             if rect.intersects(box):
                 painter.drawPixmap(
                     box, self.m_tilePixmaps.get(QPointH(tp), self.m_emptyTile)
                 )
Ejemplo n.º 4
0
def is_visible(elem, mainframe):
    """Check if the given element is visible in the frame.

    We need this as a standalone function (as opposed to a WebElementWrapper
    method) because we want to check this before wrapping when hinting for
    performance reasons.

    Args:
        elem: The QWebElement to check.
        mainframe: The QWebFrame in which the element should be visible.
    """
    if elem.isNull():
        raise IsNullError("Got called on a null element!")
    # CSS attributes which hide an element
    hidden_attributes = {
        'visibility': 'hidden',
        'display': 'none',
    }
    for k, v in hidden_attributes.items():
        if elem.styleProperty(k, QWebElement.ComputedStyle) == v:
            return False
    elem_geometry = elem.geometry()
    if not elem_geometry.isValid() and elem_geometry.x() == 0:
        # Most likely an invisible link
        return False
    # First check if the element is visible on screen
    elem_rect = rect_on_view(elem, elem_geometry=elem_geometry)
    mainframe_geometry = mainframe.geometry()
    if elem_rect.isValid():
        visible_on_screen = mainframe_geometry.intersects(elem_rect)
    else:
        # We got an invalid rectangle (width/height 0/0 probably), but this
        # can still be a valid link.
        visible_on_screen = mainframe_geometry.contains(
            elem_rect.topLeft())
    # Then check if it's visible in its frame if it's not in the main
    # frame.
    elem_frame = elem.webFrame()
    framegeom = QRect(elem_frame.geometry())
    if not framegeom.isValid():
        visible_in_frame = False
    elif elem_frame.parentFrame() is not None:
        framegeom.moveTo(0, 0)
        framegeom.translate(elem_frame.scrollPosition())
        if elem_geometry.isValid():
            visible_in_frame = framegeom.intersects(elem_geometry)
        else:
            # We got an invalid rectangle (width/height 0/0 probably), but
            # this can still be a valid link.
            visible_in_frame = framegeom.contains(elem_geometry.topLeft())
    else:
        visible_in_frame = visible_on_screen
    return all([visible_on_screen, visible_in_frame])
Ejemplo n.º 5
0
def is_visible(elem, mainframe):
    """Check if the given element is visible in the frame.

    We need this as a standalone function (as opposed to a WebElementWrapper
    method) because we want to check this before wrapping when hinting for
    performance reasons.

    Args:
        elem: The QWebElement to check.
        mainframe: The QWebFrame in which the element should be visible.
    """
    if elem.isNull():
        raise IsNullError("Got called on a null element!")
    # CSS attributes which hide an element
    hidden_attributes = {
        'visibility': 'hidden',
        'display': 'none',
    }
    for k, v in hidden_attributes.items():
        if elem.styleProperty(k, QWebElement.ComputedStyle) == v:
            return False
    elem_geometry = elem.geometry()
    if not elem_geometry.isValid() and elem_geometry.x() == 0:
        # Most likely an invisible link
        return False
    # First check if the element is visible on screen
    elem_rect = rect_on_view(elem, elem_geometry=elem_geometry)
    mainframe_geometry = mainframe.geometry()
    if elem_rect.isValid():
        visible_on_screen = mainframe_geometry.intersects(elem_rect)
    else:
        # We got an invalid rectangle (width/height 0/0 probably), but this
        # can still be a valid link.
        visible_on_screen = mainframe_geometry.contains(
            elem_rect.topLeft())
    # Then check if it's visible in its frame if it's not in the main
    # frame.
    elem_frame = elem.webFrame()
    framegeom = QRect(elem_frame.geometry())
    if not framegeom.isValid():
        visible_in_frame = False
    elif elem_frame.parentFrame() is not None:
        framegeom.moveTo(0, 0)
        framegeom.translate(elem_frame.scrollPosition())
        if elem_geometry.isValid():
            visible_in_frame = framegeom.intersects(elem_geometry)
        else:
            # We got an invalid rectangle (width/height 0/0 probably), but
            # this can still be a valid link.
            visible_in_frame = framegeom.contains(elem_geometry.topLeft())
    else:
        visible_in_frame = visible_on_screen
    return all([visible_on_screen, visible_in_frame])
Ejemplo n.º 6
0
    def movimiento_miuenzo(self, teclas, labels,
                            miuenzo, dimensiones_mapa):
        ''' En caso de que el movimiento de miuenzo sea valido, mandamos senal
        a VentanaMapa'''
        # guardamos la posicion de miuenzo antes del movimiento
        # tecla W:
        if teclas[87]:
            dx = 0
            dy = - VEL_MOVIMIENTO
            tecla = 87
        # tecka A:
        elif teclas[65]:
            dx = - VEL_MOVIMIENTO
            dy = 0
            tecla = 65
        # tecla D:
        elif teclas[68]:
            dx = VEL_MOVIMIENTO
            dy = 0
            tecla = 68
        # tecla S:
        elif teclas[83]:
            dx = 0
            dy = VEL_MOVIMIENTO
            tecla = 83

        nueva_posicion = QRect(miuenzo.pos().x() + dx, miuenzo.pos().y() + dy,
                                miuenzo.width(), miuenzo.height())
        interseccion = False
        for label in labels:
            if nueva_posicion.intersects(label.geometry()):
                interseccion = True
                if label.__class__.__name__ == 'Chef':
                    if not label.cocinando and not miuenzo.ocupado: # esperando
                        self.senal_colision_chef.emit(label, 1) # empezar a cocinar
                        self.timer_chef(label) # empezamos un timer
                    elif label.cocinando == 2 and not miuenzo.ocupado:
                        # el 2 significa que el chef termino el bocadillo
                        self.senal_colision_chef.emit(label, 0) # agarrar el bocadillo

                elif label.__class__.__name__ == 'Mesa':
                    if miuenzo.ocupado and label.ocupado:
                        # mesa con cliente y miuenzo con el bocadillo
                        self.senal_colision_mesa.emit(label)

        if not dimensiones_mapa.contains(nueva_posicion):
            interseccion = True

        if interseccion:
            dx = dy = 0 # su desplazamiento sera 0
        # siempre mandamos la senal, pues la animacion es independiente de
        # si se desplaza o no
        self.senal_mover_miuenzo.emit(dx, dy, tecla)
Ejemplo n.º 7
0
    def _is_visible(self, mainframe: QWebFrame) -> bool:
        """Check if the given element is visible in the given frame.

        This is not public API because it can't be implemented easily here with
        QtWebEngine, and is only used via find_css(..., only_visible=True) via
        the tab API.
        """
        self._check_vanished()
        # CSS attributes which hide an element
        hidden_attributes = {
            'visibility': 'hidden',
            'display': 'none',
            'opacity': '0',
        }
        for k, v in hidden_attributes.items():
            if (self._elem.styleProperty(k, QWebElement.ComputedStyle) == v and
                    'ace_text-input' not in self.classes()):
                return False

        elem_geometry = self._elem.geometry()
        if not elem_geometry.isValid() and elem_geometry.x() == 0:
            # Most likely an invisible link
            return False
        # First check if the element is visible on screen
        elem_rect = self.rect_on_view(elem_geometry=elem_geometry)
        mainframe_geometry = mainframe.geometry()
        if elem_rect.isValid():
            visible_on_screen = mainframe_geometry.intersects(elem_rect)
        else:
            # We got an invalid rectangle (width/height 0/0 probably), but this
            # can still be a valid link.
            visible_on_screen = mainframe_geometry.contains(
                elem_rect.topLeft())
        # Then check if it's visible in its frame if it's not in the main
        # frame.
        elem_frame = self._elem.webFrame()
        framegeom = QRect(elem_frame.geometry())
        if not framegeom.isValid():
            visible_in_frame = False
        elif elem_frame.parentFrame() is not None:
            framegeom.moveTo(0, 0)
            framegeom.translate(elem_frame.scrollPosition())
            if elem_geometry.isValid():
                visible_in_frame = framegeom.intersects(elem_geometry)
            else:
                # We got an invalid rectangle (width/height 0/0 probably), but
                # this can still be a valid link.
                visible_in_frame = framegeom.contains(elem_geometry.topLeft())
        else:
            visible_in_frame = visible_on_screen
        return all([visible_on_screen, visible_in_frame])
Ejemplo n.º 8
0
    def _is_visible(self, mainframe):
        """Check if the given element is visible in the given frame.

        This is not public API because it can't be implemented easily here with
        QtWebEngine, and is only used via find_css(..., only_visible=True) via
        the tab API.
        """
        self._check_vanished()
        # CSS attributes which hide an element
        hidden_attributes = {
            'visibility': 'hidden',
            'display': 'none',
            'opacity': '0',
        }
        for k, v in hidden_attributes.items():
            if (self._elem.styleProperty(k, QWebElement.ComputedStyle) == v and
                    'ace_text-input' not in self.classes()):
                return False

        elem_geometry = self._elem.geometry()
        if not elem_geometry.isValid() and elem_geometry.x() == 0:
            # Most likely an invisible link
            return False
        # First check if the element is visible on screen
        elem_rect = self.rect_on_view(elem_geometry=elem_geometry)
        mainframe_geometry = mainframe.geometry()
        if elem_rect.isValid():
            visible_on_screen = mainframe_geometry.intersects(elem_rect)
        else:
            # We got an invalid rectangle (width/height 0/0 probably), but this
            # can still be a valid link.
            visible_on_screen = mainframe_geometry.contains(
                elem_rect.topLeft())
        # Then check if it's visible in its frame if it's not in the main
        # frame.
        elem_frame = self._elem.webFrame()
        framegeom = QRect(elem_frame.geometry())
        if not framegeom.isValid():
            visible_in_frame = False
        elif elem_frame.parentFrame() is not None:
            framegeom.moveTo(0, 0)
            framegeom.translate(elem_frame.scrollPosition())
            if elem_geometry.isValid():
                visible_in_frame = framegeom.intersects(elem_geometry)
            else:
                # We got an invalid rectangle (width/height 0/0 probably), but
                # this can still be a valid link.
                visible_in_frame = framegeom.contains(elem_geometry.topLeft())
        else:
            visible_in_frame = visible_on_screen
        return all([visible_on_screen, visible_in_frame])
Ejemplo n.º 9
0
 def is_visible(self, mainframe):
     """Check if the given element is visible in the given frame."""
     self._check_vanished()
     # CSS attributes which hide an element
     hidden_attributes = {
         'visibility': 'hidden',
         'display': 'none',
     }
     for k, v in hidden_attributes.items():
         if self._elem.styleProperty(k, QWebElement.ComputedStyle) == v:
             return False
     elem_geometry = self._elem.geometry()
     if not elem_geometry.isValid() and elem_geometry.x() == 0:
         # Most likely an invisible link
         return False
     # First check if the element is visible on screen
     elem_rect = self.rect_on_view(elem_geometry=elem_geometry)
     mainframe_geometry = mainframe.geometry()
     if elem_rect.isValid():
         visible_on_screen = mainframe_geometry.intersects(elem_rect)
     else:
         # We got an invalid rectangle (width/height 0/0 probably), but this
         # can still be a valid link.
         visible_on_screen = mainframe_geometry.contains(
             elem_rect.topLeft())
     # Then check if it's visible in its frame if it's not in the main
     # frame.
     elem_frame = self._elem.webFrame()
     framegeom = QRect(elem_frame.geometry())
     if not framegeom.isValid():
         visible_in_frame = False
     elif elem_frame.parentFrame() is not None:
         framegeom.moveTo(0, 0)
         framegeom.translate(elem_frame.scrollPosition())
         if elem_geometry.isValid():
             visible_in_frame = framegeom.intersects(elem_geometry)
         else:
             # We got an invalid rectangle (width/height 0/0 probably), but
             # this can still be a valid link.
             visible_in_frame = framegeom.contains(elem_geometry.topLeft())
     else:
         visible_in_frame = visible_on_screen
     return all([visible_on_screen, visible_in_frame])
Ejemplo n.º 10
0
    def _is_visible(self, mainframe: QWebFrame) -> bool:
        """Check if the given element is visible in the given frame.

        This is not public API because it can't be implemented easily here with
        QtWebEngine, and is only used via find_css(..., only_visible=True) via
        the tab API.
        """
        self._check_vanished()
        if self._is_hidden_css():
            return False

        elem_geometry = self._elem.geometry()
        if not elem_geometry.isValid() and elem_geometry.x() == 0:
            # Most likely an invisible link
            return False
        # First check if the element is visible on screen
        elem_rect = self.rect_on_view(elem_geometry=elem_geometry)
        mainframe_geometry = mainframe.geometry()
        if elem_rect.isValid():
            visible_on_screen = mainframe_geometry.intersects(elem_rect)
        else:
            # We got an invalid rectangle (width/height 0/0 probably), but this
            # can still be a valid link.
            visible_on_screen = mainframe_geometry.contains(
                elem_rect.topLeft())
        # Then check if it's visible in its frame if it's not in the main
        # frame.
        elem_frame = self._elem.webFrame()
        framegeom = QRect(elem_frame.geometry())
        if not framegeom.isValid():
            visible_in_frame = False
        elif elem_frame.parentFrame() is not None:
            framegeom.moveTo(0, 0)
            framegeom.translate(elem_frame.scrollPosition())
            if elem_geometry.isValid():
                visible_in_frame = framegeom.intersects(elem_geometry)
            else:
                # We got an invalid rectangle (width/height 0/0 probably), but
                # this can still be a valid link.
                visible_in_frame = framegeom.contains(elem_geometry.topLeft())
        else:
            visible_in_frame = visible_on_screen
        return all([visible_on_screen, visible_in_frame])
Ejemplo n.º 11
0
 def is_visible(self, mainframe):
     """Check if the given element is visible in the given frame."""
     self._check_vanished()
     # CSS attributes which hide an element
     hidden_attributes = {
         'visibility': 'hidden',
         'display': 'none',
     }
     for k, v in hidden_attributes.items():
         if self._elem.styleProperty(k, QWebElement.ComputedStyle) == v:
             return False
     elem_geometry = self._elem.geometry()
     if not elem_geometry.isValid() and elem_geometry.x() == 0:
         # Most likely an invisible link
         return False
     # First check if the element is visible on screen
     elem_rect = self.rect_on_view(elem_geometry=elem_geometry)
     mainframe_geometry = mainframe.geometry()
     if elem_rect.isValid():
         visible_on_screen = mainframe_geometry.intersects(elem_rect)
     else:
         # We got an invalid rectangle (width/height 0/0 probably), but this
         # can still be a valid link.
         visible_on_screen = mainframe_geometry.contains(
             elem_rect.topLeft())
     # Then check if it's visible in its frame if it's not in the main
     # frame.
     elem_frame = self._elem.webFrame()
     framegeom = QRect(elem_frame.geometry())
     if not framegeom.isValid():
         visible_in_frame = False
     elif elem_frame.parentFrame() is not None:
         framegeom.moveTo(0, 0)
         framegeom.translate(elem_frame.scrollPosition())
         if elem_geometry.isValid():
             visible_in_frame = framegeom.intersects(elem_geometry)
         else:
             # We got an invalid rectangle (width/height 0/0 probably), but
             # this can still be a valid link.
             visible_in_frame = framegeom.contains(elem_geometry.topLeft())
     else:
         visible_in_frame = visible_on_screen
     return all([visible_on_screen, visible_in_frame])
    def dropEvent(self, event):
        label_dropeado = event.source()
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        if label_dropeado.tipo == "choza":
            copia_choza = Casa(x, y, self)
            colider_copia = QRect(copia_choza.x(), copia_choza.y(),
                                  copia_choza.width(), copia_choza.height())
            for id_label_nodo in self.labels_nodos:
                label_nodo = self.labels_nodos[id_label_nodo]
                colider_nodo = QRect(label_nodo.x(), label_nodo.y(),
                                     label_nodo.width(), label_nodo.height())
                if colider_copia.intersects(colider_nodo):
                    self.senal_casa_dropeada.emit(id_label_nodo)
                    copia_choza.hide()
                    copia_choza.setParent(None)
                    return

        elif label_dropeado.tipo == "camino":
            pass
    def mouseMoveEvent(self, event):
        self.intersect = 0
        for i in self.rect_list:
            # Drag condition
            if i.drag == 1:
                rect_begin_dragged = i.temp_rect_begin + event.pos(
                ) - i.relative_start
                rect_end_dragged = i.temp_rect_end + event.pos(
                ) - i.relative_start
                for j in self.rect_list:
                    if j != i:
                        rect_begin_x = j.rect_begin.x() - 2 * j.Tri_In_H
                        rect_begin_y = j.rect_begin.y() - 10
                        rect_width = j.width + 3 * j.Tri_In_H
                        rect_height = j.height + 20
                        rect_temp = QRect(rect_begin_x, rect_begin_y,
                                          rect_width, rect_height)
                        rect_dragged = QRect(
                            rect_begin_dragged.x() - 2 * i.Tri_In_H,
                            rect_begin_dragged.y() - 10,
                            i.width + 3 * i.Tri_In_H, i.height + 20)
                        if rect_temp.intersects(rect_dragged):
                            self.intersect = 1
                            break

                if self.intersect == 0:
                    i.rect_begin = rect_begin_dragged
                    i.rect_end = rect_end_dragged
                    i.drag_release = 1
                    i.update()
                    self.update()  # To call paintEvent
                break

            # Top left resize
            elif i.resize == 1:
                rect_begin_dragged = event.pos()
                rect_end_dragged = copy.deepcopy(i.rect_end)
                for j in self.rect_list:
                    if j != i:
                        rect_begin_x = j.rect_begin.x() - 2 * j.Tri_In_H
                        rect_begin_y = j.rect_begin.y() - 10
                        rect_width = j.width + 3 * j.Tri_In_H
                        rect_height = j.height + 20
                        rect_temp = QRect(rect_begin_x, rect_begin_y,
                                          rect_width, rect_height)
                        rect_dragged = QRect(
                            rect_begin_dragged.x() - 2 * i.Tri_In_H,
                            rect_begin_dragged.y() - 10,
                            i.width + 3 * i.Tri_In_H, i.height + 20)
                        if rect_temp.intersects(rect_dragged):
                            self.intersect = 1
                            break

                if self.intersect == 0:
                    i.rect_begin = rect_begin_dragged
                    i.rect_end = rect_end_dragged
                    i.resize_release = 1
                    i.update()
                    self.update()  # To call paintEvent
                break

            # Bottom left resize
            elif i.resize == 2:
                rect_begin_dragged = copy.deepcopy(i.rect_begin)
                rect_begin_dragged.setX(event.pos().x())
                rect_end_dragged = copy.deepcopy(i.rect_end)
                rect_end_dragged.setY(event.pos().y())
                for j in self.rect_list:
                    if j != i:
                        rect_begin_x = j.rect_begin.x() - 2 * j.Tri_In_H
                        rect_begin_y = j.rect_begin.y() - 10
                        rect_width = j.width + 3 * j.Tri_In_H
                        rect_height = j.height + 20
                        rect_temp = QRect(rect_begin_x, rect_begin_y,
                                          rect_width, rect_height)
                        rect_dragged = QRect(
                            rect_begin_dragged.x() - 2 * i.Tri_In_H,
                            rect_begin_dragged.y() - 10,
                            i.width + 3 * i.Tri_In_H, i.height + 20)
                        if rect_temp.intersects(rect_dragged):
                            self.intersect = 1
                            break

                if self.intersect == 0:
                    i.rect_begin = rect_begin_dragged
                    i.rect_end = rect_end_dragged
                    i.resize_release = 2
                    i.update()
                    self.update()  # To call paintEvent
                break

            # Top right resize
            elif i.resize == 3:
                rect_begin_dragged = copy.deepcopy(i.rect_begin)
                rect_begin_dragged.setX(event.pos().y())
                rect_end_dragged = copy.deepcopy(i.rect_end)
                rect_end_dragged.setY(event.pos().x())
                for j in self.rect_list:
                    if j != i:
                        rect_begin_x = j.rect_begin.x() - 2 * j.Tri_In_H
                        rect_begin_y = j.rect_begin.y() - 10
                        rect_width = j.width + 3 * j.Tri_In_H
                        rect_height = j.height + 20
                        rect_temp = QRect(rect_begin_x, rect_begin_y,
                                          rect_width, rect_height)
                        rect_dragged = QRect(
                            rect_begin_dragged.x() - 2 * i.Tri_In_H,
                            rect_begin_dragged.y() - 10,
                            i.width + 3 * i.Tri_In_H, i.height + 20)
                        if rect_temp.intersects(rect_dragged):
                            self.intersect = 1
                            break

                if self.intersect == 0:
                    i.rect_begin = rect_begin_dragged
                    i.rect_end = rect_end_dragged
                    i.resize_release = 3
                    i.update()
                    self.update()  # To call paintEvent
                break

            # Bottom right resize
            elif i.resize == 4:
                rect_begin_dragged = copy.deepcopy(i.rect_begin)
                rect_end_dragged = event.pos()
                for j in self.rect_list:
                    if j != i:
                        rect_begin_x = j.rect_begin.x() - 2 * j.Tri_In_H
                        rect_begin_y = j.rect_begin.y() - 10
                        rect_width = j.width + 3 * j.Tri_In_H
                        rect_height = j.height + 20
                        rect_temp = QRect(rect_begin_x, rect_begin_y,
                                          rect_width, rect_height)
                        rect_dragged = QRect(
                            rect_begin_dragged.x() - 2 * i.Tri_In_H,
                            rect_begin_dragged.y() - 10,
                            i.width + 3 * i.Tri_In_H, i.height + 20)
                        if rect_temp.intersects(rect_dragged):
                            self.intersect = 1
                            break

                if self.intersect == 0:
                    i.rect_begin = rect_begin_dragged
                    i.rect_end = rect_end_dragged
                    i.resize_release = 4
                    i.update()
                    self.update()  # To call paintEvent
                break
            else:
                pass
Ejemplo n.º 14
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self._background_color = QColor(204, 204, 204, 255)

        self.setClearBeforeRendering(False)
        self.beforeRendering.connect(self._render, type=Qt.DirectConnection)

        self._mouse_device = QtMouseDevice(self)
        self._mouse_device.setPluginId("qt_mouse")
        self._key_device = QtKeyDevice()
        self._key_device.setPluginId("qt_key")
        self._previous_focus = None  # type: Optional["QQuickItem"]

        self._app = QCoreApplication.instance()

        # Remove previously added input devices (if any). This can happen if the window was re-loaded.
        self._app.getController().removeInputDevice("qt_mouse")
        self._app.getController().removeInputDevice("qt_key")

        self._app.getController().addInputDevice(self._mouse_device)
        self._app.getController().addInputDevice(self._key_device)
        self._app.getController().getScene().sceneChanged.connect(
            self._onSceneChanged)
        self._app.getController().activeViewChanged.connect(
            self._onActiveViewChanged)
        Selection.selectionChanged.connect(self._onSceneChanged)
        self._preferences = Application.getInstance().getPreferences()

        self._preferences.addPreference("general/window_width",
                                        self.DEFAULT_WINDOW_WIDTH)
        self._preferences.addPreference("general/window_height",
                                        self.DEFAULT_WINDOW_HEIGHT)
        self._preferences.addPreference("general/window_left",
                                        self.DEFAULT_WINDOW_LEFT)
        self._preferences.addPreference("general/window_top",
                                        self.DEFAULT_WINDOW_TOP)
        self._preferences.addPreference("general/window_state",
                                        Qt.WindowNoState)
        self._preferences.addPreference("general/restore_window_geometry",
                                        True)

        restored_geometry = QRect(
            int(self._preferences.getValue("general/window_left")),
            int(self._preferences.getValue("general/window_top")),
            int(self._preferences.getValue("general/window_width")),
            int(self._preferences.getValue("general/window_height")))

        if not self._preferences.getValue("general/restore_window_geometry"):
            # Ignore whatever the preferences said.
            Logger.log(
                "i",
                "Not restoring window geometry from preferences because 'restore_window_geometry' is false"
            )
            restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT,
                                      self.DEFAULT_WINDOW_TOP,
                                      self.DEFAULT_WINDOW_WIDTH,
                                      self.DEFAULT_WINDOW_HEIGHT)

        # Make sure restored geometry is not outside the currently available screens
        screen_found = False
        for s in range(0, self._app.desktop().screenCount()):
            if restored_geometry.intersects(
                    self._app.desktop().availableGeometry(s)):
                screen_found = True
                break

        if not screen_found:
            Logger.log(
                "w",
                "Could not restore to previous location on screen, since the sizes or number of monitors "
                "have changed since then")
            # Unable to find the screen that this window used to be on, so just use the defaults
            restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT,
                                      self.DEFAULT_WINDOW_TOP,
                                      self.DEFAULT_WINDOW_WIDTH,
                                      self.DEFAULT_WINDOW_HEIGHT)

        self.setGeometry(restored_geometry)
        self.setWindowState(
            int(self._preferences.getValue("general/window_state")))

        self._mouse_x = 0
        self._mouse_y = 0

        self._mouse_pressed = False

        self._viewport_rect = QRectF(0, 0, 1.0, 1.0)

        self.closing.connect(self.preClosing)

        Application.getInstance().setMainWindow(self)
        self._fullscreen = False

        self._full_render_required = True

        self._allow_resize = True
Ejemplo n.º 15
0
    def paintEvent(self, event):
        ## Draw Background Grid
        minorGridSpacing = 25
        lineLength = 10000
        lineCount = 100
        majorGridSpacing = 8
        minorGridColor = [100, 100, 100, 100]
        majorGridColor = [0, 0, 0, 255]

        ## Draw grid background
        painter = QPainter(self)
        painter.setPen(
            QPen(
                QColor(minorGridColor[0], minorGridColor[1], minorGridColor[2],
                       minorGridColor[3]), 1, Qt.SolidLine))
        ##TODO: This is hapazard with the line distances. Probably should be fixed
        for i in range(0, lineCount):
            painter.drawLine(minorGridSpacing * i, 0, minorGridSpacing * i,
                             lineLength)
            painter.drawLine(0, minorGridSpacing * i, lineLength,
                             minorGridSpacing * i)

        painter.setPen(
            QPen(
                QColor(majorGridColor[0], majorGridColor[1], majorGridColor[2],
                       majorGridColor[3]), 2, Qt.SolidLine))

        for i in range(0, lineCount):
            painter.drawLine(majorGridSpacing * minorGridSpacing * i, 0,
                             majorGridSpacing * minorGridSpacing * i,
                             lineLength)
            painter.drawLine(0, majorGridSpacing * minorGridSpacing * i,
                             lineLength,
                             majorGridSpacing * minorGridSpacing * i)

        painter.setPen(QPen(QColor(255, 255, 255), 2, Qt.SolidLine))
        painter.setRenderHint(QPainter.Antialiasing)
        cubicCurveFactor = 0.5
        if (self.mouseIsHot):
            mousePos = self.mapFromGlobal(QtGui.QCursor.pos())
            hotPortLoc = self.hotPort.parent.pos() + self.hotPort.pos(
            ) + QPoint(self.hotPort.width / 2, self.hotPort.height / 2)
            path = QPainterPath()
            path.moveTo(hotPortLoc)
            ##TODO CUBIC PATH
            path.cubicTo(
                hotPortLoc + QPoint(
                    (mousePos.x() - hotPortLoc.x()) * cubicCurveFactor, 0),
                mousePos - QPoint(
                    (mousePos.x() - hotPortLoc.x()) * cubicCurveFactor, 0),
                mousePos)

            painter.drawPath(path)
            # painter.drawLine(hotPortLoc.x(), hotPortLoc.y(), mousePos.x(), mousePos.y())

        for input in self.connectionManager.inputPorts:
            for connection in input.connections:
                painter.setPen(QPen(QColor(255, 255, 255), 2, Qt.SolidLine))
                painter.setRenderHint(QPainter.Antialiasing)
                port1Pos = input.parent.mapToParent(input.pos()) + QPoint(
                    input.size().width(),
                    input.size().height()) / 2 - 0 * QPoint(
                        self.size().width(), 0)
                port2Pos = connection.parent.mapToParent(connection.pos(
                )) + QPoint(connection.size().width(),
                            connection.size().height()) / 2 - 0 * QPoint(
                                self.size().width(), 0)
                path = QPainterPath()
                path.moveTo(port1Pos)
                ##TODO CUBIC PATH
                path.cubicTo(
                    port1Pos - QPoint(
                        (port1Pos.x() - port2Pos.x()) * cubicCurveFactor, 0),
                    port2Pos + QPoint(
                        (port1Pos.x() - port2Pos.x()) * cubicCurveFactor, 0),
                    port2Pos)
                painter.drawPath(path)

        if self.shouldDrawSelectionBox:
            painter.setPen(QPen(QColor(255, 255, 255), 1, Qt.DashLine))
            selectionRect = QRect(
                np.min(
                    [self.mousePressLocation.x(),
                     self.mouseDragLocation.x()]),
                np.min(
                    [self.mousePressLocation.y(),
                     self.mouseDragLocation.y()]),
                np.abs(self.mousePressLocation.x() -
                       self.mouseDragLocation.x()),
                np.abs(self.mousePressLocation.y() -
                       self.mouseDragLocation.y()))
            painter.drawRect(selectionRect)

            for brick in self.bricks:
                P1 = brick.rect().topLeft()
                brickRect = QRect(
                    brick.mapTo(self, P1),
                    QSize(brick.rect().size().width(),
                          brick.rect().size().height()))
                if selectionRect.intersects(brickRect):
                    self.addToSelected(brick)
                    if brick not in self.boxedRects:
                        self.boxedRects.append(brick)
                else:
                    if brick in self.boxedRects:
                        self.deselect(brick)
                        self.boxedRects.remove(brick)
    def contextMenuEvent(self, event):
        module_area = 0
        for i in self.rect_list:
            if i.rect_begin.x() < event.pos().x() < i.rect_end.x(
            ) and i.rect_begin.y() < event.pos().y() < i.rect_end.y():
                module_area = 1
                contextMenu = QMenu(self)

                # Add Input Port action is used to add input port to both code and block
                portAction = contextMenu.addAction("Add Port")
                renameAction = contextMenu.addAction("Rename Module")
                removeModuleAction = contextMenu.addAction("Remove Module")

                action = contextMenu.exec_(self.mapToGlobal(event.pos()))

                if action == portAction:
                    self.myshow = AddPort(i)
                    self.myshow.setWindowTitle("Add Port")
                    self.myshow.show()
                    self.update()
                elif action == renameAction:
                    self.myshow = RenameModule(i, self.forbidden_module_names)
                    self.myshow.setWindowTitle("Rename Module")
                    self.myshow.show()
                    self.update()
                elif action == removeModuleAction:
                    self.forbidden_module_names.remove(i.center_text)
                    self.rect_list.remove(i)
                    self.update()

        port_area = "no_port"
        if module_area == 0:
            for r in self.rect_list:
                temp_port = 0
                for i in r.in_port_list:
                    polygon = QPolygon(i.points)
                    if polygon.containsPoint(event.pos(), Qt.OddEvenFill):
                        port_area = "input"
                        temp_port = i
                for i in r.inout_port_list:
                    polygon = QPolygon(i.points)
                    if polygon.containsPoint(event.pos(), Qt.OddEvenFill):
                        port_area = "inout"
                        temp_port = i
                for i in r.out_port_list:
                    polygon = QPolygon(i.points)
                    if polygon.containsPoint(event.pos(), Qt.OddEvenFill):
                        port_area = "output"
                        temp_port = i

                if port_area != "no_port":
                    contextMenu = QMenu(self)
                    removeAction = contextMenu.addAction("Remove")
                    renameAction = contextMenu.addAction("Rename Port")

                    action = contextMenu.exec_(self.mapToGlobal(event.pos()))

                    if action == removeAction:
                        if port_area == "input":
                            r.in_port_list.remove(temp_port)
                            r.update()
                            self.update()
                        elif port_area == "inout":
                            r.inout_port_list.remove(temp_port)
                            r.update()
                            self.update()
                        elif port_area == "output":
                            r.out_port_list.remove(temp_port)
                            r.update()
                            self.update()
                        r.update()
                    elif action == renameAction:
                        self.myshow = RenamePort(temp_port, r)
                        self.myshow.setWindowTitle("Rename Port")
                        self.myshow.show()
                    break

        if port_area == "no_port" and module_area == 0:
            contextMenu = QMenu(self)

            # Add Input Port action is used to add input port to both code and block
            addModuleAction = contextMenu.addAction("Add Module")

            action = contextMenu.exec_(self.mapToGlobal(event.pos()))
            if action == addModuleAction:
                intersect = 0
                rect_begin_dragged = event.pos()
                for j in self.rect_list:
                    rect_begin_x = j.rect_begin.x() - 2 * j.Tri_In_H
                    rect_begin_y = j.rect_begin.y() - 10
                    rect_width = j.width + 3 * j.Tri_In_H
                    rect_height = j.height + 20
                    rect_temp = QRect(rect_begin_x, rect_begin_y, rect_width,
                                      rect_height)
                    rect_dragged = QRect(
                        rect_begin_dragged.x() - 2 * j.Tri_In_H,
                        rect_begin_dragged.y() - 10, 200 + 3 * j.Tri_In_H,
                        200 + 20)
                    if rect_temp.intersects(rect_dragged):
                        intersect = 1
                        break

                if intersect == 0:
                    tempModule = Module()
                    i = 0
                    while 1:
                        if 'case_block_' + str(
                                i) not in self.forbidden_module_names:
                            tempModule.center_text = 'case_block_' + str(i)
                            tempModule.rect_begin = event.pos()
                            tempModule.rect_end = event.pos() + QtCore.QPoint(
                                200, 200)
                            tempModule.update()
                            self.rect_list.append(tempModule)
                            self.forbidden_module_names.append(
                                tempModule.center_text)
                            # To call paintEvent method, update method is run.
                            # When module is created, to show it on canvas paintEvent must be called
                            self.update()
                            break
                        i = i + 1
                else:
                    self.myshow = ErrorMessage(
                        'Module cannot be created because it is too close to other modules'
                    )
Ejemplo n.º 17
0
class Rect(Node):
    def __init__(self, event: dict, x=0, y=0, w=0, h=0):
        super().__init__(event)
        self._rect = QRect(x, y, w, h)

    def copy(self):
        rect = self.__class__(self.event, *self)
        rect.set_color(self._color)
        rect.set_scale_available(self._scale_available)
        return rect

    @property
    def x(self):
        return self._rect.x()

    @property
    def y(self):
        return self._rect.y()

    @property
    def w(self):
        return self._rect.width()

    @property
    def h(self):
        return self._rect.height()

    @property
    def rect(self):
        return self._rect

    @property
    def size(self):
        return self.w, self.h

    def check_rect(self, x, y, w, h):
        return self._rect.intersects(QRect(x, y, w, h))

    def check_point(self, x, y):
        return self._rect.contains(QPoint(x, y))

    def set_size(self, w=None, h=None, convert_negative=False):
        if w is not None:
            if convert_negative and w < 0:
                w = abs(w)
                self._rect.setX(self.x - w)
            self._rect.setWidth(w)
        if h is not None:
            if convert_negative and h < 0:
                h = abs(h)
                self._rect.setY(self.y - h)
            self._rect.setHeight(h)

    def set_position(self, x=None, y=None):
        if x is not None:
            w = self.w
            self._rect.setX(x)
            self._rect.setWidth(w)
        if y is not None:
            h = self.h
            self._rect.setY(y)
            self._rect.setHeight(h)

    def draw(self):
        super().draw()
        p = self.painter
        s = self.scale
        if s == 1:
            p.drawRect(self._rect)
        else:
            size = [self.x * s, self.y * s, self.w * s, self.h * s]
            size = [int(i) for i in size]
            p.drawRect(*size)

    def __iter__(self):
        # Support unpack.
        for i in [self.x, self.y, self.w, self.h]:
            yield i