Skip to content

Instantly share code, notes, and snippets.

@kived
Created May 29, 2015 19:26
Show Gist options
  • Save kived/da69db748457a23fc897 to your computer and use it in GitHub Desktop.
Save kived/da69db748457a23fc897 to your computer and use it in GitHub Desktop.
Kivy: FileChooser virtual filesystem
import kivy
kivy.require('1.9.0')
from kivy.app import App
from kivy.uix.filechooser import FileChooser, FileSystemAbstract, FileChooserIconLayout
virtual_files = {
'a': {
'size': 20,
'files': {
'a1': {
'size': 30
}
}
},
'b': {
'size': 100
},
'c': {
'size': 50,
'files': {'c1': {
'size': 10
},
'c2': {
'size': 50,
'files': {
'c21': {
'size': 10000
}
}
}
}
}
}
class FileSystemVirtual(FileSystemAbstract):
def __init__(self, files):
self.files = files
def _collapse(self, nameparts):
while '.' in nameparts:
nameparts.remove('.')
while '' in nameparts:
nameparts.remove('')
while '..' in nameparts:
i = nameparts.index('..')
nameparts = nameparts[:i - 1] + nameparts[i + 1:]
return nameparts
def _getentry(self, name):
parts = name.strip('/').split('/')
parts = self._collapse(parts)
target = {'files': self.files, 'size': 0}
while parts:
nextpart = parts[0]
parts = parts[1:]
target = target['files'][nextpart]
return target
def listdir(self, fn):
target = self._getentry(fn)
return target['files'].keys()
def getsize(self, fn):
target = self._getentry(fn)
return target['size']
def is_hidden(self, fn):
return False
def is_dir(self, fn):
target = self._getentry(fn)
return 'files' in target
class TestApp(App):
def build(self):
fc = FileChooser(file_system=FileSystemVirtual(virtual_files), path='/')
fc.add_widget(FileChooserIconLayout())
return fc
if __name__ == '__main__':
TestApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment