7ae2293fc27f2fd062c4953e048c188717f3ff7d
[ctsim.git] / src / views.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          view.cpp
5 **   Purpose:       View & Canvas routines for CTSim program
6 **   Programmer:    Kevin Rosenberg
7 **   Date Started:  July 2000
8 **
9 **  This is part of the CTSim program
10 **  Copyright (c) 1983-2001 Kevin Rosenberg
11 **
12 **  $Id: views.cpp,v 1.147 2001/09/27 02:11:29 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);
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     wxProgressDialog dlgProgress (wxString("Rasterize"), wxString("Rasterization Progress"), 
2229       pImageFile->nx() + 1, getFrameForChild(), wxPD_CAN_ABORT );
2230     Timer timer;
2231     for (unsigned int i = 0; i < pImageFile->nx(); i++) {
2232       rPhantom.convertToImagefile (*pImageFile, m_dDefaultRasterViewRatio, m_iDefaultRasterNSamples, Trace::TRACE_NONE, i, 1, true);
2233       if (! dlgProgress.Update (i+1)) {
2234         delete pImageFile;
2235         return;
2236       }
2237     }
2238     
2239     ImageFileDocument* pRasterDoc = theApp->newImageDoc();
2240     if (! pRasterDoc) {
2241       sys_error (ERR_SEVERE, "Unable to create image file");
2242       return;
2243     }
2244     pRasterDoc->setImageFile (pImageFile);
2245     if (theApp->getAskDeleteNewDocs())
2246       pRasterDoc->Modify (true);
2247     pRasterDoc->UpdateAllViews (this);
2248     pRasterDoc->getView()->getFrame()->Show(true);
2249     *theApp->getLog() << os.str().c_str() << "\n";
2250     pImageFile->labelAdd (os.str().c_str(), timer.timerEnd());
2251     ImageFileView* rasterView = pRasterDoc->getView();
2252     if (rasterView) {
2253       rasterView->getFrame()->SetFocus();
2254       rasterView->OnUpdate (rasterView, NULL);
2255     }
2256     pRasterDoc->Activate();
2257   }
2258 }
2259
2260
2261 PhantomCanvas* 
2262 PhantomFileView::CreateCanvas (wxFrame *parent)
2263 {
2264   PhantomCanvas* pCanvas;
2265   
2266   pCanvas = new PhantomCanvas (this, parent, wxPoint(0, 0), wxSize(0,0), 0);
2267   pCanvas->SetBackgroundColour(*wxWHITE);
2268   pCanvas->Clear();
2269   
2270   return pCanvas;
2271 }
2272
2273 #if CTSIM_MDI
2274 wxDocMDIChildFrame*
2275 #else
2276 wxDocChildFrame*
2277 #endif
2278 PhantomFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2279 {
2280 #if CTSIM_MDI
2281   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2282 #else
2283   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2284 #endif
2285   theApp->setIconForFrame (subframe);
2286   
2287   m_pFileMenu = new wxMenu;
2288   
2289   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
2290   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
2291   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
2292   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
2293   m_pFileMenu->Append(wxID_CLOSE, "&Close");
2294   
2295   m_pFileMenu->AppendSeparator();
2296   m_pFileMenu->Append(PHMMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
2297   
2298   m_pFileMenu->AppendSeparator();
2299   m_pFileMenu->Append(wxID_PRINT, "&Print...");
2300   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
2301   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
2302   m_pFileMenu->AppendSeparator();
2303   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
2304 #ifdef CTSIM_MDI
2305   m_pFileMenu->AppendSeparator();
2306   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
2307   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
2308 #endif
2309   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
2310   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
2311   
2312   wxMenu *process_menu = new wxMenu;
2313   process_menu->Append(PHMMENU_PROCESS_RASTERIZE, "&Rasterize...\tCtrl-R");
2314   process_menu->Append(PHMMENU_PROCESS_PROJECTIONS, "&Projections...\tCtrl-J");
2315   
2316   wxMenu *help_menu = new wxMenu;
2317   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
2318   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
2319   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
2320   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
2321   
2322   wxMenuBar *menu_bar = new wxMenuBar;
2323   
2324   menu_bar->Append(m_pFileMenu, "&File");
2325   menu_bar->Append(process_menu, "&Process");
2326   menu_bar->Append(help_menu, "&Help");
2327   
2328   subframe->SetMenuBar(menu_bar);
2329   subframe->Centre(wxBOTH);
2330   
2331   wxAcceleratorEntry accelEntries[3];
2332   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('J'), PHMMENU_PROCESS_PROJECTIONS);
2333   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('R'), PHMMENU_PROCESS_RASTERIZE);
2334   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('I'), PHMMENU_FILE_PROPERTIES);
2335   wxAcceleratorTable accelTable (3, accelEntries);
2336   subframe->SetAcceleratorTable (accelTable);
2337   
2338   return subframe;
2339 }
2340
2341
2342 bool 
2343 PhantomFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
2344 {
2345   m_pFrame = CreateChildFrame(doc, this);
2346   SetFrame(m_pFrame);
2347   m_pCanvas = CreateCanvas (m_pFrame);
2348   m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
2349   m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
2350   
2351   m_pFrame->SetTitle ("PhantomFileView");
2352   
2353 #ifdef __X__
2354   int x, y;  // X requires a forced resize
2355   m_pFrame->GetSize(&x, &y);
2356   m_pFrame->SetSize(-1, -1, x, y);
2357 #endif
2358   
2359   m_pFrame->Show(true);
2360   Activate(true);
2361   
2362   return true;
2363 }
2364
2365 void 
2366 PhantomFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2367 {
2368   if (m_pCanvas)
2369     m_pCanvas->Refresh();
2370 }
2371
2372 bool 
2373 PhantomFileView::OnClose (bool deleteWindow)
2374 {
2375   //GetDocumentManager()->ActivateView (this, false, true);
2376   if (! GetDocument() || ! GetDocument()->Close())
2377     return false;
2378   
2379   Activate(false);
2380   if (m_pCanvas) {
2381     m_pCanvas->setView(NULL);
2382     m_pCanvas = NULL;
2383   }
2384   wxString s(wxTheApp->GetAppName());
2385   if (m_pFrame)
2386     m_pFrame->SetTitle(s);
2387   
2388   SetFrame(NULL);
2389   
2390   if (deleteWindow) {
2391     delete m_pFrame;
2392     m_pFrame = NULL;
2393     if (GetDocument() && GetDocument()->getBadFileOpen())
2394       ::wxYield();  // wxWindows bug workaround
2395   }
2396   
2397   return true;
2398 }
2399
2400 void
2401 PhantomFileView::OnDraw (wxDC* dc)
2402 {
2403   int xsize, ysize;
2404   m_pCanvas->GetClientSize (&xsize, &ysize);
2405   SGPDriver driver (dc, xsize, ysize);
2406   SGP sgp (driver);
2407   const Phantom& rPhantom = GetDocument()->getPhantom();
2408   sgp.setColor (C_RED);
2409   rPhantom.show (sgp);
2410 }
2411
2412 // ProjectionCanvas
2413
2414 ProjectionFileCanvas::ProjectionFileCanvas (ProjectionFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
2415 : wxScrolledWindow(frame, -1, pos, size, style)
2416 {
2417   m_pView = v;
2418 }
2419
2420 ProjectionFileCanvas::~ProjectionFileCanvas ()
2421 {
2422   m_pView = NULL;
2423 }
2424
2425 void 
2426 ProjectionFileCanvas::OnDraw(wxDC& dc)
2427 {
2428   if (m_pView)
2429     m_pView->OnDraw(& dc);
2430 }
2431
2432 wxSize
2433 ProjectionFileCanvas::GetBestSize () const
2434 {
2435   wxSize best (0, 0);
2436   if (m_pView) {
2437     Projections& rProj = m_pView->GetDocument()->getProjections();
2438     best.Set (rProj.nDet(), rProj.nView());
2439   }
2440   
2441   return best;
2442 }
2443
2444
2445 // ProjectionFileView
2446
2447 IMPLEMENT_DYNAMIC_CLASS(ProjectionFileView, wxView)
2448
2449 BEGIN_EVENT_TABLE(ProjectionFileView, wxView)
2450 EVT_MENU(PJMENU_FILE_PROPERTIES, ProjectionFileView::OnProperties)
2451 EVT_MENU(PJMENU_RECONSTRUCT_FBP, ProjectionFileView::OnReconstructFBP)
2452 EVT_MENU(PJMENU_RECONSTRUCT_FBP_REBIN, ProjectionFileView::OnReconstructFBPRebin)
2453 EVT_MENU(PJMENU_RECONSTRUCT_FOURIER, ProjectionFileView::OnReconstructFourier)
2454 EVT_MENU(PJMENU_CONVERT_RECTANGULAR, ProjectionFileView::OnConvertRectangular)
2455 EVT_MENU(PJMENU_CONVERT_POLAR, ProjectionFileView::OnConvertPolar)
2456 EVT_MENU(PJMENU_CONVERT_FFT_POLAR, ProjectionFileView::OnConvertFFTPolar)
2457 EVT_MENU(PJMENU_CONVERT_PARALLEL, ProjectionFileView::OnConvertParallel)
2458 EVT_MENU(PJMENU_PLOT_TTHETA_SAMPLING, ProjectionFileView::OnPlotTThetaSampling)
2459 EVT_MENU(PJMENU_PLOT_HISTOGRAM, ProjectionFileView::OnPlotHistogram)
2460 EVT_MENU(PJMENU_ARTIFACT_REDUCTION, ProjectionFileView::OnArtifactReduction)
2461 END_EVENT_TABLE()
2462
2463
2464 ProjectionFileView::ProjectionFileView() 
2465 : wxView(), m_pFrame(0), m_pCanvas(0), m_pFileMenu(0)
2466 {
2467 #ifdef DEBUG
2468   m_iDefaultNX = 115;
2469   m_iDefaultNY = 115;
2470 #else
2471   m_iDefaultNX = 256;
2472   m_iDefaultNY = 256;
2473 #endif
2474   
2475   m_iDefaultFilter = SignalFilter::FILTER_ABS_BANDLIMIT;
2476   m_dDefaultFilterParam = 1.;
2477 #if HAVE_FFTW
2478   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_RFFTW;
2479   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_INVERSE_FOURIER;
2480 #else
2481   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_CONVOLUTION;
2482   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT;
2483 #endif
2484   m_iDefaultZeropad = 1;
2485   m_iDefaultBackprojector = Backprojector::BPROJ_IDIFF;
2486   m_iDefaultInterpolation = Backprojector::INTERP_LINEAR;
2487   m_iDefaultInterpParam = 1;
2488   m_iDefaultTrace = Trace::TRACE_NONE;
2489   
2490   m_iDefaultPolarNX = 256;
2491   m_iDefaultPolarNY = 256;
2492   m_iDefaultPolarInterpolation = Projections::POLAR_INTERP_BILINEAR;
2493   m_iDefaultPolarZeropad = 1;
2494 }
2495
2496 ProjectionFileView::~ProjectionFileView()
2497 {
2498   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
2499   GetDocumentManager()->ActivateView(this, FALSE, TRUE);;
2500 }
2501
2502 void
2503 ProjectionFileView::OnProperties (wxCommandEvent& event)
2504 {
2505   const Projections& rProj = GetDocument()->getProjections();
2506   std::ostringstream os;
2507   rProj.printScanInfo(os);
2508   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
2509   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Projection File Properties", wxOK | wxICON_INFORMATION);
2510   dialogMsg.ShowModal();
2511   GetDocument()->Activate();
2512 }
2513
2514
2515 void
2516 ProjectionFileView::OnConvertRectangular (wxCommandEvent& event)
2517 {
2518   Projections& rProj = GetDocument()->getProjections();
2519   
2520   int nDet = rProj.nDet();
2521   int nView = rProj.nView();
2522   ImageFile* pIF = new ImageFile (nDet, nView);
2523   ImageFileArray v = pIF->getArray();
2524   for (int iv = 0; iv < nView; iv++) {
2525     DetectorValue* detval = rProj.getDetectorArray(iv).detValues();
2526     
2527     for (int id = 0; id < nDet; id++)
2528       v[id][iv] = detval[id];
2529   }
2530   
2531   ImageFileDocument* pRectDoc = theApp->newImageDoc ();
2532   if (! pRectDoc) {
2533     sys_error (ERR_SEVERE, "Unable to create image file");
2534     return;
2535   }
2536   pRectDoc->setImageFile (pIF);
2537   pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2538   std::ostringstream os;
2539   os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to rectangular image";
2540   *theApp->getLog() << os.str().c_str() << "\n";
2541   pIF->labelAdd (os.str().c_str());
2542   if (theApp->getAskDeleteNewDocs())
2543     pRectDoc->Modify (true);
2544   pRectDoc->getView()->getFrame()->Show(true);
2545   pRectDoc->UpdateAllViews ();
2546   pRectDoc->Activate();
2547 }
2548
2549 void
2550 ProjectionFileView::OnConvertPolar (wxCommandEvent& event)
2551 {
2552   Projections& rProj = GetDocument()->getProjections();
2553   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2554     m_iDefaultPolarInterpolation, -1, IDH_DLG_POLAR);
2555   if (dialogPolar.ShowModal() == wxID_OK) {
2556     wxProgressDialog dlgProgress (wxString("Convert Polar"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2557     wxString strInterpolation (dialogPolar.getInterpolationName());
2558     m_iDefaultPolarNX = dialogPolar.getXSize();
2559     m_iDefaultPolarNY = dialogPolar.getYSize();
2560     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2561     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2562     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2563     
2564     if (! rProj.convertPolar (*pIF, m_iDefaultPolarInterpolation)) {
2565       delete pIF;
2566       *theApp->getLog() << "Error converting to Polar\n";
2567       return;
2568     }
2569     
2570     pPolarDoc = theApp->newImageDoc ();
2571     if (! pPolarDoc) {
2572       sys_error (ERR_SEVERE, "Unable to create image file");
2573       return;
2574     }
2575     pPolarDoc->setImageFile (pIF);
2576     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2577     std::ostringstream os;
2578     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to polar image: xSize=" 
2579       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2580       << strInterpolation.c_str();
2581     *theApp->getLog() << os.str().c_str() << "\n";
2582     pIF->labelAdd (os.str().c_str());
2583     if (theApp->getAskDeleteNewDocs())
2584       pPolarDoc->Modify (true);
2585     pPolarDoc->getView()->getFrame()->Show(true);
2586     pPolarDoc->UpdateAllViews ();
2587     pPolarDoc->Activate();
2588   }
2589 }
2590
2591 void
2592 ProjectionFileView::OnConvertFFTPolar (wxCommandEvent& event)
2593 {
2594   Projections& rProj = GetDocument()->getProjections();
2595   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert to FFT Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2596     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad, IDH_DLG_FFT_POLAR);
2597   if (dialogPolar.ShowModal() == wxID_OK) {
2598     wxProgressDialog dlgProgress (wxString("Convert FFT Polar"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2599     wxString strInterpolation (dialogPolar.getInterpolationName());
2600     m_iDefaultPolarNX = dialogPolar.getXSize();
2601     m_iDefaultPolarNY = dialogPolar.getYSize();
2602     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2603     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2604     
2605     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2606     if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
2607       delete pIF;
2608       *theApp->getLog() << "Error converting to polar\n";
2609       return;
2610     }
2611     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2612     if (! pPolarDoc) {
2613       sys_error (ERR_SEVERE, "Unable to create image file");
2614       return;
2615     }
2616     pPolarDoc->setImageFile (pIF);
2617     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2618     std::ostringstream os;
2619     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to FFT polar image: xSize=" 
2620       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2621       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2622     *theApp->getLog() << os.str().c_str() << "\n";
2623     pIF->labelAdd (os.str().c_str());
2624     if (theApp->getAskDeleteNewDocs())
2625       pPolarDoc->Modify (true);
2626     pPolarDoc->getView()->getFrame()->Show(true);
2627     pPolarDoc->UpdateAllViews ();
2628     pPolarDoc->Activate();
2629   }
2630 }
2631
2632 void
2633 ProjectionFileView::OnPlotTThetaSampling (wxCommandEvent& event)
2634 {
2635   DialogGetThetaRange dlgTheta (this->getFrame(), ParallelRaysums::THETA_RANGE_UNCONSTRAINED);
2636   if (dlgTheta.ShowModal() != wxID_OK)
2637     return;
2638   
2639   int iThetaRange = dlgTheta.getThetaRange();
2640   
2641   Projections& rProj = GetDocument()->getProjections();
2642   ParallelRaysums parallel (&rProj, iThetaRange);
2643   PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
2644   PlotFile& rPlot = pPlotDoc->getPlotFile();
2645   ParallelRaysums::CoordinateContainer& coordContainer = parallel.getCoordinates();
2646   double* pdT = new double [parallel.getNumCoordinates()];
2647   double* pdTheta = new double [parallel.getNumCoordinates()];
2648   
2649   for (int i = 0; i < parallel.getNumCoordinates(); i++) {
2650     pdT[i] = coordContainer[i]->m_dT;
2651     pdTheta[i] = coordContainer[i]->m_dTheta;
2652   }
2653   rPlot.setCurveSize (2, parallel.getNumCoordinates(), true);
2654   rPlot.addEzsetCommand ("title T-Theta Sampling");
2655   rPlot.addEzsetCommand ("xlabel T");
2656   rPlot.addEzsetCommand ("ylabel Theta");
2657   rPlot.addEzsetCommand ("curve 1");
2658   if (rProj.nDet() < 50 && rProj.nView() < 50)
2659     rPlot.addEzsetCommand ("symbol 1"); // x symbol
2660   else
2661     rPlot.addEzsetCommand ("symbol 6"); // point symbol
2662   rPlot.addEzsetCommand ("noline");
2663   rPlot.addColumn (0, pdT);
2664   rPlot.addColumn (1, pdTheta);
2665   delete pdT;
2666   delete pdTheta;
2667   if (theApp->getAskDeleteNewDocs())
2668     pPlotDoc->Modify (true);
2669   pPlotDoc->getView()->getFrame()->Show(true);
2670   pPlotDoc->UpdateAllViews ();
2671   pPlotDoc->Activate();
2672 }
2673
2674
2675 void
2676 ProjectionFileView::OnPlotHistogram (wxCommandEvent& event)
2677
2678   Projections& rProj = GetDocument()->getProjections();
2679   int nDet = rProj.nDet();
2680   int nView = rProj.nView();
2681   
2682   if (nDet < 1 || nView < 1)
2683     return;
2684
2685   PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
2686   if (! pPlotDoc) {
2687     sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
2688     return;
2689   }
2690     
2691   DetectorValue* pdDetval = rProj.getDetectorArray(0).detValues();
2692   double dMin = pdDetval[0], dMax = pdDetval[0];
2693
2694   for (int iv = 0; iv < nView; iv++) {
2695     pdDetval = rProj.getDetectorArray(iv).detValues();
2696     for (int id = 0; id < nDet; id++) {
2697       double dV = pdDetval[id];
2698       if (dV < dMin)
2699         dMin = dV;
2700       else if (dV > dMax)
2701         dMax = dV;
2702     }
2703   }
2704
2705   double* pX = new double [NUMBER_HISTOGRAM_BINS];
2706   double* pY = new double [NUMBER_HISTOGRAM_BINS];
2707   double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
2708     
2709   for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
2710     pX[i] = dMin + (i + 0.5) * dBinWidth;
2711     pY[i] = 0;
2712   }
2713   for (int j = 0; j < nView; j++) {
2714     pdDetval = rProj.getDetectorArray(j).detValues();
2715     for (int id = 0; id < nDet; id++) {
2716       int iBin = nearest<int> ((pdDetval[id] - dMin) / dBinWidth);
2717       if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
2718         pY[iBin] += 1;
2719     }
2720   }      
2721   PlotFile& rPlotFile = pPlotDoc->getPlotFile();
2722   std::ostringstream os;
2723   os << "Histogram";
2724   std::string title("title ");
2725   title += os.str();
2726   rPlotFile.addEzsetCommand (title.c_str());
2727   rPlotFile.addEzsetCommand ("xlabel Detector Value");
2728   rPlotFile.addEzsetCommand ("ylabel Count");
2729   rPlotFile.addEzsetCommand ("box");
2730   rPlotFile.addEzsetCommand ("grid");
2731   rPlotFile.setCurveSize (2, NUMBER_HISTOGRAM_BINS);
2732   rPlotFile.addColumn (0, pX);
2733   rPlotFile.addColumn (1, pY);
2734   rPlotFile.addDescription (rProj.remark());
2735   os << " plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
2736   *theApp->getLog() << os.str().c_str() << "\n";
2737   rPlotFile.addDescription (os.str().c_str());
2738   delete pX;
2739   delete pY;
2740   if (theApp->getAskDeleteNewDocs())
2741     pPlotDoc->Modify (true);
2742   pPlotDoc->getView()->getFrame()->Show(true);
2743   pPlotDoc->UpdateAllViews ();
2744   pPlotDoc->Activate();
2745 }
2746
2747
2748 void
2749 ProjectionFileView::OnConvertParallel (wxCommandEvent& event)
2750 {
2751   Projections& rProj = GetDocument()->getProjections();
2752   if (rProj.geometry() == Scanner::GEOMETRY_PARALLEL) {
2753     wxMessageBox ("Projections are already parallel", "Error");
2754     return;
2755   }
2756   wxProgressDialog dlgProgress (wxString("Convert to Parallel"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2757   Projections* pProjNew = rProj.interpolateToParallel();
2758   ProjectionFileDocument* pProjDocNew = theApp->newProjectionDoc();
2759   pProjDocNew->setProjections (pProjNew);  
2760   
2761   if (ProjectionFileView* projView = pProjDocNew->getView()) {
2762     projView->OnUpdate (projView, NULL);
2763     if (projView->getCanvas())
2764       projView->getCanvas()->SetClientSize (pProjNew->nDet(), pProjNew->nView());
2765     if (wxFrame* pFrame = projView->getFrame()) {
2766       pFrame->Show(true);
2767       pFrame->SetFocus();
2768       pFrame->Raise();
2769     }
2770     GetDocumentManager()->ActivateView (projView, true, false);
2771   }
2772   if (theApp->getAskDeleteNewDocs())
2773     pProjDocNew-> Modify(true);
2774   pProjDocNew->UpdateAllViews (this);
2775   pProjDocNew->Activate();
2776 }
2777
2778 void
2779 ProjectionFileView::OnReconstructFourier (wxCommandEvent& event)
2780 {
2781   Projections& rProj = GetDocument()->getProjections();
2782   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Fourier Reconstruction", m_iDefaultPolarNX, m_iDefaultPolarNY,
2783     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad, IDH_DLG_RECON_FOURIER);
2784   if (dialogPolar.ShowModal() == wxID_OK) {
2785     wxProgressDialog dlgProgress (wxString("Reconstruction Fourier"), wxString("Reconstruction Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2786     wxString strInterpolation (dialogPolar.getInterpolationName());
2787     m_iDefaultPolarNX = dialogPolar.getXSize();
2788     m_iDefaultPolarNY = dialogPolar.getYSize();
2789     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2790     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2791     
2792     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2793     if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
2794       delete pIF;
2795       *theApp->getLog() << "Error converting to polar\n";
2796       return;
2797     }
2798 #ifdef HAVE_FFT
2799     pIF->ifft(*pIF);
2800 #endif
2801     pIF->magnitude(*pIF);
2802     Fourier::shuffleFourierToNaturalOrder (*pIF);
2803
2804     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2805     if (! pPolarDoc) {
2806       sys_error (ERR_SEVERE, "Unable to create image file");
2807       return;
2808     }
2809     pPolarDoc->setImageFile (pIF);
2810     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2811     std::ostringstream os;
2812     os << "Reconstruct Fourier " << GetFrame()->GetTitle().c_str() << ": xSize=" 
2813       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2814       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2815     *theApp->getLog() << os.str().c_str() << "\n";
2816     pIF->labelAdd (os.str().c_str());
2817     if (theApp->getAskDeleteNewDocs())
2818       pPolarDoc->Modify (true);
2819     pPolarDoc->getView()->getFrame()->Show(true);
2820     pPolarDoc->UpdateAllViews ();
2821     pPolarDoc->Activate();
2822   }
2823 }
2824
2825 void
2826 ProjectionFileView::OnReconstructFBPRebin (wxCommandEvent& event)
2827 {
2828   Projections& rProj = GetDocument()->getProjections();
2829   doReconstructFBP (rProj, true);
2830 }
2831
2832 void
2833 ProjectionFileView::OnReconstructFBP (wxCommandEvent& event)
2834 {
2835   Projections& rProj = GetDocument()->getProjections();
2836   doReconstructFBP (rProj, false);
2837 }
2838
2839 void
2840 ProjectionFileView::doReconstructFBP (const Projections& rProj, bool bRebinToParallel)
2841 {
2842   ReconstructionROI defaultROI;
2843   defaultROI.m_dXMin = -rProj.phmLen() / 2;
2844   defaultROI.m_dXMax = defaultROI.m_dXMin + rProj.phmLen();
2845   defaultROI.m_dYMin = -rProj.phmLen() / 2;
2846   defaultROI.m_dYMax = defaultROI.m_dYMin + rProj.phmLen();
2847   
2848   DialogGetReconstructionParameters dialogReconstruction (getFrameForChild(), m_iDefaultNX, m_iDefaultNY, 
2849     m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration, 
2850     m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector, 
2851     m_iDefaultTrace,  &defaultROI);
2852   
2853   int retVal = dialogReconstruction.ShowModal();
2854   if (retVal != wxID_OK)
2855     return;
2856   
2857   m_iDefaultNX = dialogReconstruction.getXSize();
2858   m_iDefaultNY = dialogReconstruction.getYSize();
2859   wxString optFilterName = dialogReconstruction.getFilterName();
2860   m_iDefaultFilter = SignalFilter::convertFilterNameToID (optFilterName.c_str());
2861   m_dDefaultFilterParam = dialogReconstruction.getFilterParam();
2862   wxString optFilterMethodName = dialogReconstruction.getFilterMethodName();
2863   m_iDefaultFilterMethod = ProcessSignal::convertFilterMethodNameToID(optFilterMethodName.c_str());
2864   m_iDefaultZeropad = dialogReconstruction.getZeropad();
2865   wxString optFilterGenerationName = dialogReconstruction.getFilterGenerationName();
2866   m_iDefaultFilterGeneration = ProcessSignal::convertFilterGenerationNameToID (optFilterGenerationName.c_str());
2867   wxString optInterpName = dialogReconstruction.getInterpName();
2868   m_iDefaultInterpolation = Backprojector::convertInterpNameToID (optInterpName.c_str());
2869   m_iDefaultInterpParam = dialogReconstruction.getInterpParam();
2870   wxString optBackprojectName = dialogReconstruction.getBackprojectName();
2871   m_iDefaultBackprojector = Backprojector::convertBackprojectNameToID (optBackprojectName.c_str());
2872   m_iDefaultTrace = dialogReconstruction.getTrace();
2873   dialogReconstruction.getROI (&defaultROI);
2874   
2875   if (m_iDefaultNX <= 0 && m_iDefaultNY <= 0) 
2876     return;
2877   
2878   std::ostringstream os;
2879   os << "Reconstruct " << rProj.getFilename() << ": xSize=" << m_iDefaultNX << ", ySize=" << m_iDefaultNY << ", Filter=" << optFilterName.c_str() << ", FilterParam=" << m_dDefaultFilterParam << ", FilterMethod=" << optFilterMethodName.c_str() << ", FilterGeneration=" << optFilterGenerationName.c_str() << ", Zeropad=" << m_iDefaultZeropad << ", Interpolation=" << optInterpName.c_str() << ", InterpolationParam=" << m_iDefaultInterpParam << ", Backprojection=" << optBackprojectName.c_str();
2880   if (bRebinToParallel)
2881     os << "; Interpolate to Parallel";
2882   
2883   Timer timerRecon;
2884   ImageFile* pImageFile = NULL;
2885   if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
2886     pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
2887     Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(), 
2888       m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), 
2889       optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, 
2890       &defaultROI, bRebinToParallel);
2891     
2892     ReconstructDialog* pDlgReconstruct = new ReconstructDialog (*pReconstructor, rProj, *pImageFile, m_iDefaultTrace, getFrameForChild());
2893     for (int iView = 0; iView < rProj.nView(); iView++) {
2894       ::wxYield();
2895       if (pDlgReconstruct->isCancelled() || ! pDlgReconstruct->reconstructView (iView, true)) {
2896         delete pDlgReconstruct;
2897         delete pReconstructor;
2898         return;
2899       }
2900       ::wxYield();
2901       ::wxYield();
2902       while (pDlgReconstruct->isPaused()) {
2903         ::wxYield();
2904         ::wxUsleep(50);
2905       }
2906     }
2907     pReconstructor->postProcessing();
2908     delete pDlgReconstruct;
2909     delete pReconstructor;
2910   } else {
2911 #if HAVE_WXTHREADS
2912     if (theApp->getUseBackgroundTasks()) {
2913       ReconstructorSupervisorThread* pReconstructor = new ReconstructorSupervisorThread (this, m_iDefaultNX, 
2914         m_iDefaultNY, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(), 
2915         m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam, 
2916         optBackprojectName.c_str(), os.str().c_str(), &defaultROI, bRebinToParallel);
2917       if (pReconstructor->Create() != wxTHREAD_NO_ERROR) {
2918         sys_error (ERR_SEVERE, "Error creating reconstructor thread");
2919         delete pReconstructor;
2920         return;
2921       }
2922       pReconstructor->SetPriority (60);
2923       pReconstructor->Run();
2924       return;
2925     } else 
2926 #endif
2927     {
2928       pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
2929       wxProgressDialog dlgProgress (wxString("Reconstruction"), wxString("Reconstruction Progress"), rProj.nView() + 1, getFrameForChild(), wxPD_CAN_ABORT );
2930       Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(), 
2931         m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), 
2932         optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, 
2933         &defaultROI, bRebinToParallel);
2934       
2935       for (int iView = 0; iView < rProj.nView(); iView++) {
2936         pReconstructor->reconstructView (iView, 1);
2937         if (! dlgProgress.Update (iView + 1)) {
2938           delete pReconstructor;
2939           return; // don't make new window, thread will do this
2940         }
2941       }
2942       pReconstructor->postProcessing();
2943       delete pReconstructor;
2944     }
2945   }
2946   ImageFileDocument* pReconDoc = theApp->newImageDoc();
2947   if (! pReconDoc) {
2948     sys_error (ERR_SEVERE, "Unable to create image file");
2949     return;
2950   }
2951   pReconDoc->setImageFile (pImageFile);
2952   if (theApp->getAskDeleteNewDocs())
2953     pReconDoc->Modify (true);
2954   pReconDoc->UpdateAllViews (this);
2955   pReconDoc->Activate();
2956   if (ImageFileView* rasterView = pReconDoc->getView()) {
2957     rasterView->OnUpdate (rasterView, NULL);
2958     rasterView->getFrame()->SetFocus();
2959     rasterView->getFrame()->Show(true);
2960   }
2961   *theApp->getLog() << os.str().c_str() << "\n";
2962   pImageFile->labelAdd (rProj.getLabel());
2963   pImageFile->labelAdd (os.str().c_str(), timerRecon.timerEnd());    
2964 }
2965
2966
2967 void
2968 ProjectionFileView::OnArtifactReduction (wxCommandEvent& event)
2969 {
2970 }
2971
2972
2973 ProjectionFileCanvas* 
2974 ProjectionFileView::CreateCanvas (wxFrame *parent)
2975 {
2976   ProjectionFileCanvas* pCanvas;
2977   int width, height;
2978   parent->GetClientSize(&width, &height);
2979   
2980   pCanvas = new ProjectionFileCanvas (this, parent, wxPoint(0, 0), wxSize(width, height), 0);
2981   
2982   pCanvas->SetScrollbars(20, 20, 50, 50);
2983   pCanvas->SetBackgroundColour(*wxWHITE);
2984   pCanvas->Clear();
2985   
2986   return pCanvas;
2987 }
2988
2989 #if CTSIM_MDI
2990 wxDocMDIChildFrame*
2991 #else
2992 wxDocChildFrame*
2993 #endif
2994 ProjectionFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2995 {
2996 #ifdef CTSIM_MDI
2997   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
2998 #else
2999   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
3000 #endif
3001   theApp->setIconForFrame (subframe);
3002   
3003   m_pFileMenu = new wxMenu;
3004   
3005   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3006   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3007   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3008   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3009   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3010   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3011   
3012   m_pFileMenu->AppendSeparator();
3013   m_pFileMenu->Append(PJMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
3014   
3015   m_pFileMenu->AppendSeparator();
3016   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3017   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3018   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3019   m_pFileMenu->AppendSeparator();
3020   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3021 #ifdef CTSIM_MDI
3022   m_pFileMenu->AppendSeparator();
3023   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3024   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3025 #endif
3026   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3027   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3028   
3029   wxMenu *convert_menu = new wxMenu;
3030   convert_menu->Append (PJMENU_CONVERT_RECTANGULAR, "&Rectangular Image");
3031   convert_menu->Append (PJMENU_CONVERT_POLAR, "&Polar Image...\tCtrl-L");
3032   convert_menu->Append (PJMENU_CONVERT_FFT_POLAR, "FF&T->Polar Image...\tCtrl-T");
3033   convert_menu->AppendSeparator();
3034   convert_menu->Append (PJMENU_CONVERT_PARALLEL, "&Interpolate to Parallel");
3035   
3036   wxMenu* filter_menu = new wxMenu;
3037   filter_menu->Append (PJMENU_ARTIFACT_REDUCTION, "&Artifact Reduction");
3038   
3039   wxMenu* analyze_menu = new wxMenu;
3040   analyze_menu->Append (PJMENU_PLOT_HISTOGRAM, "&Plot Histogram");
3041   analyze_menu->Append (PJMENU_PLOT_TTHETA_SAMPLING, "Plot T-T&heta Sampling...\tCtrl-H");
3042
3043   wxMenu *reconstruct_menu = new wxMenu;
3044   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP, "&Filtered Backprojection...\tCtrl-R", "Reconstruct image using filtered backprojection");
3045   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP_REBIN, "Filtered &Backprojection (Rebin to Parallel)...\tCtrl-B", "Reconstruct image using filtered backprojection");
3046   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FOURIER, "&Fourier...\tCtrl-E", "Reconstruct image using inverse Fourier");
3047   
3048   wxMenu *help_menu = new wxMenu;
3049   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3050   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3051   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3052   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3053   
3054   wxMenuBar *menu_bar = new wxMenuBar;
3055   
3056   menu_bar->Append (m_pFileMenu, "&File");
3057   menu_bar->Append (convert_menu, "&Convert");
3058   menu_bar->Append (filter_menu, "Fi&lter");
3059   menu_bar->Append (analyze_menu, "&Analyze");
3060   menu_bar->Append (reconstruct_menu, "&Reconstruct");
3061   menu_bar->Append (help_menu, "&Help");
3062   
3063   subframe->SetMenuBar(menu_bar);  
3064   subframe->Centre(wxBOTH);
3065   
3066   wxAcceleratorEntry accelEntries[7];
3067   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('L'), PJMENU_CONVERT_POLAR);
3068   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('T'), PJMENU_CONVERT_FFT_POLAR);
3069   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('R'), PJMENU_RECONSTRUCT_FBP);
3070   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('B'), PJMENU_RECONSTRUCT_FBP_REBIN);
3071   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('E'), PJMENU_RECONSTRUCT_FOURIER);
3072   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('I'), PJMENU_FILE_PROPERTIES);
3073   accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('H'), PJMENU_PLOT_TTHETA_SAMPLING);
3074   wxAcceleratorTable accelTable (7, accelEntries);
3075   subframe->SetAcceleratorTable (accelTable);
3076   
3077   return subframe;
3078 }
3079
3080
3081 bool 
3082 ProjectionFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
3083 {
3084   m_pFrame = CreateChildFrame(doc, this);
3085   SetFrame(m_pFrame);
3086   
3087   int width, height;
3088   m_pFrame->GetClientSize (&width, &height);
3089   m_pFrame->SetTitle ("ProjectionFileView");
3090   m_pCanvas = CreateCanvas (m_pFrame);
3091   
3092 #ifdef __X__
3093   int x, y;  // X requires a forced resize
3094   m_pFrame->GetSize(&x, &y);
3095   m_pFrame->SetSize(-1, -1, x, y);
3096 #endif
3097   
3098   m_pFrame->Show(true);
3099   Activate(true);
3100   
3101   return true;
3102 }
3103
3104 void 
3105 ProjectionFileView::OnDraw (wxDC* dc)
3106 {
3107   wxSize clientSize = m_pFrame->GetClientSize();
3108   wxSize bestSize = m_pCanvas->GetBestSize();
3109   
3110   if (clientSize.x > bestSize.x || clientSize.y > bestSize.y)
3111     m_pFrame->SetClientSize (bestSize);
3112   
3113   if (m_bitmap.Ok())
3114     dc->DrawBitmap (m_bitmap, 0, 0, false);
3115 }
3116
3117
3118 void 
3119 ProjectionFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3120 {
3121   const Projections& rProj = GetDocument()->getProjections();
3122   const int nDet = rProj.nDet();
3123   const int nView = rProj.nView();
3124   if (nDet != 0 && nView != 0) {
3125     const DetectorArray& detarray = rProj.getDetectorArray(0);
3126     const DetectorValue* detval = detarray.detValues();
3127     double min = detval[0];
3128     double max = detval[0];
3129     for (int iy = 0; iy < nView; iy++) {
3130       const DetectorArray& detarray = rProj.getDetectorArray(iy);
3131       const DetectorValue* detval = detarray.detValues();
3132       for (int ix = 0; ix < nDet; ix++) {
3133         if (min > detval[ix])
3134           min = detval[ix];
3135         else if (max < detval[ix])
3136           max = detval[ix];
3137       }
3138     }
3139     
3140     unsigned char* imageData = new unsigned char [nDet * nView * 3];
3141     if (! imageData) {
3142       sys_error (ERR_SEVERE, "Unable to allocate memory for image display");
3143       return;
3144     }
3145     double scale = (max - min) / 255;
3146     for (int iy2 = 0; iy2 < nView; iy2++) {
3147       const DetectorArray& detarray = rProj.getDetectorArray (iy2);
3148       const DetectorValue* detval = detarray.detValues();
3149       for (int ix = 0; ix < nDet; ix++) {
3150         int intensity = static_cast<int>(((detval[ix] - min) / scale) + 0.5);
3151         intensity = clamp(intensity, 0, 255);
3152         int baseAddr = (iy2 * nDet + ix) * 3;
3153         imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
3154       }
3155     }
3156     wxImage image (nDet, nView, imageData, true);
3157     m_bitmap = image.ConvertToBitmap();
3158     delete imageData;
3159     int xSize = nDet;
3160     int ySize = nView;
3161     xSize = clamp (xSize, 0, 800);
3162     ySize = clamp (ySize, 0, 800);
3163     m_pFrame->SetClientSize (xSize, ySize);
3164     m_pCanvas->SetScrollbars (20, 20, nDet/20, nView/20);
3165   }
3166   
3167   if (m_pCanvas)
3168     m_pCanvas->Refresh();
3169 }
3170
3171 bool 
3172 ProjectionFileView::OnClose (bool deleteWindow)
3173 {
3174   //GetDocumentManager()->ActivateView (this, false, true);
3175   if (! GetDocument() || ! GetDocument()->Close())
3176     return false;
3177   
3178   Activate(false);
3179   if (m_pCanvas) {
3180         m_pCanvas->setView(NULL);
3181     m_pCanvas = NULL;
3182   }
3183   wxString s(wxTheApp->GetAppName());
3184   if (m_pFrame)
3185     m_pFrame->SetTitle(s);
3186   
3187   SetFrame(NULL);
3188   
3189   if (deleteWindow) {
3190     delete m_pFrame;
3191     m_pFrame = NULL;
3192     if (GetDocument() && GetDocument()->getBadFileOpen())
3193       ::wxYield();  // wxWindows bug workaround
3194   }
3195   
3196   return true;
3197 }
3198
3199
3200
3201 // PlotFileCanvas
3202 PlotFileCanvas::PlotFileCanvas (PlotFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
3203 : wxScrolledWindow(frame, -1, pos, size, style)
3204 {
3205   m_pView = v;
3206 }
3207
3208 PlotFileCanvas::~PlotFileCanvas ()
3209 {
3210   m_pView = NULL;
3211 }
3212
3213 void 
3214 PlotFileCanvas::OnDraw(wxDC& dc)
3215 {
3216   if (m_pView)
3217     m_pView->OnDraw(& dc);
3218 }
3219
3220
3221 // PlotFileView
3222
3223 IMPLEMENT_DYNAMIC_CLASS(PlotFileView, wxView)
3224
3225 BEGIN_EVENT_TABLE(PlotFileView, wxView)
3226 EVT_MENU(PLOTMENU_FILE_PROPERTIES, PlotFileView::OnProperties)
3227 EVT_MENU(PLOTMENU_VIEW_SCALE_MINMAX, PlotFileView::OnScaleMinMax)
3228 EVT_MENU(PLOTMENU_VIEW_SCALE_AUTO, PlotFileView::OnScaleAuto)
3229 EVT_MENU(PLOTMENU_VIEW_SCALE_FULL, PlotFileView::OnScaleFull)
3230 END_EVENT_TABLE()
3231
3232 PlotFileView::PlotFileView() 
3233 : wxView(), m_pFrame(NULL), m_pCanvas(NULL), m_pEZPlot(NULL), m_pFileMenu(0), m_bMinSpecified(false), m_bMaxSpecified(false)
3234 {
3235 }
3236
3237 PlotFileView::~PlotFileView()
3238 {
3239   if (m_pEZPlot)
3240     delete m_pEZPlot;
3241   
3242   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);  
3243 }
3244
3245 void
3246 PlotFileView::OnProperties (wxCommandEvent& event)
3247 {
3248   const PlotFile& rPlot = GetDocument()->getPlotFile();
3249   std::ostringstream os;
3250   os << "Columns: " << rPlot.getNumColumns() << ", Records: " << rPlot.getNumRecords() << "\n";
3251   rPlot.printHeadersBrief (os);
3252   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<<\n";
3253   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Plot File Properties", wxOK | wxICON_INFORMATION);
3254   dialogMsg.ShowModal();
3255   GetDocument()->Activate();
3256 }
3257
3258
3259 void 
3260 PlotFileView::OnScaleAuto (wxCommandEvent& event)
3261 {
3262   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3263   double min, max, mean, mode, median, stddev;
3264   rPlotFile.statistics (1, min, max, mean, mode, median, stddev);
3265   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
3266   int iRetVal = dialogAutoScale.ShowModal();
3267   if (iRetVal == wxID_OK) {
3268     m_bMinSpecified = true;
3269     m_bMaxSpecified = true;
3270     double dMin, dMax;
3271     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
3272       m_dMinPixel = dMin;
3273       m_dMaxPixel = dMax;
3274       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
3275       OnUpdate (this, NULL);
3276     }
3277   }
3278   GetDocument()->Activate();
3279 }
3280
3281 void 
3282 PlotFileView::OnScaleMinMax (wxCommandEvent& event)
3283 {
3284   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3285   double min;
3286   double max;
3287   
3288   if (! m_bMinSpecified || ! m_bMaxSpecified) {
3289     if (! rPlotFile.getMinMax (1, min, max)) {
3290       *theApp->getLog() << "Error: unable to find Min/Max\n";
3291       return;
3292     }
3293   }
3294   
3295   if (m_bMinSpecified)
3296     min = m_dMinPixel;
3297   if (m_bMaxSpecified)
3298     max = m_dMaxPixel;
3299   
3300   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Y-axis Minimum & Maximum", min, max);
3301   int retVal = dialogMinMax.ShowModal();
3302   if (retVal == wxID_OK) {
3303     m_bMinSpecified = true;
3304     m_bMaxSpecified = true;
3305     m_dMinPixel = dialogMinMax.getMinimum();
3306     m_dMaxPixel = dialogMinMax.getMaximum();
3307     OnUpdate (this, NULL);
3308   }
3309   GetDocument()->Activate();
3310 }
3311
3312 void 
3313 PlotFileView::OnScaleFull (wxCommandEvent& event)
3314 {
3315   if (m_bMinSpecified || m_bMaxSpecified) {
3316     m_bMinSpecified = false;
3317     m_bMaxSpecified = false;
3318     OnUpdate (this, NULL);
3319   }
3320   GetDocument()->Activate();
3321 }
3322
3323
3324 PlotFileCanvas* 
3325 PlotFileView::CreateCanvas (wxFrame* parent)
3326 {
3327   PlotFileCanvas* pCanvas;
3328   int width, height;
3329   parent->GetClientSize(&width, &height);
3330   
3331   pCanvas = new PlotFileCanvas (this, parent, wxPoint(0, 0), wxSize(width, height), 0);
3332   
3333   pCanvas->SetBackgroundColour(*wxWHITE);
3334   pCanvas->Clear();
3335   
3336   return pCanvas;
3337 }
3338
3339 #if CTSIM_MDI
3340 wxDocMDIChildFrame*
3341 #else
3342 wxDocChildFrame*
3343 #endif
3344 PlotFileView::CreateChildFrame(wxDocument *doc, wxView *view)
3345 {
3346 #ifdef CTSIM_MDI
3347   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(10, 10), wxSize(500, 300), wxDEFAULT_FRAME_STYLE);
3348 #else
3349   wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(10, 10), wxSize(500, 300), wxDEFAULT_FRAME_STYLE);
3350 #endif
3351   theApp->setIconForFrame (subframe);
3352   
3353   m_pFileMenu = new wxMenu;
3354   
3355   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3356   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3357   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3358   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3359   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3360   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3361   
3362   m_pFileMenu->AppendSeparator();
3363   m_pFileMenu->Append(PLOTMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
3364   
3365   m_pFileMenu->AppendSeparator();
3366   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3367   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3368   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3369   m_pFileMenu->AppendSeparator();
3370   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3371 #ifdef CTSIM_MDI
3372   m_pFileMenu->AppendSeparator();
3373   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3374   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3375 #endif
3376   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3377   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3378   
3379   wxMenu *view_menu = new wxMenu;
3380   view_menu->Append(PLOTMENU_VIEW_SCALE_MINMAX, "Display Scale &Set...\tCtrl-E");
3381   view_menu->Append(PLOTMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
3382   view_menu->Append(PLOTMENU_VIEW_SCALE_FULL, "Display &Full Scale\tCtrl-U");
3383   
3384   wxMenu *help_menu = new wxMenu;
3385   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3386   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3387   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3388   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3389   
3390   wxMenuBar *menu_bar = new wxMenuBar;
3391   
3392   menu_bar->Append(m_pFileMenu, "&File");
3393   menu_bar->Append(view_menu, "&View");
3394   menu_bar->Append(help_menu, "&Help");
3395   
3396   subframe->SetMenuBar(menu_bar);
3397   subframe->Centre(wxBOTH);
3398   
3399   wxAcceleratorEntry accelEntries[4];
3400   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('E'), PLOTMENU_VIEW_SCALE_MINMAX);
3401   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('A'), PLOTMENU_VIEW_SCALE_AUTO);
3402   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('U'), PLOTMENU_VIEW_SCALE_FULL);
3403   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('I'), PLOTMENU_FILE_PROPERTIES);
3404   wxAcceleratorTable accelTable (4, accelEntries);
3405   subframe->SetAcceleratorTable (accelTable);
3406   
3407   return subframe;
3408 }
3409
3410
3411 bool 
3412 PlotFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
3413 {
3414   m_pFrame = CreateChildFrame(doc, this);
3415   SetFrame(m_pFrame);
3416   
3417   m_bMinSpecified = false;
3418   m_bMaxSpecified = false;
3419   m_dAutoScaleFactor = 1.;
3420   
3421   int width, height;
3422   m_pFrame->GetClientSize(&width, &height);
3423   m_pFrame->SetTitle ("Plot File");
3424   m_pCanvas = CreateCanvas (m_pFrame);
3425   
3426 #ifdef __X__
3427   int x, y;  // X requires a forced resize
3428   m_pFrame->GetSize(&x, &y);
3429   m_pFrame->SetSize(-1, -1, x, y);
3430 #endif
3431   
3432   m_pFrame->Show(true);
3433   Activate(true);
3434   
3435   return true;
3436 }
3437
3438 void 
3439 PlotFileView::OnDraw (wxDC* dc)
3440 {
3441   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3442   const int iNColumns = rPlotFile.getNumColumns();
3443   const int iNRecords = rPlotFile.getNumRecords();
3444   
3445   if (iNColumns > 0 && iNRecords > 0) {
3446     int xsize, ysize;
3447     m_pCanvas->GetClientSize (&xsize, &ysize);
3448     SGPDriver driver (dc, xsize, ysize);
3449     SGP sgp (driver);
3450     if (m_pEZPlot)
3451       m_pEZPlot->plot (&sgp);
3452   }
3453 }
3454
3455
3456 void 
3457 PlotFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3458 {
3459   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3460   const int iNColumns = rPlotFile.getNumColumns();
3461   const int iNRecords = rPlotFile.getNumRecords();
3462   const bool bScatterPlot = rPlotFile.getIsScatterPlot();
3463   
3464   if (iNColumns > 0 && iNRecords > 0) {
3465     if (m_pEZPlot)
3466       delete m_pEZPlot;
3467     m_pEZPlot = new EZPlot;
3468     
3469     for (unsigned int iEzset = 0; iEzset < rPlotFile.getNumEzsetCommands(); iEzset++)
3470       m_pEZPlot->ezset (rPlotFile.getEzsetCommand (iEzset));
3471     
3472     if (m_bMinSpecified) {
3473       std::ostringstream os;
3474       os << "ymin " << m_dMinPixel;
3475       m_pEZPlot->ezset (os.str());
3476     }
3477     
3478     if (m_bMaxSpecified) {
3479       std::ostringstream os;
3480       os << "ymax " << m_dMaxPixel;
3481       m_pEZPlot->ezset (os.str());
3482     }
3483     
3484     m_pEZPlot->ezset("box");
3485     m_pEZPlot->ezset("grid");
3486     
3487     double* pdX = new double [iNRecords];
3488     double* pdY = new double [iNRecords];
3489     if (! bScatterPlot) {
3490       rPlotFile.getColumn (0, pdX);
3491       
3492       for (int iCol = 1; iCol < iNColumns; iCol++) {
3493         rPlotFile.getColumn (iCol, pdY);
3494         m_pEZPlot->addCurve (pdX, pdY, iNRecords);
3495       }
3496     } else {
3497       rPlotFile.getColumn (0, pdX);
3498       rPlotFile.getColumn (1, pdY);
3499       m_pEZPlot->addCurve (pdX, pdY, iNRecords);
3500     }
3501     delete pdX;
3502     delete pdY;
3503   }
3504   
3505   if (m_pCanvas)
3506     m_pCanvas->Refresh();
3507 }
3508
3509 bool 
3510 PlotFileView::OnClose (bool deleteWindow)
3511 {
3512   //GetDocumentManager()->ActivateView (this, false, true);
3513   if (! GetDocument() || ! GetDocument()->Close())
3514     return false;
3515   
3516   Activate(false);
3517   if (m_pCanvas) {
3518     m_pCanvas->setView (NULL);
3519     m_pCanvas = NULL;
3520   }
3521   wxString s(wxTheApp->GetAppName());
3522   if (m_pFrame)
3523     m_pFrame->SetTitle(s);
3524   
3525   SetFrame(NULL);
3526   if (deleteWindow) {
3527     delete m_pFrame;
3528     m_pFrame = NULL;
3529     if (GetDocument() && GetDocument()->getBadFileOpen())
3530       ::wxYield();  // wxWindows bug workaround
3531   }
3532   
3533   return true;
3534 }
3535
3536
3537 ////////////////////////////////////////////////////////////////
3538
3539
3540 IMPLEMENT_DYNAMIC_CLASS(TextFileView, wxView)
3541
3542 TextFileView::~TextFileView() 
3543 {
3544   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
3545   GetDocumentManager()->ActivateView(this, FALSE, TRUE);;
3546 }
3547
3548 bool TextFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
3549 {
3550   m_pFrame = CreateChildFrame(doc, this);
3551   SetFrame (m_pFrame);
3552   
3553   int width, height;
3554   m_pFrame->GetClientSize(&width, &height);
3555   m_pFrame->SetTitle("TextFile");
3556   m_pCanvas = new TextFileCanvas (this, m_pFrame, wxPoint(0, 0), wxSize(width, height), wxTE_MULTILINE | wxTE_READONLY);
3557   m_pFrame->SetTitle("Log");
3558   
3559 #ifdef __X__
3560   // X seems to require a forced resize
3561   int x, y;
3562   frame->GetSize(&x, &y);
3563   frame->SetSize(-1, -1, x, y);
3564 #endif
3565   
3566   m_pFrame->Show (true);
3567   Activate (true);
3568   
3569   return true;
3570 }
3571
3572 // Handled by wxTextWindow
3573 void TextFileView::OnDraw(wxDC *WXUNUSED(dc) )
3574 {
3575 }
3576
3577 void TextFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3578 {
3579 }
3580
3581 bool 
3582 TextFileView::OnClose (bool deleteWindow)
3583 {
3584   if (! theApp->getMainFrame()->getShuttingDown())
3585     return false;
3586   
3587   Activate(false);
3588   //GetDocumentManager()->ActivateView (this, false, true);
3589   if (! GetDocument() || ! GetDocument()->Close())
3590     return false;
3591   
3592   SetFrame(NULL);
3593   if (deleteWindow) {
3594     delete m_pFrame;
3595     m_pFrame = NULL;
3596     if (GetDocument() && GetDocument()->getBadFileOpen())
3597       ::wxYield();  // wxWindows bug workaround
3598   }
3599   
3600   return TRUE;
3601 }
3602
3603 #if CTSIM_MDI
3604 wxDocMDIChildFrame*
3605 #else
3606 wxDocChildFrame*
3607 #endif
3608 TextFileView::CreateChildFrame (wxDocument *doc, wxView *view)
3609 {
3610 #if CTSIM_MDI
3611   wxDocMDIChildFrame* subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(0,0), wxDEFAULT_FRAME_STYLE, "Log");
3612 #else
3613   wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(300, 150), wxDEFAULT_FRAME_STYLE, "Log");
3614 #endif
3615   theApp->setIconForFrame (subframe);
3616   
3617   m_pFileMenu = new wxMenu;
3618   
3619   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3620   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3621   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3622   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3623   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3624   //  m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3625   
3626   m_pFileMenu->AppendSeparator();
3627   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3628   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3629   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3630   m_pFileMenu->AppendSeparator();
3631   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3632 #ifdef CTSIM_MDI
3633   m_pFileMenu->AppendSeparator();
3634   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3635   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3636 #endif
3637   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3638   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3639   
3640   wxMenu *help_menu = new wxMenu;
3641   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3642   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3643   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3644   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3645   
3646   wxMenuBar *menu_bar = new wxMenuBar;
3647   
3648   menu_bar->Append(m_pFileMenu, "&File");
3649   menu_bar->Append(help_menu, "&Help");
3650   
3651   subframe->SetMenuBar(menu_bar);
3652   subframe->Centre(wxBOTH);
3653   
3654   return subframe;
3655 }
3656
3657
3658 // Define a constructor for my text subwindow
3659 TextFileCanvas::TextFileCanvas (TextFileView* v, wxFrame* frame, const wxPoint& pos, const wxSize& size, long style)
3660 : wxTextCtrl (frame, -1, "", pos, size, style), m_pView(v)
3661 {
3662 }
3663
3664 TextFileCanvas::~TextFileCanvas ()
3665 {
3666   m_pView = NULL;
3667 }