8053e7e710c07e517345aed8f9cb23c57537f29f
[ctsim.git] / src / views.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          view.cpp
5 **   Purpose:       View & Canvas routines for CTSim program
6 **   Programmer:    Kevin Rosenberg
7 **   Date Started:  July 2000
8 **
9 **  This is part of the CTSim program
10 **  Copyright (C) 1983-2000 Kevin Rosenberg
11 **
12 **  $Id: views.cpp,v 1.75 2001/01/26 23:23:00 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 // For compilers that support precompilation, includes "wx/wx.h".
29 #include "wx/wxprec.h"
30
31 #ifdef __BORLANDC__
32 #pragma hdrstop
33 #endif
34
35 #ifndef WX_PRECOMP
36 #include "wx/wx.h"
37 #endif
38
39 #if !wxUSE_DOC_VIEW_ARCHITECTURE
40 #error You must set wxUSE_DOC_VIEW_ARCHITECTURE to 1 in setup.h!
41 #endif
42
43 #include "wx/image.h"
44 #include "wx/progdlg.h"
45
46 #include "ct.h"
47 #include "ctsim.h"
48 #include "docs.h"
49 #include "views.h"
50 #include "dialogs.h"
51 #include "dlgprojections.h"
52 #include "dlgreconstruct.h"
53 #include "backprojectors.h"
54 #include "reconstruct.h"
55 #include "timer.h"
56
57 #if defined(MSVC) || HAVE_SSTREAM
58 #include <sstream>
59 #else
60 #include <sstream_subst>
61 #endif
62
63
64 // ImageFileCanvas
65
66 BEGIN_EVENT_TABLE(ImageFileCanvas, wxScrolledWindow)
67 EVT_MOUSE_EVENTS(ImageFileCanvas::OnMouseEvent)
68 END_EVENT_TABLE()
69
70
71 ImageFileCanvas::ImageFileCanvas (ImageFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
72 : wxScrolledWindow(frame, -1, pos, size, style), m_pView(v), m_xCursor(-1), m_yCursor(-1)
73 {
74 }
75
76 ImageFileCanvas::~ImageFileCanvas()
77 {
78         m_pView = NULL;
79 }
80
81 void 
82 ImageFileCanvas::OnDraw(wxDC& dc)
83 {
84   if (m_pView)
85     m_pView->OnDraw(& dc);
86 }
87
88 void 
89 ImageFileCanvas::DrawRubberBandCursor (wxDC& dc, int x, int y)
90 {
91   const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
92   int nx = rIF.nx();
93   int ny = rIF.ny();
94   
95   int yPt = ny - y - 1;
96   dc.SetLogicalFunction (wxINVERT);
97   dc.SetPen (*wxGREEN_PEN);
98   dc.DrawLine (0, yPt, nx, yPt);
99   dc.DrawLine (x, 0, x, ny);
100   dc.SetLogicalFunction (wxCOPY);
101 }
102
103 bool
104 ImageFileCanvas::GetCurrentCursor (int& x, int& y)
105 {
106   x = m_xCursor;
107   y = m_yCursor;
108   
109   if (m_xCursor >= 0 && m_yCursor >= 0)
110     return true;
111   else
112     return false;
113 }
114
115 void 
116 ImageFileCanvas::OnMouseEvent(wxMouseEvent& event)
117 {
118   if (! m_pView)
119     return;
120   
121   wxClientDC dc(this);
122   PrepareDC(dc);
123   
124   wxPoint pt(event.GetLogicalPosition(dc));
125   
126   const ImageFileDocument* pIFDoc = m_pView->GetDocument();
127   if (! pIFDoc)
128     return;
129   const ImageFile& rIF = pIFDoc->getImageFile();
130   ImageFileArrayConst v = rIF.getArray();
131   int nx = rIF.nx();
132   int ny = rIF.ny();
133   const int yPt = ny - 1 - pt.y;
134   if (event.RightIsDown()) {
135     if (pt.x >= 0 && pt.x < nx && pt.y >= 0 && pt.y < ny) {
136       std::ostringstream os;
137       os << "Image value (" << pt.x << "," << yPt << ") = " << v[pt.x][yPt];
138       if (rIF.isComplex()) {
139         double dImag = rIF.getImaginaryArray()[pt.x][yPt];
140         if (dImag < 0)
141           os << " - " << -dImag;
142         else
143           os << " + " << dImag;
144         os << "i\n";
145       } else
146         os << "\n";
147       *theApp->getLog() << os.str().c_str();
148     } else
149       *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << yPt << ")\n";
150   }
151   else if (event.LeftIsDown() || event.LeftUp() || event.RightUp()) {
152     if (pt.x >= 0 && pt.x < nx && pt.y >= 0 && pt.y < ny) {
153       if (m_xCursor >= 0 && m_yCursor >= 0) {
154         DrawRubberBandCursor (dc, m_xCursor, m_yCursor);
155       }
156       DrawRubberBandCursor (dc, pt.x, yPt);
157       m_xCursor = pt.x;
158       m_yCursor = yPt;
159     } else
160       *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << yPt << ")\n";
161   }
162   if (event.LeftUp()) {
163     std::ostringstream os;
164     os << "Selected column " << pt.x << " , row " << yPt << "\n";
165     *theApp->getLog() << os.str().c_str();
166   }
167 }
168
169 wxSize
170 ImageFileCanvas::GetBestSize() const
171 {
172   if (! m_pView)
173     return wxSize(0,0);
174   
175   const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
176   return wxSize (rIF.nx(), rIF.ny());
177 }
178
179
180 // ImageFileView
181
182 IMPLEMENT_DYNAMIC_CLASS(ImageFileView, wxView)
183
184 BEGIN_EVENT_TABLE(ImageFileView, wxView)
185 EVT_MENU(IFMENU_FILE_EXPORT, ImageFileView::OnExport)
186 EVT_MENU(IFMENU_FILE_PROPERTIES, ImageFileView::OnProperties)
187 EVT_MENU(IFMENU_VIEW_SCALE_MINMAX, ImageFileView::OnScaleMinMax)
188 EVT_MENU(IFMENU_VIEW_SCALE_AUTO, ImageFileView::OnScaleAuto)
189 EVT_MENU(IFMENU_VIEW_SCALE_FULL, ImageFileView::OnScaleFull)
190 EVT_MENU(IFMENU_COMPARE_IMAGES, ImageFileView::OnCompare)
191 EVT_MENU(IFMENU_COMPARE_ROW, ImageFileView::OnCompareRow)
192 EVT_MENU(IFMENU_COMPARE_COL, ImageFileView::OnCompareCol)
193 EVT_MENU(IFMENU_FILTER_INVERTVALUES, ImageFileView::OnInvertValues)
194 EVT_MENU(IFMENU_FILTER_SQUARE, ImageFileView::OnSquare)
195 EVT_MENU(IFMENU_FILTER_SQRT, ImageFileView::OnSquareRoot)
196 EVT_MENU(IFMENU_FILTER_LOG, ImageFileView::OnLog)
197 EVT_MENU(IFMENU_FILTER_EXP, ImageFileView::OnExp)
198 EVT_MENU(IFMENU_FILTER_FOURIER, ImageFileView::OnFourier)
199 EVT_MENU(IFMENU_FILTER_INVERSE_FOURIER, ImageFileView::OnInverseFourier)
200 EVT_MENU(IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER, ImageFileView::OnShuffleFourierToNaturalOrder)
201 EVT_MENU(IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER, ImageFileView::OnShuffleNaturalToFourierOrder)
202 EVT_MENU(IFMENU_IMAGE_ADD, ImageFileView::OnAdd)
203 EVT_MENU(IFMENU_IMAGE_SUBTRACT, ImageFileView::OnSubtract)
204 EVT_MENU(IFMENU_IMAGE_MULTIPLY, ImageFileView::OnMultiply)
205 EVT_MENU(IFMENU_IMAGE_DIVIDE, ImageFileView::OnDivide)
206 EVT_MENU(IFMENU_IMAGE_SCALESIZE, ImageFileView::OnScaleSize)
207 #ifdef HAVE_FFT
208 EVT_MENU(IFMENU_FILTER_FFT, ImageFileView::OnFFT)
209 EVT_MENU(IFMENU_FILTER_IFFT, ImageFileView::OnIFFT)
210 EVT_MENU(IFMENU_FILTER_FFT_ROWS, ImageFileView::OnFFTRows)
211 EVT_MENU(IFMENU_FILTER_IFFT_ROWS, ImageFileView::OnIFFTRows)
212 EVT_MENU(IFMENU_FILTER_FFT_COLS, ImageFileView::OnFFTCols)
213 EVT_MENU(IFMENU_FILTER_IFFT_COLS, ImageFileView::OnIFFTCols)
214 #endif
215 EVT_MENU(IFMENU_FILTER_MAGNITUDE, ImageFileView::OnMagnitude)
216 EVT_MENU(IFMENU_FILTER_PHASE, ImageFileView::OnPhase)
217 EVT_MENU(IFMENU_PLOT_ROW, ImageFileView::OnPlotRow)
218 EVT_MENU(IFMENU_PLOT_COL, ImageFileView::OnPlotCol)
219 #ifdef HAVE_FFT
220 EVT_MENU(IFMENU_PLOT_FFT_ROW, ImageFileView::OnPlotFFTRow)
221 EVT_MENU(IFMENU_PLOT_FFT_COL, ImageFileView::OnPlotFFTCol)
222 #endif
223 EVT_MENU(IFMENU_PLOT_HISTOGRAM, ImageFileView::OnPlotHistogram)
224 END_EVENT_TABLE()
225
226 ImageFileView::ImageFileView() 
227 : wxView(), m_canvas(NULL), m_pFrame(NULL), m_bMinSpecified(false), m_bMaxSpecified(false), m_pFileMenu(0)
228 {
229   m_iDefaultExportFormatID = ImageFile::FORMAT_PNG;
230 }
231
232 ImageFileView::~ImageFileView()
233 {
234   theApp->getDocManager()->FileHistoryRemoveMenu (m_pFileMenu);
235 }
236
237 void
238 ImageFileView::OnProperties (wxCommandEvent& event)
239 {
240   const ImageFile& rIF = GetDocument()->getImageFile();
241   if (rIF.nx() == 0 || rIF.ny() == 0)
242     *theApp->getLog() << "Properties: empty imagefile\n";
243   else {
244     const std::string& rFilename = rIF.getFilename();
245     std::ostringstream os;
246     double min, max, mean, mode, median, stddev;
247     rIF.statistics (rIF.getArray(), min, max, mean, mode, median, stddev);
248     os << "Filename: " << rFilename << "\n";
249     os << "Size: (" << rIF.nx() << "," << rIF.ny() << ")\n";
250     os << "Data type: ";
251     if (rIF.isComplex())
252       os << "Complex\n";
253     else
254       os << "Real\n";
255     os << "\nMinimum: "<<min<<"\nMaximum: "<<max<<"\nMean: "<<mean<<"\nMedian: "<<median<<"\nMode: "<<mode<<"\nStandard Deviation: "<<stddev << "\n";
256     if (rIF.isComplex()) {
257       rIF.statistics (rIF.getImaginaryArray(), min, max, mean, mode, median, stddev);
258       os << "\nImaginary: min: "<<min<<"\nmax: "<<max<<"\nmean: "<<mean<<"\nmedian: "<<median<<"\nmode: "<<mode<<"\nstddev: "<<stddev << "\n";
259     }
260     if (rIF.nLabels() > 0) {
261       os << "\n";
262       rIF.printLabelsBrief (os);
263     }
264     *theApp->getLog() << os.str().c_str();
265     wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Imagefile Properties", wxOK | wxICON_INFORMATION);
266     dialogMsg.ShowModal();
267   }
268 }
269
270 void 
271 ImageFileView::OnScaleAuto (wxCommandEvent& event)
272 {
273   const ImageFile& rIF = GetDocument()->getImageFile();
274   double min, max, mean, mode, median, stddev;
275   rIF.statistics(min, max, mean, mode, median, stddev);
276   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
277   int iRetVal = dialogAutoScale.ShowModal();
278   if (iRetVal == wxID_OK) {
279     m_bMinSpecified = true;
280     m_bMaxSpecified = true;
281     double dMin, dMax;
282     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
283       m_dMinPixel = dMin;
284       m_dMaxPixel = dMax;
285       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
286       OnUpdate (this, NULL);
287     }
288   }
289 }
290
291 void 
292 ImageFileView::OnScaleMinMax (wxCommandEvent& event)
293 {
294   const ImageFile& rIF = GetDocument()->getImageFile();
295   double min, max;
296   if (! m_bMinSpecified && ! m_bMaxSpecified)
297     rIF.getMinMax (min, max);
298   
299   if (m_bMinSpecified)
300     min = m_dMinPixel;
301   if (m_bMaxSpecified)
302     max = m_dMaxPixel;
303   
304   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Image Minimum & Maximum", min, max);
305   int retVal = dialogMinMax.ShowModal();
306   if (retVal == wxID_OK) {
307     m_bMinSpecified = true;
308     m_bMaxSpecified = true;
309     m_dMinPixel = dialogMinMax.getMinimum();
310     m_dMaxPixel = dialogMinMax.getMaximum();
311     OnUpdate (this, NULL);
312   }
313 }
314
315 void 
316 ImageFileView::OnScaleFull (wxCommandEvent& event)
317 {
318   if (m_bMinSpecified || m_bMaxSpecified) {
319     m_bMinSpecified = false;
320     m_bMaxSpecified = false;
321     OnUpdate (this, NULL);
322   }
323 }
324
325 void
326 ImageFileView::OnCompare (wxCommandEvent& event)
327 {
328   std::vector<ImageFileDocument*> vecIF;
329   theApp->getCompatibleImages (GetDocument(), vecIF);
330   
331   if (vecIF.size() == 0) {
332     wxMessageBox("There are no compatible image files open for comparision", "No comparison images");
333   } else {
334     DialogGetComparisonImage dialogGetCompare(getFrameForChild(), "Get Comparison Image", vecIF, true);
335     
336     if (dialogGetCompare.ShowModal() == wxID_OK) {
337       const ImageFile& rIF = GetDocument()->getImageFile();
338       ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
339       const ImageFile& rCompareIF = pCompareDoc->getImageFile();
340       std::ostringstream os;
341       double min, max, mean, mode, median, stddev;
342       rIF.statistics (min, max, mean, mode, median, stddev);
343       os << GetFrame()->GetTitle().c_str() << ": minimum=" << min << ", maximum=" << max << ", mean=" << mean << ", mode=" << mode << ", median=" << median << ", stddev=" << stddev << "\n";
344       rCompareIF.statistics (min, max, mean, mode, median, stddev);
345       os << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": minimum=" << min << ", maximum=" << max << ", mean=" << mean << ", mode=" << mode << ", median=" << median << ", stddev=" << stddev << "\n";
346       os << "\n";
347       double d, r, e;
348       rIF.comparativeStatistics (rCompareIF, d, r, e);
349       os << "Comparative Statistics: d=" << d << ", r=" << r << ", e=" << e << "\n";
350       *theApp->getLog() << os.str().c_str();
351       if (dialogGetCompare.getMakeDifferenceImage()) {
352         ImageFileDocument* pDifferenceDoc = theApp->newImageDoc();
353         if (! pDifferenceDoc) {
354           sys_error (ERR_SEVERE, "Unable to create image file");
355           return;
356         }
357         ImageFile& differenceImage = pDifferenceDoc->getImageFile();
358         
359         differenceImage.setArraySize (rIF.nx(), rIF.ny());
360         if (! rIF.subtractImages (rCompareIF, differenceImage)) {
361           pDifferenceDoc->DeleteAllViews();
362           return;
363         }
364         
365         wxString s = GetFrame()->GetTitle() + ": ";
366         differenceImage.labelsCopy (rIF, s.c_str());
367         s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
368         differenceImage.labelsCopy (rCompareIF, s.c_str());
369         std::ostringstream osLabel;
370         osLabel << "Compare image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() 
371           << " and " << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": "
372           << os.str().c_str();
373         differenceImage.labelAdd (os.str().c_str());
374         if (theApp->getSetModifyNewDocs())
375           pDifferenceDoc->Modify(true);
376         pDifferenceDoc->UpdateAllViews(this);
377         pDifferenceDoc->GetFirstView()->OnUpdate (this, NULL);
378       }
379       wxMessageBox(os.str().c_str(), "Image Comparison");
380     }
381   }
382 }
383
384 void
385 ImageFileView::OnInvertValues (wxCommandEvent& event)
386 {
387   ImageFile& rIF = GetDocument()->getImageFile();
388   rIF.invertPixelValues (rIF);
389   rIF.labelAdd ("Invert Pixel Values");
390   if (theApp->getSetModifyNewDocs())
391     GetDocument()->Modify(TRUE);
392   GetDocument()->UpdateAllViews(this);
393 }
394
395 void
396 ImageFileView::OnSquare (wxCommandEvent& event)
397 {
398   ImageFile& rIF = GetDocument()->getImageFile();
399   rIF.square (rIF);
400   rIF.labelAdd ("Square Pixel Values");
401   if (theApp->getSetModifyNewDocs())
402     GetDocument()->Modify(TRUE);
403   GetDocument()->UpdateAllViews(this);
404 }
405
406 void
407 ImageFileView::OnSquareRoot (wxCommandEvent& event)
408 {
409   ImageFile& rIF = GetDocument()->getImageFile();
410   rIF.sqrt (rIF);
411   rIF.labelAdd ("Square-root Pixel Values");
412   if (theApp->getSetModifyNewDocs())
413     GetDocument()->Modify(TRUE);
414   GetDocument()->UpdateAllViews(this);
415 }
416
417 void
418 ImageFileView::OnLog (wxCommandEvent& event)
419 {
420   ImageFile& rIF = GetDocument()->getImageFile();
421   rIF.log (rIF);
422   rIF.labelAdd ("Logrithm base-e Pixel Values");
423   if (theApp->getSetModifyNewDocs())
424     GetDocument()->Modify(TRUE);
425   GetDocument()->UpdateAllViews(this);
426 }
427
428 void
429 ImageFileView::OnExp (wxCommandEvent& event)
430 {
431   ImageFile& rIF = GetDocument()->getImageFile();
432   rIF.exp (rIF);
433   rIF.labelAdd ("Exponent base-e Pixel Values");
434   if (theApp->getSetModifyNewDocs())
435     GetDocument()->Modify(TRUE);
436   GetDocument()->UpdateAllViews(this);
437 }
438
439 void
440 ImageFileView::OnAdd (wxCommandEvent& event)
441 {
442   std::vector<ImageFileDocument*> vecIF;
443   theApp->getCompatibleImages (GetDocument(), vecIF);
444   
445   if (vecIF.size() == 0) {
446     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
447   } else {
448     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Add", vecIF, false);
449     
450     if (dialogGetCompare.ShowModal() == wxID_OK) {
451       ImageFile& rIF = GetDocument()->getImageFile();
452       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
453       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
454       ImageFileDocument* pNewDoc = theApp->newImageDoc();
455       if (! pNewDoc) {
456         sys_error (ERR_SEVERE, "Unable to create image file");
457         return;
458       }
459       ImageFile& newImage = pNewDoc->getImageFile();  
460       newImage.setArraySize (rIF.nx(), rIF.ny());
461       rIF.addImages (rRHSIF, newImage);
462       std::ostringstream os;
463       os << "Add image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
464         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
465       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
466       newImage.labelsCopy (rIF, s.c_str());
467       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
468       newImage.labelsCopy (rRHSIF, s.c_str());
469       newImage.labelAdd (os.str().c_str());
470       *theApp->getLog() << os.str().c_str() << "\n";
471       if (theApp->getSetModifyNewDocs())
472         pNewDoc->Modify(TRUE);
473       pNewDoc->UpdateAllViews(this);
474       pNewDoc->GetFirstView()->OnUpdate (this, NULL);
475     }
476   }
477 }
478
479 void
480 ImageFileView::OnSubtract (wxCommandEvent& event)
481 {
482   std::vector<ImageFileDocument*> vecIF;
483   theApp->getCompatibleImages (GetDocument(), vecIF);
484   
485   if (vecIF.size() == 0) {
486     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
487   } else {
488     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Subtract", vecIF, false);
489     
490     if (dialogGetCompare.ShowModal() == wxID_OK) {
491       ImageFile& rIF = GetDocument()->getImageFile();
492       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
493       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
494       ImageFileDocument* pNewDoc = theApp->newImageDoc();
495       if (! pNewDoc) {
496         sys_error (ERR_SEVERE, "Unable to create image file");
497         return;
498       }
499       ImageFile& newImage = pNewDoc->getImageFile();  
500       newImage.setArraySize (rIF.nx(), rIF.ny());
501       rIF.subtractImages (rRHSIF, newImage);
502       std::ostringstream os;
503       os << "Subtract image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
504         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
505       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
506       newImage.labelsCopy (rIF, s.c_str());
507       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
508       newImage.labelsCopy (rRHSIF, s.c_str());
509       newImage.labelAdd (os.str().c_str());
510       *theApp->getLog() << os.str().c_str() << "\n";
511       if (theApp->getSetModifyNewDocs())
512         pNewDoc->Modify(TRUE);
513       pNewDoc->UpdateAllViews(this);
514       pNewDoc->GetFirstView()->OnUpdate (this, NULL);
515     }
516   }
517 }
518
519 void
520 ImageFileView::OnMultiply (wxCommandEvent& event)
521 {
522   std::vector<ImageFileDocument*> vecIF;
523   theApp->getCompatibleImages (GetDocument(), vecIF);
524   
525   if (vecIF.size() == 0) {
526     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
527   } else {
528     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Multiply", vecIF, false);
529     
530     if (dialogGetCompare.ShowModal() == wxID_OK) {
531       ImageFile& rIF = GetDocument()->getImageFile();
532       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
533       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
534       ImageFileDocument* pNewDoc = theApp->newImageDoc();
535       if (! pNewDoc) {
536         sys_error (ERR_SEVERE, "Unable to create image file");
537         return;
538       }
539       ImageFile& newImage = pNewDoc->getImageFile();  
540       newImage.setArraySize (rIF.nx(), rIF.ny());
541       rIF.multiplyImages (rRHSIF, newImage);
542       std::ostringstream os;
543       os << "Multiply image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
544         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
545       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
546       newImage.labelsCopy (rIF, s.c_str());
547       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
548       newImage.labelsCopy (rRHSIF, s.c_str());
549       newImage.labelAdd (os.str().c_str());
550       *theApp->getLog() << os.str().c_str() << "\n";
551       if (theApp->getSetModifyNewDocs())
552         pNewDoc->Modify(TRUE);
553       pNewDoc->UpdateAllViews(this);
554       pNewDoc->GetFirstView()->OnUpdate (this, NULL);
555     }
556   }
557 }
558
559 void
560 ImageFileView::OnDivide (wxCommandEvent& event)
561 {
562   std::vector<ImageFileDocument*> vecIF;
563   theApp->getCompatibleImages (GetDocument(), vecIF);
564   
565   if (vecIF.size() == 0) {
566     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
567   } else {
568     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Divide", vecIF, false);
569     
570     if (dialogGetCompare.ShowModal() == wxID_OK) {
571       ImageFile& rIF = GetDocument()->getImageFile();
572       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
573       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
574       ImageFileDocument* pNewDoc = theApp->newImageDoc();
575       if (! pNewDoc) {
576         sys_error (ERR_SEVERE, "Unable to create image file");
577         return;
578       }
579       ImageFile& newImage = pNewDoc->getImageFile();  
580       newImage.setArraySize (rIF.nx(), rIF.ny());
581       rIF.divideImages (rRHSIF, newImage);
582       std::ostringstream os;
583       os << "Divide image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " by " 
584         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
585       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
586       newImage.labelsCopy (rIF, s.c_str());
587       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
588       newImage.labelsCopy (rRHSIF, s.c_str());
589       newImage.labelAdd (os.str().c_str());
590       *theApp->getLog() << os.str().c_str() << "\n";
591       if (theApp->getSetModifyNewDocs())
592         pNewDoc->Modify(TRUE);
593       pNewDoc->UpdateAllViews(this);
594       pNewDoc->GetFirstView()->OnUpdate (this, NULL);
595     }
596   }
597 }
598
599
600 #ifdef HAVE_FFT
601 void
602 ImageFileView::OnFFT (wxCommandEvent& event)
603 {
604   ImageFile& rIF = GetDocument()->getImageFile();
605   rIF.fft (rIF);
606   rIF.labelAdd ("FFT Image");
607   m_bMinSpecified = false;
608   m_bMaxSpecified = false;
609   if (theApp->getSetModifyNewDocs())
610     GetDocument()->Modify(TRUE);
611   GetDocument()->UpdateAllViews(this);
612 }
613
614 void
615 ImageFileView::OnIFFT (wxCommandEvent& event)
616 {
617   ImageFile& rIF = GetDocument()->getImageFile();
618   rIF.ifft (rIF);
619   rIF.labelAdd ("IFFT Image");
620   m_bMinSpecified = false;
621   m_bMaxSpecified = false;
622   if (theApp->getSetModifyNewDocs())
623     GetDocument()->Modify(TRUE);
624   GetDocument()->UpdateAllViews(this);
625 }
626
627 void
628 ImageFileView::OnFFTRows (wxCommandEvent& event)
629 {
630   ImageFile& rIF = GetDocument()->getImageFile();
631   rIF.fftRows (rIF);
632   rIF.labelAdd ("FFT Rows");
633   m_bMinSpecified = false;
634   m_bMaxSpecified = false;
635   if (theApp->getSetModifyNewDocs())
636     GetDocument()->Modify(TRUE);
637   GetDocument()->UpdateAllViews(this);
638 }
639
640 void
641 ImageFileView::OnIFFTRows (wxCommandEvent& event)
642 {
643   ImageFile& rIF = GetDocument()->getImageFile();
644   rIF.ifftRows (rIF);
645   rIF.labelAdd ("IFFT Rows");
646   m_bMinSpecified = false;
647   m_bMaxSpecified = false;
648   if (theApp->getSetModifyNewDocs())
649     GetDocument()->Modify(TRUE);
650   GetDocument()->UpdateAllViews(this);
651 }
652
653 void
654 ImageFileView::OnFFTCols (wxCommandEvent& event)
655 {
656   ImageFile& rIF = GetDocument()->getImageFile();
657   rIF.fftCols (rIF);
658   rIF.labelAdd ("FFT Columns");
659   m_bMinSpecified = false;
660   m_bMaxSpecified = false;
661   if (theApp->getSetModifyNewDocs())
662     GetDocument()->Modify(TRUE);
663   GetDocument()->UpdateAllViews(this);
664 }
665
666 void
667 ImageFileView::OnIFFTCols (wxCommandEvent& event)
668 {
669   ImageFile& rIF = GetDocument()->getImageFile();
670   rIF.ifftCols (rIF);
671   rIF.labelAdd ("IFFT Columns");
672   m_bMinSpecified = false;
673   m_bMaxSpecified = false;
674   if (theApp->getSetModifyNewDocs())
675     GetDocument()->Modify(TRUE);
676   GetDocument()->UpdateAllViews(this);
677 }
678 #endif
679
680 void
681 ImageFileView::OnFourier (wxCommandEvent& event)
682 {
683   ImageFile& rIF = GetDocument()->getImageFile();
684   wxProgressDialog dlgProgress (wxString("Fourier"), wxString("Fourier Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
685   rIF.fourier (rIF);
686   rIF.labelAdd ("Fourier Image");
687   m_bMinSpecified = false;
688   m_bMaxSpecified = false;
689   if (theApp->getSetModifyNewDocs())
690     GetDocument()->Modify(TRUE);
691   GetDocument()->UpdateAllViews(this);
692 }
693
694 void
695 ImageFileView::OnInverseFourier (wxCommandEvent& event)
696 {
697   ImageFile& rIF = GetDocument()->getImageFile();
698   wxProgressDialog dlgProgress (wxString("Inverse Fourier"), wxString("Inverse Fourier Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
699   rIF.inverseFourier (rIF);
700   rIF.labelAdd ("Inverse Fourier Image");
701   m_bMinSpecified = false;
702   m_bMaxSpecified = false;
703   if (theApp->getSetModifyNewDocs())
704     GetDocument()->Modify(TRUE);
705   GetDocument()->UpdateAllViews(this);
706 }
707
708 void
709 ImageFileView::OnShuffleNaturalToFourierOrder (wxCommandEvent& event)
710 {
711   ImageFile& rIF = GetDocument()->getImageFile();
712   Fourier::shuffleNaturalToFourierOrder (rIF);
713   rIF.labelAdd ("Shuffle Natural To Fourier Order");
714   m_bMinSpecified = false;
715   m_bMaxSpecified = false;
716   if (theApp->getSetModifyNewDocs())
717     GetDocument()->Modify(TRUE);
718   GetDocument()->UpdateAllViews(this);
719 }
720
721 void
722 ImageFileView::OnShuffleFourierToNaturalOrder (wxCommandEvent& event)
723 {
724   ImageFile& rIF = GetDocument()->getImageFile();
725   Fourier::shuffleFourierToNaturalOrder (rIF);
726   rIF.labelAdd ("Shuffle Fourier To Natural Order");
727   m_bMinSpecified = false;
728   m_bMaxSpecified = false;
729   if (theApp->getSetModifyNewDocs())
730     GetDocument()->Modify(TRUE);
731   GetDocument()->UpdateAllViews(this);
732 }
733
734 void
735 ImageFileView::OnMagnitude (wxCommandEvent& event)
736 {
737   ImageFile& rIF = GetDocument()->getImageFile();
738   if (rIF.isComplex()) {
739     rIF.magnitude (rIF);
740     rIF.labelAdd ("Magnitude of complex-image");
741     m_bMinSpecified = false;
742     m_bMaxSpecified = false;
743     if (theApp->getSetModifyNewDocs())
744       GetDocument()->Modify(TRUE);
745     GetDocument()->UpdateAllViews(this);
746   }
747 }
748
749 void
750 ImageFileView::OnPhase (wxCommandEvent& event)
751 {
752   ImageFile& rIF = GetDocument()->getImageFile();
753   if (rIF.isComplex()) {
754     rIF.phase (rIF);
755     rIF.labelAdd ("Phase of complex-image");
756     m_bMinSpecified = false;
757     m_bMaxSpecified = false;
758     if (theApp->getSetModifyNewDocs())
759       GetDocument()->Modify(TRUE);
760     GetDocument()->UpdateAllViews(this);
761   }
762 }
763
764
765 ImageFileCanvas* 
766 ImageFileView::CreateCanvas (wxView *view, wxFrame *parent)
767 {
768   ImageFileCanvas* pCanvas;
769   int width, height;
770   parent->GetClientSize(&width, &height);
771   
772   pCanvas = new ImageFileCanvas (dynamic_cast<ImageFileView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
773   
774   pCanvas->SetScrollbars(20, 20, 50, 50);
775   pCanvas->SetBackgroundColour(*wxWHITE);
776   pCanvas->Clear();
777   
778   return pCanvas;
779 }
780
781 #if CTSIM_MDI
782 wxDocMDIChildFrame*
783 #else
784 wxDocChildFrame*
785 #endif
786 ImageFileView::CreateChildFrame(wxDocument *doc, wxView *view)
787 {
788 #if CTSIM_MDI
789   wxDocMDIChildFrame* subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1, -1), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
790 #else
791   wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1, -1), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
792 #endif
793   theApp->setIconForFrame (subframe);
794   
795   wxMenu *m_pFileMenu = new wxMenu;
796   
797   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
798   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
799   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
800   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
801   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
802   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
803   
804   m_pFileMenu->AppendSeparator();
805   m_pFileMenu->Append(IFMENU_FILE_PROPERTIES, "P&roperties");
806   m_pFileMenu->Append(IFMENU_FILE_EXPORT, "&Export...");
807   
808   m_pFileMenu->AppendSeparator();
809   m_pFileMenu->Append(wxID_PRINT, "&Print...");
810   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
811   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
812 #ifdef CTSIM_MDI
813   m_pFileMenu->AppendSeparator();
814   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
815 #endif
816   theApp->getDocManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
817   theApp->getDocManager()->FileHistoryUseMenu(m_pFileMenu);
818   
819   wxMenu *view_menu = new wxMenu;
820   view_menu->Append(IFMENU_VIEW_SCALE_MINMAX, "Display Scale S&et...\tCtrl-E");
821   view_menu->Append(IFMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
822   view_menu->Append(IFMENU_VIEW_SCALE_FULL, "Display F&ull Scale\tCtrl-U");
823   
824   wxMenu* filter_menu = new wxMenu;
825   filter_menu->Append (IFMENU_FILTER_INVERTVALUES, "&Invert Values");
826   filter_menu->Append (IFMENU_FILTER_SQUARE, "&Square");
827   filter_menu->Append (IFMENU_FILTER_SQRT, "Square &Root");
828   filter_menu->Append (IFMENU_FILTER_LOG, "&Log");
829   filter_menu->Append (IFMENU_FILTER_EXP, "&Exp");
830   filter_menu->AppendSeparator();
831 #ifdef HAVE_FFT
832   filter_menu->Append (IFMENU_FILTER_FFT, "2D &FFT");
833   filter_menu->Append (IFMENU_FILTER_IFFT, "2D &IFFT");
834   filter_menu->Append (IFMENU_FILTER_FFT_ROWS, "FFT Rows");
835   filter_menu->Append (IFMENU_FILTER_IFFT_ROWS, "IFFT Rows");
836   filter_menu->Append (IFMENU_FILTER_FFT_COLS, "FFT Columns");
837   filter_menu->Append (IFMENU_FILTER_IFFT_COLS, "IFFT Columns");
838   filter_menu->Append (IFMENU_FILTER_FOURIER, "F&ourier");
839   filter_menu->Append (IFMENU_FILTER_INVERSE_FOURIER, "Inverse Fo&urier");
840 #else
841   filter_menu->Append (IFMENU_FILTER_FOURIER, "&Fourier");
842   filter_menu->Append (IFMENU_FILTER_INVERSE_FOURIER, "&Inverse Fourier");
843 #endif
844   filter_menu->Append (IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER, "S&huffle Fourier to Natural Order");
845   filter_menu->Append (IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER, "Shu&ffle Natural to Fourier Order");
846   filter_menu->Append (IFMENU_FILTER_MAGNITUDE, "&Magnitude");
847   filter_menu->Append (IFMENU_FILTER_PHASE, "&Phase");
848   
849   wxMenu* image_menu = new wxMenu;
850   image_menu->Append (IFMENU_IMAGE_ADD, "&Add...");
851   image_menu->Append (IFMENU_IMAGE_SUBTRACT, "&Subtract...");
852   image_menu->Append (IFMENU_IMAGE_MULTIPLY, "&Multiply...");
853   image_menu->Append (IFMENU_IMAGE_DIVIDE, "&Divide...");
854   image_menu->AppendSeparator();
855   image_menu->Append (IFMENU_IMAGE_SCALESIZE, "S&cale Size...");
856   
857   wxMenu *analyze_menu = new wxMenu;
858   analyze_menu->Append (IFMENU_PLOT_ROW, "Plot &Row");
859   analyze_menu->Append (IFMENU_PLOT_COL, "Plot &Column");
860   analyze_menu->Append (IFMENU_PLOT_HISTOGRAM, "Plot &Histogram");
861   analyze_menu->AppendSeparator();
862   analyze_menu->Append (IFMENU_PLOT_FFT_ROW, "Plot FFT Row");
863   analyze_menu->Append (IFMENU_PLOT_FFT_COL, "Plot FFT Column");
864   analyze_menu->AppendSeparator();
865   analyze_menu->Append (IFMENU_COMPARE_IMAGES, "Compare &Images...");
866   analyze_menu->Append (IFMENU_COMPARE_ROW, "Compare &Row");
867   analyze_menu->Append (IFMENU_COMPARE_COL, "Compare &Column");
868   
869   wxMenu *help_menu = new wxMenu;
870   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
871   help_menu->Append(MAINMENU_HELP_TOPICS, "&Topics\tCtrl-H");
872   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
873   
874   wxMenuBar *menu_bar = new wxMenuBar;
875   
876   menu_bar->Append(m_pFileMenu, "&File");
877   menu_bar->Append(view_menu, "&View");
878   menu_bar->Append(image_menu, "&Image");
879   menu_bar->Append(filter_menu, "Fi&lter");
880   menu_bar->Append(analyze_menu, "&Analyze");
881   menu_bar->Append(help_menu, "&Help");
882   
883   subframe->SetMenuBar(menu_bar);
884   
885   subframe->Centre(wxBOTH);
886   
887   wxAcceleratorEntry accelEntries[10];
888   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('O'), wxID_OPEN);
889   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('S'), wxID_SAVE);
890   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('W'), wxID_CLOSE);
891   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('H'), MAINMENU_HELP_TOPICS);
892   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('P'), MAINMENU_FILE_CREATE_PHANTOM);
893   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('F'), MAINMENU_FILE_CREATE_FILTER);
894   accelEntries[6].Set (wxACCEL_NORMAL, WXK_F1, MAINMENU_HELP_CONTENTS);
895   accelEntries[7].Set (wxACCEL_CTRL, static_cast<int>('A'), IFMENU_VIEW_SCALE_AUTO);
896   accelEntries[8].Set (wxACCEL_CTRL, static_cast<int>('U'), IFMENU_VIEW_SCALE_FULL);
897   accelEntries[9].Set (wxACCEL_CTRL, static_cast<int>('E'), IFMENU_VIEW_SCALE_MINMAX);
898   wxAcceleratorTable accelTable (10, accelEntries);
899   subframe->SetAcceleratorTable (accelTable);
900   
901   return subframe;
902 }
903
904
905 bool 
906 ImageFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
907 {
908   m_pFrame = CreateChildFrame(doc, this);
909   SetFrame (m_pFrame);
910   
911   m_bMinSpecified = false;
912   m_bMaxSpecified = false;
913   m_dAutoScaleFactor = 1.;
914   
915   int width, height;
916   m_pFrame->GetClientSize (&width, &height);
917   m_pFrame->SetTitle("ImageFileView");
918   m_canvas = CreateCanvas (this, m_pFrame);
919   
920   int x, y;  // X requires a forced resize
921   m_pFrame->GetSize(&x, &y);
922   m_pFrame->SetSize(-1, -1, x, y);
923   m_pFrame->SetFocus();
924   m_pFrame->Show(true);
925   Activate(true);
926   
927   return true;
928 }
929
930 void 
931 ImageFileView::OnDraw (wxDC* dc)
932 {
933   wxSize sizeWindow = m_pFrame->GetClientSize();
934   wxSize sizeBest = m_canvas->GetBestSize();
935   if (sizeWindow.x > sizeBest.x || sizeWindow.y > sizeBest.y)
936     m_pFrame->SetClientSize (sizeBest);
937   
938   if (m_bitmap.Ok())
939     dc->DrawBitmap(m_bitmap, 0, 0, false);
940   
941   int xCursor, yCursor;
942   if (m_canvas->GetCurrentCursor (xCursor, yCursor))
943     m_canvas->DrawRubberBandCursor (*dc, xCursor, yCursor);
944 }
945
946
947 void 
948 ImageFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
949 {
950   const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
951   ImageFileArrayConst v = rIF.getArray();
952   int nx = rIF.nx();
953   int ny = rIF.ny();
954   if (v != NULL && nx != 0 && ny != 0) {
955     if (! m_bMinSpecified || ! m_bMaxSpecified) {
956       double min, max;
957       rIF.getMinMax (min, max);
958       if (! m_bMinSpecified)
959         m_dMinPixel = min;
960       if (! m_bMaxSpecified)
961         m_dMaxPixel = max;
962     }
963     double scaleWidth = m_dMaxPixel - m_dMinPixel;
964     
965     unsigned char* imageData = new unsigned char [nx * ny * 3];
966     for (int ix = 0; ix < nx; ix++) {
967       for (int iy = 0; iy < ny; iy++) {
968         double scaleValue = ((v[ix][iy] - m_dMinPixel) / scaleWidth) * 255;
969         int intensity = static_cast<int>(scaleValue + 0.5);
970         intensity = clamp (intensity, 0, 255);
971         int baseAddr = ((ny - 1 - iy) * nx + ix) * 3;
972         imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
973       }
974     }
975     wxImage image (nx, ny, imageData, true);
976     m_bitmap = image.ConvertToBitmap();
977     delete imageData;
978     int xSize = nx;
979     int ySize = ny;
980     ySize = clamp (ySize, 0, 800);
981     m_pFrame->SetClientSize (xSize, ySize);
982     m_canvas->SetScrollbars(20, 20, nx/20, ny/20);
983     m_canvas->SetBackgroundColour(*wxWHITE);
984   } 
985   
986   if (m_canvas)
987     m_canvas->Refresh();
988 }
989
990 bool 
991 ImageFileView::OnClose (bool deleteWindow)
992 {
993   if (! GetDocument() || ! GetDocument()->Close())
994     return false;
995   
996   if (m_canvas) {
997     m_canvas->Clear();
998         m_canvas->Show(false);
999     m_canvas->setView(NULL);
1000     m_canvas = NULL;
1001   }
1002   wxString s(theApp->GetAppName());
1003   if (m_pFrame)
1004     m_pFrame->SetTitle(s);
1005   SetFrame(NULL);
1006   
1007   Activate(false);
1008   
1009   if (deleteWindow) {
1010           m_pFrame->Show(false);
1011           m_pFrame->Destroy();
1012 //        delete m_pFrame;
1013     m_pFrame = NULL;
1014   }
1015   return true;
1016 }
1017
1018 void
1019 ImageFileView::OnExport (wxCommandEvent& event)
1020 {
1021   ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
1022   ImageFileArrayConst v = rIF.getArray();
1023   int nx = rIF.nx();
1024   int ny = rIF.ny();
1025   if (v != NULL && nx != 0 && ny != 0) {
1026     if (! m_bMinSpecified || ! m_bMaxSpecified) {
1027       double min, max;
1028       rIF.getMinMax (min, max);
1029       if (! m_bMinSpecified)
1030         m_dMinPixel = min;
1031       if (! m_bMaxSpecified)
1032         m_dMaxPixel = max;
1033     }
1034     
1035     DialogExportParameters dialogExport (getFrameForChild(), m_iDefaultExportFormatID);
1036     if (dialogExport.ShowModal() == wxID_OK) {
1037       wxString strFormatName (dialogExport.getFormatName ());
1038       m_iDefaultExportFormatID = ImageFile::convertFormatNameToID (strFormatName.c_str());
1039       
1040       wxString strExt;
1041       wxString strWildcard;
1042       if (m_iDefaultExportFormatID == ImageFile::FORMAT_PGM || m_iDefaultExportFormatID == ImageFile::FORMAT_PGMASCII) {
1043         strExt = ".pgm";
1044         strWildcard = "PGM Files (*.pgm)|*.pgm";
1045       }
1046 #ifdef HAVE_PNG
1047       else if (m_iDefaultExportFormatID == ImageFile::FORMAT_PNG || m_iDefaultExportFormatID == ImageFile::FORMAT_PNG16) {
1048         strExt = ".png";
1049         strWildcard = "PNG Files (*.png)|*.png";
1050       }
1051 #endif
1052       
1053       const wxString& strFilename = wxFileSelector (wxString("Export Filename"), wxString(""), 
1054         wxString(""), strExt, strWildcard, wxOVERWRITE_PROMPT | wxHIDE_READONLY | wxSAVE);
1055       if (strFilename) {
1056         rIF.exportImage (strFormatName.c_str(), strFilename.c_str(), 1, 1, m_dMinPixel, m_dMaxPixel);
1057         *theApp->getLog() << "Exported file " << strFilename << "\n";
1058       }
1059     }
1060   }
1061 }
1062
1063 void
1064 ImageFileView::OnScaleSize (wxCommandEvent& event)
1065 {
1066   ImageFile& rIF = GetDocument()->getImageFile();
1067   unsigned int iOldNX = rIF.nx();
1068   unsigned int iOldNY = rIF.ny();
1069   
1070   DialogGetXYSize dialogGetXYSize (getFrameForChild(), "Set New X & Y Dimensions", iOldNX, iOldNY);
1071   if (dialogGetXYSize.ShowModal() == wxID_OK) {
1072     unsigned int iNewNX = dialogGetXYSize.getXSize();
1073     unsigned int iNewNY = dialogGetXYSize.getYSize();
1074     std::ostringstream os;
1075     os << "Scale Size from (" << iOldNX << "," << iOldNY << ") to (" << iNewNX << "," << iNewNY << ")";
1076     ImageFileDocument* pScaledDoc = theApp->newImageDoc();
1077     if (! pScaledDoc) {
1078       sys_error (ERR_SEVERE, "Unable to create image file");
1079       return;
1080     }
1081     ImageFile& rScaledIF = pScaledDoc->getImageFile();
1082     rScaledIF.setArraySize (iNewNX, iNewNY);
1083     rScaledIF.labelsCopy (rIF);
1084     rScaledIF.labelAdd (os.str().c_str());
1085     rIF.scaleImage (rScaledIF);
1086     *theApp->getLog() << os.str().c_str() << "\n";
1087     if (theApp->getSetModifyNewDocs())
1088       pScaledDoc->Modify(TRUE);
1089     pScaledDoc->UpdateAllViews (this);
1090     pScaledDoc->GetFirstView()->OnUpdate (this, NULL);
1091   }
1092 }
1093
1094 void
1095 ImageFileView::OnPlotRow (wxCommandEvent& event)
1096 {
1097   int xCursor, yCursor;
1098   if (! m_canvas->GetCurrentCursor (xCursor, yCursor)) {
1099     wxMessageBox ("No row selected. Please use left mouse button on image to select column","Error");
1100     return;
1101   }
1102   
1103   const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
1104   ImageFileArrayConst v = rIF.getArray();
1105   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1106   int nx = rIF.nx();
1107   int ny = rIF.ny();
1108   
1109   if (v != NULL && yCursor < ny) {
1110     double* pX = new double [nx];
1111     double* pYReal = new double [nx];
1112     double *pYImag = NULL;
1113     double *pYMag = NULL;
1114     if (rIF.isComplex()) {
1115       pYImag = new double [nx];
1116       pYMag = new double [nx];
1117     }
1118     for (int i = 0; i < nx; i++) {
1119       pX[i] = i;
1120       pYReal[i] = v[i][yCursor];
1121       if (rIF.isComplex()) {
1122         pYImag[i] = vImag[i][yCursor];
1123         pYMag[i] = ::sqrt (v[i][yCursor] * v[i][yCursor] + vImag[i][yCursor] * vImag[i][yCursor]);
1124       }
1125     }
1126     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1127     if (! pPlotDoc) {
1128       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1129     } else {
1130       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1131       std::ostringstream os;
1132       os << "Row " << yCursor;
1133       std::string title("title ");
1134       title += os.str();
1135       rPlotFile.addEzsetCommand (title.c_str());
1136       rPlotFile.addEzsetCommand ("xlabel Column");
1137       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1138       rPlotFile.addEzsetCommand ("lxfrac 0");
1139       rPlotFile.addEzsetCommand ("box");
1140       rPlotFile.addEzsetCommand ("grid");
1141       rPlotFile.addEzsetCommand ("curve 1");
1142       rPlotFile.addEzsetCommand ("color 1");
1143       if (rIF.isComplex()) {
1144         rPlotFile.addEzsetCommand ("dash 1");
1145         rPlotFile.addEzsetCommand ("curve 2");
1146         rPlotFile.addEzsetCommand ("color 4");
1147         rPlotFile.addEzsetCommand ("dash 3");
1148         rPlotFile.addEzsetCommand ("curve 3");
1149         rPlotFile.addEzsetCommand ("color 0");
1150         rPlotFile.addEzsetCommand ("solid");
1151         rPlotFile.setCurveSize (4, nx);
1152       } else
1153         rPlotFile.setCurveSize (2, nx);
1154       rPlotFile.addColumn (0, pX);
1155       rPlotFile.addColumn (1, pYReal); 
1156       if (rIF.isComplex()) {
1157         rPlotFile.addColumn (2, pYImag);
1158         rPlotFile.addColumn (3, pYMag);
1159       }
1160       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++)
1161         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1162       os << " Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1163       *theApp->getLog() << os.str().c_str() << "\n";
1164       rPlotFile.addDescription (os.str().c_str());
1165     }
1166     delete pX;
1167     delete pYReal;
1168     if (rIF.isComplex()) {
1169       delete pYImag;
1170       delete pYMag;
1171     }
1172     if (theApp->getSetModifyNewDocs())
1173       pPlotDoc->Modify(true);
1174     pPlotDoc->UpdateAllViews();
1175   }
1176 }
1177
1178 void
1179 ImageFileView::OnPlotCol (wxCommandEvent& event)
1180 {
1181   int xCursor, yCursor;
1182   if (! m_canvas->GetCurrentCursor (xCursor, yCursor)) {
1183     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1184     return;
1185   }
1186   
1187   const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
1188   ImageFileArrayConst v = rIF.getArray();
1189   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1190   int nx = rIF.nx();
1191   int ny = rIF.ny();
1192   
1193   if (v != NULL && xCursor < nx) {
1194     double* pX = new double [ny];
1195     double* pYReal = new double [ny];
1196     double* pYImag = NULL;
1197     double* pYMag = NULL;
1198     if (rIF.isComplex()) {
1199       pYImag = new double [ny];
1200       pYMag = new double [ny];
1201     }
1202     for (int i = 0; i < ny; i++) {
1203       pX[i] = i;
1204       pYReal[i] = v[xCursor][i];
1205       if (rIF.isComplex()) {
1206         pYImag[i] = vImag[xCursor][i];
1207         pYMag[i] = ::sqrt (v[xCursor][i] * v[xCursor][i] + vImag[xCursor][i] * vImag[xCursor][i]);
1208       }
1209     }
1210     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1211     if (! pPlotDoc) {
1212       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1213     } else {
1214       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1215       std::ostringstream os;
1216       os << "Column " << xCursor;
1217       std::string title("title ");
1218       title += os.str();
1219       rPlotFile.addEzsetCommand (title.c_str());
1220       rPlotFile.addEzsetCommand ("xlabel Row");
1221       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1222       rPlotFile.addEzsetCommand ("lxfrac 0");
1223       rPlotFile.addEzsetCommand ("box");
1224       rPlotFile.addEzsetCommand ("grid");
1225       rPlotFile.addEzsetCommand ("curve 1");
1226       rPlotFile.addEzsetCommand ("color 1");
1227       if (rIF.isComplex()) {
1228         rPlotFile.addEzsetCommand ("dash 1");
1229         rPlotFile.addEzsetCommand ("curve 2");
1230         rPlotFile.addEzsetCommand ("color 4");
1231         rPlotFile.addEzsetCommand ("dash 3");
1232         rPlotFile.addEzsetCommand ("curve 3");
1233         rPlotFile.addEzsetCommand ("color 0");
1234         rPlotFile.addEzsetCommand ("solid");
1235         rPlotFile.setCurveSize (4, ny);
1236       } else
1237         rPlotFile.setCurveSize (2, ny);
1238       rPlotFile.addColumn (0, pX);
1239       rPlotFile.addColumn (1, pYReal); 
1240       if (rIF.isComplex()) {
1241         rPlotFile.addColumn (2, pYImag);
1242         rPlotFile.addColumn (3, pYMag);
1243       }
1244       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++)
1245         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1246       os << " Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1247       *theApp->getLog() << os.str().c_str() << "\n";
1248       rPlotFile.addDescription (os.str().c_str());
1249     }
1250     delete pX;
1251     delete pYReal;
1252     if (rIF.isComplex()) {
1253       delete pYImag;
1254       delete pYMag;
1255     }
1256     if (theApp->getSetModifyNewDocs())
1257       pPlotDoc->Modify(true);
1258     pPlotDoc->UpdateAllViews();
1259   }
1260 }
1261
1262 #ifdef HAVE_FFT
1263 void
1264 ImageFileView::OnPlotFFTRow (wxCommandEvent& event)
1265 {
1266   int xCursor, yCursor;
1267   if (! m_canvas->GetCurrentCursor (xCursor, yCursor)) {
1268     wxMessageBox ("No row selected. Please use left mouse button on image to select column","Error");
1269     return;
1270   }
1271   
1272   const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
1273   ImageFileArrayConst v = rIF.getArray();
1274   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1275   int nx = rIF.nx();
1276   int ny = rIF.ny();
1277   
1278   if (v != NULL && yCursor < ny) {
1279     fftw_complex* pcIn = new fftw_complex [nx];
1280     
1281     int i;
1282     for (i = 0; i < nx; i++) {
1283       pcIn[i].re = v[i][yCursor];
1284       if (rIF.isComplex())
1285         pcIn[i].im = vImag[i][yCursor];
1286       else
1287         pcIn[i].im = 0;
1288     }
1289     
1290     fftw_plan plan = fftw_create_plan (nx, FFTW_FORWARD, FFTW_IN_PLACE);
1291     fftw_one (plan, pcIn, NULL);
1292     fftw_destroy_plan (plan);
1293     
1294     double* pX = new double [nx];
1295     double* pYReal = new double [nx];
1296     double* pYImag = new double [nx];
1297     double* pYMag = new double [nx];
1298     for (i = 0; i < nx; i++) {
1299       pX[i] = i;
1300       pYReal[i] = pcIn[i].re;
1301       pYImag[i] = pcIn[i].im;
1302       pYMag[i] = ::sqrt (pcIn[i].re * pcIn[i].re + pcIn[i].im * pcIn[i].im);
1303     }
1304     Fourier::shuffleFourierToNaturalOrder (pYReal, nx);
1305     Fourier::shuffleFourierToNaturalOrder (pYImag, nx);
1306     Fourier::shuffleFourierToNaturalOrder (pYMag, nx);
1307     
1308     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1309     if (! pPlotDoc) {
1310       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1311     } else {
1312       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1313       std::ostringstream os;
1314       os << "Row " << yCursor;
1315       std::string title("title ");
1316       title += os.str();
1317       rPlotFile.addEzsetCommand (title.c_str());
1318       rPlotFile.addEzsetCommand ("xlabel Column");
1319       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1320       rPlotFile.addEzsetCommand ("lxfrac 0");
1321       rPlotFile.addEzsetCommand ("curve 1");
1322       rPlotFile.addEzsetCommand ("color 1");
1323       rPlotFile.addEzsetCommand ("dash 1");
1324       rPlotFile.addEzsetCommand ("curve 2");
1325       rPlotFile.addEzsetCommand ("color 4");
1326       rPlotFile.addEzsetCommand ("dash 3");
1327       rPlotFile.addEzsetCommand ("curve 3");
1328       rPlotFile.addEzsetCommand ("color 0");
1329       rPlotFile.addEzsetCommand ("solid");
1330       rPlotFile.addEzsetCommand ("box");
1331       rPlotFile.addEzsetCommand ("grid");
1332       rPlotFile.setCurveSize (4, nx);
1333       rPlotFile.addColumn (0, pX);
1334       rPlotFile.addColumn (1, pYReal);
1335       rPlotFile.addColumn (2, pYImag);
1336       rPlotFile.addColumn (3, pYMag);
1337       for (int iL = 0; iL < rIF.nLabels(); iL++)
1338         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1339       os << " FFT Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1340       *theApp->getLog() << os.str().c_str() << "\n";
1341       rPlotFile.addDescription (os.str().c_str());
1342     }
1343     delete pX;
1344     delete pYReal;
1345     delete pYImag;
1346     delete pYMag;
1347     delete [] pcIn;
1348     
1349     if (theApp->getSetModifyNewDocs())
1350       pPlotDoc->Modify(true);
1351     pPlotDoc->UpdateAllViews();
1352   }
1353 }
1354
1355 void
1356 ImageFileView::OnPlotFFTCol (wxCommandEvent& event)
1357 {
1358   int xCursor, yCursor;
1359   if (! m_canvas->GetCurrentCursor (xCursor, yCursor)) {
1360     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1361     return;
1362   }
1363   
1364   const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
1365   ImageFileArrayConst v = rIF.getArray();
1366   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1367   int nx = rIF.nx();
1368   int ny = rIF.ny();
1369   
1370   if (v != NULL && xCursor < nx) {
1371     fftw_complex* pcIn = new fftw_complex [ny];
1372     double *pdTemp = new double [ny];
1373     
1374     int i;
1375     for (i = 0; i < ny; i++)
1376       pdTemp[i] = v[xCursor][i];
1377     Fourier::shuffleNaturalToFourierOrder (pdTemp, ny);
1378     for (i = 0; i < ny; i++) 
1379       pcIn[i].re = pdTemp[i];
1380     
1381     for (i = 0; i < ny; i++) {
1382       if (rIF.isComplex())
1383         pdTemp[i] = vImag[xCursor][i];
1384       else
1385         pdTemp[i] = 0;
1386     }
1387     Fourier::shuffleNaturalToFourierOrder (pdTemp, ny);
1388     for (i = 0; i < ny; i++)
1389       pcIn[i].im = pdTemp[i];
1390     
1391     fftw_plan plan = fftw_create_plan (ny, FFTW_BACKWARD, FFTW_IN_PLACE);
1392     fftw_one (plan, pcIn, NULL);
1393     fftw_destroy_plan (plan);
1394     
1395     double* pX = new double [ny];
1396     double* pYReal = new double [ny];
1397     double* pYImag = new double [ny];
1398     double* pYMag = new double [ny];
1399     for (i = 0; i < ny; i++) {
1400       pX[i] = i;
1401       pYReal[i] = pcIn[i].re;
1402       pYImag[i] = pcIn[i].im;
1403       pYMag[i] = ::sqrt (pcIn[i].re * pcIn[i].re + pcIn[i].im * pcIn[i].im);
1404     }
1405     
1406     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1407     if (! pPlotDoc) {
1408       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1409     } else {
1410       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1411       std::ostringstream os;
1412       os << "Column " << xCursor;
1413       std::string title("title ");
1414       title += os.str();
1415       rPlotFile.addEzsetCommand (title.c_str());
1416       rPlotFile.addEzsetCommand ("xlabel Column");
1417       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1418       rPlotFile.addEzsetCommand ("lxfrac 0");
1419       rPlotFile.addEzsetCommand ("curve 1");
1420       rPlotFile.addEzsetCommand ("color 1");
1421       rPlotFile.addEzsetCommand ("dash 1");
1422       rPlotFile.addEzsetCommand ("curve 2");
1423       rPlotFile.addEzsetCommand ("color 4");
1424       rPlotFile.addEzsetCommand ("dash 3");
1425       rPlotFile.addEzsetCommand ("curve 3");
1426       rPlotFile.addEzsetCommand ("color 0");
1427       rPlotFile.addEzsetCommand ("solid");
1428       rPlotFile.addEzsetCommand ("box");
1429       rPlotFile.addEzsetCommand ("grid");
1430       rPlotFile.setCurveSize (4, ny);
1431       rPlotFile.addColumn (0, pX);
1432       rPlotFile.addColumn (1, pYReal);
1433       rPlotFile.addColumn (2, pYImag);
1434       rPlotFile.addColumn (3, pYMag);
1435       for (int iL = 0; iL < rIF.nLabels(); iL++)
1436         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1437       os << " FFT Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1438       *theApp->getLog() << os.str().c_str() << "\n";
1439       rPlotFile.addDescription (os.str().c_str());
1440     }
1441     delete pX;
1442     delete pYReal;
1443     delete pYImag;
1444     delete pYMag;
1445     delete pdTemp;
1446     delete [] pcIn;
1447     
1448     if (theApp->getSetModifyNewDocs())
1449       pPlotDoc->Modify(true);
1450     pPlotDoc->UpdateAllViews();
1451   }
1452 }
1453 #endif
1454
1455 void
1456 ImageFileView::OnCompareCol (wxCommandEvent& event)
1457 {
1458   int xCursor, yCursor;
1459   if (! m_canvas->GetCurrentCursor (xCursor, yCursor)) {
1460     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1461     return;
1462   }
1463   
1464   std::vector<ImageFileDocument*> vecIFDoc;
1465   theApp->getCompatibleImages (GetDocument(), vecIFDoc);
1466   if (vecIFDoc.size() == 0) {
1467     wxMessageBox ("No compatible images for Column Comparison", "Error");
1468     return;
1469   }
1470   DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Comparison Image", vecIFDoc, false);
1471   
1472   if (dialogGetCompare.ShowModal() == wxID_OK) {
1473     ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
1474     const ImageFile& rIF = GetDocument()->getImageFile();
1475     const ImageFile& rCompareIF = pCompareDoc->getImageFile();
1476     
1477     ImageFileArrayConst v1 = rIF.getArray();
1478     ImageFileArrayConst v2 = rCompareIF.getArray();
1479     int nx = rIF.nx();
1480     int ny = rIF.ny();
1481     
1482     if (v1 != NULL && xCursor < nx) {
1483       double* pX = new double [ny];
1484       double* pY1 = new double [ny];
1485       double* pY2 = new double [ny];
1486       for (int i = 0; i < ny; i++) {
1487         pX[i] = i;
1488         pY1[i] = v1[xCursor][i];
1489         pY2[i] = v2[xCursor][i];
1490       }
1491       PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1492       if (! pPlotDoc) {
1493         sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1494       } else {
1495         PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1496         std::ostringstream os;
1497         os << "Column " << xCursor << " Comparison";
1498         std::string title("title ");
1499         title += os.str();
1500         rPlotFile.addEzsetCommand (title.c_str());
1501         rPlotFile.addEzsetCommand ("xlabel Row");
1502         rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1503         rPlotFile.addEzsetCommand ("lxfrac 0");
1504         rPlotFile.addEzsetCommand ("curve 1");
1505         rPlotFile.addEzsetCommand ("color 2");
1506         rPlotFile.addEzsetCommand ("curve 2");
1507         rPlotFile.addEzsetCommand ("color 4");
1508         rPlotFile.addEzsetCommand ("dash 5");
1509         rPlotFile.addEzsetCommand ("box");
1510         rPlotFile.addEzsetCommand ("grid");
1511         rPlotFile.setCurveSize (3, ny);
1512         rPlotFile.addColumn (0, pX);
1513         rPlotFile.addColumn (1, pY1);
1514         rPlotFile.addColumn (2, pY2);
1515         
1516         unsigned int iL;
1517         for (iL = 0; iL < rIF.nLabels(); iL++) {
1518           std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1519           s += ": ";
1520           s += rIF.labelGet(iL).getLabelString();
1521           rPlotFile.addDescription (s.c_str());
1522         }
1523         for (iL = 0; iL < rCompareIF.nLabels(); iL++) {
1524           std::string s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1525           s += ": ";
1526           s += rCompareIF.labelGet(iL).getLabelString();
1527           rPlotFile.addDescription (s.c_str());
1528         }
1529         os << " Between " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
1530           << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1531         *theApp->getLog() << os.str().c_str() << "\n";
1532         rPlotFile.addDescription (os.str().c_str());
1533       }
1534       delete pX;
1535       delete pY1;
1536       delete pY2;
1537       if (theApp->getSetModifyNewDocs())
1538         pPlotDoc->Modify(true);
1539       pPlotDoc->UpdateAllViews();
1540     }
1541   }
1542 }
1543
1544 void
1545 ImageFileView::OnCompareRow (wxCommandEvent& event)
1546 {
1547   int xCursor, yCursor;
1548   if (! m_canvas->GetCurrentCursor (xCursor, yCursor)) {
1549     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1550     return;
1551   }
1552   
1553   std::vector<ImageFileDocument*> vecIFDoc;
1554   theApp->getCompatibleImages (GetDocument(), vecIFDoc);
1555   
1556   if (vecIFDoc.size() == 0) {
1557     wxMessageBox ("No compatible images for Row Comparison", "Error");
1558     return;
1559   }
1560   
1561   DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Comparison Image", vecIFDoc, false);
1562   
1563   if (dialogGetCompare.ShowModal() == wxID_OK) {
1564     ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
1565     const ImageFile& rIF = GetDocument()->getImageFile();
1566     const ImageFile& rCompareIF = pCompareDoc->getImageFile();
1567     
1568     ImageFileArrayConst v1 = rIF.getArray();
1569     ImageFileArrayConst v2 = rCompareIF.getArray();
1570     int nx = rIF.nx();
1571     int ny = rIF.ny();
1572     
1573     if (v1 != NULL && yCursor < ny) {
1574       double* pX = new double [nx];
1575       double* pY1 = new double [nx];
1576       double* pY2 = new double [nx];
1577       for (int i = 0; i < nx; i++) {
1578         pX[i] = i;
1579         pY1[i] = v1[i][yCursor];
1580         pY2[i] = v2[i][yCursor];
1581       }
1582       PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1583       if (! pPlotDoc) {
1584         sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1585       } else {
1586         PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1587         std::ostringstream os;
1588         os << "Row " << yCursor << " Comparison";
1589         std::string title("title ");
1590         title += os.str();
1591         rPlotFile.addEzsetCommand (title.c_str());
1592         rPlotFile.addEzsetCommand ("xlabel Column");
1593         rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1594         rPlotFile.addEzsetCommand ("lxfrac 0");
1595         rPlotFile.addEzsetCommand ("curve 1");
1596         rPlotFile.addEzsetCommand ("color 2");
1597         rPlotFile.addEzsetCommand ("curve 2");
1598         rPlotFile.addEzsetCommand ("color 4");
1599         rPlotFile.addEzsetCommand ("dash 5");
1600         rPlotFile.addEzsetCommand ("box");
1601         rPlotFile.addEzsetCommand ("grid");
1602         rPlotFile.setCurveSize (3, nx);
1603         rPlotFile.addColumn (0, pX);
1604         rPlotFile.addColumn (1, pY1);
1605         rPlotFile.addColumn (2, pY2);
1606         unsigned int iL;
1607         for (iL = 0; iL < rIF.nLabels(); iL++) {
1608           std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1609           s += ": ";
1610           s += rIF.labelGet(iL).getLabelString();
1611           rPlotFile.addDescription (s.c_str());
1612         }
1613         for (iL = 0; iL < rCompareIF.nLabels(); iL++) {
1614           std::string s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1615           s += ": ";
1616           s += rCompareIF.labelGet(iL).getLabelString();
1617           rPlotFile.addDescription (s.c_str());
1618         }
1619         os << " Between " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
1620           << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1621         *theApp->getLog() << os.str().c_str() << "\n";
1622         rPlotFile.addDescription (os.str().c_str());
1623       }
1624       delete pX;
1625       delete pY1;
1626       delete pY2;
1627       if (theApp->getSetModifyNewDocs())
1628         pPlotDoc->Modify(true);
1629       pPlotDoc->UpdateAllViews();
1630     }
1631   }
1632 }
1633
1634 static int NUMBER_HISTOGRAM_BINS = 256;
1635
1636 void
1637 ImageFileView::OnPlotHistogram (wxCommandEvent& event)
1638
1639   const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
1640   ImageFileArrayConst v = rIF.getArray();
1641   int nx = rIF.nx();
1642   int ny = rIF.ny();
1643   
1644   if (v != NULL && nx > 0 && ny > 0) {
1645     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1646     if (! pPlotDoc) {
1647       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1648       return;
1649     }
1650     
1651     double* pX = new double [NUMBER_HISTOGRAM_BINS];
1652     double* pY = new double [NUMBER_HISTOGRAM_BINS];
1653     double dMin, dMax;
1654     rIF.getMinMax (dMin, dMax);
1655     double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
1656     
1657     for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
1658       pX[i] = dMin + (i + 0.5) * dBinWidth;
1659       pY[i] = 0;
1660     }
1661     for (int ix = 0; ix < nx; ix++)
1662       for (int iy = 0; iy < ny; iy++) {
1663         int iBin = nearest<int> ((v[ix][iy] - dMin) / dBinWidth);
1664         if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
1665           pY[iBin] += 1;
1666       }
1667       
1668       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1669       std::ostringstream os;
1670       os << "Histogram";
1671       std::string title("title ");
1672       title += os.str();
1673       rPlotFile.addEzsetCommand (title.c_str());
1674       rPlotFile.addEzsetCommand ("xlabel Pixel Value");
1675       rPlotFile.addEzsetCommand ("ylabel Count");
1676       rPlotFile.addEzsetCommand ("box");
1677       rPlotFile.addEzsetCommand ("grid");
1678       rPlotFile.setCurveSize (2, NUMBER_HISTOGRAM_BINS);
1679       rPlotFile.addColumn (0, pX);
1680       rPlotFile.addColumn (1, pY);
1681       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++) {
1682         std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1683         s += ": ";
1684         s += rIF.labelGet(iL).getLabelString();
1685         rPlotFile.addDescription (s.c_str());
1686       }
1687       os << " Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1688       *theApp->getLog() << os.str().c_str() << "\n";
1689       rPlotFile.addDescription (os.str().c_str());
1690       delete pX;
1691       delete pY;
1692       if (theApp->getSetModifyNewDocs())
1693         pPlotDoc->Modify(true);
1694       pPlotDoc->UpdateAllViews();
1695   }
1696 }
1697
1698
1699 // PhantomCanvas
1700
1701 PhantomCanvas::PhantomCanvas (PhantomFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
1702 : wxScrolledWindow(frame, -1, pos, size, style)
1703 {
1704   m_pView = v;
1705 }
1706
1707 PhantomCanvas::~PhantomCanvas ()
1708 {
1709     m_pView = NULL;
1710 }
1711
1712 void 
1713 PhantomCanvas::OnDraw (wxDC& dc)
1714 {
1715   if (m_pView)
1716     m_pView->OnDraw(& dc);
1717 }
1718
1719
1720 // PhantomFileView
1721
1722 IMPLEMENT_DYNAMIC_CLASS(PhantomFileView, wxView)
1723
1724 BEGIN_EVENT_TABLE(PhantomFileView, wxView)
1725 EVT_MENU(PHMMENU_FILE_PROPERTIES, PhantomFileView::OnProperties)
1726 EVT_MENU(PHMMENU_PROCESS_RASTERIZE, PhantomFileView::OnRasterize)
1727 EVT_MENU(PHMMENU_PROCESS_PROJECTIONS, PhantomFileView::OnProjections)
1728 END_EVENT_TABLE()
1729
1730 PhantomFileView::PhantomFileView() 
1731 : wxView(), m_canvas(NULL), m_pFrame(NULL), m_pFileMenu(0)
1732 {
1733   m_iDefaultNDet = 367;
1734   m_iDefaultNView = 320;
1735   m_iDefaultNSample = 1;
1736   m_dDefaultRotation = 1;
1737   m_dDefaultFocalLength = 2;
1738   m_dDefaultFieldOfView = 1;
1739   m_iDefaultGeometry = Scanner::GEOMETRY_PARALLEL;
1740   m_iDefaultTrace = Trace::TRACE_NONE;
1741   
1742   m_iDefaultRasterNX = 256;
1743   m_iDefaultRasterNY = 256;
1744   m_iDefaultRasterNSamples = 2;
1745 }
1746
1747 PhantomFileView::~PhantomFileView()
1748 {
1749     theApp->getDocManager()->FileHistoryRemoveMenu (m_pFileMenu);
1750 }
1751
1752 void
1753 PhantomFileView::OnProperties (wxCommandEvent& event)
1754 {
1755   const int idPhantom = GetDocument()->getPhantomID();
1756   const wxString& namePhantom = GetDocument()->getPhantomName();
1757   std::ostringstream os;
1758   os << "Phantom " << namePhantom.c_str() << " (" << idPhantom << ")" << "\n";
1759   const Phantom& rPhantom = GetDocument()->getPhantom();
1760   rPhantom.printDefinitions (os);
1761 #if DEBUG
1762   rPhantom.print (os);
1763 #endif
1764   *theApp->getLog() << os.str().c_str() << "\n";
1765   wxMessageBox (os.str().c_str(), "Phantom Properties");
1766 }
1767
1768
1769 void
1770 PhantomFileView::OnProjections (wxCommandEvent& event)
1771 {
1772   DialogGetProjectionParameters dialogProjection (getFrameForChild(), m_iDefaultNDet, m_iDefaultNView, m_iDefaultNSample, m_dDefaultRotation, m_dDefaultFocalLength, m_dDefaultFieldOfView, m_iDefaultGeometry, m_iDefaultTrace);
1773   int retVal = dialogProjection.ShowModal();
1774   if (retVal == wxID_OK) {
1775     m_iDefaultNDet = dialogProjection.getNDet();
1776     m_iDefaultNView = dialogProjection.getNView();
1777     m_iDefaultNSample = dialogProjection.getNSamples();
1778     m_iDefaultTrace = dialogProjection.getTrace();
1779     m_dDefaultRotation = dialogProjection.getRotAngle();
1780     m_dDefaultFocalLength = dialogProjection.getFocalLengthRatio();
1781     m_dDefaultFieldOfView = dialogProjection.getFieldOfViewRatio();
1782     wxString sGeometry = dialogProjection.getGeometry();
1783     m_iDefaultGeometry = Scanner::convertGeometryNameToID (sGeometry.c_str());
1784     
1785     if (m_iDefaultNDet > 0 && m_iDefaultNView > 0 && sGeometry != "") {
1786       const Phantom& rPhantom = GetDocument()->getPhantom();
1787       ProjectionFileDocument* pProjectionDoc = theApp->newProjectionDoc();
1788       if (! pProjectionDoc) {
1789         sys_error (ERR_SEVERE, "Unable to create projection document");
1790         return;
1791       }
1792       Projections& rProj = pProjectionDoc->getProjections();
1793       Scanner theScanner (rPhantom, sGeometry.c_str(), m_iDefaultNDet, m_iDefaultNView, m_iDefaultNSample, m_dDefaultRotation, m_dDefaultFocalLength, m_dDefaultFieldOfView);
1794       if (theScanner.fail()) {
1795         *theApp->getLog() << "Failed making scanner: " << theScanner.failMessage().c_str() << "\n";
1796         return;
1797       }
1798       rProj.initFromScanner (theScanner);
1799       m_dDefaultRotation /= PI;  // convert back to PI units
1800       
1801       Timer timer;
1802       if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
1803         ProjectionsDialog dialogProjections (theScanner, rProj, rPhantom, m_iDefaultTrace, dynamic_cast<wxWindow*>(getFrameForChild()));
1804         for (int iView = 0; iView < rProj.nView(); iView++) {
1805           ::wxYield();
1806           ::wxYield();
1807           if (dialogProjections.isCancelled() || ! dialogProjections.projectView (iView)) {
1808             pProjectionDoc->DeleteAllViews();
1809             return;
1810           }
1811           ::wxYield();
1812           ::wxYield();
1813           while (dialogProjections.isPaused()) {
1814             ::wxYield();
1815             ::wxUsleep(50);
1816           }
1817         }
1818       } else {
1819         wxProgressDialog dlgProgress (wxString("Projection"), wxString("Projection Progress"), rProj.nView() + 1, getFrameForChild(), wxPD_CAN_ABORT);
1820         for (int i = 0; i < rProj.nView(); i++) {
1821           theScanner.collectProjections (rProj, rPhantom, i, 1, true, m_iDefaultTrace);
1822           if (! dlgProgress.Update (i+1)) {
1823             pProjectionDoc->DeleteAllViews();
1824             return;
1825           }
1826         }
1827       }
1828       
1829       std::ostringstream os;
1830       os << "Projections for " << rPhantom.name() << ": nDet=" << m_iDefaultNDet << ", nView=" << m_iDefaultNView << ", nSamples=" << m_iDefaultNSample << ", RotAngle=" << m_dDefaultRotation << ", FocalLengthRatio=" << m_dDefaultFocalLength << ", FieldOfViewRatio=" << m_dDefaultFieldOfView << ", Geometry=" << sGeometry.c_str();
1831       rProj.setCalcTime (timer.timerEnd());
1832       rProj.setRemark (os.str());
1833       *theApp->getLog() << os.str().c_str() << "\n";
1834       
1835       m_pFrame->Lower();
1836       ::wxYield();
1837       ProjectionFileView* projView = dynamic_cast<ProjectionFileView*>(pProjectionDoc->GetFirstView());
1838       if (projView) {
1839         projView->getFrame()->SetFocus();
1840         projView->OnUpdate (projView, NULL);
1841       }
1842       if (wxView* pView = pProjectionDoc->GetFirstView()) {
1843         if (wxFrame* pFrame = pView->GetFrame()) {
1844           pFrame->SetFocus();
1845           pFrame->Raise();
1846         }
1847         theApp->getDocManager()->ActivateView (pView, true, false);
1848       }
1849       ::wxYield();
1850       if (theApp->getSetModifyNewDocs())
1851         pProjectionDoc->Modify(true);
1852       pProjectionDoc->UpdateAllViews(this);
1853     }
1854   }
1855 }
1856
1857
1858 void
1859 PhantomFileView::OnRasterize (wxCommandEvent& event)
1860 {
1861   DialogGetRasterParameters dialogRaster (getFrameForChild(), m_iDefaultRasterNX, m_iDefaultRasterNY, m_iDefaultRasterNSamples);
1862   int retVal = dialogRaster.ShowModal();
1863   if (retVal == wxID_OK) {
1864     m_iDefaultRasterNX = dialogRaster.getXSize();
1865     m_iDefaultRasterNY  = dialogRaster.getYSize();
1866     m_iDefaultRasterNSamples = dialogRaster.getNSamples();
1867     if (m_iDefaultRasterNSamples < 1)
1868       m_iDefaultRasterNSamples = 1;
1869     if (m_iDefaultRasterNX > 0 && m_iDefaultRasterNY > 0) {
1870       const Phantom& rPhantom = GetDocument()->getPhantom();
1871       ImageFileDocument* pRasterDoc = theApp->newImageDoc();
1872       if (! pRasterDoc) {
1873         sys_error (ERR_SEVERE, "Unable to create image file");
1874         return;
1875       }
1876       ImageFile& imageFile = pRasterDoc->getImageFile();
1877       
1878       imageFile.setArraySize (m_iDefaultRasterNX, m_iDefaultRasterNX);
1879       wxProgressDialog dlgProgress (wxString("Rasterize"), wxString("Rasterization Progress"), imageFile.nx() + 1, getFrameForChild(), wxPD_CAN_ABORT);
1880       Timer timer;
1881       for (unsigned int i = 0; i < imageFile.nx(); i++) {
1882         rPhantom.convertToImagefile (imageFile, m_iDefaultRasterNSamples, Trace::TRACE_NONE, i, 1, true);
1883         if (! dlgProgress.Update(i+1)) {
1884           pRasterDoc->DeleteAllViews();
1885           return;
1886         }
1887       }
1888       if (theApp->getSetModifyNewDocs())
1889         pRasterDoc->Modify(true);
1890       pRasterDoc->UpdateAllViews(this);
1891       std::ostringstream os;
1892       os << "Rasterize Phantom " << rPhantom.name() << ": XSize=" << m_iDefaultRasterNX << ", YSize=" 
1893         << m_iDefaultRasterNY << ", nSamples=" << m_iDefaultRasterNSamples;
1894       *theApp->getLog() << os.str().c_str() << "\n";
1895       imageFile.labelAdd (os.str().c_str(), timer.timerEnd());
1896       ImageFileView* rasterView = dynamic_cast<ImageFileView*>(pRasterDoc->GetFirstView());
1897       if (rasterView) {
1898         rasterView->getFrame()->SetFocus();
1899         rasterView->OnUpdate (rasterView, NULL);
1900       }
1901       
1902     }
1903   }
1904 }
1905
1906
1907 PhantomCanvas* 
1908 PhantomFileView::CreateCanvas (wxView *view, wxFrame *parent)
1909 {
1910   PhantomCanvas* pCanvas;
1911   int width, height;
1912   parent->GetClientSize(&width, &height);
1913   
1914   pCanvas = new PhantomCanvas (dynamic_cast<PhantomFileView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
1915   
1916   pCanvas->SetBackgroundColour(*wxWHITE);
1917   pCanvas->Clear();
1918   
1919   return pCanvas;
1920 }
1921
1922 #if CTSIM_MDI
1923 wxDocMDIChildFrame*
1924 #else
1925 wxDocChildFrame*
1926 #endif
1927 PhantomFileView::CreateChildFrame(wxDocument *doc, wxView *view)
1928 {
1929 #if CTSIM_MDI
1930   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(256, 256), wxDEFAULT_FRAME_STYLE);
1931 #else
1932   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(256, 256), wxDEFAULT_FRAME_STYLE);
1933 #endif
1934   theApp->setIconForFrame (subframe);
1935   
1936   wxMenu *m_pFileMenu = new wxMenu;
1937   
1938   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
1939   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
1940   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
1941   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
1942   m_pFileMenu->Append(wxID_CLOSE, "&Close");
1943   
1944   m_pFileMenu->AppendSeparator();
1945   m_pFileMenu->Append(PHMMENU_FILE_PROPERTIES, "P&roperties");
1946   
1947   m_pFileMenu->AppendSeparator();
1948   m_pFileMenu->Append(wxID_PRINT, "&Print...");
1949   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
1950   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
1951 #ifdef CTSIM_MDI
1952   m_pFileMenu->AppendSeparator();
1953   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
1954 #endif
1955   theApp->getDocManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
1956   theApp->getDocManager()->FileHistoryUseMenu(m_pFileMenu);
1957   
1958   wxMenu *process_menu = new wxMenu;
1959   process_menu->Append(PHMMENU_PROCESS_RASTERIZE, "&Rasterize...\tCtrl-R");
1960   process_menu->Append(PHMMENU_PROCESS_PROJECTIONS, "&Projections...\tCtrl-J");
1961   
1962   wxMenu *help_menu = new wxMenu;
1963   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
1964   help_menu->Append(MAINMENU_HELP_TOPICS, "&Topics\tCtrl-H");
1965   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
1966   
1967   wxMenuBar *menu_bar = new wxMenuBar;
1968   
1969   menu_bar->Append(m_pFileMenu, "&File");
1970   menu_bar->Append(process_menu, "&Process");
1971   menu_bar->Append(help_menu, "&Help");
1972   
1973   subframe->SetMenuBar(menu_bar);
1974   subframe->Centre(wxBOTH);
1975   
1976   wxAcceleratorEntry accelEntries[8];
1977   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('O'), wxID_OPEN);
1978   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('S'), wxID_SAVE);
1979   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('H'), MAINMENU_HELP_TOPICS);
1980   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('P'), MAINMENU_FILE_CREATE_PHANTOM);
1981   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('F'), MAINMENU_FILE_CREATE_FILTER);
1982   accelEntries[5].Set (wxACCEL_NORMAL, WXK_F1, MAINMENU_HELP_CONTENTS);
1983   accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('J'), PHMMENU_PROCESS_PROJECTIONS);
1984   accelEntries[7].Set (wxACCEL_CTRL, static_cast<int>('R'), PHMMENU_PROCESS_RASTERIZE);
1985   wxAcceleratorTable accelTable (8, accelEntries);
1986   subframe->SetAcceleratorTable (accelTable);
1987   
1988   return subframe;
1989 }
1990
1991
1992 bool 
1993 PhantomFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
1994 {
1995   m_pFrame = CreateChildFrame(doc, this);
1996   SetFrame(m_pFrame);
1997   
1998   int width, height;
1999   m_pFrame->GetClientSize(&width, &height);
2000   m_pFrame->SetTitle("PhantomFileView");
2001   m_canvas = CreateCanvas (this, m_pFrame);
2002   
2003 #ifdef __X__
2004   int x, y;  // X requires a forced resize
2005   m_pFrame->GetSize(&x, &y);
2006   m_pFrame->SetSize(-1, -1, x, y);
2007 #endif
2008   
2009   m_pFrame->Show(true);
2010   Activate(true);
2011   
2012   return true;
2013 }
2014
2015 void 
2016 PhantomFileView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2017 {
2018   if (m_canvas)
2019     m_canvas->Refresh();
2020 }
2021
2022 bool 
2023 PhantomFileView::OnClose (bool deleteWindow)
2024 {
2025   if (! GetDocument() || ! GetDocument()->Close())
2026     return false;
2027   
2028   if (m_canvas) {
2029     m_canvas->Clear();
2030     m_canvas->setView(NULL);
2031         m_canvas->Show(false);
2032     m_canvas = NULL;
2033   }
2034   wxString s(wxTheApp->GetAppName());
2035   if (m_pFrame)
2036     m_pFrame->SetTitle(s);
2037   SetFrame(NULL);
2038   
2039   Activate(false);
2040   
2041   if (deleteWindow) {
2042           m_pFrame->Show(false);
2043           m_pFrame->Destroy();
2044 //    delete m_pFrame;
2045     m_pFrame = NULL;
2046   }
2047   
2048   return true;
2049 }
2050
2051 void
2052 PhantomFileView::OnDraw (wxDC* dc)
2053 {
2054   int xsize, ysize;
2055   m_canvas->GetClientSize (&xsize, &ysize);
2056   SGPDriver driver (dc, xsize, ysize);
2057   SGP sgp (driver);
2058   const Phantom& rPhantom = GetDocument()->getPhantom();
2059   sgp.setColor (C_RED);
2060   rPhantom.show (sgp);
2061 }
2062
2063 // ProjectionCanvas
2064
2065 ProjectionFileCanvas::ProjectionFileCanvas (ProjectionFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
2066 : wxScrolledWindow(frame, -1, pos, size, style)
2067 {
2068   m_pView = v;
2069 }
2070
2071 ProjectionFileCanvas::~ProjectionFileCanvas ()
2072 {
2073         m_pView = NULL;
2074 }
2075
2076 void 
2077 ProjectionFileCanvas::OnDraw(wxDC& dc)
2078 {
2079   if (m_pView)
2080     m_pView->OnDraw(& dc);
2081 }
2082
2083 wxSize
2084 ProjectionFileCanvas::GetBestSize () const
2085 {
2086   wxSize best (0, 0);
2087   if (m_pView) {
2088     Projections& rProj = m_pView->GetDocument()->getProjections();
2089     best.Set (rProj.nDet(), rProj.nView());
2090   }
2091   
2092   return best;
2093 }
2094
2095
2096 // ProjectionFileView
2097
2098 IMPLEMENT_DYNAMIC_CLASS(ProjectionFileView, wxView)
2099
2100 BEGIN_EVENT_TABLE(ProjectionFileView, wxView)
2101 EVT_MENU(PJMENU_FILE_PROPERTIES, ProjectionFileView::OnProperties)
2102 EVT_MENU(PJMENU_RECONSTRUCT_FBP, ProjectionFileView::OnReconstructFBP)
2103 EVT_MENU(PJMENU_CONVERT_POLAR, ProjectionFileView::OnConvertPolar)
2104 EVT_MENU(PJMENU_CONVERT_FFT_POLAR, ProjectionFileView::OnConvertFFTPolar)
2105 END_EVENT_TABLE()
2106
2107 ProjectionFileView::ProjectionFileView() 
2108 : wxView(), m_canvas(NULL), m_pFrame(NULL), m_pFileMenu(0)
2109 {
2110   m_iDefaultNX = 256;
2111   m_iDefaultNY = 256;
2112   m_iDefaultFilter = SignalFilter::FILTER_ABS_BANDLIMIT;
2113   m_dDefaultFilterParam = 1.;
2114 #if HAVE_FFTW
2115   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_RFFTW;
2116   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_INVERSE_FOURIER;
2117 #else
2118   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_CONVOLUTION;
2119   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT;
2120 #endif
2121   m_iDefaultZeropad = 1;
2122   m_iDefaultBackprojector = Backprojector::BPROJ_IDIFF3;
2123   m_iDefaultInterpolation = Backprojector::INTERP_LINEAR;
2124   m_iDefaultInterpParam = 1;
2125   m_iDefaultTrace = Trace::TRACE_NONE;
2126   
2127   m_iDefaultPolarNX = 256;
2128   m_iDefaultPolarNY = 256;
2129   m_iDefaultPolarInterpolation = Projections::POLAR_INTERP_BILINEAR;
2130   m_iDefaultPolarZeropad = 1;
2131 }
2132
2133 ProjectionFileView::~ProjectionFileView()
2134 {
2135         theApp->getDocManager()->FileHistoryRemoveMenu (m_pFileMenu);
2136 }
2137
2138 void
2139 ProjectionFileView::OnProperties (wxCommandEvent& event)
2140 {
2141   const Projections& rProj = GetDocument()->getProjections();
2142   std::ostringstream os;
2143   rProj.printScanInfo(os);
2144   *theApp->getLog() << os.str().c_str();
2145   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Projection File Properties", wxOK | wxICON_INFORMATION);
2146   dialogMsg.ShowModal();
2147 }
2148
2149
2150 void
2151 ProjectionFileView::OnConvertPolar (wxCommandEvent& event)
2152 {
2153   Projections& rProj = GetDocument()->getProjections();
2154   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2155     m_iDefaultPolarInterpolation, -1);
2156   if (dialogPolar.ShowModal() == wxID_OK) {
2157     wxString strInterpolation (dialogPolar.getInterpolationName());
2158     m_iDefaultPolarNX = dialogPolar.getXSize();
2159     m_iDefaultPolarNY = dialogPolar.getYSize();
2160     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2161     ImageFile& rIF = pPolarDoc->getImageFile();
2162     if (! pPolarDoc) {
2163       sys_error (ERR_SEVERE, "Unable to create image file");
2164       return;
2165     }
2166     rIF.setArraySize (m_iDefaultPolarNX, m_iDefaultPolarNY);
2167     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2168     rProj.convertPolar (rIF, m_iDefaultPolarInterpolation);
2169     rIF.labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2170     std::ostringstream os;
2171     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to polar image: xSize=" 
2172       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2173       << strInterpolation.c_str();
2174     *theApp->getLog() << os.str().c_str() << "\n";
2175     rIF.labelAdd (os.str().c_str());
2176     if (theApp->getSetModifyNewDocs())
2177       pPolarDoc->Modify(true);
2178     pPolarDoc->UpdateAllViews();
2179     pPolarDoc->GetFirstView()->OnUpdate (this, NULL);
2180   }
2181 }
2182
2183 void
2184 ProjectionFileView::OnConvertFFTPolar (wxCommandEvent& event)
2185 {
2186   Projections& rProj = GetDocument()->getProjections();
2187   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert to FFT Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2188     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad);
2189   if (dialogPolar.ShowModal() == wxID_OK) {
2190     wxString strInterpolation (dialogPolar.getInterpolationName());
2191     m_iDefaultPolarNX = dialogPolar.getXSize();
2192     m_iDefaultPolarNY = dialogPolar.getYSize();
2193     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2194     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2195     ImageFile& rIF = pPolarDoc->getImageFile();
2196     if (! pPolarDoc) {
2197       sys_error (ERR_SEVERE, "Unable to create image file");
2198       return;
2199     }
2200     rIF.setArraySize (m_iDefaultPolarNX, m_iDefaultPolarNY);
2201     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2202     rProj.convertFFTPolar (rIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad);
2203     rIF.labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2204     std::ostringstream os;
2205     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to FFT polar image: xSize=" 
2206       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2207       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2208     *theApp->getLog() << os.str().c_str() << "\n";
2209     rIF.labelAdd (os.str().c_str());
2210     if (theApp->getSetModifyNewDocs())
2211       pPolarDoc->Modify(true);
2212     pPolarDoc->UpdateAllViews();
2213     pPolarDoc->GetFirstView()->OnUpdate (this, NULL);
2214 }}
2215
2216 void
2217 ProjectionFileView::OnReconstructFourier (wxCommandEvent& event)
2218 {
2219   wxMessageBox ("Fourier Reconstruction is not yet supported", "Unimplemented function");
2220 }
2221
2222 void
2223 ProjectionFileView::OnReconstructFBP (wxCommandEvent& event)
2224 {
2225   DialogGetReconstructionParameters dialogReconstruction (getFrameForChild(), m_iDefaultNX, m_iDefaultNY, m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration, m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector, m_iDefaultTrace);
2226   
2227   int retVal = dialogReconstruction.ShowModal();
2228   if (retVal == wxID_OK) {
2229     m_iDefaultNX = dialogReconstruction.getXSize();
2230     m_iDefaultNY = dialogReconstruction.getYSize();
2231     wxString optFilterName = dialogReconstruction.getFilterName();
2232     m_iDefaultFilter = SignalFilter::convertFilterNameToID (optFilterName.c_str());
2233     m_dDefaultFilterParam = dialogReconstruction.getFilterParam();
2234     wxString optFilterMethodName = dialogReconstruction.getFilterMethodName();
2235     m_iDefaultFilterMethod = ProcessSignal::convertFilterMethodNameToID(optFilterMethodName.c_str());
2236     m_iDefaultZeropad = dialogReconstruction.getZeropad();
2237     wxString optFilterGenerationName = dialogReconstruction.getFilterGenerationName();
2238     m_iDefaultFilterGeneration = ProcessSignal::convertFilterGenerationNameToID (optFilterGenerationName.c_str());
2239     wxString optInterpName = dialogReconstruction.getInterpName();
2240     m_iDefaultInterpolation = Backprojector::convertInterpNameToID (optInterpName.c_str());
2241     m_iDefaultInterpParam = dialogReconstruction.getInterpParam();
2242     wxString optBackprojectName = dialogReconstruction.getBackprojectName();
2243     m_iDefaultBackprojector = Backprojector::convertBackprojectNameToID (optBackprojectName.c_str());
2244     m_iDefaultTrace = dialogReconstruction.getTrace();
2245     if (m_iDefaultNX > 0 && m_iDefaultNY > 0) {
2246       ImageFileDocument* pReconDoc = theApp->newImageDoc();
2247       if (! pReconDoc) {
2248         sys_error (ERR_SEVERE, "Unable to create image file");
2249         return;
2250       }
2251       ImageFile& imageFile = pReconDoc->getImageFile();
2252       const Projections& rProj = GetDocument()->getProjections();
2253       imageFile.setArraySize (m_iDefaultNX, m_iDefaultNY);
2254       
2255       Reconstructor* pReconstruct = new Reconstructor (rProj, imageFile, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace);
2256       
2257       Timer timerRecon;
2258       if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
2259         ReconstructDialog* pDlgReconstruct = new ReconstructDialog (*pReconstruct, rProj, imageFile, m_iDefaultTrace, getFrameForChild());
2260         for (int iView = 0; iView < rProj.nView(); iView++) {
2261           ::wxYield();
2262           ::wxYield();
2263           if (pDlgReconstruct->isCancelled() || ! pDlgReconstruct->reconstructView (iView)) {
2264             delete pDlgReconstruct;
2265             delete pReconstruct;
2266             pReconDoc->DeleteAllViews();
2267             return;
2268           }
2269           ::wxYield();
2270           ::wxYield();
2271           while (pDlgReconstruct->isPaused()) {
2272             ::wxYield();
2273             ::wxUsleep(50);
2274           }
2275         }
2276         delete pDlgReconstruct;
2277       } else {
2278         wxProgressDialog dlgProgress (wxString("Reconstruction"), wxString("Reconstruction Progress"), rProj.nView() + 1, getFrameForChild(), wxPD_CAN_ABORT);
2279         for (int i = 0; i < rProj.nView(); i++) {
2280           pReconstruct->reconstructView (i, 1);
2281           if (! dlgProgress.Update(i + 1)) {
2282             delete pReconstruct;
2283             pReconDoc->DeleteAllViews();
2284             return;
2285           }
2286         }
2287       }
2288       delete pReconstruct;
2289       if (theApp->getSetModifyNewDocs())
2290         pReconDoc->Modify(true);
2291       pReconDoc->UpdateAllViews(this);
2292       ImageFileView* rasterView = dynamic_cast<ImageFileView*>(pReconDoc->GetFirstView());
2293       if (rasterView) {
2294         rasterView->getFrame()->SetFocus();
2295         rasterView->OnUpdate (rasterView, NULL);
2296       }
2297       std::ostringstream os;
2298       os << "Reconstruct " << rProj.getFilename() << ": xSize=" << m_iDefaultNX << ", ySize=" << m_iDefaultNY << ", Filter=" << optFilterName.c_str() << ", FilterParam=" << m_dDefaultFilterParam << ", FilterMethod=" << optFilterMethodName.c_str() << ", FilterGeneration=" << optFilterGenerationName.c_str() << ", Zeropad=" << m_iDefaultZeropad << ", Interpolation=" << optInterpName.c_str() << ", InterpolationParam=" << m_iDefaultInterpParam << ", Backprojection=" << optBackprojectName.c_str();
2299       *theApp->getLog() << os.str().c_str() << "\n";
2300       imageFile.labelAdd (rProj.getLabel());
2301       imageFile.labelAdd (os.str().c_str(), timerRecon.timerEnd());
2302     }
2303   }
2304 }
2305
2306
2307 ProjectionFileCanvas* 
2308 ProjectionFileView::CreateCanvas (wxView *view, wxFrame *parent)
2309 {
2310   ProjectionFileCanvas* pCanvas;
2311   int width, height;
2312   parent->GetClientSize(&width, &height);
2313   
2314   pCanvas = new ProjectionFileCanvas (dynamic_cast<ProjectionFileView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
2315   
2316   pCanvas->SetScrollbars(20, 20, 50, 50);
2317   pCanvas->SetBackgroundColour(*wxWHITE);
2318   pCanvas->Clear();
2319   
2320   return pCanvas;
2321 }
2322
2323 #if CTSIM_MDI
2324 wxDocMDIChildFrame*
2325 #else
2326 wxDocChildFrame*
2327 #endif
2328 ProjectionFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2329 {
2330 #ifdef CTSIM_MDI
2331   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2332 #else
2333   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2334 #endif
2335   theApp->setIconForFrame (subframe);
2336   
2337   wxMenu *m_pFileMenu = new wxMenu;
2338   
2339   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
2340   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
2341   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
2342   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
2343   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
2344   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
2345   
2346   m_pFileMenu->AppendSeparator();
2347   m_pFileMenu->Append(PJMENU_FILE_PROPERTIES, "P&roperties");
2348   
2349   m_pFileMenu->AppendSeparator();
2350   m_pFileMenu->Append(wxID_PRINT, "&Print...");
2351   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
2352   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
2353 #ifdef CTSIM_MDI
2354   m_pFileMenu->AppendSeparator();
2355   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
2356 #endif
2357   theApp->getDocManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
2358   theApp->getDocManager()->FileHistoryUseMenu(m_pFileMenu);
2359   
2360   wxMenu *convert_menu = new wxMenu;
2361   convert_menu->Append (PJMENU_CONVERT_POLAR, "&Polar Image...\tCtrl-L");
2362   convert_menu->Append (PJMENU_CONVERT_FFT_POLAR, "&FFT->Polar Image...\tCtrl-I");
2363   
2364   wxMenu *reconstruct_menu = new wxMenu;
2365   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP, "&Filtered Backprojection...\tCtrl-R");
2366   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FOURIER, "&Fourier...\tCtrl-E");
2367   
2368   wxMenu *help_menu = new wxMenu;
2369   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
2370   help_menu->Append(MAINMENU_HELP_TOPICS, "&Topics\tCtrl-H");
2371   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
2372   
2373   wxMenuBar *menu_bar = new wxMenuBar;
2374   
2375   menu_bar->Append (m_pFileMenu, "&File");
2376   menu_bar->Append (convert_menu, "&Convert");
2377   menu_bar->Append (reconstruct_menu, "&Reconstruct");
2378   menu_bar->Append (help_menu, "&Help");
2379   
2380   subframe->SetMenuBar(menu_bar);  
2381   subframe->Centre(wxBOTH);
2382   
2383   wxAcceleratorEntry accelEntries[11];
2384   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('O'), wxID_OPEN);
2385   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('S'), wxID_SAVE);
2386   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('W'), wxID_CLOSE);
2387   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('H'), MAINMENU_HELP_TOPICS);
2388   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('P'), MAINMENU_FILE_CREATE_PHANTOM);
2389   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('F'), MAINMENU_FILE_CREATE_FILTER);
2390   accelEntries[6].Set (wxACCEL_NORMAL, WXK_F1, MAINMENU_HELP_CONTENTS);
2391   accelEntries[7].Set (wxACCEL_CTRL, static_cast<int>('L'), PJMENU_CONVERT_POLAR);
2392   accelEntries[8].Set (wxACCEL_CTRL, static_cast<int>('I'), PJMENU_CONVERT_FFT_POLAR);
2393   accelEntries[9].Set (wxACCEL_CTRL, static_cast<int>('R'), PJMENU_RECONSTRUCT_FBP);
2394   accelEntries[10].Set (wxACCEL_CTRL, static_cast<int>('E'), PJMENU_RECONSTRUCT_FOURIER);
2395   wxAcceleratorTable accelTable (11, accelEntries);
2396   subframe->SetAcceleratorTable (accelTable);
2397   
2398   return subframe;
2399 }
2400
2401
2402 bool 
2403 ProjectionFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
2404 {
2405   m_pFrame = CreateChildFrame(doc, this);
2406   SetFrame(m_pFrame);
2407   
2408   int width, height;
2409   m_pFrame->GetClientSize(&width, &height);
2410   m_pFrame->SetTitle("ProjectionFileView");
2411   m_canvas = CreateCanvas(this, m_pFrame);
2412   
2413 #ifdef __X__
2414   int x, y;  // X requires a forced resize
2415   m_pFrame->GetSize(&x, &y);
2416   m_pFrame->SetSize(-1, -1, x, y);
2417 #endif
2418   
2419   m_pFrame->Show(true);
2420   Activate(true);
2421   
2422   return true;
2423 }
2424
2425 void 
2426 ProjectionFileView::OnDraw (wxDC* dc)
2427 {
2428   wxSize clientSize = m_pFrame->GetClientSize();
2429   wxSize bestSize = m_canvas->GetBestSize();
2430   
2431   if (clientSize.x > bestSize.x || clientSize.y > bestSize.y)
2432     m_pFrame->SetClientSize (bestSize);
2433   
2434   if (m_bitmap.Ok())
2435     dc->DrawBitmap (m_bitmap, 0, 0, false);
2436 }
2437
2438
2439 void 
2440 ProjectionFileView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2441 {
2442   const Projections& rProj = GetDocument()->getProjections();
2443   const int nDet = rProj.nDet();
2444   const int nView = rProj.nView();
2445   if (nDet != 0 && nView != 0) {
2446     const DetectorArray& detarray = rProj.getDetectorArray(0);
2447     const DetectorValue* detval = detarray.detValues();
2448     double min = detval[0];
2449     double max = detval[0];
2450     for (int iy = 0; iy < nView; iy++) {
2451       const DetectorArray& detarray = rProj.getDetectorArray(iy);
2452       const DetectorValue* detval = detarray.detValues();
2453       for (int ix = 0; ix < nDet; ix++) {
2454         if (min > detval[ix])
2455           min = detval[ix];
2456         else if (max < detval[ix])
2457           max = detval[ix];
2458       }
2459     }
2460     
2461     unsigned char* imageData = new unsigned char [nDet * nView * 3];
2462     double scale = (max - min) / 255;
2463     for (int iy2 = 0; iy2 < nView; iy2++) {
2464       const DetectorArray& detarray = rProj.getDetectorArray (iy2);
2465       const DetectorValue* detval = detarray.detValues();
2466       for (int ix = 0; ix < nDet; ix++) {
2467         int intensity = static_cast<int>(((detval[ix] - min) / scale) + 0.5);
2468         intensity = clamp(intensity, 0, 255);
2469         int baseAddr = (iy2 * nDet + ix) * 3;
2470         imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
2471       }
2472     }
2473     wxImage image (nDet, nView, imageData, true);
2474     m_bitmap = image.ConvertToBitmap();
2475     delete imageData;
2476     int xSize = nDet;
2477     int ySize = nView;
2478     xSize = clamp (xSize, 0, 800);
2479     ySize = clamp (ySize, 0, 800);
2480     m_pFrame->SetClientSize (xSize, ySize);
2481     m_canvas->SetScrollbars (20, 20, nDet/20, nView/20);
2482   }
2483   
2484   if (m_canvas)
2485     m_canvas->Refresh();
2486 }
2487
2488 bool 
2489 ProjectionFileView::OnClose (bool deleteWindow)
2490 {
2491   if (! GetDocument() || ! GetDocument()->Close())
2492     return false;
2493   
2494   if (m_canvas) {
2495     m_canvas->Clear();
2496     m_canvas->setView(NULL);
2497         m_canvas->Show(false);
2498     m_canvas = NULL;
2499   }
2500   wxString s(wxTheApp->GetAppName());
2501   if (m_pFrame)
2502     m_pFrame->SetTitle(s);
2503 //  SetFrame(NULL);
2504   
2505   Activate(false);
2506   
2507   if (deleteWindow) {
2508           m_pFrame->Show(false);
2509           m_pFrame->Destroy();
2510 //        delete m_pFrame;
2511     m_pFrame = NULL;
2512   }
2513   return true;
2514 }
2515
2516
2517
2518 // PlotFileCanvas
2519 PlotFileCanvas::PlotFileCanvas (PlotFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
2520 : wxScrolledWindow(frame, -1, pos, size, style)
2521 {
2522   m_pView = v;
2523 }
2524
2525 PlotFileCanvas::~PlotFileCanvas ()
2526 {
2527     m_pView = NULL;
2528 }
2529
2530 void 
2531 PlotFileCanvas::OnDraw(wxDC& dc)
2532 {
2533   if (m_pView)
2534     m_pView->OnDraw(& dc);
2535 }
2536
2537
2538 // PlotFileView
2539
2540 IMPLEMENT_DYNAMIC_CLASS(PlotFileView, wxView)
2541
2542 BEGIN_EVENT_TABLE(PlotFileView, wxView)
2543 EVT_MENU(PJMENU_FILE_PROPERTIES, PlotFileView::OnProperties)
2544 EVT_MENU(PLOTMENU_VIEW_SCALE_MINMAX, PlotFileView::OnScaleMinMax)
2545 EVT_MENU(PLOTMENU_VIEW_SCALE_AUTO, PlotFileView::OnScaleAuto)
2546 EVT_MENU(PLOTMENU_VIEW_SCALE_FULL, PlotFileView::OnScaleFull)
2547 END_EVENT_TABLE()
2548
2549 PlotFileView::PlotFileView() 
2550 : wxView(), m_canvas(NULL), m_pFrame(NULL), m_pEZPlot(NULL), m_pFileMenu(0)
2551 {
2552   m_bMinSpecified = false;
2553   m_bMaxSpecified = false;
2554 }
2555
2556 PlotFileView::~PlotFileView()
2557 {
2558   if (m_pEZPlot)
2559     delete m_pEZPlot;
2560
2561   theApp->getDocManager()->FileHistoryRemoveMenu (m_pFileMenu);  
2562 }
2563
2564 void
2565 PlotFileView::OnProperties (wxCommandEvent& event)
2566 {
2567   const PlotFile& rPlot = GetDocument()->getPlotFile();
2568   std::ostringstream os;
2569   os << "Columns: " << rPlot.getNumColumns() << ", Records: " << rPlot.getNumRecords() << "\n";
2570   rPlot.printHeadersBrief (os);
2571   *theApp->getLog() << os.str().c_str();
2572   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Plot File Properties", wxOK | wxICON_INFORMATION);
2573   dialogMsg.ShowModal();
2574 }
2575
2576
2577 void 
2578 PlotFileView::OnScaleAuto (wxCommandEvent& event)
2579 {
2580   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
2581   double min, max, mean, mode, median, stddev;
2582   rPlotFile.statistics (1, min, max, mean, mode, median, stddev);
2583   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
2584   int iRetVal = dialogAutoScale.ShowModal();
2585   if (iRetVal == wxID_OK) {
2586     m_bMinSpecified = true;
2587     m_bMaxSpecified = true;
2588     double dMin, dMax;
2589     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
2590       m_dMinPixel = dMin;
2591       m_dMaxPixel = dMax;
2592       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
2593       OnUpdate (this, NULL);
2594     }
2595   }
2596 }
2597
2598 void 
2599 PlotFileView::OnScaleMinMax (wxCommandEvent& event)
2600 {
2601   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
2602   double min;
2603   double max;
2604   
2605   if (! m_bMinSpecified || ! m_bMaxSpecified) {
2606     if (! rPlotFile.getMinMax (1, min, max)) {
2607       *theApp->getLog() << "Error: unable to find Min/Max\n";
2608       return;
2609     }
2610   }
2611   
2612   if (m_bMinSpecified)
2613     min = m_dMinPixel;
2614   if (m_bMaxSpecified)
2615     max = m_dMaxPixel;
2616   
2617   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Y-axis Minimum & Maximum", min, max);
2618   int retVal = dialogMinMax.ShowModal();
2619   if (retVal == wxID_OK) {
2620     m_bMinSpecified = true;
2621     m_bMaxSpecified = true;
2622     m_dMinPixel = dialogMinMax.getMinimum();
2623     m_dMaxPixel = dialogMinMax.getMaximum();
2624     OnUpdate (this, NULL);
2625   }
2626 }
2627
2628 void 
2629 PlotFileView::OnScaleFull (wxCommandEvent& event)
2630 {
2631   if (m_bMinSpecified || m_bMaxSpecified) {
2632     m_bMinSpecified = false;
2633     m_bMaxSpecified = false;
2634     OnUpdate (this, NULL);
2635   }
2636 }
2637
2638
2639 PlotFileCanvas* 
2640 PlotFileView::CreateCanvas (wxView *view, wxFrame *parent)
2641 {
2642   PlotFileCanvas* pCanvas;
2643   int width, height;
2644   parent->GetClientSize(&width, &height);
2645   
2646   pCanvas = new PlotFileCanvas (dynamic_cast<PlotFileView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
2647   
2648   pCanvas->SetBackgroundColour(*wxWHITE);
2649   pCanvas->Clear();
2650   
2651   return pCanvas;
2652 }
2653
2654 #if CTSIM_MDI
2655 wxDocMDIChildFrame*
2656 #else
2657 wxDocChildFrame*
2658 #endif
2659 PlotFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2660 {
2661 #ifdef CTSIM_MDI
2662   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(10, 10), wxSize(500, 300), wxDEFAULT_FRAME_STYLE);
2663 #else
2664   wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(10, 10), wxSize(500, 300), wxDEFAULT_FRAME_STYLE);
2665 #endif
2666   theApp->setIconForFrame (subframe);
2667   
2668   wxMenu *m_pFileMenu = new wxMenu;
2669   
2670   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
2671   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
2672   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
2673   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
2674   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
2675   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
2676   
2677   m_pFileMenu->AppendSeparator();
2678   m_pFileMenu->Append(PJMENU_FILE_PROPERTIES, "P&roperties");
2679   
2680   m_pFileMenu->AppendSeparator();
2681   m_pFileMenu->Append(wxID_PRINT, "&Print...");
2682   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
2683   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
2684 #ifdef CTSIM_MDI
2685   m_pFileMenu->AppendSeparator();
2686   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
2687 #endif
2688   theApp->getDocManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
2689   theApp->getDocManager()->FileHistoryUseMenu(m_pFileMenu);
2690   
2691   wxMenu *view_menu = new wxMenu;
2692   view_menu->Append(PLOTMENU_VIEW_SCALE_MINMAX, "Display Scale &Set...\tCtrl-E");
2693   view_menu->Append(PLOTMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
2694   view_menu->Append(PLOTMENU_VIEW_SCALE_FULL, "Display &Full Scale\tCtrl-U");
2695   
2696   wxMenu *help_menu = new wxMenu;
2697   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
2698   help_menu->Append(MAINMENU_HELP_TOPICS, "&Topics\tCtrl-H");
2699   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
2700   
2701   wxMenuBar *menu_bar = new wxMenuBar;
2702   
2703   menu_bar->Append(m_pFileMenu, "&File");
2704   menu_bar->Append(view_menu, "&View");
2705   menu_bar->Append(help_menu, "&Help");
2706   
2707   subframe->SetMenuBar(menu_bar);
2708   subframe->Centre(wxBOTH);
2709   
2710   wxAcceleratorEntry accelEntries[10];
2711   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('O'), wxID_OPEN);
2712   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('S'), wxID_SAVE);
2713   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('W'), wxID_CLOSE);
2714   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('H'), MAINMENU_HELP_TOPICS);
2715   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('P'), MAINMENU_FILE_CREATE_PHANTOM);
2716   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('F'), MAINMENU_FILE_CREATE_FILTER);
2717   accelEntries[6].Set (wxACCEL_NORMAL, WXK_F1, MAINMENU_HELP_CONTENTS);
2718   accelEntries[7].Set (wxACCEL_CTRL, static_cast<int>('E'), PLOTMENU_VIEW_SCALE_MINMAX);
2719   accelEntries[8].Set (wxACCEL_CTRL, static_cast<int>('A'), PLOTMENU_VIEW_SCALE_AUTO);
2720   accelEntries[9].Set (wxACCEL_CTRL, static_cast<int>('U'), PLOTMENU_VIEW_SCALE_FULL);
2721   wxAcceleratorTable accelTable (10, accelEntries);
2722   subframe->SetAcceleratorTable (accelTable);
2723   
2724   return subframe;
2725 }
2726
2727
2728 bool 
2729 PlotFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
2730 {
2731   m_pFrame = CreateChildFrame(doc, this);
2732   SetFrame(m_pFrame);
2733   
2734   m_bMinSpecified = false;
2735   m_bMaxSpecified = false;
2736   m_dAutoScaleFactor = 1.;
2737   
2738   int width, height;
2739   m_pFrame->GetClientSize(&width, &height);
2740   m_pFrame->SetTitle ("Plot File");
2741   m_canvas = CreateCanvas (this, m_pFrame);
2742   
2743 #ifdef __X__
2744   int x, y;  // X requires a forced resize
2745   m_pFrame->GetSize(&x, &y);
2746   m_pFrame->SetSize(-1, -1, x, y);
2747 #endif
2748   
2749   m_pFrame->Show(true);
2750   Activate(true);
2751   
2752   return true;
2753 }
2754
2755 void 
2756 PlotFileView::OnDraw (wxDC* dc)
2757 {
2758   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
2759   const int iNColumns = rPlotFile.getNumColumns();
2760   const int iNRecords = rPlotFile.getNumRecords();
2761   
2762   if (iNColumns > 0 && iNRecords > 0) {
2763     int xsize, ysize;
2764     m_canvas->GetClientSize (&xsize, &ysize);
2765     SGPDriver driver (dc, xsize, ysize);
2766     SGP sgp (driver);
2767     if (m_pEZPlot)
2768       m_pEZPlot->plot (&sgp);
2769   }
2770 }
2771
2772
2773 void 
2774 PlotFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2775 {
2776   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
2777   const int iNColumns = rPlotFile.getNumColumns();
2778   const int iNRecords = rPlotFile.getNumRecords();
2779   
2780   if (iNColumns > 0 && iNRecords > 0) {
2781     if (m_pEZPlot)
2782       delete m_pEZPlot;
2783     m_pEZPlot = new EZPlot;
2784     
2785     for (unsigned int iEzset = 0; iEzset < rPlotFile.getNumEzsetCommands(); iEzset++)
2786       m_pEZPlot->ezset (rPlotFile.getEzsetCommand (iEzset));
2787     
2788     if (m_bMinSpecified) {
2789       std::ostringstream os;
2790       os << "ymin " << m_dMinPixel;
2791       m_pEZPlot->ezset (os.str());
2792     }
2793     
2794     if (m_bMaxSpecified) {
2795       std::ostringstream os;
2796       os << "ymax " << m_dMaxPixel;
2797       m_pEZPlot->ezset (os.str());
2798     }
2799     
2800     m_pEZPlot->ezset("box");
2801     m_pEZPlot->ezset("grid");
2802     
2803     double* pdXaxis = new double [iNRecords];
2804     rPlotFile.getColumn (0, pdXaxis);
2805     
2806     double* pdY = new double [iNRecords];
2807     for (int iCol = 1; iCol < iNColumns; iCol++) {
2808       rPlotFile.getColumn (iCol, pdY);
2809       m_pEZPlot->addCurve (pdXaxis, pdY, iNRecords);
2810     }
2811     
2812     delete pdXaxis;
2813     delete pdY;
2814   }
2815   
2816   if (m_canvas)
2817     m_canvas->Refresh();
2818 }
2819
2820 bool 
2821 PlotFileView::OnClose (bool deleteWindow)
2822 {
2823   if (! GetDocument() || ! GetDocument()->Close())
2824     return false;
2825   
2826   if (m_canvas) {
2827     m_canvas->Clear();
2828     m_canvas->setView (NULL);
2829         m_canvas->Show(false);
2830     m_canvas = NULL;
2831   }
2832   wxString s(wxTheApp->GetAppName());
2833   if (m_pFrame)
2834     m_pFrame->SetTitle(s);
2835   SetFrame(NULL);
2836   
2837   Activate(false);
2838   
2839   if (deleteWindow) {
2840           m_pFrame->Show(false);
2841           m_pFrame->Destroy();
2842 //        delete m_pFrame;
2843     m_pFrame = NULL;
2844   }
2845   return true;
2846 }
2847
2848
2849 ////////////////////////////////////////////////////////////////
2850
2851
2852 IMPLEMENT_DYNAMIC_CLASS(TextFileView, wxView)
2853
2854 TextFileView::~TextFileView() 
2855 {
2856     theApp->getDocManager()->FileHistoryRemoveMenu (m_pFileMenu);
2857 }
2858
2859 bool TextFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
2860 {
2861   m_pFrame = CreateChildFrame(doc, this);
2862   SetFrame (m_pFrame);
2863   
2864   int width, height;
2865   m_pFrame->GetClientSize(&width, &height);
2866   m_pFrame->SetTitle("TextFile");
2867   m_pCanvas = new TextFileCanvas (this, m_pFrame, wxPoint(0, 0), wxSize(width, height), wxTE_MULTILINE | wxTE_READONLY);
2868   m_pFrame->SetTitle("Log");
2869   
2870 #ifdef __X__
2871   // X seems to require a forced resize
2872   int x, y;
2873   frame->GetSize(&x, &y);
2874   frame->SetSize(-1, -1, x, y);
2875 #endif
2876   
2877   m_pFrame->Show (true);
2878   Activate (true);
2879   
2880   return true;
2881 }
2882
2883 // Handled by wxTextWindow
2884 void TextFileView::OnDraw(wxDC *WXUNUSED(dc) )
2885 {
2886 }
2887
2888 void TextFileView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2889 {
2890 }
2891
2892 bool 
2893 TextFileView::OnClose (bool deleteWindow)
2894 {
2895         if (m_pFrame && m_pFrame->GetTitle() == "Log")
2896        return false;
2897   
2898   if (! GetDocument() || ! GetDocument()->Close())
2899     return false;
2900
2901   m_pCanvas->Show(false);
2902   Activate(false);
2903   
2904   if (deleteWindow) {
2905           m_pFrame->Show(false);
2906           m_pFrame->Destroy();
2907 //        delete m_pFrame;
2908         m_pFrame = NULL;
2909    
2910   }
2911   return TRUE;
2912 }
2913
2914 #if CTSIM_MDI
2915 wxDocMDIChildFrame*
2916 #else
2917 wxDocChildFrame*
2918 #endif
2919 TextFileView::CreateChildFrame (wxDocument *doc, wxView *view)
2920 {
2921 #if CTSIM_MDI
2922   wxDocMDIChildFrame* subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(300, 150), wxDEFAULT_FRAME_STYLE);
2923 #else
2924   wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(300, 150), wxDEFAULT_FRAME_STYLE);
2925 #endif
2926   theApp->setIconForFrame (subframe);
2927   
2928   wxMenu *m_pFileMenu = new wxMenu;
2929   
2930   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
2931   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
2932   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
2933   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
2934   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
2935   //  m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
2936   
2937   m_pFileMenu->AppendSeparator();
2938   m_pFileMenu->Append(wxID_PRINT, "&Print...");
2939   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
2940   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
2941 #ifdef CTSIM_MDI
2942   m_pFileMenu->AppendSeparator();
2943   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
2944 #endif
2945   theApp->getDocManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
2946   theApp->getDocManager()->FileHistoryUseMenu(m_pFileMenu);
2947   
2948   wxMenu *help_menu = new wxMenu;
2949   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
2950   help_menu->Append(MAINMENU_HELP_TOPICS, "&Topics\tCtrl-H");
2951   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
2952   
2953   wxMenuBar *menu_bar = new wxMenuBar;
2954   
2955   menu_bar->Append(m_pFileMenu, "&File");
2956   menu_bar->Append(help_menu, "&Help");
2957   
2958   subframe->SetMenuBar(menu_bar);
2959   subframe->Centre(wxBOTH);
2960   
2961   wxAcceleratorEntry accelEntries[5];
2962   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('O'), wxID_OPEN);
2963   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('S'), wxID_SAVE);
2964   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('W'), wxID_CLOSE);
2965   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('H'), MAINMENU_HELP_TOPICS);
2966   accelEntries[4].Set (wxACCEL_NORMAL, WXK_F1, MAINMENU_HELP_CONTENTS);
2967   wxAcceleratorTable accelTable (5, accelEntries);
2968   subframe->SetAcceleratorTable (accelTable);
2969   
2970   return subframe;
2971 }
2972
2973
2974 // Define a constructor for my text subwindow
2975 TextFileCanvas::TextFileCanvas (TextFileView* v, wxFrame* frame, const wxPoint& pos, const wxSize& size, long style)
2976   : wxTextCtrl (frame, -1, "", pos, size, style), m_pView(v)
2977 {
2978 }
2979
2980 TextFileCanvas::~TextFileCanvas ()
2981 {
2982         m_pView = NULL;
2983 }