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

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 d72ef56 was d72ef56, checked in by Jae Cho <jhjcho@…>, 13 years ago

can save default open/save folder

  • Property mode set to 100644
File size: 8.5 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        if self._default_save_location == None:
86            self._default_save_location = os.getcwd()
87       
88        cards = self.loader.get_wildcards()
89        temp = [APPLICATION_WLIST] + PLUGINS_WLIST
90        for item in temp:
91            if item in cards:
92                cards.remove(item)
93        wlist =  '|'.join(cards)
94        style = wx.OPEN|wx.FD_MULTIPLE
95        dlg = wx.FileDialog(self.parent, 
96                            "Choose a file", 
97                            self._default_save_location, "",
98                             wlist,
99                             style=style)
100        if dlg.ShowModal() == wx.ID_OK:
101            file_list = dlg.GetPaths()
102            if len(file_list) >= 0 and not(file_list[0]is None):
103                self._default_save_location = os.path.dirname(file_list[0])
104                path = self._default_save_location
105        dlg.Destroy()
106       
107        if path is None or not file_list or file_list[0] is None:
108            return
109        self.parent._default_save_location = self._default_save_location
110        self.get_data(file_list)
111       
112       
113    def can_load_data(self):
114        """
115        if return True, then call handler to laod data
116        """
117        return True
118 
119       
120    def _load_folder(self, event):
121        """
122        Load entire folder
123        """
124        path = None
125        if self._default_save_location == None:
126            self._default_save_location = os.getcwd()
127        dlg = wx.DirDialog(self.parent, "Choose a directory", 
128                           self._default_save_location,
129                            style=wx.DD_DEFAULT_STYLE)
130        if dlg.ShowModal() == wx.ID_OK:
131            path = dlg.GetPath()
132            self._default_save_location = path
133        dlg.Destroy()
134        if path is not None:
135            self._default_save_location = os.path.dirname(path)
136        else:
137            return   
138        file_list = self.get_file_path(path)
139        self.get_data(file_list)
140        self.parent._default_save_location = self._default_save_location
141       
142    def load_error(self, error=None):
143        """
144        Pop up an error message.
145       
146        :param error: details error message to be displayed
147        """
148        if error is not None or str(error).strip() != "":
149            dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File',
150                                wx.OK | wx.ICON_EXCLAMATION)
151            dial.ShowModal() 
152       
153    def get_file_path(self, path):
154        """
155        Receive a list containing folder then return a list of file
156        """
157        if os.path.isdir(path):
158            return [os.path.join(os.path.abspath(path),
159                                  file) for file in os.listdir(path)]
160   
161    def get_data(self, path, format=None):
162        """
163        """
164        message = ""
165        log_msg = ''
166        output = {}
167        error_message = ""
168        for p_file in path:
169            basename  = os.path.basename(p_file)
170            root, extension = os.path.splitext(basename)
171            if extension.lower() in EXTENSIONS:
172                log_msg = "Data Loader cannot "
173                log_msg += "load: %s\n" % str(p_file)
174                log_msg += """Please try to open that file from "open project" """
175                log_msg += """or "open analysis" menu\n"""
176                error_message = log_msg + "\n"
177                logging.info(log_msg)
178                continue
179       
180            try:
181                temp =  self.loader.load(p_file, format)
182                if temp.__class__.__name__ == "list":
183                    for item in temp:
184                        data = self.parent.create_gui_data(item, p_file)
185                        output[data.id] = data
186                else:
187                    data = self.parent.create_gui_data(temp, p_file)
188                    output[data.id] = data
189                message = "Loading Data..." + str(p_file) + "\n"
190                self.load_update(output=output, message=message)
191            except:
192                 error = "Error while loading Data: %s\n" % str(p_file)
193                 error += str(sys.exc_value) + "\n"
194                 error_message = "The data file you selected could not be loaded.\n"
195                 error_message += "Make sure the content of your file"
196                 error_message += " is properly formatted.\n\n"
197                 error_message += "When contacting the DANSE team, mention the"
198                 error_message += " following:\n%s" % str(error)
199                 self.load_update(output=output, message=error_message)
200               
201        message = "Loading Data Complete! "
202        message += log_msg
203        self.load_complete(output=output, error_message=error_message,
204                       message=message, path=path)
205           
206    def load_update(self, output=None, message=""):
207        """
208        print update on the status bar
209        """
210        if message != "":
211            wx.PostEvent(self.parent, StatusEvent(status=message,
212                                                  type="progress",
213                                                   info="warning"))
214    def load_complete(self, output, message="", error_message="", path=None):
215        """
216         post message to  status bar and return list of data
217        """
218        wx.PostEvent(self.parent, StatusEvent(status=message,
219                                              info="warning",
220                                              type="stop"))
221        if error_message != "":
222            self.load_error(error_message)
223        self.parent.add_data(data_list=output)
224   
225   
226       
227   
Note: See TracBrowser for help on using the repository browser.