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