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