Esempio n. 1
0
 def backup(self):
     model = self.state.model
     if not model:
         return
     widget = QApplication.focusWidget()
     filename = Lib.incrementedFilename(model.filename)
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         filename, _ = QFileDialog.getSaveFileName(
             self.window,
             "Backup Index — {}".format(QApplication.applicationName()),
             filename,
             "{} index (*{})".format(QApplication.applicationName(),
                                     EXTENSION))
     if filename:
         with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
             self.state.saving = True
             try:
                 self.state.maybeSave()
                 if not filename.endswith(EXTENSION):
                     filename += EXTENSION
                 say("Backing up to “{}”...".format(
                     QDir.toNativeSeparators(filename)))
                 model.optimize()
                 model.backup(filename, "Backing up",
                              self.window.reportProgress)
                 say("Backed up to “{}”".format(
                     QDir.toNativeSeparators(filename)))
             finally:
                 self.state.saving = False
     Lib.restoreFocus(widget)
Esempio n. 2
0
def getProjectFile(filename=None):
    d = QDir()
    d.cd(app.manifest.get('gendir',"bin")) # cd into the directory we generate to
    if filename is None:    # we want just the generation directory
        return d.absolutePath()  # so return the absolute path   
    else:                   # the only other option is a file in the gendir
        return d.absoluteFilePath(filename) # so give the absolute path to that file
Esempio n. 3
0
    def render(self, fileName, width, height):
        self.setViewportSize(QSize(width, height))

        fileInfo = QFileInfo(fileName)
        dir = QDir()
        dir.mkpath(fileInfo.absolutePath())
        viewportSize = self.viewportSize()
        pageSize = self.mainFrame().contentsSize()
        if pageSize.isEmpty():
            return False

        buffer = QImage(pageSize, QImage.Format_ARGB32)
        buffer.fill(qRgba(255, 255, 255, 0))
        p =  QPainter(buffer)

        p.setRenderHint( QPainter.Antialiasing,          True)
        p.setRenderHint( QPainter.TextAntialiasing,      True)
        p.setRenderHint( QPainter.SmoothPixmapTransform, True)

        self.setViewportSize(pageSize)
        self.mainFrame().render(p)
        p.end()

        self.setViewportSize(viewportSize)

        return buffer.save(fileName)
Esempio n. 4
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setupUi(self)

        self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, COMPANY, APPNAME)
        self.restoreGeometry(self.settings.value(self.__class__.__name__))

        self.images = []

        if len(sys.argv) > 1:
            d = QDir(path=sys.argv[1])
        else:
            d = QDir(path=QFileDialog.getExistingDirectory())

        d.setNameFilters(['*.png'])
        d.setFilter(QDir.Files or QDir.NoDotAndDotDot)

        d = QDirIterator(d)

        images = []

        while d.hasNext():
            images.append(d.next())

        for i in images:
            print i

        self.images = [QImage(i) for i in images]
        self.images += [crop_image_from_file(i, 50)[0] for i in images]
Esempio n. 5
0
    def __init__(self, parent=None, common_name=None, image=None):
        QtGui.QDialog.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        types = controller.get_types()
        self.directory = QDir.root()
        self.display = QGraphicsView()
        self.ui.scrollArea.setWidget(self.display)
        for tipo in types:
            self.ui.typeBox.addItem(tipo["nombre"], tipo["id_tipo"])

        if common_name is None:
            self.ui.btn_done.clicked.connect(self.add)
            if image is None:
                self.ui.image.setPlainText(image)
        else:
            self.setWindowTitle(u"Editar animal")
            self.common = common_name
            animal_data = controller.get_animal(common_name)
            self.ui.common_name.setPlainText(animal_data["nombre_comun"])
            self.ui.cientific_name.setText(animal_data["nombre_cientifico"])
            self.ui.data.setText(animal_data["datos"])
            tipo = self.ui.typeBox.currentText()
            id_type = controller_form.get_id_type(tipo)

            id_animal = controller_form.get_id_animal(common_name)
            self.image = controller_form.get_image(id_animal)
            if self.image:
                self.path = QDir.currentPath() + "/images/" + self.image[0] + self.image[1]
                self.ui.image.setPlainText(self.path)
                Ifile = QFileInfo(self.path)
                pixImage = controller_form.get_root_image(self.path)
                item = QGraphicsPixmapItem(pixImage.scaled(100,100))
                scene = QGraphicsScene()
                scene.addItem(item)
                self.display.setScene(scene)
                self.ui.image.setPlainText(self.path)
            else:
                noimage = controller_form.no_image()
                item = QGraphicsPixmapItem(noimage.scaled(100,100))
                scene = QGraphicsScene()
                scene.addItem(item)
                self.display.setScene(scene)
                scene = QGraphicsScene()
                scene.addItem(item)
                self.display.setScene(scene)
                self.path = ""
                self.ui.image.setPlainText(self.path)

            self.ui.btn_done.clicked.connect(self.edit)
        self.ui.btn_delete.clicked.connect(self.delete)
        self.ui.btn_open.clicked.connect(self.open)
        self.ui.btn_cancel.clicked.connect(self.cancel)
Esempio n. 6
0
def parse_interface(interfacename):
    tree = xmlparse("views" + QDir.separator() + interfacename + ".xml").getroot() # get the tree
    Compiler.current_interfacename = interfacename # set the current interfacename
    imported = [] # this is the list of interfaces to parse after this one
    
    Compiler.code += "from PySide.QtGui import *\nfrom PySide.QtCore import *\n" # import PySide
    Compiler.code += "from oxide.widgets.all import *\n" # import Oxide
    if interfacename == Compiler.start: # if this is the start interface, create a QApplication
        Compiler.code += "import sys\n"         # using sys.argv,
        Compiler.code += "app = OxideApplication(sys.argv)\n" # create a QApplication
        
    add_util_funcs() # add the utility functions
    
    add_model(interfacename,"__main__") # now add the model code to the output file
    
    for element in tree: # iterate through the elements in the tree
        if element.tag.lower() == "animations": # here we handle the special 'animations' tag
            Compiler.to_be_own_class = False # there is no way that we're in the resources tag here
            for animation in element: # go through each animation
                parse_animation(animation) # and parse it
        
        elif element.tag.lower() == "window": # here we handle the window
            Compiler.to_be_own_class = False # there is no way that we're in the resources tag here
            parse_toplevel(element)       # using parse_window
            
        elif element.tag.lower() == "resources":
            Compiler.to_be_own_class = True
            
            for child in element:
                Compiler.direct_resources_child = True
                parse_abstract_element(child)
                Compiler.direct_resources_child = False
                    
            Compiler.direct_resources_child = False
            
        elif element.tag.lower() == "import":
            Compiler.code += "import " + element.get('interface') + "\n"
            imported.append(element.get('interface'))
                    
    if interfacename == Compiler.start: # to finish up, if this is the start file
        Compiler.code += "sys.exit(app.exec_())\n" # run the application
    
    # now it has come time to put the code on the filesystem        
    if not QDir("bin").exists(): # if the 'bin' folder doesn't exist
        QDir().mkdir("bin")     # create it
    interfacefile = open(Compiler.gendir + QDir.separator() + interfacename + ".py", 'w')
    interfacefile.write(Compiler.code) # write Compiler.code to the file
    
    Compiler.code = "" # reset Compiler.code
    
    for interface in imported:
        parse_interface(interface)
Esempio n. 7
0
 def onBrowseClicked(self):
     """Slot. Called when the user clicks on the `browseButton` button"""
     
     # Presents the user with a native directory selector window
     localdir = QFileDialog.getExistingDirectory()
     localdir = QDir.fromNativeSeparators(localdir)
     if len(localdir) > 0:
         # If `localdir`'s value is good, store it using a `QSettings` object
         # and triggers a sync request.
         # Careful with '\' separators on Windows.
         localdir = QDir.toNativeSeparators(localdir)
         get_settings().setValue(SettingsKeys['localdir'], localdir)
         self.localdirEdit.setText(localdir)
Esempio n. 8
0
    def onBrowseClicked(self):
        """Slot. Called when the user clicks on the `browseButton` button"""

        # Presents the user with a native directory selector window
        localdir = QFileDialog.getExistingDirectory()
        localdir = QDir.fromNativeSeparators(localdir)
        if len(localdir) > 0:
            # If `localdir`'s value is good, store it using a `QSettings` object
            # and triggers a sync request.
            # Careful with '\' separators on Windows.
            localdir = QDir.toNativeSeparators(localdir)
            get_settings().setValue(SettingsKeys['localdir'], localdir)
            self.localdirEdit.setText(localdir)
    def on_change_root_path(self, current_path):
        if current_path == SOURCEIMAGES_TAG:
            current_path = os.path.join(
                cmds.workspace(query=True, rootDirectory=True),
                cmds.workspace(fileRuleEntry='sourceImages'))

        self.files_model.setRootPath(current_path)
        self.files_list.setRootIndex(self.files_model.index(current_path))
        if self.path_edit:
            self.path_edit.setText(current_path)

        if self.parent_folder_btn:
            current_dir = QDir(current_path)
            self.parent_folder_btn.setEnabled(current_dir.cdUp())
Esempio n. 10
0
def processModels():
    for filename in QDir("models").entryList(QDir.Files):
        out = ""
        for line in open("models" + QDir.separator() + filename).readlines():
            try:
                if not line.strip()[0] == "#":
                    if line[:8] == "from " + app.manifest.get('gendir',"bin"): out += "# " + line;
                    else: out += line
                else: out += line
            except IndexError: # it must have just been a newline (lstrip makes it ""), so there is no index 0
                out += "\n"
        f = open("models" + QDir.separator() + filename, 'w')
        f.write(out)
        f.close()
    def on_change_root_path(self, current_path):
        if current_path == SOURCEIMAGES_TAG:
            current_path = os.path.join(
                cmds.workspace(query=True, rootDirectory=True),
                cmds.workspace(fileRuleEntry='sourceImages')
            )

        self.files_model.setRootPath(current_path)
        self.files_list.setRootIndex(self.files_model.index(current_path))
        if self.path_edit:
            self.path_edit.setText(current_path)

        if self.parent_folder_btn:
            current_dir = QDir(current_path)
            self.parent_folder_btn.setEnabled(current_dir.cdUp())
Esempio n. 12
0
 def create_folder(self):
 	"""
     Crea carpeta de imagenes si no existe
     """
     self.directory = QDir.root()
     if not os.path.exists(self.directory.currentPath()+"/images"):
         os.makedirs(self.directory.currentPath()+"/images")
Esempio n. 13
0
def no_image():
    """
    Si no existe imagen carga una por defecto
    """
    path = QDir.currentPath() + "/images/noimage.jpg"
    pixMap = QPixmap(path)
    return pixMap
Esempio n. 14
0
def getConfigStyleDict():
    styledict = {} #initialize the new styledict
    
    # get the tree from the style.xml file
    tree = xmlparse("config" + QDir.separator() + "style.xml").getroot()
    
    for styletype in tree: # iterate over the types of widget
        styletype_key = styletype.tag.lower() if styletype.tag.lower().startswith("default-") else styletype.tag
        styledict[styletype_key] = {} # create a new dictionary for the style-type
        for state in States:
            styledict[styletype_key][state] = {}
        styledict[styletype_key]['normal'] = {}
        styledict[styletype_key]['durations'] = {}

        for styledef_or_statedef in styletype:
            if styledef_or_statedef.tag.lower() in States:
                for styledef in styledef_or_statedef:
                    styledict[styletype_key][styledef_or_statedef.tag.lower()][styledef.tag.lower()] = getValue(styledef)
            elif styledef_or_statedef.tag.lower() in StateTransitions:
                if styledef_or_statedef.get('time') is None:
                    raise StyleError(styletype.tag + " => " + styledef_or_statedef.tag + " must have 'time' attribute")
                styledict[styletype_key]['durations'][styledef_or_statedef.tag.lower()] = int(styledef_or_statedef.get('time'))
            else:
                for state in States:
                    styledict[styletype_key][state][styledef_or_statedef.tag.lower()] = getValue(styledef_or_statedef)
                styledict[styletype_key]['normal'][styledef_or_statedef.tag.lower()] = getValue(styledef_or_statedef)
        
    return styledict
Esempio n. 15
0
def root_abspath():
    global ROOT_ABSPATH
    if not ROOT_ABSPATH:
        from PySide.QtCore import QDir
        ROOT_ABSPATH = QDir.fromNativeSeparators(
            os.path.abspath(ROOT_LOCATION))
    return ROOT_ABSPATH
Esempio n. 16
0
 def fileOpen(self, lineEdit, filters):
     openFile = QFileDialog.getOpenFileName(self, "Find Files", QDir.currentPath(), filters="*." + filters)
     uiDebug(openFile)
     if openFile != None :
         lineEdit.setText(openFile[0])
         self.setUserConfig()
         self.showConfig()
Esempio n. 17
0
 def localFromServer(self, serverpath):
     # Removing leading '/' so `os.path.join` doesn't treat
     # `localpath` as an absolute path
     localpath = serverpath[1:] if serverpath.startswith('/') else serverpath
     localpath = QDir.toNativeSeparators(localpath)
     localpath = os.path.join(self.localdir, localpath)
     
     return localpath
Esempio n. 18
0
 def saveAs(self):  # No need to restore focus widget
     filename = self._getSaveAsFilename()
     if filename:
         # Do a backup to the new filename, then open it
         say("Saving to “{}”...".format(QDir.toNativeSeparators(filename)))
         self.state.model.backup(filename, "Saving",
                                 self.window.reportProgress)
         self.window.openXix(filename)
Esempio n. 19
0
    def _fetchChildren(self):
        '''Fetch and return new child items.'''
        children = []
        for entry in QDir.drives():
            path = os.path.normpath(entry.canonicalFilePath())
            children.append(Mount(path))

        return children
Esempio n. 20
0
    def _fetchChildren(self):
        '''Fetch and return new child items.'''
        children = []
        for entry in QDir.drives():
            path = os.path.normpath(entry.canonicalFilePath())
            children.append(Mount(path))

        return children
Esempio n. 21
0
    def localFromServer(self, serverpath):
        # Removing leading '/' so `os.path.join` doesn't treat
        # `localpath` as an absolute path
        localpath = serverpath[1:] if serverpath.startswith(
            '/') else serverpath
        localpath = QDir.toNativeSeparators(localpath)
        localpath = os.path.join(self.localdir, localpath)

        return localpath
Esempio n. 22
0
 def loadConfig(self):
     '''加载配置文件'''
     configfile = QFileDialog.getOpenFileName(self, "Load Config File", QDir.currentPath(), filter="*.cfg")
     uiDebug(configfile)
     if configfile != None :
         self.readConfig(configfile)
         self.stopServer()
         self.startServer()
         self.showConfig()
     uiDebug("loadConfig") 
    def addImages(self, directory, images):
        self.directory = directory

        json_file_name = self.directory.path() + QDir.separator() + 'box2d.json'

        if os.path.exists(json_file_name):
            try:
                with open(json_file_name) as f:
                    self.images = [Image(self.directory, json_dict=js_image) for js_image in json.load(f)]
            except ValueError, e:
                self.images = [Image(self.directory, file_name=image) for image in images]
Esempio n. 24
0
 def config_posix(self):
     """"""
     # Path for all pinguinowriteable files
     PATH = QDir.home().path() + "/.local/share/pinguino_ide"
     
     writeable_path = PATH
     pinguino_user_libs = PATH + "/pinguino-libraries"
     pinguino_resources = "qtgui/resources"
     pinguino_examples = PATH + "/examples/examples"
     pinguino_examples_graphical = PATH + "/examples/examples_graphical"
     
     # create (if not exist) a work dir space
     if not os.path.isdir(writeable_path):
         os.makedirs(writeable_path, 0777)
         
     self.first_config.add_section("Paths")
     self.first_config.set("Paths", "pinguino_writeable_path", writeable_path)
     self.first_config.set("Paths", "pinguino_user_libs", pinguino_user_libs)
     self.first_config.set("Paths", "pinguino_resources", pinguino_resources)
     self.first_config.set("Paths", "pinguino_examples_graphical", pinguino_examples_graphical)
     self.first_config.set("Paths", "pinguino_examples", pinguino_examples)
     
     # set default paths
     self.first_config.set("Paths", "sdcc_bin", "/usr/bin/sdcc")
     #self.first_config.set("Paths", "sdcc_libs", "/usr/share/sdcc")
     self.first_config.set("Paths", "gcc_bin", "")
     #self.first_config.set("Paths", "gcc_libs", "")
     self.first_config.set("Paths", "pinguino_8_libs", "pinguino/p8")
     self.first_config.set("Paths", "pinguino_32_libs", "pinguino/p32")   
     self.first_config.set("Paths", "source", PATH + "/source")
     
     config_location = os.path.join(writeable_path, CONFIG_FILENAME)
     
     self.first_config.write(file(config_location, "w"))
     
     local_config = file("config", "w")
     local_config.write(config_location)
     
     # Remove examples
     if os.path.exists(pinguino_examples): shutil.rmtree(pinguino_examples)
     if os.path.exists(pinguino_examples_graphical): shutil.rmtree(pinguino_examples_graphical)
     
     # Copy examples to writeable path
     shutil.copytree("pinguino/examples", pinguino_examples)
     shutil.copytree("qtgui/gide/examples", pinguino_examples_graphical)
     
     # Copy other configs
     shutil.copy("qtgui/config/reserved.pickle", PATH + "/reserved.pickle")
     shutil.copy("qtgui/config/wikidocs.pickle", PATH + "/wikidocs.pickle")
     
     # Copy pinguino source dir
     if os.path.exists(PATH + "/source"): shutil.rmtree(PATH + "/source")
     shutil.copytree("pinguino/source", PATH + "/source")
Esempio n. 25
0
def pack(directory, quiet, algorithm, size):
    cprint('working directory {}'.format(directory), color='green')
    cprint('quiet {}'.format(quiet), color='green')
    cprint('algorithm {}'.format(algorithm), color='green')
    cprint('size {}'.format(size))

    folder = QDir(path=directory)
    folder.setNameFilters(['*.png'])
    folder.setFilter(QDir.Files or QDir.NoDotAndDotDot)

    dit = QDirIterator(folder, flags=QDirIterator.Subdirectories, filters=QDir.Files)

    filenames = []

    while dit.hasNext():
        im = folder.relativeFilePath(dit.next())
        if not re.search('atlas', im):
            filenames.append(im)

    images = [Image(directory, filename) for filename in filenames]

    BinPacking.bin_packing_progress = MyBinPackingProgress()

    bin_packer = FirstFitShelfBinPacking(Size(2048, 2048), images, bin_parameters={})
    bin_packer.saveAtlases(directory)

    print ''
Esempio n. 26
0
    def __init__(self, directory, filename):
        self.directory = directory
        self.filename = filename

        image = QImage(self.directory + QDir.separator() + self.filename)

        Rect.__init__(self, Point(), Size(image.width(), image.height()))

        cropped_image, x, y, width, height = self.__getCrop(image, False)

        self.crop = Rect(Point(x, y), Size(width, height))

        self.rotated = False
Esempio n. 27
0
def old_add_model(interfacename,scope):   
    try: f = open("models" + QDir.separator() + interfacename + Compiler.model_extension) # try to open the model file
    except IOError: # there must not be a model for this interface name
        print "Warning: interface '" + interfacename + "' is missing a model"
        return
        
    for line in f.readlines():
        # the if statement prevents generated files from importing each other when we don't want them to
        if not line.startswith("from " + Compiler.gendir + "."):
            Compiler.code += line # add the code, under the above condition
    Compiler.code += "\n" #in case there's not newline at the end of the file
    
            
    
Esempio n. 28
0
def rewrite_model(interfacename):
    try: in_file = open("models" + QDir.separator() + interfacename + Compiler.model_extension) # try to open the model file
    except IOError: # there must not be a model for this interface name
        print "Warning: interface '" + interfacename + "' is missing a model"
        return
    
    outcode = "from PySide.QtGui import *\nfrom PySide.QtCore import *\nfrom oxide.widgets.all import *\nfrom oxide.widgets import util_funcs\nimport sys\n"
        # now we won't get errors on import of the rewritten model
    for line in in_file.readlines():
        # the if statement prevents generated files from importing each other when we don't want them to
        if not line.startswith("from " + Compiler.gendir + "."): # if the line does not import from the gendir
            match_object = re.match("class (\w+)" + Compiler.modelclass_extension + "\(\w+\):", line)
            if match_object:
                line = "class " + match_object.group(1) + Compiler.modelclass_extension + "():\n"
            outcode += line # add the code, under the above condition
            
    sep = QDir.separator()
    try: out_file = open(Compiler.gendir + sep + "tmp" + sep + "models" + sep + interfacename + Compiler.model_extension,'w') # create the new file
    except IOError: # could not create the new file
        print "Could not create file in gendir"
        sys.exit()
        
    out_file.write(outcode)
Esempio n. 29
0
    def parsePluginSpecs(self, parentItem, plugins):
        ret = 0
        loadCount = 0

        for i in range(len(plugins)):
            spec = plugins[i]
            if spec.hasError():
                ret |= ParsedState.ParsedWithErrors
            pluginItem = QTreeWidgetItem([spec.name(), "",
                                         "{0} ({1})".format(spec.version(), spec.compatVersion()),
                                         spec.vendor()])
            pluginItem.setToolTip(0, QDir.toNativeSeparators(spec.filePath()))
            ok = not spec.hasError()
            icon = self.okIcon if ok else self.errorIcon
            if ok and spec.state() is not PluginState.Running:
                icon = self.notLoadedIcon
            pluginItem.setIcon(0, icon)
            pluginItem.setData(0, Qt.UserRole, spec)

            state = Qt.Unchecked
            if spec.isEnabled():
                state = Qt.Checked
                loadCount += 1

            if spec.name() not in self.whitelist:
                pluginItem.setData(C_LOAD, Qt.CheckStateRole, state)
            else:
                pluginItem.setData(C_LOAD, Qt.CheckStateRole, Qt.Checked)
                pluginItem.setFlags(Qt.ItemIsSelectable)
            pluginItem.setToolTip(C_LOAD, "Load on Startup")

            self.specToItem[spec] = pluginItem

            if parentItem:
                parentItem.addChild(pluginItem)
            else:
                self.items.append(pluginItem)

        if loadCount == len(plugins):
            groupState = Qt.Checked
            ret |= ParsedState.ParsedAll
        elif loadCount == 0:
            groupState = Qt.Unchecked
            ret |= ParsedState.ParsedNone
        else:
            groupState = Qt.PartiallyChecked
            ret |= ParsedState.ParsedPartial

        return ret, groupState
Esempio n. 30
0
def get_image_pix(id_animal):
    """
    Carga la imagen ya almacenada en la base de datos
    """
    con = controller.connect()
    c = con.cursor()
    query = """SELECT ubicacion, formato FROM imagen WHERE fk_id_animal=?"""
    c.execute(query,[id_animal])
    result = c.fetchone()
    if result:
        path = result[0]
        format = result[1]
        image = QDir.currentPath()+"/images/"+path+format
        pixMap = QPixmap(image)
        return pixMap
Esempio n. 31
0
    def __readPluginPaths(self):
        self.pluginCategories.clear()
        self.pluginSpecs[:] = []

        specFiles = []
        searchPaths = self.pluginPaths
        print("Append plugin spec files:")
        while searchPaths:
            searchDir = QDir(searchPaths.pop(0))
            pattern = "*." + self.extension
            fileInfoList = searchDir.entryInfoList([pattern], QDir.Files)
            for fileInfo in fileInfoList:
                print(BColors.DARKCYAN + fileInfo.absoluteFilePath() + BColors.ENDC)
                specFiles.append(fileInfo.absoluteFilePath())
            dirInfoList = searchDir.entryInfoList(QDir.Dirs | QDir.NoDotAndDotDot)
            for dirInfo in dirInfoList:
                searchPaths.append(dirInfo.absoluteFilePath())
        self.defaultCollection = PluginCollection("")
        self.pluginCategories[""] = self.defaultCollection

        for specFile in specFiles:
            spec = PluginSpec(self)
            spec.private.read(specFile)
            if spec.category() in self.pluginCategories:
                collection = self.pluginCategories[spec.category()]
            else:
                collection = PluginCollection(spec.category())
                self.pluginCategories[spec.category()] = collection
            if spec.isExperimental() and (spec.name() in self.forceEnabledPlugins):
                spec.setEnabled(True)
            if not spec.isExperimental() and (spec.name() in self.disabledPlugins):
                spec.setEnabled(False)
            collection.addPlugin(spec)
            self.pluginSpecs.append(spec)
        self.resolveDependencies()
        self.pluginManager.pluginsChanged.emit()
Esempio n. 32
0
def ReadTagsFromConfiguration():
    try:
        map = {}
        dom_file = os.path.join(QDir.currentPath(),"Data","swn_tag_data.xml")
        print "fetching data from ", dom_file
        dom = parse(dom_file)
        map["Tags"] = __parseTags(dom)
        map["Atmosphere"] = __parseTable(dom.getElementsByTagName("Atmosphere")[0])        
        map["Biosphere"] = __parseTable(dom.getElementsByTagName("Biosphere")[0])
        map["Tech"] = __parseTable(dom.getElementsByTagName("Tech")[0])
        map["Temperature"] = __parseTable(dom.getElementsByTagName("Temperature")[0])
        map["Population"] = __parseTable1(dom.getElementsByTagName("Population")[0])
        return map
    except Exception as inst:
        print "Some error occurred: %s", inst
        return None
Esempio n. 33
0
    def _create_control ( self, parent ):
        # If the caller provided a default path instead of a default directory
        # and filename, split the path into it directory and filename
        # components.
        if ((len( self.default_path )      != 0) and
            (len( self.default_directory ) == 0) and
            (len( self.default_filename )  == 0)):
            default_directory, default_filename = \
                os.path.split( self.default_path )
        else:
            default_directory = self.default_directory
            default_filename  = self.default_filename

        # Convert the filter:
        keep    = True
        filters = []

        for f in self.wildcard.split( '|' ):
            if keep and f:
                filters.append( f )

            keep = not keep

        # Set the default directory:
        if not default_directory:
            default_directory = QDir.currentPath()

        dlg = QFileDialog( parent, self.title, default_directory )

        dlg.setViewMode( QFileDialog.Detail )
        dlg.selectFile( default_filename )
        dlg.setFilters( filters )

        if self.wildcard_index < filters.count():
            dlg.selectFilter( filters[ self.wildcard_index ] )

        if self.action == 'open':
            dlg.setAcceptMode( QFileDialog.AcceptOpen )
            dlg.setFileMode( QFileDialog.ExistingFile )
        elif self.action == 'open files':
            dlg.setAcceptMode( QFileDialog.AcceptOpen )
            dlg.setFileMode( QFileDialog.ExistingFiles )
        else:
            dlg.setAcceptMode( QFileDialog.AcceptSave )
            dlg.setFileMode( QFileDialog.AnyFile )

        return dlg
Esempio n. 34
0
    def addImages(self, directory, images):
        self.directory = directory

        json_file_name = self.directory.path() + QDir.separator(
        ) + 'box2d.json'

        if os.path.exists(json_file_name):
            try:
                with open(json_file_name) as f:
                    self.images = [
                        Image(self.directory, json_dict=js_image)
                        for js_image in json.load(f)
                    ]
            except ValueError, e:
                self.images = [
                    Image(self.directory, file_name=image) for image in images
                ]
 def harvestDirectory(self, directory):
     folder = QDir(path=directory)
     folder.setNameFilters(["*.png"])
     folder.setFilter(QDir.Files or QDir.NoDotAndDotDot)
     dit = QDirIterator(folder, flags=QDirIterator.Subdirectories, filters=QDir.Files)
     while dit.hasNext():
         im = folder.relativeFilePath(dit.next())
         if not re.search("atlas", im):
             self.images.append(im)
     self.bin_packing_thread.setDirectory(self.directory)
     self.bin_packing_thread.setImages(self.images)
     self.updateImages(self.images)
    def run(self):
        if not self.directory or not len(self.images):
            return

        self.prepare_progress_signal.emit(0)
        self.packing_progress_signal.emit(0)
        self.verify_progress_signal.emit(0)
        self.saving_progress_signal.emit(0)

        images = []
        for i, image in enumerate(self.images):
            self.prepare_progress_signal.emit(int(100 * (i + 1) / float(len(self.images))))
            images.append(Image(self.directory, image))

        bin_packing = self.method["type"](self.bin_size, images, bin_parameters=self.bin_parameter[self.method["name"]])
        bin_packing.saveAtlases(self.directory + QDir.separator())

        self.update_bins.emit(bin_packing.bins)
        self.on_end.emit(True)
Esempio n. 37
0
def print_error(type,error,tb):  # @ReservedAssignment
    # re-implementation of sys.excepthook
    tb = traceback.extract_tb(tb)
    if os.path.exists("models" + QDir.separator() + os.path.basename(tb[-1][0])):
        sys.stderr.write("Error in model " + ".".join(os.path.basename(tb[-1][0]).split(".")[:-1]) +
                         ", line " + str(tb[-1][1]) +
                         " in " + str(tb[-1][2]) + ":\n" + 
                         "    " + tb[-1][3] + "\n")
    elif issubclass(error.__class__,InterfaceError):
        sys.stderr.write("Error in view " + error.interface + ".xml:\n")
        
        
    sys.stderr.write(str(type)[:-2].split(".")[-1] + ": ")
    
    if not isinstance(error, IOError) and not isinstance(error, OSError):
        for arg in error.args:
            sys.stderr.write(arg)
    else:
        sys.stderr.write(error.strerror)
    sys.exit()
Esempio n. 38
0
 def loadLibrary(self):
     if self.hasError:
         return False
     if self.state is not PluginState.Resolved:
         if self.state is PluginState.Loaded:
             return True
         self.errorString = QCoreApplication.translate(None, "Loading the library failed because state != Resolved")
         self.hasError = True
         return False
     pluginPath = QDir.toNativeSeparators(self.location)
     pluginClass = pluginloader.loadIPlugin(pluginPath, self.name + "." + self.mainClass)
     if not pluginClass:
         self.hasError = True
         self.errorString = QCoreApplication.translate(None,
                                                       "Plugin is not valid (does not derive from IPlugin")
         return False
     self.state = PluginState.Loaded
     self.plugin = pluginClass(self.manager)
     self.plugin.private.pluginSpec = self.pluginSpec
     return True
Esempio n. 39
0
 def updateRecentFilesMenu(self):
     recentAction = self.fileActions.openRecentAction
     if self.recent_files:
         self.recent_files = [
             filename for filename in self.recent_files
             if filename and os.path.exists(filename)
         ]
     if not self.recent_files:
         recentAction.setEnabled(False)
     else:
         recentAction.setEnabled(True)
         menu = QMenu(self)
         for i, filename in enumerate(self.recent_files, 1):
             action = QAction(
                 QIcon(":/document-open.svg"),
                 "&{} {}".format(i,
                                 QDir.toNativeSeparators(filename)), menu)
             action.triggered.connect(
                 lambda filename=filename: self.openXix(filename))
             menu.addAction(action)
         recentAction.setMenu(menu)
Esempio n. 40
0
    def _create_lockfile(self):
        """
        Attempt to create a lockfile in the user's temporary directory. This is
        one of the few things that doesn't obey the path functions of profile.
        """
        lockfile = os.path.abspath(os.path.join(QDir.tempPath(),
                                                u'%s.lock' % self._app_id))

        try:
            fd = os.open(lockfile, os.O_TRUNC | os.O_CREAT | os.O_RDWR)
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            os.write(fd, "%d\n" % os.getpid())
        
        except (OSError, IOError) as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                return False
            raise
        
        # We've got it.
        self._lockfd = fd
        self._lockfile = lockfile
        return True
Esempio n. 41
0
    def _outputIndex(self, filename, widget):
        monitor = Lib.MonitorFile(filename)
        self.state.outputPath = os.path.dirname(filename)
        nativeFilename = QDir.toNativeSeparators(filename)
        try:
            say("Outputting to “{}”…".format(nativeFilename))
            with Lib.DisableUI(*self.state.window.widgets()):
                config = self.state.model.configs().copy()
                config.Filename = filename
                Output.outputEntries(self.state.model, config, "Outputting",
                                     self.window.reportProgress)

            self._reportOnOutput(
                monitor, "Output to “{}”".format(nativeFilename),
                "Output Failed",
                "Failed to output to “{}”".format(nativeFilename))
        except Output.Error as err:
            self._reportOnOutput(
                monitor, "Output to “{}”".format(nativeFilename),
                "Output Failed",
                "Failed to output to “{}”: {}".format(nativeFilename, err))
        Lib.restoreFocus(widget)
Esempio n. 42
0
    def open_folder(self):
        self.imagesList.clear()
        if not self.current_directory:
            self.current_directory = QFileDialog.getExistingDirectory(
                parent=self, caption=u'Add images from directory')

        folder = QDir(self.current_directory)
        folder.setNameFilters(['*.png'])
        folder.setFilter(QDir.Files or QDir.NoDotAndDotDot)

        dir_iterator = QDirIterator(folder,
                                    flags=QDirIterator.Subdirectories,
                                    filters=QDir.Files)

        images = []

        while dir_iterator.hasNext():
            images.append(folder.relativeFilePath(dir_iterator.next()))

        self.white_albatross.addImages(folder, images)
        self.imagesList.addItems(images)
Esempio n. 43
0
def generate_data_dir():
    lmms_rc_file = os.path.join(QDir.home().absolutePath(), '.lmmsrc.xml')

    xml = BeautifulSoup(open(lmms_rc_file).read())
    return os.path.normpath(
        os.path.split(os.path.split(xml.paths['artwork'].rstrip('/\\'))[0])[0])
Esempio n. 44
0
 def loadImage(self):
     self.image = QImage(self.directory.path() + QDir.separator() + self.file_name)
Esempio n. 45
0
 def setUp(self):
     self.original = QDir("./")
Esempio n. 46
0
def root_abspath():
    from PySide.QtCore import QDir
    return QDir.fromNativeSeparators(os.path.abspath(ROOT_LOCATION))
Esempio n. 47
0
def initIcons():
    # use "icons" as prefix which we used in the .py file (pixmap: icons:file.svg)
    QDir.addSearchPath("icons", os.path.dirname(__file__) + ICONS_PATH)
Esempio n. 48
0
    def serverFromLocal(self, localpath):
        serverpath = localpath.replace(self.localdir, '')
        serverpath = QDir.fromNativeSeparators(serverpath)

        return serverpath
 def on_go_up_parent(self):
     current_path = QDir(self.files_model.rootPath())
     current_path.cdUp()
     self.on_change_root_path(current_path.absolutePath())
Esempio n. 50
0
import os
from PySide.QtCore import QDir, QFileInfo
from Qt5.QtWidgets import QDesktopServices
from skunicode import u
from skdebug import dwarn


def abspath(path):
    """As a replacement of os.path.abspath, which has encoding issue for unicode path
  @param  path  unicode or str
  @return  unicode
  """
    return QFileInfo(path).absoluteFilePath() if path else u""


HOME = QDir.homePath()  # unicode
#HOME = os.path.expanduser('~') # This will be str instead of unicode

DESKTOP = (QDesktopServices.storageLocation(QDesktopServices.DesktopLocation)
           or os.path.join(HOME, 'Desktop'))

SYSTEMDRIVE = u(os.environ.get('windir')) or r"C:"
WINDIR = u(os.environ.get('WinDir')) or os.path.join(SYSTEMDRIVE, r"Windows")
PROGRAMFILES = u(os.environ.get('ProgramFiles')) or os.path.join(
    SYSTEMDRIVE, r"Program Files")
PROGRAMFILESx86 = u(
    os.environ.get('ProgramFiles(x86)')) or PROGRAMFILES  # try x86 first
COMMONPROGRAMFILES = u(os.environ.get('CommonProgramFiles')) or os.path.join(
    PROGRAMFILES, r"Common Files")
COMMONPROGRAMFILESx86 = u(
    os.environ.get('CommonProgramFiles(x86)')) or os.path.join(
Esempio n. 51
0
import os
from PySide.QtCore import QDir
QDir.setSearchPaths(
    "resources",
    [os.path.join(os.getenv("GLADE_ROOT", ""), "resources")]
)
Esempio n. 52
0
 def _open_image(self):
     filename, _ = QFileDialog.getOpenFileName(
         self, 'Open image ...', QDir.homePath(),
         "Images (*.tiff *.png *.xpm *.jpg)")
     if filename:
         self.image_viewer.image = QImage(filename)
import sys
#import os

from PySide import QtGui
#from PySide import QtCore
from PySide.QtCore import QDir

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)

    model = QtGui.QFileSystemModel()
    sRootPath = u"C:/users/sebcourtois"
    model.setRootPath(sRootPath)

    model.setFilter(QDir.Filters(QDir.NoDotAndDotDot | QDir.Dirs | QDir.Files))
    model.setNameFilters(["*_pkg"])

    tree = QtGui.QTreeView()
    tree.setModel(model)
    tree.setRootIndex(model.index(sRootPath))
    tree.setSortingEnabled(True)

    tree.show()

    sys.exit(app.exec_())
Esempio n. 54
0
 def select_save_path(self):
     fname, _ = QFileDialog.getSaveFileName(self, 'Save file',
                                            QDir.homePath(), "*.pdf")
     self.dest_path_edit.setText(fname)
Esempio n. 55
0
 def clicked_add(self):
     fname, _ = QFileDialog.getOpenFileNames(
         self, 'Select two or more PDFs to merge', QDir.homePath(), "*.pdf")
     self.files_list.addItems(fname)
Esempio n. 56
0
 def testBeginEntryList(self):
     obj = TestFSHandler()
     qdir = QDir('/bup')
     for n1, n2 in zip(qdir.entryList(), ['.', '..', 'A', 'B', 'C']):
         self.assertEqual(n1, n2)
     self.assertEqual(len(qdir.entryList()), 5)
Esempio n. 57
0
    def checkout(self):
        """
        Recursively checks out all files on the server.
        Returns a dictionary of files on the server with their last modified date.
        
        :param download: Indicates whether or not the files should be downloaded
        """

        # Check  `self.deleteQueue`, `self.uploadQueue` and `self.downloadQueue` queues.
        # These tasks are done in queues to make sure all FTP commands
        # are done sequentially, in the same thread.
        self.deleteAll()
        self.uploadAll()
        self.downloadAll()

        # Handy list to keep track of the checkout process.
        # This list contain absolute paths only.
        checked_dirs = list()

        # Sets '/' as initial directory and initializes `downloading_dir`
        self.ftp.cwd('/')
        downloading_dir = self.currentdir
        check_date = dt.utcnow()

        sidirlist = list()

        root_cached = False

        fileC = 0
        while True:
            # Gets the list of sub directories and files inside the
            # current directory `downloading_dir`.
            self.textStatus.emit('Remote scan- Downloading folder list of ' +
                                 downloading_dir + '...')

            if root_cached and downloading_dir == '/':
                dir_subdirs = saved_root_dirs
                dirfiles = saved_root_files
            else:

                dir_subdirs = self.getDirs(downloading_dir)

                if downloading_dir == '/':
                    saved_root_dirs = dir_subdirs

                # sidirlist.extend(dir_subdirs)
                self.textStatus.emit(
                    'Remote scan- Downloading files list of ' +
                    downloading_dir + '...')
                dirfiles = self.getFiles(downloading_dir)

                if downloading_dir == '/':
                    saved_root_files = dirfiles
                    root_cached = True

            # Leading '/' in `downloading_dir` breaks the `os.path.join` call
            localdir = os.path.join(self.localdir, downloading_dir[1:])
            if not os.path.exists(localdir):
                # Creates the directory if it doesn't already exists.
                os.makedirs(localdir)

            for file_ in dirfiles:

                # `serverpath` is the absolute path of the file on the server,
                # download it only if it hasn't been already downloaded
                serverpath = os.path.join(downloading_dir, file_)
                serverpath = QDir.fromNativeSeparators(serverpath)
                server_file = File.fromPath(serverpath)

                self.textStatus.emit('Scanning remote file... ' + serverpath +
                                     '...')

                # How do we know if we should check this server file?
                # We see if the date last checked is the check start time.
                if server_file.last_checked_server != check_date:

                    # Do this process only once per file

                    # Added by Simon
                    # Give feedback on scanning of files.
                    fileC += 1
                    if fileC % 1 == 2:
                        self.textStatus.emit(
                            'Scanning remote files for changes, ' +
                            str(fileC) + ' files scanned.')

                    # STEP: IS THIS THE FIRST TIME WE SAW THE FILE, OR WAS IT ALREADY IN OUR DB?
                    just_added = not server_file.inserver

                    # STEP: IF ITS A NEW FILE, ENSURE WE DONT WANT TO SKIP IT
                    # Example: If it's a temporary file, or a Unix file with a name we don't support.

                    if just_added:
                        filename = os.path.basename(serverpath)

                        if platform.system() == 'Windows':

                            badName = False
                            for chr in [
                                    '\\', '/', ':', '?', '"', '<', '>', '|'
                            ]:
                                if chr in filename:
                                    badName = True
                                    break
                            if badName:
                                if filename not in self.warnedNames:
                                    self.warnedNames.append(filename)
                                    self.badFilenameFound.emit(filename)
                                continue

                    # STEP: ASSUMING THE FILE DID EXIST IN OUR DB, LETS SAVE THE LAST MODIFICATION DATE
                    lastmdate = server_file.servermdate

                    # STEP: SAVE THE MOD DATE TO A VARIABLE
                    # Now we get the last mod time.
                    # We expect this to work fine since this file
                    # was found on the server
                    servermdate = self.lastModified(serverpath)

                    # STEP: SET BOOL SHOWING THAT IT WAS ON THE SERVER, SINCE WE KNOW IT IS.
                    server_file.inserver = True

                    # STEP: SET THE TIME THE FILE WAS LAST CHECKED TO THE SCAN START TIME
                    server_file.last_checked_server = check_date

                    # STEP: SET THE MOD DATE IN THE DATABASE TO THE ONE WE JUST GOT
                    server_file.servermdate = servermdate

                    # STEP: SAVE THIS CHANGE TO THE DATABASE
                    server_file.session.commit()

                    delta = 0
                    if server_file.inlocal:
                        delta = server_file.timeDiff()

                    # Emit the signals after the attributes has been set and committed
                    if just_added is True:
                        self.fileAdded.emit(ServerWatcher.LOCATION, serverpath)
                    elif server_file.servermdate > lastmdate or delta < -Watcher.TOLERANCE:
                        self.fileChanged.emit(ServerWatcher.LOCATION,
                                              serverpath, False)
            #END FOR

            self.textStatus.emit('Remote scan- Finding next folder...')
            dir_ready = True
            for dir_ in dir_subdirs:
                # `dirpath` is the absolute path of the subdirectory on the server,
                dirpath = QDir.fromNativeSeparators(
                    os.path.join(downloading_dir, dir_))
                # `downloading_dir` is ready only when all its subdirectory are on the
                # `checked_dirs` list.
                if dirpath not in checked_dirs:
                    # Found one subdirectory that is not on `checked_dirs`,
                    # will process it in the next iteration.
                    downloading_dir = dirpath
                    dir_ready = False
                    break

            if dir_ready is True:
                # All subdirectories of `downloading_dir` are already in `checked_dirs`
                if downloading_dir == '/':
                    # All directories ready and at '/', means checkout is complete
                    # So, exit the main While loop!!
                    break

                else:
                    # Not at '/'. Current directory is ready so is appended to `checked_dirs`
                    # Back one directory to find directories that are not in `checked_dirs`
                    checked_dirs.append(downloading_dir)
                    downloading_dir = os.path.dirname(downloading_dir)

            self.textStatus.emit('Remote scan- Found Folder...')


##### END OF WHILE ################
###################################################################

# Deleted files are the ones whose `last_checked_server` attribute
# didn't get updated in the recursive run.
        session = Session()
        deleted = session.query(File).filter(
            File.last_checked_server < check_date).filter(
                File.inserver == True)
        for file_ in deleted:
            self.fileDeleted.emit(ServerWatcher.LOCATION, file_.path)

        # Wraps up the checkout process, commits to the database.
        session.commit()
Esempio n. 58
0
 def save(self):
     with open(self.directory.path() + QDir.separator() + 'box2d.json',
               'w') as js:
         figures_ = [image.getDict() for image in self.images]
         json.dump(obj=figures_, fp=js, separators=(',', ':'), indent=4)
Esempio n. 59
0
    def initialize(self):
        locale = QLocale()
        model = self.state.model
        if not bool(model):
            self.browser.setHtml("<font color=red>Information can only "
                                 "be shown if an index is open</font>")
            return

        top, total, _ = self.state.indicatorCounts()
        fullname = QDir.toNativeSeparators(os.path.abspath(model.filename))
        creator = model.config(Gconf.Key.Creator)
        created = model.config("Created")
        created = locale.toString(
            QDateTime.fromString(created, "yyyy-MM-dd HH:mm:ss"))
        updated = locale.toString(QFileInfo(model.filename).lastModified())
        size = os.path.getsize(model.filename)
        KB = 1024
        MB = KB * KB
        if size < MB:
            size = "~{:,} KB ({:,} bytes)".format(round(size / KB), size)
        else:
            size = "~{:,} MB ({:,} bytes)".format(round(size / MB), size)
        filename = re.sub(r"\.xix$", "", os.path.basename(fullname),
                          re.IGNORECASE)
        version = str(model.version())
        secs = self.state.workTime + int(time.monotonic() -
                                         self.state.startTime)
        hours, secs = divmod(secs, 3600)
        if hours:
            worktime = "{:,}h{}'".format(hours, secs // 60)
        else:
            worktime = "{}'".format(secs // 60)
        uuid = model.config(UUID)
        LEFT_STYLE = """ style="
margin-right: 0;
padding-right: 0;
spacing-right: 0;
border-right: 0;
"
"""
        RIGHT_STYLE = """ style="
margin-left: 0;
padding-left: 0;
spacing-left: 0;
border-left: 0;
"
"""
        color1 = "#DDDDFF"
        color2 = "#EEEEFF"
        STYLE = ' style="background-color: {};"'
        texts = [
            """<html><table border=0 style="
background-color: {};
">""".format(color1)
        ]
        for i, (name, value, right, debug) in enumerate((
            ("Index", filename, False, False),
            ("Creator", creator, False, False),
            ("Filename", fullname, False, False),
            ("Size", size, False, False),
            ("Created", created, False, False),
            ("Updated", updated, False, False),
            ("Total Entries", "{:,}".format(total), True, False),
            ("Main Entries", "{:,}".format(top), True, False),
            ("Subentries", "{:,}".format(total - top), True, False),
            ("Worktime", worktime, True, False),
            (None, None, False, False),
            ("Index Format", version, True, False),
            ("Index UUID", uuid, True, True),
        )):
            if debug and not self.state.window.debug:
                continue
            if name is None:
                color1 = "#EEEEEE"
                color2 = "#DDDDDD"
                continue
            style = STYLE.format(color1 if i % 2 == 0 else color2)
            align = " align=right" if right else ""
            texts.append("""<tr{}><td{}>{}&nbsp;&nbsp;</td>
<td{}{}>{}</td></tr>""".format(style, LEFT_STYLE, html.escape(name), align,
                               RIGHT_STYLE, html.escape(value)))
        texts.append("</table></html>")
        self.browser.setHtml("".join(texts))