Ran update_copyright.py
[hooke.git] / hooke / ui / gui / dialog / save_file.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke.  If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """Define :func:`select_save_file`
20 """
21
22 import os.path
23
24 import wx
25
26
27 def select_save_file(directory, name, extension=None, *args, **kwargs):
28     """Get a filename from the user for saving data.
29
30     1) Prompt the user for a name using `name` as the default.
31
32        * If the user cancels, return `None`
33        * If the selected name does not exist, return it.
34
35     2) If the selected name already exists, ask for clobber
36        confirmation.
37
38        * If clobbering is ok, return the selected name.
39        * Otherwise, return to (1).
40     """
41     def path(name):
42         return os.path.join(directory, name+extension)
43     def name_exists(name):
44         os.path.exists(path(name))
45         
46     while True:
47         dialog = wx.TextEntryDialog(*args, **kwargs)
48         dialog.SetValue(name)
49         if dialog.ShowModal() != wx.ID_OK:
50             return  # abort
51         name = dialog.GetValue()    
52         if not name_exists(name):
53             return name
54         dialogConfirm = wx.MessageDialog(
55             parent=self,
56             message='\n\n'.join(
57                 ['A file with this name already exists.',
58                  'Do you want to replace it?']),
59                 caption='Confirm',
60                 style=wx.YES_NO|wx.ICON_QUESTION|wx.CENTER)
61         if dialogConfirm.ShowModal() == wx.ID_YES:
62             return name