def send_ctrl_to_process(self, letter): char = chr("abcdefghijklmnopqrstuvwxyz".index(letter) + 1) byte_array = QByteArray() byte_array.append(char) self.process.write(byte_array) self.process.waitForBytesWritten(-1) self.shell.write(locale_codec.toUnicode(byte_array), flush=True)
class FriendFeedRequest(QObject): def __init__(self, reply, feed = False, parent = None): QObject.__init__(self, parent) self.reply = reply self.feed = feed self.connect(self.reply, SIGNAL("readyRead()"), self.readData) self.connect(self.reply, SIGNAL("finished()"), self.dataDone) self.data = QByteArray() def readData(self): self.data.append(self.reply.readAll()) def dataDone(self): if self.reply.error() != QNetworkReply.NoError: self.emit(SIGNAL("error"), self.reply.error()) else: self.data.append(self.reply.readAll()) result = simplejson.loads(str(self.data).decode("utf-8")) if self.feed: date_properties = frozenset(("updated", "published")) for entry in result.get("entries", []): entry["updated"] = self._parse_date(entry["updated"]) entry["published"] = self._parse_date(entry["published"]) for comment in entry.get("comments", []): comment["date"] = self._parse_date(comment["date"]) for like in entry.get("likes", []): like["date"] = self._parse_date(like["date"]) result["entries"].sort(key = lambda x:x["updated"], reverse = True) self.emit(SIGNAL("ready"), result) self.emit(SIGNAL("cleanup"), self) def _parse_date(self, date_str): rfc3339_date = "%Y-%m-%dT%H:%M:%SZ" return datetime.datetime(*time.strptime(date_str, rfc3339_date)[:6])
def startDrag(self, dropAction): """ Start drag @param dropAction: @type dropAction: """ indexes = self.selectedIndexes() if not indexes: return for index in indexes: if not index.isValid(): return rowVal = self.model.getValueRow(indexes[0]) if len(rowVal) > 1: meta = QByteArray() if self.datasetView: meta.append("__%s__" % rowVal['name']) else: meta.append("agent('%s')" % rowVal['name']) # create mime data object mime = QMimeData() mime.setData('application/x-%s-agent-item' % self.__acronym, meta) # start drag drag = QDrag(self) drag.setMimeData(mime) drag.exec_(Qt.CopyAction)
def startDrag(self, dropAction): """ Start drag @param dropAction: @type dropAction: """ if self.datasetView: return # check indexes indexes = self.selectedIndexes() if not indexes: return for index in indexes: if not index.isValid(): return rowVal = self.model.getValueRow(indexes[0]) if len(rowVal) > 1: meta = QByteArray() meta.append("description('%s')" % rowVal['key']) # create mime data object mime = QMimeData() m = 'application/x-%s-description-item' % Settings.instance( ).readValue(key='Common/acronym').lower() mime.setData(m, meta) # start drag drag = QDrag(self) drag.setMimeData(mime) drag.exec_(Qt.CopyAction)
def qstring2path (qs): # BUG: this is ugly; might be properly handled w/PyQt4.6/Python2.6 qba= QByteArray () qba.append (qs) s= str (qba) return s
def send_ctrl_to_process(self, letter): char = chr("abcdefghijklmnopqrstuvwxyz".index(letter) + 1) byte_array = QByteArray() byte_array.append(char) self.process.write(byte_array) self.process.waitForBytesWritten(-1) self.shell.write(QString(byte_array))
def mimeData(self, items): """ Returns QMimeData for drag and drop. """ logging.debug(self.__class__.__name__ + ": mimeData()") mime = QMimeData() encodedData = QByteArray() for item in items: encodedData.append(item.text(0)) mime.setData(self.mimeType(), encodedData) return mime
def do_ftp_put(self): num = len(self.files) for i in range(num): file = self.files[i] fhandle = QFile(file) fhandle.open(QIODevice.ReadOnly) byte_array = QByteArray() byte_array.append(fhandle.readData(fhandle.size())) fileinfo = QFileInfo(file) filename = fileinfo.fileName() self.ftp.put(byte_array, filename) self.ftp.close()
def ask_for_token(c_id, c_secret, request_status=True): """Ask a token from Isogeo API authentification page. This send a POST request to Isogeo API with the user id and secret in its header. The API should return an access token """ headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret) data = urllib.urlencode({"grant_type": "client_credentials"}) databyte = QByteArray() databyte.append(data) url = QUrl('https://id.api.isogeo.com/oauth/token') request = QNetworkRequest(url) request.setRawHeader("Authorization", headervalue) if request_status is True: request_status = False return request, databyte QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
def onPushButtonSendClicked(self): if not self.__serial.isOpen: self.__postText("E[?]: Port is not open.") return text = self.lineEditData.text().simplified() if text.isEmpty(): self.__postText("E[?]: No input provided.") return self.__history.add(text) data = QByteArray() if self.checkBoxRawText.isChecked(): dataFormat = "S" data = text.toLocal8Bit() else: INDEX_BASE = {0: 2, 1: 8, 2: 10, 3: 16} index = self.comboBoxFormat.currentIndex() base = INDEX_BASE.get(index, None) if not base: self.__postText("E[?]: Invalid base of a number.") try: values = stringToBytes(str(text), base) except ValueError as error: self.__postText("E[?]: Incorrect input: <%s>." % str(error).capitalize()) for value in values: data.append(chr(value)) text = bytesToString(values, base, self.checkBoxLeadingZeroes.isChecked()) INDEX_FORMAT = {0: "B", 1: "O", 2: "D", 3: "H"} dataFormat = INDEX_FORMAT.get(index, None) if not dataFormat: self.__postText("E[?]: Invalid data format.") self.lineEditData.clear() self.__postText("T[%s:%s]: %s" % (dataFormat, len(data), text)) self.__serial.write(data)
def ask_for_token(self, c_id, c_secret): """Ask a token from Isogeo API authentification page. This send a POST request to Isogeo API with the user id and secret in its header. The API should return an access token """ headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret) data = urlencode({"grant_type": "client_credentials"}) databyte = QByteArray() databyte.append(data) url = QUrl('https://id.api.isogeo.com/oauth/token') request = QNetworkRequest(url) request.setRawHeader("Authorization", headervalue) if self.requestStatusClear is True: self.requestStatusClear = False token_reply = self.manager.post(request, databyte) token_reply.finished.connect( partial(self.handle_token, answer=token_reply)) QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
def open(self, url, post_data=None, headers={}, receiver=None): request = QNetworkRequest(QUrl(url)) if post_data: debug.debug('post %s' % url) postData = QByteArray() for key, var in post_data.items(): postData.append('%s=%s&' % (key, var)) for header, var in headers.items(): request.setRawHeader(header, var) reply = self.netWorkMgr.post(request, postData) else: debug.debug('get %s' % url) for header, var in headers.items(): request.setRawHeader(header, var) reply = self.netWorkMgr.get(request) if receiver: reply.finished.connect(receiver) else: receiver = self.netWorkMgr.parent() reply.finished.connect(receiver.replyFinished)
def upload_questionnaire_project(self): """Upload questionnaire.""" self.set_status(tr('Update questionnaire')) post_url = '/api/v1/organizations/' \ '%s/projects/%s/questionnaire/' % ( self.data['organisation']['slug'], self.project_upload_result['slug'] ) post_data = QByteArray() post_data.append(self.data['questionnaire']) connector = ApiConnect(get_url_instance() + post_url) status, result = self._call_json_put(connector, post_data) self.set_status(tr('Finished update questionnaire')) if status: self.set_progress_bar(self.current_progress + self.upload_increment) else: self.set_progress_bar(0) self.set_status(Utilities.extract_error_detail(result))
class Login(BaseApi): post_data = None def __init__(self, domain, username, password, on_finished=None): """Constructor. Constructor of login class needs domain, username and password for check connection. :param username: username for login. :type username: QString :param password: username for login. :type password: QString :param on_finished: (optional) is a function that catch tools result request. :type on_finished: Function """ super(Login, self).__init__(domain + '/api/v1/account/login/?') self.post_data = QByteArray() self.post_data.append("username=%s&" % username) self.post_data.append("password=%s" % password) self.on_finished = on_finished def connection_finished(self): """Function finished handler. When tools request is finished, this function will be called. Try get result from self.get_json_results() in json format""" # extract result if self.error: self.on_finished(self.error) else: result = self.get_json_results() if self.on_finished and callable(self.on_finished): self.on_finished(result)
def onPushButtonSendClicked(self): text = self.lineEditData.text().simplified() if text.isEmpty(): return data = QByteArray() if self.checkBoxRawText.isChecked(): dataFormat = "S" data = text.toLocal8Bit() else: INDEX_BASE = {0: 2, 1: 8, 2: 10, 3: 16} index = self.comboBoxFormat.currentIndex() base = INDEX_BASE.get(index, None) if not base: self.__postText("E[?]: Invalid base of a number.") try: values = stringToBytes(str(text), base) except ValueError as error: self.__postText("E[?]: Incorrect input: <%s>." % error) for value in values: data.append(chr(value)) INDEX_FORMAT = {0: "B", 1: "O", 2: "D", 3: "H"} dataFormat = INDEX_FORMAT.get(index, None) if not dataFormat: self.__postText("E[?]: Invalid data format.") self.__postText("T[%s:%s]: %s" % (dataFormat, len(data), text)) self.__socket.write(data) self.__history.add(self.lineEditData.text()) self.lineEditData.clear()
def test_network_mixin_post(self): """Test network mixin post""" request_url = 'http://jsonplaceholder.typicode.com/posts' post_data = QByteArray() post_data.append("title=%s&" % self.api_results['title']) post_data.append("body=%s&" % self.api_results['body']) post_data.append("userId=%d&" % self.api_results['userId']) manager = NetworkMixin(request_url=request_url) manager.connect_post(post_data) while not manager.is_finished(): QCoreApplication.processEvents() self.assertIsNotNone(manager.get_json_results()) self.assertEqual(manager.get_json_results()['userId'], self.api_results['userId']) self.assertEqual(manager.get_json_results()['body'], self.api_results['body'])
class FileDownloader(object): """The blueprint for downloading file from url.""" def __init__(self, url, output_path, progress_dialog=None): """Constructor of the class. .. versionchanged:: 3.3 removed manager parameter. :param url: URL of file. :type url: str :param output_path: Output path. :type output_path: str :param progress_dialog: Progress dialog widget. :type progress_dialog: QWidget """ # noinspection PyArgumentList self.manager = qgis.core.QgsNetworkAccessManager.instance() self.url = QUrl(url) self.output_path = output_path self.progress_dialog = progress_dialog if self.progress_dialog: self.prefix_text = self.progress_dialog.labelText() self.output_file = None self.reply = None self.downloaded_file_buffer = None self.finished_flag = False def download(self): """Downloading the file. :returns: True if success, otherwise returns a tuple with format like this (QNetworkReply.NetworkError, error_message) :raises: IOError - when cannot create output_path """ # Prepare output path self.output_file = QFile(self.output_path) if not self.output_file.open(QFile.WriteOnly): raise IOError(self.output_file.errorString()) # Prepare downloaded buffer self.downloaded_file_buffer = QByteArray() # Request the url request = QNetworkRequest(self.url) self.reply = self.manager.get(request) self.reply.readyRead.connect(self.get_buffer) self.reply.finished.connect(self.write_data) self.manager.requestTimedOut.connect(self.request_timeout) if self.progress_dialog: # progress bar def progress_event(received, total): """Update progress. :param received: Data received so far. :type received: int :param total: Total expected data. :type total: int """ # noinspection PyArgumentList QCoreApplication.processEvents() self.progress_dialog.adjustSize() human_received = humanize_file_size(received) human_total = humanize_file_size(total) label_text = tr( "%s : %s of %s" % (self.prefix_text, human_received, human_total)) self.progress_dialog.setLabelText(label_text) self.progress_dialog.setMaximum(total) self.progress_dialog.setValue(received) # cancel def cancel_action(): """Cancel download.""" self.reply.abort() self.reply.deleteLater() self.reply.downloadProgress.connect(progress_event) self.progress_dialog.canceled.connect(cancel_action) # Wait until finished # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always # returns False even after finished slot is called. So, that's why we # are adding self.finished_flag (see #864) while not self.reply.isFinished() and not self.finished_flag: # noinspection PyArgumentList QCoreApplication.processEvents() result = self.reply.error() try: http_code = int( self.reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)) except TypeError: # If the user cancels the request, the HTTP response will be None. http_code = None self.reply.abort() self.reply.deleteLater() if result == QNetworkReply.NoError: return True, None elif result == QNetworkReply.UnknownNetworkError: return False, tr( 'The network is unreachable. Please check your internet ' 'connection.') elif http_code == 408: msg = tr('Sorry, the server aborted your request. ' 'Please try a smaller area.') LOGGER.debug(msg) return False, msg elif http_code == 509: msg = tr( 'Sorry, the server is currently busy with another request. ' 'Please try again in a few minutes.') LOGGER.debug(msg) return False, msg elif result == QNetworkReply.ProtocolUnknownError or \ result == QNetworkReply.HostNotFoundError: LOGGER.exception('Host not found : %s' % self.url.encodedHost()) return False, tr( 'Sorry, the server is unreachable. Please try again later.') elif result == QNetworkReply.ContentNotFoundError: LOGGER.exception('Path not found : %s' % self.url.path()) return False, tr('Sorry, the layer was not found on the server.') else: return result, self.reply.errorString() def get_buffer(self): """Get buffer from self.reply and store it to our buffer container.""" buffer_size = self.reply.size() data = self.reply.read(buffer_size) self.downloaded_file_buffer.append(data) def write_data(self): """Write data to a file.""" self.output_file.write(self.downloaded_file_buffer) self.output_file.close() self.finished_flag = True def request_timeout(self): """The request timed out.""" if self.progress_dialog: self.progress_dialog.hide()
class FileDownloader(object): """The blueprint for downloading file from url.""" def __init__(self, url, output_path, progress_dialog=None): """Constructor of the class. .. versionchanged:: 3.3 removed manager parameter. :param url: URL of file. :type url: str :param output_path: Output path. :type output_path: str :param progress_dialog: Progress dialog widget. :type progress_dialog: QWidget """ # noinspection PyArgumentList self.manager = qgis.core.QgsNetworkAccessManager.instance() self.url = QUrl(url) self.output_path = output_path self.progress_dialog = progress_dialog if self.progress_dialog: self.prefix_text = self.progress_dialog.labelText() self.output_file = None self.reply = None self.downloaded_file_buffer = None self.finished_flag = False def download(self): """Downloading the file. :returns: True if success, otherwise returns a tuple with format like this (QNetworkReply.NetworkError, error_message) :raises: IOError - when cannot create output_path """ # Prepare output path self.output_file = QFile(self.output_path) if not self.output_file.open(QFile.WriteOnly): raise IOError(self.output_file.errorString()) # Prepare downloaded buffer self.downloaded_file_buffer = QByteArray() # Request the url request = QNetworkRequest(self.url) self.reply = self.manager.get(request) self.reply.readyRead.connect(self.get_buffer) self.reply.finished.connect(self.write_data) self.manager.requestTimedOut.connect(self.request_timeout) if self.progress_dialog: # progress bar def progress_event(received, total): """Update progress. :param received: Data received so far. :type received: int :param total: Total expected data. :type total: int """ # noinspection PyArgumentList QCoreApplication.processEvents() self.progress_dialog.adjustSize() human_received = humanize_file_size(received) human_total = humanize_file_size(total) label_text = tr("%s : %s of %s" % ( self.prefix_text, human_received, human_total)) self.progress_dialog.setLabelText(label_text) self.progress_dialog.setMaximum(total) self.progress_dialog.setValue(received) # cancel def cancel_action(): """Cancel download.""" self.reply.abort() self.reply.deleteLater() self.reply.downloadProgress.connect(progress_event) self.progress_dialog.canceled.connect(cancel_action) # Wait until finished # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always # returns False even after finished slot is called. So, that's why we # are adding self.finished_flag (see #864) while not self.reply.isFinished() and not self.finished_flag: # noinspection PyArgumentList QCoreApplication.processEvents() result = self.reply.error() try: http_code = int(self.reply.attribute( QNetworkRequest.HttpStatusCodeAttribute)) except TypeError: # If the user cancels the request, the HTTP response will be None. http_code = None self.reply.abort() self.reply.deleteLater() if result == QNetworkReply.NoError: return True, None elif result == QNetworkReply.UnknownNetworkError: return False, tr( 'The network is unreachable. Please check your internet ' 'connection.') elif http_code == 408: msg = tr( 'Sorry, the server aborted your request. ' 'Please try a smaller area.') LOGGER.debug(msg) return False, msg elif http_code == 509: msg = tr( 'Sorry, the server is currently busy with another request. ' 'Please try again in a few minutes.') LOGGER.debug(msg) return False, msg elif result == QNetworkReply.ProtocolUnknownError or \ result == QNetworkReply.HostNotFoundError: LOGGER.exception('Host not found : %s' % self.url.encodedHost()) return False, tr( 'Sorry, the server is unreachable. Please try again later.') elif result == QNetworkReply.ContentNotFoundError: LOGGER.exception('Path not found : %s' % self.url.path()) return False, tr('Sorry, the layer was not found on the server.') else: return result, self.reply.errorString() def get_buffer(self): """Get buffer from self.reply and store it to our buffer container.""" buffer_size = self.reply.size() data = self.reply.read(buffer_size) self.downloaded_file_buffer.append(data) def write_data(self): """Write data to a file.""" self.output_file.write(self.downloaded_file_buffer) self.output_file.close() self.finished_flag = True def request_timeout(self): """The request timed out.""" if self.progress_dialog: self.progress_dialog.hide()
def createWidgets(self): """ Create qt widgets """ # prepare menu self.toolbar = QToolBar(self) self.toolbar.setStyleSheet( "QToolBar { border: 0px }") # remove 3D border self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.toolbarPlugins = QToolBar(self) self.toolbarPlugins.setStyleSheet( "QToolBar { border: 0px }") # remove 3D border self.toolbarPlugins.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.pluginsBox = QGroupBox("Plugins") self.pluginsBox.setStyleSheet(""" QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } QGroupBox::title { subcontrol-position: bottom center;} """) layoutPlugins = QHBoxLayout() layoutPlugins.addWidget(self.toolbarPlugins) layoutPlugins.setContentsMargins(0, 0, 0, 0) self.pluginsBox.setLayout(layoutPlugins) self.pluginsBox.hide() self.exportBox = QGroupBox("Exports") self.exportBox.setStyleSheet(""" QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } QGroupBox::title { subcontrol-position: bottom center;} """) layoutExports = QHBoxLayout() layoutExports.addWidget(self.toolbar) layoutExports.setContentsMargins(0, 0, 0, 0) self.exportBox.setLayout(layoutExports) self.exportBox.setMaximumHeight(70) layout = QVBoxLayout() if self.toXml: self.txtEdit = QtHelper.RawXmlEditor(parent=self) self.txtEdit.setText(self.__data) # self.txtEdit.setUtf8(False) self.txtEdit.setFont(QFont("Courier", 9)) else: self.txtEdit = QWebView(parent=self) # convert to qbyte array to support qt5 tmp_ = QByteArray() tmp_.append(self.__data) self.txtEdit.setContent(tmp_, "text/html; charset=utf-8") layoutToolbars = QHBoxLayout() layoutToolbars.addWidget(self.exportBox) layoutToolbars.addWidget(self.pluginsBox) layoutToolbars.addStretch(1) layoutToolbars.setContentsMargins(5, 0, 0, 0) layout.addLayout(layoutToolbars) layout.addWidget(self.txtEdit) self.setLayout(layout)
class FileDownloader(object): """The blueprint for downloading file from url.""" def __init__(self, manager, url, output_path, progress_dialog=None): """Constructor of the class. :param manager: QNetworkAccessManager instance to handle downloading. :type manager: QNetworkAccessManager :param url: URL of file. :type url: str :param output_path: Output path. :type output_path: str :param progress_dialog: Progress dialog widget. :type progress_dialog: QWidget """ self.manager = manager self.url = url self.output_path = output_path self.progress_dialog = progress_dialog self.output_file = None self.reply = None self.downloaded_file_buffer = None self.finished_flag = False def download(self): """Downloading the file. :returns: True if success, otherwise returns a tuple with format like this (QNetworkReply.NetworkError, error_message) :raises: IOError - when cannot create output_path """ # Prepare output path self.output_file = QFile(self.output_path) if not self.output_file.open(QFile.WriteOnly): raise IOError(self.output_file.errorString()) # Prepare downloaded buffer self.downloaded_file_buffer = QByteArray() # Request the url request = QNetworkRequest(QUrl(self.url)) self.reply = self.manager.get(request) self.reply.readyRead.connect(self.update_buffer_container) self.reply.finished.connect(self.write_data) if self.progress_dialog: # progress bar def progress_event(received, total): """Update progress. :param received: Data received so far. :type received: int :param total: Total expected data. :type total: int """ # noinspection PyArgumentList QCoreApplication.processEvents() label_text = "%s / %s" % (received, total) self.progress_dialog.setLabelText(label_text) self.progress_dialog.setMaximum(total) self.progress_dialog.setValue(received) # cancel def cancel_action(): """Cancel download.""" self.reply.abort() self.reply.downloadProgress.connect(progress_event) self.progress_dialog.canceled.connect(cancel_action) # Wait until finished # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always # returns False even after finished slot is called. So, that's why we # are adding self.finished_flag (see #864) while not self.reply.isFinished() and not self.finished_flag: # noinspection PyArgumentList QCoreApplication.processEvents() result = self.reply.error() if result == QNetworkReply.NoError: return True, None else: return result, str(self.reply.errorString()) def update_buffer_container(self): """Update buffer container by using buffer obtained from self.reply""" buffer_size = self.reply.size() data = self.reply.read(buffer_size) self.downloaded_file_buffer.append(data) def write_data(self): """Write data to a file.""" self.output_file.write(self.downloaded_file_buffer) self.output_file.close() self.finished_flag = True
class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) format = QAudioFormat() format.setChannels(1) format.setFrequency(22050) format.setSampleSize(16) format.setCodec("audio/pcm") format.setByteOrder(QAudioFormat.LittleEndian) format.setSampleType(QAudioFormat.SignedInt) self.output = QAudioOutput(format, self) self.frequency = 440 self.volume = 0 self.buffer = QBuffer() self.data = QByteArray() self.deviceLineEdit = QLineEdit() self.deviceLineEdit.setReadOnly(True) self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName()) self.pitchSlider = QSlider(Qt.Horizontal) self.pitchSlider.setMaximum(100) self.volumeSlider = QSlider(Qt.Horizontal) self.volumeSlider.setMaximum(32767) self.volumeSlider.setPageStep(1024) self.playButton = QPushButton(self.tr("&Play")) self.pitchSlider.valueChanged.connect(self.changeFrequency) self.volumeSlider.valueChanged.connect(self.changeVolume) self.playButton.clicked.connect(self.play) formLayout = QFormLayout() formLayout.addRow(self.tr("Device:"), self.deviceLineEdit) formLayout.addRow(self.tr("P&itch:"), self.pitchSlider) formLayout.addRow(self.tr("&Volume:"), self.volumeSlider) buttonLayout = QVBoxLayout() buttonLayout.addWidget(self.playButton) buttonLayout.addStretch() horizontalLayout = QHBoxLayout(self) horizontalLayout.addLayout(formLayout) horizontalLayout.addLayout(buttonLayout) def changeFrequency(self, value): self.frequency = 440 + (value * 2) def play(self): if self.output.state() == QAudio.ActiveState: self.output.stop() if self.buffer.isOpen(): self.buffer.close() self.createData() self.buffer.setData(self.data) self.buffer.open(QIODevice.ReadOnly) self.buffer.seek(0) self.output.start(self.buffer) def changeVolume(self, value): self.volume = value def createData(self): # Create 2 seconds of data with 22050 samples per second, each sample # being 16 bits (2 bytes). self.data.clear() for i in xrange(2 * 22050): t = i / 22050.0 value = int(self.volume * sin(2 * pi * self.frequency * t)) self.data.append(struct.pack("<h", value))
def xmlDownloaded(self): """ populate the plugins object with the fetched data """ reply = self.sender() reposName = reply.property('reposName') if reply.error() != QNetworkReply.NoError: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mRepositories[reposName]["error"] += "\n\n" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window.") else: reposXML = QDomDocument() content = reply.readAll() # Fix lonely ampersands in metadata a = QByteArray() a.append("& ") b = QByteArray() b.append("& ") content = content.replace(a, b) reposXML.setContent(content) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement("file_name").text().strip() if not fileName: fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().strip().split("?")[0]).fileName() name = fileName.partition(".")[0] experimental = False if pluginNodes.item(i).firstChildElement("experimental").text().strip().upper() in ["TRUE", "YES"]: experimental = True deprecated = False if pluginNodes.item(i).firstChildElement("deprecated").text().strip().upper() in ["TRUE", "YES"]: deprecated = True icon = pluginNodes.item(i).firstChildElement("icon").text().strip() if icon and not icon.startswith("http"): icon = "http://%s/%s" % (QUrl(self.mRepositories[reposName]["url"]).host(), icon) if pluginNodes.item(i).toElement().hasAttribute("plugin_id"): plugin_id = pluginNodes.item(i).toElement().attribute("plugin_id") else: plugin_id = None plugin = { "id": name, "plugin_id": plugin_id, "name": pluginNodes.item(i).toElement().attribute("name"), "version_available": pluginNodes.item(i).toElement().attribute("version"), "description": pluginNodes.item(i).firstChildElement("description").text().strip(), "about": pluginNodes.item(i).firstChildElement("about").text().strip(), "author_name": pluginNodes.item(i).firstChildElement("author_name").text().strip(), "homepage": pluginNodes.item(i).firstChildElement("homepage").text().strip(), "download_url": pluginNodes.item(i).firstChildElement("download_url").text().strip(), "category": pluginNodes.item(i).firstChildElement("category").text().strip(), "tags": pluginNodes.item(i).firstChildElement("tags").text().strip(), "changelog": pluginNodes.item(i).firstChildElement("changelog").text().strip(), "author_email": pluginNodes.item(i).firstChildElement("author_email").text().strip(), "tracker": pluginNodes.item(i).firstChildElement("tracker").text().strip(), "code_repository": pluginNodes.item(i).firstChildElement("repository").text().strip(), "downloads": pluginNodes.item(i).firstChildElement("downloads").text().strip(), "average_vote": pluginNodes.item(i).firstChildElement("average_vote").text().strip(), "rating_votes": pluginNodes.item(i).firstChildElement("rating_votes").text().strip(), "icon": icon, "experimental": experimental, "deprecated": deprecated, "filename": fileName, "installed": False, "available": True, "status": "not installed", "error": "", "error_details": "", "version_installed": "", "zip_repository": reposName, "library": "", "readonly": False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().strip() if not qgisMinimumVersion: qgisMinimumVersion = "2" qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99" #if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE", "YES"]: if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion): #add the plugin to the cache plugins.addFromRepository(plugin) self.mRepositories[reposName]["state"] = 2 else: # no plugin metadata found self.mRepositories[reposName]["state"] = 3 if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200: self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options.") else: self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Status code:") + " %d %s" % ( reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute) ) self.repositoryFetched.emit(reposName) # is the checking done? if not self.fetchingInProgress(): self.checkingDone.emit() reply.deleteLater()
class FileDownloader(object): """The blueprint for downloading file from url.""" def __init__(self, manager, url, output_path, progress_dialog=None): """Constructor of the class. :param manager: QNetworkAccessManager instance to handle downloading. :type manager: QNetworkAccessManager :param url: URL of file. :type url: str :param output_path: Output path. :type output_path: str :param progress_dialog: Progress dialog widget. :type progress_dialog: QWidget """ self.manager = manager self.url = url self.output_path = output_path self.progress_dialog = progress_dialog self.output_file = None self.reply = None self.downloaded_file_buffer = None self.finished_flag = False def download(self): """Downloading the file. :returns: True if success, otherwise returns a tuple with format like this (QNetworkReply.NetworkError, error_message) :raises: IOError - when cannot create output_path """ # Prepare output path self.output_file = QFile(self.output_path) if not self.output_file.open(QFile.WriteOnly): raise IOError(self.output_file.errorString()) # Prepare downloaded buffer self.downloaded_file_buffer = QByteArray() # Request the url request = QNetworkRequest(QUrl(self.url)) self.reply = self.manager.get(request) self.reply.readyRead.connect(self.get_buffer) self.reply.finished.connect(self.write_data) if self.progress_dialog: # progress bar def progress_event(received, total): """Update progress. :param received: Data received so far. :type received: int :param total: Total expected data. :type total: int """ # noinspection PyArgumentList QCoreApplication.processEvents() label_text = "%s / %s" % (received, total) self.progress_dialog.setLabelText(label_text) self.progress_dialog.setMaximum(total) self.progress_dialog.setValue(received) # cancel def cancel_action(): """Cancel download.""" self.reply.abort() self.reply.downloadProgress.connect(progress_event) self.progress_dialog.canceled.connect(cancel_action) # Wait until finished # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always # returns False even after finished slot is called. So, that's why we # are adding self.finished_flag (see #864) while not self.reply.isFinished() and not self.finished_flag: # noinspection PyArgumentList QCoreApplication.processEvents() result = self.reply.error() if result == QNetworkReply.NoError: return True, None else: return result, str(self.reply.errorString()) def get_buffer(self): """Get buffer from self.reply and store it to our buffer container.""" buffer_size = self.reply.size() data = self.reply.read(buffer_size) self.downloaded_file_buffer.append(data) def write_data(self): """Write data to a file.""" self.output_file.write(self.downloaded_file_buffer) self.output_file.close() self.finished_flag = True
class ServicoScreenshot(ServicoInformacao): telaRecebida = pyqtSignal(str, QPixmap) ENVIANDO_PARTE_IMAGEM = 40 ENVIANDO_FINAL_IMAGEM = 41 PARTE_RECEBIDA = 42 def __init__(self, portaReceber=4002, portaResponder=4003, parent=None): super().__init__(portaReceber=portaReceber, portaResponder=portaResponder, parent=parent) self._arrayEnviar = QByteArray() self._recebendoPartesImagem = [] def _receberInformacaoTipoValor(self, de, tipo, valor): # Recebendo print(tipo) if tipo == ServicoScreenshot.ENVIANDO_PARTE_IMAGEM: self.setPara(de) self._arrayEnviar.append(valor) print("ENVIANDO RECEBIDA") self.enviarInformacaoTipoValor(ServicoScreenshot.PARTE_RECEBIDA, None) elif tipo == ServicoScreenshot.ENVIANDO_FINAL_IMAGEM: imagem = self._imagemByteArray(self._arrayEnviar) self._arrayEnviar.clear() self.telaRecebida.emit(de, imagem) # Enviando elif tipo == ServicoScreenshot.PARTE_RECEBIDA: self._enviarParte() super()._receberInformacaoTipoValor(de, tipo, valor) def _imagemByteArray(self, array): data = QDataStream(array) image = QPixmap() data >> image return image def _dividirArray(self, array, tam=30000): lista = [] partes = int(array.length() / tam) for i in range(partes): lista.append(array.mid(tam * i, tam)) if tam * partes != array.length(): lista.append(array.mid(tam * partes)) return lista def _enviarParte(self): self.enviarInformacaoTipoValor(ServicoScreenshot.ENVIANDO_PARTE_IMAGEM, self._recebendoPartesImagem.pop(0)) print("PARTE") if not self._recebendoPartesImagem: print("FINAL") self.enviarInformacaoTipoValor(ServicoScreenshot.ENVIANDO_FINAL_IMAGEM, None) def enviarScreenshot(self): self.enviarImagem(QPixmap.grabWindow(QApplication.desktop().winId())) def enviarImagem(self, imagem): array = QByteArray() data = QDataStream(array, QIODevice.WriteOnly) data << imagem self._recebendoPartesImagem = self._dividirArray(array) self._enviarParte()