File: DirBrowser.py

package info (click to toggle)
python-pmw 1.2-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,024 kB
  • ctags: 3,802
  • sloc: python: 17,143; makefile: 41
file content (306 lines) | stat: -rw-r--r-- 12,040 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#
#  FILE: DirBrowser.py
#
#  DESCRIPTION:
#    This file provides a generic Directory browser selection widget.
#
#  AUTHOR:  MontaVista Software, Inc. <source@mvista.com>
#
#  Copyright 2001 MontaVista Software Inc.
#
#  This program is free software; you can redistribute  it and/or modify it
#  under  the terms of  the GNU General  Public License as published by the
#  Free Software Foundation;  either version 2 of the  License, or (at your
#  option) any later version.
#
#  THIS  SOFTWARE  IS PROVIDED   ``AS  IS'' AND   ANY  EXPRESS OR IMPLIED
#  WARRANTIES,   INCLUDING, BUT NOT  LIMITED  TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
#  NO  EVENT  SHALL   THE AUTHOR  BE    LIABLE FOR ANY   DIRECT, INDIRECT,
#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#  NOT LIMITED   TO, PROCUREMENT OF  SUBSTITUTE GOODS  OR SERVICES; LOSS OF
#  USE, DATA,  OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#  ANY THEORY OF LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#  You should have received a copy of the  GNU General Public License along
#  with this program; if not, write  to the Free Software Foundation, Inc.,
#  675 Mass Ave, Cambridge, MA 02139, USA.
#


import os
import Tkinter
import Pmw


class DirBrowserDialog(Pmw.MegaToplevel):
    def __init__(self, parent = None, **kw):
        cwd = os.getcwd()
	# Define the megawidget options.
	INITOPT = Pmw.INITOPT
	optiondefs = (
            ('path',               cwd,             None),
            ('hidedotfiles',       1,               INITOPT),
            ('label',              None,            INITOPT),
	    #('labelmargin',        0,               INITOPT),
	    #('labelpos',           None,            INITOPT),
            ('borderx',    20,  INITOPT),
            ('bordery',    20,  INITOPT),
            )
        
	self.defineoptions(kw, optiondefs)

	# Initialise the base class (after defining the options).
        Pmw.MegaToplevel.__init__(self, parent)

        interior = self.interior()

        self.childframe = self.createcomponent('childframe', (), None,
                                               Tkinter.Frame,
                                               (interior,),
                                               borderwidth = 1,
                                               relief = 'raised',
                                              )
        self.childframe.pack(expand = 1,
                             fill = 'both',
                             )

        self.labelframe = self.createcomponent('labelframe', (), None,
                                              Tkinter.Frame,
                                              (self.childframe,),
                                              borderwidth = 2,
                                              relief = 'groove',
                                              )
        self.labelframe.pack(padx = 10, pady = 10, expand = 1, fill = 'both')
        
        if self['label']:
            self.label = self.createcomponent('label', (), None,
                                              Tkinter.Label,
                                              (self.childframe,),
                                              text = self['label'],
                                              )
            self.label.place(x = (10 + self['borderx']), y = 10, anchor = 'w')


        self.workframe = self.createcomponent('workframe', (), None,
                                              Tkinter.Frame,
                                              (self.labelframe,),
                                              #borderwidth = 2,
                                              #relief = 'groove',
                                              )
        self.workframe.pack(padx = self['borderx'],
                            pady = self['bordery'],
                            expand = 1,
                            fill = 'both',
                            )

        self.buttonframe = self.createcomponent('buttonframe', (), None,
                                                Tkinter.Frame,
                                                (interior,),
                                                borderwidth = 1,
                                                relief = 'raised',
                                                )
        self.buttonframe.pack(expand = 0,
                              fill = 'x',
                              )

        self.optbox = self.createcomponent('optbox', (), None,
                                           Pmw.OptionMenu,
                                           (self.workframe,),
                                           command = self.setpath,
                                           )
        self.optbox.bind('<Configure>', self._setMinimumSize)

        self.listbox = self.createcomponent('listbox', (), None,
                                            Pmw.ScrolledListBox,
                                            (self.workframe,),
                                            dblclickcommand = self._select,
                                            )

        path = self['path']
        self.entry = self.createcomponent('entryfield', (), None,
                                          Pmw.EntryField,
                                          (self.workframe,),
                                          value = path,
                                          command = self.enteredpath,
                                          labelpos = 'nw',
                                          label_text = 'Current Path:',
                                          )

        #self.createlabel(self.workframe, childCols = 1, childRows = 3)

        self.buttonbox = self.createcomponent('buttonbox', (), None,
                                              Pmw.ButtonBox,
                                              (self.buttonframe,),
                                              )
        self.buttonbox.add('OK', text = 'OK',
                           command = self.okbutton)
        self.buttonbox.add('Cancel', text = 'Cancel',
                           command =  self.cancelbutton)
        self.buttonbox.add('New Directory', text = 'New Directory',
                           command =  self.newdirbutton)
        
        self.buttonbox.alignbuttons()
        self.buttonbox.pack(expand = 1, fill = 'x')

        self.optbox.grid(row = 2, column = 2, sticky = 'ew')
        self.listbox.grid(row = 3, column = 2, sticky = 'news')
        self.entry.grid(row = 5, column = 2, sticky = 'ew')
        self.workframe.grid_rowconfigure(3, weight = 1)
        self.workframe.grid_rowconfigure(4, minsize = 20)
        self.workframe.grid_columnconfigure(2, weight = 1)


        self.setpath(self['path'])

        # Check keywords and initialise options.
        self.initialiseoptions()

    def setpath(self, path):
        path = os.path.abspath(os.path.expanduser(path))
        
        if os.path.isfile(path):
            path = os.path.dirname(path)

        dirlist = []
        hidedotfiles = self['hidedotfiles']
        try:
            posix = (os.name == 'posix')
            for entry in os.listdir(path):
                entryPath = path + '/' + entry
                if hidedotfiles and entry[0] == '.':
                    # skip dot files if desired
                    continue
                if not os.path.isdir(entryPath):
                    # skip files
                    continue
                if not os.access(entryPath, os.R_OK | os.X_OK):
                    # skip directories we can't enter any way
                    continue
                dirlist.append(entry)

        except:
            self.entry.setentry(self['path'])
            return

        self.entry.setentry(path)
        
        self['path'] = path
        
        dirlist.sort()
        if path != '/':
            dirlist.insert(0, '..')

        self.listbox.setlist(dirlist)
        pathlist = []
        while path != '/':
            pathlist.append(path)
            path = os.path.dirname(path)
        pathlist.append('/')
        self.optbox.setitems(pathlist, 0)

    def _setMinimumSize(self, event):
        # If the optionmenu changes width, make sure it does not
        # shrink later.
        owidth = self.optbox.winfo_width()
        self.workframe.grid_columnconfigure(2, minsize = owidth)

    def _select(self):
        sel = self.listbox.getcurselection()
        if self['path'] == '/':
            self['path'] = ''
        if len(sel) > 0:
            if sel[0] == '..':
                self.setpath(os.path.dirname(self['path']))
            else:
                self.setpath(self['path'] + '/' + sel[0])


    def getcurpath(self):
        return self['path']

    def enteredpath(self):
        self.setpath(self.entry.get())

    def okbutton(self):
        self.deactivate(self['path'])

    def cancelbutton(self):
        self.deactivate(None)

    def newdirbutton(self):
        CreateDirectoryPopup(self.interior(), self['path'])
        self.setpath(self['path'])


        
class CreateDirectoryPopup:
    def __init__(self, parent, path):
        self.path = path
        self.parent = parent
        self.newdirpopup = Pmw.PromptDialog(parent,
                                            buttons = ('OK', 'Cancel'),
                                            defaultbutton = 'OK',
                                            title = 'New Directory',
                                            entryfield_labelpos = 'nw',
                                            label_text = 'Enter new directory name for:\n%s'%self.path,
                                            command = self._buttonpress
                                            )

        self.newdirpopup.activate()

    def _buttonpress(self, button):
        if button == 'OK':
            newdirname = self.newdirpopup.get()
            dirlist = os.listdir(self.path)
            if newdirname in dirlist:
                ErrorPopup(self.parent,
                           'Error: "%s", already exists as a file or directory.'%newdirname)
            else:
                try:
                    os.mkdir(self.path + '/' + newdirname)
                except:
                    ErrorPopup(self.parent,
                               'Error: Could not create directory: "%s"'%newdirname)
                else:
                    self.newdirpopup.deactivate()
        else:
            self.newdirpopup.deactivate()
            

def ErrorPopup(parent, message):
    error = Pmw.MessageDialog(parent, title = 'Error',
                              message_text = message,
                              defaultbutton = 0,
                              )
    error.activate()
    
if __name__ == '__main__':

    rootWin = Tkinter.Tk()

    Pmw.initialise()

    rootWin.title('Directory Browser Dialog Demo')

    def buildBrowser():
        # Create the hierarchical directory browser widget
        dirBrowserDialog = DirBrowserDialog(rootWin,
                                            #labelpos = 'nw',
                                            label = 'Select a directory',
                                            title = 'Directory Selector',
                                            #path = '~',
                                            #hidedotfiles = 0,
                                            )
        dir = dirBrowserDialog.activate()
        print 'Selected Directory:', dir

    dirButton = Tkinter.Button(rootWin, text="Browser", command=buildBrowser)
    dirButton.pack(side = 'left', padx = 10, pady = 10)

    exitButton = Tkinter.Button(rootWin, text="Quit", command=rootWin.quit)
    exitButton.pack(side = 'left', padx = 10, pady = 10)

    rootWin.mainloop()