コード例 #1
0
ファイル: Watch.py プロジェクト: ChSt98/KraftKonnect
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)
コード例 #2
0
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)
コード例 #3
0
ファイル: CBullet_MAC.py プロジェクト: Envl/BulletGo
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")
コード例 #4
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("KOSAN KEDİ...")
        self.resize(512, 256)

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

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

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

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

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.drawImage(0, 0, self.sprite_sheet, self.x, self.y, self.sw, self.sh)
コード例 #5
0
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
コード例 #6
0
    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()
コード例 #7
0
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()
コード例 #8
0
class CartPoleWidget(QWidget):
    # Emitted when a key is pressed
    keyPressed = pyqtSignal(object)

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

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

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

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

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

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

        # Schedule a repaint
        self.repaint()

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

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

        # Schedule a repaint
        self.repaint()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.setEnabled(True)

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

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

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

    @environment.setter
    def environment(self, val):
        self._environment = val
        self.syncUI()
コード例 #9
0
    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
コード例 #10
0
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()
コード例 #11
0
ファイル: view.py プロジェクト: duniter/sakia
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)
コード例 #12
0
ファイル: gameview.py プロジェクト: Litude/py-labyrinth
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
コード例 #13
0
ファイル: run_widget.py プロジェクト: yijiangtian/ninja-ide
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()
コード例 #14
0
                         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_())
コード例 #15
0
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)
コード例 #16
0
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))
コード例 #17
0
ファイル: dedenimeur.py プロジェクト: nim65s/scripts
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))
コード例 #18
0
class RoomRow(QFrame):
    def __init__(self, idRoom):
        super(RoomRow, self).__init__()
        self.setStyleSheet(
            'QFrame {background: #757575; border-radius: 10px; margin: 0px}')
        self.setFixedHeight(50)

        self.callModel = service.CallModel()

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

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

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

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

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

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

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

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

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

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

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

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

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

    def disable(self):
        self.setStyleSheet(
            'QFrame {background: #757575; border-radius: 10px; margin: 0px}')