def main(): # Load recorder config from file and update displayed status on UI recr = Recorder() recr.read_config() recr.update_status() # Load clipper config from file and update displayed status on UI clpr = Clipper() clpr.read_config() clpr.update_status() app = QApplication(sys.argv) app.setApplicationName('Live Audio Tool') app.setApplicationDisplayName('Live Audio Tool') ex = UI(clpr, recr) ex.show() app.exec_() # Ensure recorder is stopped recr.is_recording = False # Wait to ensure all clip exports are finished time.sleep(clpr.post_buffer) sys.exit()
def start_gui(): logger = core.logger.get_logger(__name__) logger.info('Qt gui starting, PyQt5 version: {}; sip version: {}'.format( PYQT_VERSION_STR, sip.SIP_VERSION_STR)) sip.setdestroyonexit(False) ver = version.get_pyevemon_version() # flags are usually set BEFORE app object is created QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) app = QApplication(sys.argv) app.setApplicationVersion(ver['version']) app.setApplicationName(ver['app_name']) app.setApplicationDisplayName(ver['app_displayname']) app.setOrganizationDomain(ver['app_domain']) app.setOrganizationName(ver['author_name']) # print(app.applicationName(), app.applicationDirPath(), app.applicationPid()) # print(app.applicationDisplayName(), app.applicationVersion()) # do not forget to start ESI auth callback receiver core.esi_handler.esi_handler_start() mainwindow = gui_qt.mainwindow.QtEmMainWindow() mainwindow.show() return app.exec_()
def _create_app(): app = QApplication([]) icon = get_icon(PROGRAM) app.setApplicationName(PROGRAM) app.setApplicationDisplayName(PROGRAM) app.setWindowIcon(icon) return app
class Application(object): def __init__(self): Environment.bootstrap_application_directories() self._app = QApplication(sys.argv) self._app.setStyle(QStyleFactory.create("Fusion")) self._app.setWindowIcon( QtGui.QIcon( os.path.join(Environment.get_resource_path(), 'designs/default/OXNote.icns'))) self._app.setApplicationDisplayName('OXNote') self._app.setApplicationName('OXNote') def start_wizard(self): logger.debug('Preparing to start account setup wizard') self._oxnote_setup_wizard_widget = SetupWizard() self._oxnote_setup_wizard_widget.show() self.exit() def start_main_window(self): logger.debug('Preparing to start main window') self._oxnote_main_window_widget = MainWindow() self._oxnote_main_window_widget.show() self.exit() def exit(self): sys.exit(self._app.exec_())
def main(): app = QApplication(sys.argv) main_window = MainWindow() main_window.show() app.setApplicationName("Whatsdesk") app.setApplicationDisplayName("Whatsdesk") print("App Started") sys.exit(app.exec())
def set_app_display_metadata(app: QtWidgets.QApplication) -> None: with resources.open_binary(speedwagon.__name__, "favicon.ico") as icon: app.setWindowIcon(QtGui.QIcon(icon.name)) try: app.setApplicationVersion(metadata.version(__package__)) except metadata.PackageNotFoundError: pass app.setApplicationDisplayName(f"{speedwagon.__name__.title()}") QtWidgets.QApplication.processEvents()
def main(argv): a = QApplication(sys.argv) a.setApplicationDisplayName(__application__) a.setOrganizationName(__organization__) w = MainWindow() w.show() return a.exec()
def main(): if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qtbase_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True if globalSettings.openLastFilesOnStartup: window.restoreLastOpenedFiles() inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def app(): app = QApplication(sys.argv) app.setApplicationName('CuriElements') app.setApplicationDisplayName('CuriElements') app.setOrganizationName('CodeHuntersLab') app.setOrganizationDomain('CodeHuntersLab.com') app.setApplicationVersion('1.0') w = CuriWidget() w.show() sys.exit(app.exec_())
def main(): if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def main(): QApplication.setQuitOnLastWindowClosed(False) app = QApplication(sys.argv) app.setApplicationName(APP_NAME) app.setApplicationDisplayName(APP_NAME) app_window = AppWindow() tray_icon = init_tray_icon(app_window) tray_icon.show() return app.exec_()
def main(): app = QApplication(sys.argv) app.setApplicationDisplayName("EvoBridge") args = app.arguments() window = MainWindow(args[1] if len(args) == 2 else None) app.installEventFilter(window) window.resize(800, 600) window.show() sys.exit(app.exec_())
def main(): if sys.excepthook is sys.__excepthook__: sys.excepthook = lambda *args: sys.__excepthook__(*args) app = QApplication(sys.argv) app.setApplicationDisplayName('SIT-Tagger') app.setApplicationName('SIT-Tagger') opts = parse_options(list(app.arguments())[1:]) win = Win(opts) win.show() app.exec_()
def main(): logging.basicConfig(level=logging.DEBUG) mainLogger = logging.getLogger(moduleName) mainLogger.setLevel(logging.DEBUG) from PyQt5.QtWidgets import QApplication app = QApplication([]) app.setApplicationName(appName) app.setOrganizationName(orgName) app.setApplicationDisplayName(appDisplayName) tabWidget = TagSpaceTabWidget() tabWidget.show() app.exec()
def __generate_window(self): """ Generate's the application and it's primary window. """ with open('ui/style/style.qss', 'r') as file: self.__app.setStyleSheet(file.read()) QApplication.setApplicationDisplayName(WINDOW_TITLE) # Move main window to center of center monitor's display area self.__main_win.setGeometry(0, 0, self.app_dimensions.height(), self.app_dimensions.width()) self.__main_win.move(get_center_pos(self.__main_win)) self.__main_win.show() sys.exit(self.__app.exec())
def main(): dirpath = os.path.dirname(__file__) qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) qt_app.setApplicationName(__component__) qt_app.setApplicationDisplayName(__component__) win = QMainWindow() win.setWindowIcon(QIcon('icon.png')) win.setWindowTitle(__component__) app = Application() # app.config.pop('basepath',None) w = MainWidget(app, win) win.setCentralWidget(w) win.show() sys.exit(qt_app.exec_())
def main(): faulthandler.enable(all_threads=False) logging.basicConfig(level=logging.DEBUG) mainLogger = logging.getLogger(moduleName) mainLogger.setLevel(logging.DEBUG) from PyQt5.QtWidgets import QApplication from multi_video.window.main import VideoWindow app = QApplication([]) app.setApplicationName(appName) app.setOrganizationName(orgName) app.setApplicationDisplayName(appDisplayName) vw = VideoWindow() vw.show() app.exec()
def main(): app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True inputData = '' if sys.stdin.isatty() else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def main(): app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.trigger() elif fileName == '--preview': previewMode = True if sys.stdin: inputData = '' if sys.stdin.isatty() else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def main(): """ :rtype: int """ parent_wid = os.environ.get('XSCREENSAVER_WINDOW') url = 'https://web-animations.github.io/web-animations-demos/#galaxy/' if len(sys.argv) > 1: url = sys.argv[1] app = QApplication(sys.argv[:1]) app.setApplicationDisplayName(APP_NAME) browser = Browser(app) if parent_wid is None: browser.show_window() else: browser.embed_window(int(parent_wid, 16)) browser.open(url) return app.exec_()
class Application: _app = None # type: QApplication @property def app(self) -> QApplication: if self._app is None: self.setup() return self._app def setup(self) -> None: # Imports .qrc resources even if it is "unused" from genial.resources import icons_rc from genial.resources import locale_rc from genial.resources import plugins_rc # Initializes the app variable self._app = QApplication(sys.argv) self._app.setApplicationName("Génial") self._app.setApplicationDisplayName("Génial") self._app.setProperty("AA_EnableHighDpiScaling", True) # Qt translation qt_translator = QTranslator() if qt_translator.load(QLocale(), "qt", "_", ":/locale"): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QCoreApplication.installTranslator(qt_translator) # App translation genial_translator = QTranslator() if genial_translator.load(QLocale(), "genial", "_", ":/locale"): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QCoreApplication.installTranslator(genial_translator) def run(self) -> int: # Importing here makes available PyQt5.QtWidgets.QApplication.instance() # for each of these modules (and for their imports too.) from genial.controllers.maincontroller import MainController main_controller = MainController(self.app) main_controller.start() return self.app.exec()
def main(): parser = init_argparse() args = parser.parse_args() if args.config: # if config argument used create file settings = config.Config(args.config) settings.save() else: settings = config.Config() # select language if settings.language is None: lang = gettext else: lang = gettext.translation( "autobrightness", os.path.join(autobrightness.ROOT_DIR, 'locales'), [settings.language]) global _ _ = lang.gettext if args.start: sys.stdout = Unbuffered(sys.stdout) daemonIns = autobrightness.daemon.Daemon(settings, lang) daemonIns.start() elif args.set: brightnessIns = brightness.Brightness(settings, lang) brightnessIns.set(brightnessIns.calculate()) else: app = QApplication([]) app.setApplicationName("Auto Brightness") app.setApplicationDisplayName("Auto Brightness") app.setApplicationVersion(autobrightness.__version__) app.setQuitOnLastWindowClosed(False) trayIcon = autobrightness.gui.trayicon.TrayIcon( settings, autobrightness.gui.daemon.Service(), app, lang) trayIcon.show() app.exec_()
def __generate_window(self, account: Optional[Account]): """ Generate's the application and it's primary window. UI main :return: Application's exit code """ with open('style/darkstyle.qss', 'r') as file: self.__app.setStyleSheet(file.read()) QApplication.setApplicationDisplayName(WINDOW_TITLE) self.__main_win.setGeometry(0, 0, self.app_dimensions.height(), self.app_dimensions.width()) if len(sys.argv) > 1 and sys.argv[1] != 'DEBUG': self.__main_win.move(get_center_pos(self.__main_win)) self.__main_win.show() # Load central widget landing_window = LandingWindow(self.__main_win, account, self.__client) self.__main_win.setCentralWidget(landing_window) self.__main_win.setMenuBar(landing_window.menu_bar()) sys.exit(self.__app.exec())
def createWindow(): #create the applicaton first app = QApplication([]) app.setApplicationDisplayName("Game Launcher") #creating menu bar m1 = QMenu('File') m2 = QMenu('Edit') bar = QMenuBar() bar.addMenu(m1) bar.addMenu(m2) #creating window window = QWidget() layout = QVBoxLayout() #create a button for starting the game button = QPushButton("Open Megaman") #click method i.e. to start the game def button_on_click(): subprocess.call('start game.exe', cwd="D:\\Games\\Mega Man 11", shell=True) #setting up the event listener button.clicked.connect(button_on_click) layout.addWidget(bar) layout.addWidget(button) #setting the layout and then starting the application window.setLayout(layout) window.show() app.exec_()
if __name__ == "__main__": SQueue = StreamQueue() SQueueExit = StreamQueue() utils.parse_options(utils.get_argparser().parse_args()) utils.setup_i18n() if config.gui_start_on_boot.value: toggle_start_on_boot(None, config.gui_start_on_boot.value) config.gui_start_on_boot.add_trigger(toggle_start_on_boot) app = QApplication(sys.argv) app.setAttribute(Qt.AA_EnableHighDpiScaling) app.setWindowIcon(QIcon(constants.favicon_path)) app.setApplicationDisplayName("HappyPanda X") app.setApplicationName("HappyPanda X") app.setApplicationVersion(".".join(str(x) for x in constants.version)) app.setOrganizationDomain("Twiddly") app.setOrganizationName("Twiddly") app.setDesktopFileName("HappyPanda X") window = Window() window.resize(650, 650) sys.stdout = SQueue sys.stderr = SQueue if config.gui_start_minimized.value: window.tray.show() else: window.show() window.activateWindow() e = app.exec()
__Author__ = "By: Irony.\"[讽刺]\nQQ: 892768447\nEmail: [email protected]" __Copyright__ = "Copyright (c) 2018 Irony.\"[讽刺]" __Version__ = "Version 1.0" class Window(QTextEdit): def __init__(self, parent=None): super(Window, self).__init__(parent) self.resize(800, 600) # 设置横向纵向滚动条总是显示 self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) with open("Data/ScrollBar.qss", "rb") as fp: content = fp.read() encoding = chardet.detect(content) or {} content = content.decode(encoding.get("encoding") or "utf-8") self.setText(content) # 设置样式 self.setStyleSheet(content) if __name__ == "__main__": import sys app = QApplication(sys.argv) app.setApplicationName("滚动条样式") app.setApplicationDisplayName("滚动条样式") window = Window() window.show() sys.exit(app.exec_())
def start(test=False): app_constants.APP_RESTART_CODE = -123456789 if os.name == "posix": main_path = os.path.dirname(os.path.realpath(__file__)) log_path = os.path.join(main_path, "happypanda.log") debug_log_path = os.path.join(main_path, "happypanda_debug.log") else: log_path = "happypanda.log" debug_log_path = "happypanda_debug.log" parser = argparse.ArgumentParser(prog="Happypanda", description="A manga/doujinshi manager with tagging support") parser.add_argument( "-d", "--debug", action="store_true", help="happypanda_debug_log.log will be created in main directory" ) parser.add_argument( "-t", "--test", action="store_true", help="Run happypanda in test mode. 5000 gallery will be preadded in DB." ) parser.add_argument("-v", "--version", action="version", version="Happypanda v{}".format(app_constants.vs)) parser.add_argument("-e", "--exceptions", action="store_true", help="Disable custom excepthook") args = parser.parse_args() if args.debug: print("happypanda_debug.log created at {}".format(os.getcwd())) # create log try: with open(debug_log_path, "x") as f: pass except FileExistsError: pass logging.basicConfig( level=logging.DEBUG, format="%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s", datefmt="%d-%m %H:%M", filename="happypanda_debug.log", filemode="w", ) app_constants.DEBUG = True else: try: with open(log_path, "x") as f: pass except FileExistsError: pass file_handler = logging.handlers.RotatingFileHandler( log_path, maxBytes=1000000 * 10, encoding="utf-8", backupCount=2 ) logging.basicConfig( level=logging.INFO, format="%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s", datefmt="%d-%m %H:%M", handlers=(file_handler,), ) log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical if not args.exceptions: def uncaught_exceptions(ex_type, ex, tb): log_c("".join(traceback.format_tb(tb))) log_c("{}: {}".format(ex_type, ex)) traceback.print_exception(ex_type, ex, tb) sys.excepthook = uncaught_exceptions application = QApplication(sys.argv) application.setOrganizationName("Pewpews") application.setOrganizationDomain("https://github.com/Pewpews/happypanda") application.setApplicationName("Happypanda") application.setApplicationDisplayName("Happypanda") application.setApplicationVersion("v{}".format(app_constants.vs)) log_i("Happypanda Version {}".format(app_constants.vs)) log_i("OS: {} {}\n".format(platform.system(), platform.release())) conn = None try: if args.test: conn = db.init_db(True) else: conn = db.init_db() log_d("Init DB Conn: OK") log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION)) except: log_c("Invalid database") log.exception("Database connection failed!") from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText("Invalid database") msg_box.setInformativeText("Do you want to create a new database?") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: pass else: application.exit() log_d("Normal Exit App: OK") sys.exit() def start_main_window(conn): db.DBBase._DB_CONN = conn # if args.test: # import threading, time # ser_list = [] # for x in range(5000): # s = gallerydb.gallery() # s.profile = app_constants.NO_IMAGE_PATH # s.title = 'Test {}'.format(x) # s.artist = 'Author {}'.format(x) # s.path = app_constants.static_dir # s.type = 'Test' # s.language = 'English' # s.info = 'I am number {}'.format(x) # ser_list.append(s) # done = False # thread_list = [] # i = 0 # while not done: # try: # if threading.active_count() > 5000: # thread_list = [] # done = True # else: # thread_list.append( # threading.Thread(target=gallerydb.galleryDB.add_gallery, # args=(ser_list[i],))) # thread_list[i].start() # i += 1 # print(i) # print('Threads running: {}'.format(threading.activeCount())) # except IndexError: # done = True WINDOW = app.AppWindow() # styling d_style = app_constants.default_stylesheet_path u_style = app_constants.user_stylesheet_path if len(u_style) is not 0: try: style_file = QFile(u_style) log_i("Select userstyle: OK") except: style_file = QFile(d_style) log_i("Select defaultstyle: OK") else: style_file = QFile(d_style) log_i("Select defaultstyle: OK") style_file.open(QFile.ReadOnly) style = str(style_file.readAll(), "utf-8") application.setStyleSheet(style) try: os.mkdir(app_constants.temp_dir) except FileExistsError: try: for root, dirs, files in scandir.walk("temp", topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) except: log.exception("Empty temp: FAIL") log_d("Create temp: OK") if test: return application, WINDOW return application.exec_() def db_upgrade(): log_d("Database connection failed") from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText("Incompatible database!") msg_box.setInformativeText( "Do you want to upgrade to newest version?" + " It shouldn't take more than a second. Don't start a new instance!" ) msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: utils.backup_database() import threading db_p = db_constants.DB_PATH db.add_db_revisions(db_p) conn = db.init_db() return start_main_window(conn) else: application.exit() log_d("Normal Exit App: OK") return 0 if conn: return start_main_window(conn) else: return db_upgrade()
def main(): multiprocessing.set_start_method('spawn') if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') try: # See https://github.com/retext-project/retext/issues/399 # and https://launchpad.net/bugs/941826 ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL) except OSError: pass # Needed for Qt WebEngine on Windows QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) initializeDataDirs() RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qtbase_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False readStdIn = False if globalSettings.openLastFilesOnStartup: window.restoreLastOpenedFiles() for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True elif fileName == '-': readStdIn = True inputData = '' if readStdIn and sys.stdin is not None: if sys.stdin.isatty(): print('Reading stdin, press ^D to end...') inputData = sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def main(): app = QApplication(sys.argv) window = MainWindow() app.setApplicationDisplayName('ES Time') window.setWindowTitle('Estimator') global Stayontop global darkmode global resetfields global viewResMsgBox global ScaleFact global configpath try: configFile = pickle.load(open(configpath, "rb")) darkmode = configFile[0] ScaleFact = configFile[1] Stayontop = configFile[2] viewResMsgBox = configFile[3] resetfields = configFile[4] except: pass #black shadow effect shadow_black = QGraphicsDropShadowEffect() shadow_black.setBlurRadius(20) shadow_black.setYOffset(5) shadow_black.setXOffset(0) if darkmode == 1: shadow_black.setColor(PyQt5.QtGui.QColor("#A1A1A1")) else: shadow_black.setColor(PyQt5.QtGui.QColor("#c1c1c1")) window.tabWidget.setGraphicsEffect(shadow_black) #setup for Dark mode wrapping if darkmode == 1: #Tabs window.tabWidget.setStyleSheet( "QTabBar::tab:selected {border-bottom: 2px solid #00BFF3;} QTabBar::tab:hover {border-bottom: 2px solid #00BFF3;}" ) #TimeES labels window.label_AvSp.setStyleSheet("color:white;") window.label_Si.setStyleSheet("color:white;") window.label_Comp.setStyleSheet("color:white;") window.label_Perc.setStyleSheet("color:white;") window.label_Result.setStyleSheet("color:#27C499;") window.label_Er.setStyleSheet("color:#F1304D;") #TimeES inputs window.input_AvSp.setStyleSheet("color:white;") window.input_Si.setStyleSheet("color:white;") window.input_Comp.setStyleSheet("color:white;") #TimeES buttons window.SpeedTest_PB.setStyleSheet( "#SpeedTest_PB { font: 87 8pt 'Arca Majora 3 Heavy'; background: #656565; border-radius: 5.3px; border: 1px solid #FFFFFF; color:white; } #SpeedTest_PB:hover { border: 1.25px solid #FFFFFF; background: #00bff3; } #SpeedTest_PB:pressed { background: #007392; color:lightgray; }" ) window.Start_PB.setStyleSheet( "#Start_PB { background: #656565; border-radius: 8px; border: 2px solid #FFFFFF; color:white; } #Start_PB:hover { border: 3px solid #FFFFFF; background: #00bff3; } #Start_PB:pressed {background: #007392; color:lightgray;}" ) #TimeES radios window.RB_KBs.setStyleSheet("color:white;") window.RB_MBs.setStyleSheet("color:white;") window.RB_Mbs.setStyleSheet("color:white;") window.RB_MB.setStyleSheet("color:white;") window.RB_GB.setStyleSheet("color:white;") window.RB_TB.setStyleSheet("color:white;") #DataES labels window.label_AvSpD.setStyleSheet("color: white;") window.label_Time_head.setStyleSheet("color: white;") window.label_seconds.setStyleSheet("color:white;") window.label_minutes.setStyleSheet("color:white;") window.label_hours.setStyleSheet("color:white;") window.label_days.setStyleSheet("color:white;") window.label_months.setStyleSheet("color:white;") window.label_years.setStyleSheet("color:white;") window.label_decades.setStyleSheet("color:white;") window.label_centuries.setStyleSheet("color:white;") window.label_ResultD.setStyleSheet("color:#27C499;") #DataES inputs window.input_AvSpD.setStyleSheet("color:white;") window.SPcomboBox.setStyleSheet("color:white;") #DataES spinners window.spinSeconds.setStyleSheet("color:white;") window.spinMinutes.setStyleSheet("color:white;") window.spinHours.setStyleSheet("color:white;") window.spinDays.setStyleSheet("color:white;") window.spinMonths.setStyleSheet("color:white;") window.spinYears.setStyleSheet("color:white;") window.spinDecades.setStyleSheet("color:white;") window.spinCenturies.setStyleSheet("color:white;") #DataES PB window.StartD_PB.setStyleSheet( "#StartD_PB { background: #656565; border-radius: 8px; border: 2px solid #FFFFFF; color:white; } #StartD_PB:hover { border: 3px solid #FFFFFF; /*color:#00bff3;*/ background: #00bff3; } #StartD_PB:pressed { /*border: 3px solid lightgray;*/ background: #007392; color:lightgray; }" ) window.ResetD_PB.setStyleSheet( "#ResetD_PB { font: 87 8pt 'Arca Majora 3 Heavy'; background: #656565; border-radius: 5.3px; border: 1px solid #FFFFFF; color:white; } #ResetD_PB:hover { border: 1.25px solid #FFFFFF; background: #00bff3; } #ResetD_PB:pressed { background: #007392; color:lightgray; }" ) window.SpeedTest_PB_2.setStyleSheet( "#SpeedTest_PB_2 { font: 87 8pt 'Arca Majora 3 Heavy'; background: #656565; border-radius: 5.3px; border: 1px solid #FFFFFF; color:white; } #SpeedTest_PB_2:hover { border: 1.25px solid #FFFFFF; background: #00bff3; } #SpeedTest_PB_2:pressed { background: #007392; color:lightgray; }" ) #savePB window.Save_PB.setStyleSheet( "#Save_PB { font: 87 8pt 'Arca Majora 3 Heavy'; background: #656565; border-radius: 5.3px; border: 1px solid #FFFFFF; color:white; } #Save_PB:hover { border: 1.25px solid #FFFFFF; background: #00bff3; } #Save_PB:pressed { background: #007392; color:lightgray; }" ) #UpdatePB #window.Update_PB.setStyleSheet("#Update_PB { font: 87 8pt 'Arca Majora 3 Heavy'; background: #656565; border-radius: 5.3px; border: 1px solid #FFFFFF; color:white; } #Update_PB:hover { border: 1.25px solid #FFFFFF; background: #00bff3; } #Update_PB:pressed { background: #007392; color:lightgray; }") #scalesettingSpinner window.scaleSpin.setStyleSheet("color:white;") #Restart_label window.Restart_label.setStyleSheet("color:#F1304D;") #set size window.setFixedHeight(190) window.border_bottom.move(0, 187) #load fonts font_status = PyQt5.QtGui.QFontDatabase.addApplicationFont( ':/Font/Files/Fonts/ArcaMajora3-Bold.otf' ) #set font (returns -1 if failed) font_status_2 = PyQt5.QtGui.QFontDatabase.addApplicationFont( ':/Font/Files/Fonts/ArcaMajora3-Heavy.otf') window.label_Er.hide() #Hide Error label window.DMW_label.hide() window.SizeBrowse_PB.hide() #Hide Browse Button (still in dev) #Get App location path for no reason (yet) #print(application_path) #initiate loading animation window.movie = QMovie(":/Animation/Files/Animation/loader.gif") window.loading.setMovie(window.movie) window.loading_2.setMovie(window.movie) window.loading.hide() window.loading_2.hide() window.show() #load theme #fd = QtCore.QFile(":/Themes/Files/Theme/light-blue.qss") #if fd.open(QtCore.QIODevice.ReadOnly | QtCore.QFile.Text): #qss = QtCore.QTextStream(fd).readAll() #fd.close() #app.setStyleSheet(qss) if darkmode == 1: qtmodern.styles.dark(app) mw = qtmodern.windows.ModernWindow(window.DMW_label) #mw.show() #Warning for failed font loading: if font_status == -1 or font_status_2 == -1: QMessageBox.Warning(window, "Font failed to load", "Font failed to load, using default system font") ############ app.exec_()
str: キー文字列 ''' modifier = '' if (event.modifiers() & Qt.ShiftModifier): modifier += "Shift+" if (event.modifiers() & Qt.ControlModifier): modifier += "Ctrl+" if (event.modifiers() & Qt.AltModifier): modifier += "Alt+" if (event.modifiers() & Qt.MetaModifier): modifier += "Meta+" key = QKeySequence(event.key()).toString() return QKeySequence(modifier + key) if __name__ == '__main__': '''メイン処理 スクリーンサイズに応じてウィンドウサイズを設定し メインウィンドウを表示する ''' app = QApplication(sys.argv) app.setApplicationDisplayName('Color Picker') # window size calc s_size = app.desktop().availableGeometry().size() w_size = QSize(int(s_size.width() * 9 / 10), int(s_size.height() * 9 / 10)) w_pos = QPoint(int((s_size.width() - w_size.width()) / 2), int((s_size.height() - w_size.height()) / 2)) main = MainWindow() main.setGeometry(QRect(w_pos, w_size)) main.show() sys.exit(app.exec())
from PyQt5.QtQuick import QQuickView from PyQt5.QtWidgets import QApplication from qtypes.argv import ArgParser from qtypes.vend import Vend if __name__ == '__main__': # Reminder to self, see link for why we avoid a 'main' function here # http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html#object-destruction-on-exit app = QApplication(sys.argv) print(sys.version) print("InvoiceIt") root = os.path.dirname(__file__) app.setApplicationName("InvoiceIt") app.setApplicationDisplayName("InvoiceIt") app.setApplicationVersion("0.1") view = QQuickView() qmlRegisterType(ArgParser, "ArgV", 1, 0, "ArgParser") qmlRegisterType(Vend, "Vend", 1, 0, "Vendor") f = QUrl.fromLocalFile(join(root, 'qml', 'main.qml')) view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(f) view.show() sys.exit(app.exec_())
if opt == '-h': Usage() sys.exit() elif opt == "-f": configFile = arg #endfor global config log.debug("Reading config from %s" % (configFile, )) config = Config(configFile) config.InitLogging() log.info("Started, loading icons from " + config.iconPath) app = QApplication(sys.argv) QApplication.setApplicationDisplayName('Yoga Spin GUI') controller = Controller() tray = LidControlMenu(app, controller) tray.Show() view = LidControlView(app, controller) eventListener = EventListener() eventListener.spinSignal.connect(controller.HandleIncomingEvent) controller.SetView(view) sys.exit(app.exec_())
import sys from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication from presenter.presenter import Presenter if __name__ == '__main__': app = QApplication(sys.argv) app.setStyle("Fusion") app.setWindowIcon(QtGui.QIcon("./resources/virusIcon.png")) app.setApplicationDisplayName("Simulator") presenter = Presenter() presenter.ui.show() sys.exit(app.exec_())
def start(test=False): app_constants.APP_RESTART_CODE = -123456789 if os.name == 'posix': main_path = os.path.dirname(os.path.realpath(__file__)) log_path = os.path.join(main_path, 'happypanda.log') debug_log_path = os.path.join(main_path, 'happypanda_debug.log') else: log_path = 'happypanda.log' debug_log_path = 'happypanda_debug.log' if os.path.exists('cacert.pem'): os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(os.getcwd(), "cacert.pem") parser = argparse.ArgumentParser(prog='Happypanda', description='A manga/doujinshi manager with tagging support') parser.add_argument('-d', '--debug', action='store_true', help='happypanda_debug_log.log will be created in main directory') parser.add_argument('-v', '--version', action='version', version='Happypanda v{}'.format(app_constants.vs)) parser.add_argument('-e', '--exceptions', action='store_true', help='Disable custom excepthook') parser.add_argument('-x', '--dev', action='store_true', help='Development Switch') args = parser.parse_args() log_handlers = [] log_level = logging.INFO if args.dev: log_handlers.append(logging.StreamHandler()) if args.debug: print("happypanda_debug.log created at {}".format(os.getcwd())) # create log try: with open(debug_log_path, 'x') as f: pass except FileExistsError: pass log_handlers.append(logging.FileHandler(debug_log_path, 'w', 'utf-8')) log_level = logging.DEBUG app_constants.DEBUG = True else: try: with open(log_path, 'x') as f: pass except FileExistsError: pass log_handlers.append(logging.handlers.RotatingFileHandler( log_path, maxBytes=1000000*10, encoding='utf-8', backupCount=2)) # Fix for logging not working # clear the handlers first before adding these custom handler # http://stackoverflow.com/a/15167862 logging.getLogger('').handlers = [] logging.basicConfig(level=log_level, format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s', datefmt='%d-%m %H:%M', handlers=tuple(log_handlers)) log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical if not args.exceptions: def uncaught_exceptions(ex_type, ex, tb): log_c(''.join(traceback.format_tb(tb))) log_c('{}: {}'.format(ex_type, ex)) traceback.print_exception(ex_type, ex, tb) sys.excepthook = uncaught_exceptions if app_constants.FORCE_HIGH_DPI_SUPPORT: log_i("Enabling high DPI display support") os.environ.putenv("QT_DEVICE_PIXEL_RATIO", "auto") effects = [Qt.UI_AnimateCombo, Qt.UI_FadeMenu, Qt.UI_AnimateMenu, Qt.UI_AnimateTooltip, Qt.UI_FadeTooltip] for effect in effects: QApplication.setEffectEnabled(effect) application = QApplication(sys.argv) application.setOrganizationName('Pewpews') application.setOrganizationDomain('https://github.com/Pewpews/happypanda') application.setApplicationName('Happypanda') application.setApplicationDisplayName('Happypanda') application.setApplicationVersion('v{}'.format(app_constants.vs)) application.setAttribute(Qt.AA_UseHighDpiPixmaps) application.font().setStyleStrategy(application.font().PreferAntialias) log_i('Starting Happypanda...'.format(app_constants.vs)) if args.debug: log_i('Running in debug mode'.format(app_constants.vs)) import pprint sys.displayhook = pprint.pprint app_constants.load_icons() log_i('Happypanda Version {}'.format(app_constants.vs)) log_i('OS: {} {}\n'.format(platform.system(), platform.release())) conn = None try: conn = db.init_db() log_d('Init DB Conn: OK') log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION)) except: log_c('Invalid database') log.exception('Database connection failed!') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText('Invalid database') msg_box.setInformativeText("Do you want to create a new database?") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: pass else: application.exit() log_d('Normal Exit App: OK') sys.exit() def start_main_window(conn): db.DBBase._DB_CONN = conn #if args.test: # import threading, time # ser_list = [] # for x in range(5000): # s = gallerydb.gallery() # s.profile = app_constants.NO_IMAGE_PATH # s.title = 'Test {}'.format(x) # s.artist = 'Author {}'.format(x) # s.path = app_constants.static_dir # s.type = 'Test' # s.language = 'English' # s.info = 'I am number {}'.format(x) # ser_list.append(s) # done = False # thread_list = [] # i = 0 # while not done: # try: # if threading.active_count() > 5000: # thread_list = [] # done = True # else: # thread_list.append( # threading.Thread(target=gallerydb.galleryDB.add_gallery, # args=(ser_list[i],))) # thread_list[i].start() # i += 1 # print(i) # print('Threads running: {}'.format(threading.activeCount())) # except IndexError: # done = True WINDOW = app.AppWindow(args.exceptions) # styling d_style = app_constants.default_stylesheet_path u_style = app_constants.user_stylesheet_path if len(u_style) is not 0: try: style_file = QFile(u_style) log_i('Select userstyle: OK') except: style_file = QFile(d_style) log_i('Select defaultstyle: OK') else: style_file = QFile(d_style) log_i('Select defaultstyle: OK') style_file.open(QFile.ReadOnly) style = str(style_file.readAll(), 'utf-8') application.setStyleSheet(style) try: os.mkdir(app_constants.temp_dir) except FileExistsError: try: for root, dirs, files in scandir.walk('temp', topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) except: log.exception("Empty temp: FAIL") log_d('Create temp: OK') if test: return application, WINDOW return application.exec_() def db_upgrade(): log_d('Database connection failed') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText('Incompatible database!') msg_box.setInformativeText("Do you want to upgrade to newest version?" + " It shouldn't take more than a second. Don't start a new instance!") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: utils.backup_database() import threading db_p = db_constants.DB_PATH db.add_db_revisions(db_p) conn = db.init_db() return start_main_window(conn) else: application.exit() log_d('Normal Exit App: OK') return 0 if conn: return start_main_window(conn) else: return db_upgrade()
import os import sys from typing import Union from data.job import Job from data.database import Database from timer.timer import JobTimer from PyQt5.QtCore import Qt, QSize from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QComboBox, QInputDialog, \ QLabel, QSizePolicy, QMessageBox, QSystemTrayIcon # Note : time is not saved if application crashes or is closed by end of Windows session app = QApplication([]) app.setApplicationDisplayName("Job Timer") window = QWidget() vLayout = QVBoxLayout() hLayout = QHBoxLayout() projectList = QComboBox() createProjectButton = QPushButton("Nouveau") deleteProjectButton = QPushButton("Supprimer") clock = QLabel() clock.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) clock.setAlignment(Qt.AlignCenter) clock.setStyleSheet('font-size: 18px; color:grey; font-weight: bold') clock_button = QPushButton("Démarrer/arrêter") hLayout.addWidget(projectList) hLayout.addWidget(createProjectButton) hLayout.addWidget(deleteProjectButton) vLayout.addLayout(hLayout)
def start(test=False): if os.name == 'posix': main_path = os.path.dirname(os.path.realpath(__file__)) log_path = os.path.join(main_path, 'happypanda.log') debug_log_path = os.path.join(main_path, 'happypanda_debug.log') else: log_path = 'happypanda.log' debug_log_path = 'happypanda_debug.log' parser = argparse.ArgumentParser(prog='Happypanda', description='A manga/doujinshi manager with tagging support') parser.add_argument('-d', '--debug', action='store_true', help='happypanda_debug_log.log will be created in main directory') parser.add_argument('-t', '--test', action='store_true', help='Run happypanda in test mode. 5000 gallery will be preadded in DB.') parser.add_argument('-v', '--versi on', action='version', version='Happypanda v{}'.format(gui_constants.vs)) parser.add_argument('-e', '--exceptions', action='store_true', help='Disable custom excepthook') args = parser.parse_args() if args.debug: print("happypanda_debug.log created at {}".format(os.getcwd())) # create log try: with open(debug_log_path, 'x') as f: pass except FileExistsError: pass logging.basicConfig(level=logging.DEBUG, format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s', datefmt='%d-%m %H:%M', filename='happypanda_debug.log', filemode='w') gui_constants.DEBUG = True else: try: with open(log_path, 'x') as f: pass except FileExistsError: pass file_handler = logging.handlers.RotatingFileHandler( log_path, maxBytes=1000000*10, encoding='utf-8', backupCount=2) logging.basicConfig(level=logging.INFO, format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s', datefmt='%d-%m %H:%M', handlers=(file_handler,)) log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical if not args.exceptions: def uncaught_exceptions(ex_type, ex, tb): log_c(''.join(traceback.format_tb(tb))) log_c('{}: {}'.format(ex_type, ex)) traceback.print_exception(ex_type, ex, tb) sys.excepthook = uncaught_exceptions application = QApplication(sys.argv) application.setOrganizationName('Pewpews') application.setOrganizationDomain('https://github.com/Pewpews/happypanda') application.setApplicationName('Happypanda') application.setApplicationDisplayName('Happypanda') application.setApplicationVersion('v{}'.format(gui_constants.vs)) log_i('Happypanda Version {}'.format(gui_constants.vs)) log_i('OS: {} {}\n'.format(platform.system(), platform.release())) try: if args.test: conn = db.init_db(True) else: conn = db.init_db() log_d('Init DB Conn: OK') log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION)) except: log_c('Invalid database') log.exception('Database connection failed!') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(gui_constants.APP_ICO_PATH)) msg_box.setText('Invalid database') msg_box.setInformativeText("Do you want to create a new database?") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: pass else: application.exit() log_d('Normal Exit App: OK') sys.exit() def start_main_window(conn): DB = db.DBThread(conn) #if args.test: # import threading, time # ser_list = [] # for x in range(5000): # s = gallerydb.gallery() # s.profile = gui_constants.NO_IMAGE_PATH # s.title = 'Test {}'.format(x) # s.artist = 'Author {}'.format(x) # s.path = gui_constants.static_dir # s.type = 'Test' # s.chapters = {0:gui_constants.static_dir} # s.language = 'English' # s.info = 'I am number {}'.format(x) # ser_list.append(s) # done = False # thread_list = [] # i = 0 # while not done: # try: # if threading.active_count() > 5000: # thread_list = [] # done = True # else: # thread_list.append( # threading.Thread(target=gallerydb.galleryDB.add_gallery, # args=(ser_list[i],))) # thread_list[i].start() # i += 1 # print(i) # print('Threads running: {}'.format(threading.activeCount())) # except IndexError: # done = True WINDOW = app.AppWindow() # styling d_style = gui_constants.default_stylesheet_path u_style = gui_constants.user_stylesheet_path if len(u_style) is not 0: try: style_file = QFile(u_style) log_i('Select userstyle: OK') except: style_file = QFile(d_style) log_i('Select defaultstyle: OK') else: style_file = QFile(d_style) log_i('Select defaultstyle: OK') style_file.open(QFile.ReadOnly) style = str(style_file.readAll(), 'utf-8') application.setStyleSheet(style) try: os.mkdir(gui_constants.temp_dir) except FileExistsError: try: for root, dirs, files in scandir.walk('temp', topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) except: log_i('Empty temp: FAIL') log_d('Create temp: OK') if test: return application, WINDOW sys.exit(application.exec_()) def db_upgrade(): log_d('Database connection failed') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(gui_constants.APP_ICO_PATH)) msg_box.setText('Incompatible database!') msg_box.setInformativeText("Do you want to upgrade to newest version?" + " It shouldn't take more than a second. Don't start a new instance!") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: import threading db_p = db_constants.DB_PATH threading.Thread(target=db.add_db_revisions, args=(db_p,)).start() done = None while not done: done = db.ResultQueue.get() conn = db.init_db() start_main_window(conn) else: application.exit() log_d('Normal Exit App: OK') sys.exit() if conn: start_main_window(conn) else: db_upgrade()
def run_dwarf(): """ fire it up """ os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" # os.environ["QT_SCALE_FACTOR"] = "1" # os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "0" # os.environ["QT_SCREEN_SCALE_FACTORS"] = "1" from dwarf.lib import utils from dwarf.lib.git import Git from dwarf.lib.prefs import Prefs from dwarf.ui.app import AppWindow from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication import dwarf.resources # pylint: disable=unused-import qapp = QApplication([]) qapp.setDesktopSettingsAware(True) qapp.setAttribute(Qt.AA_EnableHighDpiScaling) qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) qapp.setLayoutDirection(Qt.LeftToRight) qapp.setOrganizationName("https://github.com/iGio90/Dwarf") qapp.setApplicationName("Dwarf") qapp.setApplicationDisplayName('Dwarf') # set icon _icon = None if os.name == "nt": if os.path.exists(utils.resource_path('assets/dwarf.ico')): _icon = QIcon(utils.resource_path('assets/dwarf.ico')) else: _icon = QIcon(':/assets/dwarf.ico') else: if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) else: _icon = QIcon(':/assets/dwarf.png') if _icon: qapp.setWindowIcon(_icon) _prefs = Prefs() local_update_disabled = _prefs.get('disable_local_frida_update', False) args = process_args() """ did_first_run = _prefs.get('did_first_run', False) if False: from dwarf.ui.dialogs.dialog_setup import SetupDialog # did_first_run: _prefs.put('did_first_run', True) SetupDialog.showDialog(_prefs) """ if not local_update_disabled: _git = Git() import frida remote_frida = _git.get_frida_version() local_frida = frida.__version__ if remote_frida and local_frida != remote_frida[0]['tag_name']: print('Updating local frida version to ' + remote_frida[0]['tag_name']) try: res = utils.do_shell_command( 'pip3 install frida --upgrade --user') if 'Successfully installed frida-' + remote_frida[0][ 'tag_name'] in res: _on_restart() elif 'Requirement already up-to-date' in res: if os.path.exists('.git_cache'): shutil.rmtree('.git_cache', ignore_errors=True) else: print('failed to update local frida') print(res) except Exception as e: # pylint: disable=broad-except, invalid-name print('failed to update local frida') print(str(e)) if os.name == 'nt': # windows stuff import ctypes try: if os.path.exists(utils.resource_path('assets/dwarf.ico')): # write ini to show folder with dwarficon folder_stuff = "[.ShellClassInfo]\n" folder_stuff += "IconResource=dwarf\\assets\\dwarf.ico,0\n" folder_stuff += "[ViewState]\n" folder_stuff += "Mode=\n" folder_stuff += "Vid=\n" folder_stuff += "FolderType=Generic\n" try: ini_path = os.path.dirname( os.path.abspath(__file__) ) + os.sep + os.pardir + os.sep + 'desktop.ini' with open(ini_path, 'w') as ini: ini.writelines(folder_stuff) # set fileattributes to hidden + systemfile ctypes.windll.kernel32.SetFileAttributesW( ini_path, 0x02 | 0x04 | ~0x20 ) # FILE_ATTRIBUTE_HIDDEN = 0x02 | FILE_ATTRIBUTE_SYSTEM = 0x04 except PermissionError: # its hidden+system already pass # fix for showing dwarf icon in windows taskbar instead of pythonicon _appid = u'iGio90.dwarf.debugger' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( _appid) ctypes.windll.user32.SetProcessDPIAware() except Exception: # pylint: disable=broad-except pass try: # parse target as pid args.pid = int(args.any) except ValueError: args.pid = 0 # default to local if not specified if args.target is None: args.target = 'local' app_window = AppWindow(args) if _icon: app_window.setWindowIcon(_icon) app_window.onRestart.connect(_on_restart) try: sys.exit(qapp.exec_()) except SystemExit as sys_err: if sys_err.code == 0: # thanks for using dwarf print('Thank\'s for using Dwarf\nHave a nice day...') else: # something was wrong print('sysexit with: %d' % sys_err.code)
self.select.setToolTip("Select student profiles") self.check = QPushButton("Check",self) self.check.setToolTip("Check work against past work") self.screen = QTextEdit() self.screen.setReadOnly(True) self.grid.addWidget(self.add,9,2) self.grid.addWidget(self.select,9,3) self.grid.addWidget(self.check,9,4) self.grid.addWidget(self.screen,3,0,4,7) self.upload.clicked.connect(self.getFile) self.add.clicked.connect(CreateAddWindow) self.select.clicked.connect(CreateSelectWindow) self.select.clicked.connect(self.setCurrentStudent) self.setLayout(self.grid) if __name__ == '__main__': #resets CurrentStudent.txt newFile = open("CurrentStudent.txt","w") newFile.write("CurrentStudent") newFile.close() app = QApplication(sys.argv) app.setApplicationDisplayName("Checkr") window = CreateControllerWindow() sys.exit(app.exec_())