Exemplo n.º 1
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("KOSAN KEDİ...")
        self.resize(512, 256)

        self.sprite_sheet = QImage("sprites-cat-running.png")
        self.sw = 512
        self.sh = 256
        self.frame_index = 0
        self.x = 0
        self.y = 0
        self.frames = []
        for i in range(2):
            for j in range(4):
                self.frames.append(QPoint(j * self.sw, i * self.sh))
                print(i, j)
        self.delta_time = 0
        self.animation_time = 0
        self.animation_speed = 100

        self.timer = QTimer()
        self.timer.timeout.connect(self.animationLoop)
        self.elapsedTimer = QElapsedTimer()
        self.timer.start(50)
        print("Timer start")

    def animationLoop(self):
        print("Timer started...")

        self.delta_time = self.elapsedTimer.elapsed()
        self.elapsedTimer.restart()
        self.animation_time += self.delta_time
        if self.animation_time <= self.animation_speed:
            print("self.animation_time >= self.animation_speed")
            self.animation_time = 0
            self.x = self.frames[self.frame_index].x()
            self.y = self.frames[self.frame_index].y()
            self.frame_index += 1
            if self.frame_index >= len(self.frames):
                self.frame_index = 0
                print("self.frame_index = 0")
        self.update()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.drawImage(0, 0, self.sprite_sheet, self.x, self.y, self.sw, self.sh)
Exemplo n.º 2
0
class Window(QMainWindow):
    ''' docstring '''
    def __init__(self):
        super().__init__()
        self.conn_status = False
        self.query_status = False
        self.sckt = None
        self.new_tcp_host = "192.168.43.67"  #TCP_HOST_IP
        self.init_ui()
        self.q_p1_x = 116.30
        self.q_p1_y = 39.97
        self.q_p2_x = 116.32
        self.q_p2_y = 40.00
        self.query_elapsed = None
        self.proc_elapsed = 0
        self.timer = QElapsedTimer()

    def init_ui(self):
        ''' docstring '''

        #self.com = Communicate()
        # self.com.close_app.connect(self.close)

        self.custom_wid = MainWidget(self)
        self.custom_wid.control_wid.connect_btn.clicked.connect(
            self.connect_server)
        self.custom_wid.control_wid.open_btn.clicked.connect(self.open_file)
        self.custom_wid.control_wid.close_btn.clicked.connect(self.close_app)
        self.custom_wid.control_wid.plot_btn.clicked.connect(self.load_data)
        self.custom_wid.control_wid.query_btn.clicked.connect(
            self.query_region)

        self.setCentralWidget(self.custom_wid)
        self.statusBar()
        self.statusBar().showMessage('Ready')
        self.resize(1280, 720)
        self.center()
        self.setWindowTitle('Trajectory Mapping - Client App')
        self.show()

    def center(self):
        ''' docstring '''

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def connect_server(self):
        ''' docstring '''

        self.new_tcp_host, ok = QInputDialog.getText(
            self, 'Connect to Server', 'Enter server IP address:',
            QLineEdit.Normal, str(self.new_tcp_host))

        if ok:
            # close existing socket
            try:
                self.sckt.close()
            except:
                pass
            # create a socket object
            self.sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # connection to hostname on the port.
            print(self.new_tcp_host)
            try:
                self.sckt.connect((self.new_tcp_host, TCP_PORT))
            except:
                return

            self.conn_status = True
            # send message to server
            msg_to_send = 'Houssem & Ayoub'
            self.sckt.send(msg_to_send.encode('utf-8'))

            # Receive no more than BUFFER_SIZE bytes
            msg = self.sckt.recv(BUFFER_SIZE)

            # print received reply
            print(msg.decode('utf-8'))
            self.statusBar().showMessage(msg.decode('utf-8'))

    def open_file(self):
        ''' docstring '''
        self.timer.restart()
        if self.conn_status:
            fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')

            if fname[0]:
                fsize = os.path.getsize(fname[0])
                self.sckt.send(str(fsize).encode('utf-8'))

                with open(fname[0], 'rb') as f:
                    data_buffer = f.read(BUFFER_SIZE)
                    while data_buffer:
                        self.sckt.send(data_buffer)
                        data_buffer = f.read(BUFFER_SIZE)

                print('File opened and sent to server')
                self.statusBar().showMessage('File opened and sent to server')
                self.receive_files()
        else:
            self.statusBar().showMessage('First connect to server')

    def close_app(self):
        ''' docstring '''
        if self.conn_status:
            self.sckt.close()
        QApplication.instance().quit()

    def receive_files(self):
        ''' docstring'''

        with open(ORIGINAL_DATASET_FILE, 'wb') as f:
            print('Receiving data ...')
            msg = self.sckt.recv(BUFFER_SIZE)
            fsize = int(msg.decode('utf-8'))
            rsize = 0
            while True:
                data = self.sckt.recv(BUFFER_SIZE)
                #print('Received data = %s', (data))
                rsize = rsize + len(data)
                f.write(data)
                #print(rsize)
                if rsize >= fsize:
                    print('Breaking from file write')
                    break

        with open(REDUCED_DATASET_FILE, 'wb') as f:
            print('Receiving data ...')
            msg = self.sckt.recv(BUFFER_SIZE)
            fsize = int(msg.decode('utf-8'))
            rsize = 0
            while True:
                data = self.sckt.recv(BUFFER_SIZE)
                #print('Received data = %s', (data))
                rsize = rsize + len(data)
                f.write(data)
                #print(rsize)
                if rsize >= fsize:
                    print('Breaking from file write')
                    break

        self.statusBar().showMessage('Files received from server')

        self.proc_elapsed = self.timer.nsecsElapsed()
        print(self.timer.clockType())
        print(self.proc_elapsed)
        self.custom_wid.control_wid.label_7.setText(
            "Processing time: {}".format(self.proc_elapsed))

    def load_data(self):
        ''' docstring'''
        full_ds = 0
        reduced_ds = 0
        reduction_rate = 0
        query_full_ratio = 0
        query_reduced_ratio = 0

        lines_buffer = []
        original_dataset = []
        with open(ORIGINAL_DATASET_FILE, 'r') as f:
            lines_buffer = f.readlines()
            full_ds = len(lines_buffer)
            #print(lines_buffer)
        for line in lines_buffer:
            tmp = line.split(',')
            tmp[0] = float(tmp[0])
            tmp[1] = float(tmp[1])
            original_dataset.append(tmp)
        #print(original_dataset)

        lines_buffer = []
        reduced_dataset = []
        with open(REDUCED_DATASET_FILE, 'r') as f:
            lines_buffer = f.readlines()
            reduced_ds = len(lines_buffer)
            #print(lines_buffer)
        for line in lines_buffer:
            tmp = line.split(',')
            tmp[0] = float(tmp[0])
            tmp[1] = float(tmp[1])
            reduced_dataset.append(tmp)
        #print(reduced_dataset)

        reduction_rate = 100 * (1 - reduced_ds / full_ds)
        self.custom_wid.control_wid.label_1.setText(
            "Full dataset: {}".format(full_ds))
        self.custom_wid.control_wid.label_2.setText(
            "Reduced dataset: {}".format(reduced_ds))
        self.custom_wid.control_wid.label_3.setText(
            "Reduction rate: {} %".format(round(reduction_rate, 2)))

        query_original_dataset = []
        query_reduced_dataset = []

        if self.query_status:
            lines_buffer = []
            with open(QUERY_ORIGINAL_DATASET_FILE, 'r') as f:
                lines_buffer = f.readlines()
                query_full_ratio = 100 * len(lines_buffer) / full_ds
                #print(lines_buffer)
            for line in lines_buffer:
                tmp = line.split(',')
                tmp[0] = float(tmp[0])
                tmp[1] = float(tmp[1])
                query_original_dataset.append(tmp)

            lines_buffer = []
            with open(QUERY_REDUCED_DATASET_FILE, 'r') as f:
                lines_buffer = f.readlines()
                query_reduced_ratio = 100 * len(lines_buffer) / reduced_ds
                #print(lines_buffer)
            for line in lines_buffer:
                tmp = line.split(',')
                tmp[0] = float(tmp[0])
                tmp[1] = float(tmp[1])
                query_reduced_dataset.append(tmp)

        else:
            self.custom_wid.control_wid.coord1_x.setValue(
                reduced_dataset[0][0])
            self.custom_wid.control_wid.coord1_y.setValue(
                reduced_dataset[0][1])
            self.custom_wid.control_wid.coord2_x.setValue(
                reduced_dataset[-1][0])
            self.custom_wid.control_wid.coord2_y.setValue(
                reduced_dataset[-1][1])

        self.custom_wid.control_wid.label_4.setText(
            "Results ratio to full dataset: {} %".format(
                round(query_full_ratio)))
        self.custom_wid.control_wid.label_5.setText(
            "Results ratio to reduced dataset: {} %".format(
                round(query_reduced_ratio)))

        xy = np.array(reduced_dataset)
        q_xy = np.array([])
        tmp = self.custom_wid.control_wid.combo_box.currentText()
        if tmp == "Full Dataset":
            xy = np.array(original_dataset)
            q_xy = np.array(query_original_dataset)
        elif tmp == "Reduced Dataset":
            xy = np.array(reduced_dataset)
            q_xy = np.array(query_reduced_dataset)

        # Plot the path as red dots connected by a blue line
        plt.hold(True)
        if self.query_status:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            rect = mpatches.Rectangle(
                [min(self.q_p1_x, self.q_p2_x),
                 min(self.q_p1_y, self.q_p2_y)],
                abs(self.q_p1_x - self.q_p2_x), abs(self.q_p1_y - self.q_p2_y))
            ax.add_patch(rect)
            #plt.plot()
        plt.plot(xy[:, 0], xy[:, 1], 'ko')
        if self.query_status and len(q_xy):
            plt.plot(q_xy[:, 0], q_xy[:, 1], 'rD')
        plt.plot(xy[:, 0], xy[:, 1], 'b')

        root, ext = os.path.splitext(__file__)
        mapfile = root + '.html'
        print("mapfile: {}".format(mapfile))
        # Create the map. Save the file to basic_plot.html. _map.html is the default
        # if 'path' is not specified
        mplleaflet.show(inbrowser=False, path=mapfile)
        self.custom_wid.map_wid.setUrl(
            QUrl.fromLocalFile(QFileInfo(mapfile).absoluteFilePath()))

    def query_region(self):
        ''' docstring '''
        self.timer.restart()
        print('Sending query ...')
        self.q_p1_x = self.custom_wid.control_wid.coord1_x.value()
        self.q_p1_y = self.custom_wid.control_wid.coord1_y.value()
        self.q_p2_x = self.custom_wid.control_wid.coord2_x.value()
        self.q_p2_y = self.custom_wid.control_wid.coord2_y.value()
        msg_to_send = '{},{},{},{}'.format(self.q_p1_x, self.q_p1_y,
                                           self.q_p2_x, self.q_p2_y)
        self.sckt.send(msg_to_send.encode('utf-8'))
        print('Query sent ...')

        with open(QUERY_ORIGINAL_DATASET_FILE, 'wb') as f:
            print('Receiving query data ...')
            msg = self.sckt.recv(BUFFER_SIZE)
            fsize = int(msg.decode('utf-8'))
            rsize = 0
            if fsize:
                while True:
                    data = self.sckt.recv(BUFFER_SIZE)
                    #print('Received data = %s', (data))
                    rsize = rsize + len(data)
                    f.write(data)
                    #print(rsize)
                    if rsize >= fsize:
                        print('Breaking from query file write')
                        break

        with open(QUERY_REDUCED_DATASET_FILE, 'wb') as f:
            print('Receiving query data ...')
            msg = self.sckt.recv(BUFFER_SIZE)
            fsize = int(msg.decode('utf-8'))
            rsize = 0
            if fsize:
                while True:
                    data = self.sckt.recv(BUFFER_SIZE)
                    #print('Received data = %s', (data))
                    rsize = rsize + len(data)
                    f.write(data)
                    #print(rsize)
                    if rsize >= fsize:
                        print('Breaking from query file write')
                        break

        self.query_status = True
        self.query_elapsed = self.timer.nsecsElapsed()
        print(self.timer.clockType())
        print(self.query_elapsed)
        self.custom_wid.control_wid.label_6.setText("Query time: {}".format(
            self.query_elapsed))
Exemplo n.º 3
0
class ConnectionConfigView(QDialog, Ui_ConnectionConfigurationDialog):
    """
    Connection config view
    """
    values_changed = pyqtSignal()

    def __init__(self, parent):
        """
        Constructor
        """
        super().__init__(parent)
        self.setupUi(self)
        self.last_speed = 0.1
        self.average_speed = 1
        self.timer = QElapsedTimer()
        self.edit_uid.textChanged.connect(self.values_changed)
        self.edit_password.textChanged.connect(self.values_changed)
        self.edit_password_repeat.textChanged.connect(self.values_changed)
        self.edit_salt.textChanged.connect(self.values_changed)
        self.edit_pubkey.textChanged.connect(self.values_changed)
        self.button_generate.clicked.connect(self.action_show_pubkey)
        self.text_license.setReadOnly(True)

        self.combo_scrypt_params.currentIndexChanged.connect(self.handle_combo_change)
        self.scrypt_params = ScryptParams(4096, 16, 1)
        self.spin_n.setMaximum(2 ** 20)
        self.spin_n.setValue(self.scrypt_params.N)
        self.spin_n.valueChanged.connect(self.handle_n_change)
        self.spin_r.setMaximum(128)
        self.spin_r.setValue(self.scrypt_params.r)
        self.spin_r.valueChanged.connect(self.handle_r_change)
        self.spin_p.setMaximum(128)
        self.spin_p.setValue(self.scrypt_params.p)
        self.spin_p.valueChanged.connect(self.handle_p_change)
        self.label_info.setTextFormat(Qt.RichText)

    def handle_combo_change(self, index):
        strengths = [
            (2 ** 12, 16, 1),
            (2 ** 14, 32, 2),
            (2 ** 16, 32, 4),
            (2 ** 18, 64, 8),
        ]
        self.spin_n.blockSignals(True)
        self.spin_r.blockSignals(True)
        self.spin_p.blockSignals(True)
        self.spin_n.setValue(strengths[index][0])
        self.spin_r.setValue(strengths[index][1])
        self.spin_p.setValue(strengths[index][2])
        self.spin_n.blockSignals(False)
        self.spin_r.blockSignals(False)
        self.spin_p.blockSignals(False)

    def set_license(self, currency):
        license_text = self.tr(G1_LICENCE)
        self.text_license.setText(license_text)

    def handle_n_change(self, value):
        spinbox = self.sender()
        self.scrypt_params.N = ConnectionConfigView.compute_power_of_2(spinbox, value, self.scrypt_params.N)

    def handle_r_change(self, value):
        spinbox = self.sender()
        self.scrypt_params.r = ConnectionConfigView.compute_power_of_2(spinbox, value, self.scrypt_params.r)

    def handle_p_change(self, value):
        spinbox = self.sender()
        self.scrypt_params.p = ConnectionConfigView.compute_power_of_2(spinbox, value, self.scrypt_params.p)

    @staticmethod
    def compute_power_of_2(spinbox, value, param):
        if value > 1:
            if value > param:
                value = pow(2, ceil(log(value) / log(2)))
            else:
                value -= 1
                value = 2 ** int(log(value, 2))
        else:
            value = 1

        spinbox.blockSignals(True)
        spinbox.setValue(value)
        spinbox.blockSignals(False)

        return value

    def display_info(self, info):
        self.label_info.setText(info)

    def set_currency(self, currency):
        self.label_currency.setText(currency)

    def add_node_parameters(self):
        server = self.lineedit_add_address.text()
        port = self.spinbox_add_port.value()
        return server, port

    async def show_success(self, notification):
        if notification:
            toast.display(self.tr("UID broadcast"), self.tr("Identity broadcasted to the network"))
        else:
            await QAsyncMessageBox.information(self, self.tr("UID broadcast"),
                                               self.tr("Identity broadcasted to the network"))

    def show_error(self, notification, error_txt):
        if notification:
            toast.display(self.tr("UID broadcast"), error_txt)
        self.label_info.setText(self.tr("Error") + " " + error_txt)

    def set_nodes_model(self, model):
        self.tree_peers.setModel(model)

    def set_creation_layout(self, currency):
        """
        Hide unecessary buttons and display correct title
        """
        self.setWindowTitle(self.tr("New connection to {0} network").format(ROOT_SERVERS[currency]["display"]))

    def action_show_pubkey(self):
        salt = self.edit_salt.text()
        password = self.edit_password.text()
        pubkey = SigningKey(salt, password, self.scrypt_params).pubkey
        self.label_info.setText(pubkey)

    def account_name(self):
        return self.edit_account_name.text()

    def set_communities_list_model(self, model):
        """
        Set communities list model
        :param sakia.models.communities.CommunitiesListModel model:
        """
        self.list_communities.setModel(model)

    def stream_log(self, log):
        """
        Add log to
        :param str log:
        """
        self.plain_text_edit.appendPlainText(log)

    def progress(self, step_ratio):
        """

        :param float ratio: the ratio of progress of current step (between 0 and 1)
        :return:
        """
        SMOOTHING_FACTOR = 0.005
        if self.timer.elapsed() > 0:
            value = self.progress_bar.value()
            next_value = value + 1000000*step_ratio
            speed_percent_by_ms = (next_value - value) / self.timer.elapsed()
            self.average_speed = SMOOTHING_FACTOR * self.last_speed + (1 - SMOOTHING_FACTOR) * self.average_speed
            remaining = (self.progress_bar.maximum() - next_value) / self.average_speed
            self.last_speed = speed_percent_by_ms
            displayed_remaining_time = QDateTime.fromTime_t(remaining).toUTC().toString("hh:mm:ss")
            self.progress_bar.setFormat(self.tr("{0} remaining...".format(displayed_remaining_time)))
            self.progress_bar.setValue(next_value)
            self.timer.restart()

    def set_progress_steps(self, steps):
        self.progress_bar.setValue(0)
        self.timer.start()
        self.progress_bar.setMaximum(steps*1000000)

    def set_step(self, step):
        self.progress_bar.setValue(step * 1000000)

    async def show_register_message(self, blockchain_parameters):
        """

        :param sakia.data.entities.BlockchainParameters blockchain_parameters:
        :return:
        """
        days, hours, minutes, seconds = timestamp_to_dhms(blockchain_parameters.idty_window)
        expiration_time_str = self.tr("{days} days, {hours}h  and {min}min").format(days=days,
                                                                                    hours=hours,
                                                                                    min=minutes)

        dialog = QDialog(self)
        about_dialog = Ui_CongratulationPopup()
        about_dialog.setupUi(dialog)
        dialog.setWindowTitle("Registration")
        about_dialog.label.setText(self.tr("""
<p><b>Congratulations !</b><br>
<br>
You just published your identity to the network.<br>
For your identity to be registered, you will need<br>
<b>{certs} certifications</b> from members.<br>
Once you got the required certifications, <br>
you will be able to validate your registration<br>
by <b>publishing your membership request !</b><br>
Please notice that your identity document <br>
<b>will expire in {expiration_time_str}.</b><br>
If you failed to get {certs} certifications before this time, <br>
the process will have to be restarted from scratch.</p>
""".format(certs=blockchain_parameters.sig_qty, expiration_time_str=expiration_time_str)))

        await dialog_async_exec(dialog)
Exemplo n.º 4
0
class GameView(QWidget):
    """GameView UI class handles drawing the game and also keeps the Game instance"""
    def __init__(self):
        super().__init__()
        self.game = Game()
        self.game.new_game(Coordinate(20, 20, 2))
        self.elapsed_timer = QElapsedTimer()
        self.elapsed_timer.start()

    def keyPressEvent(self, event):  # pylint: disable=invalid-name
        """Redefined function that gets called periodically by the base class.
        Disable movement when maze is solved or game is won."""
        if not self.game.get_field().is_solved() and not self.game.is_won():
            if event.key() == Qt.Key_Right:
                self.game.get_player().move_player(self.game.get_field(),
                                                   Cell.RIGHT)
            if event.key() == Qt.Key_Left:
                self.game.get_player().move_player(self.game.get_field(),
                                                   Cell.LEFT)
            if event.key() == Qt.Key_Up:
                self.game.get_player().move_player(self.game.get_field(),
                                                   Cell.BACK)
            if event.key() == Qt.Key_Down:
                self.game.get_player().move_player(self.game.get_field(),
                                                   Cell.FRONT)
            if event.key() == Qt.Key_Q:
                self.game.get_player().move_player(self.game.get_field(),
                                                   Cell.TOP)
            if event.key() == Qt.Key_A:
                self.game.get_player().move_player(self.game.get_field(),
                                                   Cell.BOTTOM)
        self.update()

    def paintEvent(self, event):  # pylint: disable=invalid-name,unused-argument
        """Redefined function that gets called periodically by the base class.
        Used to call drawing functions."""
        painter = QPainter()
        painter.begin(self)
        self.draw_game(painter)
        painter.end()

    def refresh(self):
        """Periodically called from GameMainUI and used to update player position if the
        auto-solve option has been enabled"""
        if self.game.get_field().is_solved() and not self.game.is_won():
            player_position = self.game.get_player().get_position()
            solution_direction = self.game.get_field().get_cell(
                player_position).get_solution()
            self.game.get_player().move_player(self.game.get_field(),
                                               solution_direction)

    def solve_game(self):
        """Called by GameMainUI to solve the maze"""
        goal_position = self.game.get_field().get_goal()
        player_position = self.game.get_player().get_position()
        return self.game.get_field().solve_maze(player_position, goal_position)

    def draw_game(self, painter):
        """Called by paintEvent to initialize the actual drawing of the game"""
        line_pen = QPen(Qt.black, 1, Qt.SolidLine)
        painter.setPen(line_pen)

        #Calculate offsets to move view acc. to position or center the maze if whole maze fits
        if self.width() < self.game.get_field().get_width() * TILESIZE:
            x_offset = self.width() / 2 - self.game.get_player().get_position(
            ).x * TILESIZE
        else:
            x_offset = (self.width() -
                        self.game.get_field().get_width() * TILESIZE) / 2

        if self.height() < self.game.get_field().get_width() * TILESIZE:
            y_offset = self.height() / 2 - self.game.get_player().get_position(
            ).y * TILESIZE
        else:
            y_offset = (self.height() -
                        self.game.get_field().get_height() * TILESIZE) / 2

        #Draw the current floor and solution if the maze is solved
        z = self.game.get_player().get_floor()
        for y in range(self.game.get_field().get_height()):
            for x in range(self.game.get_field().get_width()):
                coordinates = Coordinate(x, y, z)
                self.draw_maze(painter, x_offset, y_offset, coordinates)
                if self.game.get_field().get_cell(coordinates).get_solution():
                    self.draw_solution(painter, x_offset, y_offset,
                                       coordinates)

        #Draw the player
        self.draw_player(painter, x_offset, y_offset)

    def draw_maze(self, painter, x_offset, y_offset, coordinates):
        """Draws the maze"""
        maze_pen = QPen(Qt.black, 1, Qt.SolidLine)
        painter.setPen(maze_pen)
        cell = self.game.get_field().get_cell(coordinates)
        x = coordinates.x
        y = coordinates.y

        if cell.is_wall(Cell.BACK) and not cell.is_entrance():
            painter.drawLine(x * TILESIZE + x_offset, y * TILESIZE + y_offset,
                             (x + 1) * TILESIZE + x_offset,
                             y * TILESIZE + y_offset)
        if cell.is_wall(Cell.FRONT) and not cell.is_goal():
            painter.drawLine(x * TILESIZE + x_offset,
                             (y + 1) * TILESIZE + y_offset,
                             (x + 1) * TILESIZE + x_offset,
                             (y + 1) * TILESIZE + y_offset)
        if cell.is_wall(Cell.LEFT):
            painter.drawLine(x * TILESIZE + x_offset, y * TILESIZE + y_offset,
                             x * TILESIZE + x_offset,
                             (y + 1) * TILESIZE + y_offset)
        if cell.is_wall(Cell.RIGHT):
            painter.drawLine(
                (x + 1) * TILESIZE + x_offset, y * TILESIZE + y_offset,
                (x + 1) * TILESIZE + x_offset, (y + 1) * TILESIZE + y_offset)

        if not cell.is_wall(Cell.TOP):
            #Draw ladders
            painter.drawLine(x * TILESIZE + 6 + x_offset,
                             y * TILESIZE + 2 + y_offset,
                             x * TILESIZE + 6 + x_offset,
                             (y + 1) * TILESIZE - 6 + y_offset)
            painter.drawLine((x + 1) * TILESIZE - 6 + x_offset,
                             y * TILESIZE + 2 + y_offset,
                             (x + 1) * TILESIZE - 6 + x_offset,
                             (y + 1) * TILESIZE - 6 + y_offset)
            painter.drawLine(x * TILESIZE + 6 + x_offset,
                             y * TILESIZE + 4 + y_offset,
                             (x + 1) * TILESIZE - 6 + x_offset,
                             y * TILESIZE + 4 + y_offset)
            painter.drawLine(x * TILESIZE + 6 + x_offset,
                             y * TILESIZE + 8 + y_offset,
                             (x + 1) * TILESIZE - 6 + x_offset,
                             y * TILESIZE + 8 + y_offset)
            painter.drawLine(x * TILESIZE + 6 + x_offset,
                             y * TILESIZE + 12 + y_offset,
                             (x + 1) * TILESIZE - 6 + x_offset,
                             y * TILESIZE + 12 + y_offset)

        if not cell.is_wall(Cell.BOTTOM):
            painter.drawEllipse(x * TILESIZE + 2 + x_offset,
                                y * TILESIZE + TILESIZE / 2 + y_offset,
                                TILESIZE - 4, TILESIZE / 2 - 4)

    def draw_solution(self, painter, x_offset, y_offset, coordinates):
        """Draws the solution"""
        solution_pen = QPen(Qt.green, 1, Qt.SolidLine)
        painter.setPen(solution_pen)
        cell = self.game.get_field().get_cell(coordinates)
        x = coordinates.x
        y = coordinates.y

        if cell.get_solution() == Cell.RIGHT:
            painter.drawLine(x * TILESIZE + x_offset + TILESIZE / 2,
                             y * TILESIZE + y_offset + TILESIZE / 2,
                             (x + 1) * TILESIZE + x_offset + TILESIZE / 2,
                             y * TILESIZE + y_offset + TILESIZE / 2)
        if cell.get_solution() == Cell.LEFT:
            painter.drawLine((x - 1) * TILESIZE + x_offset + TILESIZE / 2,
                             y * TILESIZE + y_offset + TILESIZE / 2,
                             x * TILESIZE + x_offset + TILESIZE / 2,
                             y * TILESIZE + y_offset + TILESIZE / 2)
        if cell.get_solution() == Cell.BACK:
            painter.drawLine(x * TILESIZE + x_offset + TILESIZE / 2,
                             y * TILESIZE + y_offset + TILESIZE / 2,
                             x * TILESIZE + x_offset + TILESIZE / 2,
                             (y - 1) * TILESIZE + y_offset + TILESIZE / 2)
        if cell.get_solution() == Cell.FRONT:
            painter.drawLine(x * TILESIZE + x_offset + TILESIZE / 2,
                             (y + 1) * TILESIZE + y_offset + TILESIZE / 2,
                             x * TILESIZE + x_offset + TILESIZE / 2,
                             y * TILESIZE + y_offset + TILESIZE / 2)

    def draw_player(self, painter, x_offset, y_offset):
        """Draws the player"""
        player_pen = QPen(Qt.red, 1, Qt.SolidLine)
        painter.setPen(player_pen)
        player_position = self.game.get_player().get_position()
        painter.drawEllipse(player_position.x * TILESIZE + 2 + x_offset,
                            player_position.y * TILESIZE + 2 + y_offset,
                            TILESIZE - 4, TILESIZE - 4)

    def reset_timer(self):
        """Resets the internal timer, should be called always when the current time is updated
        to the game instance. This means when saving or loading games."""
        self.elapsed_timer.restart()

    def get_game_instance(self):
        """Returns the game instance"""
        return self.game

    def store_time(self):
        """Stores the current time in the Game instance"""
        self.game.set_elapsed_time(self.get_time() / 1000)

    def get_time(self):
        """Need to add time stored in the game instance to properly restore time from saved games"""
        return self.elapsed_timer.elapsed(
        ) + self.game.get_elapsed_time() * 1000
Exemplo n.º 5
0
class RoomRow(QFrame):
    def __init__(self, idRoom):
        super(RoomRow, self).__init__()
        self.setStyleSheet(
            'QFrame {background: #757575; border-radius: 10px; margin: 0px}')
        self.setFixedHeight(50)

        self.callModel = service.CallModel()

        self.elapsedTimer = QElapsedTimer()
        self.elapsedTimer.start()
        self.timerSingle = QTimer()
        self.timerSingle.setSingleShot(True)
        self.timerSingle.timeout.connect(self.deactivateBlink)

        self.timer = QTimer()
        self.timer.timeout.connect(self.blink)
        self.stopwatch = QTimer()
        self.stopwatch.timeout.connect(self.updateStopwatch)

        self.types = {
            'azul': '#0d47a1',
            'normal': '#00e676',
            'bano': '#fdd835'
        }
        self.flagBlink = True
        self.isActive = False
        self.callType = None

        self.room = QLabel(idRoom)
        self.room.setStyleSheet('font: 25px; color: white')
        self.room.setAlignment(Qt.AlignCenter)
        self.timePassed = QLabel('—')
        self.timePassed.setStyleSheet('color: white')
        self.timePassed.setFont(QFont('DS-Digital', 25))
        self.timePassed.setAlignment(Qt.AlignCenter)

        hbox = QHBoxLayout(self)
        hbox.addWidget(self.room)
        hbox.addWidget(self.timePassed)

    def activate(self, callType):
        self.isActive = True
        self.callType = callType

        self.callModel.callType.setIcon(callType)
        self.elapsedTimer.restart()
        self.timer.start(500)
        self.stopwatch.start(1000)
        self.callModel.player.playSound(callType)

        self.timerSingle.start(self.callModel.alarmDuration)

    def deactivate(self, callType):
        self.isActive = False
        self.stopwatch.stop()
        self.timer.stop()
        self.timerSingle.stop()
        self.disable()
        self.timePassed.setText('—')
        self.callModel.player.stopSound(callType)

    def deactivateBlink(self):
        self.timer.stop()
        if self.isActive:
            self.enable()
            if (self.callType != 'azul'):
                self.callModel.player.stopSound(self.callType)

    def updateStopwatch(self):
        self.timePassed.setText(
            str(datetime.timedelta(seconds=self.elapsedTimer.elapsed() /
                                   1000)))

    def blink(self):
        if self.flagBlink:
            self.enable()
        else:
            self.disable()
        self.flagBlink = not self.flagBlink

    def enable(self, callType=None):
        if callType:
            self.setStyleSheet('QFrame {background:' + self.types[callType] +
                               '; border-radius: 10px; margin: 0px}')
            self.isActive = True
        else:
            self.setStyleSheet('QFrame {background:' +
                               self.types[self.callType] +
                               '; border-radius: 10px; margin: 0px}')

    def disable(self):
        self.setStyleSheet(
            'QFrame {background: #757575; border-radius: 10px; margin: 0px}')
Exemplo n.º 6
0
class Browser(QTreeView):
    """
    Class used to display a file system tree.
    
    Via the context menu that
    is displayed by a right click the user can select various actions on
    the selected file.
    
    @signal sourceFile(filename) emitted to open a Python file at a line (str)
    @signal sourceFile(filename, lineno) emitted to open a Python file at a
        line (str, int)
    @signal sourceFile(filename, lineno, type) emitted to open a Python file
        at a line giving an explicit file type (str, int, str)
    @signal sourceFile(filename, linenos) emitted to open a Python file giving
        a list of lines(str, list)
    @signal designerFile(filename) emitted to open a Qt-Designer file (str)
    @signal linguistFile(filename) emitted to open a Qt-Linguist (*.ts)
        file (str)
    @signal trpreview(filenames) emitted to preview Qt-Linguist (*.qm)
        files (list of str)
    @signal trpreview(filenames, ignore) emitted to preview Qt-Linguist (*.qm)
        files indicating whether non-existent files shall be ignored
        (list of str, bool)
    @signal projectFile(filename) emitted to open an eric project file (str)
    @signal multiProjectFile(filename) emitted to open an eric multi project
        file (str)
    @signal pixmapFile(filename) emitted to open a pixmap file (str)
    @signal pixmapEditFile(filename) emitted to edit a pixmap file (str)
    @signal svgFile(filename) emitted to open a SVG file (str)
    @signal binaryFile(filename) emitted to open a file as binary (str)
    @signal unittestOpen(filename) emitted to open a Python file for a
        unit test (str)
    """
    sourceFile = pyqtSignal((str, ), (str, int), (str, list), (str, int, str))
    designerFile = pyqtSignal(str)
    linguistFile = pyqtSignal(str)
    trpreview = pyqtSignal((list, ), (list, bool))
    projectFile = pyqtSignal(str)
    multiProjectFile = pyqtSignal(str)
    pixmapFile = pyqtSignal(str)
    pixmapEditFile = pyqtSignal(str)
    svgFile = pyqtSignal(str)
    binaryFile = pyqtSignal(str)
    unittestOpen = pyqtSignal(str)

    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent parent widget (QWidget)
        """
        super(Browser, self).__init__(parent)

        self.setWindowTitle(
            QCoreApplication.translate('Browser', 'File-Browser'))
        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))

        self.__model = BrowserModel()
        self.__sortModel = BrowserSortFilterProxyModel()
        self.__sortModel.setSourceModel(self.__model)
        self.setModel(self.__sortModel)

        self.selectedItemsFilter = [BrowserFileItem]

        self._activating = False

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self._contextMenuRequested)
        self.activated.connect(self._openItem)
        self.expanded.connect(self._resizeColumns)
        self.collapsed.connect(self._resizeColumns)

        self.setWhatsThis(
            QCoreApplication.translate(
                'Browser', """<b>The Browser Window</b>"""
                """<p>This allows you to easily navigate the hierarchy of"""
                """ directories and files on your system, identify the Python"""
                """ programs and open them up in a Source Viewer window. The"""
                """ window displays several separate hierarchies.</p>"""
                """<p>The first hierarchy is only shown if you have opened a"""
                """ program for debugging and its root is the directory"""
                """ containing that program. Usually all of the separate files"""
                """ that make up a Python application are held in the same"""
                """ directory, so this hierarchy gives you easy access to most"""
                """ of what you will need.</p>"""
                """<p>The next hierarchy is used to easily navigate the"""
                """ directories that are specified in the Python"""
                """ <tt>sys.path</tt> variable.</p>"""
                """<p>The remaining hierarchies allow you navigate your system"""
                """ as a whole. On a UNIX system there will be a hierarchy with"""
                """ <tt>/</tt> at its root and another with the user home"""
                """ directory. On a Windows system there will be a hierarchy for"""
                """ each drive on the"""
                """ system.</p>"""
                """<p>Python programs (i.e. those with a <tt>.py</tt> file name"""
                """ suffix) are identified in the hierarchies with a Python"""
                """ icon. The right mouse button will popup a menu which lets"""
                """ you open the file in a Source Viewer window, open the file"""
                """ for debugging or use it for a unittest run.</p>"""
                """<p>The context menu of a class, function or method allows you"""
                """ to open the file defining this class, function or method and"""
                """ will ensure, that the correct source line is visible.</p>"""
                """<p>Qt-Designer files (i.e. those with a <tt>.ui</tt> file"""
                """ name suffix) are shown with a Designer icon. The context"""
                """ menu of these files allows you to start Qt-Designer with"""
                """ that file.</p>"""
                """<p>Qt-Linguist files (i.e. those with a <tt>.ts</tt> file"""
                """ name suffix) are shown with a Linguist icon. The context"""
                """ menu of these files allows you to start Qt-Linguist with"""
                """ that file.</p>"""))

        self.__createPopupMenus()

        self._init()  # perform common initialization tasks

        self._keyboardSearchString = ""
        self._keyboardSearchTimer = QElapsedTimer()
        self._keyboardSearchTimer.invalidate()

    def _init(self):
        """
        Protected method to perform initialization tasks common to this
        base class and all derived classes.
        """
        self.setRootIsDecorated(True)
        self.setAlternatingRowColors(True)

        header = self.header()
        header.setSortIndicator(0, Qt.AscendingOrder)
        header.setSortIndicatorShown(True)
        header.setSectionsClickable(True)

        self.setSortingEnabled(True)

        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.header().setStretchLastSection(True)
        self.headerSize0 = 0
        self.layoutDisplay()

    def layoutDisplay(self):
        """
        Public slot to perform a layout operation.
        """
        self._resizeColumns(QModelIndex())
        self._resort()

    def _resizeColumns(self, index):
        """
        Protected slot to resize the view when items get expanded or collapsed.
        
        @param index index of item (QModelIndex)
        """
        w = max(100, self.sizeHintForColumn(0))
        if w != self.headerSize0:
            self.header().resizeSection(0, w)
            self.headerSize0 = w

    def _resort(self):
        """
        Protected slot to resort the tree.
        """
        self.model().sort(self.header().sortIndicatorSection(),
                          self.header().sortIndicatorOrder())

    def __createPopupMenus(self):
        """
        Private method to generate the various popup menus.
        """
        # create the popup menu for source files
        self.sourceMenu = QMenu(self)
        self.sourceMenu.addAction(
            QCoreApplication.translate('Browser', 'Open'), self._openItem)
        self.unittestAct = self.sourceMenu.addAction(
            QCoreApplication.translate('Browser', 'Run unittest...'),
            self.handleUnittest)
        self.sourceMenu.addSeparator()
        self.mimeTypeAct = self.sourceMenu.addAction(
            QCoreApplication.translate('Browser', 'Show Mime-Type'),
            self.__showMimeType)
        self.sourceMenu.addSeparator()
        self.sourceMenu.addAction(
            QCoreApplication.translate('Browser', 'Copy Path to Clipboard'),
            self._copyToClipboard)

        # create the popup menu for general use
        self.menu = QMenu(self)
        self.menu.addAction(QCoreApplication.translate('Browser', 'Open'),
                            self._openItem)
        self.menu.addAction(
            QCoreApplication.translate('Browser', 'Open in Hex Editor'),
            self._openHexEditor)
        self.editPixmapAct = self.menu.addAction(
            QCoreApplication.translate('Browser', 'Open in Icon Editor'),
            self._editPixmap)
        self.menu.addSeparator()
        self.mimeTypeAct = self.menu.addAction(
            QCoreApplication.translate('Browser', 'Show Mime-Type'),
            self.__showMimeType)
        self.menu.addSeparator()
        self.menu.addAction(
            QCoreApplication.translate('Browser', 'Copy Path to Clipboard'),
            self._copyToClipboard)

        # create the menu for multiple selected files
        self.multiMenu = QMenu(self)
        self.multiMenu.addAction(QCoreApplication.translate('Browser', 'Open'),
                                 self._openItem)

        # create the directory menu
        self.dirMenu = QMenu(self)
        self.dirMenu.addAction(
            QCoreApplication.translate('Browser', 'New toplevel directory...'),
            self.__newToplevelDir)
        self.addAsTopLevelAct = self.dirMenu.addAction(
            QCoreApplication.translate('Browser', 'Add as toplevel directory'),
            self.__addAsToplevelDir)
        self.removeFromToplevelAct = self.dirMenu.addAction(
            QCoreApplication.translate('Browser', 'Remove from toplevel'),
            self.__removeToplevel)
        self.dirMenu.addSeparator()
        self.dirMenu.addAction(
            QCoreApplication.translate('Browser', 'Refresh directory'),
            self.__refreshDirectory)
        self.dirMenu.addSeparator()
        self.dirMenu.addAction(
            QCoreApplication.translate('Browser', 'Find in this directory'),
            self.__findInDirectory)
        self.dirMenu.addAction(
            QCoreApplication.translate('Browser',
                                       'Find && Replace in this directory'),
            self.__replaceInDirectory)
        self.dirMenu.addAction(
            QCoreApplication.translate('Browser', 'Copy Path to Clipboard'),
            self._copyToClipboard)

        # create the attribute menu
        self.gotoMenu = QMenu(QCoreApplication.translate('Browser', "Goto"),
                              self)
        self.gotoMenu.aboutToShow.connect(self._showGotoMenu)
        self.gotoMenu.triggered.connect(self._gotoAttribute)

        self.attributeMenu = QMenu(self)
        self.attributeMenu.addAction(
            QCoreApplication.translate('Browser', 'New toplevel directory...'),
            self.__newToplevelDir)
        self.attributeMenu.addSeparator()
        self.attributeMenu.addMenu(self.gotoMenu)

        # create the background menu
        self.backMenu = QMenu(self)
        self.backMenu.addAction(
            QCoreApplication.translate('Browser', 'New toplevel directory...'),
            self.__newToplevelDir)

    def mouseDoubleClickEvent(self, mouseEvent):
        """
        Protected method of QAbstractItemView.
        
        Reimplemented to disable expanding/collapsing of items when
        double-clicking. Instead the double-clicked entry is opened.
        
        @param mouseEvent the mouse event (QMouseEvent)
        """
        index = self.indexAt(mouseEvent.pos())
        if index.isValid():
            itm = self.model().item(index)
            if isinstance(itm, (BrowserDirectoryItem, BrowserImportsItem,
                                ProjectBrowserSimpleDirectoryItem,
                                BrowserSysPathItem, BrowserGlobalsItem)):
                self.setExpanded(index, not self.isExpanded(index))
            else:
                self._openItem()

    def _contextMenuRequested(self, coord):
        """
        Protected slot to show the context menu of the listview.
        
        @param coord the position of the mouse pointer (QPoint)
        """
        categories = self.getSelectedItemsCountCategorized([
            BrowserDirectoryItem, BrowserFileItem, BrowserClassItem,
            BrowserMethodItem
        ])
        cnt = categories["sum"]
        bfcnt = categories[str(BrowserFileItem)]
        if cnt > 1 and cnt == bfcnt:
            self.multiMenu.popup(self.mapToGlobal(coord))
        else:
            index = self.indexAt(coord)

            if index.isValid():
                self.setCurrentIndex(index)
                flags = QItemSelectionModel.SelectionFlags(
                    QItemSelectionModel.ClearAndSelect
                    | QItemSelectionModel.Rows)
                self.selectionModel().select(index, flags)

                itm = self.model().item(index)
                coord = self.mapToGlobal(coord)
                if isinstance(itm, BrowserFileItem):
                    if itm.isPython3File():
                        if itm.fileName().endswith('.py'):
                            self.unittestAct.setEnabled(True)
                        else:
                            self.unittestAct.setEnabled(False)
                        self.sourceMenu.popup(coord)
                    else:
                        self.editPixmapAct.setVisible(itm.isPixmapFile())
                        self.menu.popup(coord)
                elif isinstance(
                        itm,
                    (BrowserClassItem, BrowserMethodItem, BrowserImportItem)):
                    self.editPixmapAct.setVisible(False)
                    self.menu.popup(coord)
                elif isinstance(itm, BrowserClassAttributeItem):
                    self.attributeMenu.popup(coord)
                elif isinstance(itm, BrowserDirectoryItem):
                    if not index.parent().isValid():
                        self.removeFromToplevelAct.setEnabled(True)
                        self.addAsTopLevelAct.setEnabled(False)
                    else:
                        self.removeFromToplevelAct.setEnabled(False)
                        self.addAsTopLevelAct.setEnabled(True)
                    self.dirMenu.popup(coord)
                else:
                    self.backMenu.popup(coord)
            else:
                self.backMenu.popup(self.mapToGlobal(coord))

    def _showGotoMenu(self):
        """
        Protected slot to prepare the goto submenu of the attribute menu.
        """
        self.gotoMenu.clear()

        itm = self.model().item(self.currentIndex())
        linenos = itm.linenos()
        fileName = itm.fileName()

        for lineno in sorted(linenos):
            act = self.gotoMenu.addAction(
                QCoreApplication.translate('Browser',
                                           "Line {0}").format(lineno))
            act.setData([fileName, lineno])

    def _gotoAttribute(self, act):
        """
        Protected slot to handle the selection of the goto menu.
        
        @param act reference to the action (E5Action)
        """
        fileName, lineno = act.data()
        self.sourceFile[str, int].emit(fileName, lineno)

    def handlePreferencesChanged(self):
        """
        Public slot used to handle the preferencesChanged signal.
        """
        self.model().preferencesChanged()
        self._resort()

    def _openItem(self):
        """
        Protected slot to handle the open popup menu entry.
        """
        itmList = self.getSelectedItems([
            BrowserFileItem, BrowserClassItem, BrowserMethodItem,
            BrowserClassAttributeItem, BrowserImportItem
        ])

        if not self._activating:
            self._activating = True
            for itm in itmList:
                if isinstance(itm, BrowserFileItem):
                    if itm.isPython2File():
                        self.sourceFile[str].emit(itm.fileName())
                    elif itm.isPython3File():
                        self.sourceFile[str].emit(itm.fileName())
                    elif itm.isRubyFile():
                        self.sourceFile[str, int,
                                        str].emit(itm.fileName(), -1, "Ruby")
                    elif itm.isDFile():
                        self.sourceFile[str, int,
                                        str].emit(itm.fileName(), -1, "D")
                    elif itm.isDesignerFile():
                        self.designerFile.emit(itm.fileName())
                    elif itm.isLinguistFile():
                        if itm.fileExt() == '.ts':
                            self.linguistFile.emit(itm.fileName())
                        else:
                            self.trpreview.emit([itm.fileName()])
                    elif itm.isProjectFile():
                        self.projectFile.emit(itm.fileName())
                    elif itm.isMultiProjectFile():
                        self.multiProjectFile.emit(itm.fileName())
                    elif itm.isIdlFile():
                        self.sourceFile[str].emit(itm.fileName())
                    elif itm.isProtobufFile():
                        self.sourceFile[str].emit(itm.fileName())
                    elif itm.isResourcesFile():
                        self.sourceFile[str].emit(itm.fileName())
                    elif itm.isSvgFile():
                        self.svgFile.emit(itm.fileName())
                    elif itm.isPixmapFile():
                        self.pixmapFile.emit(itm.fileName())
                    else:
                        if Utilities.MimeTypes.isTextFile(itm.fileName()):
                            self.sourceFile[str].emit(itm.fileName())
                        else:
                            QDesktopServices.openUrl(QUrl(itm.fileName()))
                elif isinstance(itm, BrowserClassItem):
                    self.sourceFile[str, int].emit(itm.fileName(),
                                                   itm.classObject().lineno)
                elif isinstance(itm, BrowserMethodItem):
                    self.sourceFile[str, int].emit(itm.fileName(),
                                                   itm.functionObject().lineno)
                elif isinstance(itm, BrowserClassAttributeItem):
                    self.sourceFile[str,
                                    int].emit(itm.fileName(),
                                              itm.attributeObject().lineno)
                elif isinstance(itm, BrowserImportItem):
                    self.sourceFile[str, list].emit(itm.fileName(),
                                                    itm.linenos())
            self._activating = False

    def __showMimeType(self):
        """
        Private slot to show the mime type of the selected entry.
        """
        itmList = self.getSelectedItems([
            BrowserFileItem, BrowserClassItem, BrowserMethodItem,
            BrowserClassAttributeItem, BrowserImportItem
        ])
        if itmList:
            mimetype = Utilities.MimeTypes.mimeType(itmList[0].fileName())
            if mimetype is None:
                E5MessageBox.warning(
                    self,
                    QCoreApplication.translate('Browser', "Show Mime-Type"),
                    QCoreApplication.translate(
                        'Browser', """The mime type of the file could not be"""
                        """ determined."""))
            elif mimetype.split("/")[0] == "text":
                E5MessageBox.information(
                    self,
                    QCoreApplication.translate('Browser', "Show Mime-Type"),
                    QCoreApplication.translate(
                        'Browser',
                        """The file has the mime type <b>{0}</b>.""").format(
                            mimetype))
            else:
                textMimeTypesList = Preferences.getUI("TextMimeTypes")
                if mimetype in textMimeTypesList:
                    E5MessageBox.information(
                        self,
                        QCoreApplication.translate('Browser',
                                                   "Show Mime-Type"),
                        QCoreApplication.translate(
                            'Browser',
                            """The file has the mime type <b>{0}</b>.""").
                        format(mimetype))
                else:
                    ok = E5MessageBox.yesNo(
                        self,
                        QCoreApplication.translate('Browser',
                                                   "Show Mime-Type"),
                        QCoreApplication.translate(
                            'Browser',
                            """The file has the mime type <b>{0}</b>."""
                            """<br/> Shall it be added to the list of"""
                            """ text mime types?""").format(mimetype))
                    if ok:
                        textMimeTypesList.append(mimetype)
                        Preferences.setUI("TextMimeTypes", textMimeTypesList)

    def _editPixmap(self):
        """
        Protected slot to handle the open in icon editor popup menu entry.
        """
        itmList = self.getSelectedItems([BrowserFileItem])

        for itm in itmList:
            if isinstance(itm, BrowserFileItem):
                if itm.isPixmapFile():
                    self.pixmapEditFile.emit(itm.fileName())

    def _openHexEditor(self):
        """
        Protected slot to handle the open in hex editor popup menu entry.
        """
        itmList = self.getSelectedItems([BrowserFileItem])

        for itm in itmList:
            if isinstance(itm, BrowserFileItem):
                self.binaryFile.emit(itm.fileName())

    def _copyToClipboard(self):
        """
        Protected method to copy the text shown for an entry to the clipboard.
        """
        itm = self.model().item(self.currentIndex())
        try:
            fn = itm.fileName()
        except AttributeError:
            try:
                fn = itm.dirName()
            except AttributeError:
                fn = ""

        if fn:
            cb = QApplication.clipboard()
            cb.setText(fn)

    def handleUnittest(self):
        """
        Public slot to handle the unittest popup menu entry.
        """
        try:
            index = self.currentIndex()
            itm = self.model().item(index)
            pyfn = itm.fileName()
        except AttributeError:
            pyfn = None

        if pyfn is not None:
            self.unittestOpen.emit(pyfn)

    def __newToplevelDir(self):
        """
        Private slot to handle the New toplevel directory popup menu entry.
        """
        dname = E5FileDialog.getExistingDirectory(
            None,
            QCoreApplication.translate('Browser', "New toplevel directory"),
            "", E5FileDialog.Options(E5FileDialog.ShowDirsOnly))
        if dname:
            dname = os.path.abspath(Utilities.toNativeSeparators(dname))
            self.__model.addTopLevelDir(dname)

    def __removeToplevel(self):
        """
        Private slot to handle the Remove from toplevel popup menu entry.
        """
        index = self.currentIndex()
        sindex = self.model().mapToSource(index)
        self.__model.removeToplevelDir(sindex)

    def __addAsToplevelDir(self):
        """
        Private slot to handle the Add as toplevel directory popup menu entry.
        """
        index = self.currentIndex()
        dname = self.model().item(index).dirName()
        self.__model.addTopLevelDir(dname)

    def __refreshDirectory(self):
        """
        Private slot to refresh a directory entry.
        """
        index = self.currentIndex()
        refreshDir = self.model().item(index).dirName()
        self.__model.directoryChanged(refreshDir)

    def __findInDirectory(self):
        """
        Private slot to handle the Find in directory popup menu entry.
        """
        index = self.currentIndex()
        searchDir = self.model().item(index).dirName()

        e5App().getObject("UserInterface").showFindFilesDialog(
            searchDir=searchDir)

    def __replaceInDirectory(self):
        """
        Private slot to handle the Find&Replace in directory popup menu entry.
        """
        index = self.currentIndex()
        searchDir = self.model().item(index).dirName()

        e5App().getObject("UserInterface").showReplaceFilesDialog(
            searchDir=searchDir)

    def handleProgramChange(self, fn):
        """
        Public slot to handle the programChange signal.
        
        @param fn file name (string)
        """
        self.__model.programChange(os.path.dirname(fn))

    def handleInterpreterChanged(self, interpreter):
        """
        Public slot to handle a change of the debug client's interpreter.
        
        @param interpreter interpreter of the debug client (string)
        """
        self.__model.interpreterChanged(interpreter)

    def wantedItem(self, itm, filterList=None):
        """
        Public method to check type of an item.
        
        @param itm the item to check (BrowserItem)
        @param filterList list of classes to check against
        @return flag indicating item is a valid type (boolean)
        """
        if filterList is None:
            filterList = self.selectedItemsFilter
        for typ in filterList:
            if isinstance(itm, typ):
                return True
        return False

    def getSelectedItems(self, filterList=None):
        """
        Public method to get the selected items.
        
        @param filterList list of classes to check against
        @return list of selected items (list of BroweserItem)
        """
        selectedItems = []
        indexes = self.selectedIndexes()
        for index in indexes:
            if index.column() == 0:
                itm = self.model().item(index)
                if self.wantedItem(itm, filterList):
                    selectedItems.append(itm)
        return selectedItems

    def getSelectedItemsCount(self, filterList=None):
        """
        Public method to get the count of items selected.
        
        @param filterList list of classes to check against
        @return count of items selected (integer)
        """
        count = 0
        indexes = self.selectedIndexes()
        for index in indexes:
            if index.column() == 0:
                itm = self.model().item(index)
                if self.wantedItem(itm, filterList):
                    count += 1
        return count

    def getSelectedItemsCountCategorized(self, filterList=None):
        """
        Public method to get a categorized count of selected items.
        
        @param filterList list of classes to check against
        @return a dictionary containing the counts of items belonging
            to the individual filter classes. The keys of the dictionary
            are the string representation of the classes given in the
            filter (i.e. str(filterClass)). The dictionary contains
            an additional entry with key "sum", that stores the sum of
            all selected entries fulfilling the filter criteria.
        """
        if filterList is None:
            filterList = self.selectedItemsFilter
        categories = {}
        categories["sum"] = 0
        for typ in filterList:
            categories[str(typ)] = 0

        indexes = self.selectedIndexes()
        for index in indexes:
            if index.column() == 0:
                itm = self.model().item(index)
                for typ in filterList:
                    if isinstance(itm, typ):
                        categories["sum"] += 1
                        categories[str(typ)] += 1

        return categories

    def saveToplevelDirs(self):
        """
        Public slot to save the toplevel directories.
        """
        self.__model.saveToplevelDirs()

    def keyboardSearch(self, search):
        """
        Public function to search the tree via the keyboard.
        
        @param search the character entered via the keyboard
        @type str
        """
        if self.model().rowCount() == 0:
            return

        if self.currentIndex().isValid():
            startIndex = self.currentIndex()
        else:
            startIndex = self.model().index(0, 0)

        keyboardSearchTimeWasValid = self._keyboardSearchTimer.isValid()
        keyboardSearchTimeElapsed = self._keyboardSearchTimer.restart()
        if (not search or not keyboardSearchTimeWasValid
                or keyboardSearchTimeElapsed >
                QApplication.keyboardInputInterval()):
            self._keyboardSearchString = search.lower()
        else:
            self._keyboardSearchString += search.lower()

        index = startIndex
        found = False
        while True:
            name = self.model().data(index)
            if (name.lower().startswith(self._keyboardSearchString)
                    and self._keyboardSearchType(self.model().item(index))):
                found = True
                break

            index = self.indexBelow(index)
            if not index.isValid():
                index = self.model().index(0, 0)
            if index == startIndex:
                break

        if found:
            self.setCurrentIndex(index)

    def _keyboardSearchType(self, item):
        """
        Protected method to check, if the item is of the correct type.
        
        @param item reference to the item
        @type BrowserItem
        @return flag indicating a correct type
        @rtype bool
        """
        return isinstance(
            item, (BrowserDirectoryItem, BrowserFileItem, BrowserSysPathItem))
Exemplo n.º 7
0
class CalibrationWidget(QWidget):

    cursorPos = pyqtSignal(float, float, 'qint64')

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

        self._margin_x = 0.0
        self._margin_y = 0.0
        self._offset_x = 1.0
        self._offset_y = 1.0
        self._ampl_x = 1.0
        self._ampl_y = 1.0
        self._coeff_x = 5.0
        self._coeff_y = 4.0
        self._coeff_delta = 0.0
        self._t = 0.0
        self._circle_size = 20

        self._pen = QPen()
        self._pen.setWidth(2)
        self._pen.setColor(Qt.black)
        self._brush = QBrush(Qt.yellow)

        self._elapsed_timer = QElapsedTimer()
        self._timer = QTimer()
        self._timer.setInterval(1000 / 60)
        self._timer.timeout.connect(self.update)

        self.resize(800, 600)
        self.setWindowTitle('Eyetracker calibration')

        self._elapsed_timer.start()
        self._timer.start()

    def resizeEvent(self, event):
        w, h = self.width(), self.height()
        self._margin_x = 0.05 * w
        self._margin_y = 0.08 * h
        self._offset_x = 0.5 * w
        self._offset_y = 0.5 * h
        self._ampl_x = 0.5 * (w - 2.0 * self._margin_x)
        self._ampl_y = 0.5 * (h - 2.0 * self._margin_y)
        self._circle_size = 0.05 * h
        self._pen.setWidth(0.005 * h)

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)

        qp.setRenderHint(QPainter.Antialiasing)

        elapsed = self._elapsed_timer.restart()
        if elapsed > 100:
            elapsed = 100
        self._t += 0.0002 * elapsed

        x = self._offset_x + \
            self._ampl_x * math.sin(self._coeff_x * self._t + self._coeff_delta)

        y = self._offset_y + \
            self._ampl_y * math.sin(self._coeff_y * self._t)

        qp.setPen(self._pen)
        qp.setBrush(self._brush)
        qp.drawEllipse(QPointF(x, y), self._circle_size, self._circle_size)

        qp.end()

        self.cursorPos.emit(x, y, QDateTime.currentMSecsSinceEpoch())
Exemplo n.º 8
0
class CartPoleWidget(QWidget):
    # Emitted when a key is pressed
    keyPressed = pyqtSignal(object)

    def __init__(self, parent):
        super().__init__(parent)
        self.setFocusPolicy(Qt.StrongFocus)

        # Init data
        self._font = QFont('Serif', 14, QFont.Light)
        self._fpsTimer = QElapsedTimer()
        self._frameCount = 0
        self._fps = 0
        self._fpsTimer.start()
        self._camera = Camera()
        self._displayFrameRate = False
        self._cosmeticProperties = None
        self._environment = None
        self._cartShape = CartPoleShape()
        self._axisPlot = AxesPlot(rect=QRectF(-1, 0, 2, 0),
                                  axisX=True,
                                  axisY=False,
                                  pen=QPen(Qt.blue, 0),
                                  font=self._font,
                                  ticks=11,
                                  tickHeight=20)
        self.setEnabled(False)

    def mousePressEvent(self, event):
        # Keep track of the pressing point
        self._mousePressPosition = event.localPos()

    def mouseMoveEvent(self, event):
        # Calculate the displacement
        displacement = event.localPos() - self._mousePressPosition

        # Move the camera
        self._camera._center[0] -= displacement.x()
        self._camera._center[1] -= displacement.y()

        # Update the last press position
        self._mousePressPosition = event.localPos()

        # Schedule a repaint
        self.repaint()

    def keyPressEvent(self, event):
        self.keyPressed.emit(event)
        super().keyPressEvent(event)

    def wheelEvent(self, event):
        if (event.angleDelta().y() > 0):
            self._camera._horizontalLength *= 0.9
        else:
            self._camera._horizontalLength *= 1.1

        # Schedule a repaint
        self.repaint()

    def paintEvent(self, e):
        if self._cosmeticProperties is not None:
            qp = QPainter()
            qp.begin(self)
            self.drawWidget(qp)
            qp.end()

    # Returns the plot point at angle
    # (note: angle is the angle of the pole w.r.t. the vertical)
    def getPolePoint(self, center, angle):
        return QPointF(
            center.x() +
            math.cos(math.pi / 2 - angle) * self._environment._l * 2,
            center.y() -
            math.sin(math.pi / 2 - angle) * self._environment._l * 2)

    def drawWidget(self, qp):
        # Clear
        qp.setPen(self._cosmeticProperties._backgroundColor)
        qp.setBrush(self._cosmeticProperties._backgroundColor)
        qp.drawRect(self.rect())

        # Setup the font
        qp.setFont(self._font)
        qp.setPen(QPen(Qt.black, 0))

        # During simulation, we display the frame rate
        if self._displayFrameRate:
            # Calculate the FPS
            self._frameCount += 1
            if self._fpsTimer.elapsed() >= 1000:
                self._fps = self._frameCount / (self._fpsTimer.restart() /
                                                1000)
                self._frameCount = 0

        # Draw the FPS, environment state and time
        self.drawStatistics(qp)

        # Get viewport size
        w = self.rect().width()
        h = self.rect().height()

        # Compute the view-projection matrix
        viewProj = self._camera.getProjTransform(
            w, h) * self._camera.getViewTransform()

        # Compute the model matrix for the cart
        model = self._cartShape.modelMatrix(
            QPointF(-self._environment._position, 0),
            self._cosmeticProperties._cartWidth)

        # Draw the cart in world space
        qp.setTransform(model * viewProj)
        pen = QPen(self._cosmeticProperties._cartColor, 0)
        self._cartShape.draw(qp, pen)

        # Reset the model matrix for the cart
        qp.setTransform(viewProj)

        # Transform the cart shapes in world space
        cartBounds = model.mapRect(self._cartShape._boundingBox)
        cartBody = model.mapRect(self._cartShape._cartBody)
        poleCenter = model.map(self._cartShape._poleCenter)

        # Draw the bounds (in world space)
        qp.setPen(QPen(Qt.blue, 0))
        qp.drawLines([
            QLineF(self._environment._leftBound, cartBounds.bottom(),
                   self._environment._rightBound, cartBounds.bottom()),
            QLineF(
                self._environment._leftBound,
                cartBounds.bottom(),
                self._environment._leftBound,
                cartBody.top(),
            ),
            QLineF(
                self._environment._rightBound,
                cartBounds.bottom(),
                self._environment._rightBound,
                cartBody.top(),
            )
        ])

        # Draw the horizontal axis
        self._axisPlot._rect = QRectF(
            self._environment._leftBound, cartBounds.bottom(),
            self._environment._rightBound - self._environment._leftBound, 0)
        self._axisPlot.draw(qp, viewProj, QTransform())

        # Calculate pole position and bounds
        poleMassMin = self.getPolePoint(poleCenter,
                                        -self._environment._angleTolerance)
        poleMass = self.getPolePoint(poleCenter, self._environment._angle)
        poleMassMax = self.getPolePoint(poleCenter,
                                        self._environment._angleTolerance)

        # Draw the pole bounds
        if self._cosmeticProperties._showAngleTolerance:
            qp.setPen(QPen(self._cosmeticProperties._poleColor, 0,
                           Qt.DashLine))
            qp.drawLine(QLineF(poleCenter, poleMassMin))
            qp.drawLine(QLineF(poleCenter, poleMassMax))

        # Draw the pole
        qp.setPen(
            QPen(self._cosmeticProperties._poleColor,
                 self._cosmeticProperties._poleThickness, Qt.SolidLine,
                 Qt.RoundCap))
        qp.setBrush(self._cosmeticProperties._poleColor)
        qp.drawLine(QLineF(poleCenter, poleMass))

    def drawStatistics(self, qp):
        metrics = qp.fontMetrics()
        fw_avg = metrics.averageCharWidth()
        fh = metrics.height()

        if self._displayFrameRate:
            # Draw the fps (in screen space)
            qp.drawText(QPointF(fw_avg, fh),
                        str(round(self._fps, 2)) + " frames per second")

        qp.drawText(
            QPointF(fw_avg, 2 * fh), "Position: %.2f m, Velocity: %.2f m/s" %
            (self._environment._position, self._environment._velocity))

        qp.drawText(
            QPointF(fw_avg,
                    3 * fh), "Angle: %.2f deg, Angle velocity: %.2f deg/s" %
            (math.degrees(self._environment._angle),
             math.degrees(self._environment._angleVelocity)))

        # Draw the time (in screen space)
        qp.drawText(QPointF(fw_avg, 4 * fh),
                    str(round(self._environment._time, 2)) + " seconds")

    # Synchronizes the ui
    def syncUI(self):
        if self._environment is None or self._cosmeticProperties is None:
            self.setEnabled(False)
            return

        self.setEnabled(True)

    @property
    def cosmeticProperties(self):
        return self._cosmeticProperties

    @cosmeticProperties.setter
    def cosmeticProperties(self, val):
        self._cosmeticProperties = val
        self.syncUI()

    @property
    def environment(self):
        return self._environment

    @environment.setter
    def environment(self, val):
        self._environment = val
        self.syncUI()
Exemplo n.º 9
0
class CalibrationWidget(QWidget):

    cursorPos = pyqtSignal(float, float, "qint64")

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

        self._margin_x = 0.0
        self._margin_y = 0.0
        self._offset_x = 1.0
        self._offset_y = 1.0
        self._ampl_x = 1.0
        self._ampl_y = 1.0
        self._coeff_x = 5.0
        self._coeff_y = 4.0
        self._coeff_delta = 0.0
        self._t = 0.0
        self._circle_size = 20

        self._pen = QPen()
        self._pen.setWidth(2)
        self._pen.setColor(Qt.black)
        self._brush = QBrush(Qt.yellow)

        self._elapsed_timer = QElapsedTimer()
        self._timer = QTimer()
        self._timer.setInterval(1000 / 60)
        self._timer.timeout.connect(self.update)

        self.resize(800, 600)
        self.setWindowTitle("Eyetracker calibration")

        self._elapsed_timer.start()
        self._timer.start()

    def resizeEvent(self, event):
        w, h = self.width(), self.height()
        self._margin_x = 0.05 * w
        self._margin_y = 0.08 * h
        self._offset_x = 0.5 * w
        self._offset_y = 0.5 * h
        self._ampl_x = 0.5 * (w - 2.0 * self._margin_x)
        self._ampl_y = 0.5 * (h - 2.0 * self._margin_y)
        self._circle_size = 0.05 * h
        self._pen.setWidth(0.005 * h)

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)

        qp.setRenderHint(QPainter.Antialiasing)

        elapsed = self._elapsed_timer.restart()
        if elapsed > 100:
            elapsed = 100
        self._t += 0.0002 * elapsed

        x = self._offset_x + self._ampl_x * math.sin(self._coeff_x * self._t + self._coeff_delta)

        y = self._offset_y + self._ampl_y * math.sin(self._coeff_y * self._t)

        qp.setPen(self._pen)
        qp.setBrush(self._brush)
        qp.drawEllipse(QPointF(x, y), self._circle_size, self._circle_size)

        qp.end()

        self.cursorPos.emit(x, y, QDateTime.currentMSecsSinceEpoch())