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