source: sasview/fittingview/src/sans/perspectives/fitting/report_dialog.py @ 7415cbe

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 7415cbe was 213b445, checked in by Jae Cho <jhjcho@…>, 12 years ago

'report save as pdf' enabled on windows

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