1b54cbb93ef99314a0e0780fa7b42e552ebc6ca6
[ctsim.git] / src / views.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          views.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.156 2002/05/30 17:02:32 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 #include "wx/wxprec.h"
29 #ifndef WX_PRECOMP
30 #include "wx/wx.h"
31 #endif
32
33 #if !wxUSE_DOC_VIEW_ARCHITECTURE
34 #error You must set wxUSE_DOC_VIEW_ARCHITECTURE to 1 in setup.h!
35 #endif
36
37 #include "wx/image.h"
38 #include "wx/progdlg.h"
39 #include "wx/clipbrd.h"
40
41 #include "ct.h"
42 #include "ctsim.h"
43 #include "docs.h"
44 #include "views.h"
45 #include "dialogs.h"
46 #include "dlgprojections.h"
47 #include "dlgreconstruct.h"
48 #include "backprojectors.h"
49 #include "reconstruct.h"
50 #include "timer.h"
51 #include "threadproj.h"
52 #include "threadrecon.h"
53 #include "threadraster.h"
54
55 #if defined(MSVC) || HAVE_SSTREAM
56 #include <sstream>
57 #else
58 #include <sstream_subst>
59 #endif
60
61 // Used to reduce calls to progress bar update function
62 const short int ITER_PER_UPDATE = 10;
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   
123   wxClientDC dc(this);
124   PrepareDC(dc);
125   
126   wxPoint pt(event.GetLogicalPosition(dc));
127   
128   const ImageFileDocument* pIFDoc = m_pView->GetDocument();
129   if (! pIFDoc)
130     return;
131   const ImageFile& rIF = pIFDoc->getImageFile();
132   ImageFileArrayConst v = rIF.getArray();
133   int nx = rIF.nx();
134   int ny = rIF.ny();
135   const int yPt = ny - 1 - pt.y;
136   if (event.RightIsDown()) {
137     if (pt.x >= 0 && pt.x < nx && pt.y >= 0 && pt.y < ny) {
138       std::ostringstream os;
139       os << "Image value (" << pt.x << "," << yPt << ") = " << v[pt.x][yPt];
140       if (rIF.isComplex()) {
141         double dImag = rIF.getImaginaryArray()[pt.x][yPt];
142         if (dImag < 0)
143           os << " - " << -dImag;
144         else
145           os << " + " << dImag;
146         os << "i\n";
147       } else
148         os << "\n";
149       *theApp->getLog() << os.str().c_str();
150     } else
151       *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << yPt << ")\n";
152   }
153   else if (event.LeftIsDown() || event.LeftUp() || event.RightUp()) {
154     if (pt.x >= 0 && pt.x < nx && pt.y >= 0 && pt.y < ny) {
155       if (m_xCursor >= 0 && m_yCursor >= 0) {
156         DrawRubberBandCursor (dc, m_xCursor, m_yCursor);
157       }
158       DrawRubberBandCursor (dc, pt.x, yPt);
159       m_xCursor = pt.x;
160       m_yCursor = yPt;
161       wxMenu* pMenu = m_pView->getMenuAnalyze();
162       if (pMenu && ! pMenu->IsEnabled(IFMENU_PLOT_ROW)) {
163         pMenu->Enable (IFMENU_PLOT_ROW, true);
164         pMenu->Enable (IFMENU_PLOT_COL, true);
165         pMenu->Enable (IFMENU_COMPARE_ROW, true);
166         pMenu->Enable (IFMENU_COMPARE_COL, true);
167         pMenu->Enable (IFMENU_PLOT_FFT_ROW, true);
168         pMenu->Enable (IFMENU_PLOT_FFT_COL, true);
169       }
170     } else
171       *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << yPt << ")\n";
172   }
173   if (event.LeftUp()) {
174     std::ostringstream os;
175     os << "Selected column " << pt.x << " , row " << yPt << "\n";
176     *theApp->getLog() << os.str().c_str();
177   }
178 }
179
180 void
181 ImageFileCanvas::OnChar (wxKeyEvent& event)
182 {
183   if (event.GetKeyCode() == WXK_ESCAPE) {
184     m_xCursor = -1;
185     m_yCursor = -1;
186     if (m_pView)
187       m_pView->OnUpdate (NULL);
188   } else
189     wxScrolledWindow::OnChar (event);
190 }
191
192 wxSize
193 ImageFileCanvas::GetBestSize() const
194 {
195   if (! m_pView)
196     return wxSize(0,0);
197   
198   const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
199   return wxSize (rIF.nx(), rIF.ny());
200 }
201
202
203 // ImageFileView
204
205 IMPLEMENT_DYNAMIC_CLASS(ImageFileView, wxView)
206
207 BEGIN_EVENT_TABLE(ImageFileView, wxView)
208 EVT_MENU(IFMENU_FILE_EXPORT, ImageFileView::OnExport)
209 EVT_MENU(IFMENU_FILE_PROPERTIES, ImageFileView::OnProperties)
210 EVT_MENU(IFMENU_EDIT_COPY, ImageFileView::OnEditCopy)
211 EVT_MENU(IFMENU_EDIT_CUT, ImageFileView::OnEditCut)
212 EVT_MENU(IFMENU_EDIT_PASTE, ImageFileView::OnEditPaste)
213 EVT_MENU(IFMENU_VIEW_SCALE_MINMAX, ImageFileView::OnScaleMinMax)
214 EVT_MENU(IFMENU_VIEW_SCALE_AUTO, ImageFileView::OnScaleAuto)
215 EVT_MENU(IFMENU_VIEW_SCALE_FULL, ImageFileView::OnScaleFull)
216 EVT_MENU(IFMENU_COMPARE_IMAGES, ImageFileView::OnCompare)
217 EVT_MENU(IFMENU_COMPARE_ROW, ImageFileView::OnCompareRow)
218 EVT_MENU(IFMENU_COMPARE_COL, ImageFileView::OnCompareCol)
219 EVT_MENU(IFMENU_FILTER_INVERTVALUES, ImageFileView::OnInvertValues)
220 EVT_MENU(IFMENU_FILTER_SQUARE, ImageFileView::OnSquare)
221 EVT_MENU(IFMENU_FILTER_SQRT, ImageFileView::OnSquareRoot)
222 EVT_MENU(IFMENU_FILTER_LOG, ImageFileView::OnLog)
223 EVT_MENU(IFMENU_FILTER_EXP, ImageFileView::OnExp)
224 EVT_MENU(IFMENU_FILTER_FOURIER, ImageFileView::OnFourier)
225 EVT_MENU(IFMENU_FILTER_INVERSE_FOURIER, ImageFileView::OnInverseFourier)
226 EVT_MENU(IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER, ImageFileView::OnShuffleFourierToNaturalOrder)
227 EVT_MENU(IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER, ImageFileView::OnShuffleNaturalToFourierOrder)
228 EVT_MENU(IFMENU_IMAGE_ADD, ImageFileView::OnAdd)
229 EVT_MENU(IFMENU_IMAGE_SUBTRACT, ImageFileView::OnSubtract)
230 EVT_MENU(IFMENU_IMAGE_MULTIPLY, ImageFileView::OnMultiply)
231 EVT_MENU(IFMENU_IMAGE_DIVIDE, ImageFileView::OnDivide)
232 EVT_MENU(IFMENU_IMAGE_SCALESIZE, ImageFileView::OnScaleSize)
233 #if wxUSE_GLCANVAS
234 EVT_MENU(IFMENU_IMAGE_CONVERT3D, ImageFileView::OnConvert3d)
235 #endif
236 #ifdef HAVE_FFT
237 EVT_MENU(IFMENU_FILTER_FFT, ImageFileView::OnFFT)
238 EVT_MENU(IFMENU_FILTER_IFFT, ImageFileView::OnIFFT)
239 EVT_MENU(IFMENU_FILTER_FFT_ROWS, ImageFileView::OnFFTRows)
240 EVT_MENU(IFMENU_FILTER_IFFT_ROWS, ImageFileView::OnIFFTRows)
241 EVT_MENU(IFMENU_FILTER_FFT_COLS, ImageFileView::OnFFTCols)
242 EVT_MENU(IFMENU_FILTER_IFFT_COLS, ImageFileView::OnIFFTCols)
243 #endif
244 EVT_MENU(IFMENU_FILTER_MAGNITUDE, ImageFileView::OnMagnitude)
245 EVT_MENU(IFMENU_FILTER_PHASE, ImageFileView::OnPhase)
246 EVT_MENU(IFMENU_FILTER_REAL, ImageFileView::OnReal)
247 EVT_MENU(IFMENU_FILTER_IMAGINARY, ImageFileView::OnImaginary)
248 EVT_MENU(IFMENU_PLOT_ROW, ImageFileView::OnPlotRow)
249 EVT_MENU(IFMENU_PLOT_COL, ImageFileView::OnPlotCol)
250 #ifdef HAVE_FFT
251 EVT_MENU(IFMENU_PLOT_FFT_ROW, ImageFileView::OnPlotFFTRow)
252 EVT_MENU(IFMENU_PLOT_FFT_COL, ImageFileView::OnPlotFFTCol)
253 #endif
254 EVT_MENU(IFMENU_PLOT_HISTOGRAM, ImageFileView::OnPlotHistogram)
255 END_EVENT_TABLE()
256
257 ImageFileView::ImageFileView() 
258 : wxView(), m_pFrame(NULL), m_pCanvas(NULL), m_pFileMenu(0), m_pFilterMenu(0), m_bMinSpecified(false), m_bMaxSpecified(false)
259 {
260   m_iDefaultExportFormatID = ImageFile::EXPORT_FORMAT_PNG;
261 }
262
263 ImageFileView::~ImageFileView()
264 {
265   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
266   GetDocumentManager()->ActivateView(this, FALSE, TRUE);
267 }
268
269
270 void
271 ImageFileView::OnProperties (wxCommandEvent& event)
272 {
273   const ImageFile& rIF = GetDocument()->getImageFile();
274   if (rIF.nx() == 0 || rIF.ny() == 0)
275     *theApp->getLog() << "Properties: empty imagefile\n";
276   else {
277     const std::string rFilename = m_pFrame->GetTitle().c_str();
278     std::ostringstream os;
279     double min, max, mean, mode, median, stddev;
280     rIF.statistics (rIF.getArray(), min, max, mean, mode, median, stddev);
281     os << "Filename: " << rFilename << "\n";
282     os << "Size: (" << rIF.nx() << "," << rIF.ny() << ")\n";
283     os << "Data type: ";
284     if (rIF.isComplex())
285       os << "Complex\n";
286     else
287       os << "Real\n";
288     os << "Minimum: "<<min<<"\nMaximum: "<<max<<"\nMean: "<<mean<<"\nMedian: "<<median<<"\nMode: "<<mode<<"\nStandard Deviation: "<<stddev << "\n";
289     if (rIF.isComplex()) {
290       rIF.statistics (rIF.getImaginaryArray(), min, max, mean, mode, median, stddev);
291       os << "Imaginary: min: "<<min<<"\nmax: "<<max<<"\nmean: "<<mean<<"\nmedian: "<<median<<"\nmode: "<<mode<<"\nstddev: "<<stddev << "\n";
292     }
293     if (rIF.nLabels() > 0) {
294       rIF.printLabelsBrief (os);
295     }
296     *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
297     wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Imagefile Properties", wxOK | wxICON_INFORMATION);
298     dialogMsg.ShowModal();
299   }
300   GetDocument()->Activate();
301 }
302
303 void 
304 ImageFileView::OnScaleAuto (wxCommandEvent& event)
305 {
306   const ImageFile& rIF = GetDocument()->getImageFile();
307   double min, max, mean, mode, median, stddev;
308   rIF.statistics(min, max, mean, mode, median, stddev);
309   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
310   int iRetVal = dialogAutoScale.ShowModal();
311   if (iRetVal == wxID_OK) {
312     m_bMinSpecified = true;
313     m_bMaxSpecified = true;
314     double dMin, dMax;
315     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
316       m_dMinPixel = dMin;
317       m_dMaxPixel = dMax;
318       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
319       GetDocument()->UpdateAllViews (this);
320     }
321   }
322   GetDocument()->Activate();
323 }
324
325 void 
326 ImageFileView::OnScaleMinMax (wxCommandEvent& event)
327 {
328   const ImageFile& rIF = GetDocument()->getImageFile();
329   double min, max;
330   if (! m_bMinSpecified && ! m_bMaxSpecified)
331     rIF.getMinMax (min, max);
332   
333   if (m_bMinSpecified)
334     min = m_dMinPixel;
335   if (m_bMaxSpecified)
336     max = m_dMaxPixel;
337   
338   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Image Minimum & Maximum", min, max);
339   int retVal = dialogMinMax.ShowModal();
340   if (retVal == wxID_OK) {
341     m_bMinSpecified = true;
342     m_bMaxSpecified = true;
343     m_dMinPixel = dialogMinMax.getMinimum();
344     m_dMaxPixel = dialogMinMax.getMaximum();
345     GetDocument()->UpdateAllViews (this);
346   }
347   GetDocument()->Activate();
348 }
349
350 void 
351 ImageFileView::OnScaleFull (wxCommandEvent& event)
352 {
353   if (m_bMinSpecified || m_bMaxSpecified) {
354     m_bMinSpecified = false;
355     m_bMaxSpecified = false;
356     GetDocument()->UpdateAllViews (this);
357   }
358   GetDocument()->Activate();
359 }
360
361 void
362 ImageFileView::OnCompare (wxCommandEvent& event)
363 {
364   std::vector<ImageFileDocument*> vecIF;
365   theApp->getCompatibleImages (GetDocument(), vecIF);
366   
367   if (vecIF.size() == 0) {
368     wxMessageBox("There are no compatible image files open for comparision", "No comparison images");
369   } else {
370     DialogGetComparisonImage dialogGetCompare(getFrameForChild(), "Get Comparison Image", vecIF, true);
371     
372     if (dialogGetCompare.ShowModal() == wxID_OK) {
373       const ImageFile& rIF = GetDocument()->getImageFile();
374       ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
375       const ImageFile& rCompareIF = pCompareDoc->getImageFile();
376       std::ostringstream os;
377       double min, max, mean, mode, median, stddev;
378       rIF.statistics (min, max, mean, mode, median, stddev);
379       os << GetFrame()->GetTitle().c_str() << ": minimum=" << min << ", maximum=" << max << ", mean=" << mean << ", mode=" << mode << ", median=" << median << ", stddev=" << stddev << "\n";
380       rCompareIF.statistics (min, max, mean, mode, median, stddev);
381       os << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": minimum=" << min << ", maximum=" << max << ", mean=" << mean << ", mode=" << mode << ", median=" << median << ", stddev=" << stddev << "\n";
382       double d, r, e;
383       rIF.comparativeStatistics (rCompareIF, d, r, e);
384       os << "Comparative Statistics: d=" << d << ", r=" << r << ", e=" << e << "\n";
385       *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
386       if (dialogGetCompare.getMakeDifferenceImage()) {
387         ImageFile* pDifferenceImage = new ImageFile;
388         
389         pDifferenceImage->setArraySize (rIF.nx(), rIF.ny());
390         if (! rIF.subtractImages (rCompareIF, *pDifferenceImage)) {
391           *theApp->getLog() << "Unable to subtract images\n";
392           delete pDifferenceImage;
393           return;
394         }
395         ImageFileDocument* pDifferenceDoc = theApp->newImageDoc();
396         if (! pDifferenceDoc) {
397           sys_error (ERR_SEVERE, "Unable to create image file");
398           return;
399         }
400         pDifferenceDoc->setImageFile (pDifferenceImage);
401         
402         wxString s = GetFrame()->GetTitle() + ": ";
403         pDifferenceImage->labelsCopy (rIF, s.c_str());
404         s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
405         pDifferenceImage->labelsCopy (rCompareIF, s.c_str());
406         std::ostringstream osLabel;
407         osLabel << "Compare image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() 
408           << " and " << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": "
409           << os.str().c_str();
410         pDifferenceImage->labelAdd (os.str().c_str());
411         if (theApp->getAskDeleteNewDocs())
412           pDifferenceDoc->Modify (true);
413         pDifferenceDoc->UpdateAllViews(this);
414         pDifferenceDoc->getView()->setInitialClientSize();
415         pDifferenceDoc->Activate();
416       }
417       wxMessageBox(os.str().c_str(), "Image Comparison");
418     }
419   }
420 }
421
422 void
423 ImageFileView::OnInvertValues (wxCommandEvent& event)
424 {
425   ImageFile& rIF = GetDocument()->getImageFile();
426   rIF.invertPixelValues (rIF);
427   rIF.labelAdd ("Invert Pixel Values");
428   if (theApp->getAskDeleteNewDocs())
429     GetDocument()->Modify (true);
430   GetDocument()->UpdateAllViews (this);
431   GetDocument()->Activate();
432 }
433
434 void
435 ImageFileView::OnSquare (wxCommandEvent& event)
436 {
437   ImageFile& rIF = GetDocument()->getImageFile();
438   rIF.square (rIF);
439   rIF.labelAdd ("Square Pixel Values");
440   if (theApp->getAskDeleteNewDocs())
441     GetDocument()->Modify (true);
442   GetDocument()->UpdateAllViews (this);
443   GetDocument()->Activate();
444 }
445
446 void
447 ImageFileView::OnSquareRoot (wxCommandEvent& event)
448 {
449   ImageFile& rIF = GetDocument()->getImageFile();
450   rIF.sqrt (rIF);
451   rIF.labelAdd ("Square-root Pixel Values");
452   if (theApp->getAskDeleteNewDocs())
453     GetDocument()->Modify (true);
454   GetDocument()->UpdateAllViews (this);
455   GetDocument()->Activate();
456 }
457
458 void
459 ImageFileView::OnLog (wxCommandEvent& event)
460 {
461   ImageFile& rIF = GetDocument()->getImageFile();
462   rIF.log (rIF);
463   rIF.labelAdd ("Logrithm base-e Pixel Values");
464   if (theApp->getAskDeleteNewDocs())
465     GetDocument()->Modify (true);
466   GetDocument()->UpdateAllViews (this);
467   GetDocument()->Activate();
468 }
469
470 void
471 ImageFileView::OnExp (wxCommandEvent& event)
472 {
473   ImageFile& rIF = GetDocument()->getImageFile();
474   rIF.exp (rIF);
475   rIF.labelAdd ("Exponent base-e Pixel Values");
476   if (theApp->getAskDeleteNewDocs())
477     GetDocument()->Modify (true);
478   GetDocument()->UpdateAllViews (this);
479   GetDocument()->Activate();
480 }
481
482 void
483 ImageFileView::OnAdd (wxCommandEvent& event)
484 {
485   std::vector<ImageFileDocument*> vecIF;
486   theApp->getCompatibleImages (GetDocument(), vecIF);
487   
488   if (vecIF.size() == 0) {
489     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
490   } else {
491     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Add", vecIF, false);
492     
493     if (dialogGetCompare.ShowModal() == wxID_OK) {
494       ImageFile& rIF = GetDocument()->getImageFile();
495       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
496       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
497       ImageFileDocument* pNewDoc = theApp->newImageDoc();
498       if (! pNewDoc) {
499         sys_error (ERR_SEVERE, "Unable to create image file");
500         return;
501       }
502       ImageFile& newImage = pNewDoc->getImageFile();  
503       newImage.setArraySize (rIF.nx(), rIF.ny());
504       rIF.addImages (rRHSIF, newImage);
505       std::ostringstream os;
506       os << "Add image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
507         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
508       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
509       newImage.labelsCopy (rIF, s.c_str());
510       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
511       newImage.labelsCopy (rRHSIF, s.c_str());
512       newImage.labelAdd (os.str().c_str());
513       *theApp->getLog() << os.str().c_str() << "\n";
514       if (theApp->getAskDeleteNewDocs())
515         pNewDoc->Modify (true);
516       pNewDoc->UpdateAllViews (this);
517       pNewDoc->getView()->setInitialClientSize();
518       pNewDoc->Activate();
519     }
520   }
521 }
522
523 void
524 ImageFileView::OnSubtract (wxCommandEvent& event)
525 {
526   std::vector<ImageFileDocument*> vecIF;
527   theApp->getCompatibleImages (GetDocument(), vecIF);
528   
529   if (vecIF.size() == 0) {
530     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
531   } else {
532     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Subtract", vecIF, false);
533     
534     if (dialogGetCompare.ShowModal() == wxID_OK) {
535       ImageFile& rIF = GetDocument()->getImageFile();
536       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
537       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
538       ImageFileDocument* pNewDoc = theApp->newImageDoc();
539       if (! pNewDoc) {
540         sys_error (ERR_SEVERE, "Unable to create image file");
541         return;
542       }
543       ImageFile& newImage = pNewDoc->getImageFile();  
544       newImage.setArraySize (rIF.nx(), rIF.ny());
545       rIF.subtractImages (rRHSIF, newImage);
546       std::ostringstream os;
547       os << "Subtract image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
548         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
549       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
550       newImage.labelsCopy (rIF, s.c_str());
551       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
552       newImage.labelsCopy (rRHSIF, s.c_str());
553       newImage.labelAdd (os.str().c_str());
554       *theApp->getLog() << os.str().c_str() << "\n";
555       if (theApp->getAskDeleteNewDocs())
556         pNewDoc->Modify (true);
557       pNewDoc->UpdateAllViews (this);
558       pNewDoc->getView()->setInitialClientSize();
559       pNewDoc->Activate();
560     }
561   }
562 }
563
564 void
565 ImageFileView::OnMultiply (wxCommandEvent& event)
566 {
567   std::vector<ImageFileDocument*> vecIF;
568   theApp->getCompatibleImages (GetDocument(), vecIF);
569   
570   if (vecIF.size() == 0) {
571     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
572   } else {
573     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Multiply", vecIF, false);
574     
575     if (dialogGetCompare.ShowModal() == wxID_OK) {
576       ImageFile& rIF = GetDocument()->getImageFile();
577       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
578       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
579       ImageFileDocument* pNewDoc = theApp->newImageDoc();
580       if (! pNewDoc) {
581         sys_error (ERR_SEVERE, "Unable to create image file");
582         return;
583       }
584       ImageFile& newImage = pNewDoc->getImageFile();  
585       newImage.setArraySize (rIF.nx(), rIF.ny());
586       rIF.multiplyImages (rRHSIF, newImage);
587       std::ostringstream os;
588       os << "Multiply image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
589         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
590       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
591       newImage.labelsCopy (rIF, s.c_str());
592       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
593       newImage.labelsCopy (rRHSIF, s.c_str());
594       newImage.labelAdd (os.str().c_str());
595       *theApp->getLog() << os.str().c_str() << "\n";
596       if (theApp->getAskDeleteNewDocs())
597         pNewDoc->Modify (true);
598       pNewDoc->UpdateAllViews (this);
599       pNewDoc->getView()->setInitialClientSize();
600       pNewDoc->Activate();
601     }
602   }
603 }
604
605 void
606 ImageFileView::OnDivide (wxCommandEvent& event)
607 {
608   std::vector<ImageFileDocument*> vecIF;
609   theApp->getCompatibleImages (GetDocument(), vecIF);
610   
611   if (vecIF.size() == 0) {
612     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
613   } else {
614     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Divide", vecIF, false);
615     
616     if (dialogGetCompare.ShowModal() == wxID_OK) {
617       ImageFile& rIF = GetDocument()->getImageFile();
618       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
619       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
620       ImageFileDocument* pNewDoc = theApp->newImageDoc();
621       if (! pNewDoc) {
622         sys_error (ERR_SEVERE, "Unable to create image file");
623         return;
624       }
625       ImageFile& newImage = pNewDoc->getImageFile();  
626       newImage.setArraySize (rIF.nx(), rIF.ny());
627       rIF.divideImages (rRHSIF, newImage);
628       std::ostringstream os;
629       os << "Divide image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " by " 
630         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
631       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
632       newImage.labelsCopy (rIF, s.c_str());
633       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
634       newImage.labelsCopy (rRHSIF, s.c_str());
635       newImage.labelAdd (os.str().c_str());
636       *theApp->getLog() << os.str().c_str() << "\n";
637       if (theApp->getAskDeleteNewDocs())
638         pNewDoc->Modify (true);
639       pNewDoc->UpdateAllViews (this);
640       pNewDoc->getView()->setInitialClientSize();
641       pNewDoc->Activate();
642     }
643   }
644 }
645
646
647 #ifdef HAVE_FFT
648 void
649 ImageFileView::OnFFT (wxCommandEvent& event)
650 {
651   ImageFile& rIF = GetDocument()->getImageFile();
652   rIF.fft (rIF);
653   rIF.labelAdd ("FFT Image");
654   m_bMinSpecified = false;
655   m_bMaxSpecified = false;
656   if (theApp->getAskDeleteNewDocs())
657     GetDocument()->Modify (true);
658   GetDocument()->UpdateAllViews (this);
659   GetDocument()->Activate();
660 }
661
662 void
663 ImageFileView::OnIFFT (wxCommandEvent& event)
664 {
665   ImageFile& rIF = GetDocument()->getImageFile();
666   rIF.ifft (rIF);
667   rIF.labelAdd ("IFFT Image");
668   m_bMinSpecified = false;
669   m_bMaxSpecified = false;
670   if (theApp->getAskDeleteNewDocs())
671     GetDocument()->Modify (true);
672   GetDocument()->UpdateAllViews (this);
673   GetDocument()->Activate();
674 }
675
676 void
677 ImageFileView::OnFFTRows (wxCommandEvent& event)
678 {
679   ImageFile& rIF = GetDocument()->getImageFile();
680   rIF.fftRows (rIF);
681   rIF.labelAdd ("FFT Rows");
682   m_bMinSpecified = false;
683   m_bMaxSpecified = false;
684   if (theApp->getAskDeleteNewDocs())
685     GetDocument()->Modify (true);
686   GetDocument()->UpdateAllViews (this);
687   GetDocument()->Activate();
688 }
689
690 void
691 ImageFileView::OnIFFTRows (wxCommandEvent& event)
692 {
693   ImageFile& rIF = GetDocument()->getImageFile();
694   rIF.ifftRows (rIF);
695   rIF.labelAdd ("IFFT Rows");
696   m_bMinSpecified = false;
697   m_bMaxSpecified = false;
698   if (theApp->getAskDeleteNewDocs())
699     GetDocument()->Modify (true);
700   GetDocument()->UpdateAllViews (this);
701   GetDocument()->Activate();
702 }
703
704 void
705 ImageFileView::OnFFTCols (wxCommandEvent& event)
706 {
707   ImageFile& rIF = GetDocument()->getImageFile();
708   rIF.fftCols (rIF);
709   rIF.labelAdd ("FFT Columns");
710   m_bMinSpecified = false;
711   m_bMaxSpecified = false;
712   if (theApp->getAskDeleteNewDocs())
713     GetDocument()->Modify (true);
714   GetDocument()->UpdateAllViews (this);
715   GetDocument()->Activate();
716 }
717
718 void
719 ImageFileView::OnIFFTCols (wxCommandEvent& event)
720 {
721   ImageFile& rIF = GetDocument()->getImageFile();
722   rIF.ifftCols (rIF);
723   rIF.labelAdd ("IFFT Columns");
724   m_bMinSpecified = false;
725   m_bMaxSpecified = false;
726   if (theApp->getAskDeleteNewDocs())
727     GetDocument()->Modify (true);
728   GetDocument()->UpdateAllViews (this);
729   GetDocument()->Activate();
730 }
731 #endif
732
733 void
734 ImageFileView::OnFourier (wxCommandEvent& event)
735 {
736   ImageFile& rIF = GetDocument()->getImageFile();
737   wxProgressDialog dlgProgress (wxString("Fourier"), wxString("Fourier Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
738   rIF.fourier (rIF);
739   rIF.labelAdd ("Fourier Image");
740   m_bMinSpecified = false;
741   m_bMaxSpecified = false;
742   if (theApp->getAskDeleteNewDocs())
743     GetDocument()->Modify (true);
744   GetDocument()->UpdateAllViews (this);
745   GetDocument()->Activate();
746 }
747
748 void
749 ImageFileView::OnInverseFourier (wxCommandEvent& event)
750 {
751   ImageFile& rIF = GetDocument()->getImageFile();
752   wxProgressDialog dlgProgress (wxString("Inverse Fourier"), wxString("Inverse Fourier Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
753   rIF.inverseFourier (rIF);
754   rIF.labelAdd ("Inverse Fourier Image");
755   m_bMinSpecified = false;
756   m_bMaxSpecified = false;
757   if (theApp->getAskDeleteNewDocs())
758     GetDocument()->Modify (true);
759   GetDocument()->UpdateAllViews (this);
760   GetDocument()->Activate();
761 }
762
763 void
764 ImageFileView::OnShuffleNaturalToFourierOrder (wxCommandEvent& event)
765 {
766   ImageFile& rIF = GetDocument()->getImageFile();
767   Fourier::shuffleNaturalToFourierOrder (rIF);
768   rIF.labelAdd ("Shuffle Natural To Fourier Order");
769   m_bMinSpecified = false;
770   m_bMaxSpecified = false;
771   if (theApp->getAskDeleteNewDocs())
772     GetDocument()->Modify (true);
773   GetDocument()->UpdateAllViews (this);
774   GetDocument()->Activate();
775 }
776
777 void
778 ImageFileView::OnShuffleFourierToNaturalOrder (wxCommandEvent& event)
779 {
780   ImageFile& rIF = GetDocument()->getImageFile();
781   Fourier::shuffleFourierToNaturalOrder (rIF);
782   rIF.labelAdd ("Shuffle Fourier To Natural Order");
783   m_bMinSpecified = false;
784   m_bMaxSpecified = false;
785   if (theApp->getAskDeleteNewDocs())
786     GetDocument()->Modify (true);
787   GetDocument()->UpdateAllViews (this);
788   GetDocument()->Activate();
789 }
790
791 void
792 ImageFileView::OnMagnitude (wxCommandEvent& event)
793 {
794   ImageFile& rIF = GetDocument()->getImageFile();
795   rIF.magnitude (rIF);
796   rIF.labelAdd ("Magnitude");
797   m_bMinSpecified = false;
798   m_bMaxSpecified = false;
799   if (theApp->getAskDeleteNewDocs())
800     GetDocument()->Modify (true);
801   GetDocument()->UpdateAllViews (this);
802   GetDocument()->Activate();
803 }
804
805 void
806 ImageFileView::OnPhase (wxCommandEvent& event)
807 {
808   ImageFile& rIF = GetDocument()->getImageFile();
809   if (rIF.isComplex()) {
810     rIF.phase (rIF);
811     rIF.labelAdd ("Phase of complex-image");
812     m_bMinSpecified = false;
813     m_bMaxSpecified = false;
814     if (theApp->getAskDeleteNewDocs())
815       GetDocument()->Modify (true);
816     GetDocument()->UpdateAllViews (this);
817   }
818   GetDocument()->Activate();
819 }
820
821 void
822 ImageFileView::OnReal (wxCommandEvent& event)
823 {
824   ImageFile& rIF = GetDocument()->getImageFile();
825   if (rIF.isComplex()) {
826     rIF.real (rIF);
827     rIF.labelAdd ("Real component of complex-image");
828     m_bMinSpecified = false;
829     m_bMaxSpecified = false;
830     if (theApp->getAskDeleteNewDocs())
831       GetDocument()->Modify (true);
832     GetDocument()->UpdateAllViews (this);
833   }
834   GetDocument()->Activate();
835 }
836
837 void
838 ImageFileView::OnImaginary (wxCommandEvent& event)
839 {
840   ImageFile& rIF = GetDocument()->getImageFile();
841   if (rIF.isComplex()) {
842     rIF.imaginary (rIF);
843     rIF.labelAdd ("Imaginary component of complex-image");
844     m_bMinSpecified = false;
845     m_bMaxSpecified = false;
846     if (theApp->getAskDeleteNewDocs())
847       GetDocument()->Modify (true);
848     GetDocument()->UpdateAllViews (this);
849   }
850   GetDocument()->Activate();
851 }
852
853
854 ImageFileCanvas* 
855 ImageFileView::CreateCanvas (wxFrame* parent)
856 {
857   ImageFileCanvas* pCanvas;
858   int width, height;
859   parent->GetClientSize(&width, &height);
860   
861   pCanvas = new ImageFileCanvas (this, parent, wxPoint(0, 0), wxSize(width, height), 0);
862   
863   pCanvas->SetScrollbars(20, 20, 50, 50);
864   pCanvas->SetBackgroundColour(*wxWHITE);
865   pCanvas->Clear();
866   
867   return pCanvas;
868 }
869
870 #if CTSIM_MDI
871 wxDocMDIChildFrame*
872 #else
873 wxDocChildFrame*
874 #endif
875 ImageFileView::CreateChildFrame(wxDocument *doc, wxView *view)
876 {
877 #if CTSIM_MDI
878   wxDocMDIChildFrame* subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1, -1), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
879 #else
880   wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1, -1), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
881 #endif
882   theApp->setIconForFrame (subframe);
883   
884   m_pFileMenu = new wxMenu;
885   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
886   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
887   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
888   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
889   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
890   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
891   m_pFileMenu->Append(wxID_REVERT, "Re&vert");
892   
893   m_pFileMenu->AppendSeparator();
894   m_pFileMenu->Append(IFMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
895   m_pFileMenu->Append(IFMENU_FILE_EXPORT, "Expor&t...");
896   
897   m_pFileMenu->AppendSeparator();
898   m_pFileMenu->Append(wxID_PRINT, "&Print...");
899   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
900   m_pFileMenu->Append(wxID_PREVIEW, "Print Preview");
901   m_pFileMenu->AppendSeparator();
902   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
903 #ifdef CTSIM_MDI
904   m_pFileMenu->AppendSeparator();
905   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
906   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
907 #endif
908   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
909   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
910   
911   wxMenu* edit_menu = new wxMenu;
912   edit_menu->Append(IFMENU_EDIT_COPY, "Copy\tCtrl-C");
913   edit_menu->Append(IFMENU_EDIT_CUT, "Cut\tCtrl-X");
914   edit_menu->Append(IFMENU_EDIT_PASTE, "Paste\tCtrl-V");
915   
916   wxMenu *view_menu = new wxMenu;
917   view_menu->Append(IFMENU_VIEW_SCALE_MINMAX, "Display Scale S&et...\tCtrl-E");
918   view_menu->Append(IFMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
919   view_menu->Append(IFMENU_VIEW_SCALE_FULL, "Display F&ull Scale\tCtrl-U");
920   
921   m_pFilterMenu = new wxMenu;
922   m_pFilterMenu->Append (IFMENU_FILTER_INVERTVALUES, "In&vert Values");
923   m_pFilterMenu->Append (IFMENU_FILTER_SQUARE, "&Square");
924   m_pFilterMenu->Append (IFMENU_FILTER_SQRT, "Square &Root");
925   m_pFilterMenu->Append (IFMENU_FILTER_LOG, "&Log");
926   m_pFilterMenu->Append (IFMENU_FILTER_EXP, "E&xp");
927   m_pFilterMenu->AppendSeparator();
928 #ifdef HAVE_FFT
929   m_pFilterMenu->Append (IFMENU_FILTER_FFT, "2-D &FFT\tCtrl-2");
930   m_pFilterMenu->Append (IFMENU_FILTER_IFFT, "2-D &IFFT\tAlt-2");
931   m_pFilterMenu->Append (IFMENU_FILTER_FFT_ROWS, "FFT Rows");
932   m_pFilterMenu->Append (IFMENU_FILTER_IFFT_ROWS, "IFFT Rows");
933   m_pFilterMenu->Append (IFMENU_FILTER_FFT_COLS, "FFT Columns");
934   m_pFilterMenu->Append (IFMENU_FILTER_IFFT_COLS, "IFFT Columns");
935   m_pFilterMenu->Append (IFMENU_FILTER_FOURIER, "2-D F&ourier");
936   m_pFilterMenu->Append (IFMENU_FILTER_INVERSE_FOURIER, "2-D Inverse Fo&urier");
937 #else
938   m_pFilterMenu->Append (IFMENU_FILTER_FOURIER, "&Fourier");
939   m_pFilterMenu->Append (IFMENU_FILTER_INVERSE_FOURIER, "&Inverse Fourier");
940 #endif
941   m_pFilterMenu->Append (IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER, "Shuffl&e Fourier to Natural Order");
942   m_pFilterMenu->Append (IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER, "Shuffle &Natural to Fourier Order");
943   m_pFilterMenu->AppendSeparator();
944   m_pFilterMenu->Append (IFMENU_FILTER_MAGNITUDE, "&Magnitude");
945   m_pFilterMenu->Append (IFMENU_FILTER_PHASE, "&Phase");
946   m_pFilterMenu->Append (IFMENU_FILTER_REAL, "Re&al");
947   m_pFilterMenu->Append (IFMENU_FILTER_IMAGINARY, "Ima&ginary");
948   
949   wxMenu* image_menu = new wxMenu;
950   image_menu->Append (IFMENU_IMAGE_ADD, "&Add...");
951   image_menu->Append (IFMENU_IMAGE_SUBTRACT, "&Subtract...");
952   image_menu->Append (IFMENU_IMAGE_MULTIPLY, "&Multiply...");
953   image_menu->Append (IFMENU_IMAGE_DIVIDE, "&Divide...");
954   image_menu->AppendSeparator();
955   image_menu->Append (IFMENU_IMAGE_SCALESIZE, "S&cale Size...");
956 #if wxUSE_GLCANVAS
957   image_menu->Append (IFMENU_IMAGE_CONVERT3D, "Convert &3-D\tCtrl-3");
958 #endif
959   
960   m_pMenuAnalyze = new wxMenu;
961   m_pMenuAnalyze->Append (IFMENU_PLOT_ROW, "Plot &Row");
962   m_pMenuAnalyze->Append (IFMENU_PLOT_COL, "Plot &Column");
963   m_pMenuAnalyze->Append (IFMENU_PLOT_HISTOGRAM, "Plot &Histogram");
964   m_pMenuAnalyze->AppendSeparator();
965   m_pMenuAnalyze->Append (IFMENU_PLOT_FFT_ROW, "P&lot FFT Row");
966   m_pMenuAnalyze->Append (IFMENU_PLOT_FFT_COL, "Plo&t FFT Column");
967   m_pMenuAnalyze->AppendSeparator();
968   m_pMenuAnalyze->Append (IFMENU_COMPARE_IMAGES, "Compare &Images...");
969   m_pMenuAnalyze->Append (IFMENU_COMPARE_ROW, "Compare Ro&w");
970   m_pMenuAnalyze->Append (IFMENU_COMPARE_COL, "Compare Colu&mn");
971   m_pMenuAnalyze->Enable (IFMENU_PLOT_ROW, false);
972   m_pMenuAnalyze->Enable (IFMENU_PLOT_COL, false);
973   m_pMenuAnalyze->Enable (IFMENU_COMPARE_ROW, false);
974   m_pMenuAnalyze->Enable (IFMENU_COMPARE_COL, false);
975   m_pMenuAnalyze->Enable (IFMENU_PLOT_FFT_ROW, false);
976   m_pMenuAnalyze->Enable (IFMENU_PLOT_FFT_COL, false);
977   
978   wxMenu *help_menu = new wxMenu;
979   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
980   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
981   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
982   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
983   
984   wxMenuBar *menu_bar = new wxMenuBar;
985   
986   menu_bar->Append(m_pFileMenu, "&File");
987   menu_bar->Append(edit_menu, "&Edit");
988   menu_bar->Append(view_menu, "&View");
989   menu_bar->Append(image_menu, "&Image");
990   menu_bar->Append(m_pFilterMenu, "Fi&lter");
991   menu_bar->Append(m_pMenuAnalyze, "&Analyze");
992   menu_bar->Append(help_menu, "&Help");
993   
994   subframe->SetMenuBar(menu_bar);
995   
996   subframe->Centre(wxBOTH);
997   
998   wxAcceleratorEntry accelEntries[10];
999   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('A'), IFMENU_VIEW_SCALE_AUTO);
1000   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('U'), IFMENU_VIEW_SCALE_FULL);
1001   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('E'), IFMENU_VIEW_SCALE_MINMAX);
1002   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('I'), IFMENU_FILE_PROPERTIES);
1003   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('C'), IFMENU_EDIT_COPY);
1004   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('X'), IFMENU_EDIT_CUT);
1005   accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('V'), IFMENU_EDIT_PASTE);
1006   int iEntry = 7;
1007 #ifdef HAVE_FFT
1008   accelEntries[iEntry++].Set (wxACCEL_CTRL, static_cast<int>('2'), IFMENU_FILTER_FFT);
1009   accelEntries[iEntry++].Set (wxACCEL_ALT,  static_cast<int>('2'), IFMENU_FILTER_IFFT);
1010 #endif
1011 #if wxUSE_GLCANVAS
1012   accelEntries[iEntry++].Set (wxACCEL_CTRL, static_cast<int>('3'), IFMENU_IMAGE_CONVERT3D);
1013 #endif
1014   wxAcceleratorTable accelTable (iEntry, accelEntries);
1015   
1016   subframe->SetAcceleratorTable (accelTable);
1017   
1018   return subframe;
1019 }
1020
1021
1022 bool 
1023 ImageFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
1024 {
1025   m_pFrame = CreateChildFrame(doc, this);
1026   
1027   m_bMinSpecified = false;
1028   m_bMaxSpecified = false;
1029   m_dAutoScaleFactor = 1.;
1030   
1031   //  int width, height;
1032   //  m_pFrame->GetClientSize (&width, &height);
1033   m_pFrame->SetTitle("ImageFileView");
1034   m_pCanvas = CreateCanvas (m_pFrame);
1035   
1036   //  int x, y;  // X requires a forced resize
1037   //  m_pFrame->GetSize(&x, &y);
1038   //  m_pFrame->SetSize(-1, -1, x, y);
1039   m_pFrame->SetFocus();
1040   m_pFrame->Show(true);
1041   //  Activate(true);
1042   
1043   return true;
1044 }
1045
1046 void 
1047 ImageFileView::setInitialClientSize ()
1048 {
1049   if (m_pFrame && m_pCanvas) {
1050     wxSize bestSize = m_pCanvas->GetBestSize();
1051
1052     if (bestSize.x > 800)
1053       bestSize.x = 800;
1054     if (bestSize.y > 800)
1055       bestSize.y = 800;
1056     
1057     m_pFrame->SetClientSize (bestSize);
1058     m_pFrame->Show (true);
1059     m_pFrame->SetFocus();
1060   }
1061 }  
1062
1063 void 
1064 ImageFileView::OnDraw (wxDC* dc)
1065 {
1066   if (m_bitmap.Ok())
1067     dc->DrawBitmap(m_bitmap, 0, 0, false);
1068   
1069   int xCursor, yCursor;
1070   if (m_pCanvas->GetCurrentCursor (xCursor, yCursor))
1071     m_pCanvas->DrawRubberBandCursor (*dc, xCursor, yCursor);
1072 }
1073
1074
1075 void 
1076 ImageFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
1077 {
1078   const ImageFile& rIF = GetDocument()->getImageFile();
1079   if (m_pFilterMenu && rIF.isComplex()) {
1080     m_pFilterMenu->Enable(IFMENU_FILTER_REAL, true);
1081     m_pFilterMenu->Enable(IFMENU_FILTER_IMAGINARY, true);
1082     m_pFilterMenu->Enable(IFMENU_FILTER_PHASE, true);
1083   } else {
1084     m_pFilterMenu->Enable(IFMENU_FILTER_REAL, false);
1085     m_pFilterMenu->Enable(IFMENU_FILTER_IMAGINARY, false);
1086     m_pFilterMenu->Enable(IFMENU_FILTER_PHASE, false);
1087   }
1088   ImageFileArrayConst v = rIF.getArray();
1089   int nx = rIF.nx();
1090   int ny = rIF.ny();
1091   if (v != NULL && nx != 0 && ny != 0) {
1092     if (! m_bMinSpecified || ! m_bMaxSpecified) {
1093       double min, max;
1094       rIF.getMinMax (min, max);
1095       if (! m_bMinSpecified)
1096         m_dMinPixel = min;
1097       if (! m_bMaxSpecified)
1098         m_dMaxPixel = max;
1099     }
1100     double scaleWidth = m_dMaxPixel - m_dMinPixel;
1101     
1102     unsigned char* imageData = new unsigned char [nx * ny * 3];
1103     if (! imageData) {
1104       sys_error (ERR_SEVERE, "Unable to allocate memory for Image display");
1105       return;
1106     }
1107     for (int ix = 0; ix < nx; ix++) {
1108       for (int iy = 0; iy < ny; iy++) {
1109         double scaleValue = ((v[ix][iy] - m_dMinPixel) / scaleWidth) * 255;
1110         int intensity = static_cast<int>(scaleValue + 0.5);
1111         intensity = clamp (intensity, 0, 255);
1112         int baseAddr = ((ny - 1 - iy) * nx + ix) * 3;
1113         imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
1114       }
1115     }
1116     wxImage image (nx, ny, imageData, true);
1117     m_bitmap = image.ConvertToBitmap();
1118     delete imageData;
1119     m_pCanvas->SetScrollbars(20, 20, nx/20, ny/20);
1120     m_pCanvas->SetBackgroundColour(*wxWHITE);
1121   } 
1122   
1123   if (m_pCanvas)
1124     m_pCanvas->Refresh();
1125 }
1126
1127 bool 
1128 ImageFileView::OnClose (bool deleteWindow)
1129 {
1130   //GetDocumentManager()->ActivateView (this, false, true);
1131   if (! GetDocument() || ! GetDocument()->Close())
1132     return false;
1133   
1134   Activate (false);
1135   if (m_pCanvas) {
1136     m_pCanvas->setView(NULL);
1137     m_pCanvas = NULL;
1138   }
1139   wxString s(theApp->GetAppName());
1140   if (m_pFrame)
1141     m_pFrame->SetTitle(s);
1142   
1143   SetFrame(NULL);
1144   
1145   if (deleteWindow) {
1146     delete m_pFrame;
1147     m_pFrame = NULL;
1148     if (GetDocument() && GetDocument()->getBadFileOpen())
1149       ::wxYield();  // wxWindows bug workaround
1150   }
1151   
1152   return true;
1153 }
1154
1155 void
1156 ImageFileView::OnEditCopy (wxCommandEvent& event)
1157 {
1158   wxBitmapDataObject *pBitmapObject = new wxBitmapDataObject;
1159   
1160   pBitmapObject->SetBitmap (m_bitmap);
1161   
1162   if (wxTheClipboard->Open()) {
1163     wxTheClipboard->SetData (pBitmapObject);
1164     wxTheClipboard->Close();
1165   }
1166 }
1167
1168 void
1169 ImageFileView::OnEditCut (wxCommandEvent& event)
1170 {
1171   OnEditCopy (event);
1172   ImageFile& rIF = GetDocument()->getImageFile();
1173   int nx = rIF.nx();
1174   int ny = rIF.ny();
1175   ImageFile* pIF = new ImageFile (nx, ny);
1176   pIF->arrayDataClear();
1177   GetDocument()->setImageFile (pIF); // deletes old IF
1178   OnUpdate(this, NULL);
1179   GetDocument()->UpdateAllViews();
1180   if (theApp->getAskDeleteNewDocs())
1181     GetDocument()->Modify (true);
1182 }
1183
1184 void
1185 ImageFileView::OnEditPaste (wxCommandEvent& event)
1186 {
1187   ImageFile& rIF = GetDocument()->getImageFile();
1188   
1189   if (wxTheClipboard->Open()) {
1190     wxBitmap bitmap;
1191     if (wxTheClipboard->IsSupported (wxDF_BITMAP)) {
1192       wxBitmapDataObject bitmapObject;
1193       wxTheClipboard->GetData (bitmapObject);
1194       bitmap = bitmapObject.GetBitmap ();
1195     }
1196     wxTheClipboard->Close();
1197     
1198     int nx = rIF.nx();
1199     int ny = rIF.ny();
1200     bool bMonochrome = false;
1201
1202     if (bitmap.Ok() == true && bitmap.GetWidth() == nx && bitmap.GetHeight() == ny) {
1203       wxImage image (bitmap);
1204       double dScale3 = 3 * 255;
1205       unsigned char* pixels = image.GetData();
1206       ImageFileArray v = rIF.getArray();
1207       for (unsigned int ix = 0; ix < rIF.nx(); ix++) {
1208         for (unsigned int iy = 0; iy < rIF.ny(); iy++) {
1209           unsigned int iBase = 3 * (iy * nx + ix);
1210           if (ix == 0 && iy == 0 && (pixels[iBase] == pixels[iBase+1] && pixels[iBase+1] == pixels[iBase+2]))
1211             bMonochrome = true;
1212           if (bMonochrome) {
1213             v[ix][ny - 1 - iy] = (pixels[iBase]+pixels[iBase+1]+pixels[iBase+2]) / dScale3;
1214           } else {
1215             double dR = pixels[iBase] / 255.;
1216             double dG = pixels[iBase+1] / 255.;
1217             double dB = pixels[iBase+2] / 255.;
1218             v[ix][ny - 1 - iy] = ImageFile::colorToGrayscale (dR, dG, dB);
1219           }
1220         }
1221       }
1222       OnUpdate(this, NULL);
1223       GetDocument()->UpdateAllViews();
1224       if (theApp->getAskDeleteNewDocs())
1225         GetDocument()->Modify(true);
1226     }
1227   }
1228 }
1229
1230 void
1231 ImageFileView::OnExport (wxCommandEvent& event)
1232 {
1233   ImageFile& rIF = GetDocument()->getImageFile();
1234   ImageFileArrayConst v = rIF.getArray();
1235   int nx = rIF.nx();
1236   int ny = rIF.ny();
1237   if (v != NULL && nx != 0 && ny != 0) {
1238     if (! m_bMinSpecified || ! m_bMaxSpecified) {
1239       double min, max;
1240       rIF.getMinMax (min, max);
1241       if (! m_bMinSpecified)
1242         m_dMinPixel = min;
1243       if (! m_bMaxSpecified)
1244         m_dMaxPixel = max;
1245     }
1246     
1247     DialogExportParameters dialogExport (getFrameForChild(), m_iDefaultExportFormatID);
1248     if (dialogExport.ShowModal() == wxID_OK) {
1249       wxString strFormatName (dialogExport.getFormatName ());
1250       m_iDefaultExportFormatID = ImageFile::convertExportFormatNameToID (strFormatName.c_str());
1251       
1252       wxString strExt;
1253       wxString strWildcard;
1254       if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PGM || m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PGMASCII) {
1255         strExt = ".pgm";
1256         strWildcard = "PGM Files (*.pgm)|*.pgm";
1257       }
1258 #ifdef HAVE_PNG
1259       else if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PNG || m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PNG16) {
1260         strExt = ".png";
1261         strWildcard = "PNG Files (*.png)|*.png";
1262       }
1263 #endif
1264 #ifdef HAVE_CTN_DICOM
1265       else if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_DICOM) {
1266         strExt = "";
1267         strWildcard = "DICOM Files (*.*)|*.*";
1268       }
1269 #endif
1270       else if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_TEXT) {
1271         strExt = ".txt";
1272         strWildcard = "Text (*.txt)|*.txt";
1273       }
1274       else {
1275         strExt = "";
1276         strWildcard = "Miscellaneous (*.*)|*.*";
1277       }
1278       
1279       const wxString& strFilename = wxFileSelector (wxString("Export Filename"), wxString(""), 
1280         wxString(""), strExt, strWildcard, wxOVERWRITE_PROMPT | wxHIDE_READONLY | wxSAVE);
1281       if (strFilename) {
1282         rIF.exportImage (strFormatName.c_str(), strFilename.c_str(), 1, 1, m_dMinPixel, m_dMaxPixel);
1283         *theApp->getLog() << "Exported file " << strFilename << "\n";
1284       }
1285     }
1286   }
1287 }
1288
1289 void
1290 ImageFileView::OnScaleSize (wxCommandEvent& event)
1291 {
1292   ImageFile& rIF = GetDocument()->getImageFile();
1293   unsigned int iOldNX = rIF.nx();
1294   unsigned int iOldNY = rIF.ny();
1295   
1296   DialogGetXYSize dialogGetXYSize (getFrameForChild(), "Set New X & Y Dimensions", iOldNX, iOldNY);
1297   if (dialogGetXYSize.ShowModal() == wxID_OK) {
1298     unsigned int iNewNX = dialogGetXYSize.getXSize();
1299     unsigned int iNewNY = dialogGetXYSize.getYSize();
1300     std::ostringstream os;
1301     os << "Scale Size from (" << iOldNX << "," << iOldNY << ") to (" << iNewNX << "," << iNewNY << ")";
1302     ImageFileDocument* pScaledDoc = theApp->newImageDoc();
1303     if (! pScaledDoc) {
1304       sys_error (ERR_SEVERE, "Unable to create image file");
1305       return;
1306     }
1307     ImageFile& rScaledIF = pScaledDoc->getImageFile();
1308     rScaledIF.setArraySize (iNewNX, iNewNY);
1309     rScaledIF.labelsCopy (rIF);
1310     rScaledIF.labelAdd (os.str().c_str());
1311     rIF.scaleImage (rScaledIF);
1312     *theApp->getLog() << os.str().c_str() << "\n";
1313     if (theApp->getAskDeleteNewDocs())
1314       pScaledDoc->Modify (true);
1315     pScaledDoc->UpdateAllViews (this);
1316     pScaledDoc->getView()->setInitialClientSize();
1317     pScaledDoc->Activate();
1318   }
1319 }
1320
1321 #if wxUSE_GLCANVAS
1322 void
1323 ImageFileView::OnConvert3d (wxCommandEvent& event)
1324 {
1325   ImageFile& rIF = GetDocument()->getImageFile();
1326   Graph3dFileDocument* pGraph3d = theApp->newGraph3dDoc();
1327   pGraph3d->setBadFileOpen();
1328   pGraph3d->createFromImageFile (rIF);
1329   pGraph3d->getView()->OnUpdate (this, NULL);
1330   pGraph3d->UpdateAllViews();
1331   pGraph3d->getView()->getFrame()->SetClientSize (400, 400);
1332   pGraph3d->getView()->getFrame()->Show (true);
1333   GetDocumentManager()->ActivateView (pGraph3d->getView(), true, false);
1334   ::wxYield();
1335   pGraph3d->getView()->getCanvas()->SetFocus();
1336 }
1337 #endif
1338
1339 void
1340 ImageFileView::OnPlotRow (wxCommandEvent& event)
1341 {
1342   int xCursor, yCursor;
1343   if (! m_pCanvas->GetCurrentCursor (xCursor, yCursor)) {
1344     wxMessageBox ("No row selected. Please use left mouse button on image to select column","Error");
1345     return;
1346   }
1347   
1348   const ImageFile& rIF = GetDocument()->getImageFile();
1349   ImageFileArrayConst v = rIF.getArray();
1350   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1351   int nx = rIF.nx();
1352   int ny = rIF.ny();
1353   
1354   if (v != NULL && yCursor < ny) {
1355     double* pX = new double [nx];
1356     double* pYReal = new double [nx];
1357     double *pYImag = NULL;
1358     double *pYMag = NULL;
1359     if (rIF.isComplex()) {
1360       pYImag = new double [nx];
1361       pYMag = new double [nx];
1362     }
1363     for (int i = 0; i < nx; i++) {
1364       pX[i] = i;
1365       pYReal[i] = v[i][yCursor];
1366       if (rIF.isComplex()) {
1367         pYImag[i] = vImag[i][yCursor];
1368         pYMag[i] = ::sqrt (v[i][yCursor] * v[i][yCursor] + vImag[i][yCursor] * vImag[i][yCursor]);
1369       }
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 ("box");
1385       rPlotFile.addEzsetCommand ("grid");
1386       rPlotFile.addEzsetCommand ("curve 1");
1387       rPlotFile.addEzsetCommand ("color 1");
1388       if (rIF.isComplex()) {
1389         rPlotFile.addEzsetCommand ("dash 1");
1390         rPlotFile.addEzsetCommand ("curve 2");
1391         rPlotFile.addEzsetCommand ("color 4");
1392         rPlotFile.addEzsetCommand ("dash 3");
1393         rPlotFile.addEzsetCommand ("curve 3");
1394         rPlotFile.addEzsetCommand ("color 0");
1395         rPlotFile.addEzsetCommand ("solid");
1396         rPlotFile.setCurveSize (4, nx);
1397       } else
1398         rPlotFile.setCurveSize (2, nx);
1399       rPlotFile.addColumn (0, pX);
1400       rPlotFile.addColumn (1, pYReal); 
1401       if (rIF.isComplex()) {
1402         rPlotFile.addColumn (2, pYImag);
1403         rPlotFile.addColumn (3, pYMag);
1404       }
1405       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++)
1406         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1407       os << " Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1408       *theApp->getLog() << os.str().c_str() << "\n";
1409       rPlotFile.addDescription (os.str().c_str());
1410     }
1411     delete pX;
1412     delete pYReal;
1413     if (rIF.isComplex()) {
1414       delete pYImag;
1415       delete pYMag;
1416     }
1417     if (theApp->getAskDeleteNewDocs())
1418       pPlotDoc->Modify (true);
1419     pPlotDoc->getView()->getFrame()->Show(true);
1420     pPlotDoc->UpdateAllViews ();
1421     pPlotDoc->Activate();
1422   }
1423 }
1424
1425 void
1426 ImageFileView::OnPlotCol (wxCommandEvent& event)
1427 {
1428   int xCursor, yCursor;
1429   if (! m_pCanvas->GetCurrentCursor (xCursor, yCursor)) {
1430     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1431     return;
1432   }
1433   
1434   const ImageFile& rIF = GetDocument()->getImageFile();
1435   ImageFileArrayConst v = rIF.getArray();
1436   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1437   int nx = rIF.nx();
1438   int ny = rIF.ny();
1439   
1440   if (v != NULL && xCursor < nx) {
1441     double* pX = new double [ny];
1442     double* pYReal = new double [ny];
1443     double* pYImag = NULL;
1444     double* pYMag = NULL;
1445     if (rIF.isComplex()) {
1446       pYImag = new double [ny];
1447       pYMag = new double [ny];
1448     }
1449     for (int i = 0; i < ny; i++) {
1450       pX[i] = i;
1451       pYReal[i] = v[xCursor][i];
1452       if (rIF.isComplex()) {
1453         pYImag[i] = vImag[xCursor][i];
1454         pYMag[i] = ::sqrt (v[xCursor][i] * v[xCursor][i] + vImag[xCursor][i] * vImag[xCursor][i]);
1455       }
1456     }
1457     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1458     if (! pPlotDoc) {
1459       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1460     } else {
1461       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1462       std::ostringstream os;
1463       os << "Column " << xCursor;
1464       std::string title("title ");
1465       title += os.str();
1466       rPlotFile.addEzsetCommand (title.c_str());
1467       rPlotFile.addEzsetCommand ("xlabel Row");
1468       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1469       rPlotFile.addEzsetCommand ("lxfrac 0");
1470       rPlotFile.addEzsetCommand ("box");
1471       rPlotFile.addEzsetCommand ("grid");
1472       rPlotFile.addEzsetCommand ("curve 1");
1473       rPlotFile.addEzsetCommand ("color 1");
1474       if (rIF.isComplex()) {
1475         rPlotFile.addEzsetCommand ("dash 1");
1476         rPlotFile.addEzsetCommand ("curve 2");
1477         rPlotFile.addEzsetCommand ("color 4");
1478         rPlotFile.addEzsetCommand ("dash 3");
1479         rPlotFile.addEzsetCommand ("curve 3");
1480         rPlotFile.addEzsetCommand ("color 0");
1481         rPlotFile.addEzsetCommand ("solid");
1482         rPlotFile.setCurveSize (4, ny);
1483       } else
1484         rPlotFile.setCurveSize (2, ny);
1485       rPlotFile.addColumn (0, pX);
1486       rPlotFile.addColumn (1, pYReal); 
1487       if (rIF.isComplex()) {
1488         rPlotFile.addColumn (2, pYImag);
1489         rPlotFile.addColumn (3, pYMag);
1490       }
1491       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++)
1492         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1493       os << " Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1494       *theApp->getLog() << os.str().c_str() << "\n";
1495       rPlotFile.addDescription (os.str().c_str());
1496     }
1497     delete pX;
1498     delete pYReal;
1499     if (rIF.isComplex()) {
1500       delete pYImag;
1501       delete pYMag;
1502     }
1503     if (theApp->getAskDeleteNewDocs())
1504       pPlotDoc->Modify (true);
1505     pPlotDoc->getView()->getFrame()->Show(true);
1506     pPlotDoc->UpdateAllViews ();
1507     pPlotDoc->Activate();
1508   }
1509 }
1510
1511 #ifdef HAVE_FFT
1512 void
1513 ImageFileView::OnPlotFFTRow (wxCommandEvent& event)
1514 {
1515   int xCursor, yCursor;
1516   if (! m_pCanvas->GetCurrentCursor (xCursor, yCursor)) {
1517     wxMessageBox ("No row selected. Please use left mouse button on image to select column","Error");
1518     return;
1519   }
1520   
1521   const ImageFile& rIF = GetDocument()->getImageFile();
1522   ImageFileArrayConst v = rIF.getArray();
1523   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1524   int nx = rIF.nx();
1525   int ny = rIF.ny();
1526   
1527   if (v != NULL && yCursor < ny) {
1528     fftw_complex* pcIn = new fftw_complex [nx];
1529     
1530     int i;
1531     for (i = 0; i < nx; i++) {
1532       pcIn[i].re = v[i][yCursor];
1533       if (rIF.isComplex())
1534         pcIn[i].im = vImag[i][yCursor];
1535       else
1536         pcIn[i].im = 0;
1537     }
1538     
1539     fftw_plan plan = fftw_create_plan (nx, FFTW_FORWARD, FFTW_IN_PLACE | FFTW_ESTIMATE | FFTW_USE_WISDOM);
1540     fftw_one (plan, pcIn, NULL);
1541     fftw_destroy_plan (plan);
1542     
1543     double* pX = new double [nx];
1544     double* pYReal = new double [nx];
1545     double* pYImag = new double [nx];
1546     double* pYMag = new double [nx];
1547     for (i = 0; i < nx; i++) {
1548       pX[i] = i;
1549       pYReal[i] = pcIn[i].re / nx;
1550       pYImag[i] = pcIn[i].im / nx;
1551       pYMag[i] = ::sqrt (pcIn[i].re * pcIn[i].re + pcIn[i].im * pcIn[i].im);
1552     }
1553     Fourier::shuffleFourierToNaturalOrder (pYReal, nx);
1554     Fourier::shuffleFourierToNaturalOrder (pYImag, nx);
1555     Fourier::shuffleFourierToNaturalOrder (pYMag, nx);
1556     
1557     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1558     if (! pPlotDoc) {
1559       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1560     } else {
1561       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1562       std::ostringstream os;
1563       os << "Row " << yCursor;
1564       std::string title("title ");
1565       title += os.str();
1566       rPlotFile.addEzsetCommand (title.c_str());
1567       rPlotFile.addEzsetCommand ("xlabel Column");
1568       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1569       rPlotFile.addEzsetCommand ("lxfrac 0");
1570       rPlotFile.addEzsetCommand ("curve 1");
1571       rPlotFile.addEzsetCommand ("color 1");
1572       rPlotFile.addEzsetCommand ("dash 1");
1573       rPlotFile.addEzsetCommand ("curve 2");
1574       rPlotFile.addEzsetCommand ("color 4");
1575       rPlotFile.addEzsetCommand ("dash 3");
1576       rPlotFile.addEzsetCommand ("curve 3");
1577       rPlotFile.addEzsetCommand ("color 0");
1578       rPlotFile.addEzsetCommand ("solid");
1579       rPlotFile.addEzsetCommand ("box");
1580       rPlotFile.addEzsetCommand ("grid");
1581       rPlotFile.setCurveSize (4, nx);
1582       rPlotFile.addColumn (0, pX);
1583       rPlotFile.addColumn (1, pYReal);
1584       rPlotFile.addColumn (2, pYImag);
1585       rPlotFile.addColumn (3, pYMag);
1586       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++)
1587         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1588       os << " FFT Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1589       *theApp->getLog() << os.str().c_str() << "\n";
1590       rPlotFile.addDescription (os.str().c_str());
1591     }
1592     delete pX;
1593     delete pYReal;
1594     delete pYImag;
1595     delete pYMag;
1596     delete [] pcIn;
1597     
1598     if (theApp->getAskDeleteNewDocs())
1599       pPlotDoc->Modify (true);
1600     pPlotDoc->getView()->getFrame()->Show(true);
1601     pPlotDoc->UpdateAllViews ();
1602     pPlotDoc->Activate();
1603   }
1604 }
1605
1606 void
1607 ImageFileView::OnPlotFFTCol (wxCommandEvent& event)
1608 {
1609   int xCursor, yCursor;
1610   if (! m_pCanvas->GetCurrentCursor (xCursor, yCursor)) {
1611     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1612     return;
1613   }
1614   
1615   const ImageFile& rIF = GetDocument()->getImageFile();
1616   ImageFileArrayConst v = rIF.getArray();
1617   ImageFileArrayConst vImag = rIF.getImaginaryArray();
1618   int nx = rIF.nx();
1619   int ny = rIF.ny();
1620   
1621   if (v != NULL && xCursor < nx) {
1622     fftw_complex* pcIn = new fftw_complex [ny];
1623     double *pdTemp = new double [ny];
1624     
1625     int i;
1626     for (i = 0; i < ny; i++)
1627       pdTemp[i] = v[xCursor][i];
1628     Fourier::shuffleNaturalToFourierOrder (pdTemp, ny);
1629     for (i = 0; i < ny; i++) 
1630       pcIn[i].re = pdTemp[i];
1631     
1632     for (i = 0; i < ny; i++) {
1633       if (rIF.isComplex())
1634         pdTemp[i] = vImag[xCursor][i];
1635       else
1636         pdTemp[i] = 0;
1637     }
1638     Fourier::shuffleNaturalToFourierOrder (pdTemp, ny);
1639     for (i = 0; i < ny; i++)
1640       pcIn[i].im = pdTemp[i];
1641     
1642     fftw_plan plan = fftw_create_plan (ny, FFTW_BACKWARD, FFTW_IN_PLACE | FFTW_ESTIMATE | FFTW_USE_WISDOM);
1643     fftw_one (plan, pcIn, NULL);
1644     fftw_destroy_plan (plan);
1645     
1646     double* pX = new double [ny];
1647     double* pYReal = new double [ny];
1648     double* pYImag = new double [ny];
1649     double* pYMag = new double [ny];
1650     for (i = 0; i < ny; i++) {
1651       pX[i] = i;
1652       pYReal[i] = pcIn[i].re / ny;
1653       pYImag[i] = pcIn[i].im / ny;
1654       pYMag[i] = ::sqrt (pcIn[i].re * pcIn[i].re + pcIn[i].im * pcIn[i].im);
1655     }
1656     
1657     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1658     if (! pPlotDoc) {
1659       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1660     } else {
1661       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1662       std::ostringstream os;
1663       os << "Column " << xCursor;
1664       std::string title("title ");
1665       title += os.str();
1666       rPlotFile.addEzsetCommand (title.c_str());
1667       rPlotFile.addEzsetCommand ("xlabel Column");
1668       rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1669       rPlotFile.addEzsetCommand ("lxfrac 0");
1670       rPlotFile.addEzsetCommand ("curve 1");
1671       rPlotFile.addEzsetCommand ("color 1");
1672       rPlotFile.addEzsetCommand ("dash 1");
1673       rPlotFile.addEzsetCommand ("curve 2");
1674       rPlotFile.addEzsetCommand ("color 4");
1675       rPlotFile.addEzsetCommand ("dash 3");
1676       rPlotFile.addEzsetCommand ("curve 3");
1677       rPlotFile.addEzsetCommand ("color 0");
1678       rPlotFile.addEzsetCommand ("solid");
1679       rPlotFile.addEzsetCommand ("box");
1680       rPlotFile.addEzsetCommand ("grid");
1681       rPlotFile.setCurveSize (4, ny);
1682       rPlotFile.addColumn (0, pX);
1683       rPlotFile.addColumn (1, pYReal);
1684       rPlotFile.addColumn (2, pYImag);
1685       rPlotFile.addColumn (3, pYMag);
1686       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++)
1687         rPlotFile.addDescription (rIF.labelGet(iL).getLabelString().c_str());
1688       os << " FFT Plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1689       *theApp->getLog() << os.str().c_str() << "\n";
1690       rPlotFile.addDescription (os.str().c_str());
1691     }
1692     delete pX;
1693     delete pYReal;
1694     delete pYImag;
1695     delete pYMag;
1696     delete pdTemp;
1697     delete [] pcIn;
1698     
1699     if (theApp->getAskDeleteNewDocs())
1700       pPlotDoc->Modify (true);
1701     pPlotDoc->getView()->getFrame()->Show(true);
1702     pPlotDoc->UpdateAllViews ();
1703     pPlotDoc->Activate();
1704   }
1705 }
1706 #endif
1707
1708 void
1709 ImageFileView::OnCompareCol (wxCommandEvent& event)
1710 {
1711   int xCursor, yCursor;
1712   if (! m_pCanvas->GetCurrentCursor (xCursor, yCursor)) {
1713     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1714     return;
1715   }
1716   
1717   std::vector<ImageFileDocument*> vecIFDoc;
1718   theApp->getCompatibleImages (GetDocument(), vecIFDoc);
1719   if (vecIFDoc.size() == 0) {
1720     wxMessageBox ("No compatible images for Column Comparison", "Error");
1721     return;
1722   }
1723   DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Comparison Image", vecIFDoc, false);
1724   
1725   if (dialogGetCompare.ShowModal() == wxID_OK) {
1726     ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
1727     const ImageFile& rIF = GetDocument()->getImageFile();
1728     const ImageFile& rCompareIF = pCompareDoc->getImageFile();
1729     
1730     ImageFileArrayConst v1 = rIF.getArray();
1731     ImageFileArrayConst v2 = rCompareIF.getArray();
1732     int nx = rIF.nx();
1733     int ny = rIF.ny();
1734     
1735     if (v1 != NULL && xCursor < nx) {
1736       double* pX = new double [ny];
1737       double* pY1 = new double [ny];
1738       double* pY2 = new double [ny];
1739       for (int i = 0; i < ny; i++) {
1740         pX[i] = i;
1741         pY1[i] = v1[xCursor][i];
1742         pY2[i] = v2[xCursor][i];
1743       }
1744       PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1745       if (! pPlotDoc) {
1746         sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1747       } else {
1748         PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1749         std::ostringstream os;
1750         os << "Column " << xCursor << " Comparison";
1751         std::string title("title ");
1752         title += os.str();
1753         rPlotFile.addEzsetCommand (title.c_str());
1754         rPlotFile.addEzsetCommand ("xlabel Row");
1755         rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1756         rPlotFile.addEzsetCommand ("lxfrac 0");
1757         rPlotFile.addEzsetCommand ("curve 1");
1758         rPlotFile.addEzsetCommand ("color 2");
1759         rPlotFile.addEzsetCommand ("curve 2");
1760         rPlotFile.addEzsetCommand ("color 4");
1761         rPlotFile.addEzsetCommand ("dash 5");
1762         rPlotFile.addEzsetCommand ("box");
1763         rPlotFile.addEzsetCommand ("grid");
1764         rPlotFile.setCurveSize (3, ny);
1765         rPlotFile.addColumn (0, pX);
1766         rPlotFile.addColumn (1, pY1);
1767         rPlotFile.addColumn (2, pY2);
1768         
1769         unsigned int iL;
1770         for (iL = 0; iL < rIF.nLabels(); iL++) {
1771           std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1772           s += ": ";
1773           s += rIF.labelGet(iL).getLabelString();
1774           rPlotFile.addDescription (s.c_str());
1775         }
1776         for (iL = 0; iL < rCompareIF.nLabels(); iL++) {
1777           std::string s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1778           s += ": ";
1779           s += rCompareIF.labelGet(iL).getLabelString();
1780           rPlotFile.addDescription (s.c_str());
1781         }
1782         os << " Between " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
1783           << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1784         *theApp->getLog() << os.str().c_str() << "\n";
1785         rPlotFile.addDescription (os.str().c_str());
1786       }
1787       delete pX;
1788       delete pY1;
1789       delete pY2;
1790       if (theApp->getAskDeleteNewDocs())
1791         pPlotDoc->Modify (true);
1792       pPlotDoc->getView()->getFrame()->Show(true);
1793       pPlotDoc->UpdateAllViews ();
1794       pPlotDoc->Activate();
1795     }
1796   }
1797 }
1798
1799 void
1800 ImageFileView::OnCompareRow (wxCommandEvent& event)
1801 {
1802   int xCursor, yCursor;
1803   if (! m_pCanvas->GetCurrentCursor (xCursor, yCursor)) {
1804     wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
1805     return;
1806   }
1807   
1808   std::vector<ImageFileDocument*> vecIFDoc;
1809   theApp->getCompatibleImages (GetDocument(), vecIFDoc);
1810   
1811   if (vecIFDoc.size() == 0) {
1812     wxMessageBox ("No compatible images for Row Comparison", "Error");
1813     return;
1814   }
1815   
1816   DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Comparison Image", vecIFDoc, false);
1817   
1818   if (dialogGetCompare.ShowModal() == wxID_OK) {
1819     ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
1820     const ImageFile& rIF = GetDocument()->getImageFile();
1821     const ImageFile& rCompareIF = pCompareDoc->getImageFile();
1822     
1823     ImageFileArrayConst v1 = rIF.getArray();
1824     ImageFileArrayConst v2 = rCompareIF.getArray();
1825     int nx = rIF.nx();
1826     int ny = rIF.ny();
1827     
1828     if (v1 != NULL && yCursor < ny) {
1829       double* pX = new double [nx];
1830       double* pY1 = new double [nx];
1831       double* pY2 = new double [nx];
1832       for (int i = 0; i < nx; i++) {
1833         pX[i] = i;
1834         pY1[i] = v1[i][yCursor];
1835         pY2[i] = v2[i][yCursor];
1836       }
1837       PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1838       if (! pPlotDoc) {
1839         sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1840       } else {
1841         PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1842         std::ostringstream os;
1843         os << "Row " << yCursor << " Comparison";
1844         std::string title("title ");
1845         title += os.str();
1846         rPlotFile.addEzsetCommand (title.c_str());
1847         rPlotFile.addEzsetCommand ("xlabel Column");
1848         rPlotFile.addEzsetCommand ("ylabel Pixel Value");
1849         rPlotFile.addEzsetCommand ("lxfrac 0");
1850         rPlotFile.addEzsetCommand ("curve 1");
1851         rPlotFile.addEzsetCommand ("color 2");
1852         rPlotFile.addEzsetCommand ("curve 2");
1853         rPlotFile.addEzsetCommand ("color 4");
1854         rPlotFile.addEzsetCommand ("dash 5");
1855         rPlotFile.addEzsetCommand ("box");
1856         rPlotFile.addEzsetCommand ("grid");
1857         rPlotFile.setCurveSize (3, nx);
1858         rPlotFile.addColumn (0, pX);
1859         rPlotFile.addColumn (1, pY1);
1860         rPlotFile.addColumn (2, pY2);
1861         unsigned int iL;
1862         for (iL = 0; iL < rIF.nLabels(); iL++) {
1863           std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1864           s += ": ";
1865           s += rIF.labelGet(iL).getLabelString();
1866           rPlotFile.addDescription (s.c_str());
1867         }
1868         for (iL = 0; iL < rCompareIF.nLabels(); iL++) {
1869           std::string s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1870           s += ": ";
1871           s += rCompareIF.labelGet(iL).getLabelString();
1872           rPlotFile.addDescription (s.c_str());
1873         }
1874         os << " Between " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
1875           << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
1876         *theApp->getLog() << os.str().c_str() << "\n";
1877         rPlotFile.addDescription (os.str().c_str());
1878       }
1879       delete pX;
1880       delete pY1;
1881       delete pY2;
1882       if (theApp->getAskDeleteNewDocs())
1883         pPlotDoc->Modify (true);
1884       pPlotDoc->getView()->getFrame()->Show(true);
1885       pPlotDoc->UpdateAllViews ();
1886       pPlotDoc->Activate();
1887     }
1888   }
1889 }
1890
1891 static int NUMBER_HISTOGRAM_BINS = 256;
1892
1893 void
1894 ImageFileView::OnPlotHistogram (wxCommandEvent& event)
1895
1896   const ImageFile& rIF = GetDocument()->getImageFile();
1897   ImageFileArrayConst v = rIF.getArray();
1898   int nx = rIF.nx();
1899   int ny = rIF.ny();
1900   
1901   if (v != NULL && nx > 0 && ny > 0) {
1902     PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
1903     if (! pPlotDoc) {
1904       sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
1905       return;
1906     }
1907     
1908     double* pX = new double [NUMBER_HISTOGRAM_BINS];
1909     double* pY = new double [NUMBER_HISTOGRAM_BINS];
1910     double dMin, dMax;
1911     rIF.getMinMax (dMin, dMax);
1912     double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
1913     
1914     for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
1915       pX[i] = dMin + (i + 0.5) * dBinWidth;
1916       pY[i] = 0;
1917     }
1918     for (int ix = 0; ix < nx; ix++)
1919       for (int iy = 0; iy < ny; iy++) {
1920         int iBin = nearest<int> ((v[ix][iy] - dMin) / dBinWidth);
1921         if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
1922           pY[iBin] += 1;
1923       }
1924       
1925       PlotFile& rPlotFile = pPlotDoc->getPlotFile();
1926       std::ostringstream os;
1927       os << "Histogram";
1928       std::string title("title ");
1929       title += os.str();
1930       rPlotFile.addEzsetCommand (title.c_str());
1931       rPlotFile.addEzsetCommand ("xlabel Pixel Value");
1932       rPlotFile.addEzsetCommand ("ylabel Count");
1933       rPlotFile.addEzsetCommand ("box");
1934       rPlotFile.addEzsetCommand ("grid");
1935       rPlotFile.setCurveSize (2, NUMBER_HISTOGRAM_BINS);
1936       rPlotFile.addColumn (0, pX);
1937       rPlotFile.addColumn (1, pY);
1938       for (unsigned int iL = 0; iL < rIF.nLabels(); iL++) {
1939         std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1940         s += ": ";
1941         s += rIF.labelGet(iL).getLabelString();
1942         rPlotFile.addDescription (s.c_str());
1943       }
1944       os << "  plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
1945       *theApp->getLog() << os.str().c_str() << "\n";
1946       rPlotFile.addDescription (os.str().c_str());
1947       delete pX;
1948       delete pY;
1949       if (theApp->getAskDeleteNewDocs())
1950         pPlotDoc->Modify (true);
1951       pPlotDoc->getView()->getFrame()->Show(true);
1952       pPlotDoc->UpdateAllViews ();
1953       pPlotDoc->Activate();
1954   }
1955 }
1956
1957
1958 // PhantomCanvas
1959
1960 PhantomCanvas::PhantomCanvas (PhantomFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
1961 : wxScrolledWindow(frame, -1, pos, size, style)
1962 {
1963   m_pView = v;
1964 }
1965
1966 PhantomCanvas::~PhantomCanvas ()
1967 {
1968   m_pView = NULL;
1969 }
1970
1971 void 
1972 PhantomCanvas::OnDraw (wxDC& dc)
1973 {
1974   if (m_pView)
1975     m_pView->OnDraw(& dc);
1976 }
1977
1978 wxSize
1979 PhantomCanvas::GetBestSize() const
1980 {
1981   if (! m_pView)
1982     return wxSize(0,0);
1983   
1984   int xSize, ySize;
1985   theApp->getMainFrame()->GetClientSize (&xSize, &ySize);
1986   xSize = maxValue<int> (xSize, ySize);
1987 #ifdef CTSIM_MDI
1988   ySize = xSize = (xSize / 4);
1989 #else
1990   xSize = ySize = static_cast<int>(ySize * .7);
1991 #endif
1992
1993   return wxSize (xSize, ySize);
1994 }
1995
1996
1997
1998 // PhantomFileView
1999
2000 IMPLEMENT_DYNAMIC_CLASS(PhantomFileView, wxView)
2001
2002 BEGIN_EVENT_TABLE(PhantomFileView, wxView)
2003 EVT_MENU(PHMMENU_FILE_PROPERTIES, PhantomFileView::OnProperties)
2004 EVT_MENU(PHMMENU_PROCESS_RASTERIZE, PhantomFileView::OnRasterize)
2005 EVT_MENU(PHMMENU_PROCESS_PROJECTIONS, PhantomFileView::OnProjections)
2006 END_EVENT_TABLE()
2007
2008 PhantomFileView::PhantomFileView() 
2009 : wxView(), m_pFrame(NULL), m_pCanvas(NULL), m_pFileMenu(0)
2010 {
2011 #if defined(DEBUG) || defined(_DEBUG)
2012   m_iDefaultNDet = 165;
2013   m_iDefaultNView = 180;
2014   m_iDefaultNSample = 1;
2015 #else
2016   m_iDefaultNDet = 367;
2017   m_iDefaultNView = 320;
2018   m_iDefaultNSample = 2;
2019 #endif
2020   m_iDefaultOffsetView = 0;
2021   m_dDefaultRotation = 1;
2022   m_dDefaultFocalLength = 2;
2023   m_dDefaultCenterDetectorLength = 2;
2024   m_dDefaultViewRatio = 1;
2025   m_dDefaultScanRatio = 1;
2026   m_iDefaultGeometry = Scanner::GEOMETRY_PARALLEL;
2027   m_iDefaultTrace = Trace::TRACE_NONE;
2028   
2029 #ifdef DEBUG 
2030   m_iDefaultRasterNX = 115;
2031   m_iDefaultRasterNY = 115;
2032   m_iDefaultRasterNSamples = 1;
2033 #else
2034   m_iDefaultRasterNX = 256;
2035   m_iDefaultRasterNY = 256;
2036   m_iDefaultRasterNSamples = 2;
2037 #endif
2038   m_dDefaultRasterViewRatio = 1;
2039 }
2040
2041 PhantomFileView::~PhantomFileView()
2042 {
2043   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
2044   GetDocumentManager()->ActivateView(this, FALSE, TRUE);
2045 }
2046
2047 void
2048 PhantomFileView::OnProperties (wxCommandEvent& event)
2049 {
2050   const int idPhantom = GetDocument()->getPhantomID();
2051   const wxString& namePhantom = GetDocument()->getPhantomName();
2052   std::ostringstream os;
2053   os << "Phantom " << namePhantom.c_str() << " (" << idPhantom << ")" << "\n";
2054   const Phantom& rPhantom = GetDocument()->getPhantom();
2055   rPhantom.printDefinitions (os);
2056 #if DEBUG
2057   rPhantom.print (os);
2058 #endif
2059   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
2060   wxMessageBox (os.str().c_str(), "Phantom Properties");
2061   GetDocument()->Activate();
2062 }
2063
2064
2065 void
2066 PhantomFileView::OnProjections (wxCommandEvent& event)
2067 {
2068   DialogGetProjectionParameters dialogProjection (getFrameForChild(), 
2069     m_iDefaultNDet, m_iDefaultNView, m_iDefaultOffsetView, m_iDefaultNSample, m_dDefaultRotation, 
2070     m_dDefaultFocalLength, m_dDefaultCenterDetectorLength, m_dDefaultViewRatio, m_dDefaultScanRatio, 
2071     m_iDefaultGeometry, m_iDefaultTrace);
2072   int retVal = dialogProjection.ShowModal();
2073   if (retVal != wxID_OK) 
2074     return;
2075   
2076   m_iDefaultNDet = dialogProjection.getNDet();
2077   m_iDefaultNView = dialogProjection.getNView();
2078   m_iDefaultOffsetView = dialogProjection.getOffsetView();
2079   m_iDefaultNSample = dialogProjection.getNSamples();
2080   m_iDefaultTrace = dialogProjection.getTrace();
2081   m_dDefaultRotation = dialogProjection.getRotAngle();
2082   m_dDefaultFocalLength = dialogProjection.getFocalLengthRatio();
2083   m_dDefaultCenterDetectorLength = dialogProjection.getCenterDetectorLengthRatio();
2084   m_dDefaultViewRatio = dialogProjection.getViewRatio();
2085   m_dDefaultScanRatio = dialogProjection.getScanRatio();
2086   wxString sGeometry = dialogProjection.getGeometry();
2087   m_iDefaultGeometry = Scanner::convertGeometryNameToID (sGeometry.c_str());
2088   double dRotationRadians = m_dDefaultRotation;
2089   m_dDefaultRotation /= TWOPI;  // convert back to fraction of a circle
2090   
2091   if (m_iDefaultNDet <= 0 || m_iDefaultNView <= 0 || sGeometry == "")
2092     return;
2093   
2094   const Phantom& rPhantom = GetDocument()->getPhantom();
2095   Scanner theScanner (rPhantom, sGeometry.c_str(), m_iDefaultNDet, m_iDefaultNView, m_iDefaultOffsetView, m_iDefaultNSample, 
2096     dRotationRadians, m_dDefaultFocalLength, m_dDefaultCenterDetectorLength, m_dDefaultViewRatio, m_dDefaultScanRatio);
2097   if (theScanner.fail()) {
2098     wxString msg = "Failed making scanner\n";
2099     msg += theScanner.failMessage().c_str();
2100     *theApp->getLog() << msg << "\n";
2101     wxMessageBox (msg, "Error");
2102     return;
2103   }
2104   
2105   std::ostringstream os;
2106   os << "Projections for " << rPhantom.name() 
2107         << ": nDet=" << m_iDefaultNDet 
2108     << ", nView=" << m_iDefaultNView 
2109         << ", gantry offset=" << m_iDefaultOffsetView 
2110         << ", nSamples=" << m_iDefaultNSample 
2111     << ", RotAngle=" << m_dDefaultRotation 
2112         << ", FocalLengthRatio=" << m_dDefaultFocalLength 
2113     << ", CenterDetectorLengthRatio=" << m_dDefaultCenterDetectorLength
2114     << ", ViewRatio=" << m_dDefaultViewRatio 
2115         << ", ScanRatio=" << m_dDefaultScanRatio 
2116     << ", Geometry=" << sGeometry.c_str() 
2117         << ", FanBeamAngle=" << convertRadiansToDegrees (theScanner.fanBeamAngle());
2118   
2119   Timer timer;
2120   Projections* pProj = NULL;
2121   if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
2122     pProj = new Projections;
2123     pProj->initFromScanner (theScanner);
2124     
2125     ProjectionsDialog dialogProjections (theScanner, *pProj, rPhantom, m_iDefaultTrace, dynamic_cast<wxWindow*>(getFrameForChild()));
2126     for (int iView = 0; iView < pProj->nView(); iView++) {
2127       ::wxYield();
2128       if (dialogProjections.isCancelled() || ! dialogProjections.projectView (iView)) {
2129         delete pProj;
2130         return;
2131       }
2132       ::wxYield();
2133       while (dialogProjections.isPaused()) {
2134         ::wxYield();
2135         ::wxUsleep(50);
2136       }
2137     }
2138   } else {
2139 #if HAVE_WXTHREADS
2140     if (theApp->getUseBackgroundTasks()) {
2141       ProjectorSupervisorThread* pProjector = new ProjectorSupervisorThread (this, m_iDefaultNDet,
2142         m_iDefaultNView, m_iDefaultOffsetView, sGeometry.c_str(), m_iDefaultNSample, dRotationRadians,
2143         m_dDefaultFocalLength, m_dDefaultCenterDetectorLength, m_dDefaultViewRatio, m_dDefaultScanRatio, os.str().c_str());
2144       if (pProjector->Create() != wxTHREAD_NO_ERROR) {
2145         sys_error (ERR_SEVERE, "Error creating projector thread");
2146         delete pProjector;
2147         return;
2148       }
2149       pProjector->SetPriority(60);
2150       pProjector->Run();
2151       return;
2152     } else      
2153 #endif // HAVE_WXTHREADS
2154     {
2155       pProj = new Projections;
2156       pProj->initFromScanner (theScanner);
2157       wxProgressDialog dlgProgress (wxString("Projection"), wxString("Projection Progress"), pProj->nView() + 1, getFrameForChild(), wxPD_CAN_ABORT );
2158       for (int i = 0; i < pProj->nView(); i++) {
2159         //theScanner.collectProjections (*pProj, rPhantom, i, 1, true, m_iDefaultTrace);
2160         theScanner.collectProjections (*pProj, rPhantom, i, 1, theScanner.offsetView(), true, m_iDefaultTrace);
2161         if ((i + 1) % ITER_PER_UPDATE == 0)
2162           if (! dlgProgress.Update (i+1)) {
2163             delete pProj;
2164             return;
2165           }
2166       }
2167     }
2168   }
2169   
2170   *theApp->getLog() << os.str().c_str() << "\n";
2171   pProj->setRemark (os.str());
2172   pProj->setCalcTime (timer.timerEnd());
2173   
2174   ProjectionFileDocument* pProjectionDoc = theApp->newProjectionDoc();
2175   if (! pProjectionDoc) {
2176     sys_error (ERR_SEVERE, "Unable to create projection document");
2177     return;
2178   }
2179   pProjectionDoc->setProjections (pProj);
2180   if (theApp->getAskDeleteNewDocs())
2181     pProjectionDoc-> Modify(true);
2182   pProjectionDoc->UpdateAllViews (this);
2183   pProjectionDoc->getView()->setInitialClientSize();
2184   pProjectionDoc->Activate();
2185 }
2186
2187
2188 void
2189 PhantomFileView::OnRasterize (wxCommandEvent& event)
2190 {
2191   DialogGetRasterParameters dialogRaster (getFrameForChild(), m_iDefaultRasterNX, m_iDefaultRasterNY, 
2192     m_iDefaultRasterNSamples, m_dDefaultRasterViewRatio);
2193   int retVal = dialogRaster.ShowModal();
2194   if (retVal != wxID_OK)
2195     return;
2196   
2197   m_iDefaultRasterNX = dialogRaster.getXSize();
2198   m_iDefaultRasterNY  = dialogRaster.getYSize();
2199   m_iDefaultRasterNSamples = dialogRaster.getNSamples();
2200   m_dDefaultRasterViewRatio = dialogRaster.getViewRatio();
2201   if (m_iDefaultRasterNSamples < 1)
2202     m_iDefaultRasterNSamples = 1;
2203   if (m_dDefaultRasterViewRatio < 0)
2204     m_dDefaultRasterViewRatio = 0;
2205   if (m_iDefaultRasterNX <= 0 || m_iDefaultRasterNY <= 0) 
2206     return;
2207   
2208   const Phantom& rPhantom = GetDocument()->getPhantom();
2209   std::ostringstream os;
2210   os << "Rasterize Phantom " << rPhantom.name() << ": XSize=" << m_iDefaultRasterNX << ", YSize=" 
2211     << m_iDefaultRasterNY << ", ViewRatio=" << m_dDefaultRasterViewRatio << ", nSamples=" 
2212     << m_iDefaultRasterNSamples;;
2213   
2214 #if HAVE_WXTHREADS
2215   if (theApp->getUseBackgroundTasks()) {
2216     RasterizerSupervisorThread* pThread = new RasterizerSupervisorThread (this, m_iDefaultRasterNX, m_iDefaultRasterNY,
2217       m_iDefaultRasterNSamples, m_dDefaultRasterViewRatio, os.str().c_str());
2218     if (pThread->Create() != wxTHREAD_NO_ERROR) {
2219       *theApp->getLog() << "Error creating rasterizer thread\n";
2220       return;
2221     }
2222     pThread->SetPriority (60);
2223     pThread->Run();
2224   } else 
2225 #endif
2226   {
2227     ImageFile* pImageFile = new ImageFile (m_iDefaultRasterNX, m_iDefaultRasterNY);
2228
2229     wxProgressDialog dlgProgress (wxString("Rasterize"), 
2230                                   wxString("Rasterization Progress"), 
2231                                   pImageFile->nx() + 1,
2232                                   getFrameForChild(), 
2233                                   wxPD_CAN_ABORT );
2234     Timer timer;
2235     for (unsigned int i = 0; i < pImageFile->nx(); i++) {
2236       rPhantom.convertToImagefile (*pImageFile, m_dDefaultRasterViewRatio, 
2237                                    m_iDefaultRasterNSamples, Trace::TRACE_NONE,
2238                                    i, 1, true);
2239       if ((i + 1) % ITER_PER_UPDATE == 0) 
2240         if (! dlgProgress.Update (i+1)) {
2241           delete pImageFile;
2242           return;
2243         }
2244     }
2245     
2246     ImageFileDocument* pRasterDoc = theApp->newImageDoc();
2247     if (! pRasterDoc) {
2248       sys_error (ERR_SEVERE, "Unable to create image file");
2249       return;
2250     }
2251     pRasterDoc->setImageFile (pImageFile);
2252     if (theApp->getAskDeleteNewDocs())
2253       pRasterDoc->Modify (true);
2254     *theApp->getLog() << os.str().c_str() << "\n";
2255     pImageFile->labelAdd (os.str().c_str(), timer.timerEnd());
2256
2257     pRasterDoc->UpdateAllViews(this);
2258     pRasterDoc->getView()->setInitialClientSize();
2259     pRasterDoc->Activate();
2260   }
2261 }
2262
2263
2264 PhantomCanvas* 
2265 PhantomFileView::CreateCanvas (wxFrame *parent)
2266 {
2267   PhantomCanvas* pCanvas;
2268   
2269   pCanvas = new PhantomCanvas (this, parent, wxPoint(0, 0), wxSize(0,0), 0);
2270   pCanvas->SetBackgroundColour(*wxWHITE);
2271   pCanvas->Clear();
2272   
2273   return pCanvas;
2274 }
2275
2276 #if CTSIM_MDI
2277 wxDocMDIChildFrame*
2278 #else
2279 wxDocChildFrame*
2280 #endif
2281 PhantomFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2282 {
2283 #if CTSIM_MDI
2284   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2285 #else
2286   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2287 #endif
2288   theApp->setIconForFrame (subframe);
2289   
2290   m_pFileMenu = new wxMenu;
2291   
2292   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
2293   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
2294   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
2295   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
2296   m_pFileMenu->Append(wxID_CLOSE, "&Close");
2297   
2298   m_pFileMenu->AppendSeparator();
2299   m_pFileMenu->Append(PHMMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
2300   
2301   m_pFileMenu->AppendSeparator();
2302   m_pFileMenu->Append(wxID_PRINT, "&Print...");
2303   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
2304   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
2305   m_pFileMenu->AppendSeparator();
2306   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
2307 #ifdef CTSIM_MDI
2308   m_pFileMenu->AppendSeparator();
2309   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
2310   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
2311 #endif
2312   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
2313   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
2314   
2315   wxMenu *process_menu = new wxMenu;
2316   process_menu->Append(PHMMENU_PROCESS_RASTERIZE, "&Rasterize...\tCtrl-R");
2317   process_menu->Append(PHMMENU_PROCESS_PROJECTIONS, "&Projections...\tCtrl-J");
2318   
2319   wxMenu *help_menu = new wxMenu;
2320   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
2321   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
2322   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
2323   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
2324   
2325   wxMenuBar *menu_bar = new wxMenuBar;
2326   
2327   menu_bar->Append(m_pFileMenu, "&File");
2328   menu_bar->Append(process_menu, "&Process");
2329   menu_bar->Append(help_menu, "&Help");
2330   
2331   subframe->SetMenuBar(menu_bar);
2332   subframe->Centre(wxBOTH);
2333   
2334   wxAcceleratorEntry accelEntries[3];
2335   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('J'), PHMMENU_PROCESS_PROJECTIONS);
2336   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('R'), PHMMENU_PROCESS_RASTERIZE);
2337   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('I'), PHMMENU_FILE_PROPERTIES);
2338   wxAcceleratorTable accelTable (3, accelEntries);
2339   subframe->SetAcceleratorTable (accelTable);
2340   
2341   return subframe;
2342 }
2343
2344
2345 bool 
2346 PhantomFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
2347 {
2348   m_pFrame = CreateChildFrame(doc, this);
2349   SetFrame(m_pFrame);
2350   m_pCanvas = CreateCanvas (m_pFrame);
2351   m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
2352   m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
2353   m_pFrame->SetTitle ("PhantomFileView");
2354
2355   m_pFrame->Show(true);
2356   Activate(true);
2357   
2358   return true;
2359 }
2360
2361 void 
2362 PhantomFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2363 {
2364   if (m_pCanvas)
2365     m_pCanvas->Refresh();
2366 }
2367
2368 bool 
2369 PhantomFileView::OnClose (bool deleteWindow)
2370 {
2371   //GetDocumentManager()->ActivateView (this, false, true);
2372   if (! GetDocument() || ! GetDocument()->Close())
2373     return false;
2374   
2375   Activate(false);
2376   if (m_pCanvas) {
2377     m_pCanvas->setView(NULL);
2378     m_pCanvas = NULL;
2379   }
2380   wxString s(wxTheApp->GetAppName());
2381   if (m_pFrame)
2382     m_pFrame->SetTitle(s);
2383   
2384   SetFrame(NULL);
2385   
2386   if (deleteWindow) {
2387     delete m_pFrame;
2388     m_pFrame = NULL;
2389     if (GetDocument() && GetDocument()->getBadFileOpen())
2390       ::wxYield();  // wxWindows bug workaround
2391   }
2392   
2393   return true;
2394 }
2395
2396 void
2397 PhantomFileView::OnDraw (wxDC* dc)
2398 {
2399   int xsize, ysize;
2400   m_pCanvas->GetClientSize (&xsize, &ysize);
2401   SGPDriver driver (dc, xsize, ysize);
2402   SGP sgp (driver);
2403   const Phantom& rPhantom = GetDocument()->getPhantom();
2404   sgp.setColor (C_RED);
2405   rPhantom.show (sgp);
2406 }
2407
2408 // ProjectionCanvas
2409
2410 ProjectionFileCanvas::ProjectionFileCanvas (ProjectionFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
2411 : wxScrolledWindow(frame, -1, pos, size, style)
2412 {
2413   m_pView = v;
2414 }
2415
2416 ProjectionFileCanvas::~ProjectionFileCanvas ()
2417 {
2418   m_pView = NULL;
2419 }
2420
2421 void 
2422 ProjectionFileCanvas::OnDraw(wxDC& dc)
2423 {
2424   if (m_pView)
2425     m_pView->OnDraw(& dc);
2426 }
2427
2428 wxSize
2429 ProjectionFileCanvas::GetBestSize () const
2430 {
2431   wxSize best (0, 0);
2432   if (! m_pView)
2433     return best;
2434
2435   if (m_pView) {
2436     Projections& rProj = m_pView->GetDocument()->getProjections();
2437     best.Set (rProj.nDet(), rProj.nView());
2438   }
2439   
2440   return best;
2441 }
2442
2443
2444 // ProjectionFileView
2445
2446 IMPLEMENT_DYNAMIC_CLASS(ProjectionFileView, wxView)
2447
2448 BEGIN_EVENT_TABLE(ProjectionFileView, wxView)
2449 EVT_MENU(PJMENU_FILE_PROPERTIES, ProjectionFileView::OnProperties)
2450 EVT_MENU(PJMENU_RECONSTRUCT_FBP, ProjectionFileView::OnReconstructFBP)
2451 EVT_MENU(PJMENU_RECONSTRUCT_FBP_REBIN, ProjectionFileView::OnReconstructFBPRebin)
2452 EVT_MENU(PJMENU_RECONSTRUCT_FOURIER, ProjectionFileView::OnReconstructFourier)
2453 EVT_MENU(PJMENU_CONVERT_RECTANGULAR, ProjectionFileView::OnConvertRectangular)
2454 EVT_MENU(PJMENU_CONVERT_POLAR, ProjectionFileView::OnConvertPolar)
2455 EVT_MENU(PJMENU_CONVERT_FFT_POLAR, ProjectionFileView::OnConvertFFTPolar)
2456 EVT_MENU(PJMENU_CONVERT_PARALLEL, ProjectionFileView::OnConvertParallel)
2457 EVT_MENU(PJMENU_PLOT_TTHETA_SAMPLING, ProjectionFileView::OnPlotTThetaSampling)
2458 EVT_MENU(PJMENU_PLOT_HISTOGRAM, ProjectionFileView::OnPlotHistogram)
2459   // EVT_MENU(PJMENU_ARTIFACT_REDUCTION, ProjectionFileView::OnArtifactReduction)
2460 END_EVENT_TABLE()
2461
2462
2463 ProjectionFileView::ProjectionFileView() 
2464 : wxView(), m_pFrame(0), m_pCanvas(0), m_pFileMenu(0)
2465 {
2466 #ifdef DEBUG
2467   m_iDefaultNX = 115;
2468   m_iDefaultNY = 115;
2469 #else
2470   m_iDefaultNX = 256;
2471   m_iDefaultNY = 256;
2472 #endif
2473   
2474   m_iDefaultFilter = SignalFilter::FILTER_ABS_BANDLIMIT;
2475   m_dDefaultFilterParam = 1.;
2476 #if HAVE_FFTW
2477   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_RFFTW;
2478   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_INVERSE_FOURIER;
2479 #else
2480   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_CONVOLUTION;
2481   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT;
2482 #endif
2483   m_iDefaultZeropad = 1;
2484   m_iDefaultBackprojector = Backprojector::BPROJ_IDIFF;
2485   m_iDefaultInterpolation = Backprojector::INTERP_LINEAR;
2486   m_iDefaultInterpParam = 1;
2487   m_iDefaultTrace = Trace::TRACE_NONE;
2488   
2489   m_iDefaultPolarNX = 256;
2490   m_iDefaultPolarNY = 256;
2491   m_iDefaultPolarInterpolation = Projections::POLAR_INTERP_BILINEAR;
2492   m_iDefaultPolarZeropad = 1;
2493 }
2494
2495 ProjectionFileView::~ProjectionFileView()
2496 {
2497   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
2498   GetDocumentManager()->ActivateView(this, FALSE, TRUE);;
2499 }
2500
2501 void
2502 ProjectionFileView::OnProperties (wxCommandEvent& event)
2503 {
2504   const Projections& rProj = GetDocument()->getProjections();
2505   std::ostringstream os;
2506   rProj.printScanInfo(os);
2507   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
2508   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Projection File Properties", wxOK | wxICON_INFORMATION);
2509   dialogMsg.ShowModal();
2510   GetDocument()->Activate();
2511 }
2512
2513
2514 void
2515 ProjectionFileView::OnConvertRectangular (wxCommandEvent& event)
2516 {
2517   Projections& rProj = GetDocument()->getProjections();
2518   
2519   int nDet = rProj.nDet();
2520   int nView = rProj.nView();
2521   ImageFile* pIF = new ImageFile (nDet, nView);
2522   ImageFileArray v = pIF->getArray();
2523   for (int iv = 0; iv < nView; iv++) {
2524     DetectorValue* detval = rProj.getDetectorArray(iv).detValues();
2525     
2526     for (int id = 0; id < nDet; id++)
2527       v[id][iv] = detval[id];
2528   }
2529   
2530   ImageFileDocument* pRectDoc = theApp->newImageDoc ();
2531   if (! pRectDoc) {
2532     sys_error (ERR_SEVERE, "Unable to create image file");
2533     return;
2534   }
2535   pRectDoc->setImageFile (pIF);
2536   pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2537   std::ostringstream os;
2538   os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to rectangular image";
2539   *theApp->getLog() << os.str().c_str() << "\n";
2540   pIF->labelAdd (os.str().c_str());
2541   if (theApp->getAskDeleteNewDocs())
2542     pRectDoc->Modify (true);
2543   pRectDoc->UpdateAllViews();
2544   pRectDoc->getView()->setInitialClientSize();
2545   pRectDoc->Activate();
2546 }
2547
2548 void
2549 ProjectionFileView::OnConvertPolar (wxCommandEvent& event)
2550 {
2551   Projections& rProj = GetDocument()->getProjections();
2552   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2553     m_iDefaultPolarInterpolation, -1, IDH_DLG_POLAR);
2554   if (dialogPolar.ShowModal() == wxID_OK) {
2555     wxProgressDialog dlgProgress (wxString("Convert Polar"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2556     wxString strInterpolation (dialogPolar.getInterpolationName());
2557     m_iDefaultPolarNX = dialogPolar.getXSize();
2558     m_iDefaultPolarNY = dialogPolar.getYSize();
2559     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2560     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2561     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2562     
2563     if (! rProj.convertPolar (*pIF, m_iDefaultPolarInterpolation)) {
2564       delete pIF;
2565       *theApp->getLog() << "Error converting to Polar\n";
2566       return;
2567     }
2568     
2569     pPolarDoc = theApp->newImageDoc ();
2570     if (! pPolarDoc) {
2571       sys_error (ERR_SEVERE, "Unable to create image file");
2572       return;
2573     }
2574     pPolarDoc->setImageFile (pIF);
2575     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2576     std::ostringstream os;
2577     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to polar image: xSize=" 
2578       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2579       << strInterpolation.c_str();
2580     *theApp->getLog() << os.str().c_str() << "\n";
2581     pIF->labelAdd (os.str().c_str());
2582     if (theApp->getAskDeleteNewDocs())
2583       pPolarDoc->Modify (true);
2584     pPolarDoc->UpdateAllViews ();
2585     pPolarDoc->getView()->setInitialClientSize();
2586     pPolarDoc->Activate();
2587   }
2588 }
2589
2590 void
2591 ProjectionFileView::OnConvertFFTPolar (wxCommandEvent& event)
2592 {
2593   Projections& rProj = GetDocument()->getProjections();
2594   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert to FFT Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2595     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad, IDH_DLG_FFT_POLAR);
2596   if (dialogPolar.ShowModal() == wxID_OK) {
2597     wxProgressDialog dlgProgress (wxString("Convert FFT Polar"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2598     wxString strInterpolation (dialogPolar.getInterpolationName());
2599     m_iDefaultPolarNX = dialogPolar.getXSize();
2600     m_iDefaultPolarNY = dialogPolar.getYSize();
2601     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2602     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2603     
2604     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2605     if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
2606       delete pIF;
2607       *theApp->getLog() << "Error converting to polar\n";
2608       return;
2609     }
2610     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2611     if (! pPolarDoc) {
2612       sys_error (ERR_SEVERE, "Unable to create image file");
2613       return;
2614     }
2615     pPolarDoc->setImageFile (pIF);
2616     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2617     std::ostringstream os;
2618     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to FFT polar image: xSize=" 
2619       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2620       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2621     *theApp->getLog() << os.str().c_str() << "\n";
2622     pIF->labelAdd (os.str().c_str());
2623     if (theApp->getAskDeleteNewDocs())
2624       pPolarDoc->Modify (true);
2625     pPolarDoc->UpdateAllViews (this);
2626     pPolarDoc->getView()->setInitialClientSize();
2627     pPolarDoc->Activate();
2628   }
2629 }
2630
2631 void
2632 ProjectionFileView::OnPlotTThetaSampling (wxCommandEvent& event)
2633 {
2634   DialogGetThetaRange dlgTheta (this->getFrame(), ParallelRaysums::THETA_RANGE_UNCONSTRAINED);
2635   if (dlgTheta.ShowModal() != wxID_OK)
2636     return;
2637   
2638   int iThetaRange = dlgTheta.getThetaRange();
2639   
2640   Projections& rProj = GetDocument()->getProjections();
2641   ParallelRaysums parallel (&rProj, iThetaRange);
2642   PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
2643   PlotFile& rPlot = pPlotDoc->getPlotFile();
2644   ParallelRaysums::CoordinateContainer& coordContainer = parallel.getCoordinates();
2645   double* pdT = new double [parallel.getNumCoordinates()];
2646   double* pdTheta = new double [parallel.getNumCoordinates()];
2647   
2648   for (int i = 0; i < parallel.getNumCoordinates(); i++) {
2649     pdT[i] = coordContainer[i]->m_dT;
2650     pdTheta[i] = coordContainer[i]->m_dTheta;
2651   }
2652   rPlot.setCurveSize (2, parallel.getNumCoordinates(), true);
2653   rPlot.addEzsetCommand ("title T-Theta Sampling");
2654   rPlot.addEzsetCommand ("xlabel T");
2655   rPlot.addEzsetCommand ("ylabel Theta");
2656   rPlot.addEzsetCommand ("curve 1");
2657   if (rProj.nDet() < 50 && rProj.nView() < 50)
2658     rPlot.addEzsetCommand ("symbol 1"); // x symbol
2659   else
2660     rPlot.addEzsetCommand ("symbol 6"); // point symbol
2661   rPlot.addEzsetCommand ("noline");
2662   rPlot.addColumn (0, pdT);
2663   rPlot.addColumn (1, pdTheta);
2664   delete pdT;
2665   delete pdTheta;
2666   if (theApp->getAskDeleteNewDocs())
2667     pPlotDoc->Modify (true);
2668   pPlotDoc->getView()->getFrame()->Show(true);
2669   pPlotDoc->UpdateAllViews ();
2670   pPlotDoc->Activate();
2671 }
2672
2673
2674 void
2675 ProjectionFileView::OnPlotHistogram (wxCommandEvent& event)
2676
2677   Projections& rProj = GetDocument()->getProjections();
2678   int nDet = rProj.nDet();
2679   int nView = rProj.nView();
2680   
2681   if (nDet < 1 || nView < 1)
2682     return;
2683
2684   PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
2685   if (! pPlotDoc) {
2686     sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
2687     return;
2688   }
2689     
2690   DetectorValue* pdDetval = rProj.getDetectorArray(0).detValues();
2691   double dMin = pdDetval[0], dMax = pdDetval[0];
2692
2693   for (int iv = 0; iv < nView; iv++) {
2694     pdDetval = rProj.getDetectorArray(iv).detValues();
2695     for (int id = 0; id < nDet; id++) {
2696       double dV = pdDetval[id];
2697       if (dV < dMin)
2698         dMin = dV;
2699       else if (dV > dMax)
2700         dMax = dV;
2701     }
2702   }
2703
2704   double* pX = new double [NUMBER_HISTOGRAM_BINS];
2705   double* pY = new double [NUMBER_HISTOGRAM_BINS];
2706   double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
2707     
2708   for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
2709     pX[i] = dMin + (i + 0.5) * dBinWidth;
2710     pY[i] = 0;
2711   }
2712   for (int j = 0; j < nView; j++) {
2713     pdDetval = rProj.getDetectorArray(j).detValues();
2714     for (int id = 0; id < nDet; id++) {
2715       int iBin = nearest<int> ((pdDetval[id] - dMin) / dBinWidth);
2716       if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
2717         pY[iBin] += 1;
2718     }
2719   }      
2720   PlotFile& rPlotFile = pPlotDoc->getPlotFile();
2721   std::ostringstream os;
2722   os << "Histogram";
2723   std::string title("title ");
2724   title += os.str();
2725   rPlotFile.addEzsetCommand (title.c_str());
2726   rPlotFile.addEzsetCommand ("xlabel Detector Value");
2727   rPlotFile.addEzsetCommand ("ylabel Count");
2728   rPlotFile.addEzsetCommand ("box");
2729   rPlotFile.addEzsetCommand ("grid");
2730   rPlotFile.setCurveSize (2, NUMBER_HISTOGRAM_BINS);
2731   rPlotFile.addColumn (0, pX);
2732   rPlotFile.addColumn (1, pY);
2733   rPlotFile.addDescription (rProj.remark());
2734   os << " plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
2735   *theApp->getLog() << os.str().c_str() << "\n";
2736   rPlotFile.addDescription (os.str().c_str());
2737   delete pX;
2738   delete pY;
2739   if (theApp->getAskDeleteNewDocs())
2740     pPlotDoc->Modify (true);
2741   pPlotDoc->getView()->getFrame()->Show(true);
2742   pPlotDoc->UpdateAllViews ();
2743   pPlotDoc->Activate();
2744 }
2745
2746
2747 void
2748 ProjectionFileView::OnConvertParallel (wxCommandEvent& event)
2749 {
2750   Projections& rProj = GetDocument()->getProjections();
2751   if (rProj.geometry() == Scanner::GEOMETRY_PARALLEL) {
2752     wxMessageBox ("Projections are already parallel", "Error");
2753     return;
2754   }
2755   wxProgressDialog dlgProgress (wxString("Convert to Parallel"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2756   Projections* pProjNew = rProj.interpolateToParallel();
2757   ProjectionFileDocument* pProjDocNew = theApp->newProjectionDoc();
2758   pProjDocNew->setProjections (pProjNew);  
2759   
2760   if (ProjectionFileView* projView = pProjDocNew->getView()) {
2761     projView->OnUpdate (projView, NULL);
2762     if (projView->getCanvas())
2763       projView->getCanvas()->SetClientSize (pProjNew->nDet(), pProjNew->nView());
2764     if (wxFrame* pFrame = projView->getFrame()) {
2765       pFrame->Show(true);
2766       pFrame->SetFocus();
2767       pFrame->Raise();
2768     }
2769     GetDocumentManager()->ActivateView (projView, true, false);
2770   }
2771   if (theApp->getAskDeleteNewDocs())
2772     pProjDocNew-> Modify(true);
2773   pProjDocNew->UpdateAllViews (this);
2774   pProjDocNew->getView()->setInitialClientSize();
2775   pProjDocNew->Activate();
2776 }
2777
2778 void
2779 ProjectionFileView::OnReconstructFourier (wxCommandEvent& event)
2780 {
2781   Projections& rProj = GetDocument()->getProjections();
2782   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Fourier Reconstruction", m_iDefaultPolarNX, m_iDefaultPolarNY,
2783     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad, IDH_DLG_RECON_FOURIER);
2784   if (dialogPolar.ShowModal() == wxID_OK) {
2785     wxProgressDialog dlgProgress (wxString("Reconstruction Fourier"), wxString("Reconstruction Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2786     wxString strInterpolation (dialogPolar.getInterpolationName());
2787     m_iDefaultPolarNX = dialogPolar.getXSize();
2788     m_iDefaultPolarNY = dialogPolar.getYSize();
2789     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2790     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2791     
2792     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2793     if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
2794       delete pIF;
2795       *theApp->getLog() << "Error converting to polar\n";
2796       return;
2797     }
2798 #ifdef HAVE_FFT
2799     pIF->ifft(*pIF);
2800 #endif
2801     pIF->magnitude(*pIF);
2802     Fourier::shuffleFourierToNaturalOrder (*pIF);
2803
2804     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2805     if (! pPolarDoc) {
2806       sys_error (ERR_SEVERE, "Unable to create image file");
2807       return;
2808     }
2809     pPolarDoc->setImageFile (pIF);
2810     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2811     std::ostringstream os;
2812     os << "Reconstruct Fourier " << GetFrame()->GetTitle().c_str() << ": xSize=" 
2813       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2814       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2815     *theApp->getLog() << os.str().c_str() << "\n";
2816     pIF->labelAdd (os.str().c_str());
2817     if (theApp->getAskDeleteNewDocs())
2818       pPolarDoc->Modify (true);
2819     pPolarDoc->UpdateAllViews ();
2820     pPolarDoc->getView()->setInitialClientSize();
2821     pPolarDoc->Activate();
2822   }
2823 }
2824
2825 void
2826 ProjectionFileView::OnReconstructFBPRebin (wxCommandEvent& event)
2827 {
2828   Projections& rProj = GetDocument()->getProjections();
2829   doReconstructFBP (rProj, true);
2830 }
2831
2832 void
2833 ProjectionFileView::OnReconstructFBP (wxCommandEvent& event)
2834 {
2835   Projections& rProj = GetDocument()->getProjections();
2836   doReconstructFBP (rProj, false);
2837 }
2838
2839 void
2840 ProjectionFileView::doReconstructFBP (const Projections& rProj, bool bRebinToParallel)
2841 {
2842   ReconstructionROI defaultROI;
2843   defaultROI.m_dXMin = -rProj.phmLen() / 2;
2844   defaultROI.m_dXMax = defaultROI.m_dXMin + rProj.phmLen();
2845   defaultROI.m_dYMin = -rProj.phmLen() / 2;
2846   defaultROI.m_dYMax = defaultROI.m_dYMin + rProj.phmLen();
2847   
2848   DialogGetReconstructionParameters dialogReconstruction (getFrameForChild(), m_iDefaultNX, m_iDefaultNY, 
2849     m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration, 
2850     m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector, 
2851     m_iDefaultTrace,  &defaultROI);
2852   
2853   int retVal = dialogReconstruction.ShowModal();
2854   if (retVal != wxID_OK)
2855     return;
2856   
2857   m_iDefaultNX = dialogReconstruction.getXSize();
2858   m_iDefaultNY = dialogReconstruction.getYSize();
2859   wxString optFilterName = dialogReconstruction.getFilterName();
2860   m_iDefaultFilter = SignalFilter::convertFilterNameToID (optFilterName.c_str());
2861   m_dDefaultFilterParam = dialogReconstruction.getFilterParam();
2862   wxString optFilterMethodName = dialogReconstruction.getFilterMethodName();
2863   m_iDefaultFilterMethod = ProcessSignal::convertFilterMethodNameToID(optFilterMethodName.c_str());
2864   m_iDefaultZeropad = dialogReconstruction.getZeropad();
2865   wxString optFilterGenerationName = dialogReconstruction.getFilterGenerationName();
2866   m_iDefaultFilterGeneration = ProcessSignal::convertFilterGenerationNameToID (optFilterGenerationName.c_str());
2867   wxString optInterpName = dialogReconstruction.getInterpName();
2868   m_iDefaultInterpolation = Backprojector::convertInterpNameToID (optInterpName.c_str());
2869   m_iDefaultInterpParam = dialogReconstruction.getInterpParam();
2870   wxString optBackprojectName = dialogReconstruction.getBackprojectName();
2871   m_iDefaultBackprojector = Backprojector::convertBackprojectNameToID (optBackprojectName.c_str());
2872   m_iDefaultTrace = dialogReconstruction.getTrace();
2873   dialogReconstruction.getROI (&defaultROI);
2874   
2875   if (m_iDefaultNX <= 0 && m_iDefaultNY <= 0) 
2876     return;
2877   
2878   std::ostringstream os;
2879   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();
2880   if (bRebinToParallel)
2881     os << "; Interpolate to Parallel";
2882   
2883   Timer timerRecon;
2884   ImageFile* pImageFile = NULL;
2885   if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
2886     pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
2887     Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(), 
2888       m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), 
2889       optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, 
2890       &defaultROI, bRebinToParallel);
2891     
2892     ReconstructDialog* pDlgReconstruct = new ReconstructDialog (*pReconstructor, rProj, *pImageFile, m_iDefaultTrace, getFrameForChild());
2893     for (int iView = 0; iView < rProj.nView(); iView++) {
2894       ::wxYield();
2895       if (pDlgReconstruct->isCancelled() || ! pDlgReconstruct->reconstructView (iView, true)) {
2896         delete pDlgReconstruct;
2897         delete pReconstructor;
2898         return;
2899       }
2900       ::wxYield();
2901       ::wxYield();
2902       while (pDlgReconstruct->isPaused()) {
2903         ::wxYield();
2904         ::wxUsleep(50);
2905       }
2906     }
2907     pReconstructor->postProcessing();
2908     delete pDlgReconstruct;
2909     delete pReconstructor;
2910   } else {
2911 #if HAVE_WXTHREADS
2912     if (theApp->getUseBackgroundTasks()) {
2913       ReconstructorSupervisorThread* pReconstructor = new ReconstructorSupervisorThread (this, m_iDefaultNX, 
2914         m_iDefaultNY, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(), 
2915         m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam, 
2916         optBackprojectName.c_str(), os.str().c_str(), &defaultROI, bRebinToParallel);
2917       if (pReconstructor->Create() != wxTHREAD_NO_ERROR) {
2918         sys_error (ERR_SEVERE, "Error creating reconstructor thread");
2919         delete pReconstructor;
2920         return;
2921       }
2922       pReconstructor->SetPriority (60);
2923       pReconstructor->Run();
2924       return;
2925     } else 
2926 #endif
2927     {
2928       pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
2929       wxProgressDialog dlgProgress (wxString("Reconstruction"), wxString("Reconstruction Progress"), rProj.nView() + 1, getFrameForChild(), wxPD_CAN_ABORT );
2930       Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(), 
2931         m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), 
2932         optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, 
2933         &defaultROI, bRebinToParallel);
2934       
2935       for (int iView = 0; iView < rProj.nView(); iView++) {
2936         pReconstructor->reconstructView (iView, 1);
2937         if ((iView + 1) % ITER_PER_UPDATE == 0) 
2938           if (! dlgProgress.Update (iView + 1)) {
2939             delete pReconstructor;
2940             return; // don't make new window, thread will do this
2941           }
2942       }
2943       pReconstructor->postProcessing();
2944       delete pReconstructor;
2945     }
2946   }
2947   ImageFileDocument* pReconDoc = theApp->newImageDoc();
2948   if (! pReconDoc) {
2949     sys_error (ERR_SEVERE, "Unable to create image file");
2950     return;
2951   }
2952   *theApp->getLog() << os.str().c_str() << "\n";
2953   pImageFile->labelAdd (rProj.getLabel());
2954   pImageFile->labelAdd (os.str().c_str(), timerRecon.timerEnd());    
2955
2956   pReconDoc->setImageFile (pImageFile);
2957   if (theApp->getAskDeleteNewDocs())
2958     pReconDoc->Modify (true);
2959   pReconDoc->UpdateAllViews();
2960   pReconDoc->getView()->setInitialClientSize();
2961   pReconDoc->Activate();
2962 }
2963
2964
2965 void
2966 ProjectionFileView::OnArtifactReduction (wxCommandEvent& event)
2967 {
2968 }
2969
2970
2971 ProjectionFileCanvas* 
2972 ProjectionFileView::CreateCanvas (wxFrame *parent)
2973 {
2974   ProjectionFileCanvas* pCanvas;
2975   int width, height;
2976   parent->GetClientSize(&width, &height);
2977   
2978   pCanvas = new ProjectionFileCanvas (this, parent, wxPoint(0, 0), wxSize(width, height), 0);
2979   
2980   pCanvas->SetScrollbars(20, 20, 50, 50);
2981   pCanvas->SetBackgroundColour(*wxWHITE);
2982   pCanvas->Clear();
2983   
2984   return pCanvas;
2985 }
2986
2987 #if CTSIM_MDI
2988 wxDocMDIChildFrame*
2989 #else
2990 wxDocChildFrame*
2991 #endif
2992 ProjectionFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2993 {
2994 #ifdef CTSIM_MDI
2995   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2996 #else
2997   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2998 #endif
2999   theApp->setIconForFrame (subframe);
3000   
3001   m_pFileMenu = new wxMenu;
3002   
3003   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3004   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3005   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3006   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3007   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3008   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3009   
3010   m_pFileMenu->AppendSeparator();
3011   m_pFileMenu->Append(PJMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
3012   
3013   m_pFileMenu->AppendSeparator();
3014   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3015   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3016   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3017   m_pFileMenu->AppendSeparator();
3018   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3019 #ifdef CTSIM_MDI
3020   m_pFileMenu->AppendSeparator();
3021   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3022   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3023 #endif
3024   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3025   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3026   
3027   wxMenu *convert_menu = new wxMenu;
3028   convert_menu->Append (PJMENU_CONVERT_RECTANGULAR, "&Rectangular Image");
3029   convert_menu->Append (PJMENU_CONVERT_POLAR, "&Polar Image...\tCtrl-L");
3030   convert_menu->Append (PJMENU_CONVERT_FFT_POLAR, "FF&T->Polar Image...\tCtrl-T");
3031   convert_menu->AppendSeparator();
3032   convert_menu->Append (PJMENU_CONVERT_PARALLEL, "&Interpolate to Parallel");
3033   
3034   //  wxMenu* filter_menu = new wxMenu;
3035   //  filter_menu->Append (PJMENU_ARTIFACT_REDUCTION, "&Artifact Reduction");
3036   
3037   wxMenu* analyze_menu = new wxMenu;
3038   analyze_menu->Append (PJMENU_PLOT_HISTOGRAM, "&Plot Histogram");
3039   analyze_menu->Append (PJMENU_PLOT_TTHETA_SAMPLING, "Plot T-T&heta Sampling...\tCtrl-H");
3040
3041   wxMenu *reconstruct_menu = new wxMenu;
3042   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP, "&Filtered Backprojection...\tCtrl-R", "Reconstruct image using filtered backprojection");
3043   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP_REBIN, "Filtered &Backprojection (Rebin to Parallel)...\tCtrl-B", "Reconstruct image using filtered backprojection");
3044   // still buggy
3045   //   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FOURIER, "&Fourier...\tCtrl-E", "Reconstruct image using inverse Fourier");
3046   
3047   wxMenu *help_menu = new wxMenu;
3048   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3049   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3050   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3051   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3052   
3053   wxMenuBar *menu_bar = new wxMenuBar;
3054   
3055   menu_bar->Append (m_pFileMenu, "&File");
3056   menu_bar->Append (convert_menu, "&Convert");
3057   //  menu_bar->Append (filter_menu, "Fi&lter");
3058   menu_bar->Append (analyze_menu, "&Analyze");
3059   menu_bar->Append (reconstruct_menu, "&Reconstruct");
3060   menu_bar->Append (help_menu, "&Help");
3061   
3062   subframe->SetMenuBar(menu_bar);  
3063   subframe->Centre(wxBOTH);
3064   
3065   wxAcceleratorEntry accelEntries[7];
3066   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('L'), PJMENU_CONVERT_POLAR);
3067   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('T'), PJMENU_CONVERT_FFT_POLAR);
3068   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('R'), PJMENU_RECONSTRUCT_FBP);
3069   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('B'), PJMENU_RECONSTRUCT_FBP_REBIN);
3070   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('E'), PJMENU_RECONSTRUCT_FOURIER);
3071   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('I'), PJMENU_FILE_PROPERTIES);
3072   accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('H'), PJMENU_PLOT_TTHETA_SAMPLING);
3073   wxAcceleratorTable accelTable (7, accelEntries);
3074   subframe->SetAcceleratorTable (accelTable);
3075   
3076   return subframe;
3077 }
3078
3079
3080 bool 
3081 ProjectionFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
3082 {
3083   m_pFrame = CreateChildFrame(doc, this);
3084   SetFrame(m_pFrame);
3085   
3086   int width, height;
3087   m_pFrame->GetClientSize (&width, &height);
3088   m_pFrame->SetTitle ("ProjectionFileView");
3089   m_pCanvas = CreateCanvas (m_pFrame);
3090   
3091   m_pFrame->Show(true);
3092   Activate(true);
3093   
3094   return true;
3095 }
3096
3097 void 
3098 ProjectionFileView::OnDraw (wxDC* dc)
3099 {
3100   if (m_bitmap.Ok())
3101     dc->DrawBitmap (m_bitmap, 0, 0, false);
3102 }
3103
3104
3105 void 
3106 ProjectionFileView::setInitialClientSize ()
3107 {
3108   wxSize bestSize = m_pCanvas->GetBestSize();
3109
3110   if (bestSize.x > 800)
3111     bestSize.x = 800;
3112   if (bestSize.y > 800)
3113     bestSize.y = 800;
3114
3115   m_pFrame->SetClientSize (bestSize);
3116   m_pFrame->Show (true);
3117   m_pFrame->SetFocus();
3118 }  
3119
3120 void 
3121 ProjectionFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3122 {
3123   const Projections& rProj = GetDocument()->getProjections();
3124   const int nDet = rProj.nDet();
3125   const int nView = rProj.nView();
3126   if (nDet != 0 && nView != 0) {
3127     const DetectorArray& detarray = rProj.getDetectorArray(0);
3128     const DetectorValue* detval = detarray.detValues();
3129     double min = detval[0];
3130     double max = detval[0];
3131     for (int iy = 0; iy < nView; iy++) {
3132       const DetectorArray& detarray = rProj.getDetectorArray(iy);
3133       const DetectorValue* detval = detarray.detValues();
3134       for (int ix = 0; ix < nDet; ix++) {
3135         if (min > detval[ix])
3136           min = detval[ix];
3137         else if (max < detval[ix])
3138           max = detval[ix];
3139       }
3140     }
3141     
3142     unsigned char* imageData = new unsigned char [nDet * nView * 3];
3143     if (! imageData) {
3144       sys_error (ERR_SEVERE, "Unable to allocate memory for image display");
3145       return;
3146     }
3147     double scale = (max - min) / 255;
3148     for (int iy2 = 0; iy2 < nView; iy2++) {
3149       const DetectorArray& detarray = rProj.getDetectorArray (iy2);
3150       const DetectorValue* detval = detarray.detValues();
3151       for (int ix = 0; ix < nDet; ix++) {
3152         int intensity = static_cast<int>(((detval[ix] - min) / scale) + 0.5);
3153         intensity = clamp(intensity, 0, 255);
3154         int baseAddr = (iy2 * nDet + ix) * 3;
3155         imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
3156       }
3157     }
3158     wxImage image (nDet, nView, imageData, true);
3159     m_bitmap = image.ConvertToBitmap();
3160     delete imageData;
3161   }
3162   
3163     m_pCanvas->SetScrollbars(20, 20, nDet/20, nView/20);
3164     m_pCanvas->SetBackgroundColour(*wxWHITE);
3165
3166     if (m_pCanvas)
3167       m_pCanvas->Refresh();
3168 }
3169
3170 bool 
3171 ProjectionFileView::OnClose (bool deleteWindow)
3172 {
3173   //GetDocumentManager()->ActivateView (this, false, true);
3174   if (! GetDocument() || ! GetDocument()->Close())
3175     return false;
3176   
3177   Activate(false);
3178   if (m_pCanvas) {
3179         m_pCanvas->setView(NULL);
3180     m_pCanvas = NULL;
3181   }
3182   wxString s(wxTheApp->GetAppName());
3183   if (m_pFrame)
3184     m_pFrame->SetTitle(s);
3185   
3186   SetFrame(NULL);
3187   
3188   if (deleteWindow) {
3189     delete m_pFrame;
3190     m_pFrame = NULL;
3191     if (GetDocument() && GetDocument()->getBadFileOpen())
3192       ::wxYield();  // wxWindows bug workaround
3193   }
3194   
3195   return true;
3196 }
3197
3198
3199
3200 // PlotFileCanvas
3201 PlotFileCanvas::PlotFileCanvas (PlotFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
3202 : wxScrolledWindow(frame, -1, pos, size, style)
3203 {
3204   m_pView = v;
3205 }
3206
3207 wxSize
3208 PlotFileCanvas::GetBestSize() const
3209 {
3210   if (! m_pView)
3211     return wxSize(0,0);
3212   
3213   int xSize, ySize;
3214   theApp->getMainFrame()->GetClientSize (&xSize, &ySize);
3215   xSize = maxValue<int> (xSize, ySize);
3216 #ifdef CTSIM_MDI
3217   ySize = xSize = (xSize / 4);
3218 #else
3219   ySize = xSize;
3220 #endif
3221   return wxSize (xSize, ySize);
3222 }
3223
3224 PlotFileCanvas::~PlotFileCanvas ()
3225 {
3226   m_pView = NULL;
3227 }
3228
3229 void 
3230 PlotFileCanvas::OnDraw(wxDC& dc)
3231 {
3232   if (m_pView)
3233     m_pView->OnDraw(& dc);
3234 }
3235
3236
3237 // PlotFileView
3238
3239 IMPLEMENT_DYNAMIC_CLASS(PlotFileView, wxView)
3240
3241 BEGIN_EVENT_TABLE(PlotFileView, wxView)
3242 EVT_MENU(PLOTMENU_FILE_PROPERTIES, PlotFileView::OnProperties)
3243 EVT_MENU(PLOTMENU_VIEW_SCALE_MINMAX, PlotFileView::OnScaleMinMax)
3244 EVT_MENU(PLOTMENU_VIEW_SCALE_AUTO, PlotFileView::OnScaleAuto)
3245 EVT_MENU(PLOTMENU_VIEW_SCALE_FULL, PlotFileView::OnScaleFull)
3246 END_EVENT_TABLE()
3247
3248 PlotFileView::PlotFileView() 
3249 : wxView(), m_pFrame(NULL), m_pCanvas(NULL), m_pEZPlot(NULL), m_pFileMenu(0), m_bMinSpecified(false), m_bMaxSpecified(false)
3250 {
3251 }
3252
3253 PlotFileView::~PlotFileView()
3254 {
3255   if (m_pEZPlot)
3256     delete m_pEZPlot;
3257   
3258   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);  
3259 }
3260
3261 void
3262 PlotFileView::OnProperties (wxCommandEvent& event)
3263 {
3264   const PlotFile& rPlot = GetDocument()->getPlotFile();
3265   std::ostringstream os;
3266   os << "Columns: " << rPlot.getNumColumns() << ", Records: " << rPlot.getNumRecords() << "\n";
3267   rPlot.printHeadersBrief (os);
3268   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<<\n";
3269   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Plot File Properties", wxOK | wxICON_INFORMATION);
3270   dialogMsg.ShowModal();
3271   GetDocument()->Activate();
3272 }
3273
3274
3275 void 
3276 PlotFileView::OnScaleAuto (wxCommandEvent& event)
3277 {
3278   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3279   double min, max, mean, mode, median, stddev;
3280   rPlotFile.statistics (1, min, max, mean, mode, median, stddev);
3281   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
3282   int iRetVal = dialogAutoScale.ShowModal();
3283   if (iRetVal == wxID_OK) {
3284     m_bMinSpecified = true;
3285     m_bMaxSpecified = true;
3286     double dMin, dMax;
3287     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
3288       m_dMinPixel = dMin;
3289       m_dMaxPixel = dMax;
3290       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
3291       OnUpdate (this, NULL);
3292     }
3293   }
3294   GetDocument()->Activate();
3295 }
3296
3297 void 
3298 PlotFileView::OnScaleMinMax (wxCommandEvent& event)
3299 {
3300   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3301   double min;
3302   double max;
3303   
3304   if (! m_bMinSpecified || ! m_bMaxSpecified) {
3305     if (! rPlotFile.getMinMax (1, min, max)) {
3306       *theApp->getLog() << "Error: unable to find Min/Max\n";
3307       return;
3308     }
3309   }
3310   
3311   if (m_bMinSpecified)
3312     min = m_dMinPixel;
3313   if (m_bMaxSpecified)
3314     max = m_dMaxPixel;
3315   
3316   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Y-axis Minimum & Maximum", min, max);
3317   int retVal = dialogMinMax.ShowModal();
3318   if (retVal == wxID_OK) {
3319     m_bMinSpecified = true;
3320     m_bMaxSpecified = true;
3321     m_dMinPixel = dialogMinMax.getMinimum();
3322     m_dMaxPixel = dialogMinMax.getMaximum();
3323     OnUpdate (this, NULL);
3324   }
3325   GetDocument()->Activate();
3326 }
3327
3328 void 
3329 PlotFileView::OnScaleFull (wxCommandEvent& event)
3330 {
3331   if (m_bMinSpecified || m_bMaxSpecified) {
3332     m_bMinSpecified = false;
3333     m_bMaxSpecified = false;
3334     OnUpdate (this, NULL);
3335   }
3336   GetDocument()->Activate();
3337 }
3338
3339
3340 PlotFileCanvas* 
3341 PlotFileView::CreateCanvas (wxFrame* parent)
3342 {
3343   PlotFileCanvas* pCanvas;
3344   int width, height;
3345   parent->GetClientSize(&width, &height);
3346   
3347   pCanvas = new PlotFileCanvas (this, parent, wxPoint(0, 0), wxSize(width, height), 0);
3348   
3349   pCanvas->SetBackgroundColour(*wxWHITE);
3350   pCanvas->Clear();
3351   
3352   return pCanvas;
3353 }
3354
3355 #if CTSIM_MDI
3356 wxDocMDIChildFrame*
3357 #else
3358 wxDocChildFrame*
3359 #endif
3360 PlotFileView::CreateChildFrame(wxDocument *doc, wxView *view)
3361 {
3362 #ifdef CTSIM_MDI
3363   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(10, 10), wxSize(500, 300), wxDEFAULT_FRAME_STYLE);
3364 #else
3365   wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(10, 10), wxSize(500, 300), wxDEFAULT_FRAME_STYLE);
3366 #endif
3367   theApp->setIconForFrame (subframe);
3368   
3369   m_pFileMenu = new wxMenu;
3370   
3371   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3372   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3373   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3374   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3375   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3376   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3377   
3378   m_pFileMenu->AppendSeparator();
3379   m_pFileMenu->Append(PLOTMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
3380   
3381   m_pFileMenu->AppendSeparator();
3382   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3383   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3384   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3385   m_pFileMenu->AppendSeparator();
3386   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3387 #ifdef CTSIM_MDI
3388   m_pFileMenu->AppendSeparator();
3389   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3390   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3391 #endif
3392   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3393   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3394   
3395   wxMenu *view_menu = new wxMenu;
3396   view_menu->Append(PLOTMENU_VIEW_SCALE_MINMAX, "Display Scale &Set...\tCtrl-E");
3397   view_menu->Append(PLOTMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
3398   view_menu->Append(PLOTMENU_VIEW_SCALE_FULL, "Display &Full Scale\tCtrl-U");
3399   
3400   wxMenu *help_menu = new wxMenu;
3401   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3402   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3403   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3404   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3405   
3406   wxMenuBar *menu_bar = new wxMenuBar;
3407   
3408   menu_bar->Append(m_pFileMenu, "&File");
3409   menu_bar->Append(view_menu, "&View");
3410   menu_bar->Append(help_menu, "&Help");
3411   
3412   subframe->SetMenuBar(menu_bar);
3413   subframe->Centre(wxBOTH);
3414   
3415   wxAcceleratorEntry accelEntries[4];
3416   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('E'), PLOTMENU_VIEW_SCALE_MINMAX);
3417   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('A'), PLOTMENU_VIEW_SCALE_AUTO);
3418   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('U'), PLOTMENU_VIEW_SCALE_FULL);
3419   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('I'), PLOTMENU_FILE_PROPERTIES);
3420   wxAcceleratorTable accelTable (4, accelEntries);
3421   subframe->SetAcceleratorTable (accelTable);
3422   
3423   return subframe;
3424 }
3425
3426
3427 bool 
3428 PlotFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
3429 {
3430   m_pFrame = CreateChildFrame(doc, this);
3431   SetFrame(m_pFrame);
3432   
3433   m_bMinSpecified = false;
3434   m_bMaxSpecified = false;
3435   m_dAutoScaleFactor = 1.;
3436   
3437   int width, height;
3438   m_pFrame->GetClientSize(&width, &height);
3439   m_pFrame->SetTitle ("Plot File");
3440   m_pCanvas = CreateCanvas (m_pFrame);
3441   
3442   m_pFrame->Show(true);
3443   Activate(true);
3444   
3445   return true;
3446 }
3447
3448 void 
3449 PlotFileView::OnDraw (wxDC* dc)
3450 {
3451   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3452   const int iNColumns = rPlotFile.getNumColumns();
3453   const int iNRecords = rPlotFile.getNumRecords();
3454   
3455   if (iNColumns > 0 && iNRecords > 0) {
3456     int xsize, ysize;
3457     m_pCanvas->GetClientSize (&xsize, &ysize);
3458     SGPDriver driver (dc, xsize, ysize);
3459     SGP sgp (driver);
3460     if (m_pEZPlot)
3461       m_pEZPlot->plot (&sgp);
3462   }
3463 }
3464
3465
3466 void 
3467 PlotFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3468 {
3469   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3470   const int iNColumns = rPlotFile.getNumColumns();
3471   const int iNRecords = rPlotFile.getNumRecords();
3472   const bool bScatterPlot = rPlotFile.getIsScatterPlot();
3473   
3474   if (iNColumns > 0 && iNRecords > 0) {
3475     if (m_pEZPlot)
3476       delete m_pEZPlot;
3477     m_pEZPlot = new EZPlot;
3478     
3479     for (unsigned int iEzset = 0; iEzset < rPlotFile.getNumEzsetCommands(); iEzset++)
3480       m_pEZPlot->ezset (rPlotFile.getEzsetCommand (iEzset));
3481     
3482     if (m_bMinSpecified) {
3483       std::ostringstream os;
3484       os << "ymin " << m_dMinPixel;
3485       m_pEZPlot->ezset (os.str());
3486     }
3487     
3488     if (m_bMaxSpecified) {
3489       std::ostringstream os;
3490       os << "ymax " << m_dMaxPixel;
3491       m_pEZPlot->ezset (os.str());
3492     }
3493     
3494     m_pEZPlot->ezset("box");
3495     m_pEZPlot->ezset("grid");
3496     
3497     double* pdX = new double [iNRecords];
3498     double* pdY = new double [iNRecords];
3499     if (! bScatterPlot) {
3500       rPlotFile.getColumn (0, pdX);
3501       
3502       for (int iCol = 1; iCol < iNColumns; iCol++) {
3503         rPlotFile.getColumn (iCol, pdY);
3504         m_pEZPlot->addCurve (pdX, pdY, iNRecords);
3505       }
3506     } else {
3507       rPlotFile.getColumn (0, pdX);
3508       rPlotFile.getColumn (1, pdY);
3509       m_pEZPlot->addCurve (pdX, pdY, iNRecords);
3510     }
3511     delete pdX;
3512     delete pdY;
3513   }
3514   
3515   if (m_pCanvas)
3516     m_pCanvas->Refresh();
3517 }
3518
3519 bool 
3520 PlotFileView::OnClose (bool deleteWindow)
3521 {
3522   //GetDocumentManager()->ActivateView (this, false, true);
3523   if (! GetDocument() || ! GetDocument()->Close())
3524     return false;
3525   
3526   Activate(false);
3527   if (m_pCanvas) {
3528     m_pCanvas->setView (NULL);
3529     m_pCanvas = NULL;
3530   }
3531   wxString s(wxTheApp->GetAppName());
3532   if (m_pFrame)
3533     m_pFrame->SetTitle(s);
3534   
3535   SetFrame(NULL);
3536   if (deleteWindow) {
3537     delete m_pFrame;
3538     m_pFrame = NULL;
3539     if (GetDocument() && GetDocument()->getBadFileOpen())
3540       ::wxYield();  // wxWindows bug workaround
3541   }
3542   
3543   return true;
3544 }
3545
3546
3547 ////////////////////////////////////////////////////////////////
3548
3549
3550 IMPLEMENT_DYNAMIC_CLASS(TextFileView, wxView)
3551
3552 TextFileView::~TextFileView() 
3553 {
3554   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
3555   GetDocumentManager()->ActivateView(this, FALSE, TRUE);;
3556 }
3557
3558 bool TextFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
3559 {
3560   m_pFrame = CreateChildFrame(doc, this);
3561   SetFrame (m_pFrame);
3562   
3563   int width, height;
3564   m_pFrame->GetClientSize(&width, &height);
3565   m_pFrame->SetTitle("TextFile");
3566   m_pCanvas = new TextFileCanvas (this, m_pFrame, wxPoint(0, 0), wxSize(width, height), wxTE_MULTILINE | wxTE_READONLY);
3567   m_pFrame->SetTitle("Log");
3568   
3569   m_pFrame->Show (true);
3570   Activate (true);
3571   
3572   return true;
3573 }
3574
3575 // Handled by wxTextWindow
3576 void TextFileView::OnDraw(wxDC *WXUNUSED(dc) )
3577 {
3578 }
3579
3580 void TextFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3581 {
3582 }
3583
3584 bool 
3585 TextFileView::OnClose (bool deleteWindow)
3586 {
3587   if (! theApp->getMainFrame()->getShuttingDown())
3588     return false;
3589   
3590   Activate(false);
3591   //GetDocumentManager()->ActivateView (this, false, true);
3592   if (! GetDocument() || ! GetDocument()->Close())
3593     return false;
3594   
3595   SetFrame(NULL);
3596   if (deleteWindow) {
3597     delete m_pFrame;
3598     m_pFrame = NULL;
3599     if (GetDocument() && GetDocument()->getBadFileOpen())
3600       ::wxYield();  // wxWindows bug workaround
3601   }
3602   
3603   return TRUE;
3604 }
3605
3606 #if CTSIM_MDI
3607 wxDocMDIChildFrame*
3608 #else
3609 wxDocChildFrame*
3610 #endif
3611 TextFileView::CreateChildFrame (wxDocument *doc, wxView *view)
3612 {
3613 #if CTSIM_MDI
3614   wxDocMDIChildFrame* subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(0,0), wxDEFAULT_FRAME_STYLE, "Log");
3615 #else
3616   wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(300, 150), wxDEFAULT_FRAME_STYLE, "Log");
3617 #endif
3618   theApp->setIconForFrame (subframe);
3619   
3620   m_pFileMenu = new wxMenu;
3621   
3622   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3623   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3624   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3625   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3626   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3627   //  m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3628   
3629   m_pFileMenu->AppendSeparator();
3630   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3631   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3632   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3633   m_pFileMenu->AppendSeparator();
3634   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3635 #ifdef CTSIM_MDI
3636   m_pFileMenu->AppendSeparator();
3637   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3638   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3639 #endif
3640   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3641   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3642   
3643   wxMenu *help_menu = new wxMenu;
3644   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3645   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3646   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3647   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3648   
3649   wxMenuBar *menu_bar = new wxMenuBar;
3650   
3651   menu_bar->Append(m_pFileMenu, "&File");
3652   menu_bar->Append(help_menu, "&Help");
3653   
3654   subframe->SetMenuBar(menu_bar);
3655   subframe->Centre(wxBOTH);
3656   
3657   return subframe;
3658 }
3659
3660
3661 // Define a constructor for my text subwindow
3662 TextFileCanvas::TextFileCanvas (TextFileView* v, wxFrame* frame, const wxPoint& pos, const wxSize& size, long style)
3663 : wxTextCtrl (frame, -1, "", pos, size, style), m_pView(v)
3664 {
3665 }
3666
3667 TextFileCanvas::~TextFileCanvas ()
3668 {
3669   m_pView = NULL;
3670 }
3671
3672 wxSize
3673 TextFileCanvas::GetBestSize() const
3674 {
3675   int xSize, ySize;
3676   theApp->getMainFrame()->GetClientSize (&xSize, &ySize);
3677   xSize = maxValue<int> (xSize, ySize);
3678 #ifdef CTSIM_MDI
3679   ySize = xSize = (xSize / 4);
3680 #else
3681   ySize = xSize;
3682 #endif
3683   return wxSize (xSize, ySize);
3684 }