def main(): about = KAboutData( b'synaptiks', '', ki18n('synaptiks'), str(synaptiks.__version__), ki18n('touchpad management and configuration application'), KAboutData.License_BSD, ki18n('Copyright (C) 2009, 2010 Sebastian Wiesner')) about.addAuthor(ki18n('Sebastian Wiesner'), ki18n('Maintainer'), '*****@*****.**') about.addCredit( ki18n('Valentyn Pavliuchenko'), ki18n('Debian packaging, russian translation, ' 'bug reporting and testing'), '*****@*****.**') about.setHomepage('http://synaptiks.lunaryorn.de/') about.setOrganizationDomain('synaptiks.lunaryorn.de') KCmdLineArgs.init(sys.argv, about) app = KApplication() window = KMainWindow() touchpad = Touchpad.find_first(Display.from_qt()) config = TouchpadConfiguration(touchpad) config_widget = TouchpadConfigurationWidget(config) config_widget.configurationChanged.connect( partial(print, 'config changed?')) window.setCentralWidget(config_widget) window.show() app.exec_()
def main(): app_name = "danbooru_client" catalog = "danbooru_client" program_name = ki18n("Danbooru Client") version = "1.0.0" description = ki18n("A client for Danbooru sites.") license = KAboutData.License_GPL copyright = ki18n("(C) 2009 Luca Beltrame") text = ki18n("Danbooru Client is a program to" " access Danbooru image boards.") home_page = u"http://www.dennogumi.org" bug_email = "*****@*****.**" about_data = KAboutData(app_name, catalog, program_name, version, description, license, copyright, text, home_page, bug_email) about_data.setProgramIconName("internet-web-browser") component_data = KComponentData(about_data) component_data.setAboutData(about_data) KCmdLineArgs.init(sys.argv, about_data) app = KApplication() window = mainwindow.MainWindow() window.show() app.exec_()
def main(): app_name="danbooru_client" catalog = "danbooru_client" program_name = ki18n("Danbooru Client") version = "1.0.0" description = ki18n("A client for Danbooru sites.") license = KAboutData.License_GPL copyright = ki18n("(C) 2009 Luca Beltrame") text = ki18n("Danbooru Client is a program to" " access Danbooru image boards.") home_page = u"http://www.dennogumi.org" bug_email = "*****@*****.**" about_data = KAboutData(app_name, catalog, program_name, version, description, license, copyright, text, home_page, bug_email) about_data.setProgramIconName("internet-web-browser") component_data = KComponentData(about_data) component_data.setAboutData(about_data) KCmdLineArgs.init(sys.argv, about_data) app = KApplication() window = mainwindow.MainWindow() window.show() app.exec_()
def main(): about = KAboutData( b'synaptiks', '', ki18n('synaptiks'), str(synaptiks.__version__), ki18n('touchpad management and configuration application'), KAboutData.License_BSD, ki18n('Copyright (C) 2009, 2010 Sebastian Wiesner')) about.addAuthor(ki18n('Sebastian Wiesner'), ki18n('Maintainer'), '*****@*****.**') about.addCredit(ki18n('Valentyn Pavliuchenko'), ki18n('Debian packaging, russian translation, ' 'bug reporting and testing'), '*****@*****.**') about.setHomepage('http://synaptiks.lunaryorn.de/') about.setOrganizationDomain('synaptiks.lunaryorn.de') KCmdLineArgs.init(sys.argv, about) app = KApplication() window = KMainWindow() touchpad = Touchpad.find_first(Display.from_qt()) config = TouchpadConfiguration(touchpad) config_widget = TouchpadConfigurationWidget(config) config_widget.configurationChanged.connect( partial(print, 'config changed?')) window.setCentralWidget(config_widget) window.show() app.exec_()
def main(): app_name = "vlc_snapper" catalog = "danbooru_client" program_name = ki18n("KDE VLC Snapper") version = "0.1" description = ki18n("A screenshot taker for video clips.") license = KAboutData.License_GPL copyright = ki18n("(C) 2011 Luca Beltrame") text = ki18n("") home_page = "http://www.dennogumi.org" bug_email = "*****@*****.**" about_data = KAboutData(app_name, catalog, program_name, version, description, license, copyright, text, home_page, bug_email) about_data.setProgramIconName("internet-web-browser") KCmdLineArgs.init(sys.argv, about_data) app = KApplication() dialog = capturewidget.CaptureDialog() dialog.show() app.lastWindowClosed.connect(dialog.deleteLater) app.exec_()
def main(): app_name = "vlc_snapper" catalog = "danbooru_client" program_name = ki18n("KDE VLC Snapper") version = "0.1" description = ki18n("A screenshot taker for video clips.") license = KAboutData.License_GPL copyright = ki18n("(C) 2011 Luca Beltrame") text = ki18n("") home_page = "http://www.dennogumi.org" bug_email = "*****@*****.**" about_data = KAboutData( app_name, catalog, program_name, version, description, license, copyright, text, home_page, bug_email ) about_data.setProgramIconName("internet-web-browser") KCmdLineArgs.init(sys.argv, about_data) app = KApplication() dialog = capturewidget.CaptureDialog() dialog.show() app.lastWindowClosed.connect(dialog.deleteLater) app.exec_()
def main (): appName = "KMainWindow" catalog = "" programName = ki18n ("KMainWindow") version = "1.0" description = ki18n ("Tutorial - Second Program") license = KAboutData.License_GPL copyright = ki18n ("(c) 2007 Jim Bublitz") text = ki18n ("none") homePage = "www.riverbankcomputing.com" bugEmail = "*****@*****.**" aboutData = KAboutData (appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) KCmdLineArgs.init (sys.argv, aboutData) app = KApplication () #------- new stuff added here ---------- mainWindow = MainWindow () mainWindow.show () app.exec_ ()
def start(): appName = Config.appname catalog = Config.catalog programName = ki18n(Config.readable_appname) version = Config.version description = ki18n("A tablet annotation and journaling application.") license = KAboutData.License_BSD copyright = ki18n("(C) 2009 Dominik Schacht") text = ki18n("Whee, greetings.") homepage = Config.homepage bugemail = "*****@*****.**" aboutData = KAboutData(appName, catalog, programName, version, description, license, copyright, text, homepage, bugemail) KCmdLineArgs.init(sys.argv, aboutData) KCmdLineArgs.addCmdLineOptions(Config.get_param_options()) app = KApplication() Config.init_config() # Init after the KApplication has been created. mw = MainWindow() mw.show() result = app.exec_() return result
def main(): global app, aboutData import setproctitle setproctitle.setproctitle("iosshy") from PyQt4.QtCore import QCoreApplication, QTranslator, QLocale, QSettings from PyQt4.QtGui import QApplication, QSystemTrayIcon, QImage from tunneldialog import TunnelDialog try: from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs from PyKDE4.kdeui import KApplication, KIcon aboutData = KAboutData( name, #appName name, #catalogName ki18n(name), #programName version, ki18n(description), #shortDescription KAboutData.License_BSD, #licenseKey ki18n("© 2010 Massimiliano Torromeo"), #copyrightStatement ki18n(""), #text url #homePageAddress ) aboutData.setBugAddress("http://github.com/mtorromeo/iosshy/issues") aboutData.addAuthor( ki18n("Massimiliano Torromeo"), #name ki18n("Main developer"), #task "*****@*****.**" #email ) aboutData.setProgramLogo(QImage(":icons/network-server.png")) KCmdLineArgs.init(sys.argv, aboutData) app = KApplication() app.setWindowIcon(KIcon("network-server")) if app.isSessionRestored(): sys.exit(0) except ImportError: app = QApplication(sys.argv) app.setOrganizationName("MTSoft") app.setApplicationName(name) if QSystemTrayIcon.isSystemTrayAvailable(): translator = QTranslator() qmFile = "tunneller_%s.qm" % QLocale.system().name() if os.path.isfile(qmFile): translator.load(qmFile) app.installTranslator(translator) dialog = TunnelDialog() sys.exit(app.exec_()) else: print "System tray not available. Exiting." sys.exit(1)
def main(): appName = "KMainWindow" catalog = "" programName = ki18n("KMainWindow") version = "1.0" description = ki18n("Tutorial - Second Program") license = KAboutData.License_GPL copyright = ki18n("(c) 2007 Jim Bublitz") text = ki18n("none") homePage = "www.riverbankcomputing.com" bugEmail = "*****@*****.**" aboutData = KAboutData(appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) KCmdLineArgs.init(sys.argv, aboutData) app = KApplication() #------- new stuff added here ---------- mainWindow = MainWindow() mainWindow.show() app.exec_()
def main(): """Creates an application from the cmd line args and starts a editor window""" KCmdLineArgs.init(sys.argv, ABOUT) opts = KCmdLineOptions() opts.add('+[file]', ki18n('File to open')) KCmdLineArgs.addCmdLineOptions(opts) args = KCmdLineArgs.parsedArgs() urls = [args.url(i) for i in range(args.count())] #wurgs app = KApplication() #KGlobal.locale().setLanguage(['de']) TODO win = Markdowner(urls) win.show() sys.exit(app.exec_())
class Frontend(BaseFrontend): def __init__(self): BaseFrontend.__init__(self) self.previous_excepthook = sys.excepthook sys.excepthook = self.excepthook self.debconf_callbacks = {} self.language_questions = ('oem_config', 'language_label', 'language_heading_label', 'timezone_heading_label', 'keyboard_heading_label', 'user_heading_label', 'back', 'next') self.current_step = None # Set default language. dbfilter = language.Language(self, self.debconf_communicator()) dbfilter.cleanup() dbfilter.db.shutdown() self.allowed_change_step = True self.allowed_go_forward = True self.mainLoopRunning = False self.apply_changes = False appName = "oem-config" catalog = "" programName = ki18n("OEM Config") version = "1.0" description = ki18n("Sets up the system") license = KAboutData.License_GPL copyright = ki18n("2006, 2007 Anirudh Ramesh. 2008 Canonical Ltd.") text = ki18n("none") homePage = "http://www.kubuntu.org" bugEmail = "" aboutData = KAboutData(appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) KCmdLineArgs.init(['oem-config', '-style=oxygen'], aboutData) self.app = KApplication() # We want to hide the minimise button if running in the ubiquity-only mode (no desktop) # To achieve this we need to set window flags to Dialog but we also need a parent widget which is showing # else Qt tried to be clever and puts the minimise button back self.parentWidget = QWidget() self.parentWidget.show() # The parent for our actual user interface window, this is needed only because Oxygen widget # style refuses to draw our background on a top level widget self.parent2 = QWidget(self.parentWidget) self.parent2.setAutoFillBackground(True) self.parent2.setWindowState(Qt.WindowFullScreen) self.parent2.setWindowFlags(Qt.Dialog) layout = QVBoxLayout(self.parent2) layout.setContentsMargins(0, 0, 0, 0) self.userinterface = OEMConfUI(self.parent2) self.userinterface.setFrontend(self) layout.addWidget(self.userinterface) self.parent2.show() self.userinterface.next.setIcon(KIcon("go-next")) self.userinterface.back.setIcon(KIcon("go-previous")) self.translate_widgets() self.customize_installer() self.tzmap = TimezoneMap(self) map_vbox = QVBoxLayout(self.userinterface.map_frame) map_vbox.setMargin(0) map_vbox.addWidget(self.tzmap) def excepthook(self, exctype, excvalue, exctb): """Crash handler.""" if (issubclass(exctype, KeyboardInterrupt) or issubclass(exctype, SystemExit)): return self.post_mortem(exctype, excvalue, exctb) self.previous_excepthook(exctype, excvalue, exctb) def run(self): if os.getuid() != 0: title = ('This installer must be run with administrative ' 'privileges, and cannot continue without them.') result = QMessageBox.critical(self.userinterface, "Must be root", title) sys.exit(1) self.userinterface.setCursor(QCursor(Qt.ArrowCursor)) #Signals and Slots self.app.connect(self.userinterface.next,SIGNAL("clicked()"),self.on_next_clicked) self.app.connect(self.userinterface.back,SIGNAL("clicked()"),self.on_back_clicked) self.app.connect(self.userinterface.language_list, SIGNAL("itemSelectionChanged()"), self.on_language_treeview_selection_changed) self.app.connect(self.userinterface.keyboard_list_1, SIGNAL("itemSelectionChanged()"), self.on_keyboard_layout_selected) self.app.connect(self.userinterface.keyboard_list_2, SIGNAL("itemSelectionChanged()"), self.on_keyboard_variant_selected) first_step = "step_language" self.userinterface.stackedWidget.setCurrentWidget(self.userinterface.step_language) self.current_step = self.get_current_step() self.set_current_page() while self.current_step is not None: self.backup = False self.current_step = self.get_current_step() if self.current_step == 'step_language': self.dbfilter = language.Language(self) elif self.current_step == 'step_keyboard': self.dbfilter = console_setup.ConsoleSetup(self) elif self.current_step == 'step_timezone': self.dbfilter = timezone.Timezone(self) elif self.current_step == 'step_user': self.dbfilter = user.User(self) else: raise ValueError, "step %s not recognised" % self.current_step self.allow_change_step(False) self.dbfilter.start(auto_process=True) self.app.exec_() self.app.processEvents() curr = str(self.get_current_step()) if self.backup: pass elif self.current_step == 'step_user': self.allow_change_step(False) self.current_step = None self.apply_changes = True else: if self.current_step == 'step_language': self.translate_widgets() self.userinterface.stackedWidget.setCurrentIndex(self.pages.index(curr) + 1) self.set_current_page() self.app.processEvents() if self.apply_changes: dbfilter = language_apply.LanguageApply(self) dbfilter.run_command(auto_process=True) dbfilter = timezone_apply.TimezoneApply(self) dbfilter.run_command(auto_process=True) dbfilter = console_setup_apply.ConsoleSetupApply(self) dbfilter.run_command(auto_process=True) return 0 else: return 10 def customize_installer(self): self.step_icon_size = QSize(32,32) self.step_icons = [self.userinterface.step_icon_lang, self.userinterface.step_icon_loc, \ self.userinterface.step_icon_key, self.userinterface.step_icon_user] self.step_labels = [self.userinterface.language_heading_label, self.userinterface.timezone_heading_label, \ self.userinterface.keyboard_heading_label, self.userinterface.user_heading_label] if QFile.exists("../../../usr/lib/kde4/share/icons/oxygen/32x32/apps/preferences-desktop-locale.png"): self.step_icons_path_prefix = "../../../usr/lib/kde4/share/icons/oxygen/32x32/apps/" self.step_icons_path = ["preferences-desktop-locale.png", "preferences-system-time.png", "preferences-desktop-keyboard.png", "system-users.png"] else: self.step_icons_path_prefix = "../../../usr/share/icons/default.kde/32x32/apps/" self.step_icons_path = ["locale.png", "clock.png", "keyboard_layout.png", "userconfig.png"] self.step_labels_text = [self.userinterface.language_heading_label.text(),self.userinterface.timezone_heading_label.text(), \ self.userinterface.keyboard_heading_label.text(), self.userinterface.user_heading_label.text()] for icon in range(len(self.pages)): self.step_icons[icon].setPixmap(QPixmap(str(self.step_icons_path_prefix+self.step_icons_path[icon]))) # Internationalisation. def translate_widgets(self, parentWidget=None): if self.locale is None: languages = [] else: languages = [self.locale] core_names = ['oem-config/text/%s' % q for q in self.language_questions] for stock_item in ('go-back', 'go-forward'): core_names.append('oem-config/imported/%s' % stock_item) i18n.get_translations(languages=languages, core_names=core_names) self.translate_widget_children(parentWidget) def translate_widget_children(self, parentWidget=None): if parentWidget is None: parentWidget = self.userinterface self.translate_widget(parentWidget, self.locale) if parentWidget.children() is not None: for widget in parentWidget.children(): self.translate_widget_children(widget) def translate_widget(self, widget, lang): if not isinstance(widget, QWidget): return name = widget.objectName() text = self.get_string(name, lang) if str(name) == 'language_label': text = self.get_string('language_heading_label', lang) if str(name) == 'next': text = self.get_string('oem-config/imported/go-forward', lang) if str(name) == 'back': text = self.get_string('oem-config/imported/go-back', lang) if str(name) == "SysConf": text = self.get_string("oem_config", lang) if text is None: return if isinstance(widget, QLabel): if 'heading_label' in name: widget.setText("""<html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"> <span style=" font-size:13pt; color:gray;">""" + text + "</span></p></body></html>") elif 'extra_label' in name: widget.setText("""<html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:italic;">""" + text + "</span></p></body></html>") else: widget.setText(text) elif isinstance(widget, QPushButton): widget.setText(text.replace('_', '&', 1)) elif isinstance(widget, QWidget) and str(name) == "SysConf": widget.setWindowTitle(text) else: print "WARNING: unknown widget: " + name def on_keyboard_layout_selected(self): if isinstance(self.dbfilter, console_setup.ConsoleSetup): layout = self.get_keyboard() if layout is not None: self.current_layout = layout self.dbfilter.change_layout(layout) def on_keyboard_variant_selected(self): if isinstance(self.dbfilter, console_setup.ConsoleSetup): layout = self.get_keyboard() variant = self.get_keyboard_variant() if layout is not None and variant is not None: self.dbfilter.apply_keyboard(layout, variant) def selected_language(self): selection = self.userinterface.language_list.selectedItems() if len(selection) == 1: value = unicode(selection[0].text()) return self.language_choice_map[value][1] else: return '' def set_language_choices(self, choices, choice_map): BaseFrontend.set_language_choices(self, choices, choice_map) self.userinterface.language_list.clear() self.lang_store = QStringList() for choice in choices: self.lang_store.append(QString(choice)) self.userinterface.language_list.addItems(self.lang_store) def set_language(self, language): index = self.lang_store.indexOf(QRegExp("^"+language+"$")) if index != -1: self.userinterface.language_list.setCurrentRow(index) def get_language(self): value = unicode(self.userinterface.language_list.currentItem().text()) return self.language_choice_map[value][1] def on_language_treeview_selection_changed(self): lang = self.selected_language() if lang: # strip encoding; we use UTF-8 internally no matter what lang = lang.split('.')[0].lower() for widget in (self.userinterface, self.userinterface.language_label, self.userinterface.welcome_label, self.userinterface.back, self.userinterface.next): self.translate_widget(widget, lang) for step in range(len(self.pages)): self.translate_widget(self.step_labels[step], lang) self.step_labels_text[step] = self.step_labels[step].text() def set_timezone (self, timezone): self.tzmap.set_tz_from_name(timezone) def get_timezone (self): return self.tzmap.get_selected_tz_name() def set_keyboard_choices(self, choices): self.userinterface.keyboard_list_1.clear() self.key_store_1 = QStringList() for choice in sorted(choices): self.key_store_1.append(QString(choice)) self.userinterface.keyboard_list_1.addItems(self.key_store_1) if self.current_layout is not None: self.set_keyboard(self.current_layout) def set_keyboard(self, layout): BaseFrontend.set_keyboard(self, layout) index = self.key_store_1.indexOf(QRegExp("^"+layout+"$")) if index != -1: self.userinterface.keyboard_list_1.setCurrentRow(index) def get_keyboard(self): return unicode(self.userinterface.keyboard_list_1.currentItem().text()) def set_keyboard_variant_choices(self, choices): self.userinterface.keyboard_list_2.clear() self.key_store_2 = QStringList() for choice in sorted(choices): self.key_store_2.append(QString(choice)) self.userinterface.keyboard_list_2.addItems(self.key_store_2) def set_keyboard_variant(self, variant): index = self.key_store_2.indexOf(QRegExp("^"+variant+"$")) if index != -1: self.userinterface.keyboard_list_2.setCurrentRow(index) def get_keyboard_variant(self): return unicode(self.userinterface.keyboard_list_2.currentItem().text()) def set_timezone (self, timezone): self.tzmap.set_timezone(timezone) def get_timezone (self): return self.tzmap.get_timezone() def set_fullname(self, value): self.userinterface.name_ledit.setText(value) def get_fullname(self): return unicode(self.userinterface.name_ledit.text()) def set_username(self, value): self.userinterface.uname_ledit.setText(value) def get_username(self): return unicode(self.userinterface.uname_ledit.text()) def get_password(self): return unicode(self.userinterface.pass_ledit_1.text()) def get_verified_password(self): return unicode(self.userinterface.pass_ledit_2.text()) def get_auto_login(self): return False def watch_debconf_fd (self, from_debconf, process_input): self.debconf_fd_counter = 0 self.socketNotifierRead = QSocketNotifier(from_debconf, QSocketNotifier.Read, self.app) self.app.connect(self.socketNotifierRead, SIGNAL("activated(int)"), self.watch_debconf_fd_helper_read) self.socketNotifierWrite = QSocketNotifier(from_debconf, QSocketNotifier.Write, self.app) self.app.connect(self.socketNotifierWrite, SIGNAL("activated(int)"), self.watch_debconf_fd_helper_write) self.socketNotifierException = QSocketNotifier(from_debconf, QSocketNotifier.Exception, self.app) self.app.connect(self.socketNotifierException, SIGNAL("activated(int)"), self.watch_debconf_fd_helper_exception) self.debconf_callbacks[from_debconf] = process_input self.current_debconf_fd = from_debconf def watch_debconf_fd_helper_read (self, source): self.debconf_fd_counter += 1 debconf_condition = 0 debconf_condition |= filteredcommand.DEBCONF_IO_IN self.debconf_callbacks[source](source, debconf_condition) def watch_debconf_fd_helper_write(self, source): debconf_condition = 0 debconf_condition |= filteredcommand.DEBCONF_IO_OUT self.debconf_callbacks[source](source, debconf_condition) def watch_debconf_fd_helper_exception(self, source): debconf_condition = 0 debconf_condition |= filteredcommand.DEBCONF_IO_ERR self.debconf_callbacks[source](source, debconf_condition) def debconffilter_done (self, dbfilter): ##FIXME in Qt 4 without this disconnect it calls watch_debconf_fd_helper_read once more causing ## a crash after the keyboard stage. No idea why. self.app.disconnect(self.socketNotifierRead, SIGNAL("activated(int)"), self.watch_debconf_fd_helper_read) # TODO cjwatson 2006-02-10: handle dbfilter.status self.app.disconnect(self.socketNotifierWrite, SIGNAL("activated(int)"), self.watch_debconf_fd_helper_write) self.app.disconnect(self.socketNotifierException, SIGNAL("activated(int)"), self.watch_debconf_fd_helper_exception) if BaseFrontend.debconffilter_done(self, dbfilter): self.app.exit() def error_dialog (self, title, msg): self.allow_change_step(True) # TODO: cancel button as well if capb backup QMessageBox.warning(self.userinterface, title, msg, QMessageBox.Ok) def question_dialog (self, title, msg, options, use_templates=True): # I doubt we'll ever need more than three buttons. assert len(options) <= 3, options self.allow_change_step(True) buttons = {} messageBox = QMessageBox(QMessageBox.Question, title, msg, QMessageBox.NoButton, self.userinterface) for option in options: if use_templates: text = self.get_string(option) else: text = option if text is None: text = option # Convention for options is to have the affirmative action last; KDE # convention is to have it first. if option == options[-1]: button = messageBox.addButton(text, QMessageBox.AcceptRole) else: button = messageBox.addButton(text, QMessageBox.RejectRole) buttons[button] = option response = messageBox.exec_() if response < 0: return None else: return buttons[messageBox.clickedButton()] def run_main_loop (self): if not self.apply_changes: self.allow_change_step(True) #self.app.exec_() ##FIXME Qt 4 won't allow nested main loops, here it just returns directly self.mainLoopRunning = True while self.mainLoopRunning: # nasty, but works OK self.app.processEvents() def quit_main_loop (self): self.mainLoopRunning = False def on_back_clicked(self): curr = str(self.get_current_step()) self.backup = True if self.dbfilter is not None: self.userinterface.stackedWidget.setCurrentIndex(self.pages.index(curr) - 1) self.allow_change_step(False) self.dbfilter.cancel_handler() self.set_current_page() # expect recursive main loops to be exited and # debconffilter_done() to be called when the filter exits def on_next_clicked(self): if self.dbfilter is not None: self.allow_change_step(False) self.dbfilter.ok_handler() def set_current_page(self): current_name = self.get_current_step() current_page = self.pages.index(str(current_name)) if current_name == 'step_language': self.userinterface.back.hide() else: self.userinterface.back.show() if current_name == 'step_user': #FIXME needs i18n(Finish) self.userinterface.next.setIcon(KIcon("dialog-ok")) else: self.userinterface.next.setIcon(KIcon("go-next")) for icon in self.step_icons: pixmap = QIcon(icon.pixmap()).pixmap(self.step_icon_size, QIcon.Disabled) icon.setPixmap(pixmap) for step in range(len(self.pages)): self.step_labels_text[step].replace("p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> <span style=\" font-size:13pt; font-weight:800; font-style:italic;\">","<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> <span style=\" font-size:13pt; color:gray;\">") self.step_labels[step].setText(self.step_labels_text[step]) current_icon = self.step_icons[current_page] current_pixmap = QPixmap(str(self.step_icons_path_prefix+self.step_icons_path[current_page])) current_icon.setPixmap(current_pixmap) current_label_text = self.step_labels_text[current_page] current_label_text.replace("<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> <span style=\" font-size:13pt; color:gray;\">","<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> <span style=\" font-size:13pt; font-weight:800; font-style:italic;\">") self.step_labels[current_page].setText(current_label_text) def allow_change_step(self, allowed): if allowed: cursor = QCursor(Qt.ArrowCursor) else: cursor = QCursor(Qt.WaitCursor) self.userinterface.setCursor(cursor) def allow_go_forward(self, allowed): self.userinterface.next.setEnabled(allowed and self.allowed_change_step) self.allowed_go_forward = allowed def get_current_step(self): return self.userinterface.stackedWidget.currentWidget().objectName()
self.setCentralWidget (MainFrame (self)) #-------------------- main ------------------------------------------------ appName = "default.py" catalog = "" programName = ki18n ("default") #ki18n required here version = "1.0" description = ki18n ("Default Example") #ki18n required here license = KAboutData.License_GPL copyright = ki18n ("(c) 2007 Jim Bublitz") #ki18n required here text = ki18n ("none") #ki18n required here homePage = "www.riverbankcomputing.com" bugEmail = "*****@*****.**" aboutData = KAboutData (appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) # ki18n required for first two addAuthor () arguments aboutData.addAuthor (ki18n ("Troy Melhase"), ki18n ("original concept")) aboutData.addAuthor (ki18n ("Jim Bublitz"), ki18n ("pykdedocs")) KCmdLineArgs.init (sys.argv, aboutData) app = KApplication () mainWindow = MainWin (None, "main window") mainWindow.show() app.connect (app, SIGNAL ("lastWindowClosed ()"), app.quit) app.exec_ ()
class Application: """ Main application class; starting and stopping of the application is controlled from here, together with some interactions from the tray icon. """ def __init__(self): aboutData = KAboutData(APP_NAME, CATALOG, PROGRAM_NAME, VERSION, DESCRIPTION, LICENSE, COPYRIGHT, TEXT, HOMEPAGE, BUG_EMAIL) aboutData.addAuthor(ki18n("GuoCi"), ki18n("Python 3 port maintainer"), "*****@*****.**", "") aboutData.addAuthor(ki18n("Chris Dekter"), ki18n("Developer"), "*****@*****.**", "") aboutData.addAuthor(ki18n("Sam Peterson"), ki18n("Original developer"), "*****@*****.**", "") aboutData.setProgramIconName(common.ICON_FILE) self.aboutData = aboutData KCmdLineArgs.init(sys.argv, aboutData) options = KCmdLineOptions() options.add("l").add("verbose", ki18n("Enable verbose logging")) options.add("c").add("configure", ki18n("Show the configuration window on startup")) KCmdLineArgs.addCmdLineOptions(options) args = KCmdLineArgs.parsedArgs() self.app = KApplication() try: # Create configuration directory if not os.path.exists(CONFIG_DIR): os.makedirs(CONFIG_DIR) # Initialise logger rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) if args.isSet("verbose"): handler = logging.StreamHandler(sys.stdout) else: handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=MAX_LOG_SIZE, backupCount=MAX_LOG_COUNT) handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter(LOG_FORMAT)) rootLogger.addHandler(handler) if self.__verifyNotRunning(): self.__createLockFile() self.initialise(args.isSet("configure")) except Exception as e: self.show_error_dialog(i18n("Fatal error starting AutoKey.\n") + str(e)) logging.exception("Fatal error starting AutoKey: " + str(e)) sys.exit(1) def __createLockFile(self): f = open(LOCK_FILE, 'w') f.write(str(os.getpid())) f.close() def __verifyNotRunning(self): if os.path.exists(LOCK_FILE): f = open(LOCK_FILE, 'r') pid = f.read() f.close() # Check that the found PID is running and is autokey with subprocess.Popen(["ps", "-p", pid, "-o", "command"], stdout=subprocess.PIPE) as p: output = p.communicate()[0].decode() if "autokey" in output: logging.debug("AutoKey is already running as pid %s", pid) bus = dbus.SessionBus() try: dbusService = bus.get_object("org.autokey.Service", "/AppService") dbusService.show_configure(dbus_interface = "org.autokey.Service") sys.exit(0) except dbus.DBusException as e: logging.exception("Error communicating with Dbus service") self.show_error_dialog(i18n("AutoKey is already running as pid %1 but is not responding", pid), str(e)) sys.exit(1) return True def main(self): self.app.exec_() def initialise(self, configure): logging.info("Initialising application") self.monitor = monitor.FileMonitor(self) self.configManager = get_config_manager(self) self.service = service.Service(self) self.serviceDisabled = False # Initialise user code dir if self.configManager.userCodeDir is not None: sys.path.append(self.configManager.userCodeDir) try: self.service.start() except Exception as e: logging.exception("Error starting interface: " + str(e)) self.serviceDisabled = True self.show_error_dialog(i18n("Error starting interface. Keyboard monitoring will be disabled.\n" + "Check your system/configuration."), str(e)) self.notifier = Notifier(self) self.configWindow = None self.monitor.start() dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True) self.dbusService = common.AppService(self) if ConfigManager.SETTINGS[IS_FIRST_RUN] or configure: ConfigManager.SETTINGS[IS_FIRST_RUN] = False self.show_configure() self.handler = CallbackEventHandler() kbChangeFilter = KeyboardChangeFilter(self.service.mediator.interface) self.app.installEventFilter(kbChangeFilter) def init_global_hotkeys(self, configManager): logging.info("Initialise global hotkeys") configManager.toggleServiceHotkey.set_closure(self.toggle_service) configManager.configHotkey.set_closure(self.show_configure_async) def config_altered(self, persistGlobal): self.configManager.config_altered(persistGlobal) self.notifier.build_menu() def hotkey_created(self, item): logging.debug("Created hotkey: %r %s", item.modifiers, item.hotKey) self.service.mediator.interface.grab_hotkey(item) def hotkey_removed(self, item): logging.debug("Removed hotkey: %r %s", item.modifiers, item.hotKey) self.service.mediator.interface.ungrab_hotkey(item) def path_created_or_modified(self, path): time.sleep(0.5) changed = self.configManager.path_created_or_modified(path) if changed and self.configWindow is not None: self.configWindow.config_modified() def path_removed(self, path): time.sleep(0.5) changed = self.configManager.path_removed(path) if changed and self.configWindow is not None: self.configWindow.config_modified() def unpause_service(self): """ Unpause the expansion service (start responding to keyboard and mouse events). """ self.service.unpause() self.notifier.update_tool_tip() def pause_service(self): """ Pause the expansion service (stop responding to keyboard and mouse events). """ self.service.pause() self.notifier.update_tool_tip() def toggle_service(self): """ Convenience method for toggling the expansion service on or off. """ if self.service.is_running(): self.pause_service() else: self.unpause_service() def shutdown(self): """ Shut down the entire application. """ logging.info("Shutting down") self.app.closeAllWindows() self.notifier.hide_icon() self.service.shutdown() self.monitor.stop() self.app.quit() os.remove(LOCK_FILE) logging.debug("All shutdown tasks complete... quitting") def notify_error(self, message): """ Show an error notification popup. @param message: Message to show in the popup """ self.exec_in_main(self.notifier.notify_error, message) def update_notifier_visibility(self): self.notifier.update_visible_status() def show_configure(self): """ Show the configuration window, or deiconify (un-minimise) it if it's already open. """ logging.info("Displaying configuration window") try: self.configWindow.showNormal() self.configWindow.activateWindow() except (AttributeError, RuntimeError): # AttributeError when the main window is shown the first time, RuntimeError subsequently. self.configWindow = ConfigWindow(self) self.configWindow.show() def show_configure_async(self): self.exec_in_main(self.show_configure) def show_error_dialog(self, message, details=None): """ Convenience method for showing an error dialog. """ if details is None: KMessageBox.error(None, message) else: KMessageBox.detailedError(None, message, details) def show_script_error(self): """ Show the last script error (if any) """ if self.service.scriptRunner.error != '': KMessageBox.information(None, self.service.scriptRunner.error, i18n("View Script Error Details")) self.service.scriptRunner.error = '' else: KMessageBox.information(None, i18n("No error information available"), i18n("View Script Error Details")) def show_popup_menu(self, folders=[], items=[], onDesktop=True, title=None): self.exec_in_main(self.__createMenu, folders, items, onDesktop, title) def hide_menu(self): self.exec_in_main(self.menu.hide) def __createMenu(self, folders, items, onDesktop, title): self.menu = PopupMenu(self.service, folders, items, onDesktop, title) self.menu.popup(QCursor.pos()) self.menu.setFocus() def exec_in_main(self, callback, *args): self.handler.postEventWithCallback(callback, *args)
class Magneto(MagnetoCore): """ Magneto Updates Notification Applet class. """ def __init__(self): app_name = "magneto" catalog = "" prog_name = ki18n("Magneto") version = "1.0" description = ki18n("System Update Status") lic = KAboutData.License_GPL cright = ki18n("(c) 2013 Fabio Erculiani") text = ki18n("none") home_page = "www.sabayon.org" bug_mail = "*****@*****.**" self._kabout = KAboutData(app_name, catalog, prog_name, version, description, lic, cright, text, home_page, bug_mail) argv = [sys.argv[0]] KCmdLineArgs.init(argv, self._kabout) self._app = KApplication() from dbus.mainloop.qt import DBusQtMainLoop super(Magneto, self).__init__(main_loop_class=DBusQtMainLoop) self._window = KStatusNotifierItem() # do not show "Quit" and use quitSelected() signal self._window.setStandardActionsEnabled(False) icon_name = self.icons.get("okay") self._window.setIconByName(icon_name) self._window.setStatus(KStatusNotifierItem.Passive) self._window.connect(self._window, SIGNAL("activateRequested(bool,QPoint)"), self.applet_activated) self._menu = KMenu(_("Magneto Entropy Updates Applet")) self._window.setContextMenu(self._menu) self._menu_items = {} for item in self._menu_item_list: if item is None: self._menu.addSeparator() continue myid, _unused, mytxt, myslot_func = item name = self.get_menu_image(myid) action_icon = KIcon(name) w = KAction(action_icon, mytxt, self._menu) self._menu_items[myid] = w self._window.connect(w, SIGNAL("triggered()"), myslot_func) self._menu.addAction(w) self._menu.hide() def _first_check(self): def _do_check(): self.send_check_updates_signal(startup_check=True) return False if self._dbus_service_available: QTimer.singleShot(10000, _do_check) def startup(self): """ Start user interface. """ self._dbus_service_available = self.setup_dbus() if config.settings["APPLET_ENABLED"] and \ self._dbus_service_available: self.enable_applet(do_check=False) else: self.disable_applet() if not self._dbus_service_available: QTimer.singleShot(30000, self.show_service_not_available) else: self._first_check() # Notice Window instance self._notice_window = AppletNoticeWindow(self) # Enter main loop self._app.exec_() def close_service(self): super(Magneto, self).close_service() self._app.quit() def change_icon(self, icon_name): name = self.icons.get(icon_name) self._window.setIconByName(name) def disable_applet(self, *args): super(Magneto, self).disable_applet() self._menu_items["disable_applet"].setEnabled(False) self._menu_items["enable_applet"].setEnabled(True) def enable_applet(self, w=None, do_check=True): done = super(Magneto, self).enable_applet(do_check=do_check) if done: self._menu_items["disable_applet"].setEnabled(True) self._menu_items["enable_applet"].setEnabled(False) def show_alert(self, title, text, urgency=None, force=False, buttons=None): if ((title, text) == self.last_alert) and not force: return def _action_activate_cb(action_num): if not buttons: return try: action_info = buttons[action_num - 1] except IndexError: return _action_id, _button_name, button_callback = action_info button_callback() def do_show(): notification = KNotification("Updates") # Keep a reference or the callback of the actions added # below will never work. # See: https://bugzilla.redhat.com/show_bug.cgi?id=241531 self.__last_notification = notification notification.setFlags(KNotification.CloseOnTimeout) notification.setText("<b>%s</b><br/>%s" % ( title, text, )) if buttons: notification.setActions([x[1] for x in buttons]) notification.connect(notification, SIGNAL("activated(unsigned int)"), _action_activate_cb) icon_name = "okay" status = KStatusNotifierItem.Passive if urgency == "critical": icon_name = "critical" status = KStatusNotifierItem.Active name = self.icons.get(icon_name) icon = KIcon(name) self._window.setStatus(status) notification.setPixmap(icon.pixmap(48, 48)) notification.sendEvent() self.last_alert = (title, text) # thread safety QTimer.singleShot(0, do_show) def update_tooltip(self, tip): def do_update(): self._window.setToolTipTitle(tip) QTimer.singleShot(0, do_update) def applet_context_menu(self): """ No action for now. """ pass def applet_activated(self, active, pos): if active: self.applet_doubleclick() def hide_notice_window(self): self.notice_window_shown = False self._notice_window.hide() def show_notice_window(self): if self.notice_window_shown: return if not self.package_updates: return entropy_ver = None packages = [] for atom in self.package_updates: key = entropy.dep.dep_getkey(atom) avail_rev = entropy.dep.dep_get_entropy_revision(atom) avail_tag = entropy.dep.dep_gettag(atom) my_pkg = entropy.dep.remove_entropy_revision(atom) my_pkg = entropy.dep.remove_tag(my_pkg) pkgcat, pkgname, pkgver, pkgrev = entropy.dep.catpkgsplit(my_pkg) ver = pkgver if pkgrev != "r0": ver += "-%s" % (pkgrev, ) if avail_tag: ver += "#%s" % (avail_tag, ) if avail_rev: ver += "~%s" % (avail_tag, ) if key == "sys-apps/entropy": entropy_ver = ver packages.append("%s (%s)" % ( key, ver, )) critical_msg = "" if entropy_ver is not None: critical_msg = "%s <b>sys-apps/entropy</b> " "%s, %s <b>%s</b>. %s." % ( _("Your system currently has an outdated version of"), _("installed"), _("the latest available version is"), entropy_ver, _("It is recommended that you upgrade to " "the latest before updating any other packages")) self._notice_window.populate(packages, critical_msg) self._notice_window.show() self.notice_window_shown = True
class Application: """ Main application class; starting and stopping of the application is controlled from here, together with some interactions from the tray icon. """ def __init__(self): aboutData = KAboutData(APP_NAME, CATALOG, PROGRAM_NAME, VERSION, DESCRIPTION, LICENSE, COPYRIGHT, TEXT, HOMEPAGE, BUG_EMAIL) aboutData.addAuthor(ki18n("GuoCi"), ki18n("Python 3 port maintainer"), "*****@*****.**", "") aboutData.addAuthor(ki18n("Chris Dekter"), ki18n("Developer"), "*****@*****.**", "") aboutData.addAuthor(ki18n("Sam Peterson"), ki18n("Original developer"), "*****@*****.**", "") aboutData.setProgramIconName(common.ICON_FILE) self.aboutData = aboutData KCmdLineArgs.init(sys.argv, aboutData) options = KCmdLineOptions() options.add("l").add("verbose", ki18n("Enable verbose logging")) options.add("c").add("configure", ki18n("Show the configuration window on startup")) KCmdLineArgs.addCmdLineOptions(options) args = KCmdLineArgs.parsedArgs() self.app = KApplication() try: # Create configuration directory if not os.path.exists(CONFIG_DIR): os.makedirs(CONFIG_DIR) # Initialise logger rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) if args.isSet("verbose"): handler = logging.StreamHandler(sys.stdout) else: handler = logging.handlers.RotatingFileHandler( LOG_FILE, maxBytes=MAX_LOG_SIZE, backupCount=MAX_LOG_COUNT) handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter(LOG_FORMAT)) rootLogger.addHandler(handler) if self.__verifyNotRunning(): self.__createLockFile() self.initialise(args.isSet("configure")) except Exception as e: self.show_error_dialog( i18n("Fatal error starting AutoKey.\n") + str(e)) logging.exception("Fatal error starting AutoKey: " + str(e)) sys.exit(1) def __createLockFile(self): f = open(LOCK_FILE, 'w') f.write(str(os.getpid())) f.close() def __verifyNotRunning(self): if os.path.exists(LOCK_FILE): f = open(LOCK_FILE, 'r') pid = f.read() f.close() # Check that the found PID is running and is autokey with subprocess.Popen(["ps", "-p", pid, "-o", "command"], stdout=subprocess.PIPE) as p: output = p.communicate()[0].decode() if "autokey" in output: logging.debug("AutoKey is already running as pid %s", pid) bus = dbus.SessionBus() try: dbusService = bus.get_object("org.autokey.Service", "/AppService") dbusService.show_configure( dbus_interface="org.autokey.Service") sys.exit(0) except dbus.DBusException as e: logging.exception("Error communicating with Dbus service") self.show_error_dialog( i18n( "AutoKey is already running as pid %1 but is not responding", pid), str(e)) sys.exit(1) return True def main(self): self.app.exec_() def initialise(self, configure): logging.info("Initialising application") self.monitor = monitor.FileMonitor(self) self.configManager = get_config_manager(self) self.service = service.Service(self) self.serviceDisabled = False # Initialise user code dir if self.configManager.userCodeDir is not None: sys.path.append(self.configManager.userCodeDir) try: self.service.start() except Exception as e: logging.exception("Error starting interface: " + str(e)) self.serviceDisabled = True self.show_error_dialog( i18n( "Error starting interface. Keyboard monitoring will be disabled.\n" + "Check your system/configuration."), str(e)) self.notifier = Notifier(self) self.configWindow = None self.monitor.start() dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True) self.dbusService = common.AppService(self) if ConfigManager.SETTINGS[IS_FIRST_RUN] or configure: ConfigManager.SETTINGS[IS_FIRST_RUN] = False self.show_configure() self.handler = CallbackEventHandler() kbChangeFilter = KeyboardChangeFilter(self.service.mediator.interface) self.app.installEventFilter(kbChangeFilter) def init_global_hotkeys(self, configManager): logging.info("Initialise global hotkeys") configManager.toggleServiceHotkey.set_closure(self.toggle_service) configManager.configHotkey.set_closure(self.show_configure_async) def config_altered(self, persistGlobal): self.configManager.config_altered(persistGlobal) self.notifier.build_menu() def hotkey_created(self, item): logging.debug("Created hotkey: %r %s", item.modifiers, item.hotKey) self.service.mediator.interface.grab_hotkey(item) def hotkey_removed(self, item): logging.debug("Removed hotkey: %r %s", item.modifiers, item.hotKey) self.service.mediator.interface.ungrab_hotkey(item) def path_created_or_modified(self, path): time.sleep(0.5) changed = self.configManager.path_created_or_modified(path) if changed and self.configWindow is not None: self.configWindow.config_modified() def path_removed(self, path): time.sleep(0.5) changed = self.configManager.path_removed(path) if changed and self.configWindow is not None: self.configWindow.config_modified() def unpause_service(self): """ Unpause the expansion service (start responding to keyboard and mouse events). """ self.service.unpause() self.notifier.update_tool_tip() def pause_service(self): """ Pause the expansion service (stop responding to keyboard and mouse events). """ self.service.pause() self.notifier.update_tool_tip() def toggle_service(self): """ Convenience method for toggling the expansion service on or off. """ if self.service.is_running(): self.pause_service() else: self.unpause_service() def shutdown(self): """ Shut down the entire application. """ logging.info("Shutting down") self.app.closeAllWindows() self.notifier.hide_icon() self.service.shutdown() self.monitor.stop() self.app.quit() os.remove(LOCK_FILE) logging.debug("All shutdown tasks complete... quitting") def notify_error(self, message): """ Show an error notification popup. @param message: Message to show in the popup """ self.exec_in_main(self.notifier.notify_error, message) def update_notifier_visibility(self): self.notifier.update_visible_status() def show_configure(self): """ Show the configuration window, or deiconify (un-minimise) it if it's already open. """ logging.info("Displaying configuration window") try: self.configWindow.showNormal() self.configWindow.activateWindow() except (AttributeError, RuntimeError): # AttributeError when the main window is shown the first time, RuntimeError subsequently. self.configWindow = ConfigWindow(self) self.configWindow.show() def show_configure_async(self): self.exec_in_main(self.show_configure) def show_error_dialog(self, message, details=None): """ Convenience method for showing an error dialog. """ if details is None: KMessageBox.error(None, message) else: KMessageBox.detailedError(None, message, details) def show_script_error(self): """ Show the last script error (if any) """ if self.service.scriptRunner.error != '': KMessageBox.information(None, self.service.scriptRunner.error, i18n("View Script Error Details")) self.service.scriptRunner.error = '' else: KMessageBox.information(None, i18n("No error information available"), i18n("View Script Error Details")) def show_popup_menu(self, folders=[], items=[], onDesktop=True, title=None): self.exec_in_main(self.__createMenu, folders, items, onDesktop, title) def hide_menu(self): self.exec_in_main(self.menu.hide) def __createMenu(self, folders, items, onDesktop, title): self.menu = PopupMenu(self.service, folders, items, onDesktop, title) self.menu.popup(QCursor.pos()) self.menu.setFocus() def exec_in_main(self, callback, *args): self.handler.postEventWithCallback(callback, *args)
KMainWindow.__init__(self) self.resize(640, 480) label = QLabel("This is a simple PyKDE4 program", self) label.setGeometry(10, 10, 200, 20) #--------------- main ------------------ if __name__ == '__main__': appName = "KApplication" catalog = "" programName = ki18n("KApplication") version = "1.0" description = ki18n("KApplication/KMainWindow/KAboutData example") license = KAboutData.License_GPL copyright = ki18n("(c) 2007 Jim Bublitz") text = ki18n("none") homePage = "www.riverbankcomputing.com" bugEmail = "*****@*****.**" aboutData = KAboutData(appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) KCmdLineArgs.init(sys.argv, aboutData) app = KApplication() mainWindow = MainWindow() mainWindow.show() sys.exit(app.exec_())
class MainApp(DBusItem): """Our main application instance. Also exposes some methods to DBus. Instantiated only once. Emits four signals to Python others can connect to: activeChanged(Document) documentCreated(Document) documentMaterialized(Document) documentClosed(Document) """ activeChanged = Signal() documentCreated = Signal() documentMaterialized = Signal() documentClosed = Signal() iface = DBUS_IFACE_PREFIX + "MainApp" defaultEncoding = 'UTF-8' defaultMode = None fileTypes = [] def __init__(self, servicePrefix): # We manage our own documents. self.documents = [] self.history = [] # latest shown documents # KApplication needs to be instantiated before any D-Bus stuff self.kapp = KApplication() # Here we can setup config() stuff before MainWindow and its tools # are created. config = KGlobal.config().group("") # root group self.setupConfiguration(config) config.sync() # DBus init serviceName = "{0}{1}".format(servicePrefix, os.getpid()) DBusItem.__init__(self, serviceName, '/MainApp') # We support only one MainWindow. self.mainwin = self.createMainWindow() self.kapp.setTopWidget(self.mainwin) # Get our beloved editor :-) self.editor = KTextEditor.EditorChooser.editor() self.editor.readConfig() # restore session etc. self._sessionStartedFromCommandLine = False def setupConfiguration(self, config): """Opportunity to manipulate the root group of the global KConfig. This method is called after KApplication is created but before DBus init and Mainwindow creation. You can implement this method in a subclass; the default implementation does nothing. """ pass @cacheresult def stateManager(self): return StateManager(self) def defaultDirectory(self): return '' def createMainWindow(self): import kateshell.mainwindow return kateshell.mainwindow.MainWindow(self) def createDocument(self, url="", encoding=None): return Document(self, url, encoding) def findDocument(self, url): """ Return the opened document or False. """ if not isinstance(url, KUrl): url = KUrl(url) # we use string comparison, because sometimes percent encoding # issues make the same QUrls look different, esp when dragged # from KMail... url = url.toString() for d in self.documents: if d.url().toString() == url: return d return False @method(iface, in_signature='ss', out_signature='o') def openUrl(self, url, encoding=None): if not isinstance(url, KUrl): url = KUrl(url) # If no encoding given, set default or check if we can remember it if not encoding: encoding = self.defaultEncoding if self.keepMetaInfo() and not url.isEmpty(): group = self.stateManager().groupForUrl(url) if group: encoding = group.readEntry("encoding", "") # If there is only one document open and it is empty, nameless and # unmodified, use it. if (not url.isEmpty() and len(self.documents) == 1 and not self.documents[0].isModified() and self.documents[0].url().isEmpty()): d = self.documents[0] d.openUrl(url, encoding) else: d = (not url.isEmpty() and self.findDocument(url) or self.createDocument(url, encoding)) return d @method(iface, in_signature='', out_signature='o') def new(self): return self.createDocument() def run(self, sender=None): """ Last minute setup and enter the KDE event loop. At the very last, instantiates one empty doc if nothing loaded yet. """ if self.kapp.isSessionRestored(): self.mainwin.restore(1, False) elif (len(self.documents) == 0 and not self._sessionStartedFromCommandLine): # restore named session? action = config("preferences").readEntry("default session", "") if action == "lastused": self.mainwin.sessionManager().restoreLastSession() elif action == "custom": session = config("preferences").readEntry("custom session", "") if session in self.mainwin.sessionManager().names(): self.mainwin.sessionManager().switch(session) if len(self.documents) == 0: self.createDocument().setActive() sys.excepthook = self.handleException self.mainwin.show() self.kapp.exec_() KGlobal.config().sync() @method(iface, in_signature='s', out_signature='b') def isOpen(self, url): """Returns true if the specified URL is opened.""" if not isinstance(url, KUrl): url = KUrl(url) return bool(self.findDocument(url)) @method(iface, in_signature='', out_signature='o') def activeDocument(self): """Returns the currently active document.""" return self.history[-1] @method(iface, in_signature='', out_signature='') def back(self): """Sets the previous document active.""" i = self.documents.index(self.activeDocument()) - 1 self.documents[i].setActive() @method(iface, in_signature='', out_signature='') def forward(self): """Sets the next document active.""" i = self.documents.index(self.activeDocument()) + 1 i %= len(self.documents) self.documents[i].setActive() @method(iface, in_signature='', out_signature='b') def quit(self): """Quits the application. Returns True if succeeded.""" return self.mainwin.close() @method(iface, in_signature='', out_signature='') def show(self): """Raises our mainwindow if minimized.""" self.mainwin.setWindowState( self.mainwin.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) @method(iface, in_signature='s', out_signature='b') def startSession(self, session): """Switch to the given session. Use "none" to switch to the empty session. If the session does not exist, it is created on the fly. Returns True if the switch succeeded. """ self._sessionStartedFromCommandLine = True return self.mainwin.sessionManager().switch(session) @method(iface, in_signature='', out_signature='s') def currentSession(self): """Returns the name of the current session. Returns "none" if there is no active session. """ return self.mainwin.sessionManager().current() or "none" def addDocument(self, doc): """Internal. Called when a new Document is created.""" self.documents.append(doc) self.history.append(doc) self.documentCreated(doc) def removeDocument(self, doc): """Internal. Called when a Document is closed.""" if doc in self.documents: # Was this the active document? Then activate previous active doc. if doc is self.activeDocument() and len(self.documents) > 1: self.history[-2].setActive() self.documents.remove(doc) self.history.remove(doc) # Create empty document if last closed self.documents or self.createDocument().setActive() @signal(iface, signature='o') def activeDocumentChanged(self, doc): self.history.remove(doc) self.history.append(doc) self.activeChanged(doc) # emit our signal @method(iface, in_signature='', out_signature='s') def programName(self): """Returns the name of the application.""" return KGlobal.mainComponent().aboutData().programName() @method(iface, in_signature='', out_signature='s') def version(self): """Returns the version of our application.""" return KGlobal.mainComponent().aboutData().version() def handleException(self, exctype, excvalue, exctb): """Called when a Python exception goes unhandled. Catches KeyboardInterrupt and shows a dialog for other errors. Also writes the traceback to stderr. """ from traceback import format_exception sys.stderr.write(''.join(format_exception(exctype, excvalue, exctb))) if exctype != KeyboardInterrupt: from kateshell.exception import ExceptionDialog ExceptionDialog(self, exctype, excvalue, exctb) def keepMetaInfo(self): """Returns whether meta information about documents should be kept. For example the state of the view, cursor position, encoding etc. The default implementation returns False, reimplement this to return e.g. a user's configured setting. """ return False @contextmanager def busyCursor(self, cursor=None): """Performs code with a busy cursor set for the application. The default cursor to use is the Qt.WaitCursor. Usage: with app.busyCursor(): ... """ if cursor is None: cursor = QCursor(Qt.WaitCursor) KApplication.setOverrideCursor(cursor) try: yield finally: KApplication.restoreOverrideCursor() def debug(self, message): """Write message to stderr.""" message = "{0}: {1}\n".format( self.programName(), "\n ".join(message.splitlines())) sys.stderr.write(message)
KMainWindow.__init__ (self) self.resize (640, 480) label = QLabel ("This is a simple PyKDE4 program", self) label.setGeometry (10, 10, 200, 20) #--------------- main ------------------ if __name__ == '__main__': appName = "KApplication" catalog = "" programName = ki18n ("KApplication") version = "1.0" description = ki18n ("KApplication/KMainWindow/KAboutData example") license = KAboutData.License_GPL copyright = ki18n ("(c) 2007 Jim Bublitz") text = ki18n ("none") homePage = "www.riverbankcomputing.com" bugEmail = "*****@*****.**" aboutData = KAboutData (appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) KCmdLineArgs.init (sys.argv, aboutData) app = KApplication() mainWindow = MainWindow() mainWindow.show() sys.exit(app.exec_())
def main(): " Main Loop " from getopt import getopt OPAQUE = True BORDER = True try: opts, args = getopt(sys.argv[1:], "hvob", ["version", "help", "opaque", "borderless"]) pass except: pass for o, v in opts: if o in ("-h", "--help"): print( """ Usage: -h, --help Show help informations and exit. -v, --version Show version information and exit. -o, --opaque Use Opaque GUI. -b, --borderless No WM Borders. Run without parameters and arguments to use the GUI. """ ) return sys.exit(1) elif o in ("-v", "--version"): print(__version__) return sys.exit(1) elif o in ("-o", "--opaque"): OPAQUE = False elif o in ("-b", "--borderless"): BORDER = False # define our App try: app = QApplication(sys.argv) app.setApplicationName(__doc__) app.setOrganizationName(__author__) app.setOrganizationDomain(__author__) app.setStyle("Plastique") app.setStyle("Oxygen") except TypeError: aboutData = KAboutData( __doc__, "", ki18n(__doc__), __version__, ki18n(__doc__), KAboutData.License_GPL, ki18n(__author__), ki18n("none"), __url__, __email__, ) KCmdLineArgs.init(sys.argv, aboutData) app = QApplication() app.lastWindowClosed.connect(app.quit) # w is gonna be the mymainwindow class w = MyMainWindow() # set the class with the attribute of translucent background as true if OPAQUE is True: w.setAttribute(Qt.WA_TranslucentBackground, True) # WM Borders if BORDER is False: w.setWindowFlags(w.windowFlags() | Qt.FramelessWindowHint) # run the class w.show() # if exiting the loop take down the app sys.exit(app.exec_())
self.resize(640, 480) self.setCentralWidget(MainFrame(self)) #-------------------- main ------------------------------------------------ appName = "default" catalog = "" programName = ki18n("default") #ki18n required here version = "1.0" description = ki18n("Default Example") #ki18n required here license = KAboutData.License_GPL copyright = ki18n("(c) 2007 Jim Bublitz") #ki18n required here text = ki18n("none") #ki18n required here homePage = "www.riverbank.com" bugEmail = "*****@*****.**" aboutData = KAboutData(appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) # ki18n required for first two addAuthor () arguments aboutData.addAuthor(ki18n("Troy Melhase"), ki18n("original concept")) aboutData.addAuthor(ki18n("Jim Bublitz"), ki18n("pykdedocs")) KCmdLineArgs.init(sys.argv, aboutData) app = KApplication() mainWindow = MainWin(None, "main window") mainWindow.show() app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit) app.exec_()
class Magneto(MagnetoCore): """ Magneto Updates Notification Applet class. """ def __init__(self): app_name = "magneto" catalog = "" prog_name = ki18n("Magneto") version = "1.0" description = ki18n("System Update Status") lic = KAboutData.License_GPL cright = ki18n("(c) 2013 Fabio Erculiani") text = ki18n("none") home_page = "www.sabayon.org" bug_mail = "*****@*****.**" self._kabout = KAboutData (app_name, catalog, prog_name, version, description, lic, cright, text, home_page, bug_mail) argv = [sys.argv[0]] KCmdLineArgs.init(argv, self._kabout) self._app = KApplication() from dbus.mainloop.qt import DBusQtMainLoop super(Magneto, self).__init__(main_loop_class = DBusQtMainLoop) self._window = KStatusNotifierItem() # do not show "Quit" and use quitSelected() signal self._window.setStandardActionsEnabled(False) icon_name = self.icons.get("okay") self._window.setIconByName(icon_name) self._window.setStatus(KStatusNotifierItem.Passive) self._window.connect(self._window, SIGNAL("activateRequested(bool,QPoint)"), self.applet_activated) self._menu = KMenu(_("Magneto Entropy Updates Applet")) self._window.setContextMenu(self._menu) self._menu_items = {} for item in self._menu_item_list: if item is None: self._menu.addSeparator() continue myid, _unused, mytxt, myslot_func = item name = self.get_menu_image(myid) action_icon = KIcon(name) w = KAction(action_icon, mytxt, self._menu) self._menu_items[myid] = w self._window.connect(w, SIGNAL("triggered()"), myslot_func) self._menu.addAction(w) self._menu.hide() def _first_check(self): def _do_check(): self.send_check_updates_signal(startup_check = True) return False if self._dbus_service_available: QTimer.singleShot(10000, _do_check) def startup(self): """ Start user interface. """ self._dbus_service_available = self.setup_dbus() if config.settings["APPLET_ENABLED"] and \ self._dbus_service_available: self.enable_applet(do_check = False) else: self.disable_applet() if not self._dbus_service_available: QTimer.singleShot(30000, self.show_service_not_available) else: self._first_check() # Notice Window instance self._notice_window = AppletNoticeWindow(self) # Enter main loop self._app.exec_() def close_service(self): super(Magneto, self).close_service() self._app.quit() def change_icon(self, icon_name): name = self.icons.get(icon_name) self._window.setIconByName(name) def disable_applet(self, *args): super(Magneto, self).disable_applet() self._menu_items["disable_applet"].setEnabled(False) self._menu_items["enable_applet"].setEnabled(True) def enable_applet(self, w = None, do_check = True): done = super(Magneto, self).enable_applet(do_check = do_check) if done: self._menu_items["disable_applet"].setEnabled(True) self._menu_items["enable_applet"].setEnabled(False) def show_alert(self, title, text, urgency = None, force = False, buttons = None): if ((title, text) == self.last_alert) and not force: return def _action_activate_cb(action_num): if not buttons: return try: action_info = buttons[action_num - 1] except IndexError: return _action_id, _button_name, button_callback = action_info button_callback() def do_show(): notification = KNotification("Updates") # Keep a reference or the callback of the actions added # below will never work. # See: https://bugzilla.redhat.com/show_bug.cgi?id=241531 self.__last_notification = notification notification.setFlags(KNotification.CloseOnTimeout) notification.setText("<b>%s</b><br/>%s" % (title, text,)) if buttons: notification.setActions([x[1] for x in buttons]) notification.connect( notification, SIGNAL("activated(unsigned int)"), _action_activate_cb) icon_name = "okay" status = KStatusNotifierItem.Passive if urgency == "critical": icon_name = "critical" status = KStatusNotifierItem.Active name = self.icons.get(icon_name) icon = KIcon(name) self._window.setStatus(status) notification.setPixmap(icon.pixmap(48, 48)) notification.sendEvent() self.last_alert = (title, text) # thread safety QTimer.singleShot(0, do_show) def update_tooltip(self, tip): def do_update(): self._window.setToolTipTitle(tip) QTimer.singleShot(0, do_update) def applet_context_menu(self): """ No action for now. """ pass def applet_activated(self, active, pos): if active: self.applet_doubleclick() def hide_notice_window(self): self.notice_window_shown = False self._notice_window.hide() def show_notice_window(self): if self.notice_window_shown: return if not self.package_updates: return entropy_ver = None packages = [] for atom in self.package_updates: key = entropy.dep.dep_getkey(atom) avail_rev = entropy.dep.dep_get_entropy_revision(atom) avail_tag = entropy.dep.dep_gettag(atom) my_pkg = entropy.dep.remove_entropy_revision(atom) my_pkg = entropy.dep.remove_tag(my_pkg) pkgcat, pkgname, pkgver, pkgrev = entropy.dep.catpkgsplit(my_pkg) ver = pkgver if pkgrev != "r0": ver += "-%s" % (pkgrev,) if avail_tag: ver += "#%s" % (avail_tag,) if avail_rev: ver += "~%s" % (avail_tag,) if key == "sys-apps/entropy": entropy_ver = ver packages.append("%s (%s)" % (key, ver,)) critical_msg = "" if entropy_ver is not None: critical_msg = "%s <b>sys-apps/entropy</b> " "%s, %s <b>%s</b>. %s." % ( _("Your system currently has an outdated version of"), _("installed"), _("the latest available version is"), entropy_ver, _("It is recommended that you upgrade to " "the latest before updating any other packages") ) self._notice_window.populate(packages, critical_msg) self._notice_window.show() self.notice_window_shown = True
def main(): from argparse import ArgumentParser, RawTextHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter) parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__) parser.add_argument('file', nargs='?', help='PDF file to open') parser.add_argument('-o', '--output', help='where to save the cropped PDF') parser.add_argument('--rotate', type=int, choices=[0,90,180,270], help='how much to rotate the cropped pdf clockwise (default: 0)') parser.add_argument('--whichpages', help='which pages (e.g. "1-5" or "1,3-") to include in cropped PDF (default: all)') parser.add_argument('--initialpage', help='which page to open initially (default: 1)') parser.add_argument('--autotrim', action='store_true', help='create a selection for the entire initial page minus blank margins') parser.add_argument('--autotrim-padding', help='how much padding to include when auto trimming (default: previous value)') parser.add_argument('--go', action='store_true', help='output PDF without opening the krop GUI (using the choices from --autotrim, --rotate and --whichpages); if used in a script without X server access, you can run krop using xvfb-run') parser.add_argument('--selections', type=str, choices=['all','evenodd','individual'], help='to which pages should selections apply') parser.add_argument('--no-kde', action='store_true', help='do not use KDE libraries (default: use if available)') parser.add_argument('--no-qt5', action='store_true', help='do not use PyQt5 instead of PyQt4 (default: use PyQt5 if available)') parser.add_argument('--no-PyPDF2', action='store_true', help='do not use PyPDF2 instead of pyPdf (default: use PyPDF2 if available)') args = parser.parse_args() # start the GUI if KDE: #TODO also use PyKDE5 once more easily available from PyKDE4.kdecore import ki18n, KCmdLineArgs, KAboutData from PyKDE4.kdeui import KApplication appName = "krop" catalog = "" programName = ki18n("krop") aboutData = KAboutData(appName, catalog, programName, __version__) KCmdLineArgs.init(aboutData) app = KApplication() else: from krop.qt import QApplication app = QApplication(sys.argv) app.setApplicationName("krop") app.setOrganizationName("arminstraub.com") app.setOrganizationDomain("arminstraub.com") from krop.mainwindow import MainWindow window=MainWindow() if args.file is not None: fileName = args.file try: fileName = fileName.decode(sys.stdin.encoding or sys.getdefaultencoding()) except AttributeError: # not necessary (or possible) in python3, which uses unicode pass window.openFile(fileName) if args.output is not None: window.ui.editFile.setText(args.output) if args.whichpages is not None: window.ui.editWhichPages.setText(args.whichpages) if args.rotate is not None: window.ui.comboRotation.setCurrentIndex({0:0,90:2,180:3,270:1}[args.rotate]) if args.selections is not None: if args.selections == 'all': window.ui.radioSelAll.setChecked(True) elif args.selections == 'evenodd': window.ui.radioSelEvenOdd.setChecked(True) elif args.selections == 'individual': window.ui.radioSelIndividual.setChecked(True) if args.initialpage is not None: window.ui.editCurrentPage.setText(args.initialpage) window.slotCurrentPageEdited(args.initialpage) if args.autotrim_padding is not None: window.ui.editPadding.setText(args.autotrim_padding) if args.autotrim: window.slotTrimMarginsAll() # shut down on ctrl+c when pressed in terminal (not gracefully, though) # http://stackoverflow.com/questions/4938723/ import signal signal.signal(signal.SIGINT, signal.SIG_DFL) if args.go: # sys.stdout.write('kropping...\n') from krop.qt import QTimer QTimer.singleShot(0, window.slotKrop) QTimer.singleShot(0, window.close) else: window.show() # using exec_ because exec is a reserved keyword before python 3 sys.exit(app.exec_())
def run(): appName = "eclectus" catalog = "eclectusqt" programName = ki18n("Eclectus") version = eclectusqt.__version__ description = ki18n("Han character dictionary") license = KAboutData.License_GPL_V3 copyright = ki18n("(c) 2008-2009 Christoph Burgmer") text = ki18n( "Eclectus is a small Han character dictionary for learners.") homePage = eclectusqt.__url__ bugEmail = "*****@*****.**" bugAddress = "http://code.google.com/p/eclectus/issues/list" aboutData = KAboutData(appName, catalog, programName, version, description, license, copyright, text, homePage, bugEmail) aboutData.addAuthor(ki18n("Christoph Burgmer"), ki18n("Developer"), "*****@*****.**", "http://cburgmer.nfshost.com/") aboutData.setCustomAuthorText(ki18n("Please use %1 to report bugs.")\ .subs(bugAddress), ki18n('Please use %1 to report bugs.')\ .subs('<a href="%s">%s</a>' % (bugAddress, bugAddress))) aboutData.addCredit(KLocalizedString(), ki18n("Arrr, Eclectus sits on the shoulders of some fine pirates:")) aboutData.addCredit(ki18n("Jim Breen and contributors"), ki18n("EDICT"), '', 'http://www.csse.monash.edu.au/~jwb/j_edict.html') aboutData.addCredit(ki18n("Paul Denisowski and current contributors"), ki18n("CEDICT"), '', 'http://www.mdbg.net/chindict/chindict.php') aboutData.addCredit(ki18n("HanDeDict team"), ki18n("HanDeDict"), '', 'http://www.chinaboard.de/chinesisch_deutsch.php') aboutData.addCredit(ki18n("Tomoe developers"), ki18n("Tomoe handwriting recognition"), '*****@*****.**', 'http://tomoe.sourceforge.jp') aboutData.addCredit(ki18n("Mathieu Blondel and the Tegaki contributors"), ki18n("Tegaki handwriting recognition"), u'mathieu ÂT mblondel DÔT org'.encode('utf8'), 'http://tegaki.sourceforge.net') aboutData.addCredit(ki18n("Unicode Consortium and contributors"), ki18n("Unihan database"), '', 'http://unicode.org/charts/unihan.html') aboutData.addCredit(ki18n("Commons Stroke Order Project"), ki18n("Stroke order pictures"), '', 'http://commons.wikimedia.org/wiki/Commons:Stroke_Order_Project') aboutData.addCredit(ki18n("Tim Eyre, Ulrich Apel and the Wadoku Project"), ki18n("Kanji stroke order font"), '', 'http://sites.google.com/site/nihilistorguk/') aboutData.addCredit( ki18n("Yue Tan, Wei Gao, Vion Nicolas and the Shtooka Project"), ki18n("Pronunciation examples for Mandarin"), '', 'http://shtooka.net') # find logo file, don't directly use util.getData(), KApplication not # created yet aboutLogoFile = u'/usr/share/kde4/apps/eclectus/eclectus_about.png' if not os.path.exists(aboutLogoFile): modulePath = os.path.dirname(os.path.abspath(__file__)) aboutLogoFile = os.path.join(modulePath, 'data', 'eclectus_about.png') if not os.path.exists(aboutLogoFile): aboutLogoFile = util.getData('eclectus_about.png') if aboutLogoFile: aboutData.setProgramLogo(QVariant(QImage(aboutLogoFile))) KCmdLineArgs.init(sys.argv, aboutData) # create applicaton global g_app g_app = KApplication() # TODO how to access local .mo file? #base = os.path.dirname(os.path.abspath(__file__)) #localeDir = os.path.join(base, "locale") #print localeDir #if os.path.exists(localeDir): #print KGlobal.dirs().addResourceDir('locale', localeDir + '/', True) #print KGlobal.dirs().findResource('locale', 'de/LC_MESSAGES/eclectusqt.mo') # read config file and make global global GeneralConfig global DictionaryConfig global PluginConfig config = KConfig() GeneralConfig = KConfigGroup(config, "General") DictionaryConfig = KConfigGroup(config, "Dictionary") PluginConfig = KConfigGroup(config, "Plugin") # create main window MainWindow().show() # react to CTRL+C on the command line signal.signal(signal.SIGINT, signal.SIG_DFL) g_app.exec_()