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