Ejemplo n.º 1
0
	def __init__(self, parent=None):
		super(IPHelper, self).__init__(parent)
		f = QFile(os.path.join(os.path.split(__file__)[0], 'iphelper.ui'))
		loadUi(f, self)
		f.close()
		self.ipAddress = None
		
		# create validators
		validator = QRegExpValidator(QRegExp('\d{,3}'))
		self.uiFirstTetTXT.setValidator(validator)
		self.uiSecondTetTXT.setValidator(validator)
		self.uiThirdTetTXT.setValidator(validator)
		self.uiFourthTetTXT.setValidator(validator)
		
		# build a map of the buttons
		self.buttons = [None]*16
		self.signalMapper = QSignalMapper(self)
		self.signalMapper.mapped.connect(self.tetMap)
		for button in self.findChildren(QPushButton):
			match = re.findall(r'^uiTrellis(\d{,2})BTN$', button.objectName())
			if match:
				i = int(match[0])
				self.buttons[i] = button
				if i >= 12:
					self.signalMapper.setMapping(button, i)
					button.clicked.connect(self.signalMapper.map)
		self.tetMap(12)
 def findOrSaveConfig(self):
     infile = QFile('ui/config_path.ui')
     infile.open(QFile.ReadOnly)
     loader = QUiLoader()
     dialog = loader.load(infile, self.window)
     infile.close()
     
     def browse():
         path = QFileDialog.getSaveFileName(dialog, u"Choose or create a configuration file", dialog.pathBox.text())[0]
         if path != '':
             dialog.pathBox.setText(path)
     
     def cancel():
         dialog.hide()
     
     def ok():
         autodetectPort = dialog.autodetect.checkState() == Qt.Checked
         configPath = os.path.expanduser(dialog.pathBox.text())
         dialog.hide()
         self.start(configPath, autodetectPort)
     
     dialog.show()
     dialog.pathBox.setText(os.path.expanduser('~/.config/tangelo/tangelo.conf'))
     
     dialog.browseButton.clicked.connect(browse)
     dialog.cancelButton.clicked.connect(cancel)
     dialog.okButton.clicked.connect(ok)
Ejemplo n.º 3
0
 def __init__(self):
     self.loader = QUiLoader()
     infile = QFile("resources/loading.ui")
     infile.open(QFile.ReadOnly)
     self.window = self.loader.load(infile, None)
     infile.close()
     
     self.overrides = {'personID':self.window.personID,
                      'paID':self.window.paID,
                      'maID':self.window.maID,
                      'sex':self.window.sex,
                      'affected':self.window.affected,
                      'n_local_aff':self.window.n_local_aff,
                      'n_local_desc':self.window.n_local_desc,
                      'nicki_d':self.window.nicki_d,
                      'is_root':self.window.is_root,
                      'is_leaf':self.window.is_leaf,
                      'generation':self.window.generation}
     self.requiredForCalculateD = set(['personID','paID','maID','sex','affected'])
     self.header = []
     self.lowerHeader = []
     
     self.window.browseInputButton.clicked.connect(self.browseInput)
     self.window.inputField.textChanged.connect(self.switchPrograms)
     self.window.browseOutputButton.clicked.connect(self.browseOutput)
     self.window.outputField.textChanged.connect(self.switchPrograms)
     self.window.programBox.currentIndexChanged.connect(self.switchPrograms)
     self.window.runButton.clicked.connect(self.go)
     
     self.switchPrograms()
     self.window.buttonBox.setEnabled(False)
     
     self.window.show()
Ejemplo n.º 4
0
def loadDialog(file_name):
        loader = QUiLoader()
        the_file = QFile(file_name)
        the_file.open(QFile.ReadOnly)
        ret_val = loader.load(the_file)
        the_file.close()
        return ret_val
Ejemplo n.º 5
0
    def setUp(self):
        #Set up the needed resources - A temp file and a QFile
        self.called = False
        handle, self.filename = mkstemp()
        os.close(handle)

        self.qfile = QFile(self.filename)
Ejemplo n.º 6
0
def getContent(path):
    file = QFile(path)
    if not file.open(QIODevice.ReadOnly | QIODevice.Text):
        return
    ts = QTextStream(file)
    ts.setCodec("UTF-8")
    res = ts.readAll()
    return res
Ejemplo n.º 7
0
def _write_doc_to_path(doc, path):
    # write QDomDocument to path as HROX
    hrox_file = QFile(path)
    if not hrox_file.open(QFile.WriteOnly):
        raise RuntimeError("Failed to open file for writing")
    stream = QTextStream(hrox_file)
    doc.save(stream, 1)
    hrox_file.close()
Ejemplo n.º 8
0
def loadWindowFromFile(file_name):
    '''Load the window definition from the resource ui file'''
    loader = QUiLoader()
    ui_file = QFile(file_name)
    ui_file.open(QFile.ReadOnly)
    the_window = loader.load(ui_file)
    ui_file.close()
    return the_window
Ejemplo n.º 9
0
def _read_doc_from_path(path):
    # reading QDomDocument from HROX path
    hrox_file = QFile(path)
    if not hrox_file.open(QFile.ReadOnly):
        raise RuntimeError("Failed to open file for reading")
    doc = QDomDocument()
    doc.setContent(hrox_file)
    hrox_file.close()
    return doc
Ejemplo n.º 10
0
 def loadHyperlinkDialog(self):
     ''' Load dialog from ui file for defining hyperlink '''
     loader = QUiLoader()
     ui_file = QFile(':/hyperlink.ui')  # UI_DIALOG_FILE)
     ui_file.open(QFile.ReadOnly)
     self.hyperlink_dialog = loader.load(ui_file)
     ui_file.close()
     self.hyperlink_dialog.accepted.connect(self.hyperlinkChanged)
     self.hlink_field = self.hyperlink_dialog.findChild(QLineEdit, 'hlink')
Ejemplo n.º 11
0
    def download_file(self, path, setting):
        version_file = self.settings['base_url'].format(
            self.selected_version())

        location = self.get_setting('download_dir').value

        versions = re.findall('v(\d+)\.(\d+)\.(\d+)', path)[0]

        minor = int(versions[1])
        if minor >= 12:
            path = path.replace('node-webkit', 'nwjs')

        self.progress_text = 'Downloading {}'.format(
            path.replace(version_file, ''))

        url = QUrl(path)
        file_name = setting.save_file_path(self.selected_version(), location)

        archive_exists = QFile.exists(file_name)

        #dest_files_exist = False

        # for dest_file in setting.dest_files:
        #    dest_file_path = os.path.join('files', setting.name, dest_file)
        #    dest_files_exist &= QFile.exists(dest_file_path)

        forced = self.get_setting('force_download').value

        if archive_exists and not forced:
            self.continue_downloading_or_extract()
            return

        self.out_file = QFile(file_name)
        if not self.out_file.open(QIODevice.WriteOnly):
            error = self.out_file.error().name
            self.show_error('Unable to save the file {}: {}.'.format(
                file_name, error))
            self.out_file = None
            self.enable_ui()
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.http_request_aborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        # Download the file.
        self.http_get_id = self.http.get(path, self.out_file)
Ejemplo n.º 12
0
class LogFilePositionSource(QGeoPositionInfoSource):
    def __init__(self, parent):
        QGeoPositionInfoSource.__init__(self, parent)
        self.logFile = QFile(self)
        self.timer = QTimer(self)

        self.timer.timeout.connect(self.readNextPosition)

        self.logFile.setFileName(translate_filename('simplelog.txt'))
        assert self.logFile.open(QIODevice.ReadOnly)

        self.lastPosition = QGeoPositionInfo()

    def lastKnownPosition(self, fromSatellitePositioningMethodsOnly):
        return self.lastPosition

    def minimumUpdateInterval(self):
        return 100

    def startUpdates(self):
        interval = self.updateInterval()

        if interval < self.minimumUpdateInterval():
            interval = self.minimumUpdateInterval()

        self.timer.start(interval)

    def stopUpdates(self):
        self.timer.stop()

    def requestUpdate(self, timeout):
        # For simplicity, ignore timeout - assume that if data is not available
        # now, no data will be added to the file later
        if (self.logFile.canReadLine()):
            self.readNextPosition()
        else:
            self.updateTimeout.emit()

    def readNextPosition(self):
        line = self.logFile.readLine().trimmed()

        if not line.isEmpty():
            data = line.split(' ')
            hasLatitude = True
            hasLongitude = True
            timestamp = QDateTime.fromString(str(data[0]), Qt.ISODate)
            latitude = float(data[1])
            longitude = float(data[2])
            if timestamp.isValid():
                coordinate = QGeoCoordinate(latitude, longitude)
                info = QGeoPositionInfo(coordinate, timestamp)
                if info.isValid():
                    self.lastPosition = info
                    # Currently segfaulting. See Bug 657
                    # http://bugs.openbossa.org/show_bug.cgi?id=657
                    self.positionUpdated.emit(info)
Ejemplo n.º 13
0
class LogFilePositionSource(QGeoPositionInfoSource):
    def __init__(self, parent):
        QGeoPositionInfoSource.__init__(self, parent)
        self.logFile = QFile(self)
        self.timer = QTimer(self)

        self.timer.timeout.connect(self.readNextPosition)

        self.logFile.setFileName(translate_filename('simplelog.txt'))
        assert self.logFile.open(QIODevice.ReadOnly)

        self.lastPosition = QGeoPositionInfo()

    def lastKnownPosition(self, fromSatellitePositioningMethodsOnly):
        return self.lastPosition

    def minimumUpdateInterval(self):
        return 100

    def startUpdates(self):
        interval = self.updateInterval()

        if interval < self.minimumUpdateInterval():
            interval = self.minimumUpdateInterval()

        self.timer.start(interval)

    def stopUpdates(self):
        self.timer.stop()

    def requestUpdate(self, timeout):
        # For simplicity, ignore timeout - assume that if data is not available
        # now, no data will be added to the file later
        if (self.logFile.canReadLine()):
            self.readNextPosition()
        else:
            self.updateTimeout.emit()

    def readNextPosition(self):
        line = self.logFile.readLine().trimmed()

        if not line.isEmpty():
            data = line.split(' ')
            hasLatitude = True
            hasLongitude = True
            timestamp = QDateTime.fromString(str(data[0]), Qt.ISODate)
            latitude = float(data[1])
            longitude = float(data[2])
            if timestamp.isValid():
                coordinate = QGeoCoordinate(latitude, longitude)
                info = QGeoPositionInfo(coordinate, timestamp)
                if info.isValid():
                    self.lastPosition = info
                    # Currently segfaulting. See Bug 657
                    # http://bugs.openbossa.org/show_bug.cgi?id=657
                    self.positionUpdated.emit(info)
Ejemplo n.º 14
0
    def __load_ui(self):
        ui_path = os.path.dirname(__file__)
        ui_path = os.path.join(ui_path, "MainWindow.ui")
        ui_file = QFile(ui_path)
        ui_file.open(QFile.ReadOnly)
        ui_loader = QtUiTools.QUiLoader()
        self.__ui = ui_loader.load(ui_file, None)
        ui_file.close()

        self.__ui.answerTableWidget.setHorizontalHeaderLabels([self.tr("Question"), self.tr("Answer")])
Ejemplo n.º 15
0
    def testBug909(self):
        fileName = QFile(adjust_filename('bug_909.ui', __file__))
        loader = QUiLoader()
        main_win = loader.load(fileName)
        self.assertEqual(sys.getrefcount(main_win), 2)
        fileName.close()

        tw = QTabWidget(main_win)
        main_win.setCentralWidget(tw)
        main_win.show()
Ejemplo n.º 16
0
 def createWidget(self):
     # Override the existing widget
     # TODO: Do I need to delete anything explicitly?
     infile = QFile('ui/process_widget.ui')
     infile.open(QFile.ReadOnly)
     loader = QUiLoader()
     self.widget = loader.load(infile, Globals.mainWindow.window)
     infile.close()
     
     self.updateWidget(True)
Ejemplo n.º 17
0
    def testBug909(self):
        fileName = QFile(adjust_filename('bug_909.ui', __file__))
        loader = QUiLoader()
        main_win = loader.load(fileName)
        self.assertEqual(sys.getrefcount(main_win), 2)
        fileName.close()

        tw = QTabWidget(main_win)
        main_win.setCentralWidget(tw)
        main_win.show()
Ejemplo n.º 18
0
def main():
    pid_file = 'av-control.pid'
    fp = open(pid_file, 'w')
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        # another instance is running
        print "av-control is already running."
        sys.exit(1)

    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
                        level=logging.INFO)
    app = QApplication(sys.argv)

    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--fullscreen",
                        help="Run in fullscreen mode and hide the mouse cursor",
                        action="store_true")
    parser.add_argument("-c",
                        help="Specify the controller ID to connect to",
                        metavar="CONTROLLERID",
                        default="")
    args = parser.parse_args()

    try:
        ssf = QFile(":/stylesheet")
        ssf.open(QFile.ReadOnly)
        styleSheet = str(ssf.readAll())
        app.setStyleSheet(styleSheet)
    except IOError:
        # never mind
        logging.warn("Cannot find stylesheet, using default system styles.")

    try:
        controller = Controller.fromPyro(args.c)

        myapp = MainWindow(controller)

        client = AvControlClient(myapp)
        client.setDaemon(True)
        client.start()
        client.started.wait()
        atexit.register(lambda: controller.unregisterClient(client.uri))

        controller.registerClient(client.uri)

        if args.fullscreen:
            QApplication.setOverrideCursor(Qt.BlankCursor)
            myapp.showFullScreen()
        else:
            myapp.show()
        sys.exit(app.exec_())

    except VersionMismatchError as e:
        Dialogs.errorBox(str(e))
Ejemplo n.º 19
0
    def readModel(self,fileName):
	file = QFile(fileName)
	if (file.open(QIODevice.ReadOnly | QIODevice.Text)):
            xmlReader = QXmlSimpleReader()
            xmlReader.setContentHandler(self)
            xmlReader.setErrorHandler(self)
            xmlSource = QXmlInputSource(file)
            xmlReader.parse(xmlSource)
            return self.modelData
        else:
            return  None
Ejemplo n.º 20
0
    def download_file(self, path, setting):
        version_file = self.settings['base_url'].format(self.selected_version())

        location = self.get_setting('download_dir').value

        versions = re.findall('v(\d+)\.(\d+)\.(\d+)', path)[0]

        minor = int(versions[1])
        if minor >= 12:
            path = path.replace('node-webkit', 'nwjs')

        self.progress_text = 'Downloading {}'.format(path.replace(version_file, ''))

        url = QUrl(path)
        file_name = setting.save_file_path(self.selected_version(), location)

        archive_exists = QFile.exists(file_name)

        #dest_files_exist = False

        # for dest_file in setting.dest_files:
        #    dest_file_path = os.path.join('files', setting.name, dest_file)
        #    dest_files_exist &= QFile.exists(dest_file_path)

        forced = self.get_setting('force_download').value

        if archive_exists and not forced:
            self.continue_downloading_or_extract()
            return

        self.out_file = QFile(file_name)
        if not self.out_file.open(QIODevice.WriteOnly):
            error = self.out_file.error().name
            self.show_error('Unable to save the file {}: {}.'.format(file_name,
                                                                     error))
            self.out_file = None
            self.enable_ui()
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.http_request_aborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        # Download the file.
        self.http_get_id = self.http.get(path, self.out_file)
Ejemplo n.º 21
0
    def __init__(self, parent):
        QGeoPositionInfoSource.__init__(self, parent)
        self.logFile = QFile(self)
        self.timer = QTimer(self)

        self.timer.timeout.connect(self.readNextPosition)

        self.logFile.setFileName(translate_filename('simplelog.txt'))
        assert self.logFile.open(QIODevice.ReadOnly)

        self.lastPosition = QGeoPositionInfo()
Ejemplo n.º 22
0
 def findTangelo():
     infile = QFile('ui/find_tangelo.ui')
     infile.open(QFile.ReadOnly)
     loader = QUiLoader()
     dialog = loader.load(infile, None)
     infile.close()
     
     if sys.platform.startswith('win'):
         Globals.pythonPath = subprocess.Popen(['where', 'python'], stdout=subprocess.PIPE).communicate()[0].strip()
         Globals.tangeloPath = subprocess.Popen(['where', 'tangelo'], stdout=subprocess.PIPE).communicate()[0].strip()
     else:
         Globals.pythonPath = subprocess.Popen(['which', 'python'], stdout=subprocess.PIPE).communicate()[0].strip()
         Globals.tangeloPath = subprocess.Popen(['which', 'tangelo'], stdout=subprocess.PIPE).communicate()[0].strip()
     
     if os.path.exists(Globals.pythonPath):
         dialog.pythonPathBox.setText(Globals.pythonPath)
     if os.path.exists(Globals.tangeloPath):
         dialog.tangeloPathBox.setText(Globals.tangeloPath)
     
     def pythonBrowse():
         path = QFileDialog.getOpenFileName(dialog, u"Find python", dialog.pythonPathBox.text())[0]
         if path != '':
             dialog.pythonPathBox.setText(path)
     
     def tangeloBrowse():
         path = QFileDialog.getOpenFileName(dialog, u"Find tangelo", dialog.tangeloPathBox.text())[0]
         if path != '':
             dialog.tangeloPathBox.setText(path)
     
     def cancel():
         dialog.hide()
         sys.exit()
     
     def ok():
         Globals.pythonPath = os.path.expanduser(dialog.pythonPathBox.text())
         Globals.tangeloPath = os.path.expanduser(dialog.tangeloPathBox.text())
         
         if not os.path.exists(Globals.pythonPath):
             Globals.criticalError("Sorry, that python interpreter doesn't exist.")
             return
         if not os.path.exists(Globals.tangeloPath):
             Globals.criticalError("Sorry, that tangelo executable doesn't exist.")
             return
         
         Globals.mainWindow = Overview()
         Globals.mainWindow.refresh()
         dialog.hide()
     dialog.show()
     
     dialog.tangeloBrowse.clicked.connect(tangeloBrowse)
     dialog.pythonBrowse.clicked.connect(pythonBrowse)
     dialog.cancelButton.clicked.connect(cancel)
     dialog.okButton.clicked.connect(ok)
Ejemplo n.º 23
0
class TestQFileSignalBlocking(unittest.TestCase):
    '''Test case for blocking the signal QIODevice.aboutToClose()'''
    def setUp(self):
        #Set up the needed resources - A temp file and a QFile
        self.called = False
        handle, self.filename = mkstemp()
        os.close(handle)

        self.qfile = QFile(self.filename)

    def tearDown(self):
        #Release acquired resources
        os.remove(self.filename)
        del self.qfile

    def callback(self):
        #Default callback
        self.called = True

    def testAboutToCloseBlocking(self):
        #QIODevice.aboutToClose() blocking

        QObject.connect(self.qfile, SIGNAL('aboutToClose()'), self.callback)

        self.assert_(self.qfile.open(QFile.ReadOnly))
        self.qfile.close()
        self.assert_(self.called)

        self.called = False
        self.qfile.blockSignals(True)

        self.assert_(self.qfile.open(QFile.ReadOnly))
        self.qfile.close()
        self.assert_(not self.called)
Ejemplo n.º 24
0
class TestQFileSignalBlocking(unittest.TestCase):
    '''Test case for blocking the signal QIODevice.aboutToClose()'''

    def setUp(self):
        #Set up the needed resources - A temp file and a QFile
        self.called = False
        handle, self.filename = mkstemp()
        os.close(handle)

        self.qfile = QFile(self.filename)

    def tearDown(self):
        #Release acquired resources
        os.remove(self.filename)
        del self.qfile

    def callback(self):
        #Default callback
        self.called = True

    def testAboutToCloseBlocking(self):
        #QIODevice.aboutToClose() blocking

        QObject.connect(self.qfile, SIGNAL('aboutToClose()'), self.callback)

        self.assert_(self.qfile.open(QFile.ReadOnly))
        self.qfile.close()
        self.assert_(self.called)

        self.called = False
        self.qfile.blockSignals(True)

        self.assert_(self.qfile.open(QFile.ReadOnly))
        self.qfile.close()
        self.assert_(not self.called)
Ejemplo n.º 25
0
 def testBasic(self):
     '''QFile.getChar'''
     obj = QFile(self.filename)
     obj.open(QIODevice.ReadOnly)
     self.assertEqual(obj.getChar(), (True, 'a'))
     self.assertFalse(obj.getChar()[0])
     obj.close()
Ejemplo n.º 26
0
 def __init__(self, notifyRun):
     loader = QUiLoader()
     infile = QFile("gui/ui/compreheNGSive_setup.ui")
     infile.open(QFile.ReadOnly)
     self.window = loader.load(infile, None)
     self.notifyRun = notifyRun
     
     self.cvfFile = None
     
     self.window.quitButton.clicked.connect(self.closeApp)
     self.window.runButton.clicked.connect(self.run)
     self.window.browseButton.clicked.connect(self.browseCvf)
     self.window.addButton.clicked.connect(self.browseFeature)
     self.window.removeButton.clicked.connect(self.removeFeature)
             
     self.window.show()
Ejemplo n.º 27
0
    def updateFileMenu(self):
        """
        Updates the file menu dynamically, so that recent files can be shown.
        """
        self.menuFile.clear()
        #        self.menuFile.addAction(self.actionNew)    # disable for now
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSave_as)
        self.menuFile.addAction(self.actionClose_Model)

        recentFiles = []
        for filename in self.recentFiles:
            if QFile.exists(filename):
                recentFiles.append(filename)

        if len(self.recentFiles) > 0:
            self.menuFile.addSeparator()
            for i, filename in enumerate(recentFiles):
                action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self)
                action.setData(filename)
                action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName())
                action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1 + i)))
                action.triggered.connect(self.load_model)
                self.menuFile.addAction(action)

        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
Ejemplo n.º 28
0
    def __init__(self, parent=None):
        super(Update_Window, self).__init__(parent)

        self.getPath_update = os.path.abspath(os.path.join('gui', 'pp_update.ui'))

        try:
            self.ui_pp_update = QUiLoader()
            self.file = QFile(self.getPath_search_ui, self)
            self.file.open(QFile.ReadOnly)
            self.myWidget = self.ui_pp_update.load(file, self)
            self.file.close()
            print "STATUS [OK]  ", FILE_NAME, ": GUI is loaded from PySide"
        except:
            self.ui_pp_update = loadUi(self.getPath_update, self)
            print "STATUS [OK]  ", FILE_NAME, ": GUI is loaded from PyQt4"

        self.ui_pp_update.setWindowModality(Qt.ApplicationModal)


        # Set data for download and saving in path
        self.location = os.path.abspath(os.path.join('temp', 'example-app-0.3.win32.zip'))
        self.url = 'http://sophus.bplaced.net/download/example-app-0.3.win32.zip'

        self.download_task = Download_Thread(self.location, self.url)
        self.download_task.notify_progress.connect(self.on_progress)
        self.download_task.finished_thread.connect(self.on_finished)
        self.download_task.error_http.connect(self.on_HTTPError)
        self.download_task.finished_download.connect(self.on_finish_download)

        self.ui_pp_update.pushButtonUpdate.setEnabled(True)
        self.create_actions_buttons()
Ejemplo n.º 29
0
 def testDevice(self):
     '''QTextStream get/set Device'''
     device = QFile()
     self.obj.setDevice(device)
     self.assertEqual(device, self.obj.device())
     self.obj.setDevice(None)
     self.assertEqual(None, self.obj.device())
Ejemplo n.º 30
0
    def setUp(self):
        #Set up the needed resources - A temp file and a QFile
        self.called = False
        handle, self.filename = mkstemp()
        os.close(handle)

        self.qfile = QFile(self.filename)
Ejemplo n.º 31
0
def install_certificates():
    ssl_config = QSslConfiguration.defaultConfiguration()
    ssl_config.setProtocol(QSsl.SecureProtocols)

    certs = ssl_config.caCertificates()

    for cert_filename in os.listdir(make_abs_path('certs')):
        if os.path.splitext(cert_filename)[1] == '.pem':
            cert_filepath = make_abs_path('certs', cert_filename)
            cert_file = QFile(cert_filepath)
            cert_file.open(QIODevice.ReadOnly)
            cert = QSslCertificate(cert_file)
            certs.append(cert)

    ssl_config.setCaCertificates(certs)
    QSslConfiguration.setDefaultConfiguration(ssl_config)
Ejemplo n.º 32
0
    def updateFileMenu(self):
        """
        Updates the file menu dynamically, so that recent files can be shown.
        """
        self.menuFile.clear()
#        self.menuFile.addAction(self.actionNew)    # disable for now
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSave_as)
        self.menuFile.addAction(self.actionClose_Model)

        recentFiles = []
        for filename in self.recentFiles:
            if QFile.exists(filename):
                recentFiles.append(filename)

        if len(self.recentFiles) > 0:
            self.menuFile.addSeparator()
            for i, filename in enumerate(recentFiles):
                action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self)
                action.setData(filename)
                action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName())
                action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1+i)))
                action.triggered.connect(self.load_model)
                #self.connect(action, SIGNAL("triggered()"), self.load_model)
                self.menuFile.addAction(action)

        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
Ejemplo n.º 33
0
 def createManager(self):
     if self.manager != None:
         self.updateManager()
         self.manager.show()
     else:
         # Create the window
         infile = QFile('ui/process_manager.ui')
         infile.open(QFile.ReadOnly)
         loader = QUiLoader()
         #TODO: This isn't working:
         loader.registerCustomWidget(ManagerHelper)
         self.manager = loader.load(infile, Globals.mainWindow.window)
         infile.close()
         
         self.updateManager(True)
         self.manager.show()
Ejemplo n.º 34
0
 def __init__(self, vData, fData, intMan, startingXattribute, startingYattribute):
     loader = QUiLoader()
     infile = QFile("gui/ui/compreheNGSive.ui")
     infile.open(QFile.ReadOnly)
     self.window = loader.load(infile, None)
     
     self.resolution_threshold = 1000
     
     self.vData = vData
     self.fData = fData
     self.intMan = intMan
     
     self.currentXattribute = startingXattribute
     self.currentYattribute = startingYattribute
     
     self.window.resolutionSpinBox.setMinimum(10)
     self.window.resolutionSpinBox.setMaximum(len(self.vData.data))
     self.window.resolutionSpinBox.setValue(self.resolution_threshold)
     self.window.resolutionSpinBox.valueChanged.connect(self.changeResolution)
     
     self.window.refreshButton.clicked.connect(self.refreshResolution)
     
     self.window.actionQuit.triggered.connect(self.window.close)
     self.window.actionExport_History.triggered.connect(self.exportHistory)
     self.window.actionExport.triggered.connect(self.exportActivePoints)
     
     self.window.actionUndo.triggered.connect(self.intMan.undo)
     self.window.actionRedo.triggered.connect(self.intMan.redo)
     
     # TODO
     
     #self.window.actionNew.triggered.connect(self.startNewSelection)
     #self.window.actionDuplicate.triggered.connect(self.duplicateActiveSelection)
     #self.window.actionDelete.triggered.connect(self.deleteActiveSelection)
     
     #self.window.actionUnion.triggered.connect(self.intMan.newOperation(operation.SELECTION_UNION,))
     #self.window.actionIntersection.triggered.connect(self.intMan.newOperation(operation.SELECTION_UNION,))
     #self.window.actionDifference.triggered.connect(self.intMan.newOperation(operation.SELECTION_UNION,))
     #self.window.actionComplement.triggered.connect(self.intMan.newOperation(operation.SELECTION_UNION,))
     
     self.pc = parallelCoordinateWidget(vData=vData,app=self,parent=self.window.pcScrollArea)
     self.window.pcScrollArea.setWidget(self.pc)
     
     self.scatter = scatterplotWidget(vData=vData,app=self,parent=self.window.scatterWidget)
     
     #self.window.showMaximized()
     self.window.show()
Ejemplo n.º 35
0
 def __init__(self):
     # Load UI files
     infile = QFile("ui/overview.ui")
     infile.open(QFile.ReadOnly)
     loader = QUiLoader()
     #TODO: this isn't working:
     loader.registerCustomWidget(MainHelper)
     self.window = loader.load(infile, None)
     infile.close()
     
     self.processes = {}
     self.deadProcesses = {}
     
     # Events
     self.window.refreshButton.clicked.connect(self.refresh)
     self.window.startButton.clicked.connect(self.findOrSaveConfig)
     self.window.show()
Ejemplo n.º 36
0
    def downloadFile(self, path, setting):
        self.progress_text = 'Downloading {}'.format(path.replace(self.base_url.format(self.selected_version()),''))

        location = self.getSetting('download_dir').value

        url = QUrl(path)
        fileInfo = QFileInfo(url.path())
        fileName = setting.save_file_path(self.selected_version(), location)

        archive_exists = QFile.exists(fileName)

        dest_files_exist = False

        #for dest_file in setting.dest_files:
        #    dest_file_path = os.path.join('files', setting.name, dest_file)
        #    dest_files_exist &= QFile.exists(dest_file_path)

        forced = self.getSetting('force_download').value

        if (archive_exists or dest_files_exist) and not forced:
            self.continueDownloadingOrExtract()
            return #QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            self.show_error('Unable to save the file {}: {}.'.format(fileName, self.outFile.errorString()))
            self.outFile = None
            self.enableUI()
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.httpRequestAborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        # Download the file.
        self.httpGetId = self.http.get(path, self.outFile)
Ejemplo n.º 37
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    app = QApplication(argv)
    engine = QScriptEngine()

    if HAS_DEBUGGER:
        debugger = QScriptEngineDebugger()
        debugger.attachTo(engine)
        debugWindow = debugger.standardWindow()
        debugWindow.resize(1024, 640)

    scriptFileName = './calculator.js'
    scriptFile = QFile(scriptFileName)
    scriptFile.open(QIODevice.ReadOnly)
    engine.evaluate(unicode(scriptFile.readAll()), scriptFileName)
    scriptFile.close()

    loader = QUiLoader()
    ui = loader.load(':/calculator.ui')

    ctor = engine.evaluate('Calculator')
    scriptUi = engine.newQObject(ui, QScriptEngine.ScriptOwnership)
    calc = ctor.construct([scriptUi])

    if HAS_DEBUGGER:
        display = ui.findChild(QLineEdit, 'display')
        display.connect(display, SIGNAL('returnPressed()'), debugWindow,
                        SLOT('show()'))

    ui.show()
    return app.exec_()
Ejemplo n.º 38
0
 def testBasic(self):
     '''QFile.getChar'''
     obj = QFile(self.filename)
     obj.open(QIODevice.ReadOnly)
     self.assertEqual(obj.getChar(), (True, 'a'))
     self.assertFalse(obj.getChar()[0])
     obj.close()
Ejemplo n.º 39
0
 def testBug721(self):
     obj = QFile(self.filename)
     obj.open(QIODevice.ReadOnly)
     memory = obj.map(0, 1)
     self.assertEqual(len(memory), 1)
     self.assertEqual(memory[0], py3k.b('a'))
     obj.unmap(memory)
Ejemplo n.º 40
0
 def get_file_name(self, url):
     path = url.path()
     basename = QFileInfo(path).fileName()
     if not basename:
         basename = "download"
     if QFile.exists(basename):
         print "aaaaaaaaaaaaaaaah"
         return
     return basename
Ejemplo n.º 41
0
 def get_file_name(self, url):
     path = url.path()
     basename = QFileInfo(path).fileName()
     if not basename:
         basename = "download"
     if QFile.exists(basename):
         print "aaaaaaaaaaaaaaaah"
         return
     return basename
Ejemplo n.º 42
0
 def save_to_disk(self, filename, data):
     f = QFile(filename)
     if not f.open(QIODevice.WriteOnly):
         print "could not open %s for writing" % filename
         return False
     f.write(data.readAll())
     f.close()
     return True
Ejemplo n.º 43
0
    def downloadFile(self, path, setting):
        self.progress_text = 'Downloading {}'.format(path.replace(self.base_url.format(self.selected_version()),''))

        url = QUrl(path)
        fileInfo = QFileInfo(url.path())
        fileName = setting.save_file_path(self.selected_version())

        archive_exists = QFile.exists(fileName)

        dest_files_exist = True

        for dest_file in setting.dest_files:
            dest_file_path = os.path.join('files', setting.name, dest_file)
            dest_files_exist &= QFile.exists(dest_file_path)

        forced = self.getSetting('force_download').value

        if (archive_exists or dest_files_exist) and not forced:
            self.continueDownloadingOrExtract()
            return #QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            self.show_error('Unable to save the file {}: {}.'.format(fileName, self.outFile.errorString()))
            self.outFile = None
            self.enableUI()
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.httpRequestAborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        # Download the file.
        self.httpGetId = self.http.get(path, self.outFile)
Ejemplo n.º 44
0
    def save(self,fileName):
	file = QFile(fileName)
	file.open(QIODevice.WriteOnly | QIODevice.Text)
        xmlWriter = QXmlStreamWriter(file)
        xmlWriter.setAutoFormatting(1)
        xmlWriter.writeStartDocument()
        xmlWriter.writeStartElement("rws")
        for i in range(self.rowCount()):
            c = self.data(self.index(i,0),QtReduceModel.RawDataRole)
            xmlWriter.writeStartElement("group")
            l = c.toDict().items()
            l.sort()
            for x in l:
                xmlWriter.writeStartElement(x[0])
                xmlWriter.writeCharacters(x[1])
                xmlWriter.writeEndElement()
            xmlWriter.writeEndElement()
        xmlWriter.writeEndElement()
        xmlWriter.writeEndDocument()
Ejemplo n.º 45
0
    def testPhrase(self):
        #Test loading of quote.txt resource
        f = open(adjust_filename('quoteEnUS.txt', __file__), "r")
        orig = f.read()
        f.close()

        f = QFile(':/quote.txt')
        f.open(QIODevice.ReadOnly) #|QIODevice.Text)
        print("Error:", f.errorString())
        copy = f.readAll()
        f.close()
        self.assertEqual(orig, copy)
Ejemplo n.º 46
0
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowTitle("Diablo Meter")

        size = QSize(530, 470)
        self.resize(size)

        # Load ui from gui definition file
        try:
            loader = QUiLoader()
            file = QFile("widgets/widgets.ui")
            file.open(QFile.ReadOnly)
            mainWindow = loader.load(file, self)
            file.close()
        except:
            self.warning_message("Error", "Can't find widgets definition file.\nIs the widgets folder in the same path as the executable?")
            sys.exit()

        #Reference to the components
        self.left_click_lcd = mainWindow.findChild(QLCDNumber, "left_click_lcd")
        self.right_click_lcd = mainWindow.findChild(QLCDNumber, "right_click_lcd")
        self.action_keys_lcds = [mainWindow.findChild(QLCDNumber, "action_1_lcd"),
                mainWindow.findChild(QLCDNumber, "action_2_lcd"),
                mainWindow.findChild(QLCDNumber, "action_3_lcd"),
                mainWindow.findChild(QLCDNumber, "action_4_lcd")]

        options_menu = self.menuBar().addMenu("&Options")
        options_menu.addAction(QtGui.QAction("&Restart Counters", self, triggered=self.restart_counters))

        #Queue to share messsages to the message pupm on EventListener
        q = Queue()
        self.event_listener = EventListener(q)
        self.event_listener.start()

        self.thread = EventProcessor(q)
        self.thread.dataReady.connect(self.on_hook_event)
        self.thread.start()

        #Key Names we are interested in. The order in the tuple
        #determines to which action key it's mapped
        self.key_maps = ("1", "2", "3", "4")
Ejemplo n.º 47
0
    def saveHistory(self, fileName, html):  #TODO
        """
        TOWRITE

        :param `fileName`: TOWRITE
        :type `fileName`: QString
        :param `html`: TOWRITE
        :type `html`: bool
        """
        qDebug("CmdPrompt saveHistory")
        file = QFile(fileName)
        if (not file.open(QIODevice.WriteOnly | QIODevice.Text)):
            return

        # TODO: save during input in case of crash
        output = QTextStream(file)
        if html:
            output << promptHistory.toHtml()
        else:
            output << promptHistory.toPlainText()
def javaInclude(context, engine):
    fileName = context.argument(0).toString()
    scriptFile = QFile("commands/" + fileName)

    if not scriptFile.open(QIODevice.ReadOnly):
        return -1

    stream = QTextStream(scriptFile)
    s = stream.readAll()  # QString
    scriptFile.close()

    parent = context.parentContext()  # QScriptContext*

    if parent != 0:
        context.setActivationObject(context.parentContext().activationObject())
        context.setThisObject(context.parentContext().thisObject())

    result = engine.evaluate(s)  #TODO/PORT/FIXME# what's this for?

    return 0
Ejemplo n.º 49
0
    def __init__(self, parent):
        QGeoPositionInfoSource.__init__(self, parent)
        self.logFile = QFile(self)
        self.timer = QTimer(self)

        self.timer.timeout.connect(self.readNextPosition)

        self.logFile.setFileName(translate_filename('simplelog.txt'))
        assert self.logFile.open(QIODevice.ReadOnly)

        self.lastPosition = QGeoPositionInfo()
Ejemplo n.º 50
0
    def OnSaveFilePath(self, filePath):
        """"""
        file = QFile(filePath)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(self, self.tr('Warning'),
                    self.tr('Cannot write file') + ' %s:\n%s.' % (filePath, file.errorString()))
            return False

        outf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outf << self.toPlainText()
        QApplication.restoreOverrideCursor()

        self.DoSetCurrentFilePath(filePath)

        # Clear the Modified Flag.
        self.document().setModified(False)
        self.setWindowModified(False)
        self.setWindowTitle('%s[*]' % self.fileName)

        return True
Ejemplo n.º 51
0
def loadDialog(file_name):
    loader = QUiLoader()
    the_file = QFile(file_name)
    the_file.open(QFile.ReadOnly)
    ret_val = loader.load(the_file)
    the_file.close()
    return ret_val
Ejemplo n.º 52
0
 def convertTextureSize(texturePath):
     if int(cmds.about(v=1)) < 2017:
         from PySide import QtCore
         from PySide.QtGui import QPixmap, QImage
         from PySide.QtCore import QFile, QIODevice
     else:
         from PySide2 import QtCore
         from PySide2.QtGui import QPixmap, QImage
         from PySide2.QtCore import QFile, QIODevice
     folder, fileName = ntpath.split(texturePath)
     origFileName = fileName if fileName[:
                                         8] != 'resized_' else fileName[
                                             8:]
     origPath = folder + '/' + origFileName
     if not os.path.exists(origPath):
         cmds.warning("original is not exists : %s" %
                      texturePath)
         return
     convertedFileName = 'resized_%d_' % (
         int(resolusion)) + origFileName
     renamedPath = folder + "/" + convertedFileName
     ext = os.path.splitext(fileName)[-1]
     img = QImage(origPath)
     pixmap = QPixmap()
     pixmap = pixmap.fromImage(
         img.scaled(int(resolusion), int(resolusion),
                    QtCore.Qt.IgnoreAspectRatio,
                    QtCore.Qt.FastTransformation))
     qfile = QFile(renamedPath)
     qfile.open(QIODevice.WriteOnly)
     pixmap.save(qfile, ext[1:], 100)
     qfile.close()
     return renamedPath
Ejemplo n.º 53
0
def loadWindowFromFile(file_name):
    '''Load the window definition from the resource ui file'''
    loader = QUiLoader()
    ui_file = QFile(file_name)
    ui_file.open(QFile.ReadOnly)
    the_window = loader.load(ui_file)
    ui_file.close()
    return the_window
Ejemplo n.º 54
0
def load_stylesheet(theme, pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    if theme == 'darkstyle':
        import themes.darkstyle.pyside_style_rc
    elif theme == 'robotstyle':
        import themes.robotstyle.pyside_style_rc

    from PySide.QtCore import QFile, QTextStream

    basedir = os.path.abspath(os.path.dirname(__file__))
    localPath = "%s/style.qss" % theme
    f = QFile( os.path.join(basedir, localPath))

    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        # if platform.system().lower() == 'darwin':  # see issue #12 on github
        #     mac_fix = '''
        #     QDockWidget::title
        #     {
        #         background-color: #353434;
        #         text-align: center;
        #         height: 10px;
        #     }
        #     '''
        #     stylesheet += mac_fix
        return stylesheet
Ejemplo n.º 55
0
    def testImage(self):
        #Test loading of sample.png resource
        f = open(adjust_filename('sample.png', __file__), "rb")
        orig = f.read()
        f.close()

        f = QFile(':/sample.png')
        f.open(QIODevice.ReadOnly)
        copy = f.readAll()
        f.close()
        self.assertEqual(len(orig), len(copy))
        self.assertEqual(orig, copy)
Ejemplo n.º 56
0
def readRcTextFile(path):
    """Read whole text file from qt resources system."""
    assert path.startswith(':/')
    f = QFile(path)
    if not f.open(QFile.ReadOnly | QFile.Text):
        raise FileNotFoundError('failed to read rc text %s' % path)
    text = str(f.readAll())
    f.close()
    return text
Ejemplo n.º 57
0
    def testCallFunction(self):
        f = QTemporaryFile()
        self.assertTrue(f.open())
        fileName = f.fileName()
        f.close()

        f = QFile(fileName)
        self.assertEqual(
            f.open(QIODevice.Truncate | QIODevice.Text | QIODevice.ReadWrite),
            True)
        om = f.openMode()
        self.assertEqual(om & QIODevice.Truncate, QIODevice.Truncate)
        self.assertEqual(om & QIODevice.Text, QIODevice.Text)
        self.assertEqual(om & QIODevice.ReadWrite, QIODevice.ReadWrite)
        self.assertTrue(om == QIODevice.Truncate | QIODevice.Text
                        | QIODevice.ReadWrite)
        f.close()
Ejemplo n.º 58
0
 def loadWindow(self, uiFile, mainWindowAsParent=True, connectSlots=True):
     '''
     Load a Window from UI file.
     '''
     path = join(UI_PATH, uiFile)
     windowFile = QFile(path)
     windowFile.open(QIODevice.ReadOnly | QIODevice.Text)
     # Make all loaded windows children of mainWindow, except mainWindow itself
     window = self.uiLoader.load(
         windowFile, self.__mainWindow if mainWindowAsParent else None)
     windowFile.close()
     if connectSlots:
         QMetaObject.connectSlotsByName(window)
     return window