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