def generateSolution(self): """ Generate a solution for the current cubestring and display in the GUI """ self.statusbar.showMessage("Generating Solution") msg = "Generating solution for cubestring: " + self.cube.cubestring self.addLogEntry(msg) timer = QElapsedTimer() timer.start() solution = "No Solution" try: solution = kociemba.solve(self.cube.cubestring) except Exception as err: print(err) error_dialog = QErrorMessage() error_dialog.showMessage(err.args[0]) error_dialog.exec_() solution = err.args[0] self.statusbar.showMessage("Solution generation failed!") msg = "Solution could not be calculated: " + solution self.addLogEntry(msg) self.lineEdit_InOut.setText(solution) self.label_CurrentString.setText("Solution:") self.statusbar.showMessage("Generated Solution") msg = "Solution calculation took: {} ms".format(timer.nsecsElapsed() / 1000000) self.addLogEntry(msg) # self.timer1ms.stop() pass
def _wait_for_clipboard(qtbot, clipboard, mode, expected): timeout = 1000 timer = QElapsedTimer() timer.start() while True: if clipboard.text(mode=mode) == expected: return # We need to poll the clipboard, as for some reason it can change with # emitting changed (?). with qtbot.waitSignal(clipboard.changed, timeout=100, raising=False): pass if timer.hasExpired(timeout): mode_names = { QClipboard.Clipboard: 'clipboard', QClipboard.Selection: 'primary selection', } raise WaitForClipboardTimeout( "Timed out after {timeout}ms waiting for {what}:\n" " expected: {expected!r}\n" " clipboard: {clipboard!r}\n" " primary: {primary!r}.".format( timeout=timeout, what=mode_names[mode], expected=expected, clipboard=clipboard.text(mode=QClipboard.Clipboard), primary=clipboard.text(mode=QClipboard.Selection)))
def nextQuestion(self): timer = QElapsedTimer() timer.start() questionWidget = Question(self.mainWindow, self.questionNum + 1, self.result, timer, self.selectedInx) self.mainWindow.widgetList.addWidget(questionWidget) self.mainWindow.widgetList.setCurrentWidget(questionWidget)
def _wait_for_clipboard(qtbot, clipboard, mode, expected): timeout = 1000 timer = QElapsedTimer() timer.start() while True: if clipboard.text(mode=mode) == expected: return # We need to poll the clipboard, as for some reason it can change with # emitting changed (?). with qtbot.waitSignal(clipboard.changed, timeout=100, raising=False): pass if timer.hasExpired(timeout): mode_names = { QClipboard.Clipboard: 'clipboard', QClipboard.Selection: 'primary selection', } raise WaitForClipboardTimeout( "Timed out after {timeout}ms waiting for {what}:\n" " expected: {expected!r}\n" " clipboard: {clipboard!r}\n" " primary: {primary!r}.".format( timeout=timeout, what=mode_names[mode], expected=expected, clipboard=clipboard.text(mode=QClipboard.Clipboard), primary=clipboard.text(mode=QClipboard.Selection)) )
def _wait_for_new(self, timeout, do_skip, **kwargs): """Wait for a log message which doesn't exist yet. Called via wait_for. """ __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout) message = kwargs.get('message', None) if message is not None: elided = quteutils.elide(repr(message), 50) self._log("\n----> Waiting for {} in the log".format(elided)) spy = QSignalSpy(self.new_data) elapsed_timer = QElapsedTimer() elapsed_timer.start() while True: # Skip if there are pending messages causing a skip self._maybe_skip() got_signal = spy.wait(timeout) if not got_signal or elapsed_timer.hasExpired(timeout): msg = "Timed out after {}ms waiting for {!r}.".format( timeout, kwargs) if do_skip: pytest.skip(msg) else: raise WaitForTimeout(msg) match = self._wait_for_match(spy, kwargs) if match is not None: if message is not None: self._log("----> found it") return match
def wait_for(self, timeout=None, *, override_waited_for=False, do_skip=False, **kwargs): """Wait until a given value is found in the data. Keyword arguments to this function get interpreted as attributes of the searched data. Every given argument is treated as a pattern which the attribute has to match against. Args: timeout: How long to wait for the message. override_waited_for: If set, gets triggered by previous messages again. do_skip: If set, call pytest.skip on a timeout. Return: The matched line. """ __tracebackhide__ = True if timeout is None: if do_skip: timeout = 2000 elif 'CI' in os.environ: timeout = 15000 else: timeout = 5000 if not kwargs: raise TypeError("No keyword arguments given!") for key in kwargs: assert key in self.KEYS # Search existing messages existing = self._wait_for_existing(override_waited_for, **kwargs) if existing is not None: return existing # If there is none, wait for the message spy = QSignalSpy(self.new_data) elapsed_timer = QElapsedTimer() elapsed_timer.start() while True: # Skip if there are pending messages causing a skip self._maybe_skip() got_signal = spy.wait(timeout) if not got_signal or elapsed_timer.hasExpired(timeout): msg = "Timed out after {}ms waiting for {!r}.".format( timeout, kwargs) if do_skip: pytest.skip(msg) else: raise WaitForTimeout(msg) match = self._wait_for_match(spy, kwargs) if match is not None: return match
def _wait_for_new(self, timeout, do_skip, **kwargs): """Wait for a log message which doesn't exist yet. Called via wait_for. """ __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout) message = kwargs.get('message', None) if message is not None: elided = quteutils.elide(repr(message), 100) self._log("\n----> Waiting for {} in the log".format(elided)) spy = QSignalSpy(self.new_data) elapsed_timer = QElapsedTimer() elapsed_timer.start() while True: # Skip if there are pending messages causing a skip self._maybe_skip() got_signal = spy.wait(timeout) if not got_signal or elapsed_timer.hasExpired(timeout): msg = "Timed out after {}ms waiting for {!r}.".format( timeout, kwargs) if do_skip: pytest.skip(msg) else: raise WaitForTimeout(msg) match = self._wait_for_match(spy, kwargs) if match is not None: if message is not None: self._log("----> found it") return match raise quteutils.Unreachable
def wait_for(self, timeout=None, *, override_waited_for=False, **kwargs): """Wait until a given value is found in the data. Keyword arguments to this function get interpreted as attributes of the searched data. Every given argument is treated as a pattern which the attribute has to match against. Args: timeout: How long to wait for the message. override_waited_for: If set, gets triggered by previous messages again. Return: The matched line. """ __tracebackhide__ = True if timeout is None: if 'CI' in os.environ: timeout = 15000 else: timeout = 5000 if not kwargs: raise TypeError("No keyword arguments given!") for key in kwargs: assert key in self.KEYS # Search existing messages existing = self._wait_for_existing(override_waited_for, **kwargs) if existing is not None: return existing # If there is none, wait for the message spy = QSignalSpy(self.new_data) elapsed_timer = QElapsedTimer() elapsed_timer.start() while True: got_signal = spy.wait(timeout) if not got_signal or elapsed_timer.hasExpired(timeout): raise WaitForTimeout("Timed out after {}ms waiting for " "{!r}.".format(timeout, kwargs)) for args in spy: assert len(args) == 1 line = args[0] matches = [] for key, expected in kwargs.items(): value = getattr(line, key) matches.append(self._match_data(value, expected)) if all(matches): # If we waited for this line, chances are we don't mean the # same thing the next time we use wait_for and it matches # this line again. line.waited_for = True return line
def toRate(self): self.updateResult() self.updateTime() timer = QElapsedTimer() timer.start() rateWidget = Rate(self.mainWindow, self.questionNum, self.result, self.selectedInx, timer) self.mainWindow.widgetList.addWidget(rateWidget) self.mainWindow.widgetList.setCurrentWidget(rateWidget)
def wait_for(self, timeout=None, **kwargs): """Wait until a given value is found in the data. Keyword arguments to this function get interpreted as attributes of the searched data. Every given argument is treated as a pattern which the attribute has to match against. Return: The matched line. """ if timeout is None: if 'CI' in os.environ: timeout = 15000 else: timeout = 5000 # Search existing messages for line in self._data: matches = [] for key, expected in kwargs.items(): value = getattr(line, key) matches.append(self._match_data(value, expected)) if all(matches) and not line.waited_for: # If we waited for this line, chances are we don't mean the # same thing the next time we use wait_for and it matches # this line again. line.waited_for = True return line # If there is none, wait for the message spy = QSignalSpy(self.new_data) elapsed_timer = QElapsedTimer() elapsed_timer.start() while True: got_signal = spy.wait(timeout) if not got_signal or elapsed_timer.hasExpired(timeout): raise WaitForTimeout("Timed out after {}ms waiting for " "{!r}.".format(timeout, kwargs)) for args in spy: assert len(args) == 1 line = args[0] matches = [] for key, expected in kwargs.items(): value = getattr(line, key) matches.append(self._match_data(value, expected)) if all(matches): # If we waited for this line, chances are we don't mean the # same thing the next time we use wait_for and it matches # this line again. line.waited_for = True return line
class Timer(Text): def __init__(self, font_size=100, debug=False): super().__init__(font_size=font_size) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setAlignment(Qt.AlignCenter) self.speed = False self.seconds = 0.0 self._elapsed_time = QElapsedTimer() self._timer = QTimer(self, interval=100, timeout=self._update) self._timer.timeout.connect(self._update) self._timer.start() if debug: self.setFrameStyle(QFrame.Box | QFrame.Raised) def set_current_state(self, state): self._current_state = state self.stateChanged.emit(state) def set_speed(self, speed): try: self.speed = float(speed) self._elapsed_time.start() except BaseException: logging.exception("Failed to set timer speed") def set_time(self, time): try: time = time.strip() if time[0] in '+-': self.seconds += float(time) else: self.seconds = float(time) except BaseException: logging.exception("Failed to set timer time") @pyqtSlot() def _update(self): self.seconds += self.speed * self._elapsed_time.elapsed() / 1000 self.seconds = max(self.seconds, 0) self._elapsed_time.start() h, m, s = self.split_time(self.seconds) self.setText(f'{h:02}:{m:02}:{s:02}') @classmethod def split_time(cls, seconds): hours, remaining = divmod(seconds, 3600) minutes, seconds = divmod(remaining, 60) return int(hours), int(minutes), int(seconds)
def _searchBatch(self): with self.safeBatch(): start_time = QElapsedTimer() start_time.start() for self.start_line in range(self.start_line, self.editor.lines()): if start_time.hasExpired(10): return self.searchInLine(self.start_line) self.timer.stop() self.finished.emit(0)
class Bullet: """Bullet contains: 1 StartPosition 2 EndPosition 3 Color 4 Text( A String) 5 Duration It uses the "window" to draw it selft """ #这个叫做 类的属性 Count=0# 通过类名Bullet.bullet访问,就是一个静态变量 Height=GLOBAL.BULLETFONTSIZE+6 #一个Bullet占用的像素高度 def __init__(self, Text, Color,Duration): Bullet.Count+=1 #这个里面self给定的内容则只属于当前对象 self.Text=Text self.Color=Color self.Duration=Duration*1000 #单位是毫秒,输入的是秒 self.IsExpired=False """this method must be called when this bullet is ready to shoot at the first time """ def prepare(self): self.elapsedTimer=QElapsedTimer() self.elapsedTimer.start() #start time self.StartPosition=QPoint(GLOBAL.WINDOWWIDTH+random.randrange(200,500,20),\ (Bullet.Height+(Bullet.Count%(GLOBAL.WINDOWHEIGHT//Bullet.Height))*Bullet.Height)) self.EndPosition=QPoint(-2000 ,self.StartPosition.y()) """Draw this bullet at position x,y ,use painter Returns True indicates this bullet is out of screen """ def draw(self,painter): ratio=self.elapsedTimer.elapsed()/self.Duration if(ratio>0.9): self.IsExpired=True # pos=ratio*self.EndPosition+(1-ratio)*self.StartPosition pos=QPoint(ratio*self.EndPosition.x()+(1-ratio)*self.StartPosition.x(),self.StartPosition.y()) #这里需要插入绘制字体阴影的代码 # # font.setFixedPitch(True) # painter.setFont(font) painter.save() painter.drawText(pos+QPoint(2,2),self.Text) painter.setPen(QPen(self.Color)) painter.drawText(pos,self.Text) painter.restore() # def __del__(self): # Count-=1 # print ("刚刚自动Delete了一个bullet\n")
def _searchBatch(self, needOne=False): with self.safeBatch(): start_time = QElapsedTimer() start_time.start() for self.start_line in range(self.start_line, self.editor.lines()): if not needOne and start_time.hasExpired(10): return matched = self.searchInLine(self.start_line) if matched: needOne = False self.timer.stop() self.finished.emit(0)
def crawlBatch(self): start_time = QElapsedTimer() start_time.start() prefix_len = len(self.root) + 1 # 1 for the / for path in self.crawler: subpath = path[prefix_len:] qitem = QStandardItem(subpath) qitem.setData(path, AbsolutePathRole) qitem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.mdl.appendRow(qitem) if start_time.hasExpired(self.maxSecsPerCrawlBatch * 1000): self.crawlTimer.start(0) break
def _batchLoad(self): with self.safeBatch(): duration = QElapsedTimer() duration.start() for taginfo in self.parsing: self.db.add_tag(taginfo) if duration.hasExpired(10): return CACHE.addConf(self.parser.path, self.db) self.timer.stop() LOGGER.debug('db %r has finished loading', self.parser.path) self.searchInDb(self.request)
def startProgressBar(self): global PAUSED self.pushStartButton.setEnabled(False) self.pushStopButton.setEnabled(False) for buttonOption in self.button_list: if buttonOption.button != None: buttonOption.button.setEnabled(False) if buttonOption.inputBox != None: buttonOption.inputBox.setEnabled(False) PAUSED = False elapsedTime = QElapsedTimer() elapsedTime.start() self.startApplication()
class Watch(QWidget): required_keys = [] update_interval = 30 def __init__(self): super().__init__() uic.loadUi('src/widgets/default/watch/watch.ui', self) self.timer = QElapsedTimer() self.timer.start() def update_data(self, data): pass def redraw(self): self.lcd.display(format(self.timer.elapsed() / 1000, '.3f')) self.progress.setValue(self.timer.elapsed() % 1000 / 10)
def _wait_for_clipboard(qtbot, clipboard, mode, expected): timeout = 1000 timer = QElapsedTimer() timer.start() while True: if clipboard.text(mode=mode) == expected: return with qtbot.waitSignal(clipboard.changed, timeout=timeout) as blocker: pass if not blocker.signal_triggered or timer.hasExpired(timeout): mode_names = { QClipboard.Clipboard: 'clipboard', QClipboard.Selection: 'primary selection', } raise WaitForTimeout( "Timed out after {}ms waiting for {} in {}.".format( timeout, expected, mode_names[mode]))
def startProgressBar(self): global PAUSED self.pushStartButton.setEnabled(False) self.pushStopButton.setEnabled(False) for buttonOption in self.button_list: if buttonOption.button != None: buttonOption.button.setEnabled(False) if buttonOption.inputBox != None: buttonOption.inputBox.setEnabled(False) PAUSED = False elapsedTime = QElapsedTimer() elapsedTime.start() self.startApplication() os.chdir( os.path.join(os.environ.get('HOME'), "teamcode", "appsAway", "scripts")) rc = subprocess.call("./appsAway_setEnvironment.local.sh")
class MainWindow(WgpuCanvas): def __init__(self, parent=None, title=None, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.setWindowTitle(title) # Load Map texture img = Image.open(mapTexture).convert("RGBA") # Create the WebGPU draw function and initialize GPU self.drawFunction = get_draw_function(self, img) self.request_draw(self.mainloop) # Updates on resize / redraw # Set timer to update every frame self.timer = QTimer() self.timer.timeout.connect(self.mainloop) self.timer.start(math.floor(1000 / FPS)) self.timing = QElapsedTimer() self.timing.start() self.oldTime = 0 def mainloop(self): """ Main update loop """ if self.is_closed(): self.timer.stop() return # Get current time since launch t = self.timing.elapsed() / 1000 # Call draw fonction with the time self.drawFunction(t) # Display FPS if t - self.oldTime > 0: print(round(1 / (t - self.oldTime), 2), "FPS") self.oldTime = t
def slot_batch_resize(self): dialog = QDialog() dialog.setWindowTitle(i18n("Resize all Pages")) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.accepted.connect(dialog.accept) buttons.rejected.connect(dialog.reject) sizesBox = comics_export_dialog.comic_export_resize_widget("Scale", batch=True, fileType=False) exporterSizes = comics_exporter.sizesCalculator() dialog.setLayout(QVBoxLayout()) dialog.layout().addWidget(sizesBox) dialog.layout().addWidget(buttons) if dialog.exec_() == QDialog.Accepted: progress = QProgressDialog(i18n("Resizing pages..."), str(), 0, len(self.setupDictionary["pages"])) progress.setWindowTitle(i18n("Resizing Pages")) progress.setCancelButton(None) timer = QElapsedTimer() timer.start() config = {} config = sizesBox.get_config(config) for p in range(len(self.setupDictionary["pages"])): absoluteUrl = os.path.join(self.projecturl, self.setupDictionary["pages"][p]) progress.setValue(p) timePassed = timer.elapsed() if (p > 0): timeEstimated = (len(self.setupDictionary["pages"]) - p) * (timePassed / p) passedString = str(int(timePassed / 60000)) + ":" + format(int(timePassed / 1000), "02d") + ":" + format(timePassed % 1000, "03d") estimatedString = str(int(timeEstimated / 60000)) + ":" + format(int(timeEstimated / 1000), "02d") + ":" + format(int(timeEstimated % 1000), "03d") progress.setLabelText(str(i18n("{pages} of {pagesTotal} done. \nTime passed: {passedString}:\n Estimated:{estimated}")).format(pages=p, pagesTotal=len(self.setupDictionary["pages"]), passedString=passedString, estimated=estimatedString)) qApp.processEvents() if os.path.exists(absoluteUrl): doc = Application.openDocument(absoluteUrl) listScales = exporterSizes.get_scale_from_resize_config(config["Scale"], [doc.width(), doc.height(), doc.resolution(), doc.resolution()]) doc.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic") doc.waitForDone() doc.save() doc.waitForDone() doc.close()
class Stopwatch(QObject): newTime = pyqtSignal(str, arguments=['displayTime']) def __init__(self): super().__init__() self.timer = QTimer() self.delta = QElapsedTimer() self.timer.setInterval(100) self.timer.timeout.connect(self.displayTime) @pyqtSlot() def displayTime(self): t = QTime(0, 0, 0) displayTxt = t.addMSecs(self.delta.elapsed()).toString('hh:mm:ss') self.newTime.emit(displayTxt) @pyqtSlot() def start(self): self.delta.start() self.timer.start() @pyqtSlot() def stop(self): self.timer.stop()
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)
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
1) # cv2.putText(show2, text, (70, 380), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) cv.drawContours(show2, save, -1, (0, 0, 255), 2) showImage = QtGui.QImage( show2.data, show2.shape[1], show2.shape[0], QtGui.QImage.Format_RGB888) # 把读取到的视频数据变成QImage形式 self.label_show_tongkong_video.setPixmap( QtGui.QPixmap.fromImage(showImage)) # 往显示视频的Label里 显示QImage if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) # 固定的,表示程序应用 pixmap = QPixmap("ximinglogo.jpg") screen = QSplashScreen(pixmap) screen.show() dtimer = QElapsedTimer() delayTime = 5 dtimer.start() while (dtimer.elapsed() < (delayTime * 100)): {app.processEvents()} T = test_window() # H = 数据库4.Ui_MainWindow() T.setWindowTitle("希铭光学") T.show() # T.pushButton_history.clicked.connect(H.show) sys.exit(app.exec_())
class DedeNimeur(QMainWindow): def __init__(self): super(DedeNimeur, self).__init__() self.statusBar() self.size, self.height, self.width, self.mines = 30, 10, 10, 10 self.lcd = QLCDNumber() self.lcd.setFixedSize(300, 60) self.board = Board(self.height, self.width, self.mines, self.size) self.timer = QBasicTimer() self.real_timer = QElapsedTimer() vbox = QVBoxLayout() vbox.addWidget(self.lcd) vbox.addWidget(self.board) central = QWidget() central.setLayout(vbox) self.setCentralWidget(central) start = QAction('Start', self) start.setStatusTip('Start') start.setShortcut('Ctrl+N') start.triggered.connect(self.init) exit = QAction('Exit', self) exit.setStatusTip('Exit') exit.setShortcut('Ctrl+Q') exit.triggered.connect(qApp.quit) height = QAction('Height', self) height.setStatusTip('Set board width') height.triggered.connect(self.set_height) width = QAction('Width', self) width.setStatusTip('Set board height') width.triggered.connect(self.set_width) mines = QAction('Mines', self) mines.setStatusTip('Set board mines') mines.triggered.connect(self.set_mines) size = QAction('Size', self) size.setStatusTip('Set button size') size.triggered.connect(self.set_size) toolbar = self.addToolBar('Toolbar') toolbar.addAction(start) toolbar.addAction(width) toolbar.addAction(height) toolbar.addAction(mines) toolbar.addAction(size) toolbar.addAction(exit) self.setWindowTitle(u'DédéNimeur') self.show() def init(self): if self.mines < self.height * self.width: self.board.height = self.height self.board.width = self.width self.board.mines = self.mines self.board.size = self.size self.board.init() else: QMessageBox.question(self, 'NOPE', u"Va falloir spécifier un truc cohérent…", QMessageBox.Ok) def set_height(self): text, ok = QInputDialog.getText(self, 'Settings', 'height') if ok: self.height = int(text) self.init() def set_width(self): text, ok = QInputDialog.getText(self, 'Settings', 'width') if ok: self.width = int(text) self.init() def set_mines(self): text, ok = QInputDialog.getText(self, 'Settings', 'mines') if ok: self.mines = int(text) self.init() def set_size(self): text, ok = QInputDialog.getText(self, 'Settings', 'size') if ok: self.size = int(text) self.init() def start_timers(self): self.timer.start(100, self) self.real_timer.start() self.lcd.display(int(self.real_timer.elapsed() / 1000)) def stop_timers(self): self.timer.stop() return self.real_timer.elapsed() def timerEvent(self, e): self.lcd.display(int(self.real_timer.elapsed() / 1000))
def detection(): while(True): try: data = str(sock.recv(1024),'utf-8') except: data = "" if (data == 'start_object_detection;#'): try: percentage = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "confidency_threshold") except: percentage = "0.9" try: index = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "camera_index") except: index = "0" if os.path.isfile(CWD_TXT): pass else: with open(CWD_TXT, 'a+') as f: f.write('[]' + '\n') if (percentage == ""): percentage = "0.9" percentage = float(percentage) print (index) if index == "": index = 0 f = open(CWD_TXT, 'r+') f.truncate(0) try: video = cv2.VideoCapture(int(index)) width = video.get(cv2.cv2.CAP_PROP_FRAME_WIDTH) height = video.get(cv2.cv2.CAP_PROP_FRAME_HEIGHT) cam_fps = video.get(cv2.cv2.CAP_PROP_FPS) except: pass elapsed_timer = QElapsedTimer() elapsed_timer.start() if video is None or not video.isOpened(): MessageBox("Vendron","Error No such Camera exist", 64) detection() else : sent = True while(True): try: data = str(sock.recv(1024),'utf-8') except: pass if (data == 'end_object_detection;#'): sent = False cv2.destroyWindow('Object detector') video.release() socketSend("object_detection_ended;#") break else: data = [] myList = [] myScore = [] result_list = [] name = [] try: fps = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "frame_rate") except: fps = cam_fps try: ymin_1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_min_threshold_1") except: ymin_1 = "80" try: ymax_1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_max_threshold_1") except: ymax_1 = "240" try: ymin_2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_min_threshold_2") except: ymin_2 = "240" try: ymax_2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_max_threshold_2") except: ymax_2 = "400" try: places = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "is_camera_reversed") except: places = "false" try: w2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "x") except: w2 = "0" try: h2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y") except: h2 = "0" try: w1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "width") except: w1 = "640" try: h1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "height") except: h1 = "480" if video is None: pass else: ret, frame = video.read() if(w1 == ""): w1 = "640" if(w2 == ""): w2 = "0" if(h1 == ""): h1 = "480" if(h2 == ""): h2 = "0" w1 = int(w1) + int(w2) h1 = int(h1) + int(h2) frame = frame[int(h2):int(h1),int(w2):int(w1)] frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_expanded = np.expand_dims(frame, axis=0) # Perform the actual detection by running the model with the image as input try: (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: frame_expanded}) except: pass # Draw the results of the detection (aka 'visulaize the results') try: vis_util.visualize_boxes_and_labels_on_image_array( frame, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=3, min_score_thresh= percentage) data = [category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > percentage] for cl in data: if cl != None : myList.append(str(cl['name'])) objects = [] for index, value in enumerate(classes[0]): object_dict = {} if scores[0, index] > percentage: object_dict[(category_index.get(value)).get('name').encode('utf8')] = \ scores[0, index] objects.append(object_dict) coordinates = vis_util.return_coordinates( frame, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=3, min_score_thresh= percentage) except: pass if(sent == True): socketSend("object_detection_started;#") sent = False if(places == ""): places = "false" if(ymin_1 == ""): ymin_1 = "80" if(ymin_2 == ""): ymin_2 = "240" if(ymax_1 == ""): ymax_1 = "240" if(ymax_2 == ""): ymax_2 = "400" try: if(places == "true"): alpha = 0.3; overlay = frame.copy() cv2.rectangle(overlay, (0, int(ymin_1)), (int(width), int(ymin_2)),(0, 0, 255), -1) cv2.addWeighted(overlay, alpha, frame, 1 - alpha, 0, frame) overlay_blue = frame.copy() cv2.rectangle(overlay_blue, (0, int(ymax_1)), (int(width), int(ymax_2)),(255, 0, 0), -1) cv2.addWeighted(overlay_blue, alpha, frame, 1 - alpha, 0, frame) elif(places == "false"): alpha = 0.3; overlay = frame.copy() cv2.rectangle(overlay, (0, int(ymax_1)), (int(width), int(ymax_2)),(0, 0, 255), -1) cv2.addWeighted(overlay, alpha, frame, 1 - alpha, 0, frame) overlay_blue = frame.copy() cv2.rectangle(overlay_blue, (0, int(ymin_1)), (int(width), int(ymin_2)),(255, 0, 0), -1) cv2.addWeighted(overlay_blue, alpha, frame, 1 - alpha, 0, frame) except: pass if(fps == ""): fps = cam_fps fps = 1/int(fps) print (type(fps)) while(elapsed_timer.hasExpired(fps)): if coordinates is None: print("nothing") else: if video is None: sent = False cv2.destroyWindow('Object detector') socketSend("object_detection_ended;#") break list_1stesult = myList coordinates_result = coordinates for ea_list,ea_coor,score in zip(list_1stesult,coordinates_result,objects): score = str(score) score = score.split(":")[1] score = score.replace("}","") score = score.replace("]","") score = float(score) * 100 score = str(round(score)) result = os.path.join(ea_list,",",str(ea_coor),",",score) result = result.replace("[[","[") result = result.replace("\\","") result = result.replace("[","") result = result.replace("]","") name.append(ea_list) result_list.append(result) print (result_list) result_list = str(result_list).replace("', '","];[") result_list = result_list.replace("'","") result_list = result_list.replace("'","") result_list = result_list.replace(", ",",") if result_list: with open(CWD_TXT, "a") as text_file: text_file.write(str(result_list) + "\n") if result_list: with open(CWD_HISTORY,"a") as text_file: text_file.write(str(result_list) + "\n") elapsed_timer.start() # All the results have been drawn on the frame, so it's time to display it. try: path_debug = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "debug") except: path_debug = "false" if (path_debug == "true"): try: cv2.imshow('Object detector', frame) except: sent = False cv2.destroyWindow('Object detector') video.release() socketSend("object_detection_ended;#") break else: pass if cv2.waitKey(1) == ord ("q"): pass
class comicsExporter(): acbfLocation = str() acbfPageData = [] cometLocation = str() comicRackInfo = str() pagesLocationList = {} # set of keys used to define specific export behaviour for this page. pageKeys = [ "acbf_title", "acbf_none", "acbf_fade", "acbf_blend", "acbf_horizontal", "acbf_vertical", "epub_spread" ] def __init__(self): pass """ The configuration of the exporter. @param config: A dictionary containing all the config. @param projectUrl: the main location of the project folder. """ def set_config(self, config, projectURL): self.configDictionary = config self.projectURL = projectURL self.pagesLocationList = {} self.acbfLocation = str() self.acbfPageData = [] self.cometLocation = str() self.comicRackInfo = str() """ Export everything according to config and get yourself a coffee. This won't work if the config hasn't been set. """ def export(self): export_success = False path = Path(self.projectURL) if path.exists(): # Make a meta-data folder so we keep the export folder nice and clean. exportPath = path / self.configDictionary["exportLocation"] if Path(exportPath / "metadata").exists() is False: Path(exportPath / "metadata").mkdir() # Get to which formats to export, and set the sizeslist. lengthProcess = len(self.configDictionary["pages"]) sizesList = {} if "CBZ" in self.configDictionary.keys(): if self.configDictionary["CBZactive"]: lengthProcess += 5 sizesList["CBZ"] = self.configDictionary["CBZ"] if "EPUB" in self.configDictionary.keys(): if self.configDictionary["EPUBactive"]: lengthProcess += 1 sizesList["EPUB"] = self.configDictionary["EPUB"] if "TIFF" in self.configDictionary.keys(): if self.configDictionary["TIFFactive"]: sizesList["TIFF"] = self.configDictionary["TIFF"] # Export the pngs according to the sizeslist. # Create a progress dialog. self.progress = QProgressDialog(i18n("Preparing export."), str(), 0, lengthProcess) self.progress.setWindowTitle(i18n("Exporting Comic...")) self.progress.setCancelButton(None) self.timer = QElapsedTimer() self.timer.start() self.progress.show() qApp.processEvents() export_success = self.save_out_pngs(sizesList) # Export acbf metadata. if export_success: if "CBZ" in sizesList.keys(): title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): title = str(self.configDictionary["title"]).replace( " ", "_") self.acbfLocation = str(exportPath / "metadata" / str(title + ".acbf")) locationStandAlone = str(exportPath / str(title + ".acbf")) self.progress.setLabelText( i18n("Saving out ACBF and\nACBF standalone")) self.progress.setValue(self.progress.value() + 2) export_success = exporters.ACBF.write_xml( self.configDictionary, self.acbfPageData, self.pagesLocationList["CBZ"], self.acbfLocation, locationStandAlone, self.projectURL) print("CPMT: Exported to ACBF", export_success) # Export and package CBZ and Epub. if export_success: if "CBZ" in sizesList.keys(): export_success = self.export_to_cbz(exportPath) print("CPMT: Exported to CBZ", export_success) if "EPUB" in sizesList.keys(): self.progress.setLabelText(i18n("Saving out EPUB")) self.progress.setValue(self.progress.value() + 1) export_success = exporters.EPUB.export( self.configDictionary, self.projectURL, self.pagesLocationList["EPUB"], self.acbfPageData) print("CPMT: Exported to EPUB", export_success) else: QMessageBox.warning(None, i18n("Export not Possible"), i18n("Nothing to export, URL not set."), QMessageBox.Ok) print("CPMT: Nothing to export, url not set.") return export_success """ This calls up all the functions necessary for making a cbz. """ def export_to_cbz(self, exportPath): title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): title = str(self.configDictionary["title"]).replace(" ", "_") self.progress.setLabelText(i18n("Saving out CoMet\nmetadata file")) self.progress.setValue(self.progress.value() + 1) self.cometLocation = str(exportPath / "metadata" / str(title + " CoMet.xml")) export_success = exporters.CoMet.write_xml( self.configDictionary, self.pagesLocationList["CBZ"], self.cometLocation) self.comicRackInfo = str(exportPath / "metadata" / "ComicInfo.xml") self.progress.setLabelText(i18n("Saving out Comicrack\nmetadata file")) self.progress.setValue(self.progress.value() + 1) export_success = exporters.comic_rack_xml.write_xml( self.configDictionary, self.pagesLocationList["CBZ"], self.comicRackInfo) self.package_cbz(exportPath) return export_success def save_out_pngs(self, sizesList): # A small fix to ensure crop to guides is set. if "cropToGuides" not in self.configDictionary.keys(): self.configDictionary["cropToGuides"] = False # Check if we have pages at all... if "pages" in self.configDictionary.keys(): # Check if there's export methods, and if so make sure the appropriate dictionaries are initialised. if len(sizesList.keys()) < 1: QMessageBox.warning( None, i18n("Export not Possible"), i18n( "Export failed because there's no export settings configured." ), QMessageBox.Ok) print( "CPMT: Export failed because there's no export methods set." ) return False else: for key in sizesList.keys(): self.pagesLocationList[key] = [] # Get the appropriate paths. path = Path(self.projectURL) exportPath = path / self.configDictionary["exportLocation"] pagesList = self.configDictionary["pages"] fileName = str(exportPath) """ Mini function to handle the setup of this string. """ def timeString(timePassed, timeEstimated): return str( i18n("Time passed: {passedString}\n Estimated: {estimated}" )).format(passedString=timePassed, estimated=timeEstimated) for p in range(0, len(pagesList)): pagesDone = str(i18n("{pages} of {pagesTotal} done.")).format( pages=p, pagesTotal=len(pagesList)) # Update the label in the progress dialog. self.progress.setValue(p) timePassed = self.timer.elapsed() if p > 0: timeEstimated = (len(pagesList) - p) * (timePassed / p) estimatedString = self.parseTime(timeEstimated) else: estimatedString = str(u"\u221E") passedString = self.parseTime(timePassed) self.progress.setLabelText("\n".join([ pagesDone, timeString(passedString, estimatedString), i18n("Opening next page") ])) qApp.processEvents() # Get the appropriate url and open the page. url = str(Path(self.projectURL) / pagesList[p]) page = Application.openDocument(url) page.waitForDone() # Update the progress bar a little self.progress.setLabelText("\n".join([ pagesDone, timeString(self.parseTime(self.timer.elapsed()), estimatedString), i18n("Cleaning up page") ])) # remove layers and flatten. labelList = self.configDictionary["labelsToRemove"] panelsAndText = [] # These three lines are what is causing the page not to close. root = page.rootNode() self.getPanelsAndText(root, panelsAndText) self.removeLayers(labelList, root) page.refreshProjection() # We'll need the offset and scale for aligning the panels and text correctly. We're getting this from the CBZ pageData = {} pageData["vector"] = panelsAndText tree = ET.fromstring(page.documentInfo()) pageData["title"] = page.name() calligra = "{http://www.calligra.org/DTD/document-info}" about = tree.find(calligra + "about") keywords = about.find(calligra + "keyword") keys = str(keywords.text).split(",") pKeys = [] for key in keys: if key in self.pageKeys: pKeys.append(key) pageData["keys"] = pKeys page.flatten() page.waitForDone() batchsave = Application.batchmode() Application.setBatchmode(True) # Start making the format specific copy. for key in sizesList.keys(): # Update the progress bar a little self.progress.setLabelText("\n".join([ pagesDone, timeString(self.parseTime(self.timer.elapsed()), estimatedString), str(i18n("Exporting for {key}")).format(key=key) ])) w = sizesList[key] # copy over data projection = page.clone() projection.setBatchmode(True) # Crop. Cropping per guide only happens if said guides have been found. if w["Crop"] is True: listHGuides = [] listHGuides = page.horizontalGuides() listHGuides.sort() for i in range(len(listHGuides) - 1, 0, -1): if listHGuides[i] < 0 or listHGuides[ i] > page.height(): listHGuides.pop(i) listVGuides = page.verticalGuides() listVGuides.sort() for i in range(len(listVGuides) - 1, 0, -1): if listVGuides[i] < 0 or listVGuides[ i] > page.width(): listVGuides.pop(i) if self.configDictionary["cropToGuides"] and len( listVGuides) > 1: cropx = listVGuides[0] cropw = listVGuides[-1] - cropx else: cropx = self.configDictionary["cropLeft"] cropw = page.width( ) - self.configDictionary["cropRight"] - cropx if self.configDictionary["cropToGuides"] and len( listHGuides) > 1: cropy = listHGuides[0] croph = listHGuides[-1] - cropy else: cropy = self.configDictionary["cropTop"] croph = page.height( ) - self.configDictionary["cropBottom"] - cropy projection.crop(cropx, cropy, cropw, croph) projection.waitForDone() qApp.processEvents() # resize appropriately else: cropx = 0 cropy = 0 res = page.resolution() listScales = [ projection.width(), projection.height(), res, res ] projectionOldSize = [ projection.width(), projection.height() ] sizesCalc = sizesCalculator() listScales = sizesCalc.get_scale_from_resize_config( config=w, listSizes=listScales) projection.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic") projection.waitForDone() qApp.processEvents() # png, gif and other webformats should probably be in 8bit srgb at maximum. if key != "TIFF": if (projection.colorModel() != "RGBA" and projection.colorModel() != "GRAYA" ) or projection.colorDepth() != "U8": projection.setColorSpace("RGBA", "U8", "sRGB built-in") else: # Tiff on the other hand can handle all the colormodels, but can only handle integer bit depths. # Tiff is intended for print output, and 16 bit integer will be sufficient. if projection.colorDepth( ) != "U8" or projection.colorDepth() != "U16": projection.setColorSpace(page.colorModel(), "U16", page.colorProfile()) # save # Make sure the folder name for this export exists. It'll allow us to keep the # export folders nice and clean. folderName = str(key + "-" + w["FileType"]) if Path(exportPath / folderName).exists() is False: Path.mkdir(exportPath / folderName) # Get a nice and descriptive fle name. fn = str( Path(exportPath / folderName) / str("page_" + format(p, "03d") + "_" + str(listScales[0]) + "x" + str(listScales[1]) + "." + w["FileType"])) # Finally save and add the page to a list of pages. This will make it easy for the packaging function to # find the pages and store them. projection.exportImage(fn, InfoObject()) projection.waitForDone() qApp.processEvents() if key == "CBZ" or key == "EPUB": transform = {} transform["offsetX"] = cropx transform["offsetY"] = cropy transform["resDiff"] = page.resolution() / 72 transform["scaleWidth"] = projection.width( ) / projectionOldSize[0] transform["scaleHeight"] = projection.height( ) / projectionOldSize[1] pageData["transform"] = transform self.pagesLocationList[key].append(fn) projection.close() self.acbfPageData.append(pageData) page.close() self.progress.setValue(len(pagesList)) Application.setBatchmode(batchsave) # TODO: Check what or whether memory leaks are still caused and otherwise remove the entry below. print( "CPMT: Export has finished. If there are memory leaks, they are caused by file layers." ) return True print("CPMT: Export not happening because there aren't any pages.") QMessageBox.warning( None, i18n("Export not Possible"), i18n("Export not happening because there are no pages."), QMessageBox.Ok) return False """ Function to get the panel and text data. """ def getPanelsAndText(self, node, list): textLayersToSearch = ["text"] panelLayersToSearch = ["panels"] if "textLayerNames" in self.configDictionary.keys(): textLayersToSearch = self.configDictionary["textLayerNames"] if "panelLayerNames" in self.configDictionary.keys(): panelLayersToSearch = self.configDictionary["panelLayerNames"] if node.type() == "vectorlayer": for name in panelLayersToSearch: if str(name).lower() in str(node.name()).lower(): for shape in node.shapes(): if (shape.type() == "groupshape"): self.getPanelsAndTextVector(shape, list) else: self.handleShapeDescription(shape, list) for name in textLayersToSearch: if str(name).lower() in str(node.name()).lower(): for shape in node.shapes(): if (shape.type() == "groupshape"): self.getPanelsAndTextVector(shape, list, True) else: self.handleShapeDescription(shape, list, True) else: if node.childNodes(): for child in node.childNodes(): self.getPanelsAndText(node=child, list=list) def parseTime(self, time=0): timeList = [] timeList.append(str(int(time / 60000))) timeList.append(format(int((time % 60000) / 1000), "02d")) timeList.append(format(int(time % 1000), "03d")) return ":".join(timeList) """ Function to get the panel and text data from a group shape """ def getPanelsAndTextVector(self, group, list, textOnly=False): for shape in group.shapes(): if (shape.type() == "groupshape"): self.getPanelsAndTextVector(shape, list, textOnly) else: self.handleShapeDescription(shape, list, textOnly) """ Function to get text and panels in a format that acbf will accept """ def handleShapeDescription(self, shape, list, textOnly=False): if (shape.type() != "KoSvgTextShapeID" and textOnly is True): return shapeDesc = {} shapeDesc["name"] = shape.name() rect = shape.boundingBox() listOfPoints = [ rect.topLeft(), rect.topRight(), rect.bottomRight(), rect.bottomLeft() ] shapeDoc = minidom.parseString(shape.toSvg()) docElem = shapeDoc.documentElement svgRegExp = re.compile('[MLCSQHVATmlzcqshva]\d+\.?\d* \d+\.?\d*') transform = docElem.getAttribute("transform") coord = [] adjust = QTransform() # TODO: If we get global transform api, use that instead of parsing manually. if "translate" in transform: transform = transform.replace('translate(', '') for c in transform[:-1].split(" "): if "," in c: c = c.replace(",", "") coord.append(float(c)) if len(coord) < 2: coord.append(coord[0]) adjust = QTransform(1, 0, 0, 1, coord[0], coord[1]) if "matrix" in transform: transform = transform.replace('matrix(', '') for c in transform[:-1].split(" "): if "," in c: c = c.replace(",", "") coord.append(float(c)) adjust = QTransform(coord[0], coord[1], coord[2], coord[3], coord[4], coord[5]) path = QPainterPath() if docElem.localName == "path": dVal = docElem.getAttribute("d") listOfSvgStrings = [" "] listOfSvgStrings = svgRegExp.findall(dVal) if listOfSvgStrings: listOfPoints = [] for l in listOfSvgStrings: line = l[1:] coordinates = line.split(" ") if len(coordinates) < 2: coordinates.append(coordinates[0]) x = float(coordinates[-2]) y = float(coordinates[-1]) offset = QPointF() if l.islower(): offset = listOfPoints[0] if l.lower().startswith("m"): path.moveTo(QPointF(x, y) + offset) elif l.lower().startswith("h"): y = listOfPoints[-1].y() path.lineTo(QPointF(x, y) + offset) elif l.lower().startswith("v"): x = listOfPoints[-1].x() path.lineTo(QPointF(x, y) + offset) elif l.lower().startswith("c"): path.cubicTo(coordinates[0], coordinates[1], coordinates[2], coordinates[3], x, y) else: path.lineTo(QPointF(x, y) + offset) path.setFillRule(Qt.WindingFill) for polygon in path.simplified().toSubpathPolygons(adjust): for point in polygon: listOfPoints.append(point) elif docElem.localName == "rect": listOfPoints = [] if (docElem.hasAttribute("x")): x = float(docElem.getAttribute("x")) else: x = 0 if (docElem.hasAttribute("y")): y = float(docElem.getAttribute("y")) else: y = 0 w = float(docElem.getAttribute("width")) h = float(docElem.getAttribute("height")) path.addRect(QRectF(x, y, w, h)) for point in path.toFillPolygon(adjust): listOfPoints.append(point) elif docElem.localName == "ellipse": listOfPoints = [] if (docElem.hasAttribute("cx")): x = float(docElem.getAttribute("cx")) else: x = 0 if (docElem.hasAttribute("cy")): y = float(docElem.getAttribute("cy")) else: y = 0 ry = float(docElem.getAttribute("ry")) rx = float(docElem.getAttribute("rx")) path.addEllipse(QPointF(x, y), rx, ry) for point in path.toFillPolygon(adjust): listOfPoints.append(point) elif docElem.localName == "text": # NOTE: This only works for horizontal preformated text. Vertical text needs a different # ordering of the rects, and wraparound should try to take the shape it is wrapped in. family = "sans-serif" if docElem.hasAttribute("font-family"): family = docElem.getAttribute("font-family") size = "11" if docElem.hasAttribute("font-size"): size = docElem.getAttribute("font-size") multilineText = True for el in docElem.childNodes: if el.nodeType == minidom.Node.TEXT_NODE: multilineText = False if multilineText: listOfPoints = [] listOfRects = [] # First we collect all the possible line-rects. for el in docElem.childNodes: if docElem.hasAttribute("font-family"): family = docElem.getAttribute("font-family") if docElem.hasAttribute("font-size"): size = docElem.getAttribute("font-size") fontsize = int(size) font = QFont(family, fontsize) string = el.toxml() string = re.sub("\<.*?\>", " ", string) string = string.replace(" ", " ") width = min( QFontMetrics(font).width(string.strip()), rect.width()) height = QFontMetrics(font).height() anchor = "start" if docElem.hasAttribute("text-anchor"): anchor = docElem.getAttribute("text-anchor") top = rect.top() if len(listOfRects) > 0: top = listOfRects[-1].bottom() if anchor == "start": spanRect = QRectF(rect.left(), top, width, height) listOfRects.append(spanRect) elif anchor == "end": spanRect = QRectF(rect.right() - width, top, width, height) listOfRects.append(spanRect) else: # Middle spanRect = QRectF(rect.center().x() - (width * 0.5), top, width, height) listOfRects.append(spanRect) # Now we have all the rects, we can check each and draw a # polygon around them. heightAdjust = ( rect.height() - (listOfRects[-1].bottom() - rect.top())) / len(listOfRects) for i in range(len(listOfRects)): span = listOfRects[i] addtionalHeight = i * heightAdjust if i == 0: listOfPoints.append(span.topLeft()) listOfPoints.append(span.topRight()) else: if listOfRects[i - 1].width() < span.width(): listOfPoints.append( QPointF(span.right(), span.top() + addtionalHeight)) listOfPoints.insert( 0, QPointF(span.left(), span.top() + addtionalHeight)) else: bottom = listOfRects[i - 1].bottom( ) + addtionalHeight - heightAdjust listOfPoints.append( QPointF(listOfRects[i - 1].right(), bottom)) listOfPoints.insert( 0, QPointF(listOfRects[i - 1].left(), bottom)) listOfPoints.append(QPointF(span.right(), rect.bottom())) listOfPoints.insert(0, QPointF(span.left(), rect.bottom())) path = QPainterPath() path.moveTo(listOfPoints[0]) for p in range(1, len(listOfPoints)): path.lineTo(listOfPoints[p]) path.closeSubpath() listOfPoints = [] for point in path.toFillPolygon(adjust): listOfPoints.append(point) shapeDesc["boundingBox"] = listOfPoints if (shape.type() == "KoSvgTextShapeID" and textOnly is True): shapeDesc["text"] = shape.toSvg() list.append(shapeDesc) """ Function to remove layers when they have the given labels. If not, but the node does have children, check those too. """ def removeLayers(self, labels, node): if node.colorLabel() in labels: node.remove() else: if node.childNodes(): for child in node.childNodes(): self.removeLayers(labels, node=child) """ package cbz puts all the meta-data and relevant files into an zip file ending with ".cbz" """ def package_cbz(self, exportPath): # Use the project name if there's no title to avoid sillyness with unnamed zipfiles. title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): title = str(self.configDictionary["title"]).replace(" ", "_") # Get the appropriate path. url = str(exportPath / str(title + ".cbz")) # Create a zip file. cbzArchive = zipfile.ZipFile(url, mode="w", compression=zipfile.ZIP_STORED) # Add all the meta data files. cbzArchive.write(self.acbfLocation, Path(self.acbfLocation).name) cbzArchive.write(self.cometLocation, Path(self.cometLocation).name) cbzArchive.write(self.comicRackInfo, Path(self.comicRackInfo).name) comic_book_info_json_dump = str() self.progress.setLabelText( i18n("Saving out Comicbook\ninfo metadata file")) self.progress.setValue(self.progress.value() + 1) comic_book_info_json_dump = exporters.comic_book_info.writeJson( self.configDictionary) cbzArchive.comment = comic_book_info_json_dump.encode("utf-8") # Add the pages. if "CBZ" in self.pagesLocationList.keys(): for page in self.pagesLocationList["CBZ"]: if (Path(page).exists()): cbzArchive.write(page, Path(page).name) self.progress.setLabelText(i18n("Packaging CBZ")) self.progress.setValue(self.progress.value() + 1) # Close the zip file when done. cbzArchive.close()
def save_out_pngs(self, sizesList): # A small fix to ensure crop to guides is set. if "cropToGuides" not in self.configDictionary.keys(): self.configDictionary["cropToGuides"] = False # Check if we have pages at all... if "pages" in self.configDictionary.keys(): # Check if there's export methods, and if so make sure the appropriate dictionaries are initialised. if len(sizesList.keys()) < 1: print( "CPMT: Export failed because there's no export methods set." ) return False else: for key in sizesList.keys(): self.pagesLocationList[key] = [] # Get the appropriate paths. path = Path(self.projectURL) exportPath = path / self.configDictionary["exportLocation"] pagesList = self.configDictionary["pages"] fileName = str(exportPath) # Create a progress dialog. progress = QProgressDialog("Preparing export.", str(), 0, len(pagesList)) progress.setWindowTitle("Exporting comic...") progress.setCancelButton(None) timer = QElapsedTimer() timer.start() progress.show() qApp.processEvents() for p in range(0, len(pagesList)): # Update the label in the progress dialog. progress.setValue(p) timePassed = timer.elapsed() if (p > 0): timeEstimated = (len(pagesList) - p) * (timePassed / p) passedString = str(int(timePassed / 60000)) + ":" + format( int(timePassed / 1000), "02d") + ":" + format( timePassed % 1000, "03d") estimatedString = str(int( timeEstimated / 60000)) + ":" + format( int(timeEstimated / 1000), "02d") + ":" + format( int(timeEstimated % 1000), "03d") progress.setLabelText( str( i18n( "{pages} of {pagesTotal} done. \nTime passed: {passedString}:\n Estimated:{estimated}" )).format(pages=p, pagesTotal=len(pagesList), passedString=passedString, estimated=estimatedString)) qApp.processEvents() # Get the appropriate url and open the page. url = str(Path(self.projectURL) / pagesList[p]) page = Application.openDocument(url) page.waitForDone() # remove layers and flatten. labelList = self.configDictionary["labelsToRemove"] panelsAndText = [] # These three lines are what is causing the page not to close. root = page.rootNode() self.getPanelsAndText(root, panelsAndText) self.removeLayers(labelList, root) page.refreshProjection() # We'll need the offset and scale for aligning the panels and text correctly. We're getting this from the CBZ pageData = {} pageData["vector"] = panelsAndText tree = ET.fromstring(page.documentInfo()) pageData["title"] = page.name() calligra = "{http://www.calligra.org/DTD/document-info}" about = tree.find(calligra + "about") keywords = about.find(calligra + "keyword") keys = str(keywords.text).split(",") pKeys = [] for key in keys: if key in self.pageKeys: pKeys.append(key) pageData["keys"] = pKeys page.flatten() page.waitForDone() batchsave = Application.batchmode() Application.setBatchmode(True) # Start making the format specific copy. for key in sizesList.keys(): w = sizesList[key] # copy over data projection = page.clone() projection.setBatchmode(True) # Crop. Cropping per guide only happens if said guides have been found. if w["Crop"] is True: listHGuides = [] listHGuides = page.horizontalGuides() listHGuides.sort() for i in range(len(listHGuides) - 1, 0, -1): if listHGuides[i] < 0 or listHGuides[ i] > page.height(): listHGuides.pop(i) listVGuides = page.verticalGuides() listVGuides.sort() for i in range(len(listVGuides) - 1, 0, -1): if listVGuides[i] < 0 or listVGuides[ i] > page.width(): listVGuides.pop(i) if self.configDictionary["cropToGuides"] and len( listVGuides) > 1: cropx = listVGuides[0] cropw = listVGuides[-1] - cropx else: cropx = self.configDictionary["cropLeft"] cropw = page.width( ) - self.configDictionary["cropRight"] - cropx if self.configDictionary["cropToGuides"] and len( listHGuides) > 1: cropy = listHGuides[0] croph = listHGuides[-1] - cropy else: cropy = self.configDictionary["cropTop"] croph = page.height( ) - self.configDictionary["cropBottom"] - cropy projection.crop(cropx, cropy, cropw, croph) projection.waitForDone() qApp.processEvents() # resize appropriately else: cropx = 0 cropy = 0 res = page.resolution() listScales = [ projection.width(), projection.height(), res, res ] projectionOldSize = [ projection.width(), projection.height() ] sizesCalc = sizesCalculator() listScales = sizesCalc.get_scale_from_resize_config( config=w, listSizes=listScales) projection.unlock() projection.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic") projection.waitForDone() qApp.processEvents() # png, gif and other webformats should probably be in 8bit srgb at maximum. if key != "TIFF": if (projection.colorModel() != "RGBA" and projection.colorModel() != "GRAYA" ) or projection.colorDepth() != "U8": projection.setColorSpace("RGBA", "U8", "sRGB built-in") else: # Tiff on the other hand can handle all the colormodels, but can only handle integer bit depths. # Tiff is intended for print output, and 16 bit integer will be sufficient. if projection.colorDepth( ) != "U8" or projection.colorDepth() != "U16": projection.setColorSpace(page.colorModel(), "U16", page.colorProfile()) # save # Make sure the folder name for this export exists. It'll allow us to keep the # export folders nice and clean. folderName = str(key + "-" + w["FileType"]) if Path(exportPath / folderName).exists() is False: Path.mkdir(exportPath / folderName) # Get a nice and descriptive fle name. fn = str( Path(exportPath / folderName) / str("page_" + format(p, "03d") + "_" + str(listScales[0]) + "x" + str(listScales[1]) + "." + w["FileType"])) # Finally save and add the page to a list of pages. This will make it easy for the packaging function to # find the pages and store them. projection.exportImage(fn, InfoObject()) projection.waitForDone() qApp.processEvents() if key == "CBZ": transform = {} transform["offsetX"] = cropx transform["offsetY"] = cropy transform["resDiff"] = page.resolution() / 72 transform["scaleWidth"] = projection.width( ) / projectionOldSize[0] transform["scaleHeight"] = projection.height( ) / projectionOldSize[1] pageData["transform"] = transform self.pagesLocationList[key].append(fn) projection.close() self.acbfPageData.append(pageData) page.close() progress.setValue(len(pagesList)) Application.setBatchmode(batchsave) # TODO: Check what or whether memory leaks are still caused and otherwise remove the entry below. print( "CPMT: Export has finished. If there are memory leaks, they are caused by file layers." ) return True print("CPMT: Export not happening because there aren't any pages.") return False
class Program(QObject): def __init__(self, **kwargs): QObject.__init__(self) self.filename = kwargs.get("filename") self.text_code = kwargs.get("code") self.__python_exec = kwargs.get("python_exec") self.pre_script = kwargs.get("pre_script") self.post_script = kwargs.get("post_script") self.__params = kwargs.get("params") self.__elapsed = QElapsedTimer() self.outputw = None self.__current_process = None self.main_process = QProcess(self) self.main_process.started.connect(self._process_started) self.main_process.finished.connect(self._process_finished) self.main_process.finished.connect(self.__post_execution) self.main_process.readyReadStandardOutput.connect(self._refresh_output) self.main_process.readyReadStandardError.connect(self._refresh_error) self.pre_process = QProcess(self) self.pre_process.started.connect(self._process_started) self.pre_process.finished.connect(self._process_finished) self.pre_process.finished.connect(self.__main_execution) self.pre_process.readyReadStandardOutput.connect(self._refresh_output) self.pre_process.readyReadStandardError.connect(self._refresh_error) self.post_process = QProcess(self) self.post_process.started.connect(self._process_started) self.post_process.finished.connect(self._process_finished) self.post_process.readyReadStandardOutput.connect(self._refresh_output) self.post_process.readyReadStandardError.connect(self._refresh_error) def start(self): self.__pre_execution() self.outputw.setFocus() def __pre_execution(self): """Execute a script before executing the project""" self.__current_process = self.pre_process file_pre_exec = QFile(self.pre_script) if file_pre_exec.exists(): ext = file_manager.get_file_extension(self.pre_script) args = [] if ext == "py": program = self.python_exec # -u: Force python to unbuffer stding ad stdout args.append("-u") args.append(self.pre_script) elif ext == "sh": program = "bash" args.append(self.pre_script) else: program = self.pre_script self.pre_process.setProgram(program) self.pre_process.setArguments(args) self.pre_process.start() else: self.__main_execution() def __main_execution(self): self.__elapsed.start() self.__current_process = self.main_process if not self.only_text: # In case a text is executed and not a file or project file_directory = file_manager.get_folder(self.filename) self.main_process.setWorkingDirectory(file_directory) self.main_process.setProgram(self.python_exec) self.main_process.setArguments(self.arguments) environment = QProcessEnvironment() system_environment = self.main_process.systemEnvironment() for env in system_environment: key, value = env.split("=", 1) environment.insert(key, value) self.main_process.setProcessEnvironment(environment) self.main_process.start() def __post_execution(self): """Execute a script after executing the project.""" self.__current_process = self.post_process file_pre_exec = QFile(self.post_script) if file_pre_exec.exists(): ext = file_manager.get_file_extension(self.post_script) args = [] if ext == "py": program = self.python_exec # -u: Force python to unbuffer stding ad stdout args.append("-u") args.append(self.post_script) elif ext == "sh": program = "bash" args.append(self.post_script) else: program = self.post_script self.post_process.setProgram(program) self.post_process.setArguments(args) self.post_process.start() @property def process_name(self): proc = self.__current_process return proc.program() + " " + " ".join(proc.arguments()) def update(self, **kwargs): self.text_code = kwargs.get("code") self.__python_exec = kwargs.get("python_exec") self.pre_script = kwargs.get("pre_script") self.post_script = kwargs.get("post_script") self.__params = kwargs.get("params") def set_output_widget(self, ow): self.outputw = ow self.outputw.inputRequested.connect(self._write_input) def _write_input(self, data): self.main_process.write(data.encode()) self.main_process.write(b"\n") def is_running(self): running = False if self.main_process.state() == QProcess.Running: running = True return running def _process_started(self): time_str = QTime.currentTime().toString("hh:mm:ss") text = time_str + " Running: " + self.process_name self.outputw.append_text(text) self.outputw.setReadOnly(False) def _process_finished(self, code, status): frmt = OutputWidget.Format.NORMAL if status == QProcess.NormalExit == code: text = translations.TR_PROCESS_EXITED_NORMALLY % code else: text = translations.TR_PROCESS_INTERRUPTED frmt = OutputWidget.Format.ERROR self.outputw.append_text(text, frmt) if self.__current_process is self.main_process: tformat = QTime(0, 0, 0, 0).addMSecs( self.__elapsed.elapsed() + 500) time = tformat.toString("h:mm:ss") if time.startswith("0:"): # Don't display zero hours time = time[2:] self.outputw.append_text(translations.TR_ELAPSED_TIME.format(time)) self.outputw.setReadOnly(True) def _refresh_output(self): data = self.__current_process.readAllStandardOutput().data().decode() for line in data.splitlines(): self.outputw.append_text( line, text_format=OutputWidget.Format.NORMAL) def _refresh_error(self): data = self.__current_process.readAllStandardError().data().decode() for line_text in data.splitlines(): frmt = OutputWidget.Format.ERROR if self.outputw.patLink.match(line_text): frmt = OutputWidget.Format.ERROR_UNDERLINE self.outputw.append_text(line_text, frmt) def display_name(self): name = "New document" if not self.only_text: name = file_manager.get_basename(self.filename) return name @property def only_text(self): return self.filename is None @property def python_exec(self): py_exec = self.__python_exec if not py_exec: py_exec = settings.PYTHON_EXEC return py_exec @property def arguments(self): args = [] if self.text_code: args.append("-c") args.append(self.text_code) else: # Force python to unbuffer stding and stdout args.append("-u") args += settings.EXECUTION_OPTIONS.split() args.append(self.filename) return args def kill(self): self.main_process.kill()
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}')
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())
for i in range(0, len(avg_colors[face])): current_color = avg_colors[face][i] if i == 4: identifier = face[0] else: identifier = get_identifier(current_color, center_colors) cubestring += identifier # for #compare averages to center color return cubestring #when executed directly as means to benchmark if __name__ == "__main__": f = open("imageBenchmark.txt", "w") overall = 0 for i in range(0, 1000): timer = QElapsedTimer() timer.start() cubestring = analyzeCubeImages(bDebug=0) end = timer.nsecsElapsed() f.write("{}\n".format(end)) print(end) overall += end f.close() # print("; "+cubestring) # print(overall//20)
class RobotGame(QWidget): keysPressedSignal = pyqtSignal(list) def __init__(self): super().__init__() # Load level data from file if DUEL_MODE: self.levelMatrix, self.obstacles = LevelLoader.loadLevel( 'arena.txt') self.spawnPlayer1 = QVector2D(50, 500) self.spawnPlayer2 = QVector2D(950, 500) else: self.levelMatrix, self.obstacles = LevelLoader.loadLevel( 'level2.txt') self.spawnPlayer1 = QVector2D(550, 550) self.spawnPlayer2 = QVector2D(450, 450) self.initUI() self.initTextures() self.initRobots() self.initTimer() self.keysPressed = [] self.keysPressed2 = [] def initTextures(self): self.tileTextures = { tileEnum: QPixmap('textures/' + tileName + '.png') for tileName, tileEnum in Tile.__members__.items() } def initUI(self): self.setGeometry(START_WINDOW_X_POS, START_WINDOW_Y_POS, WINDOW_SIZE, WINDOW_SIZE) self.setWindowTitle(WINDOW_TITLE) self.show() def initTimer(self): self.gameTimer = QBasicTimer() self.gameTimer.start(TICK_INTERVALL, self) # For deltaTime self.elapsedTimer = QElapsedTimer() self.elapsedTimer.start() self.previous = 0 self.tickCounter = 0 def initRobots(self): self.robots = {} player1 = robots.TestRobot(1, self.spawnPlayer1.x(), self.spawnPlayer1.y(), control.PlayerController) player2 = robots.TestRobot(2, self.spawnPlayer2.x(), self.spawnPlayer2.y(), control.XboxController) if GOD_MODE: handgun = Handgun(player1, 500, 0.1, 80) shotgun = Shotgun(player1, 200, 0.1, 10, 20) grenade = GrenadeLauncher(player1, 200, 0.1, 10, 100) handgun_player_2 = Handgun(player2, 500, 0.1, 80) shotgun_player_2 = Shotgun(player2, 200, 0.1, 10, 20) grenade_player_2 = GrenadeLauncher(player2, 200, 0.1, 10, 100) else: handgun = Handgun(player1, 500, 1, 80) shotgun = Shotgun(player1, 200, 2, 10, 20) grenade = GrenadeLauncher(player1, 200, 3, 10, 100) handgun_player_2 = Handgun(player2, 500, 1, 80) shotgun_player_2 = Shotgun(player2, 200, 2, 10, 20) grenade_player_2 = GrenadeLauncher(player2, 200, 3, 10, 100) handgun.hitSignal.connect(self.hitSignalSlot) shotgun.hitSignal.connect(self.hitSignalSlot) grenade.hitSignal.connect(self.hitSignalSlot) handgun_player_2.hitSignal.connect(self.hitSignalSlot) shotgun_player_2.hitSignal.connect(self.hitSignalSlot) grenade_player_2.hitSignal.connect(self.hitSignalSlot) player1.equipWithGuns(handgun, shotgun, grenade) player2.equipWithGuns(handgun_player_2, shotgun_player_2, grenade_player_2) self.keysPressedSignal.connect(player1.controller.keysPressedSlot) if DUEL_MODE: self.robots = {robot.id: robot for robot in [player1, player2]} else: chaser1 = robots.ChaserRobot(3, 200, 500, 1, 200, control.ChaseDirectlyController) handgun1 = Handgun(chaser1, 500, 2, 80) chaser1.equipWithGuns(handgun1) handgun1.hitSignal.connect(self.hitSignalSlot) chaser2 = robots.ChaserRobot(4, 500, 200, 1, 200, control.ChasePredictController) handgun2 = Handgun(chaser2, 500, 2, 80) chaser2.equipWithGuns(handgun2) handgun2.hitSignal.connect(self.hitSignalSlot) chaser3 = robots.ChaserRobot(5, 800, 500, 1, 200, control.ChaseGuardController) handgun3 = Handgun(chaser3, 500, 2, 80) chaser3.equipWithGuns(handgun3) handgun3.hitSignal.connect(self.hitSignalSlot) self.robots = { robot.id: robot for robot in [player1, player2, chaser1, chaser2, chaser3] } for robot in self.robots.values(): robot.connectSignals() # Tell the controller the specs of the robot (a_max and a_alpha_max) robot.robotSpecsSignal.emit(robot.a_max, robot.a_alpha_max, robot.v_max, robot.v_alpha_max) # Start the controller threads robot.controller.start() def paintEvent(self, event): qp = QPainter() qp.begin(self) self.drawTiles(event, qp) for robot in self.robots.values(): robot.draw(qp) if DEBUG_LINES: self.drawObstaclesDebugLines(qp) for robot in self.robots.values(): robot.drawDebugLines(qp) qp.end() def drawTiles(self, event, qp): qp.setPen(Qt.NoPen) for row in range(NUMBER_OF_TILES): for column in range(NUMBER_OF_TILES): tile = self.levelMatrix[row][column] texture = self.tileTextures[tile] qp.drawPixmap(column * TILE_SIZE, row * TILE_SIZE, texture) def drawObstaclesDebugLines(self, qp): qp.setPen(Qt.blue) qp.setBrush(QBrush(Qt.NoBrush)) for rect in self.obstacles: qp.drawRect(rect) def timerEvent(self, event): self.tickCounter += 1 elapsed = self.elapsedTimer.elapsed() deltaTimeMillis = elapsed - self.previous deltaTime = deltaTimeMillis / MILLISECONDS_PER_SECOND if deltaTime < 0.5: # Update robots for robot in self.robots.values(): robot.update(deltaTime, self.levelMatrix, self.robots) # send positions data every 5th tick if self.tickCounter % 5 == 0: for robot in self.robots.values(): self.emitRobotSensorData(robot) # send key information to player controller self.keysPressedSignal.emit(self.keysPressed) # Update visuals self.update() self.previous = elapsed def emitRobotSensorData(self, robot): cone = robot.view_cone() robotsInView = {} timestamp = QDateTime.currentMSecsSinceEpoch() # Special case for runner robot: He sees everything: if isinstance(robot, robots.RunnerRobot): ids = self.robots.keys() wallsInView = self.obstacles else: # Get ids of all robots that are in view, i.e. that intersect with the view cone ids = filter(lambda id: cone.intersects(self.robots[id].shape()), self.robots) wallsInView = filter(cone.intersects, self.obstacles) for id in ids: other = self.robots[id] dist = (robot.pos - other.pos).length() angle = math.degrees( math.atan2(other.y - robot.y, other.x - robot.x)) robotsInView[id] = { 'x': other.x, 'y': other.y, 'id': other.id, 'pos': QVector2D(other.x, other.y), 'dist': dist, 'angle': angle, 'timestamp': timestamp } robot.robotsInViewSignal.emit(robotsInView) robot.wallsInViewSignal.emit(list(wallsInView)) def keyPressEvent(self, event): self.keysPressed.append(event.key()) def keyReleaseEvent(self, event): self.keysPressed.remove(event.key()) ### Slots # Will be called whenever a robot kills another robot. id is the id of the robots that has to be killed def hitSignalSlot(self, id, damage): self.robots[id].dealDamage(damage)
from time import sleep from PyQt5.QtCore import QTimer, QElapsedTimer from PyQt5.QtWidgets import QApplication from pyprone.entities.midifile import PrMidiFile from pyprone.entities.midifile.track import PrMidiTrack from pyprone.core.helpers.formats import sec2HMSF, tick2MBT, MBT2tick, tempo2bpm from mido import open_output midifile = PrMidiFile('midifile') midifile.load('./pyprone/resources/midifiles/a-whole-new-world.mid') port = open_output('Microsoft GS Wavetable Synth 0') etimer = QElapsedTimer() etimerT = QElapsedTimer() etimerT.start() for track in midifile.tracks: etimer.start() for t in track: pass print(f'{track.no} : {etimer.elapsed()}') print(f'total elapsed : {etimerT.elapsed()}') midifile.tracks[0].rewind(MBT2tick(7, 1, 0, midifile.tpb)) print(midifile.tracks[0]) print(midifile.tracks[0].idx) print(midifile.tracks[0].msg)
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())