Example #1
0
class DiffView(QObject):
	def __init__(self, app, difftext, leftfile, rightfile):
		QObject.__init__(self)
		self.app = app


		self.difftext = difftext
		self.window = QMainWindow()
		self.window.setWindowTitle("Log Diffs")

		self.leftfile = leftfile
		self.rightfile = rightfile

		self.view = QDeclarativeView()
		self.glw = QtOpenGL.QGLWidget()
		self.view.setViewport(self.glw)
		self.view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)
		self.window.setCentralWidget(self.view)
		self.rc = self.view.rootContext()
		self.rc.setContextProperty('controller', self)
		self.rc.setContextProperty('difftext', self.difftext)
		self.view.setSource('diffview.qml')
		self.window.show()

	@Slot()
	def diff_viewer(self):
		p = subprocess.Popen("gvim -d {0} {1}".format(self.leftfile, self.rightfile), shell=True)
		sts = os.waitpid(p.pid, 0)[1]

	def checked(self):
		for build in self.build_list.checked(): 
				yield build
Example #2
0
class LogView(QObject):
	def __init__(self, app, logpath, id, sdk_model, row_number):
		QObject.__init__(self)
		self.app = app
		self.logpath = logpath
		
		self.window = QMainWindow()
		self.window.setWindowTitle("Raptor build viewer")
		self.build_list = BuildListModel(self.logpath)
		self.controller = BuildController(app, self.build_list, id, sdk_model, row_number)

		self.view = QDeclarativeView()
		self.glw = QtOpenGL.QGLWidget()
		self.view.setViewport(self.glw)
		self.view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)
		self.window.setCentralWidget(self.view)
		self.rc = self.view.rootContext()
		self.rc.setContextProperty('controller', self.controller)
		self.rc.setContextProperty('pyBuildListModel', self.build_list)
		self.rc.setContextProperty('logpath', self.logpath)
		self.rc.setContextProperty('info', sdk_model.sdk_info(id))
		self.rc.setContextProperty('window', self.window)
		self.rc.setContextProperty('row', row_number)
		self.view.setSource('logchooser.qml')
		self.window.show()

	def checked(self):
		for build in self.build_list.checked(): 
			yield build
class QmlGameFrame(QMainWindow):
    
    def __init__(self, parent = None) :
        '''
        Constructor
        '''
        super(QmlGameFrame, self).__init__(parent)
        
        layout = QVBoxLayout()
        
        self.view = QDeclarativeView(self)

        layout.addWidget(self.view)
        self.setLayout(layout)
                
        self.geoMap = GeoMap()
        #self.model.connect()
        
        #self.noteList = self.model.getNoteList()
        #self.noteList = self.model.getToDoList()
        
        
        
        rootContext = self.view.rootContext()
        rootContext.setContextProperty('geoMap', self.geoMap)
                
        path = QDir.currentPath() + '/../../qml/SimpleQmlGameEngine/main.qml'
        path = path.replace('users', 'Users')
        print path
        url = QUrl(path)
        #url = QUrl('file:///Users/unseon_pro/myworks/SimpleQmlGameEngine/qml/SimpleQmlGameEngine/main.qml')
        self.view.setSource(url)
Example #4
0
 def start(self):
     global client
     if (len(self.email) > 0 and len(self.password) > 0):
         self.email = str(self.email[0])
         self.password = str(base64.b64decode(self.password[0]))
         client = Client(self.email, self.password)
         response = client.login()
     
         if (response['result'] == 'ok'):
             startup = client.notify_startup()
             if (not startup):
                 print_message("Could not startup!")
             else:
                 print_message("Notified!")
     
     else:
         Mbox("Budibox", "Credentials undefined or incorrect. Please login again.") 
         
         # Create the QML user interface.
         view = QDeclarativeView()
         view.setSource(QUrl('qml/main.qml'))
         view.setWindowTitle("Budibox")
         view.setWindowIcon(QIcon("qml/budibox.jpg"))
         
         context = view.rootContext()
         context.setContextProperty("send_data",Receive_data())
         
         # Display the user interface and allow the user to interact with it.
         view.setGeometry(360, 360, 360, 360)
         view.setMaximumSize(360, 360)
         view.show()
         
         app.exec_()
Example #5
0
class QmlGui(Gui):

    USES = ['geonames', 'qmllocationprovider']

    def __init__(self, core, dataroot, parent=None):
        self.app = QApplication(sys.argv)
        self.core = core
        self.view = QDeclarativeView()
        self.view.statusChanged.connect(self._status_changed)
        glw = QGLWidget()
        self.view.setViewport(glw)
        
        self.controller = Controller(self.view, self.core)
        self.settings = SettingsWrapper(self.core)

        rc = self.view.rootContext()
        rc.setContextProperty('controller', self.controller)
        rc.setContextProperty('settings', self.settings)
        rc.setContextProperty('gps', GPSDataWrapper(self.core))
        self.view.setSource(os.path.join('qml','main.qml'))

    def get_gps(self, callback):
        self.controller.callback_gps = callback

    def show(self):
        self.view.showFullScreen()
        self.app.exec_()
        self.core.on_destroy()

    def _status_changed(self, error):
        logger.error(self.view.errors())
Example #6
0
class DiffView(QObject):
    def __init__(self, app, difftext, leftfile, rightfile):
        QObject.__init__(self)
        self.app = app

        self.difftext = difftext
        self.window = QMainWindow()
        self.window.setWindowTitle("Log Diffs")

        self.leftfile = leftfile
        self.rightfile = rightfile

        self.view = QDeclarativeView()
        self.glw = QtOpenGL.QGLWidget()
        self.view.setViewport(self.glw)
        self.view.setResizeMode(
            QtDeclarative.QDeclarativeView.SizeRootObjectToView)
        self.window.setCentralWidget(self.view)
        self.rc = self.view.rootContext()
        self.rc.setContextProperty('controller', self)
        self.rc.setContextProperty('difftext', self.difftext)
        self.view.setSource('diffview.qml')
        self.window.show()

    @Slot()
    def diff_viewer(self):
        p = subprocess.Popen("gvim -d {0} {1}".format(self.leftfile,
                                                      self.rightfile),
                             shell=True)
        sts = os.waitpid(p.pid, 0)[1]

    def checked(self):
        for build in self.build_list.checked():
            yield build
Example #7
0
class LogView(QObject):
    def __init__(self, app, logpath, id, sdk_model, row_number):
        QObject.__init__(self)
        self.app = app
        self.logpath = logpath

        self.window = QMainWindow()
        self.window.setWindowTitle("Raptor build viewer")
        self.build_list = BuildListModel(self.logpath)
        self.controller = BuildController(app, self.build_list, id, sdk_model,
                                          row_number)

        self.view = QDeclarativeView()
        self.glw = QtOpenGL.QGLWidget()
        self.view.setViewport(self.glw)
        self.view.setResizeMode(
            QtDeclarative.QDeclarativeView.SizeRootObjectToView)
        self.window.setCentralWidget(self.view)
        self.rc = self.view.rootContext()
        self.rc.setContextProperty('controller', self.controller)
        self.rc.setContextProperty('pyBuildListModel', self.build_list)
        self.rc.setContextProperty('logpath', self.logpath)
        self.rc.setContextProperty('info', sdk_model.sdk_info(id))
        self.rc.setContextProperty('window', self.window)
        self.rc.setContextProperty('row', row_number)
        self.view.setSource('logchooser.qml')
        self.window.show()

    def checked(self):
        for build in self.build_list.checked():
            yield build
    def testModelExport(self):
        view = QDeclarativeView()
        dataList = [MyObject("Item 1"), MyObject("Item 2"), MyObject("Item 3"), MyObject("Item 4")]

        ctxt = view.rootContext()
        ctxt.setContextProperty("myModel", dataList)

        url = QUrl.fromLocalFile(adjust_filename("viewmodel.qml", __file__))
        view.setSource(url)
        view.show()

        self.assertEqual(view.status(), QDeclarativeView.Ready)
Example #9
0
def main():
    app = QApplication([])
    view = QDeclarativeView()
    manager = ServiceManager()
    context = view.rootContext()
    context.setContextProperty("manager", manager)

    url = QUrl('main.qml')
    view.setSource(url)
    view.showFullScreen()

    app.exec_()
def main():
    app = QApplication([])
    view = QDeclarativeView()
    manager = MyContactManager()
    context = view.rootContext()
    context.setContextProperty("manager", manager)

    url = QUrl('main.qml')
    view.setSource(url)
    view.showFullScreen()

    app.exec_()
    def testQDeclarativeViewList(self):
        view = QDeclarativeView()

        dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]

        ctxt = view.rootContext()
        ctxt.setContextProperty("myModel", dataList)

        url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
        view.setSource(url)
        view.show()

        self.assertEqual(view.status(), QDeclarativeView.Ready)
def main():
  app = QApplication(sys.argv)

  server = ElServer()
  server.start()

  view = QDeclarativeView()
  rootContext = view.rootContext()
  rootContext.setContextProperty('server', server)
  view.setSource('main.qml')
  view.showFullScreen()

  app.exec_()

  server.stop()
Example #13
0
def main():
    app = QApplication([])
    view = QDeclarativeView()
    manager = TodoManager()
    context = view.rootContext()
    context.setContextProperty("manager", manager)

    url = QUrl('main.qml')
    view.setSource(url)

    if "-no-fs" not in sys.argv:
        view.showFullScreen()
    else:
        view.show()

    app.exec_()
Example #14
0
def main():
    app = QApplication([])
    view = QDeclarativeView()
    manager = TodoManager()
    context = view.rootContext()
    context.setContextProperty("manager", manager)

    url = QUrl('main.qml')
    view.setSource(url)

    if "-no-fs" not in sys.argv:
        view.showFullScreen()
    else:
        view.show()

    app.exec_()
Example #15
0
def main():
    app = QApplication([])
    app.setApplicationName("Audio Output Test")
    view = QDeclarativeView()

    devices = []
    for info in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
        devices.append(info)

    player = TonePlayer(devices, sys.argv[1] if len(sys.argv) > 1 else None)

    context = view.rootContext()
    context.setContextProperty("player", player)
    context.setContextProperty("deviceModel", [x.deviceName() for x in devices])

    url = QUrl("main.qml")
    view.setSource(url)

    view.show()

    app.exec_()
Example #16
0
class SDKView(QObject):
	def __init__(self, app, window, logpath=None):
		QObject.__init__(self)
		self.app = app
		
		self.sdk_list_model = SDKListModel()
		self.controller = SDKController(app, self.sdk_list_model)

		self.view = QDeclarativeView()
		self.glw = QtOpenGL.QGLWidget()
		self.view.setViewport(self.glw)
		self.view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)
		window.setCentralWidget(self.view)
		self.rc = self.view.rootContext()
		self.rc.setContextProperty('sdk_controller', self.controller)
		self.rc.setContextProperty('pySDKListModel', self.sdk_list_model)
		self.view.setSource('sdkchooser.qml')
	
	@Slot()
	def quit(self):
		self.controller.quit()
Example #17
0
class SDKView(QObject):
    def __init__(self, app, window, logpath=None):
        QObject.__init__(self)
        self.app = app

        self.sdk_list_model = SDKListModel()
        self.controller = SDKController(app, self.sdk_list_model)

        self.view = QDeclarativeView()
        self.glw = QtOpenGL.QGLWidget()
        self.view.setViewport(self.glw)
        self.view.setResizeMode(
            QtDeclarative.QDeclarativeView.SizeRootObjectToView)
        window.setCentralWidget(self.view)
        self.rc = self.view.rootContext()
        self.rc.setContextProperty('sdk_controller', self.controller)
        self.rc.setContextProperty('pySDKListModel', self.sdk_list_model)
        self.view.setSource('sdkchooser.qml')

    @Slot()
    def quit(self):
        self.controller.quit()
Example #18
0
def main():
    app = QApplication([])
    app.setApplicationName('Audio Output Test')
    view = QDeclarativeView()

    devices = []
    for info in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
        devices.append(info)

    player = TonePlayer(devices, sys.argv[1] if len(sys.argv) > 1 else None)

    context = view.rootContext()
    context.setContextProperty("player", player)
    context.setContextProperty("deviceModel",
                               [x.deviceName() for x in devices])

    url = QUrl('main.qml')
    view.setSource(url)

    view.show()

    app.exec_()
Example #19
0
class QtControl(Thread):
    def __init__(self, gs):
        super(QtControl, self).__init__()

        self.gs = gs
        self.cmd = Commands(gs)
        self.results = ResultsModel(self.gs.best_times['_'])

    def get_results(self):
        # self.ctxt.setContextProperty("resutlts", [['<b>{0: >4}.</b> {2} [<font align="right" color="grey">{1:.2f}</font>]'.format(i, t[0], t[1]['name'])
        #                                               for i,t in enumerate(self.gs.best_times[s],1)]
        #                                              for s in self.gs.sets])
        self.ctxt.setContextProperty("results", self.results)

    def run(self):
        self.app = QApplication([])
        self.view = QDeclarativeView()
        self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)

        self.ctxt = self.view.rootContext()
        # setting context properities
        self.ctxt.setContextProperty("sets", self.gs.sets)
        self.ctxt.setContextProperty("cmd", self.cmd)
        self.ctxt.setContextProperty("dist", self.gs.dist)
        self.ctxt.setContextProperty("results", self.results)

        self.view.setSource(QUrl(os.path.join(BASE_QML_PATH, 'view_n900.qml')))
        self.root = self.view.rootObject()
        # connecting signals
        self.gs.out.qiface.update_race.connect(self.root.update_race)
        self.gs.out.qiface.start.connect(self.root.start)
        self.gs.out.qiface.abort.connect(self.root.abort)
        self.gs.out.qiface.finish.connect(self.root.finish)
        self.gs.out.qiface.finish.connect(self.get_results)
        self.gs.out.qiface.new_race.connect(self.root.new_race)

        self.view.show()
        self.app.exec_()
Example #20
0
class QtControl(Thread):
    def __init__(self, gs):
        super(QtControl, self).__init__()

        self.gs = gs
        self.cmd=Commands(gs)
        self.results=ResultsModel(self.gs.best_times['_'])

    def get_results(self):
        # self.ctxt.setContextProperty("resutlts", [['<b>{0: >4}.</b> {2} [<font align="right" color="grey">{1:.2f}</font>]'.format(i, t[0], t[1]['name'])
        #                                               for i,t in enumerate(self.gs.best_times[s],1)]
        #                                              for s in self.gs.sets])
        self.ctxt.setContextProperty("results", self.results)

    def run(self):
        self.app=QApplication([])
        self.view=QDeclarativeView()
        self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)

        self.ctxt = self.view.rootContext()
        # setting context properities
        self.ctxt.setContextProperty("sets", self.gs.sets)
        self.ctxt.setContextProperty("cmd", self.cmd)
        self.ctxt.setContextProperty("dist", self.gs.dist)
        self.ctxt.setContextProperty("results", self.results)

        self.view.setSource(QUrl(os.path.join(BASE_QML_PATH, 'view_n900.qml')))
        self.root=self.view.rootObject()
        # connecting signals
        self.gs.out.qiface.update_race.connect(self.root.update_race)
        self.gs.out.qiface.start.connect(self.root.start)
        self.gs.out.qiface.abort.connect(self.root.abort)
        self.gs.out.qiface.finish.connect(self.root.finish)
        self.gs.out.qiface.finish.connect(self.get_results)
        self.gs.out.qiface.new_race.connect(self.root.new_race)

        self.view.show()
        self.app.exec_()
    def __init__(self, *args):
        super(OverlayWidget, self).__init__(*args)

        # We need to set the base colour of the qml widget to be transparent.
        # This is done by setting its palette.
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Base, QtCore.Qt.transparent)

        qml_view = QDeclarativeView(self)
        qml_view.setPalette(palette)

        qml_context = qml_view.rootContext()
        qml_context.setContextProperty("slider_handler", self)

        url = QUrl('control_slides.qml')
        qml_view.setSource(url)

        qml_root = qml_view.rootObject()
        self.x_rotation_changed.connect(qml_root.x_rotation_changed)
        self.y_rotation_changed.connect(qml_root.y_rotation_changed)
        self.z_rotation_changed.connect(qml_root.z_rotation_changed)

        return
    def __init__(self, *args):
        super(OverlayWidget, self).__init__(*args)
        
        # We need to set the base colour of the qml widget to be transparent.
        # This is done by setting its palette.
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Base, QtCore.Qt.transparent)

        qml_view = QDeclarativeView(self)
        qml_view.setPalette(palette)

        qml_context = qml_view.rootContext()
        qml_context.setContextProperty("slider_handler", self)

        url = QUrl('control_slides.qml')
        qml_view.setSource(url)

        qml_root = qml_view.rootObject()
        self.x_rotation_changed.connect(qml_root.x_rotation_changed)
        self.y_rotation_changed.connect(qml_root.y_rotation_changed)
        self.z_rotation_changed.connect(qml_root.z_rotation_changed)

        return
Example #23
0
def main():
    QApplication.setOrganizationName('OpenBossa')
    QApplication.setApplicationName('mobtrans')
    QApplication.setGraphicsSystem('raster')
    app = QApplication([])
    serverConfig = ServerConfig()
    server = Server(serverConfig)
    model = TorrentModel(server)
    searchModel = SearchModel()

    view = QDeclarativeView()
    #view.setMinimumSize(800, 600)
    view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
    view.rootContext().setContextProperty('server', server)
    view.rootContext().setContextProperty('torrentModel', model)
    view.rootContext().setContextProperty('searchModel', searchModel)
    view.setSource(QUrl.fromLocalFile('./qml/main.qml'))
    view.show()
    app.exec_()
Example #24
0
            [dict(zip(['x', 'y'], targets[t].pos())) \
                for t in xrange(len(targets))] )

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("template", help="Temlate for image file name, containing "
    "%%1 where camera number should be inserted, and %%2 where frame number "
    "should be inserted. Example: my_scene/cam%%1.%%2")
parser.add_argument("first", type=int, help="Number of first frame")
parser.add_argument("last", type=int, help="Number of last frame")
parser.add_argument("--rate", type=int, default=100,
    help="Frame rate in frames per second")
args = parser.parse_args()

app = QApplication(sys.argv)
view = QDeclarativeView()
view.setSource(QtCore.QUrl('MovieBrowser.qml'))

view.rootContext().setContextProperty("image_explorer", ImageExplorer(args.template))
view.rootObject().setProperty("scene_template", args.template)
view.rootObject().setProperty("first_frame", args.first)
view.rootObject().setProperty("last_frame", args.last)
view.rootObject().setProperty("frame_rate", args.rate)

# Respond to frame change signals by possibly loading targets:


view.show()
sys.exit(app.exec_())

class GitGrownFrame(QMainWindow):
    '''
    classdocs
    '''

    @Slot(int)
    def onSelectedPathChanged(self, index) :
        print "onSelectedPathChanged is called"
        filePath = self.fileListModel.selectedValue
        obj = self.gitModel.getFileList()[index]
        
        if obj['type'] == 'blob' :
            self.fileViewModel = self.gitModel.getBlamedModel('HEAD', filePath)
            self.commitListModel = self.gitModel.getCommitListModel(filePath)
        elif obj['type'] ==  'tree':
            self.fileViewModel = None
            self.commitListModel = self.gitModel.getCommitListModel(filePath, 'dir')
        else :
            pass #error!!!!!
            
        rootContect = self.view.rootContext()
        rootContect.setContextProperty('fileViewModel', self.fileViewModel)
        rootContect.setContextProperty('commitListModel', self.commitListModel)
        self.commitListModel.selectionChanged.connect(self.onSelectedCommitChanged)
        self.commitListView.setProperty('currentIndex', 0)
        
        if obj['type'] == 'blob' :
            print "currentCommit is " + self.commitListModel.items[0][0]
            self.blameView.setProperty('currentCommit', self.commitListModel.items[0][0])

    @Slot(int)
    def onSelectedCommitChanged(self, index):
        print "onSelectedCommitChanged is called"
        sha = self.commitListModel.selectedValue
        filePath = self.fileListModel.selectedValue
        fileIndex = self.fileListModel.selectedIndex
        obj = self.gitModel.getFileList()[fileIndex]
        if obj['type'] == 'blob' :
            self.fileViewModel = self.gitModel.getBlamedModel(sha, filePath)
            rootContect = self.view.rootContext()
            rootContect.setContextProperty('fileViewModel', self.fileViewModel)
            self.blameView.setProperty('currentCommit', sha)
            print "blame model is changed"
            
    @Slot()
    def refreshStatus(self):
        print 'refreshed!!'
        self.gitModel.refreshStatus()
        rootContext = self.view.rootContext()
        rootContext.setContextProperty('gitStatus', self.gitModel.status)
        rootContext.setContextProperty('indexModel', self.gitModel.indexModel)
        self.flowModel = self.gitModel.getFlowModelWithBranches(
                                      ['master',
                                       'development',
                                       'feature_command',
                                       'feature_ui'])
        rootContext.setContextProperty('flowModel', self.flowModel)
                
    @Slot()
    def commit(self, msg):
        assert msg is not None and msg != ''
        
        print "GitGrownFrame : " + msg
        rslt = self.gitModel.executeCommit(msg)
        
        if rslt != 0:
            pass
        
        self.refreshStatus()
        
        #emit commited signal
        self.root.commited.emit()
        
    @Slot()
    def stageFile(self, path):
        print 'GitGrownFrame: slot stage called: ' + path
        self.gitModel.stageFile(path)
        self.refreshStatus()
        
    @Slot()
    def unstageFile(self, path):
        print 'GitGrownFrame: slot unstage called'
        self.gitModel.unstageFile(path)
        self.refreshStatus()
        
    @Slot()
    def undoRecentCommit(self):
        self.refreshStatus()
        if not self.gitModel.isIndexClear():
            print "GitGrownFrame: Undo Commit is not able " + \
                    "since index is not cleared"
        #get recent commit's message for restore to TextEdit
        headCommit = self.gitModel.getCommitInfo()
        print headCommit['summary']
        #undo
        self.gitModel.undoRecentCommit()        
        self.refreshStatus()
        self.root.commitUndone.emit(headCommit['summary'])
        
    @Slot()
    def discard(self, path):
        print 'GitGrownFrame: slot discard called'
        self.refreshStatus()
    
        
        
        

    def __init__(self, parent = None) :
        '''
        Constructor
        '''
        super(GitGrownFrame, self).__init__(parent)
        
        layout = QVBoxLayout()
        
        self.view = QDeclarativeView(self)

        layout.addWidget(self.view)
        self.setLayout(layout)
        
        self.gitModel = GitModel()
        #self.gitModel.connect('/Users/unseon_pro/myworks/RoughSketchpad')
        self.gitModel.connect('.')
        #self.gitModel.connect('/Users/unseon_pro/myworks/gitx')
        #self.gitModel.connect('/Users/unseon_pro/myworks/FlowsSample')
        
        self.configModel = self.gitModel.getConfigModel()
        
        self.fileListModel = self.gitModel.getFileListModel()
        self.fileListModel.selectionChanged.connect(self.onSelectedPathChanged)
        
        self.fileViewModel = None
        self.commitListModel = self.gitModel.getCommitListModel('', 'tree')
        
        #self.branchGraphModel = self.gitModel.getBranchGraphs()
        #self.commitListModel2 = self.gitModel.getCommitListModelFromBranch('master')
        
        
        self.flowModel = self.gitModel.getFlowModelWithBranches(
                                      ['master',
                                       'development',
                                       'feature_command',
                                       'feature_ui'])
        
        self.branchListModel = self.gitModel.getBranchListModel()
        
        # Create an URL to the QML file
        #url = QUrl('view.qml')
        #url = QUrl('BranchFlowView.qml')
        url = QUrl('MainView.qml')

        # Set the QML file and show
        
        rootContext = self.view.rootContext()
        
        #removed because of halt
        #rootContext.setContextProperty('rootFrame', self)
        rootContext.setContextProperty('config', self.configModel)
        rootContext.setContextProperty('fileListModel', self.fileListModel)
        rootContext.setContextProperty('fileViewModel', self.fileViewModel)
        rootContext.setContextProperty('commitListModel', self.commitListModel)
        rootContext.setContextProperty('flowModel', self.flowModel)
        rootContext.setContextProperty('gitModel', self.gitModel)
        rootContext.setContextProperty('branchListModel', self.branchListModel)

        
        self.refreshStatus()
        
        self.view.setSource(url)
        
        self.root = self.view.rootObject() #
        
        self.refreshButton = self.root.findChild(QObject, "refreshButton")
        self.refreshButton.clicked.connect(self.refreshStatus)

        self.commitButton = self.root.findChild(QObject, "commitButton")
        self.commitButton.commitWithMessage.connect(self.commit)
        
        self.undoCommitButton = self.root.findChild(QObject, "undoCommitButton")
        self.undoCommitButton.undoCommit.connect(self.undoRecentCommit)
        
        self.indexStatus = self.root.findChild(QObject, "indexStatus")
        self.indexStatus.stageFile.connect(self.stageFile)
        self.indexStatus.unstageFile.connect(self.unstageFile)
        
                
        
        #self.fileBrowser = root.findChild(QObject, "fileBrowser")
        #self.blameView = root.findChild(QObject, "blameView")
        #self.commitListView = root.findChild(QObject, "commitListView")
        
        self.selectedPath = '.'
        self.selectedCommit = None
        
Example #26
0
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    "template",
    help="Temlate for image file name, containing "
    "%%1 where camera number should be inserted, and %%2 where frame number "
    "should be inserted. Example: my_scene/cam%%1.%%2")
parser.add_argument("first", type=int, help="Number of first frame")
parser.add_argument("last", type=int, help="Number of last frame")
parser.add_argument("--rate",
                    type=int,
                    default=100,
                    help="Frame rate in frames per second")
args = parser.parse_args()

app = QApplication(sys.argv)
view = QDeclarativeView()
view.setSource(QtCore.QUrl('MovieBrowser.qml'))

view.rootContext().setContextProperty("image_explorer",
                                      ImageExplorer(args.template))
view.rootObject().setProperty("scene_template", args.template)
view.rootObject().setProperty("first_frame", args.first)
view.rootObject().setProperty("last_frame", args.last)
view.rootObject().setProperty("frame_rate", args.rate)

# Respond to frame change signals by possibly loading targets:

view.show()
sys.exit(app.exec_())
Example #27
0
File: gloUI.py Project: ksdme/GLO
@Slot()
def submitedTweet(tweet):
    print dumps({"ok": True, "tweet": str(tweet)})

    # Ideally Show a Tweeted msg
    # and then close the Messga
    QCoreApplication.quit()


#---------------------------
qView = QDeclarativeView()
qUrl = QUrl('./QML/main.qml')

# add the context first
qContext = qView.rootContext()
env = InitialEnvironment(parsed.user, "{} ago".format(parsed.last),
                         parsed.duration)
qContext.setContextProperty("environment", env)

# and then set source
qView.setSource(qUrl)

# hook required Slots
root = qView.rootObject()

# hook the safely quit command
root.safeQuit.connect(safelyQuitPlease)

# to timer and Cancel Button
cancelTweet = root.findChild(QObject, "cancelTweet")
Example #28
0
    def _get_running(self):
        return self._running

    def _set_running(self, running):
        self._running = running
        self.on_running.emit()

    def _get_result(self):
        return self._result


    on_progress = Signal()
    on_running = Signal()
    on_result = Signal()

    progress = Property(float, _get_progress, _set_progress, notify=on_progress)
    running = Property(bool, _get_running, _set_running, notify=on_running)
    result = Property(int, _get_result, notify=on_result) # notify for QML


if __name__ == '__main__':
    d = Downloader("http://www.advancedidasia.com/pdf/Reader_PR-510.pdf")
    app = QApplication(sys.argv)
    view = QDeclarativeView()
    view.rootContext().setContextProperty('downloader', d)
    view.setSource(__file__.replace('.py', '.qml'))
    view.show()
    app.exec_()


Example #29
0
            thread = threading.Thread(target=self._start_output)
            thread.start()
    
    def _set_x(self,x):
        self._x = x
        self.on_x_changed.emit()
    def _get_x(self):
        return self._x
    
    def _set_y(self,y):
        self._y = y
        self.on_y_changed.emit()
    def _get_y(self):
        return self._y
    
    on_x_changed = QtCore.Signal()
    on_y_changed = QtCore.Signal()
    
    x = QtCore.Property(float,_get_x,_set_x,notify=on_x_changed)
    y = QtCore.Property(float,_get_y,_set_y,notify=on_y_changed)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    view = QDeclarativeView()
    url = QtCore.QUrl("iSerial.qml")
    pycircle = myCircle(100,10,10)
    view.rootContext().setContextProperty("pycircle",pycircle)
    view.setSource(url)
    view.show()
    sys.exit(app.exec_())
Example #30
0
class QtClient:
    host="localhost"
    port=9998
    ctxt=''

    class Commands(QObject, Thread):
        finish = Signal()
        daemon = True

        def __init__(self, host, port):
            Thread.__init__(self)
            QObject.__init__(self)
            self.socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.connect((host,port))
            self.socket.settimeout(.5)
            self.setDaemon(True)

        def run(self):
            print 'running'
            while 1:
                try:
                    data = self.socket.recv(400)
                    if data:
                        print data
                    if data.startswith('finish'):
                        self.finish.emit()
                except socket.error:
                    sleep(3)
                except KeyboardInterrupt:
                    sys.exit()


        @Slot(str, str, str, str, result=str)
        def new_race(self, *args):
            self.socket.send('new_race("%s","%s","%s","%s")\n' % (args))

        @Slot()
        def swap(self):
            self.socket.send('swap\n')

        @Slot()
        def start_race(self):
            self.socket.send('start\n')

        @Slot()
        def abort(self):
            self.socket.send('abort\n')

        @Slot(str,int,int)
        def show_results(self, *args):
            try: self.socket.recv(4096)
            except socket.error: pass
            self.socket.send('show_results %s %s %s\n' % (args))
            results=''
            while 1:
                try: results+=self.socket.recv(4096)
                except socket.error: break
            results=results.splitlines()[1:-1]
            self.ctxt.setContextProperty('results', results)

        @Slot()
        def sponsors(self):
            self.socket.send("sponsors\n")

        @Slot()
        def init_bt(self):
            self.socket.send("init_bt\n")

        @Slot(str)
        def set_dist(self, *args):
            self.socket.send('set_dist("%s")\n' %(args))

    def __init__(self, host, port):
        self.host=host or self.host
        self.port=port or self.port

    def connect(self):
        self.cmd = self.Commands(self.host, self.port)
        self.cmd.start()

    def get_results(self):
        pass

    def show(self,qml_file):
        self.app=QApplication([])
        self.view=QDeclarativeView()
        self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
        self.view.setSource(QUrl(qml_file))
        self.ctxt = self.view.rootContext()
        self.cmd.ctxt = self.ctxt
        self.ctxt.setContextProperty("cmd", self.cmd)
        self.cmd.finish.connect(self.view.rootObject().finish)
        #self.ctxt.setContextProperty("dist", self.cmd.abort())

        self.view.show()
        self.app.exec_()
Example #31
0
class QtClient:
    host = "localhost"
    port = 9998
    ctxt = ''

    class Commands(QObject, Thread):
        finish = Signal()
        daemon = True

        def __init__(self, host, port):
            Thread.__init__(self)
            QObject.__init__(self)
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.connect((host, port))
            self.socket.settimeout(.5)
            self.setDaemon(True)

        def run(self):
            print 'running'
            while 1:
                try:
                    data = self.socket.recv(400)
                    if data:
                        print data
                    if data.startswith('finish'):
                        self.finish.emit()
                except socket.error:
                    sleep(3)
                except KeyboardInterrupt:
                    sys.exit()

        @Slot(str, str, str, str, result=str)
        def new_race(self, *args):
            self.socket.send('new_race("%s","%s","%s","%s")\n' % (args))

        @Slot()
        def swap(self):
            self.socket.send('swap\n')

        @Slot()
        def start_race(self):
            self.socket.send('start\n')

        @Slot()
        def abort(self):
            self.socket.send('abort\n')

        @Slot(str, int, int)
        def show_results(self, *args):
            try:
                self.socket.recv(4096)
            except socket.error:
                pass
            self.socket.send('show_results %s %s %s\n' % (args))
            results = ''
            while 1:
                try:
                    results += self.socket.recv(4096)
                except socket.error:
                    break
            results = results.splitlines()[1:-1]
            self.ctxt.setContextProperty('results', results)

        @Slot()
        def sponsors(self):
            self.socket.send("sponsors\n")

        @Slot()
        def init_bt(self):
            self.socket.send("init_bt\n")

        @Slot(str)
        def set_dist(self, *args):
            self.socket.send('set_dist("%s")\n' % (args))

    def __init__(self, host, port):
        self.host = host or self.host
        self.port = port or self.port

    def connect(self):
        self.cmd = self.Commands(self.host, self.port)
        self.cmd.start()

    def get_results(self):
        pass

    def show(self, qml_file):
        self.app = QApplication([])
        self.view = QDeclarativeView()
        self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
        self.view.setSource(QUrl(qml_file))
        self.ctxt = self.view.rootContext()
        self.cmd.ctxt = self.ctxt
        self.ctxt.setContextProperty("cmd", self.cmd)
        self.cmd.finish.connect(self.view.rootObject().finish)
        #self.ctxt.setContextProperty("dist", self.cmd.abort())

        self.view.show()
        self.app.exec_()
Example #32
0
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."

from PySide.QtCore import QUrl
from PySide.QtGui import QPushButton, QApplication
from PySide.QtDeclarative import QDeclarativeView

# This example uses a QML file to show a scrolling list containing
# all the items listed into dataList.

dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]

app = QApplication([])
view = QDeclarativeView()

ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)

url = QUrl('view.qml')

view.setSource(url)
view.show()

app.exec_()
Example #33
0
class MainWindow(QObject):
   
    ################################################
    # validations
    ################################################

    def validate_email(self, string):
        if len(string) > 7:
            if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", string) != None:
                return True
        return False

    def validate_fields(self):
        if self.curVars.user_name == '':
            self.rootO.show_alert("Empty name!", "Please type in your name.",False)
            return False
        if self.validate_email(self.curVars.email) == False:
            self.rootO.show_alert("Invalid email", "Please make sure the email address you typed is valid.",False)
            return False
        if len(self.curVars.password) < 6:
            self.rootO.show_alert("Bad password", "Password should contain at least 6 chars. Please try again.",False)
            return False
        elif self.curVars.password != self.curVars.password_confirm:
            self.rootO.show_alert("Passwords don't match", "Please make sure both passwords match!",False)
            return False
        return True

    ################################################
    # setting getting
    ################################################

    def prey_exists(self):
        if not os.path.exists(PREY_PATH + '/core'):
            self.rootO.show_alert("Prey not installed", "Couldn't find a Prey installation on this system. Sorry.", True)
        else:
            return True

    def is_config_writable(self):
        command = 'if [ ! -w "'+PREY_PATH+'/config" ]; then echo 1; fi'
        no_access = os.popen(command).read().strip()
        if no_access == '1':
            self.rootO.show_alert("Unauthorized", "You don't have access to manage Prey's configuration. Sorry.", True)
        else:
            return True

    def get_setting(self, var):
        command = 'grep \''+var+'=\' '+CONFIG_FILE+' | sed "s/'+var+'=\'\(.*\)\'/\\1/"'
        return os.popen(command).read().strip()

    def get_current_settings(self):

        #delay = os.popen("/opt/cron/bin/crontab -l | grep prey | cut -c 3-4").read()
        command = 'cat '+DAEMON_FILE+' | grep preyd | cut -d \' \' -f 3'
        self.curVars.delay = int(os.popen(command).read())
        #if not delay:
        #    self.curVars.delay = 30
        #else:
        #    self.curVars.delay = int(delay)

        self.curVars.auto_connect = self.get_setting('auto_connect')
        self.curVars.extended_headers = self.get_setting('extended_headers')

        self.curVars.lang = self.get_setting('lang')
        self.curVars.check_url = self.get_setting('check_url')
        self.curVars.post_method = self.get_setting('post_method')

        self.curVars.api_key = self.get_setting('api_key')
        self.curVars.device_key = self.get_setting('device_key')

        self.curVars.mail_to = self.get_setting('mail_to')
        self.curVars.smtp_server = self.get_setting('smtp_server')
        self.curVars.smtp_username = self.get_setting('smtp_username')

    def check_if_configured(self):
        if self.curVars.post_method == 'http' and self.curVars.api_key == '':
            return False
        else:
            return True

    ################################################
    # setting settings
    ################################################

    def save(self, param, value):
        if param == 'check_url': value = value.replace('/', '\/')
        command = 'sed -i -e "s/'+param+'=\'.*\'/'+param+'=\''+value+'\'/" '+ CONFIG_FILE
        os.system(command)

    @Slot(int)
    def apply_main_settings(self,delay):
        # save('lang', text('lang'))
        self.save('auto_connect', self.curVars.auto_connect)
        self.save('extended_headers', self.curVars.extended_headers)


        # check and change the crontab interval
        if delay != int(self.curVars.delay):
            # print 'Updating delay in crontab...'
            sub1 =  ' -e \'s/preyd '+str(self.curVars.delay)+'/preyd '+str(delay)+'/g\' '
            sub2 =  ' -e \'s/every '+str(self.curVars.delay)+'/every '+str(delay)+'/g\' '
            command = 'sed -i ' + sub1 + sub2 + DAEMON_FILE
            os.system('initctl stop apps/preyd')
            os.system(command)
            os.system('initctl start apps/preyd')
            #os.system('(/opt/cron/bin/crontab -l | tail -n+4 | grep -v prey; echo "*/'+str(delay)+' * * * * aegis-exec -s /opt/prey/prey.sh > /var/log/prey.log") | /opt/cron/bin/crontab -')

        if self.check_if_configured() == False:
            self.rootO.show_alert("All good.", "Configuration saved. Remember you still need to set up your posting method, otherwise Prey won't work!", True)
        else:
            self.rootO.show_alert("All good.", "Configuration saved!", True)

    @Slot()
    def create_new_user(self):
        if self.validate_fields():
            self.create_user()

    def apply_control_panel_settings(self):

        if self.curVars.post_method != 'http':
            self.save('post_method', 'http')

        if self.curVars.check_url != CONTROL_PANEL_URL:
            self.save('check_url', CONTROL_PANEL_URL)

        # we could eventually use the email as a checking method to remove prey
        # i.e. "under which email was this account set up?"
        # self.save('mail_to', self.email)
        self.save('api_key', self.curVars.api_key)

        if self.curVars.device_key != "":
            self.save('device_key', self.curVars.device_key)

    @Slot(str)
    def apply_standalone_settings(self,password):

        if self.curVars.post_method != 'email':
            self.save('post_method', 'email')

        self.save('check_url', self.curVars.check_url)
        self.save('mail_to', self.curVars.mail_to)
        self.save('smtp_server', self.curVars.smtp_server)
        self.save('smtp_username', self.curVars.smtp_username)

        #smtp_password = self.('smtp_password')

        if password != '':
            encoded_pass = os.popen('echo -n "'+ password +'" | openssl enc -base64').read().strip()
            self.save('smtp_password', encoded_pass)

        self.exit_configurator()

    def exit_configurator(self):
        self.run_prey()
        self.rootO.show_alert(_("Success"), _("Configuration saved! Your device is now setup and being tracked by Prey. Happy hunting!"), True)

    def run_prey(self):
        os.system(PREY_PATH + '/run ')

    ################################################
    # control panel api
    ################################################

    def report_connection_issue(self, result):
        print("Connection error. Response from server: " + result)
        self.rootO.show_alert("Problem connecting", "We seem to be having a problem connecting to the Prey Control Panel. This is likely a temporary issue. Please try again in a few moments.",False)

    def user_has_available_slots(self, string):
        matches = re.search(r"<available_slots>(\w*)</available_slots>", string)
        if matches and int(matches.groups()[0]) > 0:
            return True
        else:
            return False

    def get_api_key(self, string):
        matches = re.search(r"<key>(\w*)</key>", string)
        if matches:
            self.curVars.api_key = matches.groups()[0]

    @Slot(result=int)
    def create_device_list(self):
        self.deviceList = self.rootO.findChild(QObject,"deviceList")
        self.deviceList.clear()
        for device in self.deviceNames:
            self.deviceList.add(device)
        return self.chosen

    def get_device_keys(self, string, has_available_slots):
        hostname = os.popen("hostname").read().strip()
        index = -1
        self.deviceKeys = []
        self.deviceNames = []
        self.chosen = index
        matches = re.findall(r"<device>\s*<key>(\w*)</key>.*?<title>([\.\s\w]*)</title>\s*</device>", string, re.DOTALL)
        for match in matches:
            index += 1
            key = match[0]
            title = match[1]
            self.deviceKeys.append(key)
            self.deviceNames.append(title)
            if key == self.curVars.device_key:    #set the choice because we have a matching device key
                self.chosen = index
            elif title.lower() == hostname.lower and self.chosen < 0:    #set the choice because we likely have a matching title (but device key takes precedence)
                self.chosen = index
        if index < 0:
            self.rootO.show_alert("No devices exist", "There are no devices currently defined in your Control Panel.\n\nPlease select the option to create a new device.",False)
            return False
        if self.chosen < 0:
            self.chosen = 0

        return True

    def create_user(self):
        params = urllib.urlencode({'user[name]': self.curVars.user_name, 'user[email]': self.curVars.email, 'user[password]': self.curVars.password, 'user[password_confirmation]' : self.curVars.password_confirm})
        result = os.popen('curl -i -s -k --connect-timeout 10 '+ CONTROL_PANEL_URL_SSL + '/users.xml -d \"'+params+'\"').read().strip()

        if result.find("<key>") != -1:
            self.get_api_key(result)
            self.curVars.device_key = ""
        elif result.find("Email has already been taken") != -1:
            self.rootO.show_alert("Email has already been taken", "That email address already exists! If you signed up previously, please go back and select the Existing User option.",False)
            return
        else:
            self.rootO.show_alert("Couldn't create user!", "There was a problem creating your account. Please make sure the email address you entered is valid, as well as your password.",False)
            return

        self.apply_control_panel_settings()
        self.run_prey()
        self.rootO.show_alert("Account created!", "Your account has been succesfully created and configured in Prey's Control Panel.\n\nPlease check your inbox now, you should have received a verification email.", True)

    @Slot(bool, result=bool)
    def get_existing_user(self, show_devices):
        email = self.curVars.email
        password = self.curVars.password
        print email+' '+password
        result = os.popen('curl -i -s -k --connect-timeout 10 '+ CONTROL_PANEL_URL_SSL + '/profile.xml -u '+email+":'"+password+"'").read().strip()

        if result.find('401 Unauthorized') != -1:
            self.rootO.show_alert("User does not exist", "Couldn't log you in. Remember you need to activate your account opening the link we emailed you.\n\nIf you forgot your password please visit preyproject.com.",False)
            return False

        if result.find("<user>") != -1:
            self.get_api_key(result)
        else:
            self.report_connection_issue(result)
            return False

        has_available_slots = self.user_has_available_slots(result)
        if not has_available_slots and not show_devices:
            self.rootO.show_alert("Not allowed",  "It seems you've reached your limit for devices!\n\nIf you had previously added this PC, you should select the \"Device already exists\" option to select the device from a list of the ones you have already created.\n\nIf this is a new device, you can also upgrade to a Pro Account to increase your slot count and get access to additional features. For more information, please check\nhttp://preyproject.com/plans.",False)
            return False

        if show_devices:
            result = os.popen('curl -i -s -k --connect-timeout 10 '+ CONTROL_PANEL_URL_SSL + '/devices.xml -u '+email+":'"+password+"'").read().strip()
            if result.find("</devices>") != -1:
                return self.get_device_keys(result,has_available_slots)
            else:
                self.report_connection_issue(result)
                return False
        else:
            self.curVars.device_key = ""
            self.apply_control_panel_settings()
            self.exit_configurator()

    @Slot(int)
    def apply_device_settings(self,index):
        self.curVars.device_key = self.deviceKeys[index]
        self.apply_control_panel_settings()
        self.exit_configurator()




    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        # Create the Qt Application
        self.app = QApplication(["Prey-Config"])
        self.app.setWindowIcon(QIcon(''))
        self.view = QDeclarativeView()
        #self.setWindowTitle("Main Window")

        #get rootContext of QDeclarativeView
        self.context = self.view.rootContext()
        #make this class available to QML files as 'main' context
        self.context.setContextProperty('main', self)
        #create variables
        self.curVars = Vars()
        #make curVars available to QML files as 'vars' context
        self.context.setContextProperty('vars', self.curVars)
        # QML resizes to main window
        self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
        # Renders './qml/main.qml'
        self.view.setSource(QUrl.fromLocalFile('./qml/main.qml'))
        #get rootObject
        self.rootO = self.view.rootObject()

        #connect quit signal
        self.view.engine().quit.connect(self.quit_app)

        #check for prey installation, write acess to config file, and configurationstatus
        if self.prey_exists():
            if self.is_config_writable():
                self.get_current_settings()
                if self.check_if_configured() == False:
                    self.rootO.show_alert('Welcome!',"It seems this is the first time you run this setup. Please set up your reporting method now, otherwise Prey won't work!",False)
                    #os.system('(/opt/cron/bin/crontab -l | tail -n+4 | grep -v prey; echo "*/30 * * * * aegis-exec -s /opt/prey/prey.sh > /var/log/prey.log") | /opt/cron/bin/crontab -')

 
 
    def quit_app(self):
        self.view.hide()
        self.app.exit()
        self._elementData._new_element(element)

elementList = ElementList(element_datalist.get_sorted_element_list())
eelsEdgeList = EELSEdgeList()
edsLineList = EDSLineList()
elementName = ElementName()
elementData = ElementData(eelsEdgeList, edsLineList, elementName)
controller = Controller(elementData)

app = QtGui.QApplication(sys.argv)

view = QDeclarativeView()
view.setResizeMode(QDeclarativeView.SizeRootObjectToView)

rootObject = view.rootObject()
rootContext = view.rootContext()

rootContext.setContextProperty('elementList', elementList)
rootContext.setContextProperty('eelsEdgeList', eelsEdgeList)
rootContext.setContextProperty('edsLineList', edsLineList)
rootContext.setContextProperty('controller', controller)
rootContext.setContextProperty('elementName', elementName)


#"debugging" mode to run without the N9 specific QML
if options.desktop:
    if options.landscape:
        view.setSource(QtCore.QUrl('qml/Eels_edx_lookup_landscape.qml'))
    else:
        view.setSource(QtCore.QUrl('qml/Eels_edx_lookup.qml'))
    view.setGeometry(100, 100, 900, 540)
Example #35
0
    def _set_running(self, running):
        self._running = running
        self.on_running.emit()

    def _get_filename(self):
        return self._filename

    def _get_size(self):
        return self._size

    on_progress = Signal()
    on_running = Signal()
    on_filename = Signal()
    on_size = Signal()

    progress = Property(float, _get_progress, _set_progress, notify=on_progress)
    running = Property(bool, _get_running, _set_running, notify=on_running)
    filename = Property(str, _get_filename, notify=on_filename)
    size = Property(int, _get_size, notify=on_size)  # notify for QML


if __name__ == "__main__":
    d = Downloader("http://www.advancedidasia.com/pdf/Reader_PR-510.pdf")
    app = QApplication(sys.argv)
    view = QDeclarativeView()
    view.rootContext().setContextProperty("downloader", d)
    view.setSource(__file__.replace(".py", ".qml"))
    view.show()
    app.exec_()
Example #36
0
if __name__ == '__main__':
    QApplication.setGraphicsSystem("raster")
    app = QApplication(sys.argv)

    view = QDeclarativeView()
    engine = view.engine()
    engine.quit.connect(app.quit)

    if len(sys.argv) > 1:
        manager = DeviceManager(sys.argv[1])
    else:
        manager = DeviceManager()

    deviceListModel = DeviceListModel(manager)
    serviceListModel = ServiceListModel()
    deviceListModel.deviceSelected.connect(serviceListModel.loadDevice)

    view.rootContext().setContextProperty("deviceManager", manager)
    view.rootContext().setContextProperty("deviceListModel", deviceListModel)
    view.rootContext().setContextProperty("serviceListModel", serviceListModel)

    context = view.rootContext()

    view.setSource(QUrl('./qml/bluez.qml'))
    view.setMinimumSize(480, 800)
    view.show()

    manager.start()
    sys.exit(app.exec_())

class Application(QtGui.QDialog):
    __height = int(250)
    __width = int(200)

    __hostname = str('localhost')
    __portnumber = int(54321)

    ## the client socket
    __socket = QtNetwork.QTcpSocket()

    __seconds = int(0)

    __messages = int(0)

    __user = str("espen")

    def __init__(self, parent = None):
        super(Application, self).__init__(parent)

        self.handler = DocumentXmlHandler()

        ## Set values for the store/restore settings system
        QtCore.QCoreApplication.setOrganizationName("EMR")
        QtCore.QCoreApplication.setOrganizationDomain("code.rutger.no")
        QtCore.QCoreApplication.setApplicationName("QmlChatClient")

        ## create settings
        self.__settings = QtCore.QSettings()
        hostname = self.__settings.value("QmlChatClient/hostname")
        if hostname != None:
            self.__hostname = hostname
        portnumber = self.__settings.value("QmlChatClient/portnumber")
        if portnumber != None:
            self.__portnumber = portnumber

        ## Connect the socket's signals to our slots
        self.__socket.connected.connect(self.__socketConnected)
        self.__socket.disconnected.connect(self.__socketDisconnected)
        self.__socket.error.connect(self.__socketError)
        self.__socket.readyRead.connect(self.__readyRead)
        #self.__socket.stateChanged.connect(self.__socketStateChanged)

        userpassModel = UsernamePasswordModel()
        userpassModel.setHost(self.__hostname)
        userpassModel.setPort(int(self.__portnumber))

        userpassModel.connectSignal.connect(self.__connectToSystem)
        userpassModel.cancelSignal.connect(self.quitSlot)

        self.loginView = QDeclarativeView()
        self.loginView.rootContext().setContextProperty("model", userpassModel)
        self.loginView.setSource(QUrl('qml/client/LoginDialog.qml'))
        self.loginView.setResizeMode(QDeclarativeView.SizeRootObjectToView)

        self.loggedInModel = LoggedInModel()
        self.loggedInModel.disconnectSignal.connect(self.__disconnectFromHost)
        self.loggedInModel.setHeight(self.__height)
        self.loggedInModel.setWidth(self.__width)
        self.loggedInModel.sendMessageSignal.connect(self.__sendMessage)


        self.loggedInView = QDeclarativeView()
        self.loggedInView.rootContext().setContextProperty("model", self.loggedInModel)
        self.loggedInView.setSource(QUrl('qml/client/RunningDialog.qml'))
        self.loggedInView.setResizeMode(QDeclarativeView.SizeRootObjectToView)

        self.stackedWidget = QtGui.QStackedWidget()
        self.stackedWidget.addWidget(self.loginView)
        self.stackedWidget.addWidget(self.loggedInView)
        self.stackedWidget.setCurrentWidget(self.loginView)

        self.stackedWidget.setWindowTitle('Qml Chat Client')
        self.stackedWidget.setGeometry(300, 300, self.__width, self.__height)
        self.stackedWidget.show()


    def __connectToSystem(self, hostname, portnumber):
        self.__hostname = hostname
        self.__portnumber = portnumber
        #print "ConnectToSystem hostname", self.__hostname, "portnumber", self.__portnumber

       	## Try to connect to the server
        try:
            self.__socket.connectToHost(self.__hostname, int(self.__portnumber))
        except:
            text = 'Failed to connect to %s on port %d' % (self.__hostname, int(self.__portnumber))
            print text
            
            ## remove file created above
            #os.unlink(self.__loginWidget.logfileName())

    def quitSlot(self):
        print "quitSlot"
        exit()


    def __socketConnected(self):
        ## successfully logged in, write hostname and port number to settings
        self.__settings.setValue("ChatClient/hostname", self.__hostname)
        self.__settings.setValue("ChatClient/portnumber", self.__portnumber)

       	## Reset seconds and messages
        self.__seconds = 0
        self.__messages = 0

        ## Start timer that displays seconds and number of messages
        #self.__timer.start(1000)

        self.stackedWidget.setCurrentWidget(self.loggedInView)


    def __disconnectFromHost(self):
        ## Disconnect from server
        self.__socket.disconnectFromHost()


    def __socketDisconnected(self):
        ## we,re disconnected, stop the timer
        #self.__timer.stop()

       	## Create new file name - it will be displayed when current widget beocmes loginWidget in the next statement
        #self.__loginWidget.createFilename()

        ## Set login widget as current widget
        self.stackedWidget.setCurrentWidget(self.loginView)

        ## Clear dialog text
        self.loggedInModel.clear()


    ## Send the message
    def __sendMessage(self, text):
        print "sendMessage", text
        message = str('<chat><content user=\"%s\" type=\"message\"></content><message message=\"%s\"></message></chat>' % (self.__user, text))
        self.__socket.write(message)


    ## Data is ready for reading
    def __readyRead(self):
        ## Read the size of data available, return if no data
        size = self.__socket.bytesAvailable()
        if size == 0:
            return

       	## Read data
        data = str(self.__socket.read(size))

        ## Initialize xml reader
        reader = QtXml.QXmlSimpleReader()
        reader.setContentHandler(self.handler)
        reader.setErrorHandler(self.handler)

        ## xml input source
        xmlInputSource = QtXml.QXmlInputSource()
        xmlInputSource.setData(data)

        print 'DEBUG DATA', xmlInputSource.data()

        ## Parse xml file
        if reader.parse(xmlInputSource) == False:
            print "Pars xml error:", self.handler.errorString()
            return False

        ## skip empty strings
        if self.handler.message == "" or self.handler.message == '\n' or self.handler.message == '\l\c':
            print 'Empty string'
            return

        if self.handler.user == self.__user:
            data = str("%s: %s" % ("me", self.handler.message))
        else:
            data = str("%s: %s" % (self.handler.user, self.handler.message))

        #print "__readyRead:", data
        self.loggedInModel.setText(str(data))
        self.loggedInModel.onTextChanged.emit(str(data))

       	## Emit the write message signal
        #self.__writeMessageSignal.emit(data)

       	## Count the message
        self.__messages += 1



    ## The state of the socket has changed
    def __socketStateChanged(self, state):
       	print "MainWidget::socketStateChanged state", str(state)


    ## Manage socket errors
    def __socketError(self, error):
        QtGui.QMessageBox.critical(self, "Chat Client", "Socket Error: %s" % self.__socket.errorString())
        return