source: sasview/fittingview/src/sans/perspectives/fitting/report_dialog.py @ 9ede123

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

changed the path of html image to the relative

  • Property mode set to 100644
File size: 10.4 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
35   
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_mac = ISMAC
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_mac:
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(os.path.basename(pic_fname[0]))
188            elif self.nimages == 2:
189                html = report_frame % (str(os.path.basename(pic_fname[0])), 
190                                       str(os.path.basename(pic_fname[1])))
191            elif self.nimages == 3:
192                html = report_frame % (str(os.path.basename(pic_fname[0])), 
193                                       str(os.path.basename(pic_fname[1])),
194                                       str(os.path.basename(pic_fname[2])))
195
196            # make/open file in case of absence
197            f = open(fName, 'w')
198            f.close()
199            # write pdf as a pdf file
200            pdf = self.HTML2PDF(data=html, filename=fName)
201           
202            #open pdf
203            if pdf:
204                os.startfile(str(fName))
205            #delete image file
206            for num in range(self.nimages):
207                os.remove(pic_fname[num])
208            return
209        #HTML + png(graph)
210        elif ext_num == (1 - ind_cor):
211            ext = '.html'
212            for num in range(self.nimages):
213                img_ext.append('_img4html%s.png' % num)
214            report_frame = self.report_list[0]
215        #TEXT + pdf(graph)
216        elif ext_num == (2 - ind_cor):
217            ext = '.txt'   
218            # changing the image extension actually changes the image
219            # format on saving
220            for num in range(self.nimages):
221                img_ext.append('_img4txt%s.pdf' % num)
222            report = self.report_list[1]
223        else:
224            return
225       
226        #file name     
227        fName = os.path.splitext(fName)[0] + ext
228        dlg.Destroy()
229       
230        #pic (png) file path/name
231        for num in range(self.nimages):
232            pic_name = os.path.splitext(fName)[0] + img_ext[num]
233            pic_fname.append(pic_name)
234        #put the image path in html string
235        if ext_num == (1 - ind_cor):
236            if self.nimages == 1:
237                report = report_frame % os.path.basename(pic_fname[0])
238            elif self.nimages == 2:
239                report = report_frame % (os.path.basename(pic_fname[0]), 
240                                         os.path.basename(pic_fname[1]))
241            elif self.nimages == 3:
242                report = report_frame % (os.path.basename(pic_fname[0]), 
243                                         os.path.basename(pic_fname[1]),
244                                         os.path.basename(pic_fname[2]))
245        f = open(fName, 'w')
246        f.write(report)
247        f.close()
248        self.Update()
249        #save png file using pic_fname
250        for num in range(self.nimages):
251            self.report_list[2][num].savefig(pic_fname[num])
252       
253           
254    def onPreview(self, event=None):
255        """
256        Preview
257       
258        : event: Preview button event
259        """
260        previewh = html.HtmlEasyPrinting(name="Printing", parentWindow=self)
261        previewh.PreviewText(self.report_html)
262        if event is not None:
263            event.Skip()
264        self.Update()
265   
266    def onPrint(self, event=None):
267        """
268        Print
269       
270        : event: Print button event
271        """
272        printh = html.HtmlEasyPrinting(name="Printing", parentWindow=self)
273        printh.PrintText(self.report_html)
274        if event is not None:
275            event.Skip()
276        self.Update()
277       
278    def OnClose(self,event=None):
279        """
280        Close the Dialog
281       
282        : event: Close button event
283        """
284        self.Close()
285        # Reset memory
286        #wx.MemoryFSHandler()
287        if event is not None:
288            event.Skip()
289   
290    def HTML2PDF(self, data, filename):
291        """
292        Create a PDF file from html source string.
293       
294        : data: html string
295        : filename: name of file to be saved
296        """
297        import ho.pisa as pisa
298        f = file(filename, "wb")
299        # pisa requires some extra packages, see their web-site
300        pdf = pisa.CreatePDF(data, f)
301
302        # close the file here otherwise it will be open until quitting
303        #the application.
304        f.close()
305        self.Update()
306        return not pdf.err
307
308       
309       
Note: See TracBrowser for help on using the repository browser.