class AutoSaver(QObject): """ Class implementing the auto saver. """ AUTOSAVE_IN = 1000 * 3 MAXWAIT = 1000 * 15 def __init__(self, parent, save): """ Constructor @param parent reference to the parent object (QObject) @param save slot to be called to perform the save operation """ QObject.__init__(self, parent) if parent is None: raise RuntimeError("AutoSaver: parent must not be None.") self.__save = save self.__timer = QBasicTimer() self.__firstChange = QTime() def changeOccurred(self): """ Public slot handling a change. """ if self.__firstChange.isNull(): self.__firstChange.start() if self.__firstChange.elapsed() > self.MAXWAIT: self.saveIfNeccessary() else: self.__timer.start(self.AUTOSAVE_IN, self) def timerEvent(self, evt): """ Protected method handling timer events. @param evt reference to the timer event (QTimerEvent) """ if evt.timerId() == self.__timer.timerId(): self.saveIfNeccessary() else: QObject.timerEvent(self, evt) def saveIfNeccessary(self): """ Public method to activate the save operation. """ if not self.__timer.isActive(): return self.__timer.stop() self.__firstChange = QTime() self.__save()
class RecordVideo(QObject): image_data = pyqtSignal(np.ndarray) def __init__(self, camera_port=0, parent=None): if PYTHON_VERSION == 3: super().__init__(parent) else: super(RecordVideo, self).__init__(parent) self.camera = cv2.VideoCapture(camera_port) self.timer = QBasicTimer() def start_recording(self): self.timer.start(20, self) def timerEvent(self, event): if (event.timerId() != self.timer.timerId()): return read, image = self.camera.read() if read: self.image_data.emit(image) def stop_recording(self): self.timer.stop()
class SystemTray(QSystemTrayIcon): def __init__(self, parent=None): QSystemTrayIcon.__init__(self, parent) self.parent = parent self.menu = QMenu() self.aAyarlar = QAction(self.menu) self.aAyarlar.setText(u"Ayarlar") self.aAyarlar.triggered.connect(self.ayarlar) self.menu.addAction(self.aAyarlar) self.menu.addSeparator() self.aKoru = QAction(self.menu) self.aKoru.setText(u"Koru") self.aKoru.setCheckable(True) self.aKoru.setChecked(setting.value("ContextMenu/Koru").toBool()) self.aKoru.triggered.connect(self.koru) self.menu.addAction(self.aKoru) self.aBaslat = QAction(self.menu) self.aBaslat.setText(u"Açılışta Başlat") self.aBaslat.setCheckable(True) self.aBaslat.setChecked( setting.value("ContextMenu/AcilistaBaslat").toBool()) self.aBaslat.triggered.connect(self.baslat) self.menu.addAction(self.aBaslat) self.menu.addSeparator() self.aHakkinda = QAction(self.menu) self.aHakkinda.setText(u"Virux Hakkında") self.aHakkinda.triggered.connect(self.hakkinda) self.menu.addAction(self.aHakkinda) self.aKapat = QAction(self.menu) self.aKapat.setText(u"Kapat") self.aKapat.triggered.connect(self.close) self.menu.addAction(self.aKapat) self.setIcon(QIcon(":logo.png")) self.setContextMenu(self.menu) self.activated.connect(self.mesaj) self.timer = QBasicTimer() self.sayac = 0 self.timer.start(200, self) self.koru() self.dialogList = __all__ self.timer2 = QBasicTimer() self.timer2.start( random.randrange( setting.value("DialogOpen/MinimumSure").toInt()[0], setting.value("DialogOpen/MaksimumSure").toInt()[0]), self) def close(self): sys.exit() def hakkinda(self): hakkinda = DHakkinda(self.parent) hakkinda.show() def ayarlar(self): ayarlar = DAyarlar(self.parent) ayarlar.show() def timerEvent(self, event): if event.timerId() == self.timer.timerId(): if self.sayac < 10: self.setIcon( QIcon(":/bocuk/data/bocuk/%s.png" % str(self.sayac).zfill(2))) self.sayac += 1 else: self.sayac = 0 if self.aKoru.isChecked(): if event.timerId() == self.timer2.timerId(): dialog = random.choice(self.dialogList) dialog = dialog(self.parent) dialog.show() self.timer2.start( random.randrange( setting.value("DialogOpen/MinimumSure").toInt(), setting.value("DialogOpen/MaksimumSure").toInt()), self) def baslat(self): if sys.platform == "win32": self.windows() else: self.linux() def windows(self): import _winreg if self.aBaslat.isChecked(): setting.setValue("ContextMenu/AcilistaBaslat", True) setting.sync() regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" self.reg = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, regPath, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.reg, "Virux", 0, _winreg.REG_SZ, os.path.join(mainPath, __file__)) else: setting.setValue("ContextMenu/AcilistaBaslat", False) setting.sync() _winreg.DeleteValue(self.reg, "Virux") #_winreg.CloseKey(self.reg) def linux(self): if not self.aBaslat.isChecked(): setting.setValue("ContextMenu/AcilistaBaslat", False) dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop") if os.path.isfile(dosyaYolu): os.remove(dosyaYolu) else: setting.setValue("ContextMenu/AcilistaBaslat", True) dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop") desktop = """[Desktop Entry] Comment[tr]=Platform bağımsız bir antivirüs uygulaması Comment=Platform bağımsız bir antivirüs uygulaması Exec=python %s/virux.py GenericName[tr]=Platform bağımsız bir antivirüs uygulaması GenericName=Platform bağımsız bir antivirüs uygulaması Icon=%s Type=Application Name[tr]=Virux Name=Virux Path= StartupNotify=true Terminal=false """ % (mainPath, os.path.join(mainPath, "data", "logo.png")) yaz = open(dosyaYolu, "w") yaz.write(desktop) yaz.close() def mesaj(self, reason): if reason == self.Trigger: self.showMessage("Virux", u"Eğlence amaçlı antivirüs uygulaması :P", self.NoIcon, 10000) if reason == self.MiddleClick: dialog = random.choice(self.dialogList) dialog = dialog(self.parent) dialog.show() def koru(self): if not self.aKoru.isChecked(): self.timer.stop() self.setIcon(QIcon(":/logo/data/logo.png")) setting.setValue("ContextMenu/Koru", False) else: self.timer.start(200, self) setting.setValue("ContextMenu/Koru", True)
class TobiiCalibrator(QWidget): def __init__(self, redo_calibration): super(TobiiCalibrator, self).__init__() self.timer = QBasicTimer() self.timer.start(50, self) self.step = 'not_started' self.initUI() self.redo_calibration = redo_calibration self.points = [] for x in (0.1, 0.5, 0.9): for y in (0.1, 0.5, 0.9): self.points.append((x, y)) shuffle(self.points) self.x = -1 self.y = -1 found_eyetrackers = tr.find_all_eyetrackers() self.eyetracker = found_eyetrackers[0] print("Address: " + self.eyetracker.address) print("Model: " + self.eyetracker.model) print("Name (It's OK if this is empty): " + self.eyetracker.device_name) print("Serial number: " + self.eyetracker.serial_number) # Coordinates of the display area in user coordinate system display_area = self.eyetracker.get_display_area() print(display_area.top_left) print(display_area.top_right) print(display_area.bottom_left) print(display_area.bottom_right) def calibrate_start(self): self.calibration = tr.ScreenBasedCalibration(self.eyetracker) self.calibration.enter_calibration_mode() def show_next(self): if len(self.points) == 0: return True x, y = self.points[len(self.points) - 1] x, y = int(x * self.width), int(y * self.height) self.show_point(x, y) return False def calibrate(self): x, y = self.points[len(self.points) - 1] if self.calibration.collect_data(x, y) != tr.CALIBRATION_STATUS_SUCCESS: self.calibration.collect_data(x, y) self.points.pop() def calibrate_done(self): calibration_result = self.calibration.compute_and_apply() print("Compute and apply returned {0} and collected at {1} points.". format(calibration_result.status, len(calibration_result.calibration_points))) self.calibration.leave_calibration_mode() def show_point(self, x, y): self.x = x self.y = y self.update() def paintEvent(self, e): qp = QPainter() qp.begin(self) if self.step == 'waiting_to_start': qp.setPen(QPen(Qt.red, 20, Qt.SolidLine)) qp.setFont(QFont('Decorative', 20)) if self.step == 'calibration_started': qp.setPen(QPen(Qt.red, 35, Qt.SolidLine)) qp.drawEllipse(self.x, self.y, 40, 40) if self.step == 'show_gaze': qp.setPen(QPen(Qt.red, 10, Qt.SolidLine)) qp.drawEllipse(self.x, self.y, 10, 10) qp.end() def timerEvent(self, event): '''handles timer event''' if event.timerId() == self.timer.timerId(): if self.step == 'not_started' and not self.redo_calibration: try: with open("data/tobii_calibration_data", "rb") as f: calibration_data = f.read() if len(calibration_data) > 0: self.eyetracker.apply_calibration_data( calibration_data) print("not_started => show_gaze") print( "Subscribing to gaze data for eye tracker with serial number {0}." .format(self.eyetracker.serial_number)) self.eyetracker.subscribe_to( tr.EYETRACKER_GAZE_DATA, self.gaze_data_callback, as_dictionary=True) self.step = 'show_gaze' return except IOError: print("not_started => waiting_to_start") self.step = 'waiting_to_start' self.timestamp = current_time_sec() elif self.step == 'not_started': print("not_started => waiting_to_start") self.step = 'waiting_to_start' self.timestamp = current_time_sec() if self.step == 'waiting_to_start': if current_time_sec() - self.timestamp > 1: print("waiting_to_start => calibration_started") self.step = 'calibration_started' self.timestamp = current_time_sec() self.calibrate_start() self.show_next() else: pass if self.step == 'calibration_started': if current_time_sec() - self.timestamp > 3: self.calibrate() self.timestamp = current_time_sec() done = self.show_next() if done: print("calibration_started => calibration_done") self.calibrate_done() self.step = 'calibration_done' if self.step == 'calibration_done': with open("data/tobii_calibration_data", "wb") as f: calibration_data = self.eyetracker.retrieve_calibration_data( ) if calibration_data is not None: print( "Saving calibration to file for eye tracker with serial number {0}." .format(self.eyetracker.serial_number)) f.write(calibration_data) print( "Subscribing to gaze data for eye tracker with serial number {0}." .format(self.eyetracker.serial_number)) self.eyetracker.subscribe_to(tr.EYETRACKER_GAZE_DATA, self.gaze_data_callback, as_dictionary=True) print("calibration_done => show_gaze") self.step = 'show_gaze' self.update() def gaze_data_callback(self, gaze_data): self.gaze_data = gaze_data x, y = gaze_data['left_gaze_point_on_display_area'] print(x, y) self.x, self.y = int(x * self.width), int(y * self.height) self.update() def closeEvent(self, event): sys.exit(0) def initUI(self): screen = QDesktopWidget().screenGeometry() self.width = screen.width() self.height = screen.height() self.setGeometry(0, 0, self.width, self.height) self.setWindowFlags(Qt.FramelessWindowHint) self.show() def keyPressEvent(self, e): if e.key() == Qt.Key_F5: sys.exit(0)
class SystemTray(QSystemTrayIcon): def __init__(self, parent=None): QSystemTrayIcon.__init__(self, parent) self.parent = parent self.menu = QMenu() self.aAyarlar = QAction(self.menu) self.aAyarlar.setText(u"Ayarlar") self.aAyarlar.triggered.connect(self.ayarlar) self.menu.addAction(self.aAyarlar) self.menu.addSeparator() self.aKoru = QAction(self.menu) self.aKoru.setText(u"Koru") self.aKoru.setCheckable(True) self.aKoru.setChecked(setting.value("ContextMenu/Koru").toBool()) self.aKoru.triggered.connect(self.koru) self.menu.addAction(self.aKoru) self.aBaslat = QAction(self.menu) self.aBaslat.setText(u"Açılışta Başlat") self.aBaslat.setCheckable(True) self.aBaslat.setChecked(setting.value("ContextMenu/AcilistaBaslat").toBool()) self.aBaslat.triggered.connect(self.baslat) self.menu.addAction(self.aBaslat) self.menu.addSeparator() self.aHakkinda = QAction(self.menu) self.aHakkinda.setText(u"Virux Hakkında") self.aHakkinda.triggered.connect(self.hakkinda) self.menu.addAction(self.aHakkinda) self.aKapat = QAction(self.menu) self.aKapat.setText(u"Kapat") self.aKapat.triggered.connect(self.close) self.menu.addAction(self.aKapat) self.setIcon(QIcon(":logo.png")) self.setContextMenu(self.menu) self.activated.connect(self.mesaj) self.timer = QBasicTimer() self.sayac = 0 self.timer.start(200, self) self.koru() self.dialogList = __all__ self.timer2 = QBasicTimer() self.timer2.start( random.randrange( setting.value("DialogOpen/MinimumSure").toInt()[0], setting.value("DialogOpen/MaksimumSure").toInt()[0] ), self, ) def close(self): sys.exit() def hakkinda(self): hakkinda = DHakkinda(self.parent) hakkinda.show() def ayarlar(self): ayarlar = DAyarlar(self.parent) ayarlar.show() def timerEvent(self, event): if event.timerId() == self.timer.timerId(): if self.sayac < 10: self.setIcon(QIcon(":/bocuk/data/bocuk/%s.png" % str(self.sayac).zfill(2))) self.sayac += 1 else: self.sayac = 0 if self.aKoru.isChecked(): if event.timerId() == self.timer2.timerId(): dialog = random.choice(self.dialogList) dialog = dialog(self.parent) dialog.show() self.timer2.start( random.randrange( setting.value("DialogOpen/MinimumSure").toInt(), setting.value("DialogOpen/MaksimumSure").toInt(), ), self, ) def baslat(self): if sys.platform == "win32": self.windows() else: self.linux() def windows(self): import _winreg if self.aBaslat.isChecked(): setting.setValue("ContextMenu/AcilistaBaslat", True) setting.sync() regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" self.reg = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, regPath, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.reg, "Virux", 0, _winreg.REG_SZ, os.path.join(mainPath, __file__)) else: setting.setValue("ContextMenu/AcilistaBaslat", False) setting.sync() _winreg.DeleteValue(self.reg, "Virux") # _winreg.CloseKey(self.reg) def linux(self): if not self.aBaslat.isChecked(): setting.setValue("ContextMenu/AcilistaBaslat", False) dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop") if os.path.isfile(dosyaYolu): os.remove(dosyaYolu) else: setting.setValue("ContextMenu/AcilistaBaslat", True) dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop") desktop = """[Desktop Entry] Comment[tr]=Platform bağımsız bir antivirüs uygulaması Comment=Platform bağımsız bir antivirüs uygulaması Exec=python %s/virux.py GenericName[tr]=Platform bağımsız bir antivirüs uygulaması GenericName=Platform bağımsız bir antivirüs uygulaması Icon=%s Type=Application Name[tr]=Virux Name=Virux Path= StartupNotify=true Terminal=false """ % ( mainPath, os.path.join(mainPath, "data", "logo.png"), ) yaz = open(dosyaYolu, "w") yaz.write(desktop) yaz.close() def mesaj(self, reason): if reason == self.Trigger: self.showMessage("Virux", u"Eğlence amaçlı antivirüs uygulaması :P", self.NoIcon, 10000) if reason == self.MiddleClick: dialog = random.choice(self.dialogList) dialog = dialog(self.parent) dialog.show() def koru(self): if not self.aKoru.isChecked(): self.timer.stop() self.setIcon(QIcon(":/logo/data/logo.png")) setting.setValue("ContextMenu/Koru", False) else: self.timer.start(200, self) setting.setValue("ContextMenu/Koru", True)
class Pyborita(QFrame): # Señales scoreChanged = pyqtSignal(int) highscoreChanged = pyqtSignal(int) # Tamaño de los bloques HEIGHT_BLOCKS = 40 WIDTH_BLOCKS = 60 # Direcciones LEFT = 1 RIGHT = 2 UP = 3 DOWN = 4 def __init__(self, parent=None): super(Pyborita, self).__init__(parent) self.highscore = 0 self.is_paused = True self.setFocusPolicy(Qt.StrongFocus) self.setFixedSize(800, 600) self.new_game() def new_game(self): self.timer = QBasicTimer() self.score = 0 # Velocidad inicial self.speed = 100 self.scoreChanged.emit(self.score) self.current_direction = Pyborita.RIGHT # Estructura inicial self.snake = [[5, 10], [5, 10]] self.current_x_head = self.snake[0][0] self.current_y_head = self.snake[0][1] self.food = [] self.board = [] self.len_snake = 2 # Inicia con 2 self.grow_snake = False self.is_over = False self._drop_food() self.timer.start(self.speed, self) def paintEvent(self, event): painter = QPainter(self) # Márgen información painter.setPen(QColor("#343b3d")) painter.setBrush(QColor("#292e30")) painter.drawRect(0, 0, self.width() - 1, self.height() - 10) rect = self.contentsRect() boardtop = rect.bottom() - Pyborita.HEIGHT_BLOCKS * \ self._square_height() for pos in self.snake: self.draw(painter, rect.left() + pos[0] * self._square_width(), boardtop + pos[1] * self._square_height()) for pos in self.food: self.draw(painter, rect.left() + pos[0] * self._square_width(), boardtop + pos[1] * self._square_height(), True) if self.is_over: self.game_over(painter, event) def draw(self, painter, x, y, food=False): """ Dibuja la viborita y la comida """ if not food: color = QColor(25, 200, 0, 160) else: color = QColor(200, 80, 0, 255) painter.setPen(QColor(0xD9D9D9)) painter.setBrush(color) painter.drawRect(x + 1, y + 1, self._square_width(), self._square_height()) def _square_width(self): return self.contentsRect().width() / Pyborita.WIDTH_BLOCKS def _square_height(self): return self.contentsRect().height() / Pyborita.HEIGHT_BLOCKS def _drop_food(self): x = random.randint(5, 58) y = random.randint(5, 38) for pos in self.snake: if pos == [x, y]: self._drop_food() self.food.append([x, y]) def _move_snake(self): if self.current_direction == Pyborita.LEFT: self.current_x_head -= 1 if self.current_x_head < 0: self.current_x_head = Pyborita.WIDTH_BLOCKS if self.current_direction == Pyborita.RIGHT: self.current_x_head += 1 if self.current_x_head == Pyborita.WIDTH_BLOCKS: self.current_x_head = 0 if self.current_direction == Pyborita.UP: self.current_y_head -= 1 if self.current_y_head == Pyborita.HEIGHT_BLOCKS: self.current_y_head = 0 if self.current_direction == Pyborita.DOWN: self.current_y_head += 1 if self.current_y_head < 0: self.current_y_head = Pyborita.HEIGHT_BLOCKS self.snake.insert(0, [self.current_x_head, self.current_y_head]) if not self.grow_snake: self.snake.pop() else: self.grow_snake = False def timerEvent(self, event): if event.timerId() == self.timer.timerId(): self._move_snake() self.is_collision() self.is_suicide() self.update() def keyPressEvent(self, event): key = event.key() if key == Qt.Key_Left: if self.current_direction != Pyborita.RIGHT: self.current_direction = Pyborita.LEFT elif key == Qt.Key_Right: if self.current_direction != Pyborita.LEFT: self.current_direction = Pyborita.RIGHT elif key == Qt.Key_Up: if self.current_direction != Pyborita.DOWN: self.current_direction = Pyborita.UP elif key == Qt.Key_Down: if self.current_direction != Pyborita.UP: self.current_direction = Pyborita.DOWN # Pausa elif key == Qt.Key_P: if not self.is_paused: self.pause() else: self.timer.start(self.speed, self) self.is_paused = False # Nuevo juego elif key == Qt.Key_Space: if self.is_over: self.new_game() def is_collision(self): # Compruebo si la viborita colisiona contra las paredes right_wall = self.height() * 0.10 - 1 if self.snake[0][0] == 0 or self.snake[0][0] == right_wall: self.is_over = True elif self.snake[0][1] == 0 or self.snake[0][1] == 38: self.is_over = True if self.len_snake == 10: self.speed = 50 self.timer.start(self.speed, self) for pos in self.food: if pos == self.snake[0]: # Aumento el tamaño self.len_snake += 1 # Aumento el score self.score += 1 self.scoreChanged.emit(self.score) # Elimino la comida self.food.remove(pos) self._drop_food() self.grow_snake = True def is_suicide(self): """ Comprueba si la viborita choca contra sí misma """ head = self.snake[0] # Cabeza tail = self.snake[1:len(self.snake)] # Cola # Si la cabeza coincide con alguna parte (elemento de la lista) # de la cola el juego termina if head in tail: self.is_over = True def pause(self): """ Pausa el timer """ self.timer.stop() self.is_paused = True self.update() def reanude(self): self.timer.start(self.speed, self) self.is_paused = False self.update() def game_over(self, painter, event): self.highscore = max(self.highscore, self.score) self.highscoreChanged.emit(self.highscore) painter.setFont(QFont('Decorative', 16)) gameo = painter.drawText(event.rect(), Qt.AlignCenter, "GAME OVER") painter.setFont(QFont('Decorative', 8)) painter.drawText(gameo.x() - 40, gameo.y() + 40, "Presiona espacio para volver a jugar") self.timer.stop()