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