コード例 #1
0
ファイル: app.py プロジェクト: thamizha/pykalappai
    def __init__(self):
        # Initialize
        app = QApplication(sys.argv)
        app.setApplicationName("eKalappai")
        app.setApplicationVersion("4.0.0")
        shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

        # Check if already another instance of app is running and quit if it is
        if not shared.create(512, QSharedMemory.ReadWrite):
            qWarning("Cannot start more than one instance of eKalappai any time.")
            exit(0)

        # Splash Screen init
        splashImage = QPixmap(':intro/splash_screen')
        splashScreen = QSplashScreen(splashImage)
        splashScreen.show()
        # Time wait for splash screen to be shown
        time.sleep(2)
        splashScreen.hide()

        # Main application starting
        QApplication.setQuitOnLastWindowClosed(False)
        ekWindow = EKWindow(app)

        # EK Engine start
        ekWindow.engine.start()
        
        sys.exit(app.exec_())
コード例 #2
0
	def sidePlaceHolderRect ( self, widget, side ):
		widgetRect = widget.rect ()
		parentSplitter = cast ( widget.parentWidget (), QSplitter )
		if parentSplitter and parentSplitter.indexOf (widget) > 0:
			delta = parentSplitter.handleWidth () / 2 + self.rubberBandLineWidth / 2
			if side == ToolWindowManager.TopOf and parentSplitter.orientation () == Qt.Vertical:
				return QRect (QPoint ( widgetRect.left (), widgetRect.top () - int (delta) ),
										 QSize ( widgetRect.width (), self.rubberBandLineWidth ) )
			elif side == ToolWindowManager.LeftOf and parentSplitter.orientation () == Qt.Horizontal:
				return QRect (QPoint (widgetRect.left () - int (delta), widgetRect.top ()),
										 QSize (self.rubberBandLineWidth, widgetRect.height ()))

		if side == ToolWindowManager.TopOf:
			return QRect (QPoint (widgetRect.left (), widgetRect.top ()),
									 QSize (widgetRect.width (), self.rubberBandLineWidth))
		elif side == ToolWindowManager.LeftOf:
			return QRect (QPoint (widgetRect.left (), widgetRect.top ()),
									 QSize (self.rubberBandLineWidth, widgetRect.height ()))
		elif side == ToolWindowManager.BottomOf:
			return QRect (QPoint (widgetRect.left (), widgetRect.top () + widgetRect.height () - self.rubberBandLineWidth),
									 QSize (widgetRect.width (), self.rubberBandLineWidth))
		elif side == ToolWindowManager.RightOf:
			return QRect (QPoint (widgetRect.left () + widgetRect.width () - self.rubberBandLineWidth, widgetRect.top ()),
									 QSize (self.rubberBandLineWidth, widgetRect.height ()))
		else:
			qWarning ( 'invalid side' )
			return QRect ()
コード例 #3
0
	def event ( self, event ):
		if not self.areaDragCanStart and event.type () == QEvent.MouseButtonPress and not self.manager.config.setdefault (
			QTWM_AREA_SHOW_DRAG_HANDLE, False ):
			floatingWrapper = False
			wrapper = self.wrapper ()
			if wrapper and self.manager.isFloatingWrapper ( wrapper.getWidget () ):
				floatingWrapper = True

			if not floatingWrapper and self.currentWidget () and not self.currentWidget ().rect ().contains (
					self.currentWidget ().mapFromGlobal ( QCursor.pos () ) ):
				self.areaDragCanStart = True
				qWarning ( "[QToolWindowArea] event: areaDragCanStart = true" )
		elif event.type () == QEvent.MouseMove and not self.manager.config.setdefault ( QTWM_AREA_SHOW_DRAG_HANDLE,
		                                                                                   False ):
			if self.areaDragCanStart:
				if qApp.mouseButtons () == QtCore.Qt.LeftButton:
					toolWindows = [ ]
					for i in range ( 0, self.count () ):
						toolWindow = self.widget ( i )
						if cast ( toolWindow, QToolWindowSingleTabAreaFrame ) == self.tabFrame:
							toolWindow = self.tabFrame.contents
						toolWindows.append ( toolWindow )
					self.areaDragCanStart = False
					qWarning ( "[QToolWindowArea] event: areaDragCanStart = false" )
					self.manager.startDrag ( toolWindows, self )
					self.releaseMouse ()

		return QTabWidget.event ( self, event )
コード例 #4
0
ファイル: canvasbezierlinemov.py プロジェクト: jalxes/Carla
    def __init__(self, port_mode, port_type, parent):
        QGraphicsPathItem.__init__(self)
        self.setParentItem(parent)

        self.m_port_mode = port_mode
        self.m_port_type = port_type

        # Port position doesn't change while moving around line
        self.p_itemX = self.scenePos().x()
        self.p_itemY = self.scenePos().y()
        self.p_width = parent.getPortWidth()

        if port_type == PORT_TYPE_AUDIO_JACK:
            pen = QPen(canvas.theme.line_audio_jack, 2)
        elif port_type == PORT_TYPE_MIDI_JACK:
            pen = QPen(canvas.theme.line_midi_jack, 2)
        elif port_type == PORT_TYPE_MIDI_ALSA:
            pen = QPen(canvas.theme.line_midi_alsa, 2)
        elif port_type == PORT_TYPE_PARAMETER:
            pen = QPen(canvas.theme.line_parameter, 2)
        else:
            qWarning(
                "PatchCanvas::CanvasBezierLineMov({}, {}, {}) - invalid port type"
                .format(port_mode2str(port_mode), port_type2str(port_type),
                        parent))
            pen = QPen(Qt.black)

        pen.setCapStyle(Qt.FlatCap)
        pen.setWidthF(pen.widthF() + 0.00001)
        self.setPen(pen)
コード例 #5
0
 def __thumbnailCreated(self, image, thumbnailer):
     """
     Private slot to handle the creation of a thumbnail image.
     
     @param image thumbnail image
     @type QPixmap
     @param thumbnailer reference to the page thumbnailer
     @type PageThumbnailer
     """
     if thumbnailer in self.__thumbnailers:
         loadTitle = thumbnailer.loadTitle()
         title = thumbnailer.title()
         url = thumbnailer.url().toString()
         fileName = self.__imageFileName(url)
         
         if image.isNull():
             fileName = "qrc:icons/brokenPage.png"
             title = self.tr("Unable to load")
             page = self.pageForUrl(thumbnailer.url())
             page.broken = True
         else:
             if not image.save(fileName, "PNG"):
                 qWarning(
                     "SpeedDial.__thumbnailCreated: Cannot save thumbnail"
                     " to {0}".format(fileName))
         
         self.__regenerateScript = True
         thumbnailer.deleteLater()
         self.__thumbnailers.remove(thumbnailer)
         
         if loadTitle:
             self.pageTitleLoaded.emit(url, title)
         
         self.thumbnailLoaded.emit(
             url, pixmapToDataUrl(QPixmap(fileName)).toString())
コード例 #6
0
    def storeHeadingData(self, token, text):
        if token.type in [
                MTT.TokenAtxHeading1, MTT.TokenAtxHeading2,
                MTT.TokenAtxHeading3, MTT.TokenAtxHeading4,
                MTT.TokenAtxHeading5, MTT.TokenAtxHeading6
        ]:
            level = token.type - MTT.TokenAtxHeading1 + 1
            s = token.position + token.openingMarkupLength
            l = (token.length - token.openingMarkupLength -
                 token.closingMarkupLength)
            headingText = text[s:s + l].strip()

        elif token.type == MTT.TokenSetextHeading1Line1:
            level = 1
            headingText = text

        elif token.type == MTT.TokenSetextHeading2Line1:
            level = 2
            headingText = text

        else:
            qWarning("MarkdownHighlighter.storeHeadingData() encountered" +
                     " unexpected token: {}".format(token.getType()))
            return

        # FIXME: TypeError: could not convert 'TextBlockData' to 'QTextBlockUserData'
        # blockData = self.currentBlockUserData()
        # if blockData is None:
        #     blockData = TextBlockData(self.document(), self.currentBlock())
        #
        # self.setCurrentBlockUserData(blockData)
        self.headingFound.emit(level, headingText, self.currentBlock())
コード例 #7
0
	def swapAreaType ( self, oldArea, areaType = QTWMWrapperAreaType.watTabs ):
		from QToolWindowManager.QToolWindowWrapper import QToolWindowWrapper
		from QToolWindowManager.QToolWindowCustomWrapper import QToolWindowCustomWrapper
		targetWrapper = findClosestParent ( oldArea.getWidget (), [ QToolWindowWrapper, QToolWindowCustomWrapper ] )
		parentSplitter = cast ( oldArea.parentWidget (), QSplitter )
		newArea = self.createArea ( areaType )

		if parentSplitter is None and targetWrapper is None:
			qWarning ( "[QToolWindowManager] Could not determine area parent" )
			return

		newArea.addToolWindow ( oldArea.toolWindows () )
		if parentSplitter != None:
			targetIndex = parentSplitter.indexOf ( oldArea.getWidget () )
			parentSplitter.insertWidget ( targetIndex, newArea.getWidget () )
		else:
			targetWrapper.setContents ( newArea.getWidget () )

		if self.lastArea == oldArea:
			self.lastArea = newArea

		oldAreaIndex = self.areas.index ( oldArea )
		self.areas.remove ( oldArea )
		self.areas.insert ( oldAreaIndex, newArea )
		oldArea.getWidget ().setParent ( None )
		newArea.adjustDragVisuals ()
コード例 #8
0
 def write_annotation_config_to_csv(self, fileName=None):
     try:
         import csv
         options = QFileDialog.Options()
         options |= QFileDialog.DontUseNativeDialog
         fileName, _ = QFileDialog.getSaveFileName(self, 'Save File', get_project_root().as_posix(), "CSV Files(*.csv)", options=options)
         if fileName:
             with open(fileName, 'w', newline='') as stream:
                 writer = csv.writer(stream, delimiter=',')
                 header_items = [self.table.horizontalHeaderItem(i).text() for i in range(self.table.columnCount())]
                 writer.writerow(header_items)
                 for row in range(self.table.rowCount()):
                     row_data = {}
                     for col in range(self.table.columnCount()):
                         col_name = self.table.horizontalHeaderItem(col).text()
                         self.table.toolTipDuration()
                         w = self.table.cellWidget(row, col)
                         if col_name in ['name', 'key', 'symbol', 'symbol_colour']:
                             row_data[col_name] = w.text()
                         elif col_name in ['is_pinned']:
                             row_data[col_name] = bool(w.checkState())
                         elif col_name in ['pinned_to']:
                             # assert w.currentText() in pinned_to_options
                             row_data[col_name] = w.currentText()
                         elif col_name in ['pinned_window', 'min_distance']:
                             row_data[col_name] = w.value()
                         elif col_name in ['symbol_size']:
                             row_data[col_name] = int(w.text())
                     row_text = [str(int(i))if isinstance(i, bool) else str(i) for i in row_data.values()]
                     writer.writerow(row_text)
         qInfo('Annotation config saved to ' + fileName)
     except Exception as e:
         qWarning('Failed to save Annotation Config\r\n' + str(e))
コード例 #9
0
    def create_new_partition(self, event):
        from gui.viewer import PALMS
        vb = self.vbs[self.selected_view()]
        click_x = vb.mapSceneToView(event.pos()).x()
        menu = QtWidgets.QMenu()
        existing_partition_names = list(
            unique_everseen(PALMS.config['default_partition_labels'] +
                            Partitions.unique_labels()))
        menu.addActions([menu.addAction(n) for n in existing_partition_names])
        menu.addSeparator()
        menu.addAction('New Partition')
        new_partition_name = menu.exec_(event.globalPos().__add__(
            QtCore.QPoint(10, 10)))
        if new_partition_name is not None:
            new_name = new_partition_name.text()
            if new_name == 'New Partition':
                new_name, accepted = QInputDialog.getText(
                    self, 'Partition name input', 'Enter new partition name:')
                if not accepted:
                    qWarning('Incorrect name')
                    return

            if Partitions.find_partition_by_point(click_x) is not None:
                qWarning('Choose different place or delete existing region')
            else:
                p = SinglePartition.from_click(new_name, click_x=click_x)
                vb.addItem(p)
                vb.addItem(p.label)
        event.accept()
コード例 #10
0
    def convertV1toV2(self, fileName):
        reader = MapReader()
        map = reader.readMap(fileName)
        if (not map):
            qWarning("Error at conversion of " + fileName + ":\n" +
                     reader.errorString())
            return

        for layer in map.layers():
            if (layer.name().lower().startswith("ruleset")):
                layer.setName("Input_set")
            elif (layer.name().lower().startswith("rulenotset")):
                layer.setName("InputNot_set")
            elif (layer.name().lower().startswith("ruleregions")):
                layer.setName("Regions")
            elif (layer.name().lower().startswith("rule")):
                newname = layer.name().right(layer.name().length() - 4)
                layer.setName("Output" + newname)
            else:
                qWarning(
                    QString("Warning at conversion of") + fileName +
                    QString("unused layers found"))

        writer = MapWriter()
        writer.writeMap(map.data(), fileName)
        map.tilesets().clear()
コード例 #11
0
def addPort(group_id,
            port_id,
            port_name,
            port_mode,
            port_type,
            is_alternate=False):
    if canvas.debug:
        print("PatchCanvas::addPort(%i, %i, %s, %s, %s, %s)" %
              (group_id, port_id, port_name.encode(), port_mode2str(port_mode),
               port_type2str(port_type), bool2str(is_alternate)))

    for port in canvas.port_list:
        if port.group_id == group_id and port.port_id == port_id:
            qWarning(
                "PatchCanvas::addPort(%i, %i, %s, %s, %s) - port already exists"
                % (group_id, port_id, port_name.encode(),
                   port_mode2str(port_mode), port_type2str(port_type)))
            return

    box_widget = None
    port_widget = None

    for group in canvas.group_list:
        if group.group_id == group_id:
            if group.split and group.widgets[0].getSplittedMode(
            ) != port_mode and group.widgets[1]:
                n = 1
            else:
                n = 0
            box_widget = group.widgets[n]
            port_widget = box_widget.addPortFromGroup(port_id, port_mode,
                                                      port_type, port_name,
                                                      is_alternate)
            break

    if not (box_widget and port_widget):
        qCritical(
            "PatchCanvas::addPort(%i, %i, %s, %s, %s) - Unable to find parent group"
            % (group_id, port_id, port_name.encode(), port_mode2str(port_mode),
               port_type2str(port_type)))
        return

    port_dict = port_dict_t()
    port_dict.group_id = group_id
    port_dict.port_id = port_id
    port_dict.port_name = port_name
    port_dict.port_mode = port_mode
    port_dict.port_type = port_type
    port_dict.is_alternate = is_alternate
    port_dict.widget = port_widget
    canvas.port_list.append(port_dict)

    box_widget.updatePositions()

    if options.eyecandy == EYECANDY_FULL:
        CanvasItemFX(port_widget, True, False)
        return

    QTimer.singleShot(0, canvas.scene.update)
コード例 #12
0
ファイル: utils_gui.py プロジェクト: jonmart0304/PALMS
 def warningMessage(self, msg, header='Assert warning'):
     msgBox = QMessageBox(QMessageBox.Warning, header, msg,
                          QMessageBox.NoButton, self)
     qWarning(msg)
     msgBox.addButton("Ok", QMessageBox.AcceptRole)
     if msgBox.exec_() == QMessageBox.AcceptRole:
         pass
     self.show()
コード例 #13
0
	def releaseToolWindow ( self, toolWindow ):
		previousTabWidget = findClosestParent ( toolWindow, ToolWindowManagerArea )
		if not previousTabWidget:
			qWarning ( 'cannot find tab widget for tool window' )
			return
		previousTabWidget.removeTab ( previousTabWidget.indexOf (toolWindow) )
		toolWindow.hide ()
		toolWindow.setParent ( None )
コード例 #14
0
    def applyFormattingForToken(self, token, text):
        if token.type != MTT.TokenUnknown:
            fmt = self.format(token.position + token.openingMarkupLength)
            markupFormat = self.format(token.position)
            if self.theme.get("markup"):
                markupFormat.setForeground(self.theme["markup"])

            ## Debug
            def debug():
                print("{}\n{}{}{}{}   (state:{})".format(
                    text,
                    " "*token.position,
                    "^"*token.openingMarkupLength,
                    str(token.type).center(token.length
                                           - token.openingMarkupLength
                                           - token.closingMarkupLength, "-"),
                    "^" * token.closingMarkupLength,
                    self.currentBlockState(),)
                     )

            # if token.type in range(6, 10):
            # debug()

            theme = self.theme.get(token.type)
            if theme:
                fmt, markupFormat = self.formatsFromTheme(theme,
                                                          fmt,
                                                          markupFormat)

            # Focus mode
            unfocus = self.unfocusConditions()
            if unfocus:
                if (type(unfocus) == bool
                        or token.position < unfocus[0]
                        or unfocus[1] < token.position):
                    self.transparentFormat(fmt)
                    self.transparentFormat(markupFormat)

            # Format opening Markup
            self.setFormat(token.position, token.openingMarkupLength,
                           markupFormat)

            # Format Text
            self.setFormat(
                token.position + token.openingMarkupLength,
                token.length - token.openingMarkupLength - token.closingMarkupLength,
                fmt)

            # Format closing Markup
            if token.closingMarkupLength > 0:
                self.setFormat(
                    token.position + token.length - token.closingMarkupLength,
                    token.closingMarkupLength,
                    markupFormat)

        else:
            qWarning("MarkdownHighlighter.applyFormattingForToken() was passed"
                     " in a token of unknown type.")
コード例 #15
0
ファイル: eric6.py プロジェクト: skeptycal/eric6-20.3
def excepthook(excType, excValue, tracebackobj):
    """
    Global function to catch unhandled exceptions.
    
    @param excType exception type
    @param excValue exception value
    @param tracebackobj traceback object
    """
    from UI.Info import BugAddress
    import Utilities
    import Globals

    separator = '-' * 80
    logFile = os.path.join(Globals.getConfigDir(), "eric6_error.log")
    notice = (
        """An unhandled exception occurred. Please report the problem\n"""
        """using the error reporting dialog or via email to <{0}>.\n"""
        """A log has been written to "{1}".\n\nError information:\n""".format(
            BugAddress, logFile))
    timeString = time.strftime("%Y-%m-%d, %H:%M:%S")

    versionInfo = "\n{0}\n{1}".format(separator,
                                      Utilities.generateVersionInfo())
    pluginVersionInfo = Utilities.generatePluginsVersionInfo()
    if pluginVersionInfo:
        versionInfo += "{0}\n{1}".format(separator, pluginVersionInfo)
    distroInfo = Utilities.generateDistroInfo()
    if distroInfo:
        versionInfo += "{0}\n{1}".format(separator, distroInfo)

    if isinstance(excType, str):
        tbinfo = tracebackobj
    else:
        tbinfofile = io.StringIO()
        traceback.print_tb(tracebackobj, None, tbinfofile)
        tbinfofile.seek(0)
        tbinfo = tbinfofile.read()
    errmsg = '{0}: \n{1}'.format(str(excType), str(excValue))
    sections = [separator, timeString, separator, errmsg, separator, tbinfo]
    msg = '\n'.join(sections)
    try:
        f = open(logFile, "w", encoding="utf-8")
        f.write(msg)
        f.write(versionInfo)
        f.close()
    except IOError:
        pass

    if inMainLoop is None:
        warning = notice + msg + versionInfo
        print(warning)  # __IGNORE_WARNING_M801__
    else:
        warning = notice + msg + versionInfo
        # Escape &<> otherwise it's not visible in the error dialog
        warning = (warning.replace("&", "&amp;").replace(">", "&gt;").replace(
            "<", "&lt;"))
        qWarning(warning)
コード例 #16
0
ファイル: test_log.py プロジェクト: tharugrim/qutebrowser
 def test_unfiltered(self, caplog):
     """Test a message which is not filtered."""
     with log.hide_qt_warning("World", logger='qt-tests'):
         with caplog.atLevel(logging.WARNING, logger='qt-tests'):
             qWarning("Hello World")
     assert len(caplog.records()) == 1
     record = caplog.records()[0]
     assert record.levelname == 'WARNING'
     assert record.message == "Hello World"
コード例 #17
0
	def simplifyLayout ( self ):
		newAreas = []
		currentAreas = self.areas
		for area in currentAreas:
			if area.parentWidget () is None:
				if area.count () == 0:
					if area == self.lastUsedArea: self.lastUsedArea = None
					self.removeArea ( area )
				continue

			splitter = cast ( area.parentWidget (), QSplitter )
			validSplitter   = None # least top level splitter that should remain
			invalidSplitter = None #most top level splitter that should be deleted
			while ( splitter ):
				if splitter.count () > 1:
					validSplitter = splitter
					break
				else:
					invalidSplitter = splitter
					splitter = cast ( splitter.parentWidget (), QSplitter )
			if not validSplitter:
				wrapper = findClosestParent ( area, ToolWindowManagerWrapper )
				if not wrapper:
					qWarning ( 'can not find wrapper' )
					print ( findClosestParent ( area, ToolWindowManagerWrapper ) )
					print ( type ( area.parentWidget () ) == ToolWindowManagerWrapper )
					return
				if area.count () == 0 and wrapper.isWindow ():
					wrapper.hide ()
					wrapper.setParent ( None )
					# can not deleteLater immediately (strange MacOS bug)
					self.removeWrapper ( wrapper )
					
				elif area.parent () != wrapper:
					wrapper.layout ().addWidget ( area )

			else:
				if area.count () > 0:
					if validSplitter and area.parent () != validSplitter:
						index = validSplitter.indexOf ( invalidSplitter )
						validSplitter.insertWidget ( index, area )

			if not invalidSplitter is None:
				invalidSplitter.hide ()
				invalidSplitter.setParent ( None )
				invalidSplitter.deleteLater ()

			if area.count () == 0:
				area.hide ()
				area.setParent ( None )
				if area == self.lastUsedArea: self.lastUsedArea = None
				self.removeArea ( area )
				continue

			newAreas.append ( area )
		#keep
		self.areas = newAreas
コード例 #18
0
ファイル: Command.py プロジェクト: lihaochen910/Candy
    def onTriggered(self):
        cmd = ""
        commandProp = self.property("QCommandAction")
        if commandProp:
            cmd = str(commandProp)
        else:
            qWarning("Invalid QCommandAction %s" % self.objectName())

        getIEditor().executeCommand(cmd)
コード例 #19
0
 def find_partition_by_point(click_x: float):  # get partition under mouse click or None
     idx = np.where((click_x >= Partitions.all_startpoints()) & (click_x <= Partitions.all_endpoints()))[0]
     if len(idx) == 1:
         return Partitions()[idx[0]]
     elif len(idx) == 0:
         return None
     else:
         qWarning('More than one partition found! Return the first')  # should not happen, as partitions don't overlap
         return Partitions()[idx[0]]
コード例 #20
0
	def findSuggestions ( self, wrapper ):
		self.suggestions = []
		self.dropCurrentSuggestionIndex = -1
		globalPos  = QCursor.pos ()
		candidates = []
		for splitter in wrapper.findChildren ( QSplitter ):
			candidates.append ( splitter )

		for area in self.areas:
			if area.window () == wrapper.window ():
				candidates.append ( area )

		for widget in candidates:
			splitter = cast ( widget, QSplitter )
			area = cast ( widget, ToolWindowManagerArea )
			if not ( splitter or area ):
				qWarning ( 'unexpected widget type' )
				continue

			parentSplitter = cast ( widget.parentWidget (), QSplitter )
			lastInSplitter = parentSplitter and \
					parentSplitter.indexOf (widget) == parentSplitter.count () - 1

			allowedSides = []
			if not splitter or splitter.orientation () == Qt.Vertical:
				allowedSides.append ( ToolWindowManager.LeftOf )

			if not splitter or splitter.orientation () == Qt.Horizontal:
				allowedSides.append ( ToolWindowManager.TopOf )

			if not parentSplitter or parentSplitter.orientation () == Qt.Vertical or lastInSplitter:
				if not splitter or splitter.orientation () == Qt.Vertical:
					allowedSides.append ( ToolWindowManager.RightOf )

			if not parentSplitter or parentSplitter.orientation () == Qt.Horizontal or lastInSplitter:
				if not splitter or splitter.orientation () == Qt.Horizontal:
					allowedSides.append ( ToolWindowManager.BottomOf )
			for side in allowedSides:
				rect = self.sideSensitiveArea ( widget, side )
				pos  = widget.mapFromGlobal ( globalPos )
				if rect.contains ( pos ):
					self.suggestions.append ( AreaReference ( side, widget ) )
			if area:
				rect = area.rect ()
				pos  = area.mapFromGlobal ( globalPos )
				if rect.contains ( pos ):
					self.suggestions.append ( AreaReference ( ToolWindowManager.AddTo, area ) )

		#end of for
		if not candidates:
			self.suggestions.append ( AreaReference ( ToolWindowManager.EmptySpace ) )

		if len ( self.suggestions ) == 0:
			self.handleNoSuggestions ()
		else:
			self.showNextDropSuggestion ()
コード例 #21
0
    def showExportFormats(self):
        PluginManager.instance().loadPlugins()

        qWarning(self.tr("Export formats:"))
        formats = PluginManager.objects()
        for format in formats:
            if format.hasCapabilities(MapFormat.Write):
                qWarning(" " + format.nameFilter())

        self.quit = True
コード例 #22
0
	def tryCloseToolWindow ( self, toolWindow ):
		self.closingWindow += 1
		result = True

		if not toolWindow.close ():
			qWarning ( "Widget could not be closed" )
			result = False

		self.closingWindow -= 1
		return result
コード例 #23
0
ファイル: main.py プロジェクト: theall/Python-Tiled
    def showExportFormats(self):
        PluginManager.instance().loadPlugins()

        qWarning(self.tr("Export formats:"))
        formats = PluginManager.objects()
        for format in formats:
            if format.hasCapabilities(MapFormat.Write):
                qWarning(" " + format.nameFilter())

        self.quit = True
コード例 #24
0
    def updateVersions(self):
        for i in range(self.count()):
            fileName = self.mFileNames[i]
            version = self.mFileVersions[fileName]
            qWarning("processing" + fileName + "at version" + version)
            if (version == self.mControl.version1()):
                self.mControl.convertV1toV2(fileName)
                self.mFileVersions[fileName] = self.mControl.version2()

        self.dataChanged.emit(self.index(0, 0), self.index(self.count(), 1))
コード例 #25
0
    def updateVersions(self):
        for i in range(self.count()):
            fileName = self.mFileNames[i]
            version = self.mFileVersions[fileName]
            qWarning("processing"+fileName+"at version"+version)
            if (version == self.mControl.version1()):
                self.mControl.convertV1toV2(fileName)
                self.mFileVersions[fileName] = self.mControl.version2()

        self.dataChanged.emit(self.index(0, 0), self.index(self.count(), 1))
コード例 #26
0
	def finishWrapperDrag ( self ):
		target = self.dragHandler.finishDrag ( self.draggedToolWindows, None, self.lastArea )
		self.lastArea = None

		wrapper = self.draggedWrapper
		self.draggedWrapper = None
		self.raiseTimer.stop ()
		self.preview.setParent ( None )
		self.preview.hide ()

		if wrapper is None:
			qWarning ( "[QToolWindowManager] finishWrapperDrag wrapper == None." )
			return

		# print ( "[QToolWindowManager] finishWrapperDrag %s %s" % ( self.draggedWrapper, self.draggedToolWindows ) )

		contents = wrapper.getContents ()
		toolWindows = []
		contentsWidgets = contents.findChildren ( QWidget )
		contentsWidgets.append ( contents )

		for w in contentsWidgets:
			area = cast ( w, [ QToolWindowArea, QToolWindowRollupBarArea ] )
			if area != None and self.ownsArea ( area ):
				toolWindows += area.toolWindows ()

		if target.reference != QToolWindowAreaReference.Floating:
			contents = wrapper.getContents ()
			wrapper.setContents ( None )

			if target.reference == QToolWindowAreaReference.Top or \
					target.reference == QToolWindowAreaReference.Bottom or \
					target.reference == QToolWindowAreaReference.Left or \
					target.reference == QToolWindowAreaReference.Right:
				self.splitArea ( self.getFurthestParentArea ( target.area.getWidget () ).getWidget (), target.reference,
				                 contents )
			elif target.reference == QToolWindowAreaReference.HSplitTop or \
					target.reference == QToolWindowAreaReference.HSplitBottom or \
					target.reference == QToolWindowAreaReference.VSplitLeft or \
					target.reference == QToolWindowAreaReference.VSplitRight:
				self.splitArea ( target.area.getWidget (), target.reference, contents )
			elif target.reference == QToolWindowAreaReference.Combine:
				self.moveToolWindowsTarget ( toolWindows, target )

			wrapper.getWidget ().close ()
			self.simplifyLayout ()

		if target.reference != QToolWindowAreaReference.Combine:
			for w in toolWindows:
				self.toolWindowVisibilityChanged.emit ( w, True )

		if target.reference != QToolWindowAreaReference.Floating:
			self.notifyLayoutChange ()

		self.updateTrackingTooltip.emit ( "", QPoint () )
コード例 #27
0
ファイル: qmlApp.py プロジェクト: GrandHsu/demoQMLPyQt
 def root(self):
   " QmlApp's root comes from engine."
   try:
     qmlRoot = self.engine.rootObjects()[0]
   except:
     qWarning("Failed to read or parse qml.")
     raise
   
   print(qmlRoot)
   assert isinstance(qmlRoot, QQuickWindow)
   return qmlRoot
コード例 #28
0
 def restoreState(self, data):
     for objectName in data.get('objectNames', []):
         found = False
         for window in self.manager.toolWindows():
             if window.objectName() == objectName:
                 self.addToolWindow(window)
                 found = True
                 break
         if not found:
             qWarning("tool window with name '%s' not found" % objectName)
     self.setCurrentIndex(data.get("currentIndex", 0))
コード例 #29
0
ファイル: qmlApp.py プロジェクト: jacobo3d/demoQMLPyQt
    def root(self):
        " QmlApp's root comes from engine."
        try:
            qmlRoot = self.engine.rootObjects()[0]
        except:
            qWarning("Failed to read or parse qml.")
            raise

        print(qmlRoot)
        assert isinstance(qmlRoot, QQuickWindow)
        return qmlRoot
コード例 #30
0
ファイル: eric6.py プロジェクト: Darriall/eric
def excepthook(excType, excValue, tracebackobj):
    """
    Global function to catch unhandled exceptions.
    
    @param excType exception type
    @param excValue exception value
    @param tracebackobj traceback object
    """
    import xml.sax.saxutils
    from UI.Info import BugAddress
    import Utilities
    import Globals
    
    separator = '-' * 80
    logFile = os.path.join(Globals.getConfigDir(), "eric6_error.log")
    notice = \
        """An unhandled exception occurred. Please report the problem\n"""\
        """using the error reporting dialog or via email to <{0}>.\n"""\
        """A log has been written to "{1}".\n\nError information:\n""".format(
            BugAddress, logFile)
    timeString = time.strftime("%Y-%m-%d, %H:%M:%S")
    
    versionInfo = "\n{0}\n{1}".format(
        separator, Utilities.generateVersionInfo())
    pluginVersionInfo = Utilities.generatePluginsVersionInfo()
    if pluginVersionInfo:
        versionInfo += "{0}\n{1}".format(separator, pluginVersionInfo)
    distroInfo = Utilities.generateDistroInfo()
    if distroInfo:
        versionInfo += "{0}\n{1}".format(separator, distroInfo)
    
    if isinstance(excType, basestring):
        tbinfo = tracebackobj
    else:
        tbinfofile = io.StringIO()
        traceback.print_tb(tracebackobj, None, tbinfofile)
        tbinfofile.seek(0)
        tbinfo = tbinfofile.read()
    errmsg = '{0}: \n{1}'.format(str(excType), str(excValue))
    sections = [separator, timeString, separator, errmsg, separator, tbinfo]
    msg = '\n'.join(sections)
    try:
        f = open(logFile, "w", encoding="utf-8")
        f.write(msg)
        f.write(versionInfo)
        f.close()
    except IOError:
        pass
    
    warning = str(notice) + str(msg) + str(versionInfo)
    # Escape &<> otherwise it's not visible in the error dialog
    warning = xml.sax.saxutils.escape(warning)
    qWarning(warning)
コード例 #31
0
	def startDrag ( self, toolWindows ):
		'''
		开始拖拽,在指针位置显示拖拽toolWindows的简略快照
		'''
		if self.dragInProgress ():
			qWarning ( 'ToolWindowManager::execDrag: drag is already in progress' )
			return
		if not toolWindows: return
		self.draggedToolWindows = toolWindows
		self.dragIndicator.setPixmap ( self.generateDragPixmap ( toolWindows ) )
		self.updateDragPosition ()
		self.dragIndicator.show ()
コード例 #32
0
    def removePath(self, path):
        entry = self.mWatchCount.find(path)
        if (entry == self.mWatchCount.end()):
            if (QFile.exists(path)):
                qWarning("FileSystemWatcher: Path was never added:\n"+path)
            return

        # Decrement watch count
        entry -= 1
        self.mWatchCount[path] = entry
        if (entry == 0):
            self.mWatchCount.erase(path)
            self.mWatcher.removePath(path)
コード例 #33
0
 def getMergedModPluginsState(self, name):
     if name in self.__mergedModInfo:
         plugins = self.__mergedModInfo[name]['plugins']
         pluginstates = [self.getPluginStateByName(plugin.lower()) for plugin in plugins]
         if(all((pluginstate in [Dc.PluginState.ACTIVE]) for pluginstate in pluginstates)):
             return Dc.ModPluginsState.ACTIVE
         elif(all((pluginstate in [Dc.PluginState.MISSING, Dc.PluginState.INACTIVE]) for pluginstate in pluginstates)):
             return Dc.ModPluginsState.INACTIVE
         elif(any((pluginstate in [Dc.PluginState.MISSING, Dc.PluginState.INACTIVE]) for pluginstate in pluginstates)):
             return Dc.ModPluginsState.MIXED
     else:
         qWarning(self.__tr("Merged mod {} missing".format(name)).encode('utf-8'))
     return Dc.ModPluginsState.UNKNOWN
コード例 #34
0
	def saveState ( self ):
		result = { }
		result[ "type" ] = "area"
		result[ "currentIndex" ] = self.currentIndex ()
		objectNames = [ ]
		for i in range ( self.count () ):
			name = self.widget ( i ).objectName ()
			if not name:
				qWarning ( "[QToolWindowArea] saveState cannot save state of tool window without object name" )
			else:
				objectNames.append ( name )
		result[ "objectNames" ] = objectNames
		return result
コード例 #35
0
    def removePath(self, path):
        entry = self.mWatchCount.find(path)
        if (entry == self.mWatchCount.end()):
            if (QFile.exists(path)):
                qWarning("FileSystemWatcher: Path was never added:\n" + path)
            return

        # Decrement watch count
        entry -= 1
        self.mWatchCount[path] = entry
        if (entry == 0):
            self.mWatchCount.erase(path)
            self.mWatcher.removePath(path)
コード例 #36
0
 def restoreState(self, data):
     if 'geometry' in data:
         self.restoreGeometry(data['geometry'])
     if self.layout().count() > 0:
         qWarning('wrapper is not empty')
         return
     if 'splitter' in data:
         self.layout().addWidget(
             self.manager.restoreSplitterState(data['splitter'].toMap()))
     elif 'area' in data:
         area = self.manager.createArea()
         area.restoreState(data['area'])
         self.layout().addWidget(area)
コード例 #37
0
ファイル: main.py プロジェクト: theall/Python-Tiled
def parseCommandLineArguments(options):
    arguments = sys.argv
    for i in range(1, len(arguments)):
        arg = arguments[i]
        if (arg == "--help") or arg == "-h":
            options.showHelp = True
        elif (arg == "--version"
                or arg == "-v"):
            options.showVersion = True
        elif arg[0] == '-':
            qWarning("Unknown option" + arg)
            options.showHelp = True
        elif (options.fileToOpen==''):
            options.fileToOpen = arg
コード例 #38
0
    def showHelp(self):
        qWarning(self.tr("Usage:\n  %s [options] [files...]"%self.mCurrentProgramName) + "\n\n" + self.tr("Options:"))
        qWarning("  -h %-*s : %s", self.mLongestArgument, "--help", self.tr("Display this help"))
        for option in self.mOptions:
            if (not option.shortName.isNull()):
                qWarning("  -%c %-*s : %s",
                         option.shortName.toLatin1(),
                         self.mLongestArgument, option.longName,
                         option.help)
            else:
                qWarning("     %-*s : %s",
                         self.mLongestArgument, option.longName,
                         option.help)

        qWarning()
コード例 #39
0
ファイル: qmlMaster.py プロジェクト: bootchk/documentStyle
    def quickViewRoot(self, quickview):
        """
    QQuickView is a QWindow having a tree of QML objects.
    Root of the tree.
    """
        assert isinstance(quickview, QQuickView)
        try:
            qmlRoot = quickview.rootObject()  # objects()[0]
        except:
            qWarning("quickview empty: failed to read or parse qml?")
            raise

        # print(qmlRoot)
        assert isinstance(qmlRoot, QQuickItem)
        return qmlRoot
コード例 #40
0
ファイル: quickWindow.py プロジェクト: GrandHsu/demoQMLPyQt
 def create(self, qmlUrl):
   # assert isinstance(qmlUrl, QUrl)
   engine = QQmlApplicationEngine(qmlUrl)
 
   try:
     qmlRoot = engine.rootObjects()[0]
   except:
     qWarning("Failed to read or parse qml.")
     raise
   
   print(qmlRoot)
   #assert isinstance(qmlRoot, QQuickWindow)
   return qmlRoot
 
   #super().__init__(qmlRoot)
   '''
コード例 #41
0
ファイル: cngraphicsview.py プロジェクト: cadnano/cadnano2.5
    def _drawBackgroundGL(self, painter: QPainter, rect: QRectF):
        """This method is for overloading the QGraphicsScene.
        """
        if (painter.paintEngine().type() != QPaintEngine.OpenGL and
           painter.paintEngine().type() != QPaintEngine.OpenGL2):

            qWarning("OpenGLScene: drawBackground needs a QGLWidget to be"
                    "set as viewport on the graphics view")
            return
        # end if
        painter.beginNativePainting()
        GL.glDisable(GL.GL_DEPTH_TEST)  # disable for 2D drawing
        GL.glClearColor(1.0, 1.0, 1.0, 1.0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        painter.endNativePainting()
コード例 #42
0
ファイル: main.py プロジェクト: theall/Python-Tiled
def showHelp():
    # TODO: Make translatable
    qWarning(
            "Usage:\n"
            "  tmxrasterizer [options] [input file] [output file]\n"
            "\n"
            "Options:\n"
            "  -h --help               : Display this help\n"
            "  -v --version            : Display the version\n"
            "  -s --scale SCALE        : The scale of the output image (default: 1)\n"
            "  -t --tilesize SIZE      : The requested size in pixels at which a tile is rendered\n"
            "                            Overrides the --scale option\n"
            "  -a --anti-aliasing      : Smooth the output image using anti-aliasing\n"
            "     --ignore-visibility  : Ignore all layer visibility flags in the map file, and render all\n"
            "                            layers in the output (default is to omit invisible layers)\n"
            "     --hide-layer         : Specifies a layer to omit from the output image\n"
            "                            Can be repeated to hide multiple layers\n")
コード例 #43
0
ファイル: pluginspage.py プロジェクト: hlamer/enki
    def update(self, userPlugins):
        """ListOfUserpluginEntry -> Void
        Consume a list of UserpluginEntry and repopulates the plugins page"""
        for i in reversed(range(self._vbox.count())):
            try:
                self._vbox.itemAt(i).widget().setParent(None)
            except AttributeError as e:
                qWarning("Can't call setParent of None type")

        self._vbox.addWidget(QLabel(
            """<h2>Installed Plugins: <code>%i</code></h2>
            <p>Add plugins by putting them into <code>%s</code></p>
            <p></p>""" % (len(userPlugins), PLUGIN_DIR_PATH)))
        for entry in userPlugins:
            self._vbox.addWidget(PluginTitlecard(entry))

        self._vbox.addStretch(1)
コード例 #44
0
ファイル: app.py プロジェクト: kuruntham/pykalappai
    def __init__(self):
        app = QApplication(sys.argv)
        app.setApplicationName("eKalappai")
        app.setApplicationVersion("4.0.0")
        shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

        if not shared.create(512, QSharedMemory.ReadWrite):
            qWarning("Cannot start more than one instance of eKalappai any time.")
            exit(0)
        splashImage = QPixmap(':intro/splash_screen')
        splashScreen = QSplashScreen(splashImage)
        splashScreen.show()
        time.sleep(2)
        splashScreen.hide()
        QApplication.setQuitOnLastWindowClosed(False)
        ekWindow = EKWindow()
        ekWindow.engine.start()
        sys.exit(app.exec_())
コード例 #45
0
ファイル: qmlMaster.py プロジェクト: GrandHsu/demoQMLPyQt
 def quickRoot(self, quickThing):
   '''
   quickThing has a tree of QML objects.
   Root of the tree.
   
   quickThing is QQuickView is a QWindow
   OR quickThing is a QQuickWidget
   '''
   assert isinstance(quickThing, QQuickView) or isinstance(quickThing, QQuickWidget)
   try:
     qmlRoot = quickThing.rootObject()  # objects()[0]
   except:
     qWarning("quickThing empty: failed to read or parse qml?")
     raise
   
   #print(qmlRoot)
   assert isinstance(qmlRoot, QQuickItem)
   return qmlRoot
コード例 #46
0
ファイル: SpeedDial.py プロジェクト: Darriall/eric
 def __thumbnailCreated(self, image):
     """
     Private slot to handle the creation of a thumbnail image.
     
     @param image thumbnail image (QPixmap)
     """
     from .PageThumbnailer import PageThumbnailer
     thumbnailer = self.sender()
     if not isinstance(thumbnailer, PageThumbnailer) or \
        thumbnailer not in self.__thumbnailers:
         return
     
     loadTitle = thumbnailer.loadTitle()
     title = thumbnailer.title()
     url = thumbnailer.url().toString()
     fileName = self.__imageFileName(url)
     
     if image.isNull():
         fileName = "qrc:icons/brokenPage.png"
         title = self.tr("Unable to load")
         loadTitle = True
         page = self.pageForUrl(thumbnailer.url())
         page.broken = True
     else:
         if not image.save(fileName):
             qWarning(
                 "SpeedDial.__thumbnailCreated: Cannot save thumbnail"
                 " to {0}".format(fileName))
         
         fileName = QUrl.fromLocalFile(fileName).toString()
     
     self.__regenerateScript = True
     
     for frame in self.__cleanFrames():
         frame.evaluateJavaScript("setImageToUrl('{0}', '{1}');".format(
                                  url, fileName))
         if loadTitle:
             frame.evaluateJavaScript("setTitleToUrl('{0}', '{1}');".format(
                                      url, Utilities.html_uencode(title)))
     
     thumbnailer.deleteLater()
     self.__thumbnailers.remove(thumbnailer)
コード例 #47
0
ファイル: installpage.py プロジェクト: bjones1/enki
    def update(self, userPlugins):
        """ListOfUserpluginEntry -> Void
        Consume a list of UserpluginEntry and repopulates the install page"""
        for i in reversed(range(self._vbox.count())):
            try:
                self._vbox.itemAt(i).widget().setParent(None)
            except AttributeError as e:
                qWarning("Can't call setParent of None type")

        labelText = "<h2>Install Plugins</h2>"
        if (len(self._repo["plugins"]) < 1):
            labelText += "<p>It seems we could not load the plugin repository.</p>"
            labelText += "<p style='color:red'>Make shure your internet connection is working and restart Enki.</p><p></p>"
        self._vbox.addWidget(QLabel(labelText))

        for entry in self._repo["plugins"]:
            isInstalled = helper.isPluginInstalled(entry["name"], userPlugins)
            if isInstalled:
                self._vbox.addWidget(pluginspage.PluginTitlecard(isInstalled))
            else:
                self._vbox.addWidget(InstallableTitlecard(entry, self))
コード例 #48
0
ファイル: audiooutput.py プロジェクト: Axel-Erfurt/pyqt5
    def initializeAudio(self):
        self.m_pullTimer = QTimer(self, timeout=self.pullTimerExpired)
        self.m_pullMode = True

        self.m_format = QAudioFormat()
        self.m_format.setSampleRate(self.DataSampleRateHz)
        self.m_format.setChannelCount(1)
        self.m_format.setSampleSize(16)
        self.m_format.setCodec('audio/pcm')
        self.m_format.setByteOrder(QAudioFormat.LittleEndian)
        self.m_format.setSampleType(QAudioFormat.SignedInt)

        info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice())
        if not info.isFormatSupported(self.m_format):
            qWarning("Default format not supported - trying to use nearest")
            self.m_format = info.nearestFormat(self.m_format)

        self.m_generator = Generator(self.m_format,
                self.DurationSeconds * 1000000, self.ToneSampleRateHz, self)

        self.createAudioOutput()
コード例 #49
0
ファイル: audiooutput.py プロジェクト: Axel-Erfurt/pyqt5
 def toggleSuspendResume(self):
     if self.m_audioOutput.state() == QAudio.SuspendedState:
         qWarning("status: Suspended, resume()")
         self.m_audioOutput.resume()
         self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)
     elif self.m_audioOutput.state() == QAudio.ActiveState:
         qWarning("status: Active, suspend()")
         self.m_audioOutput.suspend()
         self.m_suspendResumeButton.setText(self.RESUME_LABEL)
     elif self.m_audioOutput.state() == QAudio.StoppedState:
         qWarning("status: Stopped, resume()")
         self.m_audioOutput.resume()
         self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)
     elif self.m_audioOutput.state() == QAudio.IdleState:
         qWarning("status: IdleState")
コード例 #50
0
ファイル: tmxviewer.py プロジェクト: theall/Python-Tiled
    def viewMap(self, fileName):
        del self.mRenderer
        self.mRenderer = None
        self.mScene.clear()
        self.centerOn(0, 0)
        reader = MapReader()
        self.mMap = reader.readMap(fileName)
        if (not self.mMap):
            qWarning("Error:"+reader.errorString())
            return False

        x = self.mMap.orientation()
        if x==Map.Orientation.Isometric:
            self.mRenderer = IsometricRenderer(self.mMap)
        elif x==Map.Orientation.Staggered:
            self.mRenderer = StaggeredRenderer(self.mMap)
        elif x==Map.Orientation.Hexagonal:
            self.mRenderer = HexagonalRenderer(self.mMap)
        else:
            self.mRenderer = OrthogonalRenderer(self.mMap)

        self.mScene.addItem(MapItem(self.mMap, self.mRenderer))
        return True
コード例 #51
0
ファイル: main.py プロジェクト: theall/Python-Tiled
def parseCommandLineArguments(options):
    arguments = sys.argv
    i = 1
    while i < len(arguments):
        arg = arguments[i]
        if (arg == "--help") or arg == "-h":
            options.showHelp = True
        elif (arg == "--version"
                or arg == "-v"):
            options.showVersion = True
        elif (arg == "--scale"
                or arg == "-s"):
            i += 1
            if (i >= len(arguments)):
                options.showHelp = True
            else:
                options.scale, scaleIsDouble = Float2(arguments[i])
                if (not scaleIsDouble):
                    qWarning(arguments[i] + ": the specified scale is not a number.")
                    options.showHelp = True
        elif (arg == "--tilesize"
                or arg == "-t"):
            i += 1
            if (i >= len(arguments)):
                options.showHelp = True
            else:
                options.tileSize, tileSizeIsInt = Int2(arguments[i])
                if (not tileSizeIsInt):
                    qWarning(arguments[i] + ": the specified tile size is not an integer.")
                    options.showHelp = True
        elif (arg == "--hide-layer"):
            i += 1
            if (i >= len(arguments)):
                options.showHelp = True
            else:
                options.layersToHide.append(arguments[i])
        elif (arg == "--anti-aliasing"
                or arg == "-a"):
            options.useAntiAliasing = True
        elif arg == "--ignore-visibility":
            options.ignoreVisibility = True
        elif arg == '':
            options.showHelp = True
        elif arg[0] == '-':
            qWarning("Unknown option" + arg)
            options.showHelp = True
        elif options.fileToOpen == '':
            options.fileToOpen = arg
        elif options.fileToSave == '':
            options.fileToSave = arg
        else:
            # All args are already defined. Show help.
            options.showHelp = True
            
        i += 1
コード例 #52
0
    def parse(self, arguments):
        self.mFilesToOpen.clear()
        self.mShowHelp = False
        todo = QStringList(arguments)
        self.mCurrentProgramName = QFileInfo(todo.takeFirst()).fileName()
        index = 0
        noMoreArguments = False
        while (not todo.isEmpty()):
            index += 1
            arg = todo.takeFirst()
            if (arg.isEmpty()):
                continue
            if (noMoreArguments or arg.at(0) != '-'):
                self.mFilesToOpen.append(arg)
                continue

            if (arg.length() == 1):
                # Traditionally a single hyphen means read file from stdin,
                # write file to stdout. This isn't supported right now.
                qWarning(self.tr("Bad argument %d: lonely hyphen"%index))
                self.showHelp()
                return False

            # Long options
            if (arg.at(1) == '-'):
                # Double hypen "--" means no more options will follow
                if (arg.length() == 2):
                    noMoreArguments = True
                    continue

                if (not self.handleLongOption(arg)):
                    qWarning(self.tr("Unknown long argument %d: %s"%(index, arg)))
                    self.mShowHelp = True
                    break

                continue

            # Short options
            for i in range(1, arg.length()):
                c = arg.at(i)
                if (not self.handleShortOption(c)):
                    qWarning(self.tr("Unknown short argument %d.%d: %s"%(index, i, c)))
                    self.mShowHelp = True
                    break

        if (self.mShowHelp):
            self.showHelp()
            return False

        return True
コード例 #53
0
ファイル: shared.py プロジェクト: Houston4444/Cadence
DEBUG = bool("-d" in sys.argv or "-debug" in sys.argv or "--debug" in sys.argv)

# ------------------------------------------------------------------------------------------------------------
# Global variables

global gGui
gGui = None

# ------------------------------------------------------------------------------------------------------------
# Set TMP

TMP = os.getenv("TMP")

if TMP is None:
    if WINDOWS:
        qWarning("TMP variable not set")
        TMP = os.path.join(WINDIR, "temp")
    else:
        TMP = "/tmp"

# ------------------------------------------------------------------------------------------------------------
# Set HOME

HOME = os.getenv("HOME")

if HOME is None:
    HOME = os.path.expanduser("~")

    if not WINDOWS:
        qWarning("HOME variable not set")
コード例 #54
0
ファイル: test_log.py プロジェクト: JIVS/qutebrowser
 def test_filtered_start(self):
     """Test a message which is filtered (match at line start)."""
     with log.hide_qt_warning("Hello", logger='qt-tests'):
         qWarning("Hello World")
コード例 #55
0
ファイル: test_log.py プロジェクト: JIVS/qutebrowser
 def test_filtered_whitespace(self):
     """Test a message which is filtered (match with whitespace)."""
     with log.hide_qt_warning("Hello", logger='qt-tests'):
         qWarning("  Hello World  ")
コード例 #56
0
ファイル: app.py プロジェクト: manikk/ekalappai
        elif self.iniSettings.value("shortcut_modifier") == "CTRL":
            self.engine.event_queue.register_event([['Lcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
            self.engine.event_queue.register_event([['Rcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        elif self.iniSettings.value("shortcut_modifier") == "ALT":
            self.engine.event_queue.register_event([['LMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
            self.engine.event_queue.register_event([['RMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        return True


if __name__ == "__main__":
    """
        Main Function which will initialize the app
    """
    app = QApplication(sys.argv)
    app.setApplicationName("eKalappai")
    app.setApplicationVersion("4.0.0")
    shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

    if not shared.create(512, QSharedMemory.ReadWrite):
        qWarning("Cannot start more than one instance of eKalappai any time.")
        exit(0)
    splashImage = QPixmap(':/images/intro.png')
    splashScreen = QSplashScreen(splashImage)
    splashScreen.show()
    time.sleep(2)
    splashScreen.hide()
    QApplication.setQuitOnLastWindowClosed(False)
    ekWindow = EKWindow()
    ekWindow.engine.start()
    sys.exit(app.exec_())
コード例 #57
0
ファイル: main.py プロジェクト: theall/Python-Tiled
 def showVersion(self):
     if (not self.showedVersion):
         self.showedVersion = True
         qWarning(QApplication.applicationDisplayName()+'\n'+QApplication.applicationVersion())
         self.quit = True
コード例 #58
0
ファイル: main.py プロジェクト: theall/Python-Tiled
def main(argv):
    a = TiledApplication(argv)
    a.setOrganizationDomain("mapeditor.org")
    a.setApplicationName("Tiled")
    a.setApplicationVersion("0.14.2")

    if sys.platform == 'darwin':
        a.setAttribute(Qt.AA_DontShowIconsInMenus)

    # Enable support for highres images (added in Qt 5.1, but off by default)
    a.setAttribute(Qt.AA_UseHighDpiPixmaps)
    if sys.platform != 'win32':
        baseName = QApplication.style().objectName()
        if (baseName == "windows"):
            # Avoid Windows 95 style at all cost
            if (QStyleFactory.keys().contains("Fusion")):
                baseName = "fusion" # Qt5
            else: # Qt4
                # e.g. if we are running on a KDE4 desktop
                desktopEnvironment = qgetenv("DESKTOP_SESSION")
                if (desktopEnvironment == "kde"):
                    baseName = "plastique"
                else:
                    baseName = "cleanlooks"

            a.setStyle(QStyleFactory.create(baseName))
    languageManager = LanguageManager.instance()
    languageManager.installTranslators()
    commandLine = CommandLineHandler()
    if (not commandLine.parse(QCoreApplication.arguments())):
        return 0
    if (commandLine.quit):
        return 0
    if (commandLine.disableOpenGL):
        preferences.Preferences.instance().setUseOpenGL(False)
    PluginManager.instance().loadPlugins()
    if (commandLine.exportMap):
        # Get the path to the source file and target file
        if (commandLine.filesToOpen().length() < 2):
            qWarning(QCoreApplication.translate("Command line", "Export syntax is --export-map [format] "))
            return 1

        index = 0
        if commandLine.filesToOpen().length() > 2:
            filter = commandLine.filesToOpen().at(index)
            index += 1
        else:
            filter = None
        sourceFile = commandLine.filesToOpen().at(index)
        index += 1
        targetFile = commandLine.filesToOpen().at(index)
        index += 1
        
        chosenFormat = None
        formats = PluginManager.objects()

        if filter:
            # Find the map format supporting the given filter
            for format in formats:
                if not format.hasCapabilities(MapFormat.Write):
                    continue
                if format.nameFilter().lower()==filter.lower():
                    chosenFormat = format
                    break
            if not chosenFormat:
                qWarning(QCoreApplication.translate("Command line", "Format not recognized (see --export-formats)"))
                return 1
        else:
            # Find the map format based on target file extension
            suffix = QFileInfo(targetFile).completeSuffix()
            for format in formats:
                if not format.hasCapabilities(MapFormat.Write):
                    continue
                if suffix.lower() in format.nameFilter().lower():
                    if chosenFormat:
                        qWarning(QCoreApplication.translate("Command line", "Non-unique file extension. Can't determine correct export format."))
                        return 1
                    chosenFormat = format
                    
            if not chosenFormat:
                qWarning(QCoreApplication.translate("Command line", "No exporter found for target file."))
                return 1

        # Load the source file
        reader = MapReader()
        map = reader.readMap(sourceFile)
        if (not map):
            qWarning(QCoreApplication.translate("Command line", "Failed to load source map."))
            return 1

        # Write out the file
        success = chosenFormat.write(map.data(), targetFile)

        if (not success):
            qWarning(QCoreApplication.translate("Command line", "Failed to export map to target file."))
            return 1

        return 0
    w = MainWindow()
    w.show()
    a.fileOpenRequest.connect(w.openFile)
    if (not commandLine.filesToOpen().isEmpty()):
        for fileName in commandLine.filesToOpen():
            w.openFile(fileName)
    elif preferences.Preferences.instance().openLastFilesOnStartup():
        w.openLastFiles()
    return a.exec()
コード例 #59
0
ファイル: audiooutput.py プロジェクト: Axel-Erfurt/pyqt5
 def handleStateChanged(self, state):
     qWarning("state = " + self.stateMap.get(state, "Unknown"))
コード例 #60
0
ファイル: audiooutput.py プロジェクト: Axel-Erfurt/pyqt5
 def notified(self):
     qWarning("bytesFree = %d, elapsedUSecs = %d, processedUSecs = %d" % (
             self.m_audioOutput.bytesFree(),
             self.m_audioOutput.elapsedUSecs(),
             self.m_audioOutput.processedUSecs()))