Example #1
0
 def _shutdown(self, status, restart):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         event_filter = objreg.get('event-filter', None)
         if event_filter is not None:
             qApp.removeEventFilter(event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     websettings.shutdown()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
             not restart):
         atexit.register(shutil.rmtree, self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     downloads.temp_download_manager.cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     session_manager = objreg.get('session-manager', None)
     if session_manager is not None:
         session_manager.delete_autosave()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Example #2
0
    def _exception_hook(self, exctype, excvalue, tb):
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        # pylint: disable=broad-except

        if exctype is bdb.BdbQuit or not issubclass(exctype, Exception):
            # pdb exit, KeyboardInterrupt, ...
            try:
                self.shutdown()
                return
            except Exception:
                log.init.exception("Error while shutting down")
                self.quit()
                return

        exc = (exctype, excvalue, tb)
        sys.__excepthook__(*exc)

        self._quit_status['crash'] = False

        try:
            pages = self._recover_pages()
        except Exception:
            log.destroy.exception("Error while recovering pages")
            pages = []

        try:
            history = objreg.get('status-command').history[-5:]
        except Exception:
            log.destroy.exception("Error while getting history: {}")
            history = []

        try:
            objects = self.get_all_objects()
        except Exception:
            log.destroy.exception("Error while getting objects")
            objects = ""

        try:
            self.lastWindowClosed.disconnect(self.shutdown)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")
        QApplication.closeAllWindows()
        self._crashdlg = crash.ExceptionCrashDialog(pages, history, exc,
                                                    objects)
        ret = self._crashdlg.exec_()
        if ret == QDialog.Accepted:  # restore
            self.restart(shutdown=False, pages=pages)
        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self._destroy_crashlogfile()
        sys.exit(1)
Example #3
0
 def _shutdown(self, status):
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         qApp.removeEventFilter(objreg.get("event-filter"))
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get("ipc-server").shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get("save-manager")
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not " "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!", pre_text="Error while saving {}".format(key)
                 )
     # Disable storage so removing tempdir will work
     QWebSettings.setIconDatabasePath("")
     QWebSettings.setOfflineWebApplicationCachePath("")
     QWebSettings.globalSettings().setLocalStoragePath("")
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get("crash-handler").destroy_crashlogfile()
     # Delete temp basedir
     if self._args.temp_basedir:
         atexit.register(shutil.rmtree, self._args.basedir, ignore_errors=True)
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get("signal-handler").deactivate()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Example #4
0
 def _shutdown(self, status):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         qApp.removeEventFilter(objreg.get('event-filter'))
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 msgbox = QMessageBox(
                     QMessageBox.Critical, "Error while saving!",
                     "Error while saving {}: {}".format(key, e))
                 msgbox.exec_()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactiving message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Example #5
0
 def quit(self):
     """Quit qutebrowser."""
     QApplication.closeAllWindows()
Example #6
0
 def closeEvent(self, event) :
     QApplication.closeAllWindows()
def main():
    fix_windows_stdout_stderr()

    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..",
                           "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith(
            "/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed -> add directory to path
        sys.path.insert(0, src_dir)

    if len(sys.argv) > 1 and sys.argv[1] == "--version":
        import urh.version
        print(urh.version.VERSION)
        sys.exit(0)

    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            sys.path.insert(0, os.path.join(prefix))
            from data import generate_ui
            generate_ui.gen()
        except (ImportError, FileNotFoundError):
            # The generate UI script cannot be found so we are most likely in release mode, no problem here.
            pass

    from urh.util import util
    util.set_shared_library_path()

    try:
        import urh.cythonext.signal_functions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        if hasattr(sys, "frozen"):
            print("C++ Extensions not found. Exiting...")
            sys.exit(1)
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.path.realpath(os.curdir)
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import settings

    if settings.read("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(["URH"] + sys.argv[1:])
    app.setWindowIcon(QIcon(":/icons/icons/appicon.png"))

    try:
        app.styleHints().setShowShortcutsInContextMenus(True)
    except AttributeError:
        pass

    util.set_icon_theme()

    font_size = settings.read("font_size", 0, int)
    if font_size > 0:
        font = app.font()
        font.setPointSize(font_size)
        app.setFont(font)

    settings.write("default_theme", app.style().objectName())

    if settings.read("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if settings.read("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText,
                             Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    # use system colors for painting
    widget = QWidget()
    bg_color = widget.palette().color(QPalette.Background)
    fg_color = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    settings.BGCOLOR = bg_color
    settings.LINECOLOR = fg_color
    settings.SELECTION_COLOR = selection_color
    settings.SEND_INDICATOR_COLOR = selection_color

    main_window = MainController()
    # allow usage of prange (OpenMP) in Processes
    multiprocessing.set_start_method("spawn")

    if sys.platform == "win32":
        # Ensure we get the app icon in windows taskbar
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "jopohl.urh")

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(
        return_code
    )  # sys.exit() is not enough on Windows and will result in crash on exit
 def closeEvent(self, event):
     super().closeEvent(event)
     QApplication.closeAllWindows()
     # self.clean_up()
     QApplication.quit()
     event.accept()
Example #9
0
r"""
Test file to execute all the tests from the unittest library within the scrabble code using nose.

Notes
-----
#.  Written by David C. Stauffer in March 2017.
"""

#%% Imports
import sys

import nose
from PyQt5.QtWidgets import QApplication

import dstauffman2.games.scrabble as scrab

#%% Script
if __name__ == '__main__':
    # open a qapp
    if QApplication.instance() is None:
        qapp = QApplication(sys.argv)
    else:
        qapp = QApplication.instance()
    # run the tests
    nose.run(scrab)
    # close the qapp
    qapp.closeAllWindows()
Example #10
0
class TestMemory(unittest.TestCase):
    def setUp(self) -> None:
        self.app = QApplication([])
        self.memory = MemoryWindow("test_username")
        self.memory.initialize_game(1)

    def tearDown(self) -> None:
        self.app.closeAllWindows()

    def test_check_if_memory_is_solved(self):
        self.memory.button_manager = mock.MagicMock()
        self.memory.button_manager.is_memory_solved.return_value = True

        self.memory.end_the_game = mock.MagicMock()
        self.memory.check_for_end_of_game()

        self.memory.end_the_game.assert_called_once_with()

    def test_check_if_memory_is_solved2(self):
        self.memory.button_manager = mock.MagicMock()
        self.memory.button_manager.is_memory_solved.return_value = False

        self.memory.end_the_game = mock.MagicMock()
        self.memory.check_for_end_of_game()

        self.memory.end_the_game.assert_not_called()

    @mock.patch("src.games.memory.memory.GameDatabaseManagement",
                autospec=True)
    def test_initialize_database(self, mock_class1):
        self.memory1 = MemoryWindow("username")
        mock_class1.assert_called_once_with(
            "src/databases/memory.csv", "username",
            ["unlocked_level", "achieved_points"])
        mock_class1.return_value.initialize_user_account.assert_called_once_with(
            [1, 0])

    def test_initialize_game(self):
        self.memory.set_memory_images = mock.MagicMock()
        self.memory.connect_buttons_to_game = mock.MagicMock()
        self.memory.initialize_game(2)

        self.memory.connect_buttons_to_game.assert_called()
        self.memory.set_memory_images.assert_called()
        self.assertEqual(900, self.memory.required_points)

    def test_memory_images(self):
        id_list = []
        for button in self.memory.button_manager.buttons():
            id_list.append(button.image_number)
        for i in range(1, self.memory.memory_card_pairs + 1):
            self.assertEqual(2, id_list.count(i))

    def test_update_moves(self):
        self.memory.update_moves()
        self.assertEqual(1, self.memory.moves)
        self.assertEqual("Moves: 1", self.memory.moves_label.text())

    def test_update_points(self):
        self.memory.update_points(500)
        self.assertEqual(500, self.memory.achieved_points)
        self.assertEqual("Points: 500", self.memory.points_label.text())

    def test_end_of_game1(self):
        self.memory.update_values = mock.MagicMock()
        self.memory.achieved_points = 2000
        self.memory.selected_level = 20
        self.memory.show_every_level_completed = mock.MagicMock()
        self.memory.emit_game_menu_signal = mock.MagicMock()

        self.memory.end_the_game()

        self.memory.show_every_level_completed.assert_called()
        self.memory.emit_game_menu_signal.assert_called()

    def test_end_of_game2(self):
        self.memory.update_values = mock.MagicMock()
        self.memory.achieved_points = 2000
        self.memory.unlock_next_level = mock.MagicMock()
        self.memory.show_selection_for_next_game = mock.MagicMock(
            return_value=QMessageBox.AcceptRole)
        self.memory.game_database.save_user_data = mock.MagicMock()
        self.memory.emit_game_menu_signal = mock.MagicMock()
        self.memory.end_the_game()

        self.memory.emit_game_menu_signal.assert_called()

    def test_end_of_game3(self):
        self.memory.update_values = mock.MagicMock()
        self.memory.achieved_points = 2000
        self.memory.unlock_next_level = mock.MagicMock()
        self.memory.show_selection_for_next_game = mock.MagicMock(
            return_value=QMessageBox.RejectRole)
        self.memory.game_database.save_user_data = mock.MagicMock()
        self.memory.emit_play_next_level_signal = mock.MagicMock()
        self.memory.end_the_game()

        self.memory.emit_play_next_level_signal.assert_called()

    def test_end_of_game_losing(self):
        self.memory.update_values = mock.MagicMock()
        self.memory.achieved_points = 100
        self.memory.game_database.save_user_data = mock.MagicMock()
        self.memory.emit_level_menu_signal = mock.MagicMock()

        self.memory.show_losing_screen = mock.MagicMock(
            return_value=QMessageBox.DestructiveRole)
        self.memory.end_the_game()
        self.memory.emit_level_menu_signal.assert_called()

        self.memory.emit_game_menu_signal = mock.MagicMock()
        self.memory.show_losing_screen = mock.MagicMock(
            return_value=QMessageBox.AcceptRole)
        self.memory.end_the_game()
        self.memory.emit_game_menu_signal.assert_called()

        self.memory.emit_play_level_again_signal = mock.MagicMock()
        self.memory.show_losing_screen = mock.MagicMock(
            return_value=QMessageBox.RejectRole)
        self.memory.end_the_game()
        self.memory.emit_play_level_again_signal.assert_called()
class TestCaseImgDiffer:
    @pytest.fixture(autouse=True)
    def setup_class(self):
        self.app = QApplication.instance()
        if self.app is None:
            self.app = QApplication([])

        def except_hook(*args):
            traceback.print_exception(*args)

        prev_hook = sys.excepthook
        sys.excepthook = except_hook

        yield self.app
        sys.excepthook = prev_hook

    def test_same_img(self):
        widget1 = QLabel('test1')
        widget2 = QLabel('test1')
        ref_img = widget1.grab().toImage()
        img = widget2.grab().toImage()
        assert img == ref_img

        differ = ImgDiffer()
        assert differ.get_diff(img, ref_img) is None
        expect = 'RMS diff=0.00% (rms_tol_perc=0.00%), number of pixels changed=0.00% (num_tol_perc=None), max pix diff=0 (max_pix_diff_tol=None)'
        assert differ.report() == expect

    def test_actual_wider(self):
        widget_ref = QLabel('test1')
        widget_actual = QLabel('test23456')

        def test():
            widget_ref.show()
            widget_actual.show()

            ref_img = widget_ref.grab().toImage()
            img = widget_actual.grab().toImage()
            assert img != ref_img
            assert img.width() > ref_img.width()
            assert img.height() == ref_img.height()

            differ = ImgDiffer()
            diff = differ.get_diff(img, ref_img)
            # diff.save('actual_wider_diff.png')
            expect = QPixmap('actual_wider_diff.png')
            assert expect.toImage() == diff

            self.app.closeAllWindows()

        QTimer.singleShot(0, test)
        self.app.exec()

    def test_actual_higher(self):
        widget_ref = QLabel('test1')
        widget_actual = QLabel('test1\n123')

        def test():
            widget_ref.show()
            widget_actual.show()

            ref_img = widget_ref.grab().toImage()
            img = widget_actual.grab().toImage()
            assert img != ref_img
            assert img.width() == ref_img.width()
            assert img.height() > ref_img.height()

            differ = ImgDiffer()
            diff = differ.get_diff(img, ref_img)
            # diff.save('actual_higher_diff.png')
            expect = QPixmap('actual_higher_diff.png')
            assert expect.toImage() == diff

            self.app.closeAllWindows()

        QTimer.singleShot(0, test)
        self.app.exec()

    def test_actual_higher_thinner(self):
        widget_ref = QLabel('test1')
        widget_actual = QLabel('tes\n123')

        def test():
            widget_ref.show()
            widget_actual.show()

            ref_img = widget_ref.grab().toImage()
            img = widget_actual.grab().toImage()
            assert img != ref_img
            assert img.width() < ref_img.width()
            assert img.height() > ref_img.height()

            differ = ImgDiffer()
            diff = differ.get_diff(img, ref_img)
            # diff.save('actual_higher_thinner_diff.png')
            expect = QPixmap('actual_higher_thinner_diff.png')
            assert expect.toImage() == diff

            self.app.closeAllWindows()

        QTimer.singleShot(0, test)
        self.app.exec()

    def test_same_size_img_not_eq(self):
        widget_ref = QLabel('test1')
        widget_actual = QLabel('test2')

        def test():
            widget_actual.show()
            widget_ref.setFixedSize(widget_actual.width(),
                                    widget_actual.height())
            widget_ref.show()

            ref_img = widget_ref.grab().toImage()
            img = widget_actual.grab().toImage()
            assert img != ref_img
            assert img.size() == ref_img.size()

            differ = ImgDiffer()
            diff = differ.get_diff(img, ref_img)
            # diff.save('same_size_img_neq.png')
            expect = QPixmap('same_size_img_neq.png')
            assert expect.toImage() == diff
            report = differ.report()
            assert report == "RMS diff=37.22% (rms_tol_perc=0.00%), number of pixels changed=10.46% (num_tol_perc=None), max pix diff=240 (max_pix_diff_tol=None)"

            self.app.closeAllWindows()

        QTimer.singleShot(0, test)
        self.app.exec()

    def create_same_size_images(self, width: int, height: int,
                                color: QColor) -> (QImage, QImage, QImage):
        IMG_FORMAT = QImage.Format_ARGB32

        # create ref
        ref_img = QImage(width, height, IMG_FORMAT)
        for i in range(ref_img.width()):
            for j in range(ref_img.height()):
                ref_img.setPixelColor(i, j, color)

        # create actual = ref:
        actual_img = ref_img.copy()
        assert actual_img is not ref_img
        assert actual_img == ref_img

        # create blank diff
        diff_img = QImage(width, height, IMG_FORMAT)
        for i in range(diff_img.width()):
            for j in range(diff_img.height()):
                diff_img.setPixelColor(i, j, ImgDiffer.PIXEL_COLOR_NO_DIFF)

        return ref_img, actual_img, diff_img

    def test_same_size_one_pixel_diff(self):
        ref_img, actual_img, expect_diff_img = self.create_same_size_images(
            101, 102, QColor(103, 104, 105, 106))
        actual_img.setPixelColor(50, 50, QColor(0, 0, 0, 0))
        expect_diff_img.setPixelColor(50, 50, QColor(103, 104, 105, 106))

        differ = ImgDiffer()
        diff_img = differ.get_diff(actual_img, ref_img)
        assert expect_diff_img == diff_img
        assert differ.num_diffs_perc == 1 / (101 * 102) * 100
        assert differ.max_pix_diff == 106
        assert differ.diff_rms_perc == 100 * sqrt(
            pow(103, 2) + pow(104, 2) + pow(105, 2) + pow(106, 2)) / 2 / 255
        report = differ.report()
        assert report == "RMS diff=40.98% (rms_tol_perc=0.00%), number of pixels changed=0.01% (num_tol_perc=None), max pix diff=106 (max_pix_diff_tol=None)"

        # various cases that should produce no diff:
        assert ImgDiffer(rms_tol_perc=42).get_diff(actual_img, ref_img) is None
        assert ImgDiffer(num_tol_perc=0.01).get_diff(actual_img,
                                                     ref_img) is None
        assert ImgDiffer(max_pix_diff_tol=110).get_diff(actual_img,
                                                        ref_img) is None
        assert ImgDiffer(
            rms_tol_perc=42, num_tol_perc=0.01, max_pix_diff_tol=110).get_diff(
                actual_img, ref_img) is None

        # various cases that should produce same diff:
        assert ImgDiffer(rms_tol_perc=40).get_diff(actual_img,
                                                   ref_img) == expect_diff_img
        assert ImgDiffer(num_tol_perc=0.001).get_diff(
            actual_img, ref_img) == expect_diff_img
        assert ImgDiffer(max_pix_diff_tol=100).get_diff(
            actual_img, ref_img) == expect_diff_img

    def test_same_size_all_pixel_diff(self):
        ref_img, actual_img, expect_diff_img = self.create_same_size_images(
            101, 102, QColor(103, 104, 105, 106))
        for i in range(ref_img.width()):
            for j in range(ref_img.height()):
                pixel_color = ref_img.pixelColor(i, j)
                actual_img.setPixelColor(
                    i, j, QColor(*[c + 2 for c in pixel_color.getRgb()]))
                expect_diff_img.setPixelColor(i, j, QColor(2, 2, 2, 2))

        differ = ImgDiffer()
        diff_img = differ.get_diff(actual_img, ref_img)
        assert expect_diff_img == diff_img
        assert differ.num_diffs_perc == 100
        assert differ.max_pix_diff == 2
        assert isclose(differ.diff_rms_perc, 100 * 2 / 255)
        report = differ.report()
        assert report == "RMS diff=0.78% (rms_tol_perc=0.00%), number of pixels changed=100.00% (num_tol_perc=None), max pix diff=2 (max_pix_diff_tol=None)"

        # various cases that should produce no diff:
        assert ImgDiffer(rms_tol_perc=1).get_diff(actual_img, ref_img) is None
        assert ImgDiffer(max_pix_diff_tol=2).get_diff(actual_img,
                                                      ref_img) is None
        assert ImgDiffer(rms_tol_perc=1, max_pix_diff_tol=2).get_diff(
            actual_img, ref_img) is None

        # various cases that should produce same diff:
        assert ImgDiffer(rms_tol_perc=1 / 3).get_diff(
            actual_img, ref_img) == expect_diff_img
        assert ImgDiffer(max_pix_diff_tol=1).get_diff(
            actual_img, ref_img) == expect_diff_img
Example #12
0
    layout = QVBoxLayout(dialog)

    tv = QTreeView(dialog)
    tv.setModel(model)
    tv.setAlternatingRowColors(True)
    layout.addWidget(tv)

    label = QLabel("Search for the following person")
    layout.addWidget(label)

    buts = []
    frame = QFrame(dialog)
    layout2 = QHBoxLayout(frame)

    for person in model.people:
        but = QPushButton(person.fname, frame)
        buts.append(but)
        layout2.addWidget(but)
        but.clicked.connect(but_clicked)

    layout.addWidget(frame)

    but = QPushButton("Clear Selection")
    layout.addWidget(but)
    but.clicked.connect(tv.clearSelection)
    tv.clicked.connect(row_clicked)

    dialog.exec_()

    app.closeAllWindows()
import numpy as np
import scipy as sp
import scipy.signal as sps
import pyqtgraph as pg
import pyqtgraph.opengl as gl
from signalCreationRoutines import *
from xcorrRoutines import *
from filterCreationRoutines import *
from demodulationRoutines import *
from pgplotRoutines import *
from PyQt5.QtWidgets import QApplication
import time
import matplotlib.pyplot as plt
# end of imports

QApplication.closeAllWindows()

#%% parameters
numBitsPerBurst = 48
baud = 16000
numBursts = 20
numBitsTotal = numBitsPerBurst * numBursts
m = 2  # m-ary
h = 1.0 / m
up = 8
print('Duration of burst = %fs' % (numBitsTotal / baud))

# create bits
bits = randBits(numBitsTotal, m)

# create cpfsk signal
 def closeEvent(self, e) -> None:
     QApplication.closeAllWindows()
Example #15
0
 def fileQuit(self):
     QApplication.closeAllWindows()
Example #16
0
 def closemainwindow(self):
     app = QApplication(sys.argv)
     app.closeAllWindows()
Example #17
0
 def fileQuit(self):
     # This closes application
     QApplication.closeAllWindows()
Example #18
0
 def closeEvent(self, event):
     self.imageDisplay.setOkToClose()
     self.imageDisplay.close()
     QApplication.closeAllWindows()
Example #19
0
 def quit(self):
     """Quit qutebrowser."""
     QApplication.closeAllWindows()
Example #20
0
 def closeEvent(self, event):
     self.write_state()
     self.project_instance.write_proj_tree()
     event.accept()
     QApplication.closeAllWindows()
Example #21
0
def mainlauncher(cli, cheatsheet, zooniverse, infile, imagefile, batchmode, training, testing, sdir1, sdir2, recogniser, wind, width, command):
    # determine location of config file and bird lists
    if platform.system() == 'Windows':
        # Win
        configdir = os.path.expandvars(os.path.join("%APPDATA%", "AviaNZ"))
    elif platform.system() == 'Linux' or platform.system() == 'Darwin':
        # Unix
        configdir = os.path.expanduser("~/.avianz/")
    else:
        print("ERROR: what OS is this? %s" % platform.system())
        sys.exit()

    # if config and bird files not found, copy from distributed backups.
    # so these files will always exist on load (although they could be corrupt)
    # (exceptions here not handled and should always result in crashes)
    if not os.path.isdir(configdir):
        print("Creating config dir %s" % configdir)
        try:
            os.makedirs(configdir)
        except Exception as e:
            print("ERROR: failed to make config dir")
            print(e)
            sys.exit()

    # pre-run check of config file validity
    confloader = SupportClasses.ConfigLoader()
    configschema = json.load(open("Config/config.schema"))
    try:
        config = confloader.config(os.path.join(configdir, "AviaNZconfig.txt"))
        validate(instance=config, schema=configschema)
        print("successfully validated config file")
    except Exception as e:
        print("Warning: config file failed validation with:")
        print(e)
        try:
            shutil.copy2("Config/AviaNZconfig.txt", configdir)
        except Exception as e:
            print("ERROR: failed to copy essential config files")
            print(e)
            sys.exit()

    # check and if needed copy any other necessary files
    necessaryFiles = ["ListCommonBirds.txt", "ListDOCBirds.txt", "ListBats.txt", "LearningParams.txt"]
    for f in necessaryFiles:
        if not os.path.isfile(os.path.join(configdir, f)):
            print("File %s not found in config dir, providing default" % f)
            try:
                shutil.copy2(os.path.join("Config", f), configdir)
            except Exception as e:
                print("ERROR: failed to copy essential config files")
                print(e)
                sys.exit()

    # copy over filters to ~/.avianz/Filters/:
    filterdir = os.path.join(configdir, "Filters/")
    if not os.path.isdir(filterdir):
        print("Creating filter dir %s" % filterdir)
        os.makedirs(filterdir)
    for f in os.listdir("Filters"):
        ff = os.path.join("Filters", f) # Kiwi.txt
        if not os.path.isfile(os.path.join(filterdir, f)): # ~/.avianz/Filters/Kiwi.txt
            print("Recogniser %s not found, providing default" % f)
            try:
                shutil.copy2(ff, filterdir) # cp Filters/Kiwi.txt ~/.avianz/Filters/
            except Exception as e:
                print("Warning: failed to copy recogniser %s to %s" % (ff, filterdir))
                print(e)

    # run splash screen:
    if cli:
        print("Starting AviaNZ in CLI mode")
        if batchmode:
            import AviaNZ_batch
            if os.path.isdir(sdir1) and recogniser in confloader.filters(filterdir).keys():
                avianzbatch = AviaNZ_batch.AviaNZ_batchProcess(parent=None, mode="CLI", configdir=configdir, sdir=sdir1, recogniser=recogniser, wind=wind)
                print("Analysis complete, closing AviaNZ")
            else:
                print("ERROR: valid input dir (-d) and recogniser name (-r) are essential for batch processing")
                sys.exit()
        elif training:
            import Training
            if os.path.isdir(sdir1) and os.path.isdir(sdir2) and recogniser in confloader.filters(filterdir).keys() and width>0:
                training = Training.CNNtrain(configdir,filterdir,sdir1,sdir2,recogniser,width,CLI=True)
                training.cliTrain()
                print("Training complete, closing AviaNZ")
            else:
                print("ERROR: valid input dirs (-d and -e) and recogniser name (-r) are essential for training")
                sys.exit()
        elif testing:
            import Training
            if os.path.isdir(sdir1) and recogniser in confloader.filters(filterdir).keys():
                testing = Training.CNNtest(sdir1,recogniser,configdir,filterdir,CLI=True)
                print("Testing complete, closing AviaNZ")
            else:
                print("ERROR: valid input dir (-d) and recogniser name (-r) are essential for training")
                sys.exit()
        else:
            if (cheatsheet or zooniverse) and isinstance(infile, str):
                import AviaNZ
                avianz = AviaNZ(configdir=configdir, CLI=True, cheatsheet=cheatsheet, zooniverse=zooniverse,
                                firstFile=infile, imageFile=imagefile, command=command)
                print("Analysis complete, closing AviaNZ")
            else:
                print("ERROR: valid input file (-f) is needed")
                sys.exit()
    else:
        print("Starting AviaNZ in GUI mode")
        # This screen asks what you want to do, then processes the response
        import Dialogs
        from PyQt5.QtWidgets import QApplication
        app = QApplication(sys.argv)
        first = Dialogs.StartScreen()
        first.show()
        app.exec_()

        task = first.getValues()

        avianz = None
        if task == 1:
            import AviaNZ_manual
            avianz = AviaNZ_manual.AviaNZ(configdir=configdir)
        elif task==2:
            import AviaNZ_batch_GUI
            avianz = AviaNZ_batch_GUI.AviaNZ_batchWindow(configdir=configdir)
        elif task==3:
            import AviaNZ_batch_GUI
            avianz = AviaNZ_batch_GUI.AviaNZ_reviewAll(configdir=configdir)

        if avianz:
            avianz.show()
        else:
            return
        out = app.exec_()
        QApplication.closeAllWindows()

        # restart requested:
        if out == 1:
            mainlauncher()
        elif out == 2:
            import SplitAnnotations
            avianz = SplitAnnotations.SplitData()
            avianz.show()
            app.exec_()
            print("Processing complete, returning to AviaNZ")
            QApplication.closeAllWindows()
Example #22
0
class Main:
    """Main class of the application"""
    def __init__(self):
        """Initializes the application"""
        self.__application = QApplication(sys.argv)
        self.__application.setApplicationName('OE Printtool Client')
        self.__mainWindow = QMainWindow()
        self.__mainWindow.setWindowTitle('OE Printtool Client')

        # ensures that there is data before continuing
        ssh_input = SSHInput(self.__mainWindow)
        self._connection = Connection(ssh_input)
        self._config = Config()
        try:
            with open(self._config.get("Data", "file"), 'r'):
                pass
        except FileNotFoundError:
            copyfile(self._config.get('Data', 'template_file'),
                     self._config.get('Data', 'file'))

        try:
            if not self._config.get('Data', 'initialized_local_data_file'):
                if self._config.get('SSH', 'host') == '':
                    raise RuntimeWarning(
                        'SSH host is needed for initial synchronization of data file'
                    )
                else:
                    print(
                        'Initial synchronization of data file with server-side data file'
                    )
                    self._connection.synchronize_data()
                    self._config.set('Data', 'initialized_local_data_file',
                                     'true')
                    self._config.write()
        except RuntimeWarning as rw:
            message, = rw.args
            if message != 'SSH host is needed for initial synchronization of data file':
                raise
            ssh_message_box = QMessageBox()
            ssh_message_box.setText(
                'Please enter the SSH host used for the orientation unit directory in the preferences window '
                '(Edit->Preferences)')
            ssh_message_box.setWindowTitle('SSH Host is missing')
            ssh_message_box.exec()

        # set up main window
        self.__configurationView = None  # type: ConfigurationView
        self.__materialView = None  # type: MaterialView
        self.__contentPane = self.__create_content_pane()
        self.__menuBar = self.__create_menu_bar()
        self.__mainWindow.setCentralWidget(self.__contentPane)
        self.__mainWindow.setMenuBar(self.__menuBar)
        self.__mainWindow.showMaximized()
        self.__configurationView.select_first_item()
        self.__returnCode = self.__application.exec()

    def return_code(self):
        """Returns the return code"""
        return self.__returnCode

    def __close(self):
        """Closes the application"""
        self.__application.closeAllWindows()

    def __create_content_pane(self):
        """Creates the central content pane"""
        content_pane = QWidget(self.__mainWindow)
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        content_pane.setLayout(layout)
        # add configuration view
        self.__configurationView = ConfigurationView(content_pane)
        layout.addWidget(self.__configurationView)
        # add material view
        self.__materialView = MaterialView()
        layout.addWidget(self.__materialView)
        return content_pane

    def __create_menu_bar(self):
        """Creates the menu bar"""
        # create menus
        menu_bar = QMenuBar()
        # create file menu
        file_menu = QMenu('&File', menu_bar)
        close_action = file_menu.addAction('&Quit')
        close_action.triggered.connect(self.__close)
        close_action.setShortcut(QKeySequence.Quit)

        # edit menu
        edit_menu = QMenu('&Edit', menu_bar)
        config_dialog = ConfigDialog(self.__mainWindow)
        add_config_action = edit_menu.addAction('&Add configuration')
        add_config_action.triggered.connect(self.__add_configuration)
        resync_action = edit_menu.addAction('&Synchronize with server')
        resync_action.triggered.connect(self.__synchronize)
        preferences_action = edit_menu.addAction('&Preferences')
        preferences_action.triggered.connect(config_dialog.show)

        # create help menu
        help_menu = QMenu('&Help', menu_bar)
        about_qt_action = help_menu.addAction('About &Qt')
        about_qt_action.triggered.connect(self.__application.aboutQt)

        menu_bar.addMenu(file_menu)
        menu_bar.addMenu(edit_menu)
        menu_bar.addMenu(help_menu)
        return menu_bar

    def __add_configuration(self):
        add_dialog = AddConfigurationDialog()
        result = add_dialog.exec()
        if result == QDialog.Accepted:
            config = add_dialog.get_configuration()
            self.__configurationView.add_configuration(config)

    def __synchronize(self):
        self._connection.reload_config()
        self._config = Config()
        self._connection.synchronize_data()
        if not self._config.get('Data', 'initialized_local_data_file'):
            self._config.set('Data', 'initialized_local_data_file', 'true')
            self._config.write()
        self.__configurationView.update_model()
        self.__materialView.update_model()
Example #23
0
class Controller(object):
    '''程序化入口类'''
    def __init__(self, logger, ui2eg_q, eg2ui_q):

        # 日志对象
        self.logger = logger
        # 初始化多语言
        # load_language("config")
        self._ui2egQueue = ui2eg_q
        self._eg2uiQueue = eg2ui_q

        # UI2EG发送请求对象
        self._request = SendRequest(self._ui2egQueue, self.logger)
        # 高分辨率支持
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        qInstallMessageHandler(lambda x, y, z: None)

        self.mainApp = QApplication(sys.argv)

        # 根据分辨率调整字体
        font = QFont("Microsoft YaHei UI", 11)
        pointsize = font.pointSize()
        font.setPixelSize(pointsize * 96 / 72)
        self.mainApp.setFont(font)

        ################创建回测报告####################
        self._createReportWin()
        ################################################

        version = ''
        if os.path.exists('../Version.txt'):
            with open('../Version.txt', 'r', encoding='utf-8-sig') as f:
                version = f.readline()
        if ' ' in version:
            version = version.split(' ')[1]
        if len(version) > 0:
            version = ' - ' + version

        self.mainWnd = FramelessWindow()
        self.mainWnd.setWindowTitle('极星量化' + version)
        self.app = QuantApplication(self, master=self.mainWnd)
        if self.app.settings.contains('theme') and self.app.settings.value(
                'theme') == 'vs-dark':
            theme = THESE_STATE_DARK
        else:
            theme = THESE_STATE_WHITE

        self.mainWnd.setWinThese(theme)
        self.mainWnd.setWindowIcon(QIcon('icon/epolestar ix2.ico'))
        # screen = QDesktopWidget().screenGeometry()
        # self.mainWnd.setGeometry(screen.width() * 0.1, screen.height() * 0.1, screen.width() * 0.8,
        #                          screen.height() * 0.8)
        # self.mainWnd.titleBar.buttonClose.clicked.connect(self.quitThread)
        self.mainWnd.titleBar.buttonClose.clicked.disconnect(
            self.mainWnd.titleBar.closeWindow)
        self.mainWnd.titleBar.buttonClose.clicked.connect(
            self.app.save_edit_strategy)
        self.mainWnd.setWidget(self.app)

        # 创建模块
        self.model = QuantModel(self.app, self._ui2egQueue, self._eg2uiQueue,
                                self.logger)
        self.app.init_control()
        self.logger.info("Create quant model!")

        # 策略管理器
        self.strategyManager = self.getStManager()

        # 创建接收引擎数据线程
        self.receiveEgThread = ChildThread(self.model.receiveEgEvent)

        # 设置日志更新
        # self.update_log()
        # self.update_mon()

    def _createReportWin(self):
        self.reportWnd = FramelessWindow()
        self.reportWnd.setObjectName("ReportWnd")
        self.reportWnd.resize(1000, 600)
        self.reportWnd.setMinimumSize(600, 600)
        # self.reportWnd.setMaximumSize(1000, 600)
        self.reportWnd.hideTheseBtn()
        # self.reportWnd.disabledMaximumBtn() #可以最大最小化
        self.reportWnd.setWindowTitle("回测报告")
        self.reportWnd.setWindowIcon(QIcon('icon/epolestar ix2.ico'))
        self.reportView = ReportView(self.reportWnd)
        self.reportView.setObjectName("ReportView")
        self.reportWnd.setWidget(self.reportView)

    def get_logger(self):
        return self.logger

    def update_log(self):
        try:
            self.app.updateLogText()
        except Exception as e:
            # self.logger.warn("异常", "程序退出异常")
            pass

    def update_mon(self):
        try:
            self.updateMonitor()
        except Exception as e:
            pass

    # def updateSig(self):
    #     self.app.updateSigText()
    #
    # def updateUsr(self):
    #     self.app.updateUsrText()

    def updateMonitor(self):
        # 更新监控界面策略信息
        try:
            strategyDict = self.strategyManager.getStrategyDict()
            # TODO: strategyDict的异常策略应该怎么处理?
            for stId in strategyDict:
                if "RunningData" not in strategyDict[stId]:
                    continue
                try:
                    # TODO:StrategyState为什么会不存在呢?
                    if strategyDict[stId][
                            "StrategyState"] == ST_STATUS_PAUSE or strategyDict[
                                stId]["StrategyState"] == ST_STATUS_QUIT or strategyDict[
                                    stId][
                                        "StrategyState"] == ST_STATUS_EXCEPTION:
                        continue
                except KeyError as e:
                    self.logger.warn(f"策略数据错误: {stId}, {strategyDict[stId]}")
                self.app.updateValue(stId, strategyDict[stId]["RunningData"])
        except PermissionError as e:
            self.logger.error("更新监控信息时出错")

    def quitThread(self):
        self.logger.info("quitThread exit")
        # 停止更新界面子线程
        # self.monitorThread.stop()
        # self.monitorThread.join()

        # 停止更新信号记录
        # self.sigThread.stop()
        # self.sigThread.join()

        # 停止更新用户日志
        # self.usrThread.stop()
        # self.usrThread.join()

        # 向引擎发送退出事件
        self.sendExitRequest()

        # 停止接收策略引擎队列数据
        self.receiveEgThread.stop()
        self.model.receiveExit()
        self.receiveEgThread.join()

        self.logger.info("before app.close")
        self.reportWnd.close()
        # self.mainApp.quit()
        self.mainApp.closeAllWindows()
        self.logger.info("after app.close")

    def run(self):
        import os
        self.logger.info("ControlProcess pid: " + str(os.getpid()))
        # 启动监控策略线程
        # self.monitorThread.start()
        # 启动接收数据线程
        self.receiveEgThread.start()

        # self.sigThread.start()

        # self.usrThread.start()

        # 启动主界面线程

        self.mainWnd.show()
        self.mainApp.exec_()

    def set_help_text(self, funcName, text):
        self.app.set_help_text(funcName, text)

    def setEditorTextCode(self, path):
        """设置当前编辑的策略路径和代码信息"""
        self.model.setEditorTextCode(path)

    def getEditorText(self):
        return self.model.getEditorText()

    def getStManager(self):
        """获取策略管理器"""
        return self.model.getStrategyManager()

    def saveStrategy(self):
        """保存当前策略"""
        self.app.quant_editor.saveEditor()

    def parseStrategtParam(self, strategyPath):
        """解析策略中的用户参数"""
        g_params = {}
        with open(strategyPath, 'r', encoding="utf-8") as f:
            content = [line.strip() for line in f]
            for c in content:
                # regex = re.compile(r"^g_params[\[][\"\'](.*)[\"\'][\]]\s*=[\s]*([^\s]*)[\s]*(#[\s]*(.*))?")
                regex1 = re.compile(
                    r"^g_params[\[][\"\'](.*)[\"\'][\]]\s*=[\s]*(.*)[\s]*#[\s]*(.*)?"
                )
                regex2 = re.compile(
                    r"^g_params[\[][\"\'](.*)[\"\'][\]]\s*=[\s]*(.*)[\s]*#?[\s]*(.*)?"
                )

                reg1 = regex1.search(c)
                reg2 = regex2.search(c)
                if reg1 or reg2:
                    reg = reg1 if reg1 else reg2
                    ret = [reg.groups()[1], reg.groups()[2]]
                    # if ret[1] is None: ret[1] = ""
                    try:
                        ret[0] = eval(ret[0])
                    except:
                        pass
                    g_params.update({reg.groups()[0]: ret})
        return g_params

    def load(self, strategyPath, param={}):  # 这个函数没有用到
        # TODO:新增param参数,用于接收用户策略的参数
        """
        加载合约事件
        :param strategyPath: 策略路径
        :param param: 策略参数信息
        :return:
        """
        # 运行策略前将用户修改保存
        self.saveStrategy()
        # 解析策略参数
        param = self.parseStrategtParam(strategyPath)
        self.app.create_strategy_policy_win(param=param)  # 通过传入参数来新建属性设置窗体

        config = self.app.getConfig()
        if config:  # 获取到config
            self._request.loadRequest(strategyPath, config)
            self.logger.info("load strategy")

    def paramLoad(self, id):
        """用户参数修改后策略重新启动"""
        param = self.getUserParam(id)  # 从strategyManager获取到参数信息
        strategyPath = self.strategyManager.getSingleStrategy(id)["Path"]
        self.app.create_strategy_policy_win(param, strategyPath, id)

    def generateReportReq(self, strategyIdList):  # 策略运行右键菜单里的投资报告
        """发送生成报告请求"""
        # 量化启动时的恢复策略列表中的策略没有回测数据
        # 策略停止之后的报告数据从本地获取,不发送请求
        # 策略启动时查看数据发送报告请求,从engine获取数据
        # 查看策略的投资报告(不支持查看多个)
        if len(strategyIdList) >= 1:
            id = strategyIdList[0]
            status = self.strategyManager.queryStrategyStatus(id)
            strategyData = self.strategyManager.getSingleStrategy(id)
            self.logger.info(
                f"strategyID {id} strategystatus {status}  strategyData")
            # self.logger.info(strategyData)
            if status == ST_STATUS_QUIT:  # 策略已停止,从本地获取数据
                if "ResultData" not in strategyData:  # 程序启动时恢复的策略没有回测数据
                    QMessageBox.warning(None, '警告', '策略未启动,报告数据不存在')
                    QMessageBox.warning(None, '警告', '启动测试报告窗体')
                    self.reportWnd.show()
                    self.reportWnd.raise_()
                    return
                reportData = strategyData["ResultData"]
                self.app.reportDisplay(reportData, id)
                return
            if "ResultData" in strategyData:
                self.logger.info("不管策略的状态,只要本地有回测数据,就显示出来")
                # self.logger.info(strategyData)
                reportData = strategyData["ResultData"]
                self.app.reportDisplay(reportData, id)
                return

            self._request.reportRequest(id)

    def newDir(self, path):
        """策略目录右键新建文件夹"""
        if not os.path.exists(path):
            os.makedirs(path)
        self.app.updateStrategyTree(path)

    def updateEditor(self, path):
        """
        更新策略编辑的内容和表头
        :param path: 策略路径,为空则将编辑界面内容置为空
        :return:
        """
        editor = self.getEditorText()
        fileName = os.path.basename(path)

        self.updateEditorHead(fileName)
        self.app.updateEditorText(editor["code"])

    def updateEditorHead(self, text):
        """更新策略表头"""
        self.app.updateEditorHead(text)

    def sendExitRequest(self):
        """发送量化界面退出请求"""
        self._request.quantExitRequest()

    def pauseRequest(self, strategyIdList):
        """
        发送所选策略暂停请求
        :param strategyId: 所选策略Id列表
        :return:
        """
        for id in strategyIdList:
            self._request.strategyPause(id)

    def resumeRequest(self, strategyIdList):  # 策略运行右键菜单里的启动
        """
        发送所选策略恢复运行请求
        :param strategyId: 所选策略Id列表
        :return:
        """
        for id in strategyIdList:
            # 策略如果是启动状态,则忽略此次启动请求
            strategyDict = self.strategyManager.getStrategyDict()
            if id in strategyDict:
                status = self.strategyManager.queryStrategyStatus(id)
                if status == ST_STATUS_HISTORY or status == ST_STATUS_CONTINUES:
                    self.logger.info("策略重复启动!")
                    continue
            self._request.strategyResume(id)

    def quitRequest(self, strategyIdList):  # 策略运行右键菜单里的停止
        """
        发送所选策略停止请求
        :param strategyId:  所选策略Id列表
        :return:
        """
        for id in strategyIdList:
            strategyDict = self.strategyManager.getStrategyDict()
            if id in strategyDict:
                status = self.strategyManager.queryStrategyStatus(id)
                if status == ST_STATUS_QUIT:
                    self.logger.info("策略%s已停止!" % (id))
                    continue
                self._request.strategyQuit(id)
            else:
                self.logger.info("策略管理器中不存在策略%s" % (id))

    def delStrategy(self, strategyIdList):  # 策略运行右键菜单里的删除
        # 获取策略管理器
        for id in strategyIdList:
            strategyDict = self.strategyManager.getStrategyDict()
            if id in strategyDict:
                if strategyDict[id]["StrategyState"] == ST_STATUS_QUIT or \
                        strategyDict[id]["StrategyState"] == ST_STATUS_EXCEPTION:  # 策略已经停止或策略异常
                    self.strategyManager.removeStrategy(id)
                    self.app.delUIStrategy(id)
                self._request.strategyRemove(id)
            else:
                self.app.delUIStrategy(id)

    def signalDisplay(self, strategyIdList):  # 策略运行右键菜单里的图表展示
        """查看策略的信号及指标图(默认查看一个)"""
        if len(strategyIdList) >= 1:
            id = strategyIdList[0]
            self._request.strategySignal(id)

    def getUserParam(self, id):
        """获取用户设置的参数信息"""
        return self.strategyManager.getStrategyParamData(id)

    def paramSetting(self, strategyIdList):  # 策略运行右键菜单里的属性设置
        """发送属性设置事件"""
        if len(strategyIdList) >= 1:
            id = strategyIdList[0]

            self.paramLoad(id)  # 加载已经设置好的设置信息
Example #24
0
    def _exception_hook(self, exctype, excvalue, tb):  # noqa
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        exc = (exctype, excvalue, tb)

        if not self._quit_status['crash']:
            log.misc.error("ARGH, there was an exception while the crash "
                           "dialog is already shown:", exc_info=exc)
            return

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit or
                                not issubclass(exctype, Exception))

        if self._args.pdb_postmortem:
            pdb.post_mortem(tb)

        if (is_ignored_exception or self._args.no_crash_dialog or
                self._args.pdb_postmortem):
            # pdb exit, KeyboardInterrupt, ...
            status = 0 if is_ignored_exception else 2
            try:
                self.shutdown(status)
                return
            except Exception:
                log.init.exception("Error while shutting down")
                self.quit()
                return

        self._quit_status['crash'] = False

        try:
            pages = self._recover_pages(forgiving=True)
        except Exception:
            log.destroy.exception("Error while recovering pages")
            pages = []

        try:
            cmd_history = objreg.get('command-history')[-5:]
        except Exception:
            log.destroy.exception("Error while getting history: {}")
            cmd_history = []

        try:
            objects = self.get_all_objects()
        except Exception:
            log.destroy.exception("Error while getting objects")
            objects = ""

        try:
            objreg.get('ipc-server').ignored = True
        except Exception:
            log.destroy.exception("Error while ignoring ipc")

        try:
            self.lastWindowClosed.disconnect(self.on_last_window_closed)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")
        QApplication.closeAllWindows()
        self._crashdlg = crashdialog.ExceptionCrashDialog(
            self._args.debug, pages, cmd_history, exc, objects)
        ret = self._crashdlg.exec_()
        if ret == QDialog.Accepted:  # restore
            self._do_restart(pages)

        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self._destroy_crashlogfile()
        sys.exit(1)
Example #25
0
        self.ob = onebutton.oneButton(self.apiKey.text(), self.secret.text())
        order = self.ob.sell_crypto_currency(self.ticker.text(), self.symbol.text())
        if order == -1:
            self.log.append('주문실패')
        else:
            self.log.append('매수호가' + '(' + self.symbol.text() + ')' + ': ' + str(self.ob.buy_price))
            self.log.append('수량' + '(' + self.symbol.text() + ')' + ': ' + str(self.ob.unit) + '\n')
            self.log.append('남은개수' + '(' + self.ticker.text() + ')' + ': ' + str(self.ob.balance[self.ticker.text()]['free']))
        #except:
            #self.log.append('매도실패')

        return order

    def cancel(self):
        self.ob = onebutton.oneButton(self.apiKey.text(), self.secret.text())

        resp = self.ob.cancel(self.symbol.text(), -1)
        print('resp', resp)
        if self.ob.cancelSuccess == True:
            self.log.append('주문취소ID' + '(' + self.symbol.text() + ')' + ': ' + str(self.ob.orderId))
            self.log.append('주문취소가격' + '(' + self.symbol.text() + ')' + ': ' + str(self.ob.orderPrice))
        else:
            self.log.append('주문취소실패')

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dl = testDialog()
    dl.show()
    app.exec_()
    sys.exit(app.closeAllWindows())
Example #26
0
 def handleQuit(self):
     if QMessageBox.question(None, '', "Are you sure you want to quit?",
                             QMessageBox.Yes | QMessageBox.No,
                             QMessageBox.No) == QMessageBox.Yes:
         QApplication.closeAllWindows(self)
Example #27
0
def mainlauncher(cli, cheatsheet, zooniverse, infile, imagefile, batchmode,
                 training, testing, sdir1, sdir2, recogniser, wind, width,
                 command):
    # adapt path to allow this to be launched from wherever
    import sys, os
    if getattr(sys, 'frozen', False):
        appdir = sys._MEIPASS
    else:
        appdir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(appdir)

    # print("Using python at", sys.path)
    # print(os.environ)
    # print("Version", sys.version)

    try:
        import platform, json, shutil
        from jsonschema import validate
        import SupportClasses
    except Exception as e:
        print("ERROR: could not import packages")
        raise

    # determine location of config file and bird lists
    if platform.system() == 'Windows':
        # Win
        configdir = os.path.expandvars(os.path.join("%APPDATA%", "AviaNZ"))
    elif platform.system() == 'Linux' or platform.system() == 'Darwin':
        # Unix
        configdir = os.path.expanduser("~/.avianz/")
    else:
        print("ERROR: what OS is this? %s" % platform.system())
        raise

    # if config and bird files not found, copy from distributed backups.
    # so these files will always exist on load (although they could be corrupt)
    # (exceptions here not handled and should always result in crashes)
    if not os.path.isdir(configdir):
        print("Creating config dir %s" % configdir)
        try:
            os.makedirs(configdir)
        except Exception as e:
            print("ERROR: failed to make config dir")
            print(e)
            raise

    # pre-run check of config file validity
    confloader = SupportClasses.ConfigLoader()
    configschema = json.load(open("Config/config.schema"))
    learnparschema = json.load(open("Config/learnpar.schema"))
    try:
        config = confloader.config(os.path.join(configdir, "AviaNZconfig.txt"))
        validate(instance=config, schema=configschema)
        learnpar = confloader.learningParams(
            os.path.join(configdir, "LearningParams.txt"))
        validate(instance=learnpar, schema=learnparschema)
        print("successfully validated config file")
    except Exception as e:
        print("Warning: config file failed validation with:")
        print(e)
        try:
            shutil.copy2("Config/AviaNZconfig.txt", configdir)
            shutil.copy2("Config/LearningParams.txt", configdir)
        except Exception as e:
            print("ERROR: failed to copy essential config files")
            print(e)
            raise

    # check and if needed copy any other necessary files
    necessaryFiles = [
        "ListCommonBirds.txt", "ListDOCBirds.txt", "ListBats.txt",
        "LearningParams.txt"
    ]
    for f in necessaryFiles:
        if not os.path.isfile(os.path.join(configdir, f)):
            print("File %s not found in config dir, providing default" % f)
            try:
                shutil.copy2(os.path.join("Config", f), configdir)
            except Exception as e:
                print("ERROR: failed to copy essential config files")
                print(e)
                raise

    # copy over filters to ~/.avianz/Filters/:
    filterdir = os.path.join(configdir, "Filters/")
    if not os.path.isdir(filterdir):
        print("Creating filter dir %s" % filterdir)
        os.makedirs(filterdir)
    for f in os.listdir("Filters"):
        ff = os.path.join("Filters", f)  # Kiwi.txt
        if not os.path.isfile(os.path.join(filterdir,
                                           f)):  # ~/.avianz/Filters/Kiwi.txt
            print("Recogniser %s not found, providing default" % f)
            try:
                shutil.copy2(
                    ff, filterdir)  # cp Filters/Kiwi.txt ~/.avianz/Filters/
            except Exception as e:
                print("Warning: failed to copy recogniser %s to %s" %
                      (ff, filterdir))
                print(e)

    # run splash screen:
    if cli:
        print("Starting AviaNZ in CLI mode")
        if batchmode:
            import AviaNZ_batch
            if os.path.isdir(sdir1) and recogniser in confloader.filters(
                    filterdir).keys():
                avianzbatch = AviaNZ_batch.AviaNZ_batchProcess(
                    parent=None,
                    mode="CLI",
                    configdir=configdir,
                    sdir=sdir1,
                    recogniser=recogniser,
                    wind=wind)
                print("Analysis complete, closing AviaNZ")
            else:
                print(
                    "ERROR: valid input dir (-d) and recogniser name (-r) are essential for batch processing"
                )
                raise
        elif training:
            import Training
            if os.path.isdir(sdir1) and os.path.isdir(
                    sdir2) and recogniser in confloader.filters(
                        filterdir).keys() and width > 0:
                training = Training.CNNtrain(configdir,
                                             filterdir,
                                             sdir1,
                                             sdir2,
                                             recogniser,
                                             width,
                                             CLI=True)
                training.cliTrain()
                print("Training complete, closing AviaNZ")
            else:
                print(
                    "ERROR: valid input dirs (-d and -e) and recogniser name (-r) are essential for training"
                )
                raise
        elif testing:
            import Training
            filts = confloader.filters(filterdir)
            if os.path.isdir(sdir1) and recogniser in filts:
                testing = Training.CNNtest(sdir1,
                                           filts[recogniser],
                                           recogniser,
                                           configdir,
                                           filterdir,
                                           CLI=True)
                print("Testing complete, closing AviaNZ")
            else:
                print(
                    "ERROR: valid input dir (-d) and recogniser name (-r) are essential for training"
                )
                raise
        else:
            if (cheatsheet or zooniverse) and isinstance(infile, str):
                import AviaNZ
                avianz = AviaNZ(configdir=configdir,
                                CLI=True,
                                cheatsheet=cheatsheet,
                                zooniverse=zooniverse,
                                firstFile=infile,
                                imageFile=imagefile,
                                command=command)
                print("Analysis complete, closing AviaNZ")
            else:
                print("ERROR: valid input file (-f) is needed")
                raise
    else:
        task = None
        print("Starting AviaNZ in GUI mode")
        from PyQt5.QtWidgets import QApplication
        app = QApplication(sys.argv)
        # a hack to fix default font size (Win 10 suggests 7 pt for QLabels for some reason)
        QApplication.setFont(QApplication.font("QMenu"))

        while True:
            # splash screen?
            if task is None:
                # This screen asks what you want to do, then processes the response
                import Dialogs
                first = Dialogs.StartScreen()
                first.show()
                app.exec_()
                task = first.getValues()

            avianz = None
            if task == 1:
                import AviaNZ_manual
                avianz = AviaNZ_manual.AviaNZ(configdir=configdir)
            elif task == 2:
                import AviaNZ_batch_GUI
                avianz = AviaNZ_batch_GUI.AviaNZ_batchWindow(
                    configdir=configdir)
            elif task == 3:
                import AviaNZ_batch_GUI
                avianz = AviaNZ_batch_GUI.AviaNZ_reviewAll(configdir=configdir)
            elif task == 4:
                import SplitAnnotations
                avianz = SplitAnnotations.SplitData()

            # catch bad initialiation
            if avianz:
                avianz.activateWindow()
            else:
                return

            out = app.exec_()
            QApplication.closeAllWindows()
            QApplication.processEvents()

            # catch exit code to see if restart requested:
            # (note: do not use this for more complicated cleanup,
            #  no guarantees that it is returned before program closes)
            if out == 0:
                # default quit
                break
            elif out == 1:
                # restart to splash screen
                task = None
            elif out == 2:
                # request switch to Splitter
                task = 4
Example #28
0
 def fileQuit(self):
     # This closes application
     QApplication.closeAllWindows()
Example #29
0
class TestMemory(unittest.TestCase):
    @mock.patch("src.games.hangman.hangman.HangmanWindow.initialize_database")
    def setUp(self, method) -> None:
        self.app = QApplication([])
        self.hangman = HangmanWindow("username")

    def tearDown(self) -> None:
        self.app.closeAllWindows()

    @mock.patch("src.games.hangman.hangman.GameDatabaseManagement",
                autospec=True)
    def test_initialize_database(self, mock_class):
        hangman = HangmanWindow("username")
        mock_class.assert_called_once_with(
            "src/databases/hangman.csv", "username",
            ["unlocked_level", "word_guessed_by_letter"])
        mock_class.return_value.initialize_user_account.assert_called_once_with(
            [1, 0.0])

    def test_get_trials(self):
        self.assertTrue(HangmanWindow.get_trials(4), 10)
        self.assertTrue(HangmanWindow.get_trials(8), 9)
        self.assertTrue(HangmanWindow.get_trials(12), 8)
        self.assertTrue(HangmanWindow.get_trials(16), 7)
        self.assertTrue(HangmanWindow.get_trials(18), 6)

    def test_get_hangman_picture_paths(self):
        folder = "src/assets/hangman"
        self.assertEqual(HangmanWindow.get_hangman_picture_paths(6), [
            f"{folder}/hangman1.png", f"{folder}/hangman2.png",
            f"{folder}/hangman3.png", f"{folder}/hangman4.png",
            f"{folder}/hangman5.png", f"{folder}/hangman10.png"
        ])

    def test_get_blanked_word(self):
        self.assertEqual(HangmanWindow.get_blanked_word("hallo"), "_ _ _ _ _ ")

    def test_letter_not_in_searched_word(self):
        self.hangman.searched_word = "letter"
        self.assertTrue(self.hangman.letter_not_in_searched_word("x"))
        self.assertFalse(self.hangman.letter_not_in_searched_word("e"))

    @mock.patch("src.games.hangman.hangman.QtGui.QPixmap")
    def test_update_hangman(self, mock_class):
        self.hangman.trials_left = 5
        self.hangman.trials_left_label = QtWidgets.QLabel(
            f"Trials left: {self.hangman.trials_left}")
        self.hangman.hangman_pic_label = mock.MagicMock()
        self.hangman.hangman_pic_label.setPixmap = mock.MagicMock()
        self.hangman.hangman_picture_list = [1, 2, 3, 4, 5]
        self.hangman.update_hangman()

        self.assertEqual(4, self.hangman.trials_left)
        self.assertEqual("Trials left: 4",
                         self.hangman.trials_left_label.text())

    def test_update_searched_word(self):
        self.hangman.searched_blank_word = "_ _ _ "
        self.hangman.searched_word = "UHU"
        self.hangman.searched_blank_word_label = QtWidgets.QLabel(
            f"Trials left: {self.hangman.trials_left}")

        self.hangman.update_searched_word("H")
        self.assertEqual("_ H _ ", self.hangman.searched_blank_word)
        self.assertEqual("_ H _ ",
                         self.hangman.searched_blank_word_label.text())

    def test_update_used_letters(self):
        self.hangman.used_letters_list = ["E", "A"]
        self.hangman.update_used_letters("E")
        self.assertEqual(self.hangman.used_letters_list, ["E", "A"])
Example #30
0
 def _shutdown(self, status):  # noqa
     """Second stage of shutdown."""
     # pylint: disable=too-many-branches, too-many-statements
     # FIXME refactor this
     # https://github.com/The-Compiler/qutebrowser/issues/113
     log.destroy.debug("Stage 2 of shutting down...")
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         self.removeEventFilter(self._event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         config_obj = objreg.get('config')
     except KeyError:
         log.destroy.debug("Config not initialized yet, so not saving "
                           "anything.")
     else:
         to_save = []
         if config.get('general', 'auto-save-config'):
             to_save.append(("config", config_obj.save))
             try:
                 key_config = objreg.get('key-config')
             except KeyError:
                 pass
             else:
                 to_save.append(("keyconfig", key_config.save))
         to_save += [("window geometry", self._save_geometry)]
         try:
             command_history = objreg.get('command-history')
         except KeyError:
             pass
         else:
             to_save.append(("command history", command_history.save))
         try:
             quickmark_manager = objreg.get('quickmark-manager')
         except KeyError:
             pass
         else:
             to_save.append(("command history", quickmark_manager.save))
         try:
             state_config = objreg.get('state-config')
         except KeyError:
             pass
         else:
             to_save.append(("window geometry", state_config.save))
         try:
             cookie_jar = objreg.get('cookie-jar')
         except KeyError:
             pass
         else:
             to_save.append(("cookies", cookie_jar.save))
         for what, handler in to_save:
             log.destroy.debug("Saving {} (handler: {})".format(
                 what, utils.qualname(handler)))
             try:
                 handler()
             except AttributeError as e:
                 log.destroy.warning("Could not save {}.".format(what))
                 log.destroy.debug(e)
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactiving crash log...")
     self._destroy_crashlogfile()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactiving message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     # We use a singleshot timer to exit here to minimize the likelyhood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(self.exit, status))
Example #31
0
class EmotionStimulusController:
    def __init__(self):
        # print(sys.getrecursionlimit())
        self.app = QApplication(sys.argv)
        self.setting = Setting("Conf\\Setting.yaml")

        self.view = Ui_MainWindow()
        mainWidget = Ui_MainWidget()

        mainWidget.setupUi(self.view.widget)
        # Set widget to center
        self.moveToCenter()
        mainWidget.startButton.clicked.connect(self.startTest(mainWidget))
        mainWidget.personalBox.activated.connect(
            self.activateDirectory(mainWidget))
        mainWidget.dirButton.clicked.connect(
            self.selectPicturesDict(mainWidget))

        self.mainWidget = mainWidget
        # numimages and sleeptime
        self.numImages = 130
        self.sleepTime = 10

        # imageThread
        self.imageGen = ImageGenerator(self.setting.conf["IMAGEDAT_DIR"])

        # time counter
        self.timeCounter = TimeCounter(self.sleepTime)
        self.timeCounter.signalMove.connect(self.showQuestion)

        # time start
        self.times = [0, 0]
        self.timesTest = [0, 0]

        # index
        self.index = 0
        # data
        self.data = pd.DataFrame(columns=[
            "Time_Start", "Time_End", "TestTime_Start", "TestTime_End",
            "Valence", "Arousal", "Emotion", "Image", "Valence_label",
            "Arousal_label"
        ])
        # filename for experiment data
        self.filename = str(datetime.now()).replace(" ", "_").replace(":", "-")
        self.subjectname = ""

        # video recorder
        self.videoRecorder = VideoRecorder()

        # personal picture
        self.personal = False
        self.personalDict = ""

    def activateDirectory(self, widget):
        def activate():
            idx = widget.personalBox.currentIndex()
            if idx == 1:
                widget.dirButton.setEnabled(True)
                self.personal = True
            else:
                widget.dirButton.setEnabled(False)
                widget.dirField.setText("")
                self.personal = False

        return activate

    def selectPicturesDict(self, widget):
        def select():
            fileDir = widget.pictureDict()
            widget.dirField.setText(fileDir)
            self.personalDict = fileDir

        return select

    def startTest(self, widget):
        def start():
            if (widget.nameField.text() == ""):
                QMessageBox.information(self.view, "Information",
                                        "Please insert your name")
                return
            self.subjectname = widget.fileName()
            self.filename += self.subjectname + "_" + str(
                self.personal) + ".csv"
            # start video recording
            videoname = str(datetime.now()).replace(" ", "_").replace(
                ":", "-") + self.subjectname + ".avi"
            self.videoRecorder.setFileName(
                os.path.join(self.setting.conf["VIDEO_DIR"], videoname))
            self.videoRecorder.start()
            self.imageGen.setParams(widget.sexField.currentText())
            if self.personal:
                imgLen = self.imageGen.readPersonalPictures(self.personalDict)
                if imgLen < self.setting.conf["MIN_PERSONAL_IMAGES"]:
                    QMessageBox.warning(
                        self.view, "Error",
                        str(self.setting.conf["MIN_PERSONAL_IMAGES"]) +
                        "枚の写真は必要です。")
                    return

            self.showImage()

        return start

    def moveToCenter(self):
        self.view.widget.move(self.app.desktop().screen().rect().center() -
                              self.view.widget.rect().center())

    def showImage(self):
        try:
            # set bg color
            self.view.setStyleSheet("background-color: black;")
            # clear the widget
            self.view.widget.hide()
            self.view.widget.children()[0].setParent(None)
            # set the widget
            widget = Ui_ImageWidget()
            widget.setupUi(self.view.widget)
            self.view.widget.activateWindow()

            self.setImage(widget.imageLabel)
            # move to center
            self.moveToCenter()
            # show the widget
            self.view.widget.update()
            self.view.widget.show()
            self.times[0] = datetime.now()

        except:
            raise ("Error when trying to show image")

    def showQuestion(self):
        # set bg color
        self.view.setStyleSheet("")
        # record the start time
        self.timesTest[0] = datetime.now()
        # terminate video recording

        self.times[1] = datetime.now()
        # terminate counter
        self.timeCounter.timeStop()
        # clear the widget
        self.view.widget.hide()
        self.view.widget.children()[0].setParent(None)
        # set the widget
        widget = Ui_QuestionWidget()
        widget.setupUi(self.view.widget)
        widget.setValenceArousal(self.setting.conf["VALENCE_AROUSAL"])
        widget.nextButton.clicked.connect(self.getAnswer(widget))
        # move to center
        self.moveToCenter()
        # show the widget
        self.view.widget.update()
        self.view.widget.show()

    def getAnswer(self, widget):
        def get():
            self.timesTest[1] = datetime.now()
            valenceLevel = widget.valenceLevel()
            arousalLevel = widget.arousalLevel()
            emotionLevel = widget.emotionLevel()
            timeStart = self.times[0]
            timeEnd = self.times[1]
            testTimeStart = self.timesTest[0]
            testTimeEnd = self.timesTest[1]
            self.data = self.data.append(
                {
                    "Time_Start": timeStart,
                    "Time_End": timeEnd,
                    "TestTime_Start": testTimeStart,
                    "TestTime_End": testTimeEnd,
                    "Valence": valenceLevel,
                    "Arousal": arousalLevel,
                    "Emotion": emotionLevel,
                    "Image": self.image,
                    "Valence_label": self.valLabel,
                    "Arousal_label": self.arLabel
                },
                ignore_index=True)
            self.index += 1
            if (self.index >= self.numImages):
                self.showProcessDialog(
                    os.path.join(self.setting.conf["RESULT_DIR"],
                                 self.filename),
                    os.path.join(self.setting.conf["RESULT_DIR"],
                                 "imgList_" + self.filename))
            else:
                self.saveFile(
                    os.path.join(self.setting.conf["RESULT_DIR"],
                                 self.filename),
                    os.path.join(self.setting.conf["RESULT_DIR"],
                                 "imgList_" + self.filename))
                self.showImage()

        return get

    def setImage(self, imageLabel):

        if self.personal:
            img, val, ar, personalImage, gif = self.imageGen.pickImagePersonal(
            )
            if personalImage:
                path = os.path.join(self.personalDict, img)
            else:
                path = os.path.join(self.setting.conf["OASIS_DIR"], img)
        else:
            img, val, ar, gif = self.imageGen.pickImage()
            path = os.path.join(self.setting.conf["OASIS_DIR"], img)
        self.image = img
        self.valLabel = val
        self.arLabel = ar

        # print(os.path.join(self.setting.conf["OASIS_DIR"], path))
        imageLabel.setAlignment(QtCore.Qt.AlignCenter)
        if gif == 1:
            movie = QMovie(path, QtCore.QByteArray())
            movie.setScaledSize(QtCore.QSize().scaled(
                1024, 768, QtCore.Qt.KeepAspectRatio))
            imageLabel.setMovie(movie)
            movie.start()
        else:
            pixmap = QPixmap(path)
            resizedPix = pixmap.scaled(1024, 768, QtCore.Qt.KeepAspectRatio)
            imageLabel.setPixmap(resizedPix)
            imageLabel.update()
        self.timeCounter.start()

    def showProcessDialog(self, resultPath, imageListPath):
        try:
            QMessageBox.information(self.view, "Information",
                                    "Test is finished")
            self.saveFile(resultPath, imageListPath)
            self.videoRecorder.stop()
            self.quit()

        except:
            QMessageBox.warning(self.view, "Error", "Cannot save file")

    def saveFile(self, resultPath, imageListPath):
        self.data.to_csv(resultPath)
        imageList = pd.DataFrame({"imageList": self.imageGen.imageList})
        imageList.to_csv(imageListPath)

    def quit(self):
        self.videoRecorder.terminate()
        self.timeCounter.terminate()
        self.app.closeAllWindows()
        self.killProcess()
        self.app.exit()

    def killProcess(self):
        pid = os.getpid()
        parent = psutil.Process(pid)
        for child in parent.children(recursive=True):
            child.kill()
            parent.kill()

    def run(self):
        self.view.showFullScreen()
        return self.app.exec_()
Example #32
0
 def exitprogram(self):
     cursor = self.connection.cursor()
     cursor.execute("INSERT INTO history(id,login,time,action) VALUES('" + str("1") + "','" + str(self.ui.login_text.text()) + "','" + str(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M")) + "','Exit')")
     self.connection.commit()
     QApplication.closeAllWindows()
Example #33
0
    instrument = DfwController()
    opr = Operator(instrument)
    opr.load_config()

    create_scan_window_only = False  ##### Toggle this to showcase the scanwindow or the monitor

    if create_scan_window_only:
        app = QApplication(sys.argv)
        app_icon = QIcon(
            os.path.join(labphew.package_path, 'view', 'design', 'icons',
                         'labphew_icon.png'))
        app.setWindowIcon(app_icon)  # set an icon
        gui = ScanWindow(opr)
        gui.show()
        app.exit(app.exec_())
        app.closeAllWindows(
        )  # close any child window that might have been open
    else:
        # Create a PyQt application
        app = QApplication(sys.argv)
        app_icon = QIcon(
            os.path.join(labphew.package_path, 'view', 'design', 'icons',
                         'labphew_icon.png'))
        app.setWindowIcon(app_icon)  # set an icon
        gui = MonitorWindow(opr)
        # To add Scan window(s) to the Monitor window use the following code.
        add_scan_to_monitor = True  ##### Toggle this to showcase monitor with and without scanwindow
        if add_scan_to_monitor:
            scan_1 = ScanWindow(opr, parent=gui)
            scans = {
                'Sweep &voltage': [
                    scan_1, {
Example #34
0
 def handleQuit(self):
     if QMessageBox.question(None, '', "Are you sure you want to quit?",
                             QMessageBox.Yes | QMessageBox.No,
                             QMessageBox.No) == QMessageBox.Yes:
         QApplication.closeAllWindows(self)
Example #35
0
 def _shutdown(self, status, restart):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if q_app is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         event_filter = objreg.get('event-filter', None)
         if event_filter is not None:
             q_app.removeEventFilter(event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         ipc.server.shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e,
                     self._args,
                     "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     websettings.shutdown()
     # Disable application proxy factory to fix segfaults with Qt 5.10.1
     proxy.shutdown()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted)
             and not restart):
         atexit.register(shutil.rmtree,
                         self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     downloads.temp_download_manager.cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     session_manager = objreg.get('session-manager', None)
     if session_manager is not None:
         session_manager.delete_autosave()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(q_app.exit, status))
Example #36
0
class TestMemory(unittest.TestCase):
    def setUp(self) -> None:
        self.app = QApplication([])

    def tearDown(self) -> None:
        self.app.closeAllWindows()

    @mock.patch(
        "src.games.button_shooter.button_shooter.GameDatabaseManagement",
        autospec=True)
    def test_initialize_database(self, mock_class):
        button_shooter = ButtonShooterWindow("username")
        mock_class.assert_called_once_with("src/databases/button_shooter.csv",
                                           "username",
                                           ["unlocked_level", "hit_targets"])
        mock_class.return_value.initialize_user_account.assert_called_once_with(
            [1, 0])

    @mock.patch(
        "src.games.button_shooter.button_shooter.ButtonShooter.initialize_database",
        autospec=True)
    def test_play_game(self, mock_method):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.initialize_game = mock.MagicMock()
        button_shooter.show = mock.MagicMock()
        button_shooter.required_targets = 100
        button_shooter.show_start_screen = mock.MagicMock(
            return_value=QMessageBox.AcceptRole)
        button_shooter.timer = mock.MagicMock()
        button_shooter.timer.start = mock.MagicMock()
        button_shooter.show_buttons = mock.MagicMock()
        button_shooter.play_game(1)
        button_shooter.show_buttons.assert_called()

    @mock.patch(
        "src.games.button_shooter.button_shooter.ButtonShooter.initialize_database",
        autospec=True)
    def test_reject_play_game(self, mock_method):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.initialize_game = mock.MagicMock()
        button_shooter.show = mock.MagicMock()
        button_shooter.required_targets = 100
        button_shooter.show_start_screen = mock.MagicMock(
            return_value=QMessageBox.RejectRole)
        button_shooter.emit_game_menu_signal = mock.MagicMock()
        button_shooter.play_game(1)
        button_shooter.emit_game_menu_signal.assert_called()

    @mock.patch(
        "src.games.button_shooter.button_shooter.ButtonShooter.initialize_database",
        autospec=True)
    def test_update_timer(self, mock_method):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.countdown = 5
        button_shooter.countdown_label = mock.MagicMock()
        button_shooter.countdown_label.setText = mock.MagicMock()
        button_shooter.timer = mock.MagicMock()
        button_shooter.timer.stop = mock.MagicMock()
        button_shooter.end_the_game = mock.MagicMock()

        for i in range(5):
            button_shooter.update_timer()

        button_shooter.timer.stop.assert_called()
        button_shooter.end_the_game.assert_called()

    @mock.patch(
        "src.games.button_shooter.button_shooter.ButtonShooter.initialize_database",
        autospec=True)
    def test_update_values_is_true(self, mock_method):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.game_database = mock.MagicMock()
        button_shooter.game_database.get_values = mock.MagicMock(
            return_value={"hit_targets": 50})
        button_shooter.game_database.update_values = mock.MagicMock()
        button_shooter.hit_targets = 100

        button_shooter.update_values()
        button_shooter.game_database.update_values.assert_called_once_with(
            {"hit_targets": 100})

    @mock.patch(
        "src.games.button_shooter.button_shooter.ButtonShooter.initialize_database",
        autospec=True)
    def test_update_values_is_false(self, mock_method):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.game_database = mock.MagicMock()
        button_shooter.game_database.get_values = mock.MagicMock(
            return_value={"hit_targets": 150})
        button_shooter.game_database.update_values = mock.MagicMock()
        button_shooter.hit_targets = 100

        button_shooter.update_values()
        button_shooter.game_database.update_values.assert_called_once_with({})

    @mock.patch(
        "src.games.button_shooter.button_shooter.ButtonShooter.initialize_database",
        autospec=True)
    def test_end_of_game1(self, mock_method):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.update_values = mock.MagicMock()
        button_shooter.hit_targets = 2000
        button_shooter.required_targets = 2000
        button_shooter.selected_level = button_shooter.max_level
        button_shooter.show_every_level_completed = mock.MagicMock()
        button_shooter.emit_game_menu_signal = mock.MagicMock()

        button_shooter.end_the_game()

        button_shooter.show_every_level_completed.assert_called()
        button_shooter.emit_game_menu_signal.assert_called()

    def test_end_of_game2(self):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.update_values = mock.MagicMock()
        button_shooter.hit_targets = 2000
        button_shooter.required_targets = 2000
        button_shooter.unlock_next_level = mock.MagicMock()
        button_shooter.show_selection_for_next_game = mock.MagicMock(
            return_value=QMessageBox.AcceptRole)
        button_shooter.game_database.save_user_data = mock.MagicMock()
        button_shooter.emit_game_menu_signal = mock.MagicMock()
        button_shooter.end_the_game()

        button_shooter.emit_game_menu_signal.assert_called()

    def test_end_of_game3(self):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.update_values = mock.MagicMock()
        button_shooter.hit_targets = 2000
        button_shooter.required_targets = 2000
        button_shooter.unlock_next_level = mock.MagicMock()
        button_shooter.show_selection_for_next_game = mock.MagicMock(
            return_value=QMessageBox.RejectRole)
        button_shooter.game_database.save_user_data = mock.MagicMock()
        button_shooter.emit_play_next_level_signal = mock.MagicMock()
        button_shooter.end_the_game()

        button_shooter.emit_play_next_level_signal.assert_called()

    def test_end_of_game_losing(self):
        button_shooter = ButtonShooterWindow("username")
        button_shooter.update_values = mock.MagicMock()
        button_shooter.hit_targets = 200
        button_shooter.required_targets = 2000
        button_shooter.game_database.save_user_data = mock.MagicMock()
        button_shooter.emit_level_menu_signal = mock.MagicMock()

        button_shooter.show_losing_screen = mock.MagicMock(
            return_value=QMessageBox.DestructiveRole)
        button_shooter.end_the_game()
        button_shooter.emit_level_menu_signal.assert_called()

        button_shooter.emit_game_menu_signal = mock.MagicMock()
        button_shooter.show_losing_screen = mock.MagicMock(
            return_value=QMessageBox.AcceptRole)
        button_shooter.end_the_game()
        button_shooter.emit_game_menu_signal.assert_called()

        button_shooter.emit_play_level_again_signal = mock.MagicMock()
        button_shooter.show_losing_screen = mock.MagicMock(
            return_value=QMessageBox.RejectRole)
        button_shooter.end_the_game()
        button_shooter.emit_play_level_again_signal.assert_called()
Example #37
0
    def _exception_hook(self, exctype, excvalue, tb):  # noqa
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        # pylint: disable=broad-except

        exc = (exctype, excvalue, tb)

        if not self._quit_status['crash']:
            log.misc.error(
                "ARGH, there was an exception while the crash "
                "dialog is already shown:",
                exc_info=exc)
            return

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit
                                or not issubclass(exctype, Exception))

        if is_ignored_exception or self._args.no_crash_dialog:
            # pdb exit, KeyboardInterrupt, ...
            status = 0 if is_ignored_exception else 2
            try:
                self.shutdown(status)
                return
            except Exception:
                log.init.exception("Error while shutting down")
                self.quit()
                return

        self._quit_status['crash'] = False

        try:
            pages = self._recover_pages(forgiving=True)
        except Exception:
            log.destroy.exception("Error while recovering pages")
            pages = []

        try:
            history = objreg.get('command-history')[-5:]
        except Exception:
            log.destroy.exception("Error while getting history: {}")
            history = []

        try:
            objects = self.get_all_objects()
        except Exception:
            log.destroy.exception("Error while getting objects")
            objects = ""

        try:
            objreg.get('ipc-server').ignored = True
        except Exception:
            log.destroy.exception("Error while ignoring ipc")

        try:
            self.lastWindowClosed.disconnect(self.shutdown)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")
        QApplication.closeAllWindows()
        self._crashdlg = crashdialog.ExceptionCrashDialog(
            self._args.debug, pages, history, exc, objects)
        ret = self._crashdlg.exec_()
        if ret == QDialog.Accepted:  # restore
            self.restart(shutdown=False, pages=pages)
        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self._destroy_crashlogfile()
        sys.exit(1)
Example #38
0
Test file to execute all the tests from the unittest library within the dstauffman code using nose.

Notes
-----
#.  Written by David C. Stauffer in March 2015.
"""

#%% Imports
import matplotlib.pyplot as plt
import sys
import unittest
from PyQt5.QtWidgets import QApplication

#%% Tests
if __name__ == '__main__':
    # turn interactive plotting off
    plt.ioff()
    # open a qapp
    if QApplication.instance() is None:
        qapp = QApplication(sys.argv)
    else:
        qapp = QApplication.instance()
    # get a loader
    loader = unittest.TestLoader()
    # find all the test cases
    test_suite = loader.discover('dstauffman.tests')
    # run the tests
    unittest.TextTestRunner(verbosity=1).run(test_suite)
    # close the qapp
    qapp.closeAllWindows()
Example #39
0
def main():
    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    t = time.time()
    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            urh_dir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..", ".."))
            sys.path.append(urh_dir)
            sys.path.append(os.path.join(urh_dir, "src"))

            import generate_ui

            generate_ui.gen()

            print("Time for generating UI: %.2f seconds" % (time.time() - t))
        except (ImportError, FileNotFoundError):
            print("Will not regenerate UI, because script can't be found. This is okay in release.")

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..", "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith("/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed
        print("Adding {0} to pythonpath. This is only important when running URH from source.".format(src_dir))
        sys.path.insert(0, src_dir)

    from urh.util import util
    util.set_windows_lib_path()

    try:
        import urh.cythonext.signalFunctions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.curdir
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(["URH"] + sys.argv[1:])
    app.setWindowIcon(QIcon(":/icons/data/icons/appicon.png"))

    if sys.platform != "linux":
        # noinspection PyUnresolvedReferences
        import urh.ui.xtra_icons_rc
        QIcon.setThemeName("oxy")

    constants.SETTINGS.setValue("default_theme", app.style().objectName())

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if constants.SETTINGS.value("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    main_window = MainController()

    if sys.platform == "darwin":
        menu_bar = main_window.menuBar()
        menu_bar.setNativeMenuBar(False)
        import multiprocessing as mp
        mp.set_start_method("spawn")  # prevent errors with forking in native RTL-SDR backend
    elif sys.platform == "win32":
        # Ensure we get the app icon in windows taskbar
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("jopohl.urh")

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    # use system colors for painting
    widget = QWidget()
    bgcolor = widget.palette().color(QPalette.Background)
    fgcolor = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bgcolor
    constants.LINECOLOR = fgcolor
    constants.SELECTION_COLOR = selection_color
    constants.SEND_INDICATOR_COLOR = selection_color

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(return_code)  # sys.exit() is not enough on Windows and will result in crash on exit
Example #40
0
def main():
    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    t = time.time()
    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            urh_dir = os.path.abspath(
                os.path.join(os.path.dirname(sys.argv[0]), "..", ".."))
            sys.path.append(urh_dir)
            sys.path.append(os.path.join(urh_dir, "src"))

            import generate_ui

            generate_ui.gen()

            print("Time for generating UI: %.2f seconds" % (time.time() - t))
        except (ImportError, FileNotFoundError):
            print(
                "Will not regenerate UI, because script can't be found. This is okay in release."
            )

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..",
                           "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith(
            "/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed
        print(
            "Adding {0} to pythonpath. This is only important when running URH from source."
            .format(src_dir))
        sys.path.insert(0, src_dir)

    from urh.util import util
    util.set_windows_lib_path()

    try:
        import urh.cythonext.signalFunctions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.curdir
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(":/icons/data/icons/appicon.png"))

    if sys.platform != "linux":
        # noinspection PyUnresolvedReferences
        import urh.ui.xtra_icons_rc
        QIcon.setThemeName("oxy")

    constants.SETTINGS.setValue("default_theme", app.style().objectName())

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if constants.SETTINGS.value("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText,
                             Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    main_window = MainController()

    if sys.platform == "darwin":
        menu_bar = main_window.menuBar()
        menu_bar.setNativeMenuBar(False)
        import multiprocessing as mp
        mp.set_start_method(
            "spawn")  # prevent errors with forking in native RTL-SDR backend

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    # use system colors for painting
    widget = QWidget()
    bgcolor = widget.palette().color(QPalette.Background)
    fgcolor = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bgcolor
    constants.LINECOLOR = fgcolor
    constants.SELECTION_COLOR = selection_color
    constants.SEND_INDICATOR_COLOR = selection_color

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(
        return_code
    )  # sys.exit() is not enough on Windows and will result in crash on exit
Example #41
0
 def _shutdown(self, status):  # noqa
     """Second stage of shutdown."""
     # pylint: disable=too-many-branches, too-many-statements
     # FIXME refactor this
     # https://github.com/The-Compiler/qutebrowser/issues/113
     log.destroy.debug("Stage 2 of shutting down...")
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         self.removeEventFilter(self._event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         config_obj = objreg.get('config')
     except KeyError:
         log.destroy.debug("Config not initialized yet, so not saving "
                           "anything.")
     else:
         to_save = []
         if config.get('general', 'auto-save-config'):
             to_save.append(("config", config_obj.save))
             try:
                 key_config = objreg.get('key-config')
             except KeyError:
                 pass
             else:
                 to_save.append(("keyconfig", key_config.save))
         to_save += [("window geometry", self._save_geometry)]
         try:
             command_history = objreg.get('command-history')
         except KeyError:
             pass
         else:
             to_save.append(("command history", command_history.save))
         try:
             quickmark_manager = objreg.get('quickmark-manager')
         except KeyError:
             pass
         else:
             to_save.append(("command history", quickmark_manager.save))
         try:
             state_config = objreg.get('state-config')
         except KeyError:
             pass
         else:
             to_save.append(("window geometry", state_config.save))
         try:
             cookie_jar = objreg.get('cookie-jar')
         except KeyError:
             pass
         else:
             to_save.append(("cookies", cookie_jar.save))
         for what, handler in to_save:
             log.destroy.debug("Saving {} (handler: {})".format(
                 what, utils.qualname(handler)))
             try:
                 handler()
             except AttributeError as e:
                 log.destroy.warning("Could not save {}.".format(what))
                 log.destroy.debug(e)
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactiving crash log...")
     self._destroy_crashlogfile()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactiving message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     # We use a singleshot timer to exit here to minimize the likelyhood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(self.exit, status))
Example #42
0
File: main.py Project: jopohl/urh
def main():
    fix_windows_stdout_stderr()

    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..", "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith("/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed -> add directory to path
        sys.path.insert(0, src_dir)

    if len(sys.argv) > 1 and sys.argv[1] == "--version":
        import urh.version
        print(urh.version.VERSION)
        sys.exit(0)

    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            sys.path.insert(0, os.path.join(prefix))
            from data import generate_ui
            generate_ui.gen()
        except (ImportError, FileNotFoundError):
            # The generate UI script cannot be found so we are most likely in release mode, no problem here.
            pass

    from urh.util import util
    util.set_shared_library_path()

    try:
        import urh.cythonext.signal_functions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        if hasattr(sys, "frozen"):
            print("C++ Extensions not found. Exiting...")
            sys.exit(1)
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.path.realpath(os.curdir)
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(["URH"] + sys.argv[1:])
    app.setWindowIcon(QIcon(":/icons/icons/appicon.png"))

    util.set_icon_theme()

    font_size = constants.SETTINGS.value("font_size", 0, int)
    if font_size > 0:
        font = app.font()
        font.setPointSize(font_size)
        app.setFont(font)

    constants.SETTINGS.setValue("default_theme", app.style().objectName())

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if constants.SETTINGS.value("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    # use system colors for painting
    widget = QWidget()
    bg_color = widget.palette().color(QPalette.Background)
    fg_color = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bg_color
    constants.LINECOLOR = fg_color
    constants.SELECTION_COLOR = selection_color
    constants.SEND_INDICATOR_COLOR = selection_color

    main_window = MainController()
    # allow usage of prange (OpenMP) in Processes
    multiprocessing.set_start_method("spawn")

    if sys.platform == "darwin":
        menu_bar = main_window.menuBar()
        menu_bar.setNativeMenuBar(False)
    elif sys.platform == "win32":
        # Ensure we get the app icon in windows taskbar
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("jopohl.urh")

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(return_code)  # sys.exit() is not enough on Windows and will result in crash on exit