class Controller: def __init__(self): self.qt_app = QApplication(sys.argv) self.model = Model() self.view = View() self.view.button.clicked.connect(self.update_model) self.model.signal.connect(self.update_view) signal.signal(signal.SIGINT, self.keyboardInterruptHandler) self.time = QTime() timer = QTimer() timer.timeout.connect(lambda: None) timer.start(100) self.qt_app.exec() def update_model(self): self.time.start() self.model.setdata(self.view.getdata()) def update_view(self): print("--- DONE IN {}ms ---".format(self.time.elapsed())) self.time.restart() self.view.setdata(self.model.getdata()) def keyboardInterruptHandler(self, signal, frame): self.qt_app.exit()
def main_window_no_key(mocker, homedir): # Setup app = QApplication([]) gui = Window() app.setActiveWindow(gui) gui.show() controller = Controller("http://localhost", gui, mocker.MagicMock(), homedir, proxy=False) controller.qubes = False gui.setup(controller) # Create a source widget source_list = gui.main_view.source_list source = factory.Source(public_key=None) source_list.update([source]) # Create a file widget, message widget, and reply widget mocker.patch("securedrop_client.gui.widgets.humanize_filesize", return_value="100") mocker.patch( "securedrop_client.gui.SecureQLabel.get_elided_text", return_value="1-yellow-doc.gz.gpg" ) source.collection.append( [ factory.File(source=source, filename="1-yellow-doc.gz.gpg"), factory.Message(source=source, filename="2-yellow-msg.gpg"), factory.Reply(source=source, filename="3-yellow-reply.gpg"), ] ) source_list.setCurrentItem(source_list.item(0)) gui.main_view.on_source_changed() yield gui # Teardown gui.login_dialog.close() app.exit()
def main(): """ Initializing the neccessary processes """ if globals.DEBUGGING: print("DEBUGGING MODE") app = QApplication(argv) MainWindow = QMainWindow() ui = startWindow_host() ui.setupUi(MainWindow) # Set ut the connections ui.setUpSlots() # Set up validators ui.setUpValidators() ui.setUpMisc() #ui.setUpImages() # MainWindow.setWindowState(QtCore.Qt.WindowFullScreen) MainWindow.show() app.exit(app.exec_()) # Closing down try: ui.serverThread.stop() print("Server shut down") except: pass # The server thread has not been started yet (most likely due to termination before creating server) raise SystemExit
def close(self): ''' 关闭应用程序 :return: ''' app = QApplication(sys.argv) app.exit(0)
def change_time(self): """Change time""" value = self.progress_bar.value() value -= 1 self.progress_bar.setValue(value) self.progress_bar.setFormat(str(value) + " min") if value <= 0: self.timer_shutdown.stop() if self.combo_what_do.currentIndex() == 0: self.progress_bar.hide() if self.combo_what_do.currentIndex() == 1: QApplication.exit() if self.combo_what_do.currentIndex() == 2: try: if sys.platform.startswith("linux"): QProcess.startDetached("systemctl suspend") if sys.platform.startswith("win"): QProcess.startDetached( "rundll32.exe powrprof.dll,SetSuspendState 0,1,0") except: pass if self.combo_what_do.currentIndex() == 3: if sys.platform.startswith("win"): QProcess.startDetached("shutdown.exe /s") if sys.platform.startswith("linux"): QProcess.startDetached("shutdown -P now")
class Joxi: trey = None hover_text = 'Joxi' window: QMainWindow = None def __init__(self): self.app = QApplication(sys.argv) # create trey menu self.menu_options = [('Make screenshot', None, self.makeScreenshot)] self.trey = SysTrayIcon('./Images/Logo.ico', self.hover_text, self.menu_options, self.quit) # start app execution self.app.exec() def makeScreenshot(self, *args): # show screenshot selecter and subscribe on end self.window = DesktopWindow() self.window.activateWindow() self.window.screenShotSignal.event.connect(self.showPaint) def showPaint(self, image: QPixmap): self.window = DrawWindow(image) def quit(self, *args): print('Bye') if self.app: self.app.exit(0) exit(0)
def run_24(kwargs, share): # To make process stable time.sleep(5) # To suppress warning messages config.MUTE = True # 초기화 및 로그인 app = QApplication(sys.argv) bot = myBot() bot.login() """ Hidden """ # 다운로드 시작 result = bot.histories(**kwargs) # 결과 저장 및 공유 share['result'] = result share['complete'] = True # Bot 실행 종료 app.exit()
def exit(self): latus.logger.log.info('exit') # self.hide() if self.sync: latus.logger.log.info('requesting exit') self.sync.request_exit() QApplication.exit() # todo: what should this parameter be?
def test_viewer_seeds(self): try: from imcut.seed_editor_qt import QTSeedEditor except: print("Deprecated of pyseg_base as submodule") from seed_editor_qt import QTSeedEditor from PyQt5.QtWidgets import QApplication import numpy as np img3d = (np.random.rand(30, 30, 30)*10).astype(np.int16) seeds = (np.zeros(img3d.shape)).astype(np.int8) seeds[3:6, 12:18, 9:16] = 1 seeds[3:6, 19:22, 21:27] = 2 # , QMainWindow app = QApplication(sys.argv) pyed = QTSeedEditor(img3d, seeds=seeds) pyed.exec_() # deletemask = pyed.getSeeds() # import pdb; pdb.set_trace() # pyed = QTSeedEditor(deletemask, mode='draw') # pyed.exec_() app.exit()
def PdfConverter(username): htmllink = "bootstrap_mod/usertemp/"+username+".html" app1 = QApplication(sys.argv) web = QWebView() link =QUrl.fromLocalFile(QFileInfo(htmllink).absoluteFilePath()) web.load(QUrl(link)) printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) Pdf_Generated_Name="bootstrap_mod/usertemp/"+username+".pdf" printer.setOutputFileName(Pdf_Generated_Name) web.print(printer) QApplication.exit() def convertIt(): web.print(printer) print("Pdf generated") QApplication.exit() web.loadFinished.connect(convertIt) sys.exit(app1.exec_()) return 0
def visualization(self): """ Run viewer with output data3d and segmentation """ try: from imcut.seed_editor_qt import QTSeedEditor except: logger.warning("Deprecated of pyseg_base as submodule") from seed_editor_qt import QTSeedEditor from PyQt5.QtWidgets import QApplication import numpy as np #, QMainWindow app = QApplication(sys.argv) #pyed = QTSeedEditor(self.data3d, contours=(self.segmentation>0)) pyed = QTSeedEditor(self.segmentation) pyed.exec_() #import pdb; pdb.set_trace() #pyed = QTSeedEditor(deletemask, mode='draw') #pyed.exec_() app.exit()
def launch_app(**kwargs): app = QApplication(sys.argv) pomodoro = create_pomodoro_timer(**kwargs) # Подключаемся к DBus для уведомлений notify2.init('Pomodoro', 'glib') tray_icon: QSystemTrayIcon = QSystemTrayIcon(QIcon('static/icon.png'), app) tray_icon.setToolTip('Manage your time!') tray_icon.show() menu = QMenu() display_menu: QAction = menu.addAction('00:00') display_menu.setEnabled(False) pause_menu: QAction = menu.addAction('Pause') pause_menu.triggered.connect(pomodoro.pause) continue_menu: QAction = menu.addAction('Continue') continue_menu.triggered.connect(pomodoro.continue_work) exit_menu = menu.addAction('Exit') exit_menu.triggered.connect(app.quit) tray_icon.setContextMenu(menu) tray_icon.contextMenu().aboutToShow.connect( lambda: menu_opening_event(pomodoro, display_menu)) pomodoro.start() n = notify2.Notification('Pomodoro запущен') n.timeout = 700 n.show() app.exit(app.exec_())
class App(object): def __init__(self): self.settings = SettingsManager() self.app = QApplication([]) self.gui = MainWindow(app=self) self.setup() def setup(self): self.gui.show() self.gui.resize(self.settings.get('application_width_initial'), self.settings.get('application_height_initial')) def open(self): self.app.exec_() def suspend(self): pass def close(self): self.exit() def exit(self): """ Runs cleanup and then closes the app """ self.app.exit() sys.exit()
def error_spawner(self): ignored = [] while True: time_occured, exctype, value, tb, thread = self.error_queue.get() error = "".join( traceback.format_exception(etype=exctype, value=value, tb=tb)) hash_ = hash(error) if hash_ in ignored: continue label_suffix = '' if brickv_version[1] == (0, 0, 0): label_suffix += '<br/><br/><b>Your Brick Viewer version is {}, however it is unknown if a newer version is available.</b> Please <a href="https://www.tinkerforge.com/en/doc/Downloads.html#tools">check for updates</a> before reporting this error.'.format( config.BRICKV_FULL_VERSION) elif brickv_version[0] < brickv_version[1]: label_suffix += '<br/><br/><b>Your Brick Viewer version is {}, however {}.{}.{} is available.</b> Please update and try again before reporting this error.'.format( config.BRICKV_FULL_VERSION, *brickv_version[1]) runtime = str( datetime.timedelta(seconds=time.monotonic() - self.start_time)) prefix = 'Brick Viewer {} on\n{}\nPyQt {}\nQt {}\nPython {}\nSystem language: {}\n\nException raised at {}\nBrick Viewer ran for {}\n'.format( config.BRICKV_FULL_VERSION, self.get_os_name(), PYQT_VERSION_STR, QT_VERSION_STR, sys.version.replace("\n", ""), locale.getdefaultlocale()[0], time_occured, runtime) if thread is not None: prefix += ' by Thread {}'.format(thread.ident) if thread.name is not None: prefix += ' (Name: {})'.format(thread.name) print(prefix) prefix = label_suffix + '!!!' + prefix traceback.print_exception(etype=exctype, value=value, tb=tb) print("") report_message = prefix + '\n' + error + '\nActive Threads:\n\n' + '\n\n'.join( self.get_python_thread_stack_traces()) # Either sys.executable is /path/to/python, then run calls /path/to/python /path/to/main.py --error-report, # or sys.executable is brickv[.exe], then the --error-report flag ensures, that the path to main.py is ignored. rc = subprocess.run( [sys.executable, os.path.realpath(__file__), "--error-report"] + self.argv, input=report_message, universal_newlines=True).returncode show_again = rc & 1 == 1 exit_requested = rc & 2 == 2 if exit_requested: QApplication.exit(1) return if not show_again: ignored.append(hash_)
def main(): """ Initializing the neccessary processes """ if globals.DEBUGGING: print("DEBUGGING MODE") # Start splash screen (loading) app = QApplication(argv) globals.app = app globals.standard_palette = app.palette( ) # Store standard palette if user wants to change back to the default light palette app.setAttribute(Qt.AA_DisableHighDpiScaling) MainWindow = QMainWindow() ui = startWindow_player() ui.setupUi(MainWindow) ui.setUpSlots() ui.setUpValidators() ui.setUpImages() ui.setUpTheme() ui.setUpFonts() ui.setUpMisc() clientNetwork = ClientNetwork(ui) clientNetwork.start() # end splash screen MainWindow.show() app.exit(app.exec_()) clientNetwork.stop()
def qt(): application = QApplication([]) yield application application.exit() # If we don't force deletion of the C++ wrapped object, it causes the test suite to eventually crash # Never ever remove this!! sip.delete(application)
def scct_app(tmpdir_factory, caplog): caplog.set_level(logging.ERROR) app = QApplication(sys.argv) app.setStyle(QStyleFactory.create('Fusion')) tmp_dir = tmpdir_factory.getbasetemp() if tmp_dir.join('profiles').check(exists=0): profile_dir = tmp_dir.mkdir('profiles').mkdir( hex(random.randint(49152, 65535))[2:]) casting_html_src = os.path.normpath( os.path.join(os.path.dirname(__file__), '../casting_html')) assert os.path.exists(casting_html_src) casting_html = profile_dir.join('casting_html') if casting_html.check(exists=0): shutil.copytree(casting_html_src, casting_html) scctool.settings.loadSettings(str(tmp_dir), True) cntlr = MainController() main_window = MainWindow(cntlr, app, False) main_window.show() yield (main_window, cntlr) main_window.close() cntlr.cleanUp() app.exit(1) for record in caplog.records: assert record.levelname != 'CRITICAL' assert record.levelname != 'ERROR'
def load_filename(caption='Find a filename', directory='/home/ppxjd3/Code/Generic/', file_filter='*.*;;*.png;;*.jpg', remove_ext=False): """ Choose a load filename using a dialog. Parameters ---------- caption: str Title for the window directory: str Path to open the file dialog at file_filter:str String containing extension wildcards separated by ;; Returns ------- filename: str The load filename including path and extension """ app = QApplication(sys.argv) filename = QFileDialog.getOpenFileName(parent=None, caption=caption, directory=directory, filter=file_filter)[0] app.exit() if remove_ext: filename = os.path.splitext(filename)[0] return filename
def main(): parser = createArgParser() args = parser.parse_args() # if no args print help and exit if not len(sys.argv[1:]): parser.print_help() error('No arguments found :( exit...') if not os.path.exists( args.qt_uifile ): error( 'Qt ui file path not correct :( exit... ' ) app = QApplication(sys.argv) uifile = args.qt_uifile outdir = args.ngl_out_dir verbose = args.verbose bitmap_compress = ( args.bitmap_compress, args.bitmap_jpeg_quality ) # create nuic object and parse Qt ui file nuic = NUIC( uifile ) ppage = nuic.parser.parse() nuic.informUser( 'parse_end', verbose ) # convert all fonts, generate common fonts header code ngl_fonts = nuic.convertFonts( ppage['fonts'], verbose ) ngl_fonts_header = nuic.fontsHeaderCode( ngl_fonts, verbose ) # convert all bitmaps, generate common bitmaps header code ngl_bitmaps = nuic.convertBitmaps( ppage['bitmaps'], bitmap_compress, ppage['background_color'], verbose ) ngl_bitmaps_header = nuic.bitmapsHeaderCode( ngl_bitmaps, verbose ) # generate page and objects code pagecode = nuic.pageCode( ppage, ngl_bitmaps, ngl_fonts, verbose ) pageheadercode = nuic.pageHeaderCode( ppage, verbose ) headerscode = nuic.objectsHeaderCode(ppage, ngl_bitmaps, ngl_fonts, verbose) # inform by end of conversion and generation code nuic.informUser( 'convert_end', verbose ) # create dirs for save generated code code_dirs = nuic.createDirs( basepath=outdir, pagename=ppage['name'] ) nuic.informUser('create_dirs', verbose) # save all code nuic.save( pagename = ppage['name'], pagecode = pagecode, pageheadercode = pageheadercode, headerscode = headerscode, bitmaps = ngl_bitmaps, bitmapsheader = ngl_bitmaps_header, fonts = ngl_fonts, fontsheader = ngl_fonts_header, verbose = verbose ) # final app.exit() inform( '-*-*- All works finish! :) --- out code locate in %s' % os.path.abspath(code_dirs['base']) )
def exit(self): latus.logger.log.info('exit') # self.hide() if self.sync: self.sync.request_exit() else: latus.logger.log.warn('trying to exit a non-existent sync') QApplication.exit() # todo: what should this parameter be?
def Mainloop(filepath): global Filepath Filepath = filepath app = QApplication([]) page = GraphPage() ani = animation.FuncAnimation(page.figure, page.animate, interval=100) page.show() app.exit(app.exec_())
def qt(): _print_unhandled_exceptions() application = QApplication([]) yield application application.exit() # If we don't force deletion of the C++ wrapped object, it causes the test suite to eventually crash # Never ever remove this!! sip.delete(application)
def exit(self): log.info('exit') self.stop_scan() # stop any scans currently underway request_blink_exit() if self._watcher: self._watcher.request_exit() self.hide() QApplication.exit() # todo: what should this parameter be?
def runica(x, fs, channels, mode='ica'): from PyQt5.QtWidgets import QApplication from pynfb.protocols.ssd.topomap_selector_ica import ICADialog a = QApplication([]) ica = ICADialog(x, channels, fs, mode=mode) ica.exec_() a.exit() return ica.spatial, ica.topography
def start_gui(experiment): """ Starts a GUI for the ScanWindow using the provided experiment. :param Experiment experiment: Experiment object with a loaded config. """ ap = QApplication(sys.argv) m = ScanWindow(experiment) m.show() ap.exit(ap.exec_())
def qapp(): app = QApplication.instance() if app is None: app = QApplication([]) yield app app.exit() else: yield app
def main(): """ run application """ app = QApplication(sys.argv) win = MainWindow() win.setGeometry(1200, 30, 500, 100) app.exit(app.exec_())
def test_blank(): app = QApplication(sys.argv) registerPresenterWindow = RegisterPresenter() result = registerPresenterWindow.test_loginInput(registerPresenterWindow, '', '') # blank username QTest.qWait(2.0 * 1000) app.exit() # registerPresenterWindow._view.close() expected = None assert result == expected
def run(): app = QApplication([]) win = view.StartWindow() win.setWindowTitle('Camera Calibration Application') win.resize(1500, 1000) win.show() app.exit(app.exec_())
def msg(self): reply = QMessageBox.information(self, "Tetrixs", "GameOver", QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.canvas.start() if reply == QMessageBox.No: app = QApplication(sys.argv) app.exit(0)
def test_validLogin(): app = QApplication(sys.argv) registerPresenterWindow = RegisterPresenter() result = registerPresenterWindow.test_loginInput(registerPresenterWindow, 'Munbodh21', 'Hemal21') # valid username valid password QTest.qWait(2.0 * 1000) # wait 2 seconds before closing login window app.exit() expected = MainPresenter('Munbodh21') assert result.current_user == expected.current_user
def warn_user(error): app = QApplication.instance() if not app: app = QApplication(sys.argv) QMessageBox.warning( None, 'ERROR!', 'An critical error happened running the program. Please forward this error to developer:\n\n' f'{error}', QMessageBox.Ok) QApplication.exit(1)
def exit(self): """ Exit the GUI """ if self.check_if_save() is None: return # If a robot is running, kill the process before exiting self.robot_integration_area.stop_robot() QApplication.exit()
def eventFilter(self, obj, event): """ Public method to filter events. @param obj reference to the object the event is meant for (QObject) @param event reference to the event object (QEvent) @return flag indicating, whether the event was handled (boolean) """ if event.type() == QEvent.Close: QApplication.exit() return True return False
def runica2(x, fs, channels, names=('Right', 'Left'), mode='ica'): from PyQt5.QtWidgets import QApplication from pynfb.protocols.ssd.topomap_selector_ica import ICADialog a = QApplication([]) res = [] decomposition = None for n in names: print('*** Select component for condition: ' + n) ica = ICADialog(x, channels, fs, decomposition=decomposition, mode=mode) ica.exec_() res.append(np.array((ica.spatial, ica.topography))) decomposition = ica.decomposition a.exit() return res
def on_action_quit_triggered(self, checked = None): global cfg if checked is None: return if self.dirty_either() and \ QtWidgets.QMessageBox.question(self, "Unsaved data", "There are unsaved changes, sure you want to quit", QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) != QtWidgets.QMessageBox.Yes: return try: cdoc, croot = configfile.init_save(CONFIGROOT) cfg.save(cdoc, croot) configfile.complete_save(cdoc, CONFIGFNAME) except configfile.ConfigError as e: QtWidgets.QMessageBox.warning(self, "Configuration file error", e.args[0]) QApplication.exit(0)
def error_report_main(): error_message = sys.stdin.read() error_message = "<pre>{}</pre>".format(html.escape(error_message).replace("\n", "<br>")) app = QApplication(sys.argv) if sys.platform == 'darwin': # workaround macOS QTBUG-61562 from brickv.mac_pasteboard_mime_fixed import MacPasteboardMimeFixed mac_pasteboard_mime_fixed = MacPasteboardMimeFixed() window = QMainWindow() window.setWindowTitle('Error - Brick Viewer ' + config.BRICKV_VERSION) window.setWindowIcon(QIcon(load_pixmap('brickv-icon.png'))) widget = QWidget() window.setCentralWidget(widget) widget.setLayout(QHBoxLayout()) icon = QLabel() icon.setPixmap(QMessageBox.standardIcon(QMessageBox.Critical)) icon.setAlignment(Qt.AlignHCenter | Qt.AlignTop) widget.layout().addWidget(icon) right_widget = QWidget() right_widget.setLayout(QVBoxLayout()) right_widget.layout().setContentsMargins(0, 0, 0, 0) label = QLabel("Please report this error to <a href='mailto:[email protected]'>[email protected]</a>.<br/><br/>" + "If you know what caused the error and could work around it, please report it anyway. This allows us to improve the error messages.") label.setWordWrap(True) label.setOpenExternalLinks(True) right_widget.layout().addWidget(label) tb = QTextBrowser() tb.setHtml(error_message) right_widget.layout().addWidget(tb) cbox = QCheckBox("Show this message again") cbox.setChecked(True) right_widget.layout().addWidget(cbox) btn = QPushButton("Close") btn.clicked.connect(lambda event: app.exit()) right_widget.layout().addWidget(btn) widget.layout().addWidget(right_widget) window.setMinimumSize(640, 400) window.resize(950, 600) window.show() app.exec_() return int(cbox.isChecked())
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.addSection("Parrot Companion") # Firmware version self.firmware = QAction("Firmware: Unknown", self) self.firmware.setEnabled(False) self.addAction(self.firmware) # Battery level icon = QIcon.fromTheme("battery") self.battery = QAction(icon, "Battery: Unknown", self) self.battery.setEnabled(False) self.addAction(self.battery) # Quit icon = QIcon.fromTheme("application-exit") action = QAction(icon, "&Quit", self) action.triggered.connect(lambda: QApplication.exit(0)) self.addAction(action)
def convertIt(): web.print_(printer) print ("PDF Created") QApplication.exit()
def main(): parser = createArgParser() args = parser.parse_args() # if no args print help and exit if not len(sys.argv[1:]): parser.print_help() error("No arguments found :( exit...") if not os.path.exists(args.qt_uifile): error("Qt ui file path not correct :( exit... ") app = QApplication(sys.argv) uifile = args.qt_uifile outdir = args.ngl_out_dir verbose = args.verbose bitmap_compress = (args.bitmap_compress, args.bitmap_jpeg_quality) # create nuic object and parse Qt ui file nuic = NUIC(uifile) ppage = nuic.parser.parse() nuic.informUser("parse_end", verbose) # convert all fonts, generate common fonts header code ngl_fonts = nuic.convertFonts(ppage["fonts"], verbose) ngl_fonts_header = nuic.fontsHeaderCode(ngl_fonts, verbose) # convert all bitmaps, generate common bitmaps header code ngl_bitmaps = nuic.convertBitmaps(ppage["bitmaps"], bitmap_compress, ppage["background_color"], verbose) ngl_bitmaps_header = nuic.bitmapsHeaderCode(ngl_bitmaps, verbose) # generate page and objects code pagecode = nuic.pageCode(ppage, ngl_bitmaps, ngl_fonts, verbose) pageheadercode = nuic.pageHeaderCode(ppage, verbose) headerscode = nuic.objectsHeaderCode(ppage, ngl_bitmaps, ngl_fonts, verbose) # inform by end of conversion and generation code nuic.informUser("convert_end", verbose) # create dirs for save generated code code_dirs = nuic.createDirs(basepath=outdir, pagename=ppage["name"]) nuic.informUser("create_dirs", verbose) # save all code nuic.save( pagename=ppage["name"], pagecode=pagecode, pageheadercode=pageheadercode, headerscode=headerscode, bitmaps=ngl_bitmaps, bitmapsheader=ngl_bitmaps_header, fonts=ngl_fonts, fontsheader=ngl_fonts_header, verbose=verbose, ) # final app.exit() inform("-*-*- All works finish! :) --- out code locate in %s" % os.path.abspath(code_dirs["base"]))
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 print_exc_and_exit(*args): old_excepthook(*args) sys.stderr.write("Exiting early due to an unhandled exception. See error output above.\n") QApplication.exit(1)
class QtGUIController(GUIController): def __init__(self): self.events = Queue() self.app = QApplication(sys.argv) self.w = uic.loadUi("main.ui") self.w.setAttribute(Qt.WA_DeleteOnClose, True) self.w.show() self.sattable = self.w.satTable self.satview = self.w.mapCanvas self.scene = QtScene(self.satview) self.pal = QtPalette() self.rendersats = set() self.satcolors = dict() hdr = self.sattable.horizontalHeader() hdr.setSectionResizeMode(0, QHeaderView.ResizeToContents) hdr.setSectionResizeMode(1, QHeaderView.Fixed) hdr.setSectionResizeMode(2, QHeaderView.Fixed) self.w.dtFrom.setDateTime(QDateTime.currentDateTimeUtc()) self.w.dtTo.setDateTime( QDateTime.currentDateTimeUtc().addSecs(3600 * 2) ) self.filters = ["*", "*", "*", "*"] self.selectall = False self.nosats = True self.colchange = False self.connect_sigs() def __del__(self): self.app.exit(0) def update(self): self.app.processEvents() def set_filter(self, fil): fil = [x.strip().upper() for x in fil] self.filters = list(map(lambda f: "*" if f in ["", None] else f, fil)) for r in range(self.sattable.rowCount()): hide = False for c in range(1, len(self.filters)): str = self.sattable.item(r, c).text() if not fnmatch(str, self.filters[c]): hide = True break self.sattable.setRowHidden(r, hide) def clear_sats(self): self.rendersats.clear() self.satcolors.clear() self.sattable.setRowCount(0) self.scene.clear() self.nosats = True def set_sats(self, sats): for sat in sats: self.sat_insert(sat) self.nosats = False def show_error(self, s): msg = QMessageBox() msg.setWindowTitle("Error!") msg.setText(s) msg.setIcon(QMessageBox.Warning) msg.exec() # internal methods def sat_insert(self, sat): row = self.sattable.rowCount() self.sattable.insertRow(row) cb = QTableWidgetItem("") cb.setCheckState(Qt.Unchecked) self.sattable.setItem(row, 0, cb) self.sattable.setItem( row, 1, QTableWidgetItem(str(sat.norad)) ) self.sattable.setItem( row, 2, QTableWidgetItem(str(sat.intl)) ) self.sattable.setItem( row, 3, QTableWidgetItem(str(sat.name)) ) def render_sats(self, sats, time_a, time_b): self.scene.clear() for n, lines in sats: self.pal.set_fg_color(self.satcolors[n]) self.scene.add_path(lines, self.pal.bg_pen, self.pal.fg_pen) # Qt slots def connect_sigs(self): hdr = self.sattable.horizontalHeader() hdr.sectionPressed.connect(self.slot_header_click) self.sattable.itemChanged.connect(self.slot_check_sat) self.w.destroyed.connect(self.slot_exit) self.w.fButton.pressed.connect(self.slot_set_filter) self.w.renderButton.pressed.connect(self.slot_render) self.w.saveButton.pressed.connect(self.slot_save) self.w.loadButton.pressed.connect(self.slot_load) self.w.refreshButton.pressed.connect(self.slot_refresh) def slot_render(self): time_a = self.w.dtFrom.dateTime().toMSecsSinceEpoch() / 1000 time_b = self.w.dtTo.dateTime().toMSecsSinceEpoch() / 1000 self.events.put(EvRender((time_a, time_b, self.rendersats))) def slot_set_filter(self): fil = ["*"] fil.append(self.w.fNoradEdit.text()) fil.append(self.w.fIntlEdit.text()) fil.append(self.w.fNameEdit.text()) self.set_filter(fil) def slot_check_sat(self, item): if self.nosats: return if self.colchange: self.colchange = False return if item.column() != 0: return self.colchange = True row = item.row() chk = self.sattable.item(row, 0).checkState() norad = int(self.sattable.item(row, 1).text()) if chk == Qt.Checked: self.rendersats.add(norad) self.satcolors[norad] = self.pal.wind() color = self.pal.color(self.satcolors[norad]) item.setBackground(color) else: self.rendersats.discard(norad) self.satcolors.pop(norad) item.setBackground(Qt.transparent) self.w.saveButton.setEnabled(bool(self.rendersats)) def slot_header_click(self, idx): if idx != 0: return self.selectall = not self.selectall chk = Qt.Checked if self.selectall else Qt.Unchecked for r in range(self.sattable.rowCount()): self.sattable.item(r, 0).setCheckState(chk) def slot_save(self): fname = QFileDialog.getSaveFileName( self.w, "Save TLE", ".", "TLE lists (*.txt *.tle *.tlelist)" )[0] if fname in ["", None]: return self.events.put(EvSaveTLE((self.rendersats, fname))) def slot_load(self): fname = QFileDialog.getOpenFileName( self.w, "Open TLE", "./selection.txt", "TLE lists (*.txt *.tle *.tlelist)" )[0] if fname in ["", None]: return self.events.put(EvLoadTLE(fname)) def slot_refresh(self): self.events.put(EvReloadAll()) def slot_exit(self): sys.exit(0)
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()
def convertIt(): web.print(printer) print("Pdf generated") QApplication.exit()
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()
class DistUpgradeViewKDE(DistUpgradeView): """KDE frontend of the distUpgrade tool""" def __init__(self, datadir=None, logdir=None): DistUpgradeView.__init__(self) # silence the PyQt4 logger logger = logging.getLogger("PyQt4") logger.setLevel(logging.INFO) if not datadir or datadir == '.': localedir=os.path.join(os.getcwd(),"mo") else: localedir="/usr/share/locale/ubuntu-release-upgrader" # FIXME: i18n must be somewhere relative do this dir try: gettext.bindtextdomain("ubuntu-release-upgrader", localedir) gettext.textdomain("ubuntu-release-upgrader") except Exception as e: logging.warning("Error setting locales (%s)" % e) # we test for DISPLAY here, QApplication does not throw a # exception when run without DISPLAY but dies instead if not "DISPLAY" in os.environ: raise Exception("No DISPLAY in os.environ found") self.app = QApplication(["ubuntu-release-upgrader"]) # Try to load default Qt translations so we don't have to worry about # QStandardButton translations. translator = QTranslator(self.app) if type(PYQT_VERSION) == int: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt5/translations') else: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt4/translations') self.app.installTranslator(translator) QUrlOpener().setupUrlHandles() if os.path.exists("/usr/share/icons/oxygen/48x48/apps/system-software-update.png"): messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/apps/system-software-update.png") else: messageIcon = QPixmap("/usr/share/icons/hicolor/48x48/apps/adept_manager.png") self.app.setWindowIcon(QIcon(messageIcon)) self.window_main = UpgraderMainWindow() self.window_main.setParent(self) self.window_main.show() self.prev_step = 0 # keep a record of the latest step self._opCacheProgress = KDEOpProgress(self.window_main.progressbar_cache, self.window_main.progress_text) self._acquireProgress = KDEAcquireProgressAdapter(self) self._cdromProgress = KDECdromProgressAdapter(self) self._installProgress = KDEInstallProgressAdapter(self) # reasonable fault handler sys.excepthook = self._handleException self.window_main.showTerminalButton.setEnabled(False) self.window_main.showTerminalButton.clicked.connect(self.showTerminal) # init gettext gettext.bindtextdomain("ubuntu-release-upgrader",localedir) gettext.textdomain("ubuntu-release-upgrader") self.translate_widget_children() self.window_main.label_title.setText(self.window_main.label_title.text().replace("Ubuntu", "Kubuntu")) # setup terminal text in hidden by default spot self.window_main.konsole_frame.hide() self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame) self.window_main.konsole_frame.setMinimumSize(600, 400) self.terminal_text = DumbTerminal(self._installProgress, self.window_main.konsole_frame) self.konsole_frame_layout.addWidget(self.terminal_text) self.terminal_text.show() # for some reason we need to start the main loop to get everything displayed # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets QTimer.singleShot(10, self.exitMainLoop) self.app.exec_() def exitMainLoop(self): print("exitMainLoop") self.app.exit() def translate_widget_children(self, parentWidget=None): if parentWidget == None: parentWidget = self.window_main if isinstance(parentWidget, QDialog) or isinstance(parentWidget, QWidget): if str(parentWidget.windowTitle()) == "Error": parentWidget.setWindowTitle( gettext.dgettext("kdelibs", "Error")) else: parentWidget.setWindowTitle(_( str(parentWidget.windowTitle()) )) if parentWidget.children() != None: for widget in parentWidget.children(): self.translate_widget(widget) self.translate_widget_children(widget) def translate_widget(self, widget): if isinstance(widget, QLabel) or isinstance(widget, QPushButton): if str(widget.text()) == "&Cancel": kdelibs = gettext.translation( "kdelibs", gettext.textdomain("kdelibs"), fallback=True) widget.setText(unicode_gettext(kdelibs, "&Cancel")) elif str(widget.text()) == "&Close": kdelibs = gettext.translation( "kdelibs", gettext.textdomain("kdelibs"), fallback=True) widget.setText(unicode_gettext(kdelibs, "&Close")) elif str(widget.text()) != "": widget.setText( _(str(widget.text())).replace("_", "&") ) def _handleException(self, exctype, excvalue, exctb): """Crash handler.""" if (issubclass(exctype, KeyboardInterrupt) or issubclass(exctype, SystemExit)): return # we handle the exception here, hand it to apport and run the # apport gui manually after it because we kill u-m during the upgrade # to prevent it from popping up for reboot notifications or FF restart # notifications or somesuch lines = traceback.format_exception(exctype, excvalue, exctb) logging.error("not handled exception in KDE frontend:\n%s" % "\n".join(lines)) # we can't be sure that apport will run in the middle of a upgrade # so we still show a error message here apport_crash(exctype, excvalue, exctb) if not run_apport(): tbtext = ''.join(traceback.format_exception(exctype, excvalue, exctb)) dialog = QDialog(self.window_main) loadUi("dialog_error.ui", dialog) self.translate_widget_children(self.dialog) dialog.crash_detail.setText(tbtext) # Make sure we have a suitable size depending on whether or not the view is shown dialog.adjustSize() dialog.exec_() sys.exit(1) def showTerminal(self): if self.window_main.konsole_frame.isVisible(): self.window_main.konsole_frame.hide() self.window_main.showTerminalButton.setText(_("Show Terminal >>>")) else: self.window_main.konsole_frame.show() self.window_main.showTerminalButton.setText(_("<<< Hide Terminal")) self.window_main.resize(self.window_main.sizeHint()) def getAcquireProgress(self): return self._acquireProgress def getInstallProgress(self, cache): self._installProgress._cache = cache return self._installProgress def getOpCacheProgress(self): return self._opCacheProgress def getCdromProgress(self): return self._cdromProgress def update_status(self, msg): self.window_main.label_status.setText(msg) def hideStep(self, step): image = getattr(self.window_main,"image_step%i" % step) label = getattr(self.window_main,"label_step%i" % step) image.hide() label.hide() def abort(self): step = self.prev_step if step > 0: image = getattr(self.window_main,"image_step%i" % step) if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png"): cancelIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png") elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png"): cancelIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png") else: cancelIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/cancel.png") image.setPixmap(cancelIcon) image.show() def setStep(self, step): if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png"): okIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png") elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png"): okIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png") else: okIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/ok.png") if os.path.exists("/usr/share/icons/oxygen/16x16/actions/arrow-right.png"): arrowIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/arrow-right.png") elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png"): arrowIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png") else: arrowIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/1rightarrow.png") if self.prev_step: image = getattr(self.window_main,"image_step%i" % self.prev_step) label = getattr(self.window_main,"label_step%i" % self.prev_step) image.setPixmap(okIcon) image.show() ##arrow.hide() self.prev_step = step # show the an arrow for the current step and make the label bold image = getattr(self.window_main,"image_step%i" % step) label = getattr(self.window_main,"label_step%i" % step) image.setPixmap(arrowIcon) image.show() label.setText("<b>" + label.text() + "</b>") def information(self, summary, msg, extended_msg=None): msg = "<big><b>%s</b></big><br />%s" % (summary,msg) dialogue = QDialog(self.window_main) loadUi("dialog_error.ui", dialogue) self.translate_widget_children(dialogue) dialogue.label_error.setText(msg) if extended_msg != None: dialogue.textview_error.setText(extended_msg) dialogue.textview_error.show() else: dialogue.textview_error.hide() dialogue.setWindowTitle(_("Information")) if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-information.png"): messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-information.png") elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png"): messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png") else: messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_info.png") dialogue.image.setPixmap(messageIcon) # Make sure we have a suitable size depending on whether or not the view is shown dialogue.adjustSize() dialogue.exec_() def error(self, summary, msg, extended_msg=None): msg="<big><b>%s</b></big><br />%s" % (summary, msg) dialogue = QDialog(self.window_main) loadUi("dialog_error.ui", dialogue) self.translate_widget_children(dialogue) dialogue.label_error.setText(msg) if extended_msg != None: dialogue.textview_error.setText(extended_msg) dialogue.textview_error.show() else: dialogue.textview_error.hide() if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-error.png"): messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-error.png") elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png"): messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png") else: messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_critical.png") dialogue.image.setPixmap(messageIcon) # Make sure we have a suitable size depending on whether or not the view is shown dialogue.adjustSize() dialogue.exec_() return False def confirmChanges(self, summary, changes, demotions, downloadSize, actions=None, removal_bold=True): """show the changes dialogue""" # FIXME: add a whitelist here for packages that we expect to be # removed (how to calc this automatically?) DistUpgradeView.confirmChanges(self, summary, changes, demotions, downloadSize) self.changesDialogue = QDialog(self.window_main) loadUi("dialog_changes.ui", self.changesDialogue) self.changesDialogue.treeview_details.hide() self.changesDialogue.buttonBox.helpRequested.connect(self.showChangesDialogueDetails) self.translate_widget_children(self.changesDialogue) self.changesDialogue.buttonBox.button(QDialogButtonBox.Ok).setText(_("&Start Upgrade")) self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setIcon(QIcon()) self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setText(_("Details") + " >>>") self.changesDialogue.resize(self.changesDialogue.sizeHint()) if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-warning.png"): warningIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-warning.png") elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png"): warningIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png") else: warningIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_warning.png") self.changesDialogue.question_pixmap.setPixmap(warningIcon) if actions != None: cancel = actions[0].replace("_", "") self.changesDialogue.buttonBox.button(QDialogButtonBox.Cancel).setText(cancel) confirm = actions[1].replace("_", "") self.changesDialogue.buttonBox.button(QDialogButtonBox.Ok).setText(confirm) summaryText = "<big><b>%s</b></big>" % summary self.changesDialogue.label_summary.setText(summaryText) self.changesDialogue.label_changes.setText(self.confirmChangesMessage) # fill in the details self.changesDialogue.treeview_details.clear() self.changesDialogue.treeview_details.setHeaderLabels(["Packages"]) self.changesDialogue.treeview_details.header().hide() for demoted in self.demotions: self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("No longer supported %s") % demoted.name]) ) for rm in self.toRemove: self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove %s") % rm.name]) ) for rm in self.toRemoveAuto: self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove (was auto installed) %s") % rm.name]) ) for inst in self.toInstall: self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Install %s") % inst.name]) ) for up in self.toUpgrade: self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Upgrade %s") % up.name]) ) #FIXME resize label, stop it being shrinkable res = self.changesDialogue.exec_() if res == QDialog.Accepted: return True return False def showChangesDialogueDetails(self): if self.changesDialogue.treeview_details.isVisible(): self.changesDialogue.treeview_details.hide() self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setText(_("Details") + " >>>") # Make sure we shrink the dialog otherwise it looks silly self.changesDialogue.adjustSize() else: self.changesDialogue.treeview_details.show() self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setText("<<< " + _("Details")) self.changesDialogue.resize(self.changesDialogue.sizeHint()) def askYesNoQuestion(self, summary, msg, default='No'): answer = QMessageBox.question(self.window_main, summary, "<font>" + msg, QMessageBox.Yes|QMessageBox.No, QMessageBox.No) if answer == QMessageBox.Yes: return True return False def confirmRestart(self): messageBox = QMessageBox(QMessageBox.Question, _("Restart required"), _("<b><big>Restart the system to complete the upgrade</big></b>"), QMessageBox.NoButton, self.window_main) yesButton = messageBox.addButton(QMessageBox.Yes) noButton = messageBox.addButton(QMessageBox.No) yesButton.setText(_("_Restart Now").replace("_", "&")) noButton.setText(gettext.dgettext("kdelibs", "&Close")) answer = messageBox.exec_() if answer == QMessageBox.Yes: return True return False def processEvents(self): QApplication.processEvents() def pulseProgress(self, finished=False): # FIXME: currently we do nothing here because this is # run in a different python thread and QT explodes if the UI is # touched from a non QThread pass def on_window_main_delete_event(self): #FIXME make this user friendly text = _("""<b><big>Cancel the running upgrade?</big></b> The system could be in an unusable state if you cancel the upgrade. You are strongly advised to resume the upgrade.""") text = text.replace("\n", "<br />") cancel = QMessageBox.warning(self.window_main, _("Cancel Upgrade?"), text, QMessageBox.Yes, QMessageBox.No) if cancel == QMessageBox.Yes: return True return False
#! python # -*- coding: utf-8 -*- """ pugdebug - a standalone PHP debugger ========================= copyright: (c) 2015 Robert Basic license: GNU GPL v3, see LICENSE for more details """ __author__ = "robertbasic" # Fix for Gtk-CRITICAL issues on Ubuntu # Turn off that stupid overlay scrollbars import os os.environ['LIBOVERLAY_SCROLLBAR'] = '0' import sys from PyQt5.QtWidgets import QApplication from pugdebug.pugdebug import Pugdebug if __name__ == "__main__": app = QApplication(sys.argv) pugdebug = Pugdebug() pugdebug.run() app.exit(app.exec_())
def on_close(self): self.hide() if self.is_top_level: QApplication.exit(0)
def __init__(self, parent=None): QMenu.__init__(self, parent=None) action = QAction("Exit", self) action.triggered.connect(lambda : QApplication.exit(0)) self.addAction(action)
def exit(self): latus.logger.log.info('exit') self.hide() if self.sync: self.sync.request_exit() QApplication.exit() # todo: what should this parameter be?
def print_exc_and_exit(*exc_info): _log_exception( *exc_info ) logger.error("Exiting early due to an unhandled exception. See error output above.\n") QApplication.exit(1)
<!DOCTYPE html> <html> <head> <style> p.error { color: red; } </style> </head> <body> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <p class="error">I am different.</p> <p>This is a paragraph.</p> <p class="error">I am different too.</p> </body> </html> """ web = QWebView() web.setHtml(html) printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName("./provaacazzo.pdf") web.print_(printer) app.exit()
def on_close(self): self.hide() QApplication.exit(0)