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