source: branches/active/character_customization/game/parpg/gui/filebrowser.py @ 774

Revision 774, 5.6 KB checked in by aspidites, 9 years ago (diff)

Patch by Aspidites

  • removed shebang from all python files except launcher scripts
  • added shebang to pychan_designer
  • Property svn:eol-style set to native
RevLine 
[303]1#   This program is free software: you can redistribute it and/or modify
2#   it under the terms of the GNU General Public License as published by
3#   the Free Software Foundation, either version 3 of the License, or
4#   (at your option) any later version.
5
6#   This program is distributed in the hope that it will be useful,
7#   but WITHOUT ANY WARRANTY; without even the implied warranty of
8#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9#   GNU General Public License for more details.
10
11#   You should have received a copy of the GNU General Public License
12#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
13
[473]14from fife.extensions import pychan
15from fife.extensions.pychan import widgets
16
[162]17import sys
18
19def u2s(string):
[479]20    # TODO: cryptic function name
[303]21    return string.encode(sys.getfilesystemencoding())
[162]22
23class FileBrowser(object):
[479]24    """FileBrowser displays directory and file listings from the vfs.
25       The file_selected parameter is a callback invoked when a file selection
26       has been made; its signature must be file_selected(path,filename). If
27       select_dir is set, file_selected's filename parameter should be optional.
28       The save_file option provides a box for supplying a new filename that
29       doesn't exist yet. The select_dir option allows directories to be
30       selected as well as files."""
[640]31    def __init__(self, engine, file_selected, close_callback = None, save_file=False, \
[313]32                 select_dir=False, extensions=('.dat',), \
33                 gui_xml_path="gui/filebrowser.xml"):
[303]34        self.engine = engine
[313]35        self.file_selected = file_selected
[162]36
[303]37        self._widget = None
[313]38        self.save_file = save_file
39        self.select_dir = select_dir
[640]40        self.close_callback = close_callback
[303]41       
[313]42        self.gui_xml_path = gui_xml_path
[162]43
[303]44        self.extensions = extensions
45        self.path = './saves/'
46        self.dir_list = []
47        self.file_list = []
[640]48       
49    def close(self):
50        """Closes the browser"""       
51        self._widget.hide()
52        if self.close_callback:
53            self.close_callback()
54   
[303]55    def showBrowser(self):
[479]56        """Shows the file dialog browser"""
[303]57        if self._widget:
58            self._widget.show()
59            return
[313]60        self._widget = pychan.loadXML(self.gui_xml_path)
[303]61        self._widget.mapEvents({
62            'dirList'       : self._setDirectory,
63            'selectButton'  : self._selectFile,
[640]64            'closeButton'   : self.close
[303]65        })
66        self._setDirectory()
[313]67        if self.save_file:
[303]68            self._file_entry = widgets.TextField(name='saveField', text=u'')   
[313]69            self._widget.findChild(name="fileColumn").\
70                addChild(self._file_entry)
[303]71        self._widget.show()
[162]72
[303]73    def _setDirectory(self):
[479]74        """Directory change callback."""
[303]75        selection = self._widget.collectData('dirList')
76        if not (selection < 0):
77            new_dir = u2s(self.dir_list[selection])
78            lst = self.path.split('/')
79            if new_dir == '..' and lst[-1] != '..' and lst[-1] != '.':
80                lst.pop()
81            else:
82                lst.append(new_dir)
83            self.path = '/'.join(lst)
84           
85        def decodeList(list):
86            fs_encoding = sys.getfilesystemencoding()
87            if fs_encoding is None: fs_encoding = "ascii"
88       
[313]89            new_list = []
[303]90            for i in list:
[313]91                try:
92                    new_list.append(unicode(i, fs_encoding))
[303]93                except:
[313]94                    new_list.append(unicode(i, fs_encoding, 'replace'))
[303]95                    print "WARNING: Could not decode item:", i
[313]96            return new_list
[303]97           
98       
[162]99
[303]100        self.dir_list = []
101        self.file_list = []
102       
[313]103        dir_list = ('..',) + filter(lambda d: not d.startswith('.'), \
104                                    self.engine.getVFS().\
105                                    listDirectories(self.path))
106        file_list = filter(lambda f: f.split('.')[-1] in self.extensions, \
107                           self.engine.getVFS().listFiles(self.path))
[303]108               
109        self.dir_list = decodeList(dir_list)
110        self.file_list = decodeList(file_list)
111        self._widget.distributeInitialData({
112            'dirList'  : self.dir_list,
113            'fileList' : self.file_list
114        })
[162]115
[303]116    def _selectFile(self):
117        """ File selection callback. """
118        self._widget.hide()
119        selection = self._widget.collectData('fileList')
[162]120
[313]121        if self.save_file:
[356]122            data = self._widget.collectData('saveField')
[303]123            if data:
[357]124                if (data.endswith(".dat")):
[313]125                    self.file_selected(self.path, \
126                                u2s(self._widget.collectData('saveField')))
[303]127                else:
[357]128                    self.file_selected(self.path, 
129                                       u2s(self._widget.collectData('saveField')) + '.dat')
[303]130                return
131           
[162]132
[303]133        if selection >= 0 and selection < len(self.file_list):
[313]134            self.file_selected(self.path, u2s(self.file_list[selection]))
[303]135            return
136       
[313]137        if self.select_dir:
138            self.file_selected(self.path)
[303]139            return
[162]140
[303]141        print 'FileBrowser: error, no selection.'
[162]142
[303]143    def _warningMessage(self):
[479]144        """Shows the warning message dialog when a file with a
145           faulty extension was selected."""
[303]146        window = widgets.Window(title="Warning")
147        text = "Please save the file as a .dat"
148        label = widgets.Label(text=text)
149        ok_button = widgets.Button(name="ok_button", text="Ok")
150        window.addChildren([label, ok_button])
151        window.mapEvents({'ok_button':window.hide})
152        window.show()
Note: See TracBrowser for help on using the repository browser.