示例#1
0
文件: kcombobox.py 项目: sigoa/pykde4
    def __init__(self, parent=None):
        KVBox.__init__(self, parent)
        self.help = QLabel(i18n(helpText), self)
        self.layout().setAlignment(self.help, Qt.AlignHCenter)
        self.setSpacing(10)

        hBox = KHBox(self)
        self.layout().setAlignment(hBox, Qt.AlignHCenter)

        cBox = KVBox(hBox)
        hBox.layout().setAlignment(cBox, Qt.AlignTop)
        hBox.setSpacing(25)
        hBox.setMargin(10)

        self.stdDirs = KStandardDirs()
        types = self.stdDirs.allTypes()

        comboLbl = QLabel("Types", cBox)
        combo = KComboBox(cBox)
        combo.addItems(types)
        cBox.layout().setAlignment(comboLbl, Qt.AlignTop)
        cBox.layout().setAlignment(combo, Qt.AlignTop)

        self.connect(combo, SIGNAL("currentIndexChanged (const QString&)"),
                     self.slotIndexChanged)

        lBox = KVBox(hBox)
        listLbl = QLabel("Directories", lBox)
        self.location = KListWidget(lBox)
        self.location.setMaximumSize(400, 200)
        lBox.layout().setAlignment(listLbl, Qt.AlignTop)
        lBox.layout().setAlignment(self.location, Qt.AlignTop)

        self.slotIndexChanged(combo.currentText())
示例#2
0
    def setup_welcome_widget(self):
        """Load the welcome widget at startup."""

        widget = QWidget()
        layout = QVBoxLayout()

        welcome = QLabel(parent=self)
        pix = QPixmap(KStandardDirs.locate("appdata", "logo.png"))

        welcome.setPixmap(pix)
        welcome.setAlignment(Qt.AlignCenter)

        self.first_fetch_widget = connectwidget.ConnectWidget(
            self.preferences.boards_list, self)

        self.statusbar.addPermanentWidget(self.first_fetch_widget, 300)

        self.first_fetch_widget.connectionEstablished.connect(
            self.handle_connection)
        self.first_fetch_widget.rejected.connect(self.first_fetch_widget.hide)

        self.first_fetch_widget.hide()

        self.first_fetch_widget.setSizePolicy(QSizePolicy.Preferred,
                                              QSizePolicy.Fixed)

        layout.addWidget(self.first_fetch_widget)
        layout.addWidget(welcome)
        widget.setLayout(layout)

        self.setCentralWidget(widget)
示例#3
0
    def setup_actions(self):
        """Set up the relevant actions, tooltips, and load the RC file."""

        self.create_actions()
        self.setup_tooltips()
        self.setup_action_collection()

        # Connect signals
        self.connect_action.triggered.connect(self.connect)
        self.fetch_action.triggered.connect(self.get_posts)
        self.clean_action.triggered.connect(self.clean_cache)
        self.batch_download_action.triggered.connect(self.batch_download)
        self.pool_toggle_action.toggled.connect(self.pool_toggle)
        self.tag_display_action.activeChanged.connect(self.tag_display)

        window_options = self.StandardWindowOption(self.ToolBar | self.Keys
                                                   | self.Create | self.Save
                                                   | self.StatusBar)

        setupGUI_args = [
            QSize(500, 400),
            self.StandardWindowOption(window_options)
        ]

        #Check first in standard locations for danbooruui.rc

        rc_file = KStandardDirs.locate("appdata", "danbooruui.rc")

        if rc_file.isEmpty():
            setupGUI_args.append(os.path.join(sys.path[0], "danbooruui.rc"))
        else:
            setupGUI_args.append(rc_file)

        self.setupGUI(*setupGUI_args)
示例#4
0
 def loadSetup(self):
     indihostfile = QtCore.QFile(
         KStandardDirs.locate("data", "kstars/indihosts.xml"))
     #print(indihostfile.fileName())
     if ((indihostfile.size() == 0)
             or not (indihostfile.open(QtCore.QIODevice.ReadOnly))):
         return
     handler = XmlIndiHostHandler(self)
     xmlreader = QtXml.QXmlSimpleReader()
     xmlreader.setContentHandler(handler)
     xmlreader.setErrorHandler(handler)
     source = QtXml.QXmlInputSource(indihostfile)
     ok = xmlreader.parse(source, True)
     #while (source.data() != ""):
     #source.reset()
     #ok=xmlreader.parseContinue()
     #xmlreader=QtCore.QXmlStreamReader(indihostfile)
     #ok=True
     #while not(xmlreader.atEnd()):
     #  xmlreader.readNext()
     #  if xmlreader.isStartElement():
     #    print("xml token name " + xmlreader.name().toString())
     #if xmlreader.hasError():
     #  ok=False
     if not (ok):
         print("Failed to load indihosts setup")
示例#5
0
    def __init__(self, parent=None):
        KVBox.__init__(self, parent)
        self.help  = QLabel (i18n (helpText), self)
        self.layout ().setAlignment (self.help, Qt.AlignHCenter)
        self.setSpacing (10)
        
        hBox          = KHBox (self)
        self.layout ().setAlignment (hBox, Qt.AlignHCenter)
        
        cBox          = KVBox (hBox)
        hBox.layout ().setAlignment (cBox, Qt.AlignTop)
        hBox.setSpacing (25)
        hBox.setMargin (10)

        self.stdDirs  = KStandardDirs ()
        types         = self.stdDirs.allTypes ()
        
        comboLbl      = QLabel ("Types", cBox)
        combo         = KComboBox (cBox)        
        combo.addItems (types)
        cBox.layout ().setAlignment (comboLbl, Qt.AlignTop)
        cBox.layout ().setAlignment (combo, Qt.AlignTop)
        
        self.connect (combo, SIGNAL ("currentIndexChanged (const QString&)"), self.slotIndexChanged)

        lBox          = KVBox (hBox)
        listLbl       = QLabel ("Directories", lBox)
        self.location = KListWidget (lBox)
        self.location.setMaximumSize (400, 200)
        lBox.layout ().setAlignment (listLbl, Qt.AlignTop)
        lBox.layout ().setAlignment (self.location, Qt.AlignTop)

        QLabel (self.stdDirs.installPath ("ui"), self)

        self.slotIndexChanged (combo.currentText ())
示例#6
0
    def setup_actions(self):

        """Set up the relevant actions, tooltips, and load the RC file."""

        self.create_actions()
        self.setup_tooltips()
        self.setup_action_collection()

        # Connect signals
        self.connect_action.triggered.connect(self.connect)
        self.fetch_action.triggered.connect(self.get_posts)
        self.clean_action.triggered.connect(self.clean_cache)
        self.batch_download_action.triggered.connect(self.batch_download)
        self.pool_toggle_action.toggled.connect(self.pool_toggle)
        self.tag_display_action.activeChanged.connect(self.tag_display)

        window_options = self.StandardWindowOption(self.ToolBar| self.Keys |
                                                   self.Create | self.Save |
                                                   self.StatusBar)

        setupGUI_args = [
            QSize(500, 400), self.StandardWindowOption(window_options)
        ]

        #Check first in standard locations for danbooruui.rc

        rc_file = KStandardDirs.locate("appdata", "danbooruui.rc")

        if rc_file.isEmpty():
            setupGUI_args.append(os.path.join(sys.path [0],
                                              "danbooruui.rc"))
        else:
            setupGUI_args.append(rc_file)

        self.setupGUI(*setupGUI_args)
示例#7
0
    def setup_welcome_widget(self):

        """Load the welcome widget at startup."""

        widget = QWidget()
        layout = QVBoxLayout()

        welcome = QLabel(parent=self)
        pix = QPixmap(KStandardDirs.locate("appdata","logo.png"))

        welcome.setPixmap(pix)
        welcome.setAlignment(Qt.AlignCenter)

        self.first_fetch_widget = connectwidget.ConnectWidget(
        self.preferences.boards_list, self)

        self.statusbar.addPermanentWidget(self.first_fetch_widget, 300)

        self.first_fetch_widget.connectionEstablished.connect(
            self.handle_connection)
        self.first_fetch_widget.rejected.connect(
            self.first_fetch_widget.hide)

        self.first_fetch_widget.hide()

        self.first_fetch_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)

        layout.addWidget(self.first_fetch_widget)
        layout.addWidget(welcome)
        widget.setLayout(layout)

        self.setCentralWidget(widget)
示例#8
0
class MainFrame(KVBox):
    """Example class showing the use of KStandardDirs."""
    def __init__(self, parent=None):
        super(KVBox, self).__init__(parent)
        self.help = QLabel(i18n(helpText), self)
        self.layout().setAlignment(self.help, Qt.AlignHCenter)
        self.setSpacing(10)

        hBox = KHBox(self)
        self.layout().setAlignment(hBox, Qt.AlignHCenter)

        cBox = KVBox(hBox)
        hBox.layout().setAlignment(cBox, Qt.AlignTop)
        hBox.setSpacing(25)
        hBox.setMargin(10)

        self.stdDirs = KStandardDirs()
        types = self.stdDirs.allTypes()

        comboLbl = QLabel("Types", cBox)
        combo = KComboBox(cBox)
        combo.addItems(types)
        cBox.layout().setAlignment(comboLbl, Qt.AlignTop)
        cBox.layout().setAlignment(combo, Qt.AlignTop)

        # We're calling the QString version of the signal, as
        # currentIndexChanged can also be emitted with an int (the index that
        # changed)

        combo.currentIndexChanged[QString].connect(self.slotIndexChanged)

        lBox = KVBox(hBox)
        listLbl = QLabel("Directories", lBox)
        self.location = KListWidget(lBox)
        self.location.setMaximumSize(400, 200)
        lBox.layout().setAlignment(listLbl, Qt.AlignTop)
        lBox.layout().setAlignment(self.location, Qt.AlignTop)

        QLabel(self.stdDirs.installPath("ui"), self)

        self.slotIndexChanged(combo.currentText())

    def slotIndexChanged(self, text):
        """Slot connected to currentIndexChanged."""

        self.location.clear()
        self.location.insertItems(0, self.stdDirs.resourceDirs(unicode(text)))
示例#9
0
文件: util.py 项目: cburgmer/eclectus
def getDataPaths():
    paths = []
    absPath = unicode(KStandardDirs.installPath('data'))
    if absPath:
        paths.append(os.path.join(absPath, 'eclectus', 'data'))
    if localDataDir:
        paths.append(localDataDir)
    return paths
示例#10
0
 def __init__(self):
     self.lexer = lex.lex(module=self)
     #
     # To enable generation of parser.out, debug = 1
     #
     self.parser = yacc.yacc(module = self, debug = 0, \
             tabmodule = __name__ + "generated", \
             outputdir = str(KStandardDirs().saveLocation("tmp")))
示例#11
0
文件: util.py 项目: cburgmer/eclectus
def getData(fileName):
    global localDataDir

    absPath = unicode(KStandardDirs.locate('data',
        os.path.join('eclectus', fileName)))
    if absPath:
        return absPath
    elif localDataDir:
        return os.path.join(localDataDir, fileName)
示例#12
0
 def config(self) :
     if self.sharedconfig == None :
         rcpath = KStandardDirs.locateLocal("config", "fb-plasmoidrc")
         self.sharedconfig = KSharedConfig.openConfig(rcpath)
         
         self.initSettings()
         self.writeSettings()
     
     return KConfigGroup(self.sharedconfig, "main")
示例#13
0
    def __init__ (self, parent, path="", relative=False, busName=None, busPath=None):
        SatyrObject.__init__ (self, parent, busName, busPath)


        self.songs= []
        self.count= 0
        # (re)defined by an aggregator if we're in one of those
        self.offset= 0

        # BUG: path is not reread from the config file!
        # it breaks rescanning
        self.configValues= (
            ('path', str, path),
            )
        self.loadConfig ()
        # print busPath, self.path

        # if the user requests a new path, use it
        if self.path!=path and path!="":
            path= os.path.abspath (path)
            self.path= path
            self.forceScan= True
            logger.info ("new path, forcing (re)scan")
        else:
            self.forceScan= False
        self.relative= relative
        logger.debug ("Collection(): %s", self.path)

        self.watch= KDirWatch (self)
        self.watch.addDir (self.path,
            KDirWatch.WatchMode (KDirWatch.WatchFiles|KDirWatch.WatchSubDirs))
        self.watch.created.connect (self.newFiles)

        self.scanners= []
        self.scanning= False
        self.loadMetadata= False

        if busPath is not None:
            self.collectionFile= str (KStandardDirs.locateLocal ('data', 'satyr/%s.tdb' % self.dbusName (busPath)))
        else:
            self.collectionFile= str (KStandardDirs.locateLocal ('data', 'satyr/collection.tdb'))
示例#14
0
    def getWallpaperSettings(self):
        lst = KStandardDirs().findAllResources("wallpaper",
                                               "*metadata.desktop",
                                               KStandardDirs.Recursive)

        items = []
        for desktopFiles in lst:
            wallpaper = {}
            parser = DesktopParser()
            parser.read(str(desktopFiles))

            try:
                wallpaper["wallpaperTitle"] = parser.get_locale(
                    'Desktop Entry', 'Name[%s]' % self.catLang, '')
            except:
                wallpaper["wallpaperTitle"] = parser.get_locale(
                    'Desktop Entry', 'Name', '')

            try:
                wallpaper["wallpaperDesc"] = parser.get_locale(
                    'Desktop Entry', 'X-KDE-PluginInfo-Author', '')
            except:
                wallpaper["wallpaperDesc"] = "Unknown"

                # Get all files in the wallpaper's directory
            thumbFolder = os.listdir(
                os.path.join(os.path.split(str(desktopFiles))[0], "contents"))

            #    """
            #    Appearantly the thumbnail names doesn't have a standart.
            #    So we get the file list from the contents folder and
            #    choose the file which has a name that starts with "scre".

            #    File names I've seen so far;
            #    screenshot.jpg, screnshot.jpg, screenshot.png, screnshot.png
            #    """

            wallpaper["wallpaperThumb"] = ""

            for thumb in thumbFolder:
                if thumb.startswith('scre'):
                    wallpaper["wallpaperThumb"] = os.path.join(
                        os.path.split(str(desktopFiles))[0],
                        "contents/" + thumb)

            wallpaper["wallpaperFile"] = os.path.split(str(desktopFiles))[0]

            items.append(wallpaper)

        return items
示例#15
0
def installOkularPartRC():
    """ Set our custom editor command in okularpartrc """
    # determine the command needed to run us
    command = sys.argv[0]
    if os.path.sep in command: # does the command contain a directory separator?
        if not os.path.isabs(command):
            command = os.path.abspath(command)
        if command == KStandardDirs.findExe("frescobaldi"):
            command = "frescobaldi"
    command += " --smart --line %l --column %c"
    okularpartrc = KConfig("okularpartrc", KConfig.NoGlobals)
    group = okularpartrc.group("General")
    group.writeEntry("ExternalEditor", "Custom")
    group.writeEntry("ExternalEditorCommand", command)
    if not group.readEntry("WatchFile", True):
        group.writeEntry("WatchFile", True)
    group.sync()
示例#16
0
def getKDE4HomePath():
    if isAvailableKDE4():
        try:
            if isActivePyKDE4:
                from PyKDE4.kdecore import KStandardDirs

                kdedirPath = str(KStandardDirs().localkdedir())
                if kdedirPath[-1] == os.sep:
                    kdedirPath = kdedirPath[:-1]
            else:
                from Core import Execute

                kdedirPath = Execute.getCommandResult(
                    ["kde4-config", "--localprefix"])[:-2]
            return kdedirPath
        except:
            pass
    if fu.isDir(fu.joinPath(fu.userDirectoryPath, ".kde4", "share", "config")):
        return fu.joinPath(fu.userDirectoryPath, ".kde4")
    else:
        return fu.joinPath(fu.userDirectoryPath, ".kde")
示例#17
0
 def __init__(self):
     self.dbFile = KStandardDirs.locateLocal("data","getstuffback/db.pickle")
     if exists(self.dbFile):
         tree = etree.parse(self.dbFile)
         for loan in tree.getroot():
             l = Loan()
             for attrNode in loan:
                 if (attrNode.tag in ['date','expected_date']) and (
                                                 attrNode.text is not None):
                     try:
                         dateObj = datetime.strptime(attrNode.text,
                                                         "%Y-%m-%dT%H:%M:%f")
                         l[attrNode.tag] = dateObj
                     except ValueError:
                         pass # ignore invalid data
                 else:
                     l[attrNode.tag] = attrNode.text
             self.loans.append(l)
             
         # flush memory
         del(tree)
示例#18
0
 def loadSetup(self):
   indihostfile=QtCore.QFile(KStandardDirs.locate("data", "kstars/indihosts.xml"))
   #print(indihostfile.fileName())
   if ((indihostfile.size() == 0) or not(indihostfile.open(QtCore.QIODevice.ReadOnly))):
     return
   handler=XmlIndiHostHandler(self)
   xmlreader=QtXml.QXmlSimpleReader()
   xmlreader.setContentHandler(handler)
   xmlreader.setErrorHandler(handler)
   source=QtXml.QXmlInputSource(indihostfile)
   ok=xmlreader.parse(source, True)
   #while (source.data() != ""):
     #source.reset()
     #ok=xmlreader.parseContinue()
   #xmlreader=QtCore.QXmlStreamReader(indihostfile)
   #ok=True
   #while not(xmlreader.atEnd()):
   #  xmlreader.readNext()
   #  if xmlreader.isStartElement():
   #    print("xml token name " + xmlreader.name().toString())
   #if xmlreader.hasError():
   #  ok=False
   if not(ok):
     print("Failed to load indihosts setup")
示例#19
0
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, None)
        self.ui = Ui_wallpaperWidget()
        self.ui.setupUi(self)
        # Get system locale
        self.catLang = KGlobal.locale().language()

        isWide = lambda x: float(x[0]) / float(x[1]) >= 1.6
        isSquare = lambda x: float(x[0]) / float(x[1]) < 1.6

        # Get screen resolution
        rect = QtGui.QDesktopWidget().screenGeometry()

        # Get metadata.desktop files from shared wallpaper directory
        lst = KStandardDirs().findAllResources("wallpaper",
                                               "*metadata.desktop",
                                               KStandardDirs.Recursive)

        for desktopFiles in lst:
            parser = DesktopParser()
            parser.read(str(desktopFiles))

            try:
                wallpaperTitle = parser.get_locale('Desktop Entry',
                                                   'Name[%s]' % self.catLang,
                                                   '')
            except:
                wallpaperTitle = parser.get_locale('Desktop Entry', 'Name', '')

            try:
                wallpaperDesc = parser.get_locale('Desktop Entry',
                                                  'X-KDE-PluginInfo-Author',
                                                  '')
            except:
                wallpaperDesc = "Unknown"

            # Get all files in the wallpaper's directory
            l = os.listdir(
                os.path.join(
                    os.path.split(str(desktopFiles))[0], "contents/images"))

            wallpaperFile = os.path.split(str(desktopFiles))[0]
            wallpaperThumb = os.path.join(
                os.path.split(str(desktopFiles))[0], "contents/screenshot.png")

            # Insert wallpapers to listWidget.
            item = QtGui.QListWidgetItem(self.ui.listWallpaper)
            # Each wallpaper item is a widget. Look at widgets.py for more information.
            widget = WallpaperItemWidget(unicode(wallpaperTitle),
                                         unicode(wallpaperDesc),
                                         wallpaperThumb, self.ui.listWallpaper)
            item.setSizeHint(QSize(38, 110))
            self.ui.listWallpaper.setItemWidget(item, widget)
            # Add a hidden value to each item for detecting selected wallpaper's path.
            item.setStatusTip(wallpaperFile)

        self.ui.listWallpaper.connect(self.ui.listWallpaper,
                                      SIGNAL("itemSelectionChanged()"),
                                      self.setWallpaper)
        self.ui.checkBox.connect(self.ui.checkBox, SIGNAL("stateChanged(int)"),
                                 self.disableWidgets)
        self.ui.buttonChooseWp.connect(self.ui.buttonChooseWp,
                                       SIGNAL("clicked()"),
                                       self.selectWallpaper)
示例#20
0
文件: util.py 项目: cburgmer/eclectus
def getLocalData(fileName):
    return KStandardDirs.locateLocal('data', os.path.join('eclectus', fileName))
示例#21
0
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, None)
        self.ui = Ui_wallpaperWidget()
        self.ui.setupUi(self)
        # Get system locale
        self.catLang = KGlobal.locale().language()

        # Get screen resolution
        # rect = QtGui.QDesktopWidget().screenGeometry() FIXME: where could
        # this be needed?

        # Get metadata.desktop files from shared wallpaper directory
        lst = KStandardDirs().findAllResources("wallpaper",
                                               "*metadata.desktop",
                                               KStandardDirs.Recursive)

        for desktopFiles in lst:
            parser = DesktopParser()
            parser.read(str(desktopFiles))

            try:
                wallpaperTitle = parser.get_locale('Desktop Entry',
                                                   'Name[%s]' % self.catLang,
                                                   '')
            except:
                wallpaperTitle = parser.get_locale('Desktop Entry', 'Name', '')

            try:
                wallpaperDesc = parser.get_locale('Desktop Entry',
                                                  'X-KDE-PluginInfo-Author',
                                                  '')
            except:
                wallpaperDesc = "Unknown"

            # Get all files in the wallpaper's directory
            try:
                thumbFolder = os.listdir(
                    os.path.join(
                        os.path.split(str(desktopFiles))[0], "contents"))
            except OSError:
                thumbFolder = os.listdir(
                    os.path.join(
                        os.path.split(str(desktopFiles))[0], "content"))
            """
            Appearantly the thumbnail names doesn't have a standard.
            So we get the file list from the contents folder and
            choose the file which has a name that starts with "scre".

            File names I've seen so far;
            screenshot.jpg, screnshot.jpg, screenshot.png, screnshot.png
            """

            wallpaperThumb = ""

            for thumb in thumbFolder:
                if thumb.startswith('scre'):
                    wallpaperThumb = os.path.join(
                        os.path.split(str(desktopFiles))[0],
                        "contents/" + thumb)

            wallpaperFile = os.path.split(str(desktopFiles))[0]

            # Insert wallpapers to listWidget.
            item = QtGui.QListWidgetItem(self.ui.listWallpaper)
            # Each wallpaper item is a widget. Look at widgets.py for more information.
            widget = WallpaperItemWidget(
                unicode(wallpaperTitle, "utf8", "replace"),
                unicode(wallpaperDesc, "utf8", "replace"), wallpaperThumb,
                self.ui.listWallpaper)
            item.setSizeHint(QSize(120, 170))
            self.ui.listWallpaper.setItemWidget(item, widget)
            # Add a hidden value to each item for detecting selected wallpaper's path.
            item.setStatusTip(wallpaperFile)

        self.ui.listWallpaper.itemSelectionChanged.connect(self.setWallpaper)
        self.ui.checkBox.stateChanged.connect(self.disableWidgets)
        self.ui.buttonChooseWp.clicked.connect(self.selectWallpaper)
示例#22
0
def printFiles(fileNames, printer):
    """Prints a list of files (PS or PDF) via a printer command.

    The printer command is constructed by quering the QPrinter object.
    If there is more than one PDF file, print to file should have been disabled
    in the QPrintDialog that configured the printer.
    
    """
    output = printer.outputFileName()
    if output:
        # Print to File, determine suffixes, assume one file
        fileName = fileNames[0]
        inext, outext = (os.path.splitext(name)[1].lower() for name in (fileName, output))
        if inext == outext:
            # just copy
            shutil.copyfile(fileName, output)
        else:
            cmd = "pdf2ps" if outext == ".ps" else "ps2pdf"
            try:
                ret = subprocess.call([cmd, fileName, output])
                if ret:
                    raise CommandFailed(KShell.joinArgs([cmd, fileName, output]), ret)
            except OSError:
                raise CommandNotFound(cmd)
        return

    # print to a printer

    cmd = []

    # Which exe?
    for exe in "lpr-cups", "lpr.cups", "lpr", "lp":
        if KStandardDirs.findExe(exe):
            break
    else:
        raise NoPrintCommandFound()

    cmd.append(exe)

    # Add the arguments.

    # printer name
    if exe == "lp":
        cmd.append("-d")
    else:
        cmd.append("-P")
    cmd.append(printer.printerName())

    # helper for adding (Cups) options to the command line
    def option(s):
        cmd.append("-o")
        cmd.append(s)

    # copies
    try:
        copies = printer.actualNumCopies()
    except AttributeError:  # only available in Qt >= 4.6
        copies = printer.numCopies()

    if exe == "lp":
        cmd.append("-n")
        cmd.append(format(copies))
    else:
        cmd.append("-#{0}".format(copies))

    # job name
    if printer.docName():
        if exe == "lp":
            cmd.append("-t")
            cmd.append(printer.docName())
        elif exe.startswith("lpr"):
            cmd.append("-J")
            cmd.append(printer.docName())

    # page range
    if printer.printRange() == QPrinter.PageRange:
        pageRange = "{0}-{1}".format(printer.fromPage(), printer.toPage())
        if exe == "lp":
            cmd.append("-P")
            cmd.append(pageRange)
        else:
            option("page-ranges={0}".format(pageRange))

    # CUPS-specific options; detect if CUPS is available.
    test = QPrinter()
    test.setNumCopies(2)
    cups = test.numCopies() == 1

    if cups:

        # media, size etc.
        media = []
        size = printer.paperSize()
        if size == QPrinter.Custom:
            media.append("Custom.{0}x{1}mm".format(printer.heightMM(), printer.widthMM()))
        elif size in PAGE_SIZES:
            media.append(PAGE_SIZES[size])

        # media source
        source = printer.paperSource()
        if source in PAPER_SOURCES:
            media.append(PAPER_SOURCES[source])

        if media:
            option("media={0}".format(",".join(media)))

        # orientation
        orientation = printer.orientation()
        if orientation in ORIENTATIONS:
            option(ORIENTATIONS[orientation])

        # double sided
        duplex = printer.duplex()
        if duplex == QPrinter.DuplexNone:
            option("sides=one-sided")
        elif duplex == QPrinter.DuplexAuto:
            if orientation == QPrinter.Landscape:
                option("sides=two-sided-short-edge")
            else:
                option("sides=two-sided-long-edge")
        elif duplex == QPrinter.DuplexLongSide:
            option("sides=two-sided-long-edge")
        elif duplex == QPrinter.DuplexShortSide:
            option("sides=two-sided-short-edge")

        # page order
        if printer.pageOrder() == QPrinter.LastPageFirst:
            option("outputorder=reverse")
        else:
            option("outputorder=normal")

        # collate copies
        if printer.collateCopies():
            option("Collate=True")
        else:
            option("Collate=False")

        # page margins
        if printer.printEngine().property(QPrintEngine.PPK_PageMargins):
            left, top, right, bottom = printer.getPageMargins(QPrinter.Point)
            option("page-left={0}".format(left))
            option("page-top={0}".format(top))
            option("page-right={0}".format(right))
            option("page-bottom={0}".format(bottom))

        # cups properties
        properties = printer.printEngine().property(QPrintEngine.PrintEnginePropertyKey(0xFE00))
        for name, value in zip(*repeat(iter(properties), 2)):
            option("{0}={1}".format(name, value) if value else name)

    # file names
    cmd.extend(fileNames)
    try:
        ret = subprocess.call(cmd)
        if ret:
            raise CommandFailed(KShell.joinArgs(cmd), ret)
    except OSError:
        raise CommandNotFound(cmd[0])
示例#23
0
    def __initUI(self):
        """Initialize the interface"""

        # Locate the ui for the main window and load it.
        if 'USBCREATOR_LOCAL' in os.environ:
            appdir = os.path.join(os.getcwd(), 'gui')
        else:
            file = KStandardDirs.locate("appdata", self.__mainWindow_ui)
            appdir = file[:file.rfind("/")]
        uic.loadUi(misc.text_type(appdir + "/" + self.__mainWindow_ui), self.__mainWindow)

        #set default persist size
        self.__mainWindow.ui_persist_label.setText(misc.format_mb_size(128))

        #set persistent ui elements state
        if self.__persistent:
            self.__mainWindow.ui_persist_enabled.setChecked(True)
            self.__mainWindow.ui_persist_text.setEnabled(True)
            self.__mainWindow.ui_persist_slider.setEnabled(True)
            self.__mainWindow.ui_persist_label.setEnabled(True)
        else:
            self.__mainWindow.ui_persist_disabled.setChecked(True)
            self.__mainWindow.ui_persist_frame.hide()

        #hide sources if an argument was provided
        if self.__img is not None:
            self.__mainWindow.ui_source_list.hide()
            self.__mainWindow.ui_add_source.hide()
            self.__mainWindow.insert_label.hide()
            self.__mainWindow.source_label.hide()

        #disable the start button and persist frame by default
        self.__mainWindow.ui_persist_frame.setEnabled(False)
        self.__mainWindow.ui_start_button.setEnabled(False)

        #add some buttons
        self.__mainWindow.ui_quit_button.setIcon(KIcon("application-exit"))
        self.__mainWindow.ui_start_button.setIcon(KIcon("dialog-ok-apply"))
        self.__mainWindow.ui_add_source.setIcon(KIcon("media-optical"))
        self.__mainWindow.ui_format_dest.setIcon(KIcon("drive-removable-media-usb-pendrive"))

        #set up signals
        self.connect(self.__mainWindow.ui_add_source,SIGNAL('clicked()'),
            self.add_file_source_dialog)
        self.connect(self.__mainWindow.ui_persist_slider,SIGNAL('valueChanged(int)'),
            lambda value: self.__mainWindow.ui_persist_label.setText(misc.format_mb_size(value)))
        self.connect(self.__mainWindow.ui_quit_button,SIGNAL('clicked()'),
            self.quit)
        self.connect(self.__mainWindow.ui_start_button,SIGNAL('clicked()'),
            self.install)
        self.connect(self.__mainWindow.ui_dest_list,SIGNAL(
            'currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            self.dest_selection_changed)
        self.connect(self.__mainWindow.ui_source_list,SIGNAL(
            'currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            self.source_selection_changed)
        self.connect(self.__mainWindow.ui_format_dest,SIGNAL('clicked()'),
            self.format_dest_clicked)

        self.__mainWindow.ui_source_list.setSortingEnabled(True)
        self.__mainWindow.ui_source_list.sortByColumn(0, Qt.AscendingOrder)
        self.__mainWindow.ui_dest_list.setSortingEnabled(True)
        self.__mainWindow.ui_dest_list.sortByColumn(0, Qt.AscendingOrder)
        self.progress_bar = QProgressDialog("",i18n('Cancel'),0,100,self.__mainWindow)
        #set title of progress window (same as gtk frontend)
        self.progress_bar.setWindowTitle(_('Installing'))
        #prevent progress bar from emitting reset on reaching max value (and auto closing)
        self.progress_bar.setAutoReset(False)
        #force immediate showing, rather than waiting...
        self.progress_bar.setMinimumDuration(0)
        #must disconnect the canceled() SIGNAL, otherwise the progress bar is actually destroyed
        self.disconnect(self.progress_bar,SIGNAL('canceled()'),self.progress_bar.cancel)
        #now we connect our own signal to display a warning dialog instead
        self.connect(self.progress_bar,SIGNAL('canceled()'),self.warning_dialog)

        #show the window
        self.__mainWindow.show()
示例#24
0
    def __initUI(self):
        """Initialize the interface"""

        # Locate the ui for the main window and load it.
        if os.path.exists(self.__mainWindow_ui):
            appdir = QDir.currentPath()
        else:
            file =  KStandardDirs.locate("appdata", self.__mainWindow_ui)
            appdir = file.left(file.lastIndexOf("/"))
        uic.loadUi(appdir + "/" + self.__mainWindow_ui, self.__mainWindow)

        #set default persist size
        self.__mainWindow.ui_persist_label.setText(format_mb_size(128))

        #set persistent ui elements state
        if self.__persistent:
            self.__mainWindow.ui_persist_enabled.setChecked(True)
            self.__mainWindow.ui_persist_text.setEnabled(True)
            self.__mainWindow.ui_persist_slider.setEnabled(True)
            self.__mainWindow.ui_persist_label.setEnabled(True)
        else:
            self.__mainWindow.ui_persist_disabled.setChecked(True)
            self.__mainWindow.ui_persist_text.setDisabled(True)
            self.__mainWindow.ui_persist_slider.setDisabled(True)
            self.__mainWindow.ui_persist_label.setDisabled(True)

        #disable the start button and persist frame by default
        self.__mainWindow.ui_persist_frame.setEnabled(False)
        self.__mainWindow.ui_start_button.setEnabled(False)


        #add some buttons
        self.__mainWindow.ui_quit_button.setIcon(KIcon("application-exit"))
        self.__mainWindow.ui_start_button.setIcon(KIcon("dialog-ok-apply"))
        self.__mainWindow.ui_add_source.setIcon(KIcon("media-optical"))
        self.__mainWindow.ui_format_dest.setIcon(KIcon("drive-removable-media-usb-pendrive"))

        #set up signals
        self.connect(self.__mainWindow.ui_add_source,SIGNAL('clicked()'),
            self.add_file_source_dialog)
        self.connect(self.__mainWindow.ui_persist_slider,SIGNAL('valueChanged(int)'),
            lambda value: self.__mainWindow.ui_persist_label.setText(format_mb_size(value)))
        self.connect(self.__mainWindow.ui_quit_button,SIGNAL('clicked()'),
            self.quit)
        self.connect(self.__mainWindow.ui_start_button,SIGNAL('clicked()'),
            self.install)
        self.connect(self.__mainWindow.ui_dest_list,SIGNAL(
            'currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            self.dest_selection_changed)
        self.connect(self.__mainWindow.ui_source_list,SIGNAL(
            'currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            self.source_selection_changed)
        self.connect(self.__mainWindow.ui_format_dest,SIGNAL('clicked()'),
            self.format_dest_clicked)

        self.progress_bar = QProgressDialog("","Cancel",0,100,self.__mainWindow)
        #prevent progress bar from emitting reset on reaching max value (and auto closing)
        self.progress_bar.setAutoReset(False)
        #force immediate showing, rather than waiting...
        self.progress_bar.setMinimumDuration(0)
        #must disconnect the canceled() SIGNAL, otherwise the progress bar is actually destroyed
        self.disconnect(self.progress_bar,SIGNAL('canceled()'),self.progress_bar.cancel)
        #now we connect our own signal to display a warning dialog instead
        self.connect(self.progress_bar,SIGNAL('canceled()'),self.warning_dialog)

        #show the window
        self.__mainWindow.show()
示例#25
0
# -*- coding: utf-8 -*-
from PyKDE4.kdecore import KStandardDirs
from PyQt4.QtCore import QString, QDir

from time import strftime, localtime, asctime
import distutils.dir_util as DirUtil
import git
import os

# Path to konfig-tracker db
db_path = str(KStandardDirs().localkdedir() + "konfigtracker-db")

# Source path of configuration files
source_path = str(KStandardDirs().localkdedir() + "share/config")
restore_path = str(KStandardDirs().localkdedir() + "share/config")


def createDatabase(path):
    """
	Initialize a git repository in path.
	"""
    gitRepo = git.Git(path)
    gitRepo.init()


def gitCommit():
    backupTime = strftime("%d %b %Y %H:%M:%S, %a", localtime())
    repo = git.Git(db_path)
    message = "Configuration Backup on : " + backupTime
    try:
        repo.execute(["git", "commit", "-a", "-m", message])