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