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