Beispiel #1
0
 def __load_compressed_complex(self, filename: str):
     obj = tarfile.open(filename, "r")
     members = obj.getmembers()
     obj.extract(members[0], QDir.tempPath())
     extracted_filename = os.path.join(QDir.tempPath(), obj.getnames()[0])
     self._fulldata = np.fromfile(extracted_filename, dtype=np.complex64)
     os.remove(extracted_filename)
Beispiel #2
0
    def display_downloaded_content(self):
        """Open downloaded non-html content in a separate application.

        Called when an unsupported content type is finished downloading.
        """
        file_path = (
            QDir.toNativeSeparators(
                QDir.tempPath() + "/XXXXXX_" + self.content_filename
            )
        )
        myfile = QTemporaryFile(file_path)
        myfile.setAutoRemove(False)
        if myfile.open():
            myfile.write(self.reply.readAll())
            myfile.close()
            subprocess.Popen([
                (self.config.get("content_handlers")
                 .get(str(self.content_type))),
                myfile.fileName()
            ])

            # Sometimes downloading files opens an empty window.
            # So if the current window has no URL, close it.
            if(str(self.url().toString()) in ('', 'about:blank')):
                self.close()
Beispiel #3
0
def save_data(data, filename: str):
    if filename.endswith(".wav"):
        f = wave.open(filename, "w")
        f.setnchannels(1)
        f.setsampwidth(1)
        f.setframerate(1000000)
        f.writeframes(data)
        f.close()
    elif filename.endswith(".coco"):
        with tarfile.open(filename, 'w:bz2') as tar_write:
            tmp_name = os.path.join(QDir.tempPath(), "tmpfile")
            data.tofile(tmp_name)
            tar_write.add(tmp_name)
        os.remove(tmp_name)
    else:
        try:
            data.tofile(filename)
        except Exception as e:
            Errors.write_error(e)

    if filename in archives.keys():
        archive = archives[filename]
        if archive.endswith("zip"):
            rewrite_zip(archive)
        elif archive.endswith("tar") or archive.endswith("bz2") or archive.endswith("gz"):
            rewrite_tar(archive)
 def on_showScriptSourceButton_clicked(self):
     """
     Private slot to show an editor window with the source code.
     """
     from Helpviewer import HelpUtilities
     
     tmpFileName = HelpUtilities.ensureUniqueFilename(
         os.path.join(QDir.tempPath(), "tmp-userscript.js"))
     if QFile.copy(self.__script.fileName(), tmpFileName):
         from QScintilla.MiniEditor import MiniEditor
         editor = MiniEditor(tmpFileName, "JavaScript", self)
         editor.show()
Beispiel #5
0
 def on_open_recent_action_triggered(self):
     action = self.sender()
     try:
         if os.path.isdir(action.data()):
             self.project_manager.set_project_folder(action.data())
         elif os.path.isfile(action.data()):
             self.setCursor(Qt.WaitCursor)
             self.add_files(FileOperator.uncompress_archives([action.data()], QDir.tempPath()))
             self.unsetCursor()
     except Exception as e:
         Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
         self.unsetCursor()
    def test_save_all(self):
        self.add_signal_to_form("esaver.complex")
        frame = self.form.signal_tab_controller.signal_frames[0]
        self.add_signal_to_form("ask.complex")
        frame2 = self.form.signal_tab_controller.signal_frames[1]

        frame.signal.changed = True
        frame.signal.filename = os.path.join(QDir.tempPath(), "sig1.complex")

        frame2.signal.changed = True
        frame2.signal.filename = os.path.join(QDir.tempPath(), "sig2.complex")

        self.assertFalse(os.path.isfile(frame.signal.filename))
        self.assertFalse(os.path.isfile(frame2.signal.filename))

        self.form.signal_tab_controller.save_all()

        self.assertTrue(os.path.isfile(frame.signal.filename))
        self.assertTrue(os.path.isfile(frame2.signal.filename))

        os.remove(frame.signal.filename)
        os.remove(frame2.signal.filename)
    def test_crop_and_save_signal(self):
        self.add_signal_to_form("esaver.complex")
        frame = self.form.signal_tab_controller.signal_frames[0]
        frame.ui.gvSignal.selection_area.end = 4000
        frame.ui.gvSignal.selection_area.start = 1000

        self.assertEqual(frame.ui.gvSignal.selection_area.end, 4000)
        self.assertEqual(frame.ui.gvSignal.selection_area.width, 3000)
        frame.ui.gvSignal.sel_area_start_end_changed.emit(1000, 4000)

        frame.ui.gvSignal.on_crop_action_triggered()
        self.assertEqual(frame.signal.num_samples, 3000)
        self.assertTrue(frame.signal.changed)

        frame.signal.filename = os.path.join(QDir.tempPath(), "sig.complex")
        if os.path.isfile(frame.signal.filename):
            os.remove(frame.signal.filename)

        self.assertFalse(os.path.isfile(frame.signal.filename))
        frame.ui.btnSaveSignal.click()
        self.form.close_signal_frame(frame)
        self.add_signal_to_form(os.path.join(QDir.tempPath(), "sig.complex"))
        self.assertEqual(self.form.signal_tab_controller.signal_frames[0].signal.num_samples, 3000)
        os.remove(os.path.join(QDir.tempPath(), "sig.complex"))
Beispiel #8
0
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(HgExportDialog, self).__init__(parent)
        self.setupUi(self)

        self.directoryPicker.setMode(E5PathPickerModes.DirectoryMode)

        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

        # set default values for directory and pattern
        self.patternEdit.setText("%b_%r_%h_%n_of_%N.diff")
        self.directoryPicker.setText(QDir.tempPath())
Beispiel #9
0
    def read_opened_filenames(self):
        if self.project_file is not None:
            tree = ET.parse(self.project_file)
            root = tree.getroot()
            file_names = []

            for ftag in root.findall("open_file"):
                pos = int(ftag.attrib["position"])
                filename = os.path.join(self.project_path, ftag.attrib["name"])
                file_names.insert(pos, filename)

            QApplication.setOverrideCursor(Qt.WaitCursor)
            file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
            QApplication.restoreOverrideCursor()
            return file_names
        return []
Beispiel #10
0
 def show_selector(self):
     if self.selector != self.stack.currentWidget():
         temp_dir = os.path.join(QDir.tempPath(), "ninja-ide")
         if not os.path.exists(temp_dir):
             os.mkdir(temp_dir)
         collected_data = []
         current = self.stack.currentIndex()
         for index in range(self.stack.count()):
             widget = self.stack.widget(index)
             if widget == self.selector:
                 continue
             pixmap = QWidget.grab(widget, widget.rect())
             path = os.path.join(temp_dir, "screen%s.png" % index)
             pixmap.save(path)
             collected_data.append((index, path))
         self.selector.set_model(collected_data)
         self._selector_ready()
     """
Beispiel #11
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent widget (QWidget)
     """
     super(HgExportDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.directoryButton.setIcon(UI.PixmapCache.getIcon("open.png"))
     
     self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
     
     self.__directoryCompleter = E5DirCompleter(self.directoryEdit)
     
     # set default values for directory and pattern
     self.patternEdit.setText("%b_%r_%h_%n_of_%N.diff")
     self.directoryEdit.setText(QDir.tempPath())
Beispiel #12
0
    def show_open_dialog(self, directory=False):
        dialog = FileOperator.get_open_dialog(directory_mode=directory, parent=self, name_filter="full")
        if dialog.exec_():
            try:
                file_names = dialog.selectedFiles()
                folders = [folder for folder in file_names if os.path.isdir(folder)]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    self.setCursor(Qt.WaitCursor)
                    file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
                    self.add_files(file_names)
                    self.unsetCursor()
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
                self.unsetCursor()
Beispiel #13
0
 def captureFrame(settings: QSettings,
                  source: str,
                  frametime: str,
                  thumbsize: QSize = None,
                  external: bool = False) -> QPixmap:
     if thumbsize is None:
         thumbsize = VideoService.config.thumbnails['INDEX']
     capres = QPixmap()
     img = QTemporaryFile(os.path.join(QDir.tempPath(), 'XXXXXX.jpg'))
     if img.open():
         imagecap = img.fileName()
         cmd = VideoService.findBackends(settings).ffmpeg
         tsize = '{0:d}x{1:d}'.format(thumbsize.width(), thumbsize.height())
         args = [
             '-hide_banner',
             '-ss',
             frametime,
             '-i',
             source,
             '-vframes',
             '1',
             '-s',
             tsize,
             '-y',
             imagecap,
         ]
         proc = VideoService.initProc()
         if proc.state() == QProcess.NotRunning:
             proc.start(cmd, args)
             proc.waitForFinished(-1)
             if proc.exitStatus() == QProcess.NormalExit and proc.exitCode(
             ) == 0:
                 capres = QPixmap(imagecap, 'JPG')
             if external:
                 painter = QPainter(capres)
                 painter.drawPixmap(0, 0,
                                    QPixmap(':/images/external.png', 'PNG'))
                 painter.end()
     img.remove()
     return capres
Beispiel #14
0
    def show_open_dialog(self, directory=False):
        fip = FileIconProvider()
        self.dialog = QFileDialog(self)
        self.dialog.setIconProvider(fip)
        self.dialog.setDirectory(FileOperator.RECENT_PATH)
        self.dialog.setWindowTitle("Open Folder")
        if directory:
            self.dialog.setFileMode(QFileDialog.Directory)
        else:
            self.dialog.setFileMode(QFileDialog.ExistingFiles)
            self.dialog.setNameFilter(
                "All files (*);;Complex (*.complex);;Complex16 unsigned (*.complex16u);;Complex16 signed (*.complex16s);;Wave (*.wav);;Protocols (*.proto);;"
                "Fuzzprofiles (*.fuzz);;Tar Archives (*.tar *.tar.gz *.tar.bz2);;Zip Archives (*.zip)"
            )

        self.dialog.setOptions(QFileDialog.DontResolveSymlinks)
        self.dialog.setViewMode(QFileDialog.Detail)

        if self.dialog.exec_():
            try:
                file_names = self.dialog.selectedFiles()
                folders = [
                    folder for folder in file_names if os.path.isdir(folder)
                ]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    file_names = FileOperator.uncompress_archives(
                        file_names, QDir.tempPath())
                    self.add_files(file_names)
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e),
                                     traceback.format_exc())
                self.ui.progressBar.hide()
                QApplication.restoreOverrideCursor()
    def loadProject(self, filename):
        self.default_path = filename[0:-9]  # - /Site.qml
        if self.reloadProject(filename):
            # create temp dir for undo redo
            tempPath = self.site.source_path[self.site.source_path.rfind("/") +
                                             1:]
            temp = QDir(os.path.join(QDir.tempPath(), "FlatSiteBuilder"))
            temp.mkdir(tempPath)
            temp.cd(tempPath)
            temp.mkdir("pages")
            temp.mkdir("posts")

            # in case these subfolders were empty and not published to github
            dir = QDir(self.site.source_path)
            dir.mkdir("pages")
            dir.mkdir("posts")
            dir.mkdir("assets")
            dir.cd("assets")
            dir.mkdir("images")
            return True
        else:
            return False
Beispiel #16
0
    def display_downloaded_content(self):
        """Open downloaded non-html content in a separate application.

        Called when an unsupported content type is finished downloading.
        """
        debug("displaying downloaded content from {}".format(self.reply.url()))

        file_path = (QDir.toNativeSeparators(QDir.tempPath() + "/XXXXXX_" +
                                             self.content_filename))
        myfile = QTemporaryFile(file_path)
        myfile.setAutoRemove(False)
        if myfile.open():
            myfile.write(self.reply.readAll())
            myfile.close()
            subprocess.Popen([(self.config.get("content_handlers").get(
                str(self.content_type))),
                              myfile.fileName()])

            # Sometimes downloading files opens an empty window.
            # So if the current window has no URL, close it.
            if (str(self.url().toString()) in ('', 'about:blank')):
                self.close()
Beispiel #17
0
def sendLog():
    config.logger.info("util:sendLog()")
    from email import encoders, generator
    from email.mime.base import MIMEBase
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    message = MIMEMultipart()
    if config.app_window.plus_email is not None:
        message['From'] = config.app_window.plus_email
    message["To"] = "{}@{}".format(config.log_file_account,
                                   config.log_file_domain)
    message["Subject"] = "artisan.plus client log"
    message.attach(
        MIMEText(
            "Please find attached the artisan.plus log file written by Artisan!\n--\n",
            "plain"))
    with open(config.log_file_path, "rb") as attachment:
        # Add file as application/octet-stream
        # Email client can usually download this automatically as attachment
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
    # Encode file in ASCII characters to send by email
    encoders.encode_base64(part)
    # Add header as key/value pair to attachment part
    part.add_header(
        "Content-Disposition",
        "attachment; filename= {}{}".format(config.log_file, ".log"))
    # Add attachment to message and convert message to string
    message.attach(part)
    # Save message to file tmp file
    tmpfile = QDir(QDir.tempPath()).filePath("plus-log.eml")
    try:
        os.remove(tmpfile)
    except OSError:
        pass
    with open(tmpfile, 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(message)
    QDesktopServices.openUrl(QUrl.fromLocalFile(tmpfile))
Beispiel #18
0
    def test_ask_fsk_psk_modulation(self):
        modulations = ["ASK", "FSK", "PSK"]

        for i, modulation in enumerate(modulations):
            modulator = Modulator(modulation)
            tmp_dir = QDir.tempPath()
            filename = "{0}_mod.complex".format(modulation)
            filename = os.path.join(tmp_dir, filename)
            modulator.modulation_type = i
            modulator.samples_per_bit = self.samples_per_bit

            if modulation == "ASK":
                modulator.param_for_zero = 0
                modulator.param_for_one = 100
            elif modulation == "FSK":
                modulator.param_for_zero = 1000
                modulator.param_for_one = 2500
            elif modulation == "PSK":
                modulator.param_for_zero = 0
                modulator.param_for_one = 180

            modulator.modulate(self.modulation_data, self.pause)
            modulator.modulated_samples.tofile(filename)

            signal = Signal(filename, modulation)
            signal.modulation_type = i
            signal.bit_len = self.samples_per_bit
            if modulation == "ASK":
                signal.qad_center = 0.5
            elif modulation == "FSK":
                signal.qad_center = 0.0097
            elif modulation == "PSK":
                signal.qad_center = 0
            self.assertEqual(signal.num_samples, self.total_samples, msg=modulation)
            pa = ProtocolAnalyzer(signal)
            pa.get_protocol_from_signal()
            self.assertEqual(1, len(pa.messages), msg=modulation)
            self.assertEqual(self.modulation_data, pa.messages[0].plain_bits, msg=modulation)
Beispiel #19
0
    def test_ask_fsk_psk_modulation(self):
        modulations = ["ASK", "FSK", "PSK"]

        for i, modulation in enumerate(modulations):
            modulator = Modulator(modulation)
            tmp_dir = QDir.tempPath()
            filename = "{0}_mod.complex".format(modulation)
            filename = os.path.join(tmp_dir, filename)
            modulator.modulation_type = i
            modulator.samples_per_bit = self.samples_per_bit

            if modulation == "ASK":
                modulator.param_for_zero = 0
                modulator.param_for_one = 100
            elif modulation == "FSK":
                modulator.param_for_zero = 1000
                modulator.param_for_one = 2500
            elif modulation == "PSK":
                modulator.param_for_zero = 0
                modulator.param_for_one = 180

            modulator.modulate(self.modulation_data, self.pause)
            modulator.modulated_samples.tofile(filename)

            signal = Signal(filename, modulation)
            signal.modulation_type = i
            signal.bit_len = self.samples_per_bit
            if modulation == "ASK":
                signal.qad_center = 0.5
            elif modulation == "FSK":
                signal.qad_center = 0.0097
            elif modulation == "PSK":
                signal.qad_center = 0
            self.assertEqual(signal.num_samples, self.total_samples, msg=modulation)
            pa = ProtocolAnalyzer(signal)
            pa.get_protocol_from_signal()
            self.assertEqual(1, len(pa.messages), msg=modulation)
            self.assertEqual(self.modulation_data, pa.messages[0].plain_bits, msg=modulation)
Beispiel #20
0
    def test_uncompress_archives(self):
        temp_dir = tempfile.gettempdir()
        os.chdir(temp_dir)

        with tarfile.open("test.tar.gz", "w:gz") as tar:
            for name in ["1.complex", "2.complex", "3.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                tar.add(name)

        with ZipFile('test.zip', 'w') as zip:
            for name in ["4.complex", "5.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                zip.write(name)

        QTest.qWait(10)
        form = MainController()
        app.processEvents()
        QTest.qWait(10)
        form.add_files(FileOperator.uncompress_archives(["test.tar.gz", "test.zip"], QDir.tempPath()))
        self.assertEqual(len(form.signal_tab_controller.signal_frames), 5)

        tar_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        form.signal_tab_controller.signal_frames[0].signal._fulldata = np.ones(5, dtype=np.complex64)
        form.signal_tab_controller.signal_frames[0].signal.changed = True
        form.signal_tab_controller.signal_frames[0].ui.btnSaveSignal.click()

        tar_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        self.assertNotEqual(tar_md5, tar_md5_after_save)

        zip_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        form.signal_tab_controller.signal_frames[4].signal._fulldata = np.ones(5, dtype=np.complex64)
        form.signal_tab_controller.signal_frames[4].signal.changed = True
        form.signal_tab_controller.signal_frames[4].ui.btnSaveSignal.click()

        zip_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.assertNotEqual(zip_md5, zip_md5_after_save)
Beispiel #21
0
    def _downloadAndUnzip(self, itemid):
        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimum(0)
        self.progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.progess_message_bar = self.iface.messageBar().createMessage(
            tr("Downloading..."))
        self.progess_message_bar.layout().addWidget(self.progress_bar)

        self.iface.messageBar().pushWidget(self.progess_message_bar, Qgis.Info)

        # FIXME: the signal is always emitted
        # self.iface.messageBar().widgetRemoved.connect(self.widget_removed)

        def extract_data(tmpPath, itemid):
            LOG.debug("Extract data")
            try:
                targetFolder = DataCatalogueClient.folderForDataItem(itemid)
                QDir(targetFolder).removeRecursively()
                unzip.unzip(tmpPath, targetFolder)
                QFile(tmpPath).remove()
            except Exception as e:
                LOG.debug("Error on extracting data %s" % e)

        url = f"{self.url}/content/items/{itemid}/data"
        tmpDir = QDir.tempPath()
        filename = f"{itemid}.zip"
        tmpPath = QDir.cleanPath(os.path.join(tmpDir, filename))
        loop = QEventLoop()
        self.downloader = QgsFileDownloader(QUrl(url), tmpPath)
        self.downloader.downloadProgress.connect(self.update_progress)
        self.downloader.downloadCompleted.connect(self.download_finished)
        self.downloader.downloadCompleted.connect(
            partial(extract_data, tmpPath, itemid))
        self.downloader.downloadCanceled.connect(self.download_canceled)
        self.downloader.downloadExited.connect(loop.quit)
        loop.exec_()
Beispiel #22
0
    def show_open_dialog(self, directory=False):
        fip = FileIconProvider()
        self.dialog = QFileDialog(self)
        self.dialog.setIconProvider(fip)
        self.dialog.setDirectory(FileOperator.RECENT_PATH)
        self.dialog.setWindowTitle("Open Folder")
        if directory:
            self.dialog.setFileMode(QFileDialog.Directory)
        else:
            self.dialog.setFileMode(QFileDialog.ExistingFiles)
            self.dialog.setNameFilter(
                "All files (*);;Complex (*.complex);;Complex16 unsigned (*.complex16u);;Complex16 signed (*.complex16s);;Wave (*.wav);;Protocols (*.proto);;"
                "Fuzzprofiles (*.fuzz);;Tar Archives (*.tar *.tar.gz *.tar.bz2);;Zip Archives (*.zip)")

        self.dialog.setOptions(QFileDialog.DontResolveSymlinks)
        self.dialog.setViewMode(QFileDialog.Detail)

        if self.dialog.exec_():
            try:
                file_names = self.dialog.selectedFiles()
                folders = [folder for folder in file_names if os.path.isdir(folder)]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    self.setCursor(Qt.WaitCursor)
                    file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
                    self.add_files(file_names)
                    self.unsetCursor()
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
                QApplication.instance().restoreOverrideCursor()
Beispiel #23
0
 def capture(source: str, frametime: str, thumbsize: ThumbSize = ThumbSize.INDEX, external: bool = False) -> QPixmap:
     capres = QPixmap()
     img = QTemporaryFile(os.path.join(QDir.tempPath(), 'XXXXXX.jpg'))
     if img.open():
         imagecap = img.fileName()
         size = thumbsize.value
         backend, _, _ = VideoService.initBackends()
         args = '-hide_banner -ss %s -i "%s" -vframes 1 -s %ix%i -v 16 -y "%s"' % (frametime, source, size.width(),
                                                                                   size.height(), imagecap)
         proc = VideoService.initProc()
         proc.setProcessChannelMode(QProcess.MergedChannels)
         if proc.state() == QProcess.NotRunning:
             if os.getenv('DEBUG', False):
                 logging.getLogger(__name__).info('"%s %s"' % (backend, args))
             proc.start(backend, shlex.split(args))
             proc.waitForFinished(-1)
             if proc.exitStatus() == QProcess.NormalExit and proc.exitCode() == 0:
                 capres = QPixmap(imagecap, 'JPG')
             if external:
                 painter = QPainter(capres)
                 painter.drawPixmap(0, 0, QPixmap(':/images/external.png', 'PNG'))
                 painter.end()
     img.remove()
     return capres
    def test_sniff(self):
        # add a signal so we can use it
        self.add_signal_to_form("esaver.complex")
        logger.debug("Added signalfile")
        QApplication.instance().processEvents()

        # Move with encoding to generator
        generator_frame = self.form.generator_tab_controller
        generator_frame.ui.cbViewType.setCurrentIndex(0)
        item = generator_frame.tree_model.rootItem.children[0].children[0]
        index = generator_frame.tree_model.createIndex(0, 0, item)
        mimedata = generator_frame.tree_model.mimeData([index])
        generator_frame.table_model.dropMimeData(mimedata, 1, -1, -1, generator_frame.table_model.createIndex(0, 0))
        QApplication.instance().processEvents()
        self.assertEqual(generator_frame.table_model.rowCount(), 3)

        QApplication.instance().processEvents()
        sniff_dialog = self.__get_sniff_dialog()
        self.assertEqual(sniff_dialog.device.name, NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)
        sniff_dialog.ui.comboBox_sniff_viewtype.setCurrentIndex(0)

        port = self.__get_free_port()

        sniff_dialog.device.set_server_port(port)
        generator_frame.network_sdr_plugin.client_port = port
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()

        QTest.qWait(self.SEND_RECV_TIMEOUT)
        received_msgs = sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().split("\n")
        orig_msgs = generator_frame.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        target_file = os.path.join(QDir.tempPath(), "sniff_file.txt")
        self.assertFalse(os.path.isfile(target_file))

        sniff_dialog.ui.btnClear.click()
        QApplication.instance().processEvents()
        sniff_dialog.ui.lineEdit_sniff_OutputFile.setText(target_file)
        sniff_dialog.ui.lineEdit_sniff_OutputFile.editingFinished.emit()
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        self.assertFalse(sniff_dialog.ui.btnAccept.isEnabled())

        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        os.remove(target_file)

        sniff_dialog.ui.btnStop.click()
        self.assertFalse(sniff_dialog.ui.btnStop.isEnabled())

        self.__close_dialog(sniff_dialog)
Beispiel #25
0
    def test_sniff(self):
        # add a signal so we can use it
        self.add_signal_to_form("esaver.complex")
        logger.debug("Added signalfile")
        QApplication.instance().processEvents()

        self.__add_first_signal_to_generator()
        generator_frame = self.form.generator_tab_controller
        self.assertEqual(generator_frame.table_model.rowCount(), 3)

        QApplication.instance().processEvents()
        sniff_dialog = self.__get_sniff_dialog()
        sniff_dialog.ui.checkBox_sniff_Timestamp.setChecked(False)
        self.assertEqual(sniff_dialog.device.name,
                         NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)
        sniff_dialog.ui.comboBox_sniff_viewtype.setCurrentIndex(0)

        port = self.__get_free_port()

        sniff_dialog.device.set_server_port(port)
        generator_frame.network_sdr_plugin.client_port = port
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()

        QTest.qWait(self.SEND_RECV_TIMEOUT)
        received_msgs = sniff_dialog.ui.txtEd_sniff_Preview.toPlainText(
        ).split("\n")
        orig_msgs = generator_frame.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        sniff_dialog.ui.checkBox_sniff_Timestamp.click()
        self.assertTrue(
            sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))
        sniff_dialog.ui.checkBox_sniff_Timestamp.click()
        self.assertFalse(
            sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))

        target_file = os.path.join(QDir.tempPath(), "sniff_file.txt")
        self.assertFalse(os.path.isfile(target_file))

        sniff_dialog.ui.btnClear.click()
        QApplication.instance().processEvents()
        sniff_dialog.ui.lineEdit_sniff_OutputFile.setText(target_file)
        sniff_dialog.ui.lineEdit_sniff_OutputFile.editingFinished.emit()
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        self.assertFalse(sniff_dialog.ui.btnAccept.isEnabled())

        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(
                    orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        os.remove(target_file)

        sniff_dialog.ui.btnStop.click()
        self.assertFalse(sniff_dialog.ui.btnStop.isEnabled())

        self.__close_dialog(sniff_dialog)
Beispiel #26
0
    def __init__(self, filename: str, name: str, wav_is_qad_demod=False,
                 modulation: str = None, sample_rate: float = 1e6, parent=None):
        super().__init__(parent)
        self.__name = name
        self.__tolerance = 5
        self.__bit_len = 100
        self._qad = None
        self.__qad_center = 0
        self._noise_threshold = 0
        self.__sample_rate = sample_rate
        self.noise_min_plot = 0
        self.noise_max_plot = 0
        self.block_protocol_update = False

        self.auto_detect_on_modulation_changed = True
        self.wav_mode = filename.endswith(".wav")
        self.__changed = False
        self.qad_demod_file_loaded = wav_is_qad_demod
        if modulation is None:
            modulation = "FSK"
        self.__modulation_type = self.MODULATION_TYPES.index(modulation)
        self.__parameter_cache = {mod: {"qad_center": None, "bit_len": None} for mod in self.MODULATION_TYPES}

        if len(filename) > 0:
            # Daten auslesen
            if not self.wav_mode:
                if not filename.endswith(".coco"):
                    if filename.endswith(".complex16u"):
                        # two 8 bit unsigned integers
                        raw = np.fromfile(filename, dtype=[('r', np.uint8), ('i', np.uint8)])
                        self._fulldata = np.empty(raw.shape[0], dtype=np.complex64)
                        self._fulldata.real = (raw['r'] / 127.5) - 1.0
                        self._fulldata.imag = (raw['i'] / 127.5) - 1.0
                    elif filename.endswith(".complex16s"):
                        # two 8 bit signed integers
                        raw = np.fromfile(filename, dtype=[('r', np.int8), ('i', np.int8)])
                        self._fulldata = np.empty(raw.shape[0], dtype=np.complex64)
                        self._fulldata.real = (raw['r'] + 0.5) / 127.5
                        self._fulldata.imag = (raw['i'] + 0.5) / 127.5
                    else:
                        self._fulldata = np.fromfile(filename, dtype=np.complex64)  # Uncompressed
                else:
                    obj = tarfile.open(filename, "r")
                    members = obj.getmembers()
                    obj.extract(members[0], QDir.tempPath())
                    extracted_filename = os.path.join(QDir.tempPath(), obj.getnames()[0])
                    self._fulldata = np.fromfile(extracted_filename, dtype=np.complex64)
                    os.remove(extracted_filename)

                self._fulldata = np.ascontiguousarray(self._fulldata, dtype=np.complex64)  # type: np.ndarray
            else:
                f = wave.open(filename, "r")
                n = f.getnframes()
                unsigned_bytes = struct.unpack('<{0:d}B'.format(n), f.readframes(n))
                if not self.qad_demod_file_loaded:
                    # Complex To Real WAV File load
                    self._fulldata = np.empty(n, dtype=np.complex64, order="C")
                    self._fulldata.real = np.multiply(1/256, np.subtract(unsigned_bytes, 128))
                    self._fulldata.imag = [-1/128] * n
                else:
                    self._fulldata = np.multiply(1 / 256, np.subtract(unsigned_bytes, 128).astype(np.int8)).astype(
                        np.float32)
                    self._fulldata = np.ascontiguousarray(self._fulldata, dtype=np.float32)

                f.close()

            self.filename = filename

            if not self.qad_demod_file_loaded:
                self.noise_threshold = self.calc_noise_threshold(int(0.99 * self.num_samples), self.num_samples)

        else:
            self.filename = ""
Beispiel #27
0
    def test_generation(self):
        """
        Complex test including much functionality
        1) Load a Signal
        2) Set Decoding in Compareframe
        3) Move with encoding to Generator
        4) Generate datafile
        5) Read datafile and compare with original signal

        """
        # Load a Signal
        self.form.add_signalfile(get_path_for_data_file("ask.complex"))
        sframe = self.form.signal_tab_controller.signal_frames[0]
        sframe.ui.cbModulationType.setCurrentIndex(0) # ASK
        sframe.ui.spinBoxInfoLen.setValue(295)
        sframe.ui.spinBoxCenterOffset.setValue(-0.1667)
        sframe.refresh()

        proto = "1011001001011011011011011011011011001000000"
        self.assertTrue(sframe.ui.txtEdProto.toPlainText().startswith(proto))

        # Set Decoding
        self.form.ui.tabWidget.setCurrentIndex(1)
        cfc = self.form.compare_frame_controller
        cfc.ui.cbDecoding.setCurrentIndex(1) # NRZ-I
        proto_inv = cfc.proto_analyzer.decoded_proto_bits_str[0]
        self.assertTrue(self.__is_inv_proto(proto, proto_inv))

        # Move with encoding to generator
        gframe = self.form.generator_tab_controller
        gframe.ui.cbViewType.setCurrentIndex(0)
        item = gframe.tree_model.rootItem.children[0].children[0]
        index = gframe.tree_model.createIndex(0, 0, item)
        rect = gframe.ui.treeProtocols.visualRect(index)
        QTest.mousePress(gframe.ui.treeProtocols.viewport(), Qt.LeftButton, pos = rect.center())
        self.assertEqual(gframe.ui.treeProtocols.selectedIndexes()[0], index)
        mimedata = gframe.tree_model.mimeData(gframe.ui.treeProtocols.selectedIndexes())
        gframe.table_model.dropMimeData(mimedata, 1, -1, -1, gframe.table_model.createIndex(0, 0))
        self.assertEqual(proto_inv, gframe.table_model.display_data[0])
        self.assertNotEqual(proto, gframe.table_model.display_data[0])

        # Generate Datafile
        modulator = gframe.modulators[0]
        modulator.modulation_type = 0
        modulator.samples_per_bit = 295
        modulated_data = gframe.modulate_data()
        filename = os.path.join(QDir.tempPath(), "generator_test.complex")
        modulated_data.tofile(filename)

        # Reload datafile and see if bits match
        self.form.add_signalfile(filename)
        sframe = self.form.signal_tab_controller.signal_frames[1]
        self.assertEqual(sframe.ui.lineEditSignalName.text(), "generator_test")
        sframe.ui.cbSignalView.setCurrentIndex(1)  # ASK
        sframe.ui.spinBoxInfoLen.setValue(295)
        sframe.ui.spinBoxInfoLen.editingFinished.emit()
        sframe.ui.spinBoxCenterOffset.setValue(0.1)
        sframe.ui.spinBoxCenterOffset.editingFinished.emit()
        sframe.ui.spinBoxTolerance.setValue(6)
        sframe.ui.spinBoxTolerance.editingFinished.emit()
        sframe.refresh()

        gen_proto = sframe.ui.txtEdProto.toPlainText()
        gen_proto = gen_proto[:gen_proto.index(" ")]
        self.assertTrue(proto.startswith(gen_proto))
Beispiel #28
0
    def test_project_dialog(self):
        frequency = 1e9
        sample_rate = 10e9
        bandwidth = 10
        gain = 42
        descr = "URH rockz."

        dialog = ProjectDialog(project_manager=self.form.project_manager, parent=self.form)

        dialog.ui.spinBoxFreq.setValue(frequency)
        self.assertEqual(dialog.freq, frequency)

        dialog.ui.spinBoxSampleRate.setValue(sample_rate)
        self.assertEqual(dialog.sample_rate, sample_rate)

        dialog.ui.spinBoxBandwidth.setValue(bandwidth)
        self.assertEqual(dialog.bandwidth, bandwidth)

        dialog.ui.spinBoxGain.setValue(gain)
        self.assertEqual(dialog.gain, gain)

        dialog.ui.txtEdDescription.setPlainText(descr)
        self.assertEqual(dialog.description, descr)

        dialog.ui.lineEditBroadcastAddress.setText("abcd")
        dialog.ui.lineEditBroadcastAddress.textEdited.emit("abcd")
        self.assertEqual(dialog.broadcast_address_hex, "abcd")

        if len(dialog.participants) == 0:
            dialog.ui.btnAddParticipant.click()
            self.assertEqual(len(dialog.participants), 1)

        model = dialog.participant_table_model
        model.setData(model.index(0, 0), "Testing")
        model.setData(model.index(0, 1), "T")
        model.setData(model.index(0, 2), 5)
        model.setData(model.index(0, 3), 0)
        model.setData(model.index(0, 4), "aaaa")
        participant = dialog.participants[0]
        self.assertEqual(participant.name, "Testing")
        self.assertEqual(participant.shortname, "T")
        self.assertEqual(participant.color_index, 5)
        self.assertEqual(participant.relative_rssi, 0)
        self.assertEqual(participant.address_hex, "aaaa")

        num_participants = len(dialog.participants)
        dialog.ui.btnAddParticipant.click()
        dialog.ui.btnAddParticipant.click()
        dialog.ui.btnAddParticipant.click()
        self.assertEqual(len(dialog.participants), num_participants + 3)

        dialog.ui.btnRemoveParticipant.click()
        dialog.ui.btnRemoveParticipant.click()
        dialog.ui.btnRemoveParticipant.click()
        self.assertEqual(len(dialog.participants), num_participants)

        test_path = os.path.join(QDir.tempPath(), "urh_test")

        dialog.ui.lineEdit_Path.setText(test_path)
        dialog.ui.lineEdit_Path.textEdited.emit(test_path)
        self.assertEqual(dialog.path, test_path)
        dialog.on_button_box_accepted()

        self.form.ui.tabWidget.setCurrentWidget(self.form.ui.tab_protocol)
        self.form.compare_frame_controller.ui.tabWidget.setCurrentWidget(
            self.form.compare_frame_controller.ui.tab_participants)
        self.assertGreater(self.form.compare_frame_controller.participant_list_model.rowCount(), 0)

        self.assertTrue(os.path.isdir(test_path))

        self.form.project_manager.from_dialog(dialog)

        dialog = ProjectDialog(project_manager=self.form.project_manager, parent=self.form, new_project=False)
        self.assertEqual(dialog.ui.spinBoxFreq.value(), frequency)
        self.assertEqual(dialog.ui.spinBoxSampleRate.value(), sample_rate)
        self.assertEqual(dialog.ui.spinBoxBandwidth.value(), bandwidth)
        self.assertEqual(dialog.ui.spinBoxGain.value(), gain)
        self.assertEqual(dialog.ui.txtEdDescription.toPlainText(), descr)
        self.assertFalse(dialog.ui.lineEdit_Path.isEnabled())
Beispiel #29
0
 def __add_urls_to_group(self, file_urls, group_id=0):
     local_files = [file_url.toLocalFile() for file_url in file_urls if file_url.isLocalFile()]
     if len(local_files) > 0:
         self.add_files(FileOperator.uncompress_archives(local_files, QDir.tempPath()), group_id=group_id)
    def test_uncompress_archives(self):
        temp_dir = tempfile.gettempdir()
        os.chdir(temp_dir)

        with tarfile.open("test.tar.gz", "w:gz") as tar:
            for name in ["1.complex", "2.complex", "3.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                tar.add(name)

        with ZipFile('test.zip', 'w') as zip:
            for name in ["4.complex", "5.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                zip.write(name)

        QApplication.instance().processEvents()
        QTest.qWait(self.WAIT_TIMEOUT_BEFORE_NEW)
        self.form.add_files(FileOperator.uncompress_archives(["test.tar.gz", "test.zip"], QDir.tempPath()))
        self.assertEqual(len(self.form.signal_tab_controller.signal_frames), 5)

        tar_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        self.form.signal_tab_controller.signal_frames[0].signal._fulldata = np.ones(5, dtype=np.complex64)
        self.form.signal_tab_controller.signal_frames[0].signal.changed = True
        self.form.signal_tab_controller.signal_frames[0].ui.btnSaveSignal.click()

        tar_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        self.assertNotEqual(tar_md5, tar_md5_after_save)

        zip_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.form.signal_tab_controller.signal_frames[4].signal._fulldata = np.ones(5, dtype=np.complex64)
        self.form.signal_tab_controller.signal_frames[4].signal.changed = True
        self.form.signal_tab_controller.signal_frames[4].ui.btnSaveSignal.click()

        zip_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.assertNotEqual(zip_md5, zip_md5_after_save)
    def test_sniff(self):
        # add a signal so we can use it
        self.add_signal_to_form("esaver.complex")
        logger.debug("Added signalfile")
        QApplication.instance().processEvents()

        # Move with encoding to generator
        generator_frame = self.form.generator_tab_controller
        generator_frame.ui.cbViewType.setCurrentIndex(0)
        item = generator_frame.tree_model.rootItem.children[0].children[0]
        index = generator_frame.tree_model.createIndex(0, 0, item)
        mimedata = generator_frame.tree_model.mimeData([index])
        generator_frame.table_model.dropMimeData(
            mimedata, 1, -1, -1, generator_frame.table_model.createIndex(0, 0))
        QApplication.instance().processEvents()
        self.assertEqual(generator_frame.table_model.rowCount(), 3)

        QApplication.instance().processEvents()
        sniff_dialog = self.__get_sniff_dialog()
        self.assertEqual(sniff_dialog.device.name,
                         NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)

        port = self.__get_free_port()

        sniff_dialog.device.set_server_port(port)
        generator_frame.network_sdr_plugin.client_port = port
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()

        QTest.qWait(self.SEND_RECV_TIMEOUT)
        received_msgs = sniff_dialog.ui.txtEd_sniff_Preview.toPlainText(
        ).split("\n")
        orig_msgs = generator_frame.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        target_file = os.path.join(QDir.tempPath(), "sniff_file")
        self.assertFalse(os.path.isfile(target_file))

        sniff_dialog.ui.btnClear.click()
        QApplication.instance().processEvents()
        sniff_dialog.ui.lineEdit_sniff_OutputFile.setText(target_file)
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        self.assertFalse(sniff_dialog.ui.btnAccept.isEnabled())

        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(
                    orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        os.remove(target_file)

        sniff_dialog.ui.btnStop.click()
        self.assertFalse(sniff_dialog.ui.btnStop.isEnabled())

        self.__close_dialog(sniff_dialog)
Beispiel #32
0
    def test_sniff(self):
        # Move with encoding to generator
        gframe = self.form.generator_tab_controller
        gframe.ui.cbViewType.setCurrentIndex(0)
        item = gframe.tree_model.rootItem.children[0].children[0]
        index = gframe.tree_model.createIndex(0, 0, item)
        rect = gframe.ui.treeProtocols.visualRect(index)
        QTest.mousePress(gframe.ui.treeProtocols.viewport(),
                         Qt.LeftButton,
                         pos=rect.center())
        self.assertEqual(gframe.ui.treeProtocols.selectedIndexes()[0], index)
        mimedata = gframe.tree_model.mimeData(
            gframe.ui.treeProtocols.selectedIndexes())
        gframe.table_model.dropMimeData(mimedata, 1, -1, -1,
                                        gframe.table_model.createIndex(0, 0))
        self.assertEqual(gframe.table_model.rowCount(), 3)

        self.sniff_dialog.ui.cbDevice.setCurrentText(
            NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)
        self.assertEqual(self.sniff_dialog.device.name,
                         NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)

        self.sniff_dialog.device.set_server_port(4444)
        gframe.network_sdr_plugin.client_port = 4444
        self.sniff_dialog.ui.btnStart.click()
        app.processEvents()
        gframe.ui.btnNetworkSDRSend.click()
        app.processEvents()

        QTest.qWait(500)
        received_msgs = self.sniff_dialog.ui.txtEd_sniff_Preview.toPlainText(
        ).split("\n")
        orig_msgs = gframe.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        self.sniff_dialog.ui.btnStop.click()
        target_file = os.path.join(QDir.tempPath(), "sniff_file")
        self.assertFalse(os.path.isfile(target_file))

        self.sniff_dialog.ui.btnClear.click()
        app.processEvents()
        self.sniff_dialog.ui.lineEdit_sniff_OutputFile.setText(target_file)
        self.sniff_dialog.ui.btnStart.click()
        app.processEvents()
        self.assertFalse(self.sniff_dialog.ui.btnAccept.isEnabled())

        gframe.ui.btnNetworkSDRSend.click()
        app.processEvents()
        QTest.qWait(500)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(
                    orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        os.remove(target_file)
Beispiel #33
0
 def initializePage(self):
     className = self.field('className')
     self.headerLineEdit.setText(className.lower() + '.h')
     self.implementationLineEdit.setText(className.lower() + '.cpp')
     self.outputDirLineEdit.setText(QDir.toNativeSeparators(QDir.tempPath()))
Beispiel #34
0
def tempFolder():
    tempDir = os.path.join(unicode(QDir.tempPath()), 'qgis2web')
    if not QDir(tempDir).exists():
        QDir().mkpath(tempDir)

    return unicode(os.path.abspath(tempDir))
    def test_sniff(self):
        assert isinstance(self.form, MainController)
        # add a signal so we can use it
        self.add_signal_to_form("esaver.coco")
        logger.debug("Added signalfile")
        QApplication.instance().processEvents()

        self.__add_first_signal_to_generator()
        generator_frame = self.form.generator_tab_controller
        self.assertEqual(generator_frame.table_model.rowCount(), 3)

        QApplication.instance().processEvents()
        sniff_dialog = self.__get_sniff_dialog()

        sniff_dialog.sniff_settings_widget.ui.checkBoxAdaptiveNoise.click()
        self.assertTrue(sniff_dialog.sniffer.adaptive_noise)
        sniff_dialog.sniff_settings_widget.ui.btn_sniff_use_signal.click()
        self.assertEqual(
            sniff_dialog.sniff_settings_widget.ui.spinbox_sniff_BitLen.value(),
            self.form.signal_tab_controller.signal_frames[0].signal.bit_len)

        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.setChecked(
            False)
        self.assertEqual(sniff_dialog.device.name,
                         NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)
        sniff_dialog.sniff_settings_widget.ui.comboBox_sniff_viewtype.setCurrentIndex(
            0)

        port = self.get_free_port()

        sniff_dialog.device.set_server_port(port)
        generator_frame.network_sdr_plugin.client_port = port
        sniff_dialog.ui.btnStart.click()

        for msg in generator_frame.table_model.protocol.messages:
            msg.pause = 500e3

        generator_frame.ui.btnNetworkSDRSend.click()

        time.sleep(2)
        QTest.qWait(100)
        received_msgs = sniff_dialog.ui.txtEd_sniff_Preview.toPlainText(
        ).split("\n")
        orig_msgs = generator_frame.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.click()
        self.assertTrue(
            sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.click()
        self.assertFalse(
            sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))

        n = self.form.compare_frame_controller.protocol_model.rowCount()
        sniff_dialog.protocol_accepted.emit(sniff_dialog.sniffer.messages)
        QTest.qWait(10)
        self.assertEqual(
            self.form.compare_frame_controller.protocol_model.rowCount(),
            n + 3)

        target_file = os.path.join(QDir.tempPath(), "sniff_file.txt")
        if os.path.isfile(target_file):
            os.remove(target_file)

        sniff_dialog.ui.btnClear.click()
        QApplication.instance().processEvents()
        sniff_dialog.sniff_settings_widget.ui.lineEdit_sniff_OutputFile.setText(
            target_file)
        sniff_dialog.sniff_settings_widget.ui.lineEdit_sniff_OutputFile.editingFinished.emit(
        )
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        self.assertFalse(sniff_dialog.ui.btnAccept.isEnabled())

        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(
                    orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        self.assertFalse(sniff_dialog.ui.btnStop.isEnabled())

        sniff_dialog.close()
Beispiel #36
0
    def __init__(self, jeName="JPEG Export", jeVersion="testing", parent=None):
        super(JEMainWindow, self).__init__(
            os.path.join(os.path.dirname(__file__), 'resources',
                         'jemainwindow.ui'), parent)

        self.__notifier = None

        # another instance already exist, exit
        if JEMainWindow.__IS_OPENED:
            self.close()
            return

        self.__accepted = False

        self.__timerPreview = 0  # timer used for preview update
        self.__timerResize = 0  # timer used for resize update

        self.__tmpDoc = None  # internal document used for export (not added to view)
        self.__tmpDocTgtNode = None
        self.__tmpDocPreview = None  # document used for preview (added to view)
        self.__tmpDocPreviewFileNode = None
        self.__tmpDocPreviewSrcNode = None

        self.__jeName = jeName
        self.__jeVersion = jeVersion

        self.__viewScrollbarH = None
        self.__viewScrollbarV = None
        self.__positionFull = None
        self.__positionCrop = None

        self.__doc = Krita.instance().activeDocument()
        self.__boundsSource = None
        self.__sizeTarget = None

        if self.__doc is None:
            # no document opened: cancel plugin
            QMessageBox.warning(
                QWidget(), f"{jeName}",
                i18n(
                    "There's no active document: <i>JPEG Export</i> plugin only works with opened documents"
                ))
            self.close()
            return

        JEMainWindow.__IS_OPENED = True

        basename, ext = os.path.splitext(
            os.path.basename(self.__doc.fileName()))
        self.__tmpExportPreviewFile = os.path.join(
            QDir.tempPath(), f'{basename} (JPEG Export Preview).jpeg')
        self.__tmpExportFile = os.path.join(
            QDir.tempPath(),
            f'jpegexport-{QUuid.createUuid().toString(QUuid.Id128)}.jpeg')
        self.__docFileName = self.__doc.fileName()

        self.__notifier = Krita.instance().notifier()
        self.__notifier.imageClosed.connect(self.__imageClosed)

        self.setModal(False)
        self.setWindowTitle(i18n(f'{jeName} v{jeVersion}'))
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint
                            | Qt.WindowStaysOnTopHint)

        self.__initialiseUi()
        self.__initialiseDoc()

        self.show()
Beispiel #37
0
    def test_sniff(self):
        assert isinstance(self.form, MainController)
        # add a signal so we can use it
        self.add_signal_to_form("esaver.coco")
        logger.debug("Added signalfile")
        QApplication.instance().processEvents()

        self.__add_first_signal_to_generator()
        generator_frame = self.form.generator_tab_controller
        self.assertEqual(generator_frame.table_model.rowCount(), 3)

        QApplication.instance().processEvents()
        sniff_dialog = self.__get_sniff_dialog()

        sniff_dialog.sniff_settings_widget.ui.checkBoxAdaptiveNoise.click()
        self.assertTrue(sniff_dialog.sniffer.adaptive_noise)
        sniff_dialog.sniff_settings_widget.ui.btn_sniff_use_signal.click()
        self.assertEqual(sniff_dialog.sniff_settings_widget.ui.spinbox_sniff_BitLen.value(),
                         self.form.signal_tab_controller.signal_frames[0].signal.bit_len)

        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.setChecked(False)
        self.assertEqual(sniff_dialog.device.name, NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)
        sniff_dialog.sniff_settings_widget.ui.comboBox_sniff_viewtype.setCurrentIndex(0)

        port = self.get_free_port()

        sniff_dialog.device.set_server_port(port)
        generator_frame.network_sdr_plugin.client_port = port
        sniff_dialog.ui.btnStart.click()

        for msg in generator_frame.table_model.protocol.messages:
            msg.pause = 500e3

        generator_frame.ui.btnNetworkSDRSend.click()

        time.sleep(2)
        QTest.qWait(100)
        received_msgs = sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().split("\n")
        orig_msgs = generator_frame.table_model.protocol.plain_bits_str

        self.assertEqual(len(received_msgs), len(orig_msgs))
        for received, orig in zip(received_msgs, orig_msgs):
            pad = 0 if len(orig) % 8 == 0 else 8 - len(orig) % 8
            self.assertEqual(received, orig + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.click()
        self.assertTrue(sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))
        sniff_dialog.sniff_settings_widget.ui.checkBox_sniff_Timestamp.click()
        self.assertFalse(sniff_dialog.ui.txtEd_sniff_Preview.toPlainText().startswith("["))

        n = self.form.compare_frame_controller.protocol_model.rowCount()
        sniff_dialog.protocol_accepted.emit(sniff_dialog.sniffer.messages)
        QTest.qWait(10)
        self.assertEqual(self.form.compare_frame_controller.protocol_model.rowCount(), n + 3)

        target_file = os.path.join(QDir.tempPath(), "sniff_file.txt")
        if os.path.isfile(target_file):
            os.remove(target_file)

        sniff_dialog.ui.btnClear.click()
        QApplication.instance().processEvents()
        sniff_dialog.sniff_settings_widget.ui.lineEdit_sniff_OutputFile.setText(target_file)
        sniff_dialog.sniff_settings_widget.ui.lineEdit_sniff_OutputFile.editingFinished.emit()
        sniff_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        self.assertFalse(sniff_dialog.ui.btnAccept.isEnabled())

        generator_frame.ui.btnNetworkSDRSend.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        with open(target_file, "r") as f:
            for i, line in enumerate(f):
                pad = 0 if len(orig_msgs[i]) % 8 == 0 else 8 - len(orig_msgs[i]) % 8
                self.assertEqual(line.strip(), orig_msgs[i] + "0" * pad)

        sniff_dialog.ui.btnStop.click()
        self.assertFalse(sniff_dialog.ui.btnStop.isEnabled())

        sniff_dialog.close()
Beispiel #38
0
    WINDIR = os.getenv("WINDIR")

# ------------------------------------------------------------------------------------------------------------
# Set Version

VERSION = "1.9.6 (2.0-beta4)"

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

envTMP = os.getenv("TMP")

if envTMP is None:
    if WINDOWS:
        qWarning("TMP variable not set")
    TMP = QDir.tempPath()
else:
    TMP = envTMP

if not os.path.exists(TMP):
    qWarning("TMP does not exist")
    TMP = "/"

del envTMP

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

envHOME = os.getenv("HOME")

if envHOME is None:
Beispiel #39
0
<<<
>>>>>>>+HEAD
====
>>>>>>> b1ae517... Inital Commit
def save_data(data, filename: str):
    if filename.endswith(".wav"):
        f = wave.open(filename, "w")
        f.setnchannels(1)
        f.setsampwidth(1)
        f.setframerate(1000000)
        f.writeframes(data)
<<<        f.close()
    elif filename.endswith(".coco"):
        with tarfile.open(filename, 'w:bz2') as tar_write:
            tmp_name = os.path.join(QDir.tempPath(), "tmpfile")
            data.tofile(tmp_name)
            tar_write.add(tmp_name)
>>>>>>>+HEAD
====
           f.my_close()
    elif filename.endswith(".coco"):
        with tarfile.open(filename, 'w:bz2') as tarwrite:
            tmp_name = os.path.join(QDir.tempPath(), "tmpfile")
            data.tofile(tmp_name)
            tarwrite.add(tmp_name)
>>>>>>>-b1ae517
     os.remove(tmp_name)
    else:
        try:
            data.tofile(filename)
Beispiel #40
0
def tempFolder():
    tempDir = os.path.join(unicode(QDir.tempPath()), 'qgis2web')
    if not QDir(tempDir).exists():
        QDir().mkpath(tempDir)

    return unicode(os.path.abspath(tempDir))
Beispiel #41
0
 def __add_urls_to_group(self, file_urls, group_id=0):
     local_files = [file_url.toLocalFile() for file_url in file_urls if file_url.isLocalFile()]
     if len(local_files) > 0:
         self.setCursor(Qt.WaitCursor)
         self.add_files(FileOperator.uncompress_archives(local_files, QDir.tempPath()), group_id=group_id)
         self.unsetCursor()
Beispiel #42
0
    def test_generation(self):
        """
        Complex test including much functionality
        1) Load a Signal
        2) Set Decoding in Compareframe
        3) Move with encoding to Generator
        4) Generate datafile
        5) Read datafile and compare with original signal

        """
        # Load a Signal
        self.add_signal_to_form("ask.complex")
        signal_frame = self.form.signal_tab_controller.signal_frames[0]
        signal_frame.ui.cbModulationType.setCurrentIndex(0)  # ASK
        signal_frame.ui.spinBoxInfoLen.setValue(300)
        signal_frame.ui.spinBoxInfoLen.editingFinished.emit()
        signal_frame.ui.spinBoxCenterOffset.setValue(0.032)
        signal_frame.ui.spinBoxCenterOffset.editingFinished.emit()
        signal_frame.ui.cbProtoView.setCurrentIndex(0)

        proto = "1011001001011011011011011011011011001000000"
        self.assertTrue(signal_frame.ui.txtEdProto.toPlainText().startswith(proto))

        # Set Decoding
        self.form.ui.tabWidget.setCurrentIndex(1)
        cfc = self.form.compare_frame_controller
        cfc.ui.cbDecoding.setCurrentIndex(1)  # NRZ-I
        proto_inv = cfc.proto_analyzer.decoded_proto_bits_str[0]
        self.assertTrue(self.__is_inv_proto(proto, proto_inv))

        # Move with encoding to generator
        gframe = self.form.generator_tab_controller  # type: GeneratorTabController
        gframe.ui.cbViewType.setCurrentIndex(0)
        self.add_signal_to_generator(signal_index=0)
        self.assertEqual(array.array("B", list(map(int, proto_inv))), gframe.table_model.display_data[0])
        self.assertNotEqual(array.array("B", list(map(int, proto))), gframe.table_model.display_data[0])

        gframe.table_model.protocol.messages[0].pause = 0

        # Generate Datafile
        modulator = gframe.modulators[0]
        modulator.modulation_type = 0
        modulator.samples_per_bit = 300
        buffer = gframe.prepare_modulation_buffer(gframe.total_modulated_samples, show_error=False)
        modulated_data = gframe.modulate_data(buffer)
        filename = os.path.join(QDir.tempPath(), "test_generator.complex")
        modulated_data.tofile(filename)

        # Reload datafile and see if bits match
        self.form.add_signalfile(filename)
        self.assertEqual(len(self.form.signal_tab_controller.signal_frames), 2)
        signal_frame = self.form.signal_tab_controller.signal_frames[1]

        self.assertEqual(signal_frame.signal.num_samples, 300 * len(proto))
        signal_frame.ui.cbProtoView.setCurrentIndex(0)
        self.assertEqual(signal_frame.ui.lineEditSignalName.text(), "test_generator")
        signal_frame.ui.cbModulationType.setCurrentIndex(0)  # ASK
        signal_frame.ui.spinBoxNoiseTreshold.setValue(0)
        signal_frame.ui.spinBoxNoiseTreshold.editingFinished.emit()

        signal_frame.ui.spinBoxInfoLen.setValue(295)
        signal_frame.ui.spinBoxInfoLen.editingFinished.emit()

        signal_frame.ui.spinBoxCenterOffset.setValue(0.1)
        signal_frame.ui.spinBoxCenterOffset.editingFinished.emit()

        signal_frame.ui.spinBoxTolerance.setValue(6)
        signal_frame.ui.spinBoxTolerance.editingFinished.emit()

        self.assertEqual(len(signal_frame.proto_analyzer.messages), 1)
        gen_proto = signal_frame.ui.txtEdProto.toPlainText()
        gen_proto = gen_proto[:gen_proto.index(" ")]
        self.assertTrue(proto.startswith(gen_proto))
Beispiel #43
0
def tempFile(name):
    "Returns a temp file."
    return os.path.join(QDir.tempPath(), name)
Beispiel #44
0
class MainWindow(QMainWindow):
    EXIT_CODE_REBOOT = 666
    TEMP_PROJECT_FILE = 'vidcutter_reboot.vcp'
    WORKING_FOLDER = os.path.join(QDir.tempPath(), 'vidcutter')

    def __init__(self):
        super(MainWindow, self).__init__()
        self.video, self.resizeTimer = '', 0
        self.parse_cmdline()
        self.init_settings()
        self.init_logger()
        self.init_scale()
        self.init_cutter()
        self.setWindowTitle(qApp.applicationName())
        self.setContentsMargins(0, 0, 0, 0)
        self.statusBar().showMessage('Ready')
        self.statusBar().setStyleSheet('border: none; padding: 0; margin: 0;')
        self.setAcceptDrops(True)
        self.show()
        if sys.platform == 'win32' and TaskbarProgress.isValidWinVer():
            self.win_taskbar_button = QWinTaskbarButton(self)
            self.win_taskbar_button.setWindow(self.windowHandle())
            self.win_taskbar_button.progress().setVisible(True)
            self.win_taskbar_button.progress().setValue(0)
        self.console.setGeometry(int(self.x() - (self.width() / 2)),
                                 self.y() + int(self.height() / 3), 750, 300)
        if not self.video and os.path.isfile(
                os.path.join(QDir.tempPath(), MainWindow.TEMP_PROJECT_FILE)):
            self.video = os.path.join(QDir.tempPath(),
                                      MainWindow.TEMP_PROJECT_FILE)
        if self.video:
            self.file_opener(self.video)

    def init_scale(self) -> None:
        screen_size = qApp.desktop().availableGeometry(-1)
        self.scale = 'LOW' if screen_size.width() <= 1024 else 'NORMAL'
        self.setMinimumSize(self.get_size(self.scale))
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    @pyqtSlot(str)
    def file_opener(self, filename: str) -> None:
        try:
            if QFileInfo(filename).suffix() == 'vcp':
                self.cutter.openProject(project_file=filename)
                if filename == os.path.join(QDir.tempPath(),
                                            MainWindow.TEMP_PROJECT_FILE):
                    os.remove(
                        os.path.join(QDir.tempPath(),
                                     MainWindow.TEMP_PROJECT_FILE))
            else:
                self.cutter.loadMedia(filename)
        except (FileNotFoundError, PermissionError):
            QMessageBox.critical(self, 'Error loading file', sys.exc_info()[0])
            logging.exception('Error loading file')
            qApp.restoreOverrideCursor()
            self.restart()

    @staticmethod
    def get_size(mode: str = 'NORMAL') -> QSize:
        modes = {
            'LOW': QSize(800, 425),
            'NORMAL': QSize(930, 680),
            'HIGH': QSize(1850, 1300)
        }
        return modes[mode]

    def init_logger(self) -> None:
        try:
            log_path = self.get_app_config_path()
        except AttributeError:
            if sys.platform == 'win32':
                log_path = os.path.join(QDir.homePath(), 'AppData', 'Local',
                                        qApp.applicationName().lower())
            elif sys.platform == 'darwin':
                log_path = os.path.join(QDir.homePath(), 'Library',
                                        'Preferences',
                                        qApp.applicationName().lower())
            else:
                log_path = os.path.join(QDir.homePath(), '.config',
                                        qApp.applicationName().lower())
        os.makedirs(log_path, exist_ok=True)
        self.console = ConsoleWidget(self)
        self.consoleLogger = ConsoleHandler(self.console)
        handlers = [
            logging.handlers.RotatingFileHandler(os.path.join(
                log_path, '%s.log' % qApp.applicationName().lower()),
                                                 maxBytes=1000000,
                                                 backupCount=1),
            self.consoleLogger
        ]
        if self.parser.isSet(self.debug_option) or self.verboseLogs:
            # noinspection PyTypeChecker
            handlers.append(logging.StreamHandler())
        logging.setLoggerClass(VideoLogger)
        logging.basicConfig(
            handlers=handlers,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M',
            level=logging.INFO)
        logging.captureWarnings(capture=True)
        sys.excepthook = MainWindow.log_uncaught_exceptions
        if os.getenv('DEBUG', False):
            logging.info('appconfig folder: {}'.format(log_path))

    def init_settings(self) -> None:
        try:
            settings_path = self.get_app_config_path()
        except AttributeError:
            if sys.platform == 'win32':
                settings_path = os.path.join(QDir.homePath(), 'AppData',
                                             'Local',
                                             qApp.applicationName().lower())
            elif sys.platform == 'darwin':
                settings_path = os.path.join(QDir.homePath(), 'Library',
                                             'Preferences',
                                             qApp.applicationName().lower())
            else:
                settings_path = os.path.join(QDir.homePath(), '.config',
                                             qApp.applicationName().lower())
        os.makedirs(settings_path, exist_ok=True)
        settings_file = '{}.ini'.format(qApp.applicationName().lower())
        self.settings = QSettings(os.path.join(settings_path, settings_file),
                                  QSettings.IniFormat)
        if self.settings.value('geometry') is not None:
            self.restoreGeometry(self.settings.value('geometry'))
        if self.settings.value('windowState') is not None:
            self.restoreState(self.settings.value('windowState'))
        self.theme = self.settings.value('theme', 'light', type=str)
        self.startupvol = self.settings.value('volume', 100, type=int)
        self.verboseLogs = self.settings.value('verboseLogs', 'off',
                                               type=str) in {'on', 'true'}

    @staticmethod
    def log_uncaught_exceptions(cls, exc, tb) -> None:
        logging.critical(''.join(traceback.format_tb(tb)))
        logging.critical('{0}: {1}'.format(cls, exc))

    def parse_cmdline(self) -> None:
        self.parser = QCommandLineParser()
        self.parser.setApplicationDescription(
            '\nVidCutter - the simplest + fastest media cutter & joiner')
        self.parser.addPositionalArgument('video', 'Preload video file',
                                          '[video]')
        self.parser.addPositionalArgument(
            'project', 'Open VidCutter project file (.vcp)', '[project]')
        self.debug_option = QCommandLineOption(
            ['debug'], 'debug mode; verbose console output & logging. '
            'This will basically output what is being logged to file to the '
            'console stdout. Mainly useful for debugging problems with your '
            'system video and/or audio stack and codec configuration.')
        self.parser.addOption(self.debug_option)
        self.parser.addVersionOption()
        self.parser.addHelpOption()
        self.parser.process(qApp)
        self.args = self.parser.positionalArguments()
        if self.parser.isSet(self.debug_option):
            os.environ['DEBUG'] = '1'
        if len(self.args) > 0:
            file_path = QFileInfo(self.args[0]).absoluteFilePath()
            if not os.path.exists(file_path):
                sys.stderr.write('\nERROR: File not found: %s\n' % file_path)
                self.close()
                qApp.exit(1)
            self.video = file_path

    def init_cutter(self) -> None:
        self.cutter = VideoCutter(self)
        self.cutter.errorOccurred.connect(self.errorHandler)
        self.setCentralWidget(self.cutter)
        qApp.setWindowIcon(VideoCutter.getAppIcon(encoded=False))

    @staticmethod
    def get_bitness() -> int:
        from struct import calcsize
        return calcsize('P') * 8

    @pyqtSlot()
    def reboot(self) -> None:
        if self.cutter.mediaAvailable:
            self.cutter.saveProject(reboot=True)
        self.save_settings()
        qApp.exit(MainWindow.EXIT_CODE_REBOOT)

    def save_settings(self) -> None:
        self.settings.setValue('lastFolder', self.cutter.lastFolder)
        self.settings.setValue('geometry', self.saveGeometry())
        self.settings.setValue('windowState', self.saveState())
        self.settings.sync()

    @pyqtSlot(bool)
    def lock_gui(self, locked: bool = True) -> None:
        if locked:
            qApp.setOverrideCursor(Qt.WaitCursor)
            self.cutter.cliplist.setEnabled(False)
            self.setEnabled(False)
        else:
            self.setEnabled(True)
            self.cutter.cliplist.setEnabled(True)
            qApp.restoreOverrideCursor()
        qApp.processEvents()

    @property
    def flatpak(self) -> bool:
        return sys.platform.startswith('linux') and QFileInfo(
            __file__).absolutePath().startswith('/app/')

    def get_app_config_path(self) -> str:
        if self.flatpak:
            confpath = QProcessEnvironment.systemEnvironment().value(
                'XDG_CONFIG_HOME', '')
            if len(confpath):
                return confpath
            else:
                return os.path.join(QDir.homePath(), '.var', 'app',
                                    vidcutter.__desktopid__, 'config')
        return QStandardPaths.writableLocation(
            QStandardPaths.AppConfigLocation).replace(
                qApp.applicationName(),
                qApp.applicationName().lower())

    @staticmethod
    def get_path(path: str = None, override: bool = False) -> str:
        if override:
            if getattr(sys, 'frozen', False) and getattr(
                    sys, '_MEIPASS', False):
                # noinspection PyProtectedMember, PyUnresolvedReferences
                return os.path.join(sys._MEIPASS, path)
            return os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
                                path)
        return ':{}'.format(path)

    @pyqtSlot(str)
    def errorHandler(self, msg: str, title: str = None) -> None:
        qApp.restoreOverrideCursor()
        QMessageBox.critical(self,
                             'An error occurred' if title is None else title,
                             msg, QMessageBox.Ok)
        logging.error(msg)

    @staticmethod
    @pyqtSlot()
    def cleanup():
        shutil.rmtree(MainWindow.WORKING_FOLDER, ignore_errors=True)

    def contextMenuEvent(self, event: QContextMenuEvent) -> None:
        if event.reason() in {
                QContextMenuEvent.Mouse, QContextMenuEvent.Keyboard
        }:
            self.cutter.appmenu.popup(event.globalPos())
        super(MainWindow, self).contextMenuEvent(event)

    def mousePressEvent(self, event: QMouseEvent) -> None:
        if event.button() == Qt.LeftButton and self.cutter.mediaAvailable:
            self.cutter.cliplist.clearSelection()
            self.cutter.timeCounter.clearFocus()
            self.cutter.frameCounter.clearFocus()
            # noinspection PyBroadException
            try:
                if hasattr(self.cutter, 'notify'):
                    self.cutter.notify.close()
            except BaseException:
                pass
            event.accept()

    def dragEnterEvent(self, event: QDragEnterEvent) -> None:
        if event.mimeData().hasUrls():
            event.accept()

    def dropEvent(self, event: QDropEvent) -> None:
        filename = event.mimeData().urls()[0].toLocalFile()
        self.file_opener(filename)
        event.accept()

    def resizeEvent(self, event: QResizeEvent) -> None:
        try:
            if self.isEnabled(
            ) and self.cutter.mediaAvailable and self.cutter.thumbnailsButton.isChecked(
            ):
                if self.cutter.seekSlider.thumbnailsOn:
                    self.cutter.sliderWidget.setLoader(True)
                    self.cutter.sliderWidget.hideThumbs()
                if self.resizeTimer:
                    self.killTimer(self.resizeTimer)
                self.resizeTimer = self.startTimer(500)
        except AttributeError:
            pass

    def timerEvent(self, event: QTimerEvent) -> None:
        try:
            self.cutter.seekSlider.reloadThumbs()
            self.killTimer(self.resizeTimer)
            self.resizeTimer = 0
        except AttributeError:
            pass

    def closeEvent(self, event: QCloseEvent) -> Optional[Callable]:
        event.accept()
        try:
            if not self.isEnabled():
                exitwarn = VCMessageBox('Warning',
                                        'Media is currently being processed',
                                        'Are you sure you want to exit now?',
                                        parent=self)
                exitwarn.addButton('Yes', QMessageBox.NoRole)
                cancelbutton = exitwarn.addButton('No', QMessageBox.RejectRole)
                exitwarn.exec_()
                res = exitwarn.clickedButton()
                if res == cancelbutton:
                    event.ignore()
                    return
            noexit, callback = self.cutter.saveWarning()
            if noexit:
                event.ignore()
                if callback is not None:
                    return callback()
                else:
                    return
        except AttributeError:
            logging.exception('warning dialogs on app exit exception',
                              exc_info=True)
        self.console.deleteLater()
        if hasattr(self, 'cutter'):
            self.save_settings()
            try:
                if hasattr(self.cutter.videoService, 'smartcut_jobs'):
                    [
                        self.cutter.videoService.cleanup(job.files.values())
                        for job in self.cutter.videoService.smartcut_jobs
                    ]
                if hasattr(self.cutter, 'mpvWidget'):
                    self.cutter.mpvWidget.shutdown()
            except AttributeError:
                pass
        try:
            qApp.exit(0)
        except mpv.MPVError:
            pass
    def test_project_dialog(self):
        frequency = 1e9
        sample_rate = 10e9
        bandwidth = 10
        gain = 42
        descr = "URH rockz."

        dialog = ProjectDialog(project_manager=self.form.project_manager, parent=self.form)

        dialog.ui.spinBoxFreq.setValue(frequency)
        self.assertEqual(dialog.freq, frequency)

        dialog.ui.spinBoxSampleRate.setValue(sample_rate)
        self.assertEqual(dialog.sample_rate, sample_rate)

        dialog.ui.spinBoxBandwidth.setValue(bandwidth)
        self.assertEqual(dialog.bandwidth, bandwidth)

        dialog.ui.spinBoxGain.setValue(gain)
        self.assertEqual(dialog.gain, gain)

        dialog.ui.txtEdDescription.setPlainText(descr)
        self.assertEqual(dialog.description, descr)

        dialog.ui.lineEditBroadcastAddress.setText("abcd")
        dialog.ui.lineEditBroadcastAddress.textEdited.emit("abcd")
        self.assertEqual(dialog.broadcast_address_hex, "abcd")

        if len(dialog.participants) == 0:
            dialog.ui.btnAddParticipant.click()
            self.assertEqual(len(dialog.participants), 1)

        model = dialog.participant_table_model
        model.setData(model.index(0, 0), "Testing")
        model.setData(model.index(0, 1), "T")
        model.setData(model.index(0, 2), 5)
        model.setData(model.index(0, 3), 0)
        model.setData(model.index(0, 4), "aaaa")
        participant = dialog.participants[0]
        self.assertEqual(participant.name, "Testing")
        self.assertEqual(participant.shortname, "T")
        self.assertEqual(participant.color_index, 5)
        self.assertEqual(participant.relative_rssi, 0)
        self.assertEqual(participant.address_hex, "aaaa")

        num_participants = len(dialog.participants)
        dialog.ui.btnAddParticipant.click()
        dialog.ui.btnAddParticipant.click()
        dialog.ui.btnAddParticipant.click()
        self.assertEqual(len(dialog.participants), num_participants + 3)

        dialog.ui.btnRemoveParticipant.click()
        dialog.ui.btnRemoveParticipant.click()
        dialog.ui.btnRemoveParticipant.click()
        self.assertEqual(len(dialog.participants), num_participants)

        test_path = os.path.join(QDir.tempPath(), "urh_test")

        dialog.ui.lineEdit_Path.setText(test_path)
        dialog.ui.lineEdit_Path.textEdited.emit(test_path)
        self.assertEqual(dialog.path, test_path)
        dialog.on_button_box_accepted()

        self.form.ui.tabWidget.setCurrentWidget(self.form.ui.tab_protocol)
        self.form.compare_frame_controller.ui.tabWidget.setCurrentWidget(
            self.form.compare_frame_controller.ui.tab_participants)
        self.assertGreater(self.form.compare_frame_controller.participant_list_model.rowCount(), 0)

        self.assertTrue(os.path.isdir(test_path))

        self.form.project_manager.from_dialog(dialog)

        dialog = ProjectDialog(project_manager=self.form.project_manager, parent=self.form, new_project=False)
        self.assertEqual(dialog.ui.spinBoxFreq.value(), frequency)
        self.assertEqual(dialog.ui.spinBoxSampleRate.value(), sample_rate)
        self.assertEqual(dialog.ui.spinBoxBandwidth.value(), bandwidth)
        self.assertEqual(dialog.ui.spinBoxGain.value(), gain)
        self.assertEqual(dialog.ui.txtEdDescription.toPlainText(), descr)
        self.assertFalse(dialog.ui.lineEdit_Path.isEnabled())
Beispiel #46
0
    WINDIR = os.getenv("WINDIR")

# ------------------------------------------------------------------------------------------------------------
# Set Version

VERSION = "1.9.14 (2.0-RC4)"

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

envTMP = os.getenv("TMP")

if envTMP is None:
    if WINDOWS:
        qWarning("TMP variable not set")
    TMP = QDir.tempPath()
else:
    TMP = envTMP

if not os.path.exists(TMP):
    qWarning("TMP does not exist")
    TMP = "/"

del envTMP

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

envHOME = os.getenv("HOME")

if envHOME is None:
Beispiel #47
0
 def testJoin(self, file1: str, file2: str) -> bool:
     result = False
     self.logger.info('attempting to test joining of "{0}" & "{1}"'.format(
         file1, file2))
     try:
         # 1. check audio + video codecs
         file1_codecs = self.codecs(file1)
         file2_codecs = self.codecs(file2)
         if file1_codecs != file2_codecs:
             self.logger.info(
                 'join test failed for {0} and {1}: codecs mismatched'.
                 format(file1, file2))
             self.lastError = '<p>The audio + video format of this media file is not the same as the files ' \
                              'already in your clip index.</p>' \
                              '<div align="center">Current files are <b>{0}</b> (video) and ' \
                              '<b>{1}</b> (audio)<br/>' \
                              'Failed media is <b>{2}</b> (video) and <b>{3}</b> (audio)</div>'
             self.lastError = self.lastError.format(file1_codecs[0],
                                                    file1_codecs[1],
                                                    file2_codecs[0],
                                                    file2_codecs[1])
             return result
         # 2. check frame sizes
         size1 = self.framesize(file1)
         size2 = self.framesize(file2)
         if size1 != size2:
             self.logger.info(
                 'join test failed for {0} and {1}: frame size mismatched'.
                 format(file1, file2))
             self.lastError = '<p>The frame size of this media file is not the same as the files already in ' \
                              'your clip index.</p>' \
                              '<div align="center">Current media clips are <b>{0}x{1}</b>' \
                              '<br/>Failed media file is <b>{2}x{3}</b></div>'
             self.lastError = self.lastError.format(size1.width(),
                                                    size1.height(),
                                                    size2.width(),
                                                    size2.height())
             return result
         # 2. generate temporary file handles
         _, ext = os.path.splitext(file1)
         file1_cut = QTemporaryFile(
             os.path.join(QDir.tempPath(), 'XXXXXX{}'.format(ext)))
         file2_cut = QTemporaryFile(
             os.path.join(QDir.tempPath(), 'XXXXXX{}'.format(ext)))
         final_join = QTemporaryFile(
             os.path.join(QDir.tempPath(), 'XXXXXX{}'.format(ext)))
         # 3. produce 4 secs clips from input files for join test
         if file1_cut.open() and file2_cut.open() and final_join.open():
             result1 = self.cut(file1, file1_cut.fileName(), '00:00:00.000',
                                '00:00:04.00', False)
             result2 = self.cut(file2, file2_cut.fileName(), '00:00:00.000',
                                '00:00:04.00', False)
             if result1 and result2:
                 # 4. attempt join of temp 2 second clips
                 result = self.join(
                     [file1_cut.fileName(),
                      file2_cut.fileName()], final_join.fileName(), False,
                     None)
         VideoService.cleanup([
             file1_cut.fileName(),
             file2_cut.fileName(),
             final_join.fileName()
         ])
     except BaseException:
         self.logger.exception('Exception in VideoService.testJoin',
                               exc_info=True)
         result = False
     return result
Beispiel #48
0
                        self._fulldata.imag = (raw['i'] / 127.5) - 1.0
                    elif filename.endswith(".complex16s"):
                        # two 8 bit signed integers
                        raw = np.fromfile(filename, dtype=[('r', np.int8), ('i', np.int8)])
                        self._fulldata = np.empty(raw.shape[0], dtype=np.complex64)
                        self._fulldata.real = (raw['r'] + 0.5) / 127.5
                        self._fulldata.imag = (raw['i'] + 0.5) / 127.5
                    else:
                        self._fulldata = np.fromfile(filename, dtype=np.complex64)  # Uncompressed
=======
                    self._fulldata = np.fromfile(filename, dtype=np.complex64)  # Uncompressed
>>>>>>> b1ae517... Inital Commit
                else:
                    obj = tarfile.open(filename, "r")
                    members = obj.getmembers()
                    obj.extract(members[0], QDir.tempPath())
                    extracted_filename = os.path.join(QDir.tempPath(), obj.getnames()[0])
                    self._fulldata = np.fromfile(extracted_filename, dtype=np.complex64)
                    os.remove(extracted_filename)

<<<<<<< HEAD
                self._fulldata = np.ascontiguousarray(self._fulldata, dtype=np.complex64)  # type: np.ndarray
=======
                self._fulldata = np.ascontiguousarray(self._fulldata, dtype=np.complex64)
>>>>>>> b1ae517... Inital Commit
            else:
                f = wave.open(filename, "r")
                n = f.getnframes()
                unsigned_bytes = struct.unpack('<{0:d}B'.format(n), f.readframes(n))
                if not self.qad_demod_file_loaded:
                    # Complex To Real WAV File load
Beispiel #49
0
def temporaryOutputDir():
    return QDir.tempPath() + "/Qgis2threejs"
Beispiel #50
0
def tempFile(name):
    "Returns a temp file."
    return os.path.join(QDir.tempPath(), name)
Beispiel #51
0
 def on_btnDir_tempPath_clicked(self):
     self.__showBtnInfo(self.sender())
     text = QDir.tempPath()
     self.ui.textEdit.appendPlainText(text + "\n")
Beispiel #52
0
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QDir
COL_HEADERS = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split()
ROWS = 99
COLS = len(COL_HEADERS)
WIDTH = 1440
HEIGHT = 800
APP_TITLE = 'Tablao'
ICON = QIcon('./icon.svg')
ACTIVEWINDOWFOCUSREASON = 3
UNTITLED_PATH = (QDir.tempPath() + '/tablao_untitled')
CLIPBOARD_MODE_CLIPBOARD = 0
CLIPBOARD_MODE_SELECTION = 1
print(sys.platform)
PREVIEWHEADER_FIRST_PART = "<!DOCTYPE html>\n     <html>\n       <head>\n         <meta charset='utf-8'>\n         <title></title>\n         <!-- Latest compiled and minified CSS -->\n         <style media='screen'>\n\n           body {\n             font-family: -apple-system, BlinkMacSystemFont,\n                           'Segoe UI', 'Source Sans Pro', 'Roboto', 'Oxygen',\n                           'Ubuntu', 'Cantarell', 'Fira Sans',\n                           'Droid Sans', 'Helvetica Neue', sans-serif;\n           }\n           table-bordered {\n               border: 1px solid #ddd;\n           }\n           table {\n               width: 100%;\n               max-width: 100%;\n               margin-bottom: 20px;\n           }\n           table {\n               background-color: transparent;\n           }\n           table {\n               border-spacing: 0;\n               border-collapse: collapse;\n           }\n\n           table>tbody>tr>td, table>tbody>tr>th, table>tfoot>tr>td, table>tfoot>tr>th, table>thead>tr>td, table>thead>tr>th {\n               border: 1px solid #ddd;\n           }\n\n           table>tbody>tr>td, table>tbody>tr>th, table>tfoot>tr>td, table>tfoot>tr>th, table>thead>tr>td, table>thead>tr>th {\n               padding: 5px;\n               line-height: 1.42857143;\n               vertical-align: top;\n               border-top: 1px solid #ddd;\n           }\n\n           th {\n               text-align: left;\n           }\n           "
PREVIEWHEADER_BREEZE_SCROLLBAR_STYLE = (
    '\n           ::-webkit-scrollbar\n            {\n            \tbackground: #eff0f1;\n            \twidth: 6px;\n            \theight: 6px;\n            }\n\n            ::-webkit-scrollbar-button\n            {\n            \twidth: 0px;\n            \theight: 0px;\n            }\n\n            ::-webkit-scrollbar-thumb\n            {\n            \tbackground: #3DAEE9;\n            \tborder-radius: 50px;\n            }\n\n            ::-webkit-scrollbar-thumb:hover, ::-webkit-scrollbar-thumb:window-inactive:hover\n            {\n              \tbackground: #93cee9;\n            }\n\n            ::-webkit-scrollbar-track\n            {\n            \tbackground: #eff0f1;\n            \tborder-radius: 50px;\n            }\n\n            ::-webkit-scrollbar-track:hover\n            {\n            \tbackground: rgba(106, 110, 113, 0.3);\n            }\n\n            ::-webkit-scrollbar-corner\n            {\n              \tbackground: transparent;\n            }\n\n            ::-webkit-scrollbar-thumb:window-inactive\n            {\n            \tbackground: #909396;\n            \tborder-radius: 50px;\n            }\n            '
    if ('linux' == sys.platform) else '')
PREVIEWHEADER_LAST_PART = '\n         </style>\n       </head>\n       <body>\n       '
PREVIEWHEADER = (
    (PREVIEWHEADER_FIRST_PART + PREVIEWHEADER_BREEZE_SCROLLBAR_STYLE) +
    PREVIEWHEADER_LAST_PART)
PREVIEWFOOTER = '  </body>\n      </html>'
Beispiel #53
0
    def test_generation(self):
        """
        Complex test including much functionality
        1) Load a Signal
        2) Set Decoding in Compareframe
        3) Move with encoding to Generator
        4) Generate datafile
        5) Read datafile and compare with original signal

        """
        # Load a Signal
        self.add_signal_to_form("ask.complex")
        signal_frame = self.form.signal_tab_controller.signal_frames[0]
        signal_frame.ui.cbModulationType.setCurrentIndex(0)  # ASK
        signal_frame.ui.spinBoxSamplesPerSymbol.setValue(300)
        signal_frame.ui.spinBoxSamplesPerSymbol.editingFinished.emit()
        signal_frame.ui.spinBoxCenterOffset.setValue(0.032)
        signal_frame.ui.spinBoxCenterOffset.editingFinished.emit()
        signal_frame.ui.cbProtoView.setCurrentIndex(0)

        proto = "1011001001011011011011011011011011001000000"
        self.assertTrue(
            signal_frame.ui.txtEdProto.toPlainText().startswith(proto))

        # Set Decoding
        self.form.ui.tabWidget.setCurrentIndex(1)
        cfc = self.form.compare_frame_controller
        cfc.ui.cbDecoding.setCurrentIndex(1)  # NRZ-I
        proto_inv = cfc.proto_analyzer.decoded_proto_bits_str[0]
        self.assertTrue(self.__is_inv_proto(proto, proto_inv))

        # Move with encoding to generator
        gframe = self.form.generator_tab_controller  # type: GeneratorTabController
        gframe.ui.cbViewType.setCurrentIndex(0)
        self.add_signal_to_generator(signal_index=0)
        self.assertEqual(array.array("B", list(map(int, proto_inv))),
                         gframe.table_model.display_data[0])
        self.assertNotEqual(array.array("B", list(map(int, proto))),
                            gframe.table_model.display_data[0])

        gframe.table_model.protocol.messages[0].pause = 0

        # Generate Datafile
        modulator = gframe.modulators[0]
        modulator.modulation_type = "ASK"
        modulator.samples_per_symbol = 300
        buffer = gframe.prepare_modulation_buffer(
            gframe.total_modulated_samples, show_error=False)
        modulated_data = gframe.modulate_data(buffer)
        filename = os.path.join(QDir.tempPath(), "test_generator.complex")
        modulated_data.tofile(filename)

        # Reload datafile and see if bits match
        self.form.add_signalfile(filename)
        self.assertEqual(len(self.form.signal_tab_controller.signal_frames), 2)
        signal_frame = self.form.signal_tab_controller.signal_frames[1]

        self.assertEqual(signal_frame.signal.num_samples, 300 * len(proto))
        signal_frame.ui.cbProtoView.setCurrentIndex(0)
        self.assertEqual(signal_frame.ui.lineEditSignalName.text(),
                         "test_generator")
        signal_frame.ui.cbModulationType.setCurrentIndex(0)  # ASK
        signal_frame.ui.spinBoxNoiseTreshold.setValue(0)
        signal_frame.ui.spinBoxNoiseTreshold.editingFinished.emit()

        signal_frame.ui.spinBoxSamplesPerSymbol.setValue(295)
        signal_frame.ui.spinBoxSamplesPerSymbol.editingFinished.emit()

        signal_frame.ui.spinBoxCenterOffset.setValue(0.1)
        signal_frame.ui.spinBoxCenterOffset.editingFinished.emit()

        signal_frame.ui.spinBoxTolerance.setValue(6)
        signal_frame.ui.spinBoxTolerance.editingFinished.emit()

        self.assertEqual(len(signal_frame.proto_analyzer.messages), 1)
        gen_proto = signal_frame.ui.txtEdProto.toPlainText()
        gen_proto = gen_proto[:gen_proto.index(" ")]
        self.assertTrue(proto.startswith(gen_proto))
Beispiel #54
0
 def initializePage(self):
     className = self.field('className')
     self.headerLineEdit.setText(className.lower() + '.h')
     self.implementationLineEdit.setText(className.lower() + '.cpp')
     self.outputDirLineEdit.setText(QDir.toNativeSeparators(QDir.tempPath()))