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

Revision 774, 5.6 KB checked in by aspidites, 8 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
Line 
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
14from fife.extensions import pychan
15from fife.extensions.pychan import widgets
16
17import sys
18
19def u2s(string):
20    # TODO: cryptic function name
21    return string.encode(sys.getfilesystemencoding())
22
23class FileBrowser(object):
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."""
31    def __init__(self, engine, file_selected, close_callback = None, save_file=False, \
32                 select_dir=False, extensions=('.dat',), \
33                 gui_xml_path="gui/filebrowser.xml"):
34        self.engine = engine
35        self.file_selected = file_selected
36
37        self._widget = None
38        self.save_file = save_file
39        self.select_dir = select_dir
40        self.close_callback = close_callback
41       
42        self.gui_xml_path = gui_xml_path
43
44        self.extensions = extensions
45        self.path = './saves/'
46        self.dir_list = []
47        self.file_list = []
48       
49    def close(self):
50        """Closes the browser"""       
51        self._widget.hide()
52        if self.close_callback:
53            self.close_callback()
54   
55    def showBrowser(self):
56        """Shows the file dialog browser"""
57        if self._widget:
58            self._widget.show()
59            return
60        self._widget = pychan.loadXML(self.gui_xml_path)
61        self._widget.mapEvents({
62            'dirList'       : self._setDirectory,
63            'selectButton'  : self._selectFile,
64            'closeButton'   : self.close
65        })
66        self._setDirectory()
67        if self.save_file:
68            self._file_entry = widgets.TextField(name='saveField', text=u'')   
69            self._widget.findChild(name="fileColumn").\
70                addChild(self._file_entry)
71        self._widget.show()
72
73    def _setDirectory(self):
74        """Directory change callback."""
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       
89            new_list = []
90            for i in list:
91                try:
92                    new_list.append(unicode(i, fs_encoding))
93                except:
94                    new_list.append(unicode(i, fs_encoding, 'replace'))
95                    print "WARNING: Could not decode item:", i
96            return new_list
97           
98       
99
100        self.dir_list = []
101        self.file_list = []
102       
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))
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        })
115
116    def _selectFile(self):
117        """ File selection callback. """
118        self._widget.hide()
119        selection = self._widget.collectData('fileList')
120
121        if self.save_file:
122            data = self._widget.collectData('saveField')
123            if data:
124                if (data.endswith(".dat")):
125                    self.file_selected(self.path, \
126                                u2s(self._widget.collectData('saveField')))
127                else:
128                    self.file_selected(self.path, 
129                                       u2s(self._widget.collectData('saveField')) + '.dat')
130                return
131           
132
133        if selection >= 0 and selection < len(self.file_list):
134            self.file_selected(self.path, u2s(self.file_list[selection]))
135            return
136       
137        if self.select_dir:
138            self.file_selected(self.path)
139            return
140
141        print 'FileBrowser: error, no selection.'
142
143    def _warningMessage(self):
144        """Shows the warning message dialog when a file with a
145           faulty extension was selected."""
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.