source: sasview/sansguiframe/src/sans/guiframe/local_perspectives/data_loader/data_loader.py @ 6a7cf2c

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 6a7cf2c was c553b18, checked in by Jae Cho <jhjcho@…>, 13 years ago

remember the last folder opened/saved

  • Property mode set to 100644
File size: 8.6 KB
Line 
1
2"""
3plugin DataLoader responsible of loading data
4"""
5import os
6import sys
7import wx
8import logging
9
10from sans.dataloader.loader import Loader
11import sans.dataloader.data_info as DataInfo
12from sans.guiframe.plugin_base import PluginBase
13from sans.guiframe.events import StatusEvent
14from sans.guiframe.events import NewPlotEvent
15from sans.guiframe.dataFitting import Data1D
16from sans.guiframe.dataFitting import Data2D
17from sans.guiframe.utils import parse_name
18from sans.guiframe.gui_style import GUIFRAME
19from sans.guiframe.gui_manager import DEFAULT_OPEN_FOLDER
20try:
21    # Try to find a local config
22    import imp
23    path = os.getcwd()
24    if(os.path.isfile("%s/%s.py" % (path, 'local_config'))) or \
25        (os.path.isfile("%s/%s.pyc" % (path, 'local_config'))):
26        fObj, path, descr = imp.find_module('local_config', [path])
27        config = imp.load_module('local_config', fObj, path, descr) 
28    else:
29        # Try simply importing local_config
30        import local_config as config
31except:
32    # Didn't find local config, load the default
33    import config
34
35       
36extension_list = []
37if config.APPLICATION_STATE_EXTENSION is not None:
38    extension_list.append(config.APPLICATION_STATE_EXTENSION)
39EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS + extension_list   
40PLUGINS_WLIST = config.PLUGINS_WLIST
41APPLICATION_WLIST = config.APPLICATION_WLIST
42
43class Plugin(PluginBase):
44   
45    def __init__(self, standalone=False):
46        PluginBase.__init__(self, name="DataLoader", standalone=standalone)
47        #Default location
48        self._default_save_location = DEFAULT_OPEN_FOLDER
49        self.loader = Loader() 
50        self._data_menu = None 
51       
52    def help(self, evt):
53        """
54        Show a general help dialog.
55        """
56        from help_panel import  HelpWindow
57        frame = HelpWindow(None, -1, 'HelpWindow')   
58        frame.Show(True)
59       
60    def populate_file_menu(self):
61        """
62        get a menu item and append it under file menu of the application
63        add load file menu item and load folder item
64        """
65        #menu for data files
66        menu_list = []
67        data_file_hint = "load one or more data in the application"
68        menu_list = [('&Load Data File(s)', data_file_hint, self.load_data)]
69        gui_style = self.parent.get_style()
70        style = gui_style & GUIFRAME.MULTIPLE_APPLICATIONS
71        style1 = gui_style & GUIFRAME.DATALOADER_ON
72        if style == GUIFRAME.MULTIPLE_APPLICATIONS:
73            #menu for data from folder
74            data_folder_hint = "load multiple data in the application"
75            menu_list.append(('&Load Data Folder', data_folder_hint, 
76                              self._load_folder))
77        return menu_list
78   
79
80    def load_data(self, event):
81        """
82        Load data
83        """
84        path = None
85        self._default_save_location = self.parent._default_save_location
86        if self._default_save_location == None:
87            self._default_save_location = os.getcwd()
88       
89        cards = self.loader.get_wildcards()
90        temp = [APPLICATION_WLIST] + PLUGINS_WLIST
91        for item in temp:
92            if item in cards:
93                cards.remove(item)
94        wlist =  '|'.join(cards)
95        style = wx.OPEN|wx.FD_MULTIPLE
96        dlg = wx.FileDialog(self.parent, 
97                            "Choose a file", 
98                            self._default_save_location, "",
99                             wlist,
100                             style=style)
101        if dlg.ShowModal() == wx.ID_OK:
102            file_list = dlg.GetPaths()
103            if len(file_list) >= 0 and not(file_list[0]is None):
104                self._default_save_location = os.path.dirname(file_list[0])
105                path = self._default_save_location
106        dlg.Destroy()
107       
108        if path is None or not file_list or file_list[0] is None:
109            return
110        self.parent._default_save_location = self._default_save_location
111        self.get_data(file_list)
112       
113       
114    def can_load_data(self):
115        """
116        if return True, then call handler to laod data
117        """
118        return True
119 
120       
121    def _load_folder(self, event):
122        """
123        Load entire folder
124        """
125        path = None
126        self._default_save_location = self.parent._default_save_location
127        if self._default_save_location == None:
128            self._default_save_location = os.getcwd()
129        dlg = wx.DirDialog(self.parent, "Choose a directory", 
130                           self._default_save_location,
131                            style=wx.DD_DEFAULT_STYLE)
132        if dlg.ShowModal() == wx.ID_OK:
133            path = dlg.GetPath()
134            self._default_save_location = path
135        dlg.Destroy()
136        if path is not None:
137            self._default_save_location = os.path.dirname(path)
138        else:
139            return   
140        file_list = self.get_file_path(path)
141        self.get_data(file_list)
142        self.parent._default_save_location = self._default_save_location
143       
144    def load_error(self, error=None):
145        """
146        Pop up an error message.
147       
148        :param error: details error message to be displayed
149        """
150        if error is not None or str(error).strip() != "":
151            dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File',
152                                wx.OK | wx.ICON_EXCLAMATION)
153            dial.ShowModal() 
154       
155    def get_file_path(self, path):
156        """
157        Receive a list containing folder then return a list of file
158        """
159        if os.path.isdir(path):
160            return [os.path.join(os.path.abspath(path),
161                                  file) for file in os.listdir(path)]
162   
163    def get_data(self, path, format=None):
164        """
165        """
166        message = ""
167        log_msg = ''
168        output = {}
169        error_message = ""
170        for p_file in path:
171            basename  = os.path.basename(p_file)
172            root, extension = os.path.splitext(basename)
173            if extension.lower() in EXTENSIONS:
174                log_msg = "Data Loader cannot "
175                log_msg += "load: %s\n" % str(p_file)
176                log_msg += """Please try to open that file from "open project" """
177                log_msg += """or "open analysis" menu\n"""
178                error_message = log_msg + "\n"
179                logging.info(log_msg)
180                continue
181       
182            try:
183                temp =  self.loader.load(p_file, format)
184                if temp.__class__.__name__ == "list":
185                    for item in temp:
186                        data = self.parent.create_gui_data(item, p_file)
187                        output[data.id] = data
188                else:
189                    data = self.parent.create_gui_data(temp, p_file)
190                    output[data.id] = data
191                message = "Loading Data..." + str(p_file) + "\n"
192                self.load_update(output=output, message=message)
193            except:
194                 error = "Error while loading Data: %s\n" % str(p_file)
195                 error += str(sys.exc_value) + "\n"
196                 error_message = "The data file you selected could not be loaded.\n"
197                 error_message += "Make sure the content of your file"
198                 error_message += " is properly formatted.\n\n"
199                 error_message += "When contacting the DANSE team, mention the"
200                 error_message += " following:\n%s" % str(error)
201                 self.load_update(output=output, message=error_message)
202               
203        message = "Loading Data Complete! "
204        message += log_msg
205        self.load_complete(output=output, error_message=error_message,
206                       message=message, path=path)
207           
208    def load_update(self, output=None, message=""):
209        """
210        print update on the status bar
211        """
212        if message != "":
213            wx.PostEvent(self.parent, StatusEvent(status=message,
214                                                  type="progress",
215                                                   info="warning"))
216    def load_complete(self, output, message="", error_message="", path=None):
217        """
218         post message to  status bar and return list of data
219        """
220        wx.PostEvent(self.parent, StatusEvent(status=message,
221                                              info="warning",
222                                              type="stop"))
223        if error_message != "":
224            self.load_error(error_message)
225        self.parent.add_data(data_list=output)
226   
227   
228       
229   
Note: See TracBrowser for help on using the repository browser.