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