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_()
Exemple #2
0
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():

    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_()
Exemple #4
0
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():
    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():
    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 __init__(self, argv, opts):
     """
     Constructor
     
     @param argv command line arguments
     @param opts acceptable command line options
     """
     loc = _localeString()
     os.environ["KDE_LANG"] = loc
     
     aboutData = KAboutData(
         Program, "kdelibs", ki18n(Program), Version, ki18n(""), 
         KAboutData.License_GPL, ki18n(Copyright), ki18n ("none"), 
         Homepage, BugAddress)
     sysargv = argv[:]
     KCmdLineArgs.init(sysargv, aboutData)
     
     if opts:
         options = KCmdLineOptions()
         for opt in opts:
             if len(opt) == 2:
                 options.add(opt[0], ki18n(opt[1]))
             else:
                 options.add(opt[0], ki18n(opt[1]), opt[2])
         KCmdLineArgs.addCmdLineOptions(options)
     
     KApplication.__init__(self, True)
     KQApplicationMixin.__init__(self)
Exemple #9
0
    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)
            # Create data directory (for log file)
            if not os.path.exists(DATA_DIR):
                os.makedirs(DATA_DIR)
            # Create run directory (for lock file)
            if not os.path.exists(RUN_DIR):
                os.makedirs(RUN_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 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_()
Exemple #11
0
 def pulse(self, owner):
     super(KDEFetchProgressAdapter, self).pulse(owner)
     at_item = min(self.current_items + 1, self.total_items)
     if self.current_cps > 0:
         self.label.setText(_("Downloading additional package files...") + _("File %s of %s at %sB/s" % (at_item, self.total_items, apt_pkg.size_to_str(self.current_cps))))
     else:
         self.label.setText(_("Downloading additional package files...") + _("File %s of %s" % (at_item, self.total_items)))
     self.progress.setValue(100 * self.current_bytes / self.total_bytes)
     KApplication.kApplication().processEvents()
     return True
Exemple #12
0
    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()
Exemple #13
0
    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
Exemple #14
0
    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()
Exemple #15
0
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_())
    def __init__(self, datadir, component_data=None, parent=None):
        LanguageSelectorBase.__init__(self, datadir)
        KCModule.__init__(self, component_data, parent)
        
        self.parentApp = KApplication.kApplication()
        self.ui = Ui_QtLanguageSelectorGUI()
        self.ui.setupUi(self)
        self.about = MakeAboutData()
        self.setAboutData(self.about)
        
        self.setWindowIcon(KIcon("preferences-desktop-locale"))
        
        self.imSwitch = ImSwitch()
        # remove dangling ImSwitch symlinks if present
        self.imSwitch.removeDanglingSymlinks()
        self.init()

        # connect the signals
        self.connect(self.ui.listViewLanguagesInst, SIGNAL("itemSelectionChanged()"), self.checkInstallableComponents)
        self.connect(self.ui.listViewLanguagesUninst, SIGNAL("itemSelectionChanged()"), self.onChanged)
        self.connect(self.ui.ktabwidget, SIGNAL("currentChanged(int)"), self.onTabChangeRevertApply)
        self.connect(self.ui.listBoxDefaultLanguage, SIGNAL("itemSelectionChanged()"), self.checkInputMethods)
        self.connect(self.ui.checkBoxTr, SIGNAL("stateChanged(int)"), self.onChanged)
        self.connect(self.ui.checkBoxIm, SIGNAL("stateChanged(int)"), self.onChanged)
        self.connect(self.ui.checkBoxSpell, SIGNAL("stateChanged(int)"), self.onChanged)
        self.connect(self.ui.checkBoxFonts, SIGNAL("stateChanged(int)"), self.onChanged)
Exemple #17
0
    def initUI(self):
	global config
        backupTitle = QtGui.QLabel('Backup Volume:')
        self.backupVolumeTitle = QtGui.QLabel(config.backupName)
	self.manageBackupButton = QtGui.QPushButton('Manage Backup Volumes')
	self.managePathsButton = QtGui.QPushButton('Manage Sync Paths')
	
        toplevel = QtGui.QHBoxLayout()
        toplevel.addWidget(backupTitle)
        toplevel.addWidget(self.backupVolumeTitle)
        toplevel.addWidget(self.manageBackupButton)
        
        secondlevel = QtGui.QHBoxLayout()
        progressTitle = QtGui.QLabel('Syncing Progress:')
        self.progressDetail = QtGui.QLabel('Stopped.')
        secondlevel.addWidget(progressTitle)
        secondlevel.addWidget(self.progressDetail)
        secondlevel.addWidget(self.managePathsButton)
        
        gridv = QtGui.QVBoxLayout()
        gridv.addLayout(toplevel)
        gridv.addLayout(secondlevel)
        self.setLayout(gridv)
        self.setWindowTitle("Backup2isp")
        self.move( KApplication.desktop().screen().rect().center() - self.rect().center() )
	self.manageBackupButton.connect(self.manageBackupButton, QtCore.SIGNAL("clicked()"), self.manageBackups)
	self.managePathsButton.connect(self.managePathsButton, QtCore.SIGNAL("clicked()"), self.managePaths)
        self.beginBackup()
Exemple #18
0
 def pulse(self, owner):
     super(KDEFetchProgressAdapter, self).pulse(owner)
     at_item = min(self.current_items + 1, self.total_items)
     if self.current_cps > 0:
         self.label.setText(
             _("Downloading additional package files...") +
             _("File %s of %s at %sB/s" %
               (at_item, self.total_items,
                apt_pkg.size_to_str(self.current_cps))))
     else:
         self.label.setText(
             _("Downloading additional package files...") +
             _("File %s of %s" % (at_item, self.total_items)))
     self.progress.setValue(100 * self.current_bytes / self.total_bytes)
     KApplication.kApplication().processEvents()
     return True
 def pulse(self, owner):
     apt.progress.base.AcquireProgress.pulse(self, owner)
     self.progress.setValue((self.current_bytes + self.current_items) /
                            float(self.total_bytes + self.total_items))
     current_item = self.current_items + 1
     if current_item > self.total_items:
         current_item = self.total_items
     label_text = _("Downloading additional package files...")
     if self.current_cps > 0:
         label_text += _("File %s of %s at %sB/s") % (
             self.current_items, self.total_items,
             apt_pkg.size_to_str(self.current_cps))
     else:
         label_text += _("File %s of %s") % (self.current_items,
                                             self.total_items)
     self.label.setText(label_text)
     KApplication.kApplication().processEvents()
     return True
Exemple #20
0
    def __init__(self):
        
        aboutData = KAboutData(APP_NAME, CATALOG, PROGRAM_NAME, VERSION, DESCRIPTION,
                                    LICENSE, COPYRIGHT, TEXT, HOMEPAGE, BUG_EMAIL)

        aboutData.addAuthor(ki18n("Chris Dekter"), ki18n("Developer"), "*****@*****.**", "")
        aboutData.addAuthor(ki18n("Sam Peterson"), ki18n("Original developer"), "*****@*****.**", "")
        aboutData.setProgramIconName(common.ICON_FILE)
        self.aboutData = aboutData

        aboutData_py3 = KAboutData(APP_NAME, CATALOG, PROGRAM_NAME_PY3, VERSION, DESCRIPTION_PY3,
                                    LICENSE, COPYRIGHT_PY3, TEXT, HOMEPAGE_PY3, BUG_EMAIL_PY3)
        aboutData_py3.addAuthor(ki18n("GuoCi"), ki18n("Python 3 port maintainer"), "*****@*****.**", "")
        aboutData_py3.addAuthor(ki18n("Chris Dekter"), ki18n("Developer"), "*****@*****.**", "")
        aboutData_py3.addAuthor(ki18n("Sam Peterson"), ki18n("Original developer"), "*****@*****.**", "")
        aboutData_py3.setProgramIconName(common.ICON_FILE)
        self.aboutData_py3 = aboutData_py3
        
        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)
Exemple #21
0
    def commit(self):
        # ui
        self.status.setText(
            _("Installing '%s'...") % os.path.basename(self.debfile))
        # the command
        cmd = "/usr/bin/dpkg"
        argv = [cmd, "--auto-deconfigure", "-i", self.debfile]
        (self.child_pid, self.master_fd) = pty.fork()

        if self.child_pid == 0:
            os.environ["TERM"] = "dumb"
            if not "DEBIAN_FRONTEND" in os.environ:
                os.environ["DEBIAN_FRONTEND"] = "noninteractive"
            os.environ["APT_LISTCHANGES_FRONTEND"] = "none"
            exitstatus = subprocess.call(argv)
            os._exit(exitstatus)

        while True:
            #Read from pty and write to DumbTerminal
            try:
                (rlist, wlist, xlist) = select.select([self.master_fd], [], [],
                                                      0.001)
                if len(rlist) > 0:
                    line = os.read(self.master_fd, 255)
                    self.parent.konsole.insertWithTermCodes(utf8(line))
            except Exception as e:
                #print e
                from errno import EAGAIN
                if hasattr(e, "errno") and e.errno == EAGAIN:
                    continue
                break
            KApplication.kApplication().processEvents()
        # at this point we got a read error from the pty, that most
        # likely means that the client is dead
        (pid, status) = os.waitpid(self.child_pid, 0)
        self.exitstatus = os.WEXITSTATUS(status)

        self.progress.setValue(100)
        self.parent.closeButton.setEnabled(True)
        self.parent.closeButton.setVisible(True)
        self.parent.installationProgress.setVisible(False)
        QTimer.singleShot(1, self.parent.changeSize)
 def showReleaseNotes(self):
     # FIXME: care about i18n! (append -$lang or something)
     self.dialogue = QDialog()
     uic.loadUi(self.APPDIR + "/dialog_release_notes.ui", self.dialogue)
     upgradeButton = self.dialogue.buttonBox.button(QDialogButtonBox.Ok)
     upgradeButton.setText(_("Upgrade"))
     upgradeButton.setIcon(KIcon("dialog-ok"))
     cancelButton = self.dialogue.buttonBox.button(QDialogButtonBox.Cancel)
     cancelButton.setIcon(KIcon("dialog-cancel"))
     self.dialogue.setWindowTitle(_("Release Notes"))
     self.dialogue.show()
     if self.new_dist.releaseNotesURI is not None:
         uri = self._expandUri(self.new_dist.releaseNotesURI)
         # download/display the release notes
         # FIXME: add some progress reporting here
         result = None
         try:
             release_notes = urlopen(uri)
             notes = release_notes.read().decode("UTF-8", "replace")
             self.dialogue.scrolled_notes.setText(notes)
             result = self.dialogue.exec_()
         except HTTPError:
             primary = "<span weight=\"bold\" size=\"larger\">%s</span>" % \
                       _("Could not find the release notes")
             secondary = _("The server may be overloaded. ")
             KMessageBox.sorry(None, primary + "<br />" + secondary, "")
         except IOError:
             primary = "<span weight=\"bold\" size=\"larger\">%s</span>" % \
                       _("Could not download the release notes")
             secondary = _("Please check your internet connection.")
             KMessageBox.sorry(None, primary + "<br />" + secondary, "")
         # user clicked cancel
         if result == QDialog.Accepted:
             self.progressDialogue.show()
             return True
     if __name__ == "__main__":
         KApplication.kApplication().exit(1)
     if self.useDevelopmentRelease or self.useProposed:
         #FIXME why does KApplication.kApplication().exit() crash but
         # this doesn't?
         sys.exit()
     return False
Exemple #23
0
    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()
Exemple #24
0
 def update_interface(self):
     # run the base class
     try:
         InstallProgress.update_interface(self)
     except ValueError as e:
         pass
     # log the output of dpkg (on the master_fd) to the DumbTerminal
     while True:
         try:
             (rlist, wlist, xlist) = select.select([self.master_fd],[],[], 0.01)
             # data available, read it
             if len(rlist) > 0:
                 line = os.read(self.master_fd, 255)
                 self.parent.konsole.insertWithTermCodes(utf8(line))
             else:
                 # nothing happend within the timeout, break
                 break
         except Exception as e:
             logging.debug("update_interface: %s" % e)
             break
     KApplication.kApplication().processEvents()
Exemple #25
0
    def commit(self):
        # ui
        self.status.setText(_("Installing '%s'...") % os.path.basename(self.debfile))
        # the command
        cmd = "/usr/bin/dpkg"
        argv = [cmd, "--auto-deconfigure", "-i", self.debfile]
        (self.child_pid, self.master_fd) = pty.fork()

        if self.child_pid == 0:
            os.environ["TERM"] = "dumb"
            if not "DEBIAN_FRONTEND" in os.environ:
                os.environ["DEBIAN_FRONTEND"] = "noninteractive"
            os.environ["APT_LISTCHANGES_FRONTEND"] = "none"
            exitstatus = subprocess.call(argv)
            os._exit(exitstatus)
        
        while True:
            #Read from pty and write to DumbTerminal
            try:
                (rlist, wlist, xlist) = select.select([self.master_fd],[],[], 0.001)
                if len(rlist) > 0:
                    line = os.read(self.master_fd, 255)
                    self.parent.konsole.insertWithTermCodes(utf8(line))
            except Exception as e:
                #print e
                from errno import EAGAIN
                if hasattr(e, "errno") and e.errno == EAGAIN:
                    continue
                break
            KApplication.kApplication().processEvents()
        # at this point we got a read error from the pty, that most
        # likely means that the client is dead
        (pid, status) = os.waitpid(self.child_pid, 0)
        self.exitstatus = os.WEXITSTATUS(status)

        self.progress.setValue(100)
        self.parent.closeButton.setEnabled(True)
        self.parent.closeButton.setVisible(True)
        self.parent.installationProgress.setVisible(False)
        QTimer.singleShot(1, self.parent.changeSize)
    def __init__(self, datadir, options, file="", parent=None, name=None,
                 modal=0, fl=0):
        GDebiKDEDialog.__init__(self,parent)
        GDebiCommon.__init__(self,datadir,options,file)
        # load the icon
        self.setWindowIcon(KIcon("application-x-deb"))
        # first, we load all the default descriptions -- pyuic doesn't use
        # gettext as default (FIXME, copy code from language-selector)
        self.textLabel1.setText(_("Package:"))
        self.textLabel1_2.setText(_("Status:"))
        self.detailsButton.setText(_("Details"))
        self.tabWidget2.setTabText(0,_("Description"))
        self.tabWidget2.setTabText(1,_("Details"))
        self.tabWidget2.setTabText(2,_("Included Files"))
        self.cancelButton.setText(__("kdelibs","&Cancel"))
        self.installButton.setText(_("&Install Package"))
        self.downloadButton.setText(_("&Download Package"))
        self.DetailsVersionLabel.setText(_("<b>Version:</b>"))
        self.DetailsMaintainerLabel.setText(_("<b>Maintainer:</b>"))
        self.DetailsPriorityLabel.setText(_("<b>Priority:</b>"))
        self.DetailsSectionLabel.setText(_("<b>Section:</b>"))
        self.DetailsSizeLabel.setText(_("<b>Size:</b>"))
        # translation finished
        self.setDisabled(True)
        self.PackageProgressBar.setEnabled(True)
        self.detailsButton.hide()
        self.downloadButton.hide()
        self.installButton.setIcon(KIcon("dialog-ok"))
        self.cancelButton.setIcon(KIcon("dialog-cancel"))
        self.show()
        self.kapp = KApplication.kApplication() #incidently, this stops it crashing on quit, no idea why, jriddell
        self.kapp.processEvents() #run because openCache takes a while to do its thing
        self.cprogress = CacheProgressAdapter(self.PackageProgressBar)
        if not self.openCache():
            KMessageBox.error(self, '<b>' + self.error_header + '</b><br>' + self.error_body,
                self.error_header)
            sys.exit(1)
        # try to open the file
        if file != "" and os.path.exists(file):
            self.open(file)
        else:
            header = _("The package file does not exist")
            body = _("A nonexistent file has been selected for installation. Please select an existing .deb package file.")
            KMessageBox.error(self, '<b>' + header + '</b><br>' + body, header)
            sys.exit(1)

        self.setEnabled(True)
        self.PackageProgressBar.hide()
        self.connect(self.cancelButton, SIGNAL("clicked()"), self.cancelButtonClicked)
        self.connect(self.installButton, SIGNAL("clicked()"), self.installButtonClicked)
        self.connect(self.downloadButton, SIGNAL("clicked()"), self.downloadButtonClicked)
        self.connect(self.detailsButton, SIGNAL("clicked()"), self.detailsButtonClicked)
Exemple #27
0
 def update_interface(self):
     # run the base class
     try:
         InstallProgress.update_interface(self)
     except ValueError as e:
         pass
     # log the output of dpkg (on the master_fd) to the DumbTerminal
     while True:
         try:
             (rlist, wlist, xlist) = select.select([self.master_fd], [], [],
                                                   0.01)
             # data available, read it
             if len(rlist) > 0:
                 line = os.read(self.master_fd, 255)
                 self.parent.konsole.insertWithTermCodes(utf8(line))
             else:
                 # nothing happend within the timeout, break
                 break
         except Exception as e:
             logging.debug("update_interface: %s" % e)
             break
     KApplication.kApplication().processEvents()
Exemple #28
0
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 __init__(self, parent):
     QDialog.__init__(self, parent)
     loadUi("GDebiKDEInstallDialog.ui", self)
     self.setWindowTitle(_("Installing"))
     self.showDetailsButton.setText(__("libept","Show Details")) #FIXME check i18n
     self.closeButton.setText(__("kdelibs","&Close"))
     self.showDetailsButton.setIcon(KIcon("utilities-terminal"))
     self.closeButton.setIcon(KIcon("window-close"))
     self.closeButton.setEnabled(False)
     self.closeButton.setVisible(False)
     self.parent = parent
     self.konsole = None
     self.konsoleFrameLayout = QHBoxLayout(self.konsoleFrame)
     self.konsoleFrame.hide()
     self.newKonsole()
     kapp = KApplication.kApplication()
     kapp.processEvents()
 def __init__(self, parent):
     QDialog.__init__(self, parent)
     loadUi("GDebiKDEInstallDialog.ui", self)
     self.setWindowTitle(_("Installing"))
     self.showDetailsButton.setText(__("libept",
                                       "Show Details"))  #FIXME check i18n
     self.closeButton.setText(__("kdelibs", "&Close"))
     self.showDetailsButton.setIcon(KIcon("utilities-terminal"))
     self.closeButton.setIcon(KIcon("window-close"))
     self.closeButton.setEnabled(False)
     self.closeButton.setVisible(False)
     self.parent = parent
     self.konsole = None
     self.konsoleFrameLayout = QHBoxLayout(self.konsoleFrame)
     self.konsoleFrame.hide()
     self.newKonsole()
     kapp = KApplication.kApplication()
     kapp.processEvents()
Exemple #31
0
    def initUI(self):
        global config
        
        username = QtGui.QLabel('Username')
        password = QtGui.QLabel('Password')

        self.providerBox = QtGui.QComboBox()
        self.providerBox.addItem('Virgin Media');
        
        self.usernameEdit = QtGui.QLineEdit()
        self.usernameEdit.setText( config.username )
        
        self.passwordEdit = QtGui.QLineEdit()
        self.passwordEdit.setEchoMode(QtGui.QLineEdit.Password)
        self.passwordEdit.setText( config.password )
        self.loginButton = QtGui.QPushButton('Login')

        grid = QtGui.QHBoxLayout()
        grid.addStretch(1)

        grid.addWidget(self.providerBox)
        grid.addWidget(username)
        grid.addWidget(self.usernameEdit)

        grid.addWidget(password)
        grid.addWidget(self.passwordEdit)
        
        
        grid.addWidget(self.loginButton)
        
        self.usernameEdit.connect(self.usernameEdit, QtCore.SIGNAL("returnPressed()"), self.loginSubmit)
        self.passwordEdit.connect(self.passwordEdit, QtCore.SIGNAL("returnPressed()"), self.loginSubmit)
        self.loginButton.connect(self.loginButton, QtCore.SIGNAL("clicked()"), self.loginSubmit)
        
        self.setLayout(grid)
        
        self.setWindowTitle("Backup2isp Login")
        self.setFixedSize( 450,40 )
        self.show()
        self.move( KApplication.desktop().screen().rect().center() - self.rect().center() )
Exemple #32
0
    def initUI(self):
	global config
	self.localDirTree = LocalDirTreeWidget()
	self.localDirTree.initDirTree( "/", config.syncpaths, config.excludepaths )
	self.savePathButton = QtGui.QPushButton('Save')
	self.cancelPathButton = QtGui.QPushButton('Cancel')
	
        toplevel = QtGui.QHBoxLayout()
        toplevel.addWidget(self.localDirTree)
        bottomlevel = QtGui.QHBoxLayout()
        bottomlevel.addWidget(self.savePathButton)
        bottomlevel.addWidget(self.cancelPathButton)
        
        gridv = QtGui.QVBoxLayout()
        gridv.addLayout(toplevel)
        gridv.addLayout(bottomlevel)
        self.setLayout(gridv)
        self.setWindowTitle("Backup2isp - Manage Sync Paths")
        self.move( KApplication.desktop().screen().rect().center() - self.rect().center() )
        
	self.savePathButton.connect(self.savePathButton, QtCore.SIGNAL("clicked()"), self.savePaths)
	self.cancelPathButton.connect(self.cancelPathButton, QtCore.SIGNAL("clicked()"), self.cancelPaths)
Exemple #33
0
    def initUI(self):
        global backupInstance, config
        response, backups = backupInstance.listBackups()
        
        backupTitle = QtGui.QLabel('Backup')
        self.backupList = QtGui.QComboBox()
        self.useBackupButton = QtGui.QPushButton('Use')
        self.addBackupButton = QtGui.QPushButton('Add')
        self.deleteBackupButton = QtGui.QPushButton('Delete')
        
        i=1
        self.backupList.addItem("Select Backup")
        for backup in backups:
	  self.backupList.addItem(backups[backup]["backup_name"]);
	  # select stored backup
	  if backups[backup]["backup_name"] == config.backupName:
	    self.backupList.setCurrentIndex(i)
	  i+=1
        
        grid = QtGui.QHBoxLayout()
        grid.addWidget(backupTitle)
        grid.addStretch(1)
        grid.addWidget(self.backupList)
        grid.addWidget(self.useBackupButton)
        grid.addWidget(self.addBackupButton)
        grid.addWidget(self.deleteBackupButton)
        self.setLayout(grid)
        
        self.setWindowTitle("Backup2isp - Choose Backup")
        self.show()
        self.move( KApplication.desktop().screen().rect().center() - self.rect().center() )
        
        
	self.useBackupButton.connect(self.useBackupButton, QtCore.SIGNAL("clicked()"), self.useBackup)
	self.addBackupButton.connect(self.addBackupButton, QtCore.SIGNAL("clicked()"), self.addBackup)
	self.deleteBackupButton.connect(self.deleteBackupButton, QtCore.SIGNAL("clicked()"), self.deleteBackup)
Exemple #34
0
        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_())
Exemple #35
0
    @QtCore.pyqtSignature("bool")
    def on_actionDisconnect_triggered(self):
        self.ifc.adslstop()


if not dbus.get_default_main_loop():
    from dbus.mainloop.qt import DBusQtMainLoop
    DBusQtMainLoop(set_as_default=True)

aboutData = KAboutData(appName, catalog, programName, version, description,
                       license, copyright, text, homePage, bugEmail)

KCmdLineArgs.init(sys.argv, aboutData)

app = KApplication()
app.setQuitOnLastWindowClosed(False)
mw = MainWindow()
mw.show()

aboutData.setProgramIconName(":/icons/icons/manager.png")
aboutData.addAuthor(ki18n("Cihan Okyay"), ki18n("Current Maintainer"),
                    "*****@*****.**")


def showw(event):
    if event == QtGui.QSystemTrayIcon.Trigger:
        if not mw.isVisible():
            mw.show()
        else:
            mw.hide()
Exemple #36
0
            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_ ()
Exemple #37
0
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
#--------------- main ------------------



if __name__ == '__main__':

    appName     = "KApplication"
    catalog     = ""
    programName = ki18n ("KApplication")
    version     = "1.0"
    description = ki18n ("AGH-WPA connect")
    license     = KAboutData.License_GPL
    copyright   = ki18n ("(c) 2014 Krzysiek Nowakowski, Krystian Ujma, Roger Barlik")
    text        = ki18n ("none")
    homePage    = "krisdrum.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 ()
    app.exec_ ()
Exemple #39
0
    catalog = ""
    programName = ki18n("Koo")
    version = "1.0"
    description = ki18n("KDE OpenObject Client")
    license = KAboutData.License_GPL
    copyright = ki18n("(c) 2009 Albert Cervera i Areny")
    text = ki18n("none")
    homePage = "www.nan-tic.com"
    bugEmail = "*****@*****.**"

    aboutData = KAboutData(appName, catalog, programName, version, description,
                           license, copyright, text, homePage, bugEmail)

    KCmdLineArgs.init(arguments, aboutData)

    app = KApplication()
else:
    app = QApplication(arguments)

app.setApplicationName('Koo')
app.setOrganizationDomain('www.nan-tic.com')
app.setOrganizationName('NaN')

try:
    f = open(Settings.value('koo.stylesheet'), 'r')
    try:
        app.setStyleSheet(f.read())
    finally:
        f.close()
except:
    pass
Exemple #40
0
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_()
 def close(self):
     self.accept()
     KApplication.kApplication().exit()
Exemple #42
0
    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 __init__(self,
                 datadir,
                 options,
                 file="",
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0):
        GDebiKDEDialog.__init__(self, parent)
        GDebiCommon.__init__(self, datadir, options, file)
        # load the icon
        self.setWindowIcon(KIcon("application-x-deb"))
        # first, we load all the default descriptions -- pyuic doesn't use
        # gettext as default (FIXME, copy code from language-selector)
        self.textLabel1.setText(_("Package:"))
        self.textLabel1_2.setText(_("Status:"))
        self.detailsButton.setText(_("Details"))
        self.tabWidget2.setTabText(0, _("Description"))
        self.tabWidget2.setTabText(1, _("Details"))
        self.tabWidget2.setTabText(2, _("Included Files"))
        self.cancelButton.setText(__("kdelibs", "&Cancel"))
        self.installButton.setText(_("&Install Package"))
        self.downloadButton.setText(_("&Download Package"))
        self.DetailsVersionLabel.setText(_("<b>Version:</b>"))
        self.DetailsMaintainerLabel.setText(_("<b>Maintainer:</b>"))
        self.DetailsPriorityLabel.setText(_("<b>Priority:</b>"))
        self.DetailsSectionLabel.setText(_("<b>Section:</b>"))
        self.DetailsSizeLabel.setText(_("<b>Size:</b>"))
        # translation finished
        self.setDisabled(True)
        self.PackageProgressBar.setEnabled(True)
        self.detailsButton.hide()
        self.downloadButton.hide()
        self.installButton.setIcon(KIcon("dialog-ok"))
        self.cancelButton.setIcon(KIcon("dialog-cancel"))
        self.show()
        self.kapp = KApplication.kApplication(
        )  #incidently, this stops it crashing on quit, no idea why, jriddell
        self.kapp.processEvents(
        )  #run because openCache takes a while to do its thing
        self.cprogress = CacheProgressAdapter(self.PackageProgressBar)
        if not self.openCache():
            KMessageBox.error(
                self, '<b>' + self.error_header + '</b><br>' + self.error_body,
                self.error_header)
            sys.exit(1)
        # try to open the file
        if file != "" and os.path.exists(file):
            self.open(file)
        else:
            header = _("The package file does not exist")
            body = _(
                "A nonexistent file has been selected for installation. Please select an existing .deb package file."
            )
            KMessageBox.error(self, '<b>' + header + '</b><br>' + body, header)
            sys.exit(1)

        self.setEnabled(True)
        self.PackageProgressBar.hide()
        self.connect(self.cancelButton, SIGNAL("clicked()"),
                     self.cancelButtonClicked)
        self.connect(self.installButton, SIGNAL("clicked()"),
                     self.installButtonClicked)
        self.connect(self.downloadButton, SIGNAL("clicked()"),
                     self.downloadButtonClicked)
        self.connect(self.detailsButton, SIGNAL("clicked()"),
                     self.detailsButtonClicked)
Exemple #44
0
    appName = "KApplication"
    catalog = ""
    programName = ki18n("KApplication")
    version = "1.0"
    description = ki18n("KApplication example")
    license = KAboutData.License_GPL
    copyright = ki18n("(c) 2009 Panthera Pardus")
    text = ki18n("none")
    homePage = "www.pardus.org.tr"
    bugEmail = "*****@*****.**"

    # Create about data from defined variables
    aboutData = KAboutData(appName, catalog, programName, version, description,
                           license, copyright, text, homePage, bugEmail)

    # Initialize Command Line arguments
    KCmdLineArgs.init(sys.argv, aboutData)

    # Create the application
    app = KApplication()

    # Create Main Window
    mainWindow = MainWindow()
    mainWindow.show()

    # Set top Widget as our mainWindow
    app.setTopWidget(mainWindow)

    # Run the app
    app.exec_()
Exemple #45
0
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-2011 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"))
    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)
Exemple #46
0
 def update(self, percent=None):
     self.progressbar.show()
     if percent:
         self.progressbar.setValue(percent)
     KApplication.kApplication().processEvents()
Exemple #47
0
        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_())
Exemple #48
0
 def postEventWithCallback(self, callback, *args):
     self.queue.put((callback, args))
     app = KApplication.kApplication()
     app.postEvent(self, QEvent(QEvent.User))
Exemple #49
0
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)
Exemple #50
0
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    if not dbus.get_default_main_loop():
        from dbus.mainloop.qt import DBusQtMainLoop
        DBusQtMainLoop(set_as_default = True)

    from optparse import OptionParser

    usage = ctx.Pds.i18n("%prog packages_to_install")
    parser = OptionParser(usage=usage)
    args = filter(lambda x: not x.startswith('-'), sys.argv[1:])
    if len(sys.argv) > 1:

        from mainwindow import MainWindow
        if ctx.Pds.session == ctx.pds.Kde4:
            KCmdLineArgs.init([], aboutData)
            app = KApplication()
        else:
            app = QtGui.QApplication(sys.argv)
            font = ctx.Pds.settings('font','Dejavu Sans,10').split(',')
            app.setFont(QtGui.QFont(font[0], int(font[1])))

        setSystemLocale()
        manager = MainWindow(app, silence = True)

        manager.centralWidget().state._selected_packages = args
        manager.centralWidget().state.operationAction(args, silence = True)
        manager.centralWidget().progressDialog.show()

        sys.excepthook = handleException
        ctx._time()
        app.exec_()
Exemple #51
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs
from PyKDE4.kdeui import KApplication

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()
Exemple #52
0
def show_about(*args):
    dlg = KAboutApplicationDialog(aboutData, None)
    dlg.exec_()


aboutData = KAboutData("ksmarttray", "", ki18n(NAME), VERSION,
                       ki18n(""), KAboutData.License_GPL_V2,
                       ki18n("2008 Canonical, Inc."), ki18n(""),
                       "http://smartpm.org", "*****@*****.**")
for author in AUTHORS:
    name, email = author.rsplit(" ", 1)
    aboutData.addAuthor(ki18n(name), ki18n(""), email.strip("<>"), "")

KCmdLineArgs.init(sys.argv, aboutData)
app = KApplication()

import smart

ctrl = smart.init()

mainWindow = KMainWindow()
smart_icon = QIcon(getPixmap("smart"))
mainWindow.setWindowIcon(smart_icon)
sysTray = QSystemTrayIcon(smart_icon, None)
smart_image = getPixmap("smart").toImage()
aboutData.setProgramLogo(QVariant(smart_image))

menu = QMenu(None)
menu.addAction(KIcon("view-refresh"), "Check for updates", smart_update)
menu.addAction(smart_icon, "Launch Smart", smart_gui)
Exemple #53
0
 def postEventWithCallback(self, callback, *args):
     self.queue.put((callback, args))
     app = KApplication.kApplication()
     app.postEvent(self, QEvent(QEvent.User))
Exemple #54
0
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)
Exemple #55
0
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)
Exemple #56
0
            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_()
Exemple #57
0
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()
Exemple #58
0
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 close(self):
     self.accept()
     KApplication.kApplication().exit()