source: sasview/fittingview/src/sans/perspectives/fitting/report_dialog.py @ 986da97

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 986da97 was f32d144, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Pep-8-ification

  • Property mode set to 100644
File size: 10.1 KB
Line 
1"""
2Dialog report panel to show and summarize the results of
3the invariant calculation.
4"""
5################################################################################
6#This software was developed by the University of Tennessee as part of the
7#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
8#project funded by the US National Science Foundation.
9#
10#See the license text in license.txt
11#
12#copyright 2009, University of Tennessee
13################################################################################
14
15import wx
16import sys
17import os
18import wx.html as html
19
20_STATICBOX_WIDTH = 480
21PANEL_WIDTH = 530
22PANEL_HEIGHT = 700
23FONT_VARIANT = 1
24ISMAC = False
25
26if sys.platform == "win32":
27    _STATICBOX_WIDTH = 450
28    PANEL_WIDTH = 500
29    PANEL_HEIGHT = 700
30    FONT_VARIANT = 0
31    ISMAC = False
32elif sys.platform == "darwin":
33    ISMAC = True
34ISPDF = True
35
36       
37class ReportDialog(wx.Dialog):
38    """
39    The report dialog box.
40    """
41   
42    def __init__(self, list, *args, **kwds):
43        """
44        Initialization. The parameters added to Dialog are:
45       
46        :param list: report_list (list of html_str, text_str, image)
47        from invariant_state
48        """
49        kwds["style"] = wx.RESIZE_BORDER|wx.DEFAULT_DIALOG_STYLE
50        wx.Dialog.__init__(self, *args, **kwds)
51        kwds["image"] = 'Dynamic Image'
52        # title
53        self.SetTitle("Report: Fitting")
54        # size
55        self.SetSize((720, 650))
56        # font size
57        self.SetWindowVariant(variant=FONT_VARIANT)
58        # check if tit is MAC
59        self.is_pdf = ISPDF
60        # report string
61        self.report_list = list
62        # number of images of plot
63        self.nimages = len(list[2])
64       
65        if list[2] != None:
66            # put image path in the report string
67            if len(list[2]) == 1:
68                self.report_html = self.report_list[0] % \
69                                    "memory:img_fit0.png"
70            elif len(list[2]) == 2:
71                self.report_html = self.report_list[0] % \
72                                    ("memory:img_fit0.png",
73                                     "memory:img_fit1.png")
74            # allows up to three images
75            else:
76                self.report_html = self.report_list[0] % \
77                                    ("memory:img_fit0.png",
78                                     "memory:img_fit1.png",
79                                     "memory:img_fit2.png")
80        else:
81            self.report_html = self.report_list[0]
82        # layout
83        self._setup_layout()
84       
85    def _setup_layout(self):
86        """
87        Set up layout
88        """
89        hbox = wx.BoxSizer(wx.HORIZONTAL)
90       
91        # buttons
92        id = wx.ID_OK
93        button_close = wx.Button(self, id, "Close")
94        button_close.SetToolTipString("Close this report window.")
95        #hbox.Add((5,10), 1 , wx.EXPAND|wx.ADJUST_MINSIZE,0)
96        hbox.Add(button_close)
97        button_close.SetFocus()
98
99        id = wx.NewId()
100        button_preview = wx.Button(self, id, "Preview")
101        button_preview.SetToolTipString("Print preview this report.")
102        button_preview.Bind(wx.EVT_BUTTON, self.onPreview,
103                            id=button_preview.GetId()) 
104        hbox.Add(button_preview)
105
106        id = wx.NewId()
107        button_print = wx.Button(self, id, "Print")
108        button_print.SetToolTipString("Print this report.")
109        button_print.Bind(wx.EVT_BUTTON, self.onPrint,
110                          id=button_print.GetId())
111        hbox.Add(button_print)
112       
113        id = wx.NewId()
114        button_save = wx.Button(self, id, "Save")
115        button_save.SetToolTipString("Save this report.")
116        button_save.Bind(wx.EVT_BUTTON, self.onSave, id=button_save.GetId())
117        hbox.Add(button_save)
118       
119        # panel for report page
120        #panel = wx.Panel(self, -1)
121        vbox = wx.BoxSizer(wx.VERTICAL)
122        # html window
123        self.hwindow = html.HtmlWindow(self, style=wx.BORDER)
124        # set the html page with the report string
125        self.hwindow.SetPage(self.report_html)
126       
127        # add panels to boxsizers
128        vbox.Add(hbox)
129        vbox.Add(self.hwindow, 1, wx.EXPAND|wx.ALL,0)
130
131        self.SetSizer(vbox)
132        self.Centre()
133        self.Show(True)
134
135    def onSave(self, event=None):
136        """
137        Save
138        """
139        # pdf supporting only on MAC, not on exe
140        if self.is_pdf:
141            wild_card = ' PDF files (*.pdf)|*.pdf|'
142            ind_cor = 0
143        else:
144            wild_card = ''
145            ind_cor = 1
146        wild_card += 'HTML files (*.html)|*.html|'
147        wild_card += 'Text files (*.txt)|*.txt'
148
149        #todo: complete saving fig file and as a txt file
150        dlg = wx.FileDialog(self, "Choose a file",
151                            wildcard=wild_card,
152                            style=wx.SAVE|wx.OVERWRITE_PROMPT|wx.CHANGE_DIR)
153        dlg.SetFilterIndex(0)  # Set .html files to be default
154
155        if dlg.ShowModal() != wx.ID_OK:
156            dlg.Destroy()
157            return
158       
159        fName = dlg.GetPath()
160        ext_num = dlg.GetFilterIndex()
161
162        #set file extensions
163        img_ext = []
164        pic_fname = []
165        #PDF
166        if ext_num == (0 + 2 * ind_cor):
167            # TODO: Sort this case out
168            ext = '.pdf'
169           
170            fName = os.path.splitext(fName)[0] + ext
171            dlg.Destroy()
172            #pic (png) file path/name
173            for num in range(self.nimages):
174                im_ext = '_img%s.png' % num
175                #img_ext.append(im_ext)
176                pic_name = os.path.splitext(fName)[0] + im_ext
177                pic_fname.append(pic_name)
178                # save the image for use with pdf writer
179                self.report_list[2][num].savefig(pic_name)
180
181            #put the image path in html string
182            report_frame = self.report_list[0]
183            #put image name strings into the html file
184            #Note:The str for pic_fname shouldn't be removed.
185            if self.nimages == 1:
186                html = report_frame % str(pic_fname[0])
187            elif self.nimages == 2:
188                html = report_frame % (str(pic_fname[0]), str(pic_fname[1]))
189            elif self.nimages == 3:
190                html = report_frame % (str(pic_fname[0]), str(pic_fname[1]),
191                                          str(pic_fname[2]))
192
193            # make/open file in case of absence
194            f = open(fName, 'w')
195            f.close()
196            # write pdf as a pdf file
197            pdf = self.HTML2PDF(data=html, filename=fName)
198           
199            #open pdf
200            if pdf:
201                os.startfile(str(fName))
202            #delete image file
203            for num in range(self.nimages):
204                os.remove(pic_fname[num])
205            return
206        #HTML + png(graph)
207        elif ext_num == (1 - ind_cor):
208            ext = '.html'
209            for num in range(self.nimages):
210                img_ext.append('_img4html%s.png' % num)
211            report_frame = self.report_list[0]
212        #TEXT + pdf(graph)
213        elif ext_num == (2 - ind_cor):
214            ext = '.txt'
215            # changing the image extension actually changes the image
216            # format on saving
217            for num in range(self.nimages):
218                img_ext.append('_img4txt%s.pdf' % num)
219            report = self.report_list[1]
220        else:
221            return
222       
223        #file name
224        fName = os.path.splitext(fName)[0] + ext
225        dlg.Destroy()
226       
227        #pic (png) file path/name
228        for num in range(self.nimages):
229            pic_name = os.path.splitext(fName)[0] + img_ext[num]
230            pic_fname.append(pic_name)
231        #put the image path in html string
232        if ext_num == (1 - ind_cor):
233            if self.nimages == 1:
234                report = report_frame % os.path.basename(pic_fname[0])
235            elif self.nimages == 2:
236                report = report_frame % (os.path.basename(pic_fname[0]),
237                                         os.path.basename(pic_fname[1]))
238            elif self.nimages == 3:
239                report = report_frame % (os.path.basename(pic_fname[0]),
240                                         os.path.basename(pic_fname[1]),
241                                         os.path.basename(pic_fname[2]))
242        f = open(fName, 'w')
243        f.write(report)
244        f.close()
245        self.Update()
246        #save png file using pic_fname
247        for num in range(self.nimages):
248            self.report_list[2][num].savefig(pic_fname[num])
249       
250    def onPreview(self, event=None):
251        """
252        Preview
253       
254        : event: Preview button event
255        """
256        previewh = html.HtmlEasyPrinting(name="Printing", parentWindow=self)
257        previewh.PreviewText(self.report_html)
258        if event is not None:
259            event.Skip()
260        self.Update()
261   
262    def onPrint(self, event=None):
263        """
264        Print
265       
266        : event: Print button event
267        """
268        printh = html.HtmlEasyPrinting(name="Printing", parentWindow=self)
269        printh.PrintText(self.report_html)
270        if event is not None:
271            event.Skip()
272        self.Update()
273       
274    def OnClose(self, event=None):
275        """
276        Close the Dialog
277       
278        : event: Close button event
279        """
280        self.Close()
281        # Reset memory
282        #wx.MemoryFSHandler()
283        if event is not None:
284            event.Skip()
285   
286    def HTML2PDF(self, data, filename):
287        """
288        Create a PDF file from html source string.
289       
290        : data: html string
291        : filename: name of file to be saved
292        """
293        import ho.pisa as pisa
294        f = file(filename, "wb")
295        # pisa requires some extra packages, see their web-site
296        pdf = pisa.CreatePDF(data, f)
297
298        # close the file here otherwise it will be open until quitting
299        #the application.
300        f.close()
301        self.Update()
302        return not pdf.err
Note: See TracBrowser for help on using the repository browser.