def EditFile(self, file, content, create=False):
        if self.Exists(file.source_path) == False and create == False:
            raise KicadFileManagerException('Module %s does not exists' %
                                            file.source_path)

        fullpath = os.path.join(self.root_path(), file.source_path)
        if self.Exists(file.source_path) == True:
            fcontent = {}
            for filename in glob(os.path.join(fullpath, "*")):
                for extension in self.extensions:
                    if filename.endswith('.' + extension):
                        with open(filename, 'r', encoding='utf-8') as f:
                            fcontent[os.path.basename(filename)] = f.read()
            md5file = hash.md5(json.dumps(fcontent,
                                          sort_keys=True)).hexdigest()
            md5 = hash.md5(content).hexdigest()
            if md5 == md5file:
                return file, False

        if os.path.exists(os.path.dirname(fullpath)) == False:
            os.makedirs(os.path.dirname(fullpath))
        files = json.loads(content)
        for file in files:
            filepath = os.path.join(fullpath, file)
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(files[file])

        file.md5 = hash.md5(content).hexdigest()
        file.updated = rest.api.get_date()

        return file, True
    def EditFile(self, file, content, create=False):
        if self.Exists(file.source_path) == False and create == False:
            raise KicadFileManagerException('File %s does not exists' %
                                            file.source_path)

        fullpath = os.path.join(self.root_path(), file.source_path)
        if self.Exists(file.source_path) == True:
            md5file = hash.md5(Path(fullpath).read_text()).hexdigest()
            md5 = hash.md5(content).hexdigest()
            if md5 == md5file:
                return file, False

        if os.path.exists(os.path.dirname(fullpath)) == False:
            os.makedirs(os.path.dirname(fullpath))
        with open(fullpath, 'w', encoding='utf-8') as content_file:
            if content:
                content_file.write(content)
            else:
                content_file.write('')
        content_file.close()

        file.md5 = hash.md5(content).hexdigest()
        file.updated = rest.api.get_date()

        return file, True
    def EditFile(self, file, content, create=False):
        if self.Exists(file.source_path) == False and create == False:
            raise KicadFileManagerException('File %s does not exists' %
                                            file.source_path)

        library = re.sub(r"\.lib.*\.mod$", ".lib", file.source_path)
        library_path = os.path.dirname(library)

        if self.Exists(file.source_path) == True:
            symbol = self.lib_cache.GetSymbol(file.source_path)
            md5file = hash.md5(symbol.content).hexdigest()
            md5 = hash.md5(content).hexdigest()
            if md5 == md5file:
                return file, False
            self.lib_cache.AddSymbol(file.source_path, content,
                                     symbol.metadata)
            self.write_library(library, self.lib_cache.GetSymbols(library))
        else:
            self.lib_cache.AddSymbol(file.source_path, content, {})
            self.write_library(library, self.lib_cache.GetSymbols(library))

        file.md5 = hash.md5(content).hexdigest()
        file.updated = rest.api.get_date()

        return file, True
    def Load(self):
        """
        fill cache files from disk
        """
        self.files = {}
        modules, self.folders = self.GetModules()

        for module in modules:
            source_path = module

            content = {}
            for filename in glob(
                    os.path.join(self.root_path(), source_path, "*")):
                for extension in self.extensions:
                    if filename.endswith('.' + extension):
                        with open(filename, 'r', encoding='utf-8') as f:
                            content[os.path.basename(filename)] = f.read()

            md5 = hash.md5(json.dumps(content, sort_keys=True)).hexdigest()

            file = rest.model.VersionedFile()
            file.source_path = source_path
            file.md5 = md5

            self.files[source_path] = file
    def CreateFile(self, path, content, overwrite=False):
        if self.Exists(path) and overwrite == False:
            raise KicadFileManagerException('File %s already exists' % path)

        library = re.sub(r"\.lib.*\.mod$", ".lib", path)
        symbol = re.sub(r"^.*\.lib.", "", path)
        library_path = os.path.dirname(library)

        fullpath = os.path.join(self.root_path(), library_path)
        if os.path.exists(fullpath) == False:
            os.makedirs(fullpath)

        file = rest.model.VersionedFile()
        file.source_path = path
        file.md5 = hash.md5(content).hexdigest()
        file.updated = rest.api.get_date()
        file.category = self.category()

        metadata = {}
        if file.metadata:
            metadata = json.loads(file.metadata)
        self.lib_cache.AddSymbol(path, content, metadata)
        self.write_library(library, self.lib_cache.GetSymbols(library))

        return file
 def onButtonFootprintEditApply( self, event ):
     footprint = self.footprint
     
     if footprint.metadata:
         metadata = json.loads(footprint.metadata)
     else:
         metadata = json.loads('{}')
     metadata['description'] = self.edit_footprint_description.Value
     metadata['comment'] = self.edit_footprint_comment.Value
     
     if self.button_open_url_snapeda.Label!="<None>":
         metadata['snapeda'] = self.button_open_url_snapeda.Label
         metadata['snapeda_uid'] = self.snapeda_uid
         metadata['updated'] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
     else:
         metadata.pop('snapeda', '')
         metadata.pop('snapeda_uid', '')
         metadata.pop('updated', '')
     
     footprint.metadata = json.dumps(metadata)
     if not footprint.content:
         footprint.content = ''
         footprint.md5 = hash.md5(footprint.content).hexdigest()
         
     # send result event
     event = EditFootprintApplyEvent(
         data=footprint,
         # source_path is not changed in the footprint as we only have the filename here, not the full path
         # the full path should be reconstructed by caller
         footprint_name=self.edit_footprint_name.Value+".kicad_mod"
         )
     wx.PostEvent(self, event)
    def Modified(self):
        tmp_file = tempfile.NamedTemporaryFile()
        self.SaveAs(tmp_file.name)
        content = ''
        with open(tmp_file.name, 'rb', encoding='utf-8') as f:
            content = f.read()
        src_md5 = hash.md5(content).hexdigest()

        content = ''
        with open(self.filename, 'rb', encoding='utf-8') as f:
            content = f.read()
        dst_md5 = hash.md5(content).hexdigest()

        if src_md5 != dst_md5:
            return True

        for obj in self.parent.nodes:
            if isinstance(obj, KicadSheet):
                if obj.Modified():
                    return True

        return False
示例#8
0
    def get_storage_path(self, version_file):
        md5 = hash.md5(version_file.content).hexdigest()
        levels = self.get_sublevels(md5)

        # get current sublevel
        storage_path = ''

        # create sublevels
        for level in levels:
            storage_path = os.path.join(storage_path, level)
        storage_path = os.path.join(storage_path, md5,
                                    os.path.basename(version_file.source_path))

        return storage_path
示例#9
0
    def add_file(self, version_file):
        storage_path = self.get_storage_path(version_file)
        abs_storage_path = os.path.join(self.storage_path, storage_path)

        if not os.path.exists(os.path.dirname(abs_storage_path)):
            os.makedirs(os.path.dirname(abs_storage_path))

        # create file
        md5 = hash.md5(version_file.content).hexdigest()
        with open(abs_storage_path, 'wb') as outfile:
            outfile.write(version_file.content)
            outfile.close()

        if version_file.id:
            ffile = models.VersionedFile.objects.get(pk=version_file.id)
            ffile.source_path = version_file.source_path
            ffile.storage_path = storage_path.replace('\\', '/')
            ffile.md5 = md5
            ffile.version = ffile.version + 1
            ffile.state = models.VersionedFileState.created
            ffile.updated = datetime.datetime.now()
            ffile.metadata = version_file.metadata
            ffile.category = version_file.category
            ffile.save()
        else:
            # add file to db
            ffile = models.VersionedFile(
                source_path=version_file.source_path,
                storage_path=storage_path.replace('\\', '/'),
                md5=md5,
                version=1,
                state=models.VersionedFileState.created,
                updated=datetime.datetime.now(),
                metadata=version_file.metadata,
                category=version_file.category)
            ffile.save()

        version_file.id = ffile.id
        version_file.storage_path = ffile.storage_path
        version_file.md5 = md5
        version_file.version = ffile.version
        version_file.updated = ffile.updated
        version_file.category = ffile.category
        version_file.state = ''

        print("Add file", version_file.source_path, "as", storage_path)
        return version_file
    def Load(self):
        """
        fill cache files from disk
        """
        self.files = {}
        libraries, self.folders = self.GetLibraries()
        self.lib_cache.Clear()

        for library in libraries:
            symbols = self.GetSymbols(library)
            for symbol in symbols:
                file = rest.model.VersionedFile()
                file.source_path = symbol
                self.LoadContent(file)
                file.md5 = hash.md5(file.content).hexdigest()
                file.category = self.category()
                file.metadata = self.LoadMetadata(symbol)

                self.files[file.source_path] = file
    def Load(self):
        """
        fill cache files from disk
        """
        self.files = {}
        libraries, self.folders = self.GetLibraries()

        for library in libraries:
            footprints = self.GetFootprints(library)
            for footprint in footprints:
                source_path = os.path.join(library, footprint)
                content = Path(os.path.join(self.root_path(),
                                            source_path)).read_text()
                md5 = hash.md5(content).hexdigest()

                file = rest.model.VersionedFile()
                file.source_path = source_path
                file.md5 = md5

                self.files[source_path] = file
    def CreateFile(self, path, content, overwrite=False):
        if self.Exists(path) and overwrite == False:
            raise KicadFileManagerException('File %s already exists' % path)

        fullpath = os.path.join(self.root_path(), path)
        if not os.path.exists(os.path.dirname(fullpath)):
            os.makedirs(os.path.dirname(fullpath))

        with open(fullpath, 'w', encoding='utf-8') as content_file:
            if content:
                content_file.write(content)
            else:
                content_file.write('')
        content_file.close()

        file = rest.model.VersionedFile()
        file.source_path = path
        file.md5 = hash.md5(content).hexdigest()
        file.updated = rest.api.get_date()
        file.category = self.category()

        return file
示例#13
0
    def add_file(self, upfile):
        # get content
        file = tempfile.NamedTemporaryFile(delete=False)
        upfile.save(file)
        file.flush()
        file.close()

        # get md5
        md5 = hash.md5(file.name).hexdigest()
        levels = self.get_sublevels(md5)

        # get current sublevel
        storage_path = ''

        # create sublevels
        dir = self.storage_path
        for level in levels:
            dir = os.path.join(dir, level)
            storage_path = os.path.join(storage_path, level)
            if not os.path.exists(dir):
                os.makedirs(dir)
        dir = os.path.join(dir, md5)
        storage_path = os.path.join(storage_path, md5)
        if not os.path.exists(dir):
            os.makedirs(dir)
        storage_path = os.path.join(storage_path, upfile.filename)
        # copy file
        shutil.copyfile(file.name, os.path.join(dir, upfile.filename))
        #TODO: Delete file.name from temp storage

        # add file to db
        file = models.File(source_name=upfile.filename,
                           storage_path=storage_path.replace('\\', '/'))
        file.save()

        print("Add file", upfile.filename, "as", storage_path)
        return file
    def CreateFile(self, path, content, overwrite=False):
        if self.Exists(path) and overwrite == False:
            raise KicadFileManagerException('Module %s already exists' % path)

        fullpath = os.path.join(self.root_path(), path)
        if not os.path.exists(os.path.dirname(fullpath)):
            os.makedirs(os.path.dirname(fullpath))

        files = json.loads(content)
        if not os.path.exists(os.path.join(self.root_path(), path)):
            os.makedirs(os.path.join(self.root_path(), path))
        for file in files:
            filepath = os.path.join(self.root_path(), path, file)
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(files[file])
        content = json.dumps(files, sort_keys=True)

        file = rest.model.VersionedFile()
        file.source_path = path
        file.md5 = hash.md5(content).hexdigest()
        file.updated = rest.api.get_date()
        file.category = self.category()

        return file
    def onSelectSnapedaFrameOk(self, event):
        snapeda = event.data
        if not snapeda:
            return
        print(snapeda.json)
        
        self.edit_footprint_name.Value = snapeda.part_number()
        self.edit_footprint_description.Value = snapeda.short_description()
        self.snapeda_uid = snapeda.uniqueid()
        
        try:
            download = DownloadQuery()
            download.get(part_number=snapeda.part_number(), 
                               manufacturer=snapeda.manufacturer(),
                               uniqueid=snapeda.uniqueid(),
                               has_symbol=snapeda.has_symbol(),
                               has_footprint=snapeda.has_footprint())
            if download.error():
                wx.MessageBox(download.error(), 'Error downloading footprint', wx.OK | wx.ICON_ERROR)
                
        except:
            print_stack()
            DialogSnapedaError(self).ShowModal()
            return
        
        self.button_open_url_snapeda.Label = "https://www.snapeda.com"+snapeda._links().self().href()

        # download footprint
        if download.url() and download.url()!='':
            try:
                print("Download from:", download.url())
                filename = os.path.join(tempfile.gettempdir(), os.path.basename(download.url()))
                content = scraper.get(download.url()).content
                with open(filename, 'wb', encoding='utf-8') as outfile:
                    outfile.write(content)
                outfile.close()
            except:
                print_stack()
                wx.MessageBox(download.url(), 'Error loading footprint', wx.OK | wx.ICON_ERROR)
                return
                
            # unzip file
            try:
                zip_ref = zipfile.ZipFile(filename, 'r')
                zip_ref.extractall(filename+".tmp")
                zip_ref.close()
            except Exception as e:
                print_stack()
                wx.MessageBox(format(e), 'Error unziping footprint', wx.OK | wx.ICON_ERROR)

            for file in glob.glob(filename+".tmp/*"):
                kicad_file = ''
                if file.endswith(".mod"):
                    dst_libpath, list_of_parts = lib_convert.convert_mod_to_pretty(file, file.replace('.mod', '.pretty'))
                    if len(list_of_parts)>0:
                        kicad_file = os.path.join(dst_libpath, list_of_parts[0]+".kicad_mod")
                elif file.endswith(".kicad_mod"):
                    kicad_file = file

                self.footprint.content = ''
                if kicad_file!='':
                    with open(kicad_file, 'r', encoding='utf-8') as content_file:
                        self.footprint.content = content_file.read()
                        print("****", self.footprint.content)
                    
                    mod = kicad_mod_file.KicadModFile()
                    mod.LoadFile(kicad_file)
                    image_file = tempfile.NamedTemporaryFile()
                    mod.Render(image_file.name, self.panel_image_footprint.GetRect().width, self.panel_image_footprint.GetRect().height)
                    img = wx.Image(image_file.name, wx.BITMAP_TYPE_ANY)
                    image_file.close()
                    img = img.ConvertToBitmap()
                    self.bitmap_edit_footprint.SetBitmap(img)
            
            self.footprint.md5 = hash.md5(self.footprint.content).hexdigest()