class RecordVideo(QObject): image_data = pyqtSignal(np.ndarray) def __init__(self, camera_port=0, parent=None): super().__init__(parent) self.camera_port = camera_port self.camera = cv2.VideoCapture(camera_port) self.timer = QBasicTimer() def start_recording(self): self.timer.start(0, self) def timerEvent(self, event): if self.camera_port == 0: img = cv2.imread("Match_5_original.png") self.image_data.emit(img) elif self.camera_port == 1: img = cv2.imread("Match_6_original.png") self.image_data.emit(img) """ 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 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 FlickableTicker(QObject): def __init__(self, scroller, parent=None): QObject.__init__(self, parent) self.m_scroller = scroller self.m_timer = QBasicTimer() def start(self, interval): if not self.m_timer.isActive(): self.m_timer.start(interval, self) def stop(self): self.m_timer.stop() def timerEvent(self, event): self.m_scroller.tick()
class FlickableTicker(QObject): def __init__(self, scroller, parent = None): QObject.__init__(self, parent) self.m_scroller = scroller self.m_timer = QBasicTimer() def start(self, interval): if not self.m_timer.isActive(): self.m_timer.start(interval, self) def stop(self): self.m_timer.stop() def timerEvent(self, event): self.m_scroller.tick()
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 AgknowDockWidgetTimeSlider(QtGui.QDockWidget, FORM_CLASS): """ Class for the timeslider dockwidget of the agknow plugin. """ closingPlugin = pyqtSignal() productChanged = pyqtSignal(str) def __init__(self, parent=None): """Constructor.""" super(AgknowDockWidgetTimeSlider, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) # GUI Events # lambda keyword allows the button itself to be passed #https://www.tutorialspoint.com/pyqt/pyqt_qradiobutton_widget.htm self.rdBtnVisible.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnVisible)) self.rdBtnVitality.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnVitality)) self.rdBtnVariations.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnVariations)) self.rdBtnNDRE1.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnNDRE1)) self.rdBtnNDRE2.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnNDRE2)) self.rdBtnNDWI.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnNDWI)) self.rdBtnSAVI.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnSAVI)) self.rdBtnEVI2.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnEVI2)) self.rdBtnCIRE.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnCIRE)) self.rdBtnNDVI.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnNDVI)) self.rdBtnRefl.toggled.connect(lambda: self.rdBtnProductState_toggled(self.rdBtnRefl)) self.sliderTime.valueChanged.connect(self.sliderValue_changed) self.btnTimePlay.clicked.connect(self.btnTimePlay_clicked) self.btnTimeBackward.clicked.connect(self.btnTimeBackward_clicked) self.btnTimeForward.clicked.connect(self.btnTimeForward_clicked) self.product = "vitality" self.rasters = [] # it's a list here - a dict in agknow_qgis_dockwidget.py self.data_source = "sentinel2" self.current_parcel_id = None # timeslider self.timer = QBasicTimer() self.step = 0 self.iface = qgis.utils.iface def set_data_source(self, data_source): """ Setter for the data_source (landsat-8 or sentinel-2). """ #QgsMessageLog.logMessage("Selected Data source: {0}".format(data_source), 'agknow', QgsMessageLog.INFO) self.data_source = data_source self.toggle_products_data_source_compatibility() def set_product(self, product): """ Setter for the product (vitality, variations, visible, etc). """ #QgsMessageLog.logMessage("Selected Product: {0}".format(product), 'agknow', QgsMessageLog.INFO) self.product = product # notify slots of change self.productChanged.emit(product) def set_current_parcel_id(self, parcel_id): """ Setter for the current parcel_id. """ self.current_parcel_id = parcel_id def timerEvent(self, e): """ Event handler for the timer. :param e: """ print("timerEvent()") if self.step == self.sliderTime.maximum(): self.timer.stop() self.step = 0 #reset step return else: self.step = self.step + 1 self.sliderTime.setValue(self.sliderTime.value()+1) def rdBtnProductState_toggled(self, btn): """ Handles the toggled event of the given radio button. :param btn: radio button (QRadioButton) """ # trigger update # if radio button is checked at the end if btn.isChecked(): if btn.text().lower() == "refl.": self.set_product("reflectances") else: self.set_product(btn.text().lower()) parcel_id = self.current_parcel_id if len(self.rasters) > 0: # find subgroup root = QgsProject.instance().layerTreeRoot() parcel_group = root.findGroup("parcel id: {0}".format(parcel_id)) # select active layer for identity e.g. self.set_layer_active_toc(parcel_id) if parcel_group is not None: self.toggle_products(parcel_group) def set_layer_active_toc(self, parcel_id): """ Sets the group layer of the given parcel ID in the TOC to active. :param parcel_id: parcel's ID (integer) """ # take the first layer of the group "parcel id: - source - product" data_source_group = self.find_data_source_group(parcel_id, self.product, self.data_source) # layer name date = self.rasters[0]["date"] raster_id = self.rasters[0]["raster_id"] activeLyrName = date + " - " + str(raster_id) if data_source_group is not None: for lyr in data_source_group.findLayers(): #print("searching for {0}..".format(activeLyrName)) # QGIS 2.18.1 : name(), QGIS 2.18.0 : layerName() if lyr.layerName() == activeLyrName: # QgsLayerTreeLayer to QgsMapLayer per .layer() #print("setting lyr {0} active".format(lyr.layerName())) self.iface.setActiveLayer(lyr.layer()) else: pass #print("data_source_group not found: {0} - {1} - {2}".format(parcel_id, self.product, self.data_source)) def sliderValue_changed(self): """ Handles the value changed event of the timeslider. """ if len(self.rasters) > 0: #print(self.sliderTime.value()) idx = self.sliderTime.value() #set current raster to visible - the rest invisible # get data from position in self.rasters product_id = self.product + " " #whitespace! data_source = self.rasters[idx]["source"] parcel_id = self.rasters[idx]["parcel_id"] raster_id = self.rasters[idx]["raster_id"] date = self.rasters[idx]["date"] #print(product_id, data_source, parcel_id, raster_id, date) activeLyrName = "{0}|{1}|{2}|{3}".format(product_id.strip(), date, raster_id, data_source) #date + " - " + str(raster_id) #print(activeLyrName) self.toggle_image_layer(activeLyrName, data_source, parcel_id, product_id) else: QgsMessageLog.logMessage("AgknowDockWidgetTimeSlider - sliderValue_changed() - rasters are not set!", "agknow", QgsMessageLog.CRITICAL) def toggle_image_layer(self, activeLyrName, data_source, parcel_id, product_id): """ Toggles all other image layers off except the given activeLayer. :param activeLyrName: active layer group (string) :param data_source: landsat-8 or sentinel-2 (string) :param parcel_id: parcel's ID (integer) :param product_id: product id: visible, vitality, variations, etc. (string) """ # find subgroup data_source_group = self.find_data_source_group(parcel_id, product_id, data_source) if data_source_group is not None: for lyr in data_source_group.findLayers(): # QGIS 2.18.1 : name(), QGIS 2.18.0 : layerName() if QGis.QGIS_VERSION_INT == 21800: if lyr.layerName() == activeLyrName: # set active layer visible lyr.setVisible(Qt.Checked) # select active layer for identity e.g. # QgsLayerTreeLayer to QgsMapLayer per .layer() self.iface.setActiveLayer(lyr.layer()) else: lyr.setVisible(Qt.Unchecked) elif QGis.QGIS_VERSION_INT > 21800: if lyr.name() == activeLyrName: # set active layer visible lyr.setVisible(Qt.Checked) # select active layer for identity e.g. # QgsLayerTreeLayer to QgsMapLayer per .layer() self.iface.setActiveLayer(lyr.layer()) else: lyr.setVisible(Qt.Unchecked) def find_data_source_group(self, parcel_id, product_id, data_source): """ Returns the data source group layer of the TOC for the given parcel id, product and data source. :param parcel_id: parcel's ID (integer) :param product_id: product id: visible, vitality, variations, etc. (string) :param data_source: landsat-8 or sentinel-2 (string) :return: data_source_group (QgsLayerTreeGroup) """ root = QgsProject.instance().layerTreeRoot() parcel_group = root.findGroup("parcel id: {0}".format(parcel_id)) if parcel_group is not None: #print("parcel group found") product_group = parcel_group.findGroup(product_id) #print(product_group) if product_group is not None: #print("product group found") data_source_group = product_group.findGroup(data_source) return data_source_group def toggle_products(self, parcel_group): """ Toggle all other product groups off except the given parcel_group. :param parcel_group: (QgsLayerTreeGroup) """ data_source_list = ["landsat8", "sentinel2"] matrix = {"landsat8": ["visible", "vitality", "variations"], "sentinel2": ["visible", "vitality", "variations", "reflectances", "ndvi", "ndre1", "ndre2", "ndre3", "ndwi", "savi", "evi2", "cire"] } # turn off other data_source groups for ds in data_source_list: #print("checking {0}..".format(ds)) for p in matrix[ds]: #print("checking product {0}..".format(p)) pg = parcel_group.findGroup(p + " ") if pg is not None: #print("group {0} found!".format(p)) g = pg.findGroup(ds) if g is not None: if p == self.product and ds == self.data_source: #print("group {0} visible".format(ds)) g.setVisible(Qt.Checked) else: #print("group {0} invisible!".format(ds)) g.setVisible(Qt.Unchecked) def toggle_products_data_source_compatibility(self): """ Handles radio buttons for compatibility of products & data_source """ print("toggle_products_data_source_compatibility()") matrix = {"landsat8": ["Visible", "Vitality", "Variations"], "sentinel2": ["Visible", "Vitality", "Variations", "Refl.", "NDVI", "NDRE1", "NDRE2", "NDRE3", "NDWI", "SAVI", "EVI2", "CIRE"] } radioBtns = [self.rdBtnVisible, self.rdBtnVitality, self.rdBtnVariations, self.rdBtnNDRE1, self.rdBtnNDRE2, self.rdBtnNDWI, self.rdBtnSAVI, self.rdBtnEVI2, self.rdBtnCIRE, self.rdBtnNDVI, self.rdBtnRefl] for rdBtn in radioBtns: # disable all other radio buttons if rdBtn.text() in matrix[self.data_source]: rdBtn.setEnabled(True) else: rdBtn.setEnabled(False) #TODO: if data source disables product - select another product # leads to segmentation faults at the moment because several threads are started then #for rdBtn in radioBtns: # # check if selected radio button is disabled # if rdBtn.isChecked() and not rdBtn.isEnabled(): # # if so take the first of possible radio buttons # rdBtnToCheckName = matrix[self.data_source][0] # print(rdBtnToCheckName) # for r in radioBtns: # if r.text() == rdBtnToCheckName: # r.setChecked(Qt.Checked) def btnTimePlay_clicked(self): """ Handles the click event of the Button btnTimePlay. """ self.btnTimePlay.setText(" || ") interval = 1000 #ms # stop timer if it is already active if self.timer.isActive(): self.btnTimePlay.setText(" > ") self.timer.stop() # reset timer self.step = 0 self.sliderTime.setValue(0) # start timer else: self.timer.start(interval, self) def btnTimeForward_clicked(self): """ Handles the click event of the Button btnTimeForward. """ self.sliderTime.setValue(self.sliderTime.value()+1) def btnTimeBackward_clicked(self): """ Handles the click event of the Button btnTimeBackward. """ self.sliderTime.setValue(self.sliderTime.value()-1) def reload_images(self, rasters): """ Reloads images for the given rasters. :param rasters: () """ #print("reload_images({0})".format(rasters)) if rasters is not None: self.sliderTime.setRange(0, len(rasters)-1) self.sliderTime.setTickInterval = 1 self.rasters = rasters if len(self.rasters) > 0: #print(self.rasters) parcel_id = self.rasters[0]["parcel_id"] QgsMessageLog.logMessage("AgknowDockWidgetTimeSlider - activating parcel {0}..".format(parcel_id), "agknow", QgsMessageLog.INFO) # select first image layer active in toc for identity e.g. self.set_layer_active_toc(parcel_id) else: QgsMessageLog.logMessage("AgknowDockWidgetTimeSlider - rasters is None!", "agknow", QgsMessageLog.WARNING) def closeEvent(self, event): """ Handles the close event of the class. :param event: """ self.closingPlugin.emit() event.accept()
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 SD_tool(QMainWindow, Ui_MainWindow): def __init__(self): QMainWindow.__init__(self) #threading.Thread.__init__(self) self.setupUi(self) self.burnBtn.setDisabled(True) self.progressBar.setValue(0) #self.dev_table = ["sda", "sdb", "sdc", "sdd", "sde", \ self.dev_table = ["sdX", "sdb", "sdc", "sdd", "sde", \ "sdf", "sdg", "sdh", "sdi", "sdj", "sdk"] self.timer = QBasicTimer() self.step = 0 self.isRun = False self.msg = msgThread(self) self.msg.updated.connect(self.showMsgSlot) self.action_Dnw.triggered.connect(self.do_dnw) self.action_About.triggered.connect(self.do_about) self.actionSd_partition.triggered.connect(self.do_sdpartiton) self.scanBtn.clicked.connect(self.do_scan) self.burnBtn.clicked.connect(self.do_burn) self.fileBtn.clicked.connect(self.do_file) self.devBox.currentIndexChanged.connect(self.do_indexChanged) @pyqtSlot(QString) def showMsgSlot(self, msg): self.msgBox.insertPlainText(msg + "\n") def showMsg(self, msg): self.msg.msg = msg self.msg.start() #self.msgBox.insertPlainText(msg + "\n") #pass def processThread(self): #def run(self): self.isRun = True bl1_size = 8192 #bl1_position = 1 #uboot_position = 49 #print "processThread start ... \n" #self.burnBtn.setDisabled(True) #self.devBox.setDisabled(True) #self.scanBtn.setDisabled(True) #self.fileBox.setDisabled(True) if(os.path.exists(self.fileBox.text())): file_uboot = open(self.fileBox.text(), "rb") #print "open uboot\n" try: bl1_buf = file_uboot.read(bl1_size) #print "read uboot\n" finally: #print "close uboot\n" file_uboot.flush() file_uboot.close() #print "open bl1\n" file_bl1 = open("/tmp/tmp_bl1_8k.bin", "wb") try: #print "write bl1\n" file_bl1.write(bl1_buf) finally: #print "close bl1\n" file_bl1.flush() file_bl1.close() self.burn_bl1 = "dd iflag=dsync oflag=dsync if=/tmp/tmp_bl1_8k.bin of=" + self.devBox.currentText() + " seek=1" self.burn_uboot = "dd iflag=dsync oflag=dsync if=" + self.fileBox.text() + " of=" + self.devBox.currentText() + " seek=49" #print "run burn bl1\n" #self.msgBox.insertPlainText(self.burn_bl1 + "\n") output = commands.getoutput(str(self.burn_bl1)) #self.msgBox.insertPlainText(output.decode("utf8") + "\n") self.showMsg(output.decode("utf8")) #print output time.sleep(1) #print "run burn uboot\n" #self.msgBox.insertPlainText(self.burn_uboot + "\n") output = commands.getoutput(str(self.burn_uboot)) #self.msgBox.insertPlainText(output.decode("utf8") + "\n") self.showMsg(output.decode("utf8")) #print output time.sleep(2) #self.msgBox.insertPlainText("sync\n") output = commands.getoutput(str("sync")) #self.msgBox.insertPlainText(output.decode("utf8") + "\n") self.showMsg(output.decode("utf8")) #print output time.sleep(5) self.isRun = False thread.exit_thread() return def timerEvent(self, e): if self.step == 99: if self.isRun : self.step = 0 self.progressBar.setValue(self.step) #print "is Run... \n" return if self.step >= 100: self.timer.stop() self.showMsg( "burn Finished\n") self.devBox.setDisabled(False) self.scanBtn.setDisabled(False) self.fileBox.setDisabled(False) self.burnBtn.setDisabled(False) self.exitBtn.setDisabled(False) self.fileBtn.setDisabled(False) return self.step = self.step + 1 self.progressBar.setValue(self.step) @pyqtSlot() def do_file(self): #file_img = QFileDialog(self) #file_img.setWindowTitle("file") #file_img.setNameFilters([self.tr("Binary File (*.bin)"), self.tr("All File (*)")]) #file_img.setDefaultSuffix(".bin") #if(file_img.exec_()): # print file_img. file_img = QFileDialog.getOpenFileName(self, "File Open", "./", "*.bin") #if(os.path.exists(file_img)): if(len(file_img) > 0): self.showMsg("use image is " + file_img + "\n") self.fileBox.setText(file_img) if(self.devBox.count() > 0): self.burnBtn.setDisabled(False) self.progressBar.setValue(0) @pyqtSlot(int) def do_indexChanged(self, idx): self.msgBox.clear() dev = self.devBox.currentText() self.showMsg( "use " + dev + " device\n") self.progressBar.setValue(0) @pyqtSlot() def do_scan(self): count = self.devBox.count() #for j in range(0, count): # self.devBox.removeItem(count - 1 - j) if count > 0: self.devBox.clear() for i in range(0, len(self.dev_table)): #print self.dev_table[i] #self.devBox.addItems("/dev/" + self.dev_table[i]) dev = "/dev/" + self.dev_table[i] if(os.path.exists(dev)): self.devBox.addItem(dev) self.devBox.setCurrentIndex(self.devBox.count() - 1) if(self.fileBox.text().length() > 0): self.burnBtn.setDisabled(False) self.progressBar.setValue(0) @pyqtSlot() def do_burn(self): #dev = self.devBox.currentText() #self.msgBox.insertPlainText( "use " + dev + " device\n") if(os.path.exists(self.fileBox.text())): #thread.start_new(self.processThread, ()) thread.start_new_thread(self.processThread, ()) #self.start() self.timer.start(100, self) #os.system(str(burn_bl1)) #status, output = commands.getstatusoutput(str(burn_bl1 + "&& " + burn_uboot + " && sync")) #os.system(burn_uboot) #os.system("sync") #loop = True #while loop: # if(status == 0): # loop = False # #else: # time.sleep(5) # loop = False # #print "loop ... \n" self.devBox.setDisabled(True) self.scanBtn.setDisabled(True) self.fileBox.setDisabled(True) self.burnBtn.setDisabled(True) self.exitBtn.setDisabled(True) self.fileBtn.setDisabled(True) @pyqtSlot() def do_dnw(self): dialog = SD_dnw() dialog.exec_() @pyqtSlot() def do_sdpartiton(self): dialog = SD_partition() dialog.exec_() @pyqtSlot() def do_about(self): dialog = SD_about() dialog.exec_()
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()