def createRequest(self, op, req, outgoingData):
        if op == QNetworkAccessManager.GetOperation:
            qDebug('HTTP/1.1 GET Request')
        elif op == QNetworkAccessManager.PostOperation:
            qDebug('HTTP/1.1 POST Request')
        elif op == QNetworkAccessManager.HeadOperation:
            qDebug('HTTP/1.1 HEAD Request')
        elif op == QNetworkAccessManager.PutOperation:
            qDebug('HTTP/1.1 PUT Request')
        elif op == QNetworkAccessManager.DeleteOperation:
            qDebug('HTTP/1.1 DELETE Request')
        elif op == QNetworkAccessManager.CustomOperation:
            qDebug('HTTP/1.1 CUSTOM Request')
        else:
            qWarning('Unexpected HTTP Operation Type')

        qDebug('URL %s' % req.url().toString())

        do_action('NetworkAccessManagerCreateRequestPre', Bunch(locals()))

        reply = QNetworkAccessManager.createRequest(self, op, req, outgoingData)

        if self.m_ignoreSslErrors == 'yes':
            reply.ignoreSslErrors()

        do_action('NetworkAccessManagerCreateRequestPost', Bunch(locals()))

        return reply
Example #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() - delta ),
										 QSize( widgetRect.width(), self.rubberBandLineWidth ) )
			elif side == ToolWindowManager.LeftOf and parentSplitter.orientation() == Qt.Horizontal:
				return QRect(QPoint(widgetRect.left() - 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()
Example #3
0
    def sideSensitiveArea(self, widget, side):
        widgetRect = widget.rect()
        if side == ToolWindowManager.TopOf:
            return QRect(
                QPoint(widgetRect.left(), widgetRect.top() - self.borderSensitivity),
                QSize(widgetRect.width(), self.borderSensitivity * 2),
            )
        elif side == ToolWindowManager.LeftOf:
            return QRect(
                QPoint(widgetRect.left() - self.borderSensitivity, widgetRect.top()),
                QSize(self.borderSensitivity * 2, widgetRect.height()),
            )

        elif side == ToolWindowManager.BottomOf:
            return QRect(
                QPoint(widgetRect.left(), widgetRect.top() + widgetRect.height() - self.borderSensitivity),
                QSize(widgetRect.width(), self.borderSensitivity * 2),
            )
        elif side == ToolWindowManager.RightOf:
            return QRect(
                QPoint(widgetRect.left() + widgetRect.width() - self.borderSensitivity, widgetRect.top()),
                QSize(self.borderSensitivity * 2, widgetRect.height()),
            )
        else:
            qWarning("invalid side")
            return QRect()
Example #4
0
    def stopAndWaitForWebServer(self):
        if not self.fWebServerThread.isRunning():
            return

        if not self.fWebServerThread.stopWait():
            qWarning("WebServer Thread failed top stop cleanly, forced terminate")
            self.fWebServerThread.terminate()
Example #5
0
    def stopAndWaitForWebServer(self):
        if not self.fWebServerThread.isRunning():
            return

        if not self.fWebServerThread.stopWait():
            qWarning("WebServer Thread failed top stop cleanly, forced terminate")
            self.fWebServerThread.terminate()
Example #6
0
def injectJsInFrame(filePath, libraryPath, targetFrame, startingScript=False):
    try:
        # if file doesn't exist in the CWD, use the lookup
        if not os.path.exists(filePath):
            filePath = os.path.join(libraryPath, filePath)

        with codecs.open(filePath, encoding='utf-8') as f:
            script = f.read()

        if script.startswith('#!') and not filePath.lower().endswith('.coffee'):
            script = '//' + script

        if filePath.lower().endswith('.coffee'):
            result = coffee2js(script)
            if result[0] is False:
                if startingScript:
                    sys.exit(result[1])
                else:
                    qWarning(result[1])
                    script = ''
            else:
                script = result[1]

        targetFrame.evaluateJavaScript(script)
        return True
    except IOError:
        qWarning('No such file or directory: \'%s\'' % filePath)
        return False
Example #7
0
def injectJsInFrame(filePath, libraryPath, targetFrame, startingScript=False):
    try:
        # if file doesn't exist in the CWD, use the lookup
        if not os.path.exists(filePath):
            filePath = os.path.join(libraryPath, filePath)

        with codecs.open(filePath, encoding='utf-8') as f:
            script = f.read()

        if script.startswith(
                '#!') and not filePath.lower().endswith('.coffee'):
            script = '//' + script

        if filePath.lower().endswith('.coffee'):
            result = coffee2js(script)
            if result[0] is False:
                if startingScript:
                    sys.exit(result[1])
                else:
                    qWarning(result[1])
                    script = ''
            else:
                script = result[1]

        targetFrame.evaluateJavaScript(script)
        return True
    except IOError:
        qWarning('No such file or directory: \'%s\'' % filePath)
        return False
Example #8
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
Example #9
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 )
Example #10
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)
Example #11
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
Example #12
0
    def stopAndWaitForBackend(self):
        if self.fProccessBackend.state() == QProcess.NotRunning:
            return

        self.fStoppingBackend = True
        self.fProccessBackend.terminate()
        if not self.fProccessBackend.waitForFinished(2000):
            qWarning("Backend failed top stop cleanly, forced kill")
            self.fProccessBackend.kill()
Example #13
0
    def stopAndWaitForBackend(self):
        if self.fProccessBackend.state() == QProcess.NotRunning:
            return

        self.fStoppingBackend = True
        self.fProccessBackend.terminate()
        if not self.fProccessBackend.waitForFinished(2000):
            qWarning("Backend failed top stop cleanly, forced kill")
            self.fProccessBackend.kill()
Example #14
0
	def startDrag( self, 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()
Example #15
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.topLevelWidget() == wrapper.topLevelWidget():
				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()
Example #16
0
 def setCurrentComboBoxUpdInterval(self):
     curInterval = self.prop.getUpdateInterval()
     index = self.comboBoxUpdInterval.findData(curInterval)
     if index >= 0:
         self.comboBoxUpdInterval.setCurrentIndex(index)
     else:
         qWarning("Update interval of %ds is not available." %(curInterval))
         qWarning("Resetting to default of %ds" %(Properties.DEFAULT_UPDATE_INTERVAL))
         self.prop.setUpdateInterval(Properties.DEFAULT_UPDATE_INTERVAL)
         self.setCurrentComboBoxUpdInterval()
Example #17
0
 def startDrag(self, 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()
Example #18
0
 def tabCloseRequested(self, index):
     if not isinstance(self.sender(), ToolWindowManagerArea):
         qWarning("sender is not a ToolWindowManagerArea")
         return
     area = self.sender()
     toolWindow = area.widget(index)
     if not self.hasToolWindow(toolWindow):
         qWarning("unknown tab in tab widget")
         return
     self.hideToolWindow(toolWindow)
Example #19
0
	def tabCloseRequested( self, index ):
		if not isinstance( self.sender(), ToolWindowManagerArea ):
			qWarning( 'sender is not a ToolWindowManagerArea' )
			return
		area = self.sender()
		toolWindow = area.widget( index )
		if not self.hasToolWindow( toolWindow ):
			qWarning( 'unknown tab in tab widget' )
			return
		self.hideToolWindow( toolWindow )
Example #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.topLevelWidget() == wrapper.topLevelWidget():
                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()
Example #21
0
def exception_hook(exception_type, exception_value, traceback_obj):
    separator = '-' * 80
    notice = "An unhandled exception occurred."
    time_str = time.strftime("%d.%m.%Y %H:%M:%S")
    tb_info_file = StringIO()
    traceback.print_tb(traceback_obj, None, tb_info_file)
    tb_info_file.seek(0)
    tb_info = tb_info_file.read()
    errmsg = '%s: \n%s' % (str(exception_type), str(exception_value))
    msg = '\n'.join([separator, time_str, separator, errmsg, separator, tb_info])
    qWarning('\n'.join((str(notice), msg)))
Example #22
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 ) )
Example #23
0
 def convert(self, script):
     self.setProperty('source', script)
     result = self.m_webPage.mainFrame().evaluateJavaScript('''try {
                                                                   [true, this.CoffeeScript.compile(converter.source)];
                                                               } catch (error) {
                                                                   [false, error.message];
                                                               }''')
     if result[0] is False:
         qWarning(result[1])
         return ''
     return result[1]
Example #24
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))
def saveToFile(self, text, fileName):
    fileName = self.m_scriptDir + fileName
    try:
        f = codecs.open(fileName, 'w+', 'utf-8')
    except IOError:
        qWarning('phantom.saveToFile - Could not open file: \'%s\'' % fileName)
        return False

    f.write(text)
    f.close()

    return True
Example #26
0
def saveToFile(self, text, fileName):
    fileName = self.m_scriptDir + fileName
    try:
        f = codecs.open(fileName, 'w+', 'utf-8')
    except IOError:
        qWarning('phantom.saveToFile - Could not open file: \'%s\'' % fileName)
        return False

    f.write(text)
    f.close()

    return True
Example #27
0
 def htmlCodeReplace(matchedStr):
     '''
     @param string matchedStr - &#dddd;
     @see Util.HTMLCODE_PATTERN
     '''
     try:
         htmlCoded = matchedStr.group(0)
         intCode = int(htmlCoded[2:7])
         return unichr(intCode)
     except:
         traceback.print_exc()
         qWarning(htmlCoded)
         return htmlCoded
Example #28
0
 def restoreState(self, data):
     if data.has_key('geometry'):
         self.restoreGeometry(data['geometry'])
     if self.layout().count() > 0:
         qWarning('wrapper is not empty')
         return
     if data.has_key('splitter'):
         self.layout().addWidget(
             self.manager.restoreSplitterState(data['splitter'].toMap()))
     elif data.has_key('area'):
         area = self.manager.createArea()
         area.restoreState(data['area'])
         self.layout().addWidget(area)
Example #29
0
	def saveState( self ):
		result = {}		
		objectNames = []
		for i in range( self.count() ):
			name = self.widget( i ).objectName()
			if name:
				objectNames.append( name )
			else:
				qWarning("cannot save state of tool window without object name")
		result["type"] = "area"
		result["currentIndex"] = self.currentIndex()
		result["objectNames"] = objectNames
		return result
Example #30
0
    def evalJson(str, withQuotes=True):
        try:
            if withQuotes:
                fixed = eval('\'%s\'' %(str))
            else:
                fixed = eval(str)
        except SyntaxError:
            fixed = ""
            qWarning("Syntax error")
            qWarning(str)
            traceback.print_stack()

        return fixed
Example #31
0
def saveToFile(self, text, fileName, mode='a'):
    if not os.path.isabs(fileName):
        scriptDir = os.path.dirname(os.path.abspath(self.m_scriptFile))
        fileName = os.path.join(scriptDir, fileName)

    try:
        with codecs.open(fileName, mode, 'utf-8') as f:
            f.write(text)
    except IOError:
        qWarning('phantom.saveToFile - Could not open file \'%s\' for writing' % fileName)
        return False

    return True
Example #32
0
	def restoreState( self, data ):
		if data.has_key( 'geometry' ):
			self.restoreGeometry( data['geometry'] )
		if self.layout().count() > 0:
			qWarning('wrapper is not empty')
			return
		if data.has_key( 'splitter' ):
			self.layout().addWidget(
				self.manager.restoreSplitterState(data['splitter'].toMap())
				)
		elif data.has_key( 'area' ):
			area = self.manager.createArea()
			area.restoreState( data['area'] )
			self.layout().addWidget( area )
Example #33
0
 def check_mouse_move(self, event):
     self.manager.updateDragPosition()
     if event.buttons() == Qt.LeftButton \
     and not self.rect().contains( self.mapFromGlobal( QCursor.pos() ) ) \
     and self.dragCanStart:
         self.dragCanStart = False
         toolWindows = []
         for i in range(self.count()):
             toolWindow = self.widget(i)
             if self.manager.hasToolWindow(toolWindow):
                 toolWindows.append(toolWindow)
             else:
                 qWarning("tab widget contains unmanaged widget")
         self.manager.startDrag(toolWindows)
Example #34
0
 def saveState(self):
     result = {}
     objectNames = []
     for i in range(self.count()):
         name = self.widget(i).objectName()
         if name:
             objectNames.append(name)
         else:
             qWarning(
                 "cannot save state of tool window without object name")
     result["type"] = "area"
     result["currentIndex"] = self.currentIndex()
     result["objectNames"] = objectNames
     return result
Example #35
0
	def check_mouse_move( self, event ):
		self.manager.updateDragPosition()
		if event.buttons() == Qt.LeftButton \
		and	not self.rect().contains( self.mapFromGlobal( QCursor.pos() ) ) \
		and	self.dragCanStart:
			self.dragCanStart = False
			toolWindows = []
			for i in range( self.count() ):
				toolWindow = self.widget(i)
				if self.manager.hasToolWindow( toolWindow ):
					toolWindows.append( toolWindow )
				else:
					qWarning("tab widget contains unmanaged widget")
			self.manager.startDrag(toolWindows)
Example #36
0
	def showNextDropSuggestion( self ):
		if len( self.suggestions ) == 0:
			qWarning( 'showNextDropSuggestion called but no suggestions' )
			return

		self.dropCurrentSuggestionIndex += 1
		if self.dropCurrentSuggestionIndex >= len( self.suggestions ):
			self.dropCurrentSuggestionIndex = 0
		
		suggestion = self.suggestions[ self.dropCurrentSuggestionIndex ]
		if suggestion.type in ( ToolWindowManager.AddTo , ToolWindowManager.EmptySpace ):
			if suggestion.type == ToolWindowManager.EmptySpace:
				widget = self.findChild( ToolWindowManagerWrapper )
			else:
				widget = suggestion.widget
			
			if widget.topLevelWidget() == self.topLevelWidget():
				placeHolderParent = self
			else:
				placeHolderParent = widget.topLevelWidget()

			placeHolderGeometry = widget.rect()
			placeHolderGeometry.moveTopLeft(
				widget.mapTo( placeHolderParent, placeHolderGeometry.topLeft() )
			)
			self.rectRubberBand.setGeometry( placeHolderGeometry )
			self.rectRubberBand.setParent( placeHolderParent )
			self.rectRubberBand.show()
			self.lineRubberBand.hide()

		elif suggestion.type in (
			ToolWindowManager.LeftOf , ToolWindowManager.RightOf,
			ToolWindowManager.TopOf , ToolWindowManager.BottomOf ):
			if suggestion.widget.topLevelWidget() == self.topLevelWidget():
				placeHolderParent = self
			else:
				placeHolderParent = suggestion.widget.topLevelWidget()

			placeHolderGeometry = self.sidePlaceHolderRect( suggestion.widget, suggestion.type )
			placeHolderGeometry.moveTopLeft(
				suggestion.widget.mapTo( placeHolderParent, placeHolderGeometry.topLeft() )
			)
			self.lineRubberBand.setGeometry(placeHolderGeometry)
			self.lineRubberBand.setParent(placeHolderParent)
			self.lineRubberBand.show()
			self.rectRubberBand.hide()

		else:
			qWarning( 'unsupported suggestion type' )
Example #37
0
	def saveState( self ):
		result = {}
		result[ 'toolWindowManagerStateFormat' ] = 1
		mainWrapper = self.findChild( ToolWindowManagerWrapper )
		if not mainWrapper:
			qWarning( 'can not find main wrapper' )
			return {}

		result[ 'mainWrapper' ] = mainWrapper.saveState()
		floatingWindowsData = []
		for wrapper in self.wrappers:
			if not wrapper.isWindow(): continue
			floatingWindowsData.append( wrapper.saveState() )
		result['floatingWindows'] = floatingWindowsData
		return result
Example #38
0
    def getTicker(self, rowNumber):
        '''
        @param int row
        '''
        row = self.table[rowNumber]
        e = row['e']
        t = row['t']
        if t is not None and t is not "":
            if e is not None and e is not "":
                return e + ":" + t
            else:
                return t

        qWarning("Selected entry does not have a valid exchange or ticker.")
        return ""
Example #39
0
    def showNextDropSuggestion(self):
        if len(self.suggestions) == 0:
            qWarning("showNextDropSuggestion called but no suggestions")
            return

        self.dropCurrentSuggestionIndex += 1
        if self.dropCurrentSuggestionIndex >= len(self.suggestions):
            self.dropCurrentSuggestionIndex = 0

        suggestion = self.suggestions[self.dropCurrentSuggestionIndex]
        if suggestion.type in (ToolWindowManager.AddTo, ToolWindowManager.EmptySpace):
            if suggestion.type == ToolWindowManager.EmptySpace:
                widget = self.findChild(ToolWindowManagerWrapper)
            else:
                widget = suggestion.widget

            if widget.topLevelWidget() == self.topLevelWidget():
                placeHolderParent = self
            else:
                placeHolderParent = widget.topLevelWidget()

            placeHolderGeometry = widget.rect()
            placeHolderGeometry.moveTopLeft(widget.mapTo(placeHolderParent, placeHolderGeometry.topLeft()))
            self.rectRubberBand.setGeometry(placeHolderGeometry)
            self.rectRubberBand.setParent(placeHolderParent)
            self.rectRubberBand.show()
            self.lineRubberBand.hide()

        elif suggestion.type in (
            ToolWindowManager.LeftOf,
            ToolWindowManager.RightOf,
            ToolWindowManager.TopOf,
            ToolWindowManager.BottomOf,
        ):
            if suggestion.widget.topLevelWidget() == self.topLevelWidget():
                placeHolderParent = self
            else:
                placeHolderParent = suggestion.widget.topLevelWidget()

            placeHolderGeometry = self.sidePlaceHolderRect(suggestion.widget, suggestion.type)
            placeHolderGeometry.moveTopLeft(suggestion.widget.mapTo(placeHolderParent, placeHolderGeometry.topLeft()))
            self.lineRubberBand.setGeometry(placeHolderGeometry)
            self.lineRubberBand.setParent(placeHolderParent)
            self.lineRubberBand.show()
            self.rectRubberBand.hide()

        else:
            qWarning("unsupported suggestion type")
Example #40
0
    def saveState(self):
        result = {}
        result["toolWindowManagerStateFormat"] = 1
        mainWrapper = self.findChild(ToolWindowManagerWrapper)
        if not mainWrapper:
            qWarning("can not find main wrapper")
            return {}

        result["mainWrapper"] = mainWrapper.saveState()
        floatingWindowsData = []
        for wrapper in self.wrappers:
            if not wrapper.isWindow():
                continue
            floatingWindowsData.append(wrapper.saveState())
        result["floatingWindows"] = floatingWindowsData
        return result
Example #41
0
    def finishDrag(self):
        if not self.dragInProgress():
            qWarning("unexpected finishDrag")
            return

        if len(self.suggestions) == 0:
            self.moveToolWindows(self.draggedToolWindows, ToolWindowManager.NewFloatingArea)
        else:
            if self.dropCurrentSuggestionIndex >= len(self.suggestions):
                qWarning("invalid self.dropCurrentSuggestionIndex")
                return
            suggestion = self.suggestions[self.dropCurrentSuggestionIndex]
            self.handleNoSuggestions()
            self.moveToolWindows(self.draggedToolWindows, suggestion)

        self.dragIndicator.hide()
        self.draggedToolWindows = []
Example #42
0
	def finishDrag( self ):
		if not self.dragInProgress():
			qWarning( 'unexpected finishDrag' )
			return

		if len( self.suggestions ) == 0:
			self.moveToolWindows( self.draggedToolWindows, ToolWindowManager.NewFloatingArea )
		else:
			if self.dropCurrentSuggestionIndex >= len( self.suggestions ):
				qWarning( 'invalid self.dropCurrentSuggestionIndex' )
				return
			suggestion = self.suggestions[ self.dropCurrentSuggestionIndex ]
			self.handleNoSuggestions()
			self.moveToolWindows( self.draggedToolWindows, suggestion )

		self.dragIndicator.hide()
		self.draggedToolWindows = []
Example #43
0
def injectJsInFrame(filePath, scriptLookupDir, targetFrame):
    try:
        # if file doesn't exist in the CWD, use the lookup
        if not os.path.exists(filePath):
            filePath = os.path.join(scriptLookupDir, filePath)

        with codecs.open(filePath, encoding='utf-8') as f:
            script = f.read()

        if script.startswith('#!') and not filePath.lower().endswith('.coffee'):
            script = '//' + script

        targetFrame.evaluateJavaScript(script if not filePath.lower().endswith('.coffee') else coffee2js(script))
        return True
    except IOError:
        qWarning('No such file or directory: \'%s\'' % filePath)
        return False
Example #44
0
	def sideSensitiveArea( self, widget, side ):
		widgetRect = widget.rect()
		if side == ToolWindowManager.TopOf:
			return QRect(QPoint(widgetRect.left(), widgetRect.top() - self.borderSensitivity),
									 QSize(widgetRect.width(), self.borderSensitivity * 2))
		elif side == ToolWindowManager.LeftOf:
			return QRect(QPoint(widgetRect.left() - self.borderSensitivity, widgetRect.top()),
									 QSize(self.borderSensitivity * 2, widgetRect.height()))

		elif side == ToolWindowManager.BottomOf:
			return QRect(QPoint(widgetRect.left(), widgetRect.top() + widgetRect.height() - self.borderSensitivity),
									 QSize(widgetRect.width(), self.borderSensitivity * 2))
		elif side == ToolWindowManager.RightOf:
			return QRect(QPoint(widgetRect.left() + widgetRect.width() - self.borderSensitivity, widgetRect.top()),
									 QSize(self.borderSensitivity * 2, widgetRect.height()))
		else:
			qWarning( 'invalid side' )
			return QRect()
Example #45
0
    def restoreSplitterState(self, data):
        if len(data["items"]) < 2:
            qWarning("invalid splitter encountered")

        splitter = self.createSplitter()

        for itemData in data["items"]:
            itemType = itemData["type"]
            if itemType == "splitter":
                splitter.addWidget(self.restoreSplitterState(itemData))
            elif itemType == "area":
                area = self.createArea()
                area.restoreState(itemData)
                splitter.addWidget(area)
            else:
                qWarning("unknown item type")
        splitter.restoreState(data["state"])
        return splitter
Example #46
0
	def restoreSplitterState( self, data ):
		if len( data[ 'items' ] )< 2:
			qWarning( 'invalid splitter encountered' )

		splitter = self.createSplitter()

		for itemData in data[ 'items' ]:
			itemType = itemData['type']
			if itemType == 'splitter':
				splitter.addWidget( self.restoreSplitterState( itemData ) )
			elif itemType == 'area':
				area = self.createArea()
				area.restoreState( itemData )
				splitter.addWidget( area )
			else:
				qWarning( 'unknown item type' )
		splitter.restoreState( data['state'] )
		return splitter
    def createRequest(self, op, req, outgoingData):
        if op == QNetworkAccessManager.GetOperation:
            qDebug('HTTP/1.1 GET Request')
        elif op == QNetworkAccessManager.PostOperation:
            qDebug('HTTP/1.1 POST Request')
        elif op == QNetworkAccessManager.HeadOperation:
            qDebug('HTTP/1.1 HEAD Request')
        elif op == QNetworkAccessManager.PutOperation:
            qDebug('HTTP/1.1 PUT Request')
        elif op == QNetworkAccessManager.DeleteOperation:
            qDebug('HTTP/1.1 DELETE Request')
        elif op == QNetworkAccessManager.CustomOperation:
            qDebug('HTTP/1.1 CUSTOM Request')
        else:
            qWarning('Unexpected HTTP Operation Type')

        qDebug('URL %s' % req.url().toString())

        return QNetworkAccessManager.createRequest(self, op, req, outgoingData)
Example #48
0
	def restoreState( self, data ):
		if not isinstance( data, dict ): return
		if data[ 'toolWindowManagerStateFormat' ] != 1:
			qWarning( 'state format is not recognized' )
			return
		self.moveToolWindows( self.toolWindowList, ToolWindowManager.NoArea )
		mainWrapper = self.findChild( ToolWindowManagerWrapper )
		if not mainWrapper:
			qWarning( 'can not find main wrapper' )

		mainWrapper.restoreState( data['mainWrapper'] )
		for windowData in data['floatingWindows']:
			wrapper = ToolWindowManagerWrapper( self )
			wrapper.restoreState( windowData )
			wrapper.show()

		self.simplifyLayout()
		for toolWindow in self.toolWindowList:
			self.toolWindowVisibilityChanged.emit( toolWindow, toolWindow.parentWidget() != None )
Example #49
0
    def __init__(self, parent, jsonFile):
        QObject.__init__(self, parent)

        with codecs.open(jsonFile, encoding='utf-8') as fd:
            json = fd.read()

        self.settings = {
            'auth': { 'mapping': 'auth', 'default': None },
            'cookies': { 'mapping': 'cookies', 'default': None },
            'diskCache': { 'mapping': 'disk_cache', 'default': False },
            'ignoreSslErrors': { 'mapping': 'ignore_ssl_errors', 'default': False },
            'loadImages': { 'mapping': 'load_images', 'default': True },
            'loadPlugins': { 'mapping': 'load_plugins', 'default': False },
            'localAccessRemote': { 'mapping': 'local_access_remote', 'default': False },
            'outputEncoding': { 'mapping': 'output_encoding', 'default': 'System' },
            'proxy': { 'mapping': 'proxy', 'default': None },
            'scriptEncoding': { 'mapping': 'script_encoding', 'default': 'utf-8' },
            'verbose': { 'mapping': 'verbose', 'default': False }
        }

        # generate dynamic properties
        for setting in self.settings:
            self.setProperty(setting, self.settings[setting]['default'])

        # now it's time to parse our JSON file
        if not json.lstrip().startswith('{') or not json.rstrip().endswith('}'):
            qWarning('Config file MUST be in JSON format!')
            return

        file_ = QFile(':/configurator.js')
        if not file_.open(QFile.ReadOnly):
            sys.exit('Unable to load JSON configurator!')
        configurator = str(file_.readAll())
        file_.close()
        if not configurator:
            sys.exit('Unable to set-up JSON configurator!')

        webPage = QWebPage(self)

        # add config object
        webPage.mainFrame().addToJavaScriptWindowObject('config', self)
        # apply settings
        webPage.mainFrame().evaluateJavaScript(configurator.replace('%1', json))
Example #50
0
    def saveSplitterState(self, splitter):
        result = {}
        result["state"] = splitter.saveState()
        result["type"] = "splitter"

        items = []
        for i in range(splitter.count()):
            item = splitter.widget(i)
            area = cast(item, ToolWindowManagerArea)
            if area:
                items.append(area.saveState())
            else:
                childSplitter = cast(item, QSplitter)
                if childSplitter:
                    items.append(self.saveSplitterState(childSplitter))
                else:
                    qWarning("unknown splitter item")
        result["items"] = items
        return result
Example #51
0
	def saveSplitterState( self, splitter ):
		result = {}
		result['state'] = splitter.saveState()
		result['type'] = 'splitter'
		
		items = []
		for i in range( splitter.count() ):
			item = splitter.widget(i)
			area = cast( item, ToolWindowManagerArea )
			if area:
				items.append( area.saveState() )
			else:
				childSplitter = cast( item, QSplitter )
				if childSplitter:
					items.append( self. saveSplitterState( childSplitter ) )
				else:
					qWarning( 'unknown splitter item' )
		result['items'] = items
		return result
    def createRequest(self, op, req, outgoingData):
        if op == QNetworkAccessManager.GetOperation:
            qDebug('HTTP/1.1 GET Request')
        elif op == QNetworkAccessManager.PostOperation:
            qDebug('HTTP/1.1 POST Request')
        elif op == QNetworkAccessManager.HeadOperation:
            qDebug('HTTP/1.1 HEAD Request')
        elif op == QNetworkAccessManager.PutOperation:
            qDebug('HTTP/1.1 PUT Request')
        elif op == QNetworkAccessManager.DeleteOperation:
            qDebug('HTTP/1.1 DELETE Request')
        elif op == QNetworkAccessManager.CustomOperation:
            qDebug('HTTP/1.1 CUSTOM Request')
        else:
            qWarning('Unexpected HTTP Operation Type')

        qDebug('URL %s' % req.url().toString())

        return QNetworkAccessManager.createRequest(self, op, req, outgoingData)
Example #53
0
    def slot_backendError(self, error):
        firstBackendInit = self.fFirstBackendInit
        self.fFirstBackendInit = False

        # stop webserver
        self.stopAndWaitForWebServer()

        # crashed while stopping, ignore
        if error == QProcess.Crashed and self.fStoppingBackend:
            return

        errorStr = self.tr("Could not start host backend.\n") + self.getProcessErrorAsString(error)
        qWarning(errorStr)

        # don't show error if this is the first time starting the host or using live-iso
        if firstBackendInit or USING_LIVE_ISO:
            return

        # show the error message
        QMessageBox.critical(self, self.tr("Error"), errorStr)
Example #54
0
    def __init__(self, parent, jsonFile):
        super(Config, self).__init__(parent)

        with codecs.open(jsonFile, encoding='utf-8') as fd:
            json = fd.read()

        self.settings = {
            'cookiesFile': { 'mapping': 'cookies_file', 'default': None },
            'debug': { 'mapping': 'debug', 'default': None },
            'diskCache': { 'mapping': 'disk_cache', 'default': False },
            'ignoreSslErrors': { 'mapping': 'ignore_ssl_errors', 'default': False },
            'loadImages': { 'mapping': 'load_images', 'default': True },
            'loadPlugins': { 'mapping': 'load_plugins', 'default': False },
            'localToRemoteUrlAccessEnabled': { 'mapping': 'local_to_remote_url_access', 'default': False },
            'maxDiskCacheSize': { 'mapping': 'max_disk_cache_size', 'default': -1 },
            'outputEncoding': { 'mapping': 'output_encoding', 'default': 'System' },
            'proxy': { 'mapping': 'proxy', 'default': None },
            'scriptEncoding': { 'mapping': 'script_encoding', 'default': 'utf-8' },
            'verbose': { 'mapping': 'verbose', 'default': False }
        }

        do_action('ConfigInit', self.settings)

        # generate dynamic properties
        for setting in self.settings:
            self.setProperty(setting, self.settings[setting]['default'])

        # now it's time to parse our JSON file
        if not json.lstrip().startswith('{') or not json.rstrip().endswith('}'):
            qWarning('Config file MUST be in JSON format!')
            return

        with QPyFile(':/configurator.js') as f:
            configurator = f.readAll()

        webPage = QWebPage(self)

        # add config object
        webPage.mainFrame().addToJavaScriptWindowObject('config', self)
        # apply settings
        webPage.mainFrame().evaluateJavaScript(configurator.replace('%1', json))
Example #55
0
	def setWidget( self, widget ):
		if self.type in [ 
		ToolWindowManager.LastUsedArea,
		ToolWindowManager.NewFloatingArea,
		ToolWindowManager.NoArea,
		ToolWindowManager.EmptySpace ]:
			if widget:
				qWarning( 'area parameter ignored for this type' )
			self.widget = None

		elif self.type == ToolWindowManager.AddTo:
			if isinstance( widget, ToolWindowManagerArea ):
				self.widget = widget
			else:
				qWarning( 'only ToolWindowManagerArea can be used with this type' )

		else:
			if isinstance( widget, ToolWindowManagerArea ) or	isinstance( widget, QSplitter ):
				self.widget = widget
			else:
				qWarning( 'only ToolWindowManagerArea or splitter can be used with this type' )
				self.widget = None
Example #56
0
    def saveState(self):
        result = {}
        if self.layout().count() > 1:
            qWarning('too many children for wrapper')
            return result

        if self.isWindow() and self.layout().count() == 0:
            qWarning('empty top level wrapper')
            return result

        result['geometry'] = str(self.saveGeometry())
        splitter = self.findChild(QtGui.QSplitter)
        if splitter:
            result['splitter'] = self.manager.saveSplitterState(splitter)
        else:
            area = self.findChild(ToolWindowManagerArea)
            if area:
                result['area'] = area.saveState()
            elif self.layout().count() > 0:
                qWarning('unknown child')
                return {}
        return result
Example #57
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

        QgsMapLayerRegistry.instance().addMapLayers([mVectorLayer])

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        mMapRenderer.setLayerSet(layerStringList)
        mMapRenderer.setProjectionsEnabled(True)
        mMapRenderer.setMapUnits(QGis.Meters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        mMapRenderer.setDestinationCrs(crs)

        self.mComposition = QgsComposition(mMapRenderer)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbolV2.createSimple(props)
        renderer = QgsSingleSymbolRendererV2(fillSymbol)
        mVectorLayer.setRendererV2(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.setOverviewFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbolV2.createSimple(props2)
        mOverview.setOverviewFrameMapSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%$feature || ' / ' || $numfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()

        shutil.rmtree(tmppath, True)
Example #58
0
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")