ade99b2cf2357488e503903d70d9b0a9b9c602df
[hooke.git] / hooke / ui / gui / dialog / save_file.py
1 # Copyright
2
3 """Define :func:`select_save_file`
4 """
5
6 import os.path
7
8 import wx
9
10
11 def select_save_file(directory, name, extension=None, *args, **kwargs):
12     """Get a filename from the user for saving data.
13
14     1) Prompt the user for a name using `name` as the default.
15
16        * If the user cancels, return `None`
17        * If the selected name does not exist, return it.
18
19     2) If the selected name already exists, ask for clobber
20        confirmation.
21
22        * If clobbering is ok, return the selected name.
23        * Otherwise, return to (1).
24     """
25     def path(name):
26         return os.path.join(directory, name+extension)
27     def name_exists(name):
28         os.path.exists(path(name))
29         
30     while True:
31         dialog = wx.TextEntryDialog(*args, **kwargs)
32         dialog.SetValue(name)
33         if dialog.ShowModal() != wx.ID_OK:
34             return  # abort
35         name = dialog.GetValue()    
36         if not name_exists(name):
37             return name
38         dialogConfirm = wx.MessageDialog(
39             parent=self,
40             message='\n\n'.join(
41                 ['A file with this name already exists.',
42                  'Do you want to replace it?']),
43                 caption='Confirm',
44                 style=wx.YES_NO|wx.ICON_QUESTION|wx.CENTER)
45         if dialogConfirm.ShowModal() == wx.ID_YES:
46             return name