r3874: Auto commit for Debian build
[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.165 2003/01/29 04:34:06 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 #include "wx/wxprec.h"
29 #ifndef WX_PRECOMP
30 #include "wx/wx.h"
31 #endif
32
33 #if !wxUSE_DOC_VIEW_ARCHITECTURE
34 #error You must set wxUSE_DOC_VIEW_ARCHITECTURE to 1 in setup.h!
35 #endif
36
37 #include "wx/image.h"
38 #include "wx/progdlg.h"
39 #include "wx/clipbrd.h"
40
41 #include "ct.h"
42 #include "ctsim.h"
43 #include "docs.h"
44 #include "views.h"
45 #include "dialogs.h"
46 #include "dlgprojections.h"
47 #include "dlgreconstruct.h"
48 #include "backprojectors.h"
49 #include "reconstruct.h"
50 #include "timer.h"
51 #include "threadproj.h"
52 #include "threadrecon.h"
53 #include "threadraster.h"
54
55 #if defined(MSVC) || HAVE_SSTREAM
56 #include <sstream>
57 #else
58 #include <sstream_subst>
59 #endif
60
61 // Used to reduce calls to progress bar update function
62 const short int ITER_PER_UPDATE = 10;
63
64 // ImageFileCanvas
65
66 BEGIN_EVENT_TABLE(ImageFileCanvas, wxScrolledWindow)
67 EVT_MOUSE_EVENTS(ImageFileCanvas::OnMouseEvent)
68 EVT_CHAR(ImageFileCanvas::OnChar)
69 END_EVENT_TABLE()
70
71
72 ImageFileCanvas::ImageFileCanvas (ImageFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
73 : wxScrolledWindow(frame, -1, pos, size, style), m_pView(v), m_xCursor(-1), m_yCursor(-1)
74 {
75 }
76
77 ImageFileCanvas::~ImageFileCanvas()
78 {}
79
80 void 
81 ImageFileCanvas::OnDraw(wxDC& dc)
82 {
83   if (m_pView)
84     m_pView->OnDraw(& dc);
85 }
86
87 void 
88 ImageFileCanvas::DrawRubberBandCursor (wxDC& dc, int x, int y)
89 {
90   const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
91   int nx = rIF.nx();
92   int ny = rIF.ny();
93   
94   int yPt = ny - y - 1;
95   dc.SetLogicalFunction (wxINVERT);
96   dc.SetPen (*wxGREEN_PEN);
97   dc.DrawLine (0, yPt, nx, yPt);
98   dc.DrawLine (x, 0, x, ny);
99   dc.SetLogicalFunction (wxCOPY);
100 }
101
102 bool
103 ImageFileCanvas::GetCurrentCursor (int& x, int& y)
104 {
105   x = m_xCursor;
106   y = m_yCursor;
107   
108   if (m_xCursor >= 0 && m_yCursor >= 0)
109     return true;
110   else
111     return false;
112 }
113
114 void 
115 ImageFileCanvas::OnMouseEvent(wxMouseEvent& event)
116 {
117   if (! m_pView)
118     return;
119   
120   
121   wxClientDC dc(this);
122   PrepareDC(dc);
123   
124   wxPoint pt(event.GetLogicalPosition(dc));
125   
126   const ImageFileDocument* pIFDoc = m_pView->GetDocument();
127   if (! pIFDoc)
128     return;
129   const ImageFile& rIF = pIFDoc->getImageFile();
130   ImageFileArrayConst v = rIF.getArray();
131   int nx = rIF.nx();
132   int ny = rIF.ny();
133   const int yPt = ny - 1 - pt.y;
134   if (event.RightIsDown()) {
135     if (pt.x >= 0 && pt.x < nx && pt.y >= 0 && pt.y < ny) {
136       std::ostringstream os;
137       os << "Image value (" << pt.x << "," << yPt << ") = " << v[pt.x][yPt];
138       if (rIF.isComplex()) {
139         double dImag = rIF.getImaginaryArray()[pt.x][yPt];
140         if (dImag < 0)
141           os << " - " << -dImag;
142         else
143           os << " + " << dImag;
144         os << "i\n";
145       } else
146         os << "\n";
147       *theApp->getLog() << os.str().c_str();
148     } else
149       *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << yPt << ")\n";
150   }
151   else if (event.LeftIsDown() || event.LeftUp() || event.RightUp()) {
152     if (pt.x >= 0 && pt.x < nx && pt.y >= 0 && pt.y < ny) {
153       if (m_xCursor >= 0 && m_yCursor >= 0) {
154         DrawRubberBandCursor (dc, m_xCursor, m_yCursor);
155       }
156       DrawRubberBandCursor (dc, pt.x, yPt);
157       m_xCursor = pt.x;
158       m_yCursor = yPt;
159       wxMenu* pMenu = m_pView->getMenuAnalyze();
160       if (pMenu && ! pMenu->IsEnabled(IFMENU_PLOT_ROW)) {
161         pMenu->Enable (IFMENU_PLOT_ROW, true);
162         pMenu->Enable (IFMENU_PLOT_COL, true);
163         pMenu->Enable (IFMENU_COMPARE_ROW, true);
164         pMenu->Enable (IFMENU_COMPARE_COL, true);
165         pMenu->Enable (IFMENU_PLOT_FFT_ROW, true);
166         pMenu->Enable (IFMENU_PLOT_FFT_COL, true);
167       }
168     } else
169       *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << yPt << ")\n";
170   }
171   if (event.LeftUp()) {
172     std::ostringstream os;
173     os << "Selected column " << pt.x << " , row " << yPt << "\n";
174     *theApp->getLog() << os.str().c_str();
175   }
176 }
177
178 void
179 ImageFileCanvas::OnChar (wxKeyEvent& event)
180 {
181   if (event.GetKeyCode() == WXK_ESCAPE) {
182     m_xCursor = -1;
183     m_yCursor = -1;
184     if (m_pView)
185       m_pView->OnUpdate (NULL);
186   } else
187     event.Skip();
188 }
189
190 wxSize
191 ImageFileCanvas::GetBestSize() const
192 {
193   const int iMinX = 50;
194   const int iMinY = 20;
195   wxSize bestSize (iMinX,iMinY);
196
197   if (m_pView) {
198     const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
199     bestSize.Set  (rIF.nx(), rIF.ny());
200   }
201
202   if (bestSize.x > 800)
203     bestSize.x = 800;
204   if (bestSize.y > 800)
205     bestSize.y = 800;
206   
207   if (bestSize.y < iMinY)
208     bestSize.y = iMinY;
209   if (bestSize.x < iMinX)
210     bestSize.x = iMinX;
211   
212   return bestSize;
213 }
214
215
216 // ImageFileView
217
218 IMPLEMENT_DYNAMIC_CLASS(ImageFileView, wxView)
219
220 BEGIN_EVENT_TABLE(ImageFileView, wxView)
221 EVT_MENU(IFMENU_FILE_EXPORT, ImageFileView::OnExport)
222 EVT_MENU(IFMENU_FILE_PROPERTIES, ImageFileView::OnProperties)
223 EVT_MENU(IFMENU_EDIT_COPY, ImageFileView::OnEditCopy)
224 EVT_MENU(IFMENU_EDIT_CUT, ImageFileView::OnEditCut)
225 EVT_MENU(IFMENU_EDIT_PASTE, ImageFileView::OnEditPaste)
226 EVT_MENU(IFMENU_VIEW_SCALE_MINMAX, ImageFileView::OnScaleMinMax)
227 EVT_MENU(IFMENU_VIEW_SCALE_AUTO, ImageFileView::OnScaleAuto)
228 EVT_MENU(IFMENU_VIEW_SCALE_FULL, ImageFileView::OnScaleFull)
229 EVT_MENU(IFMENU_COMPARE_IMAGES, ImageFileView::OnCompare)
230 EVT_MENU(IFMENU_COMPARE_ROW, ImageFileView::OnCompareRow)
231 EVT_MENU(IFMENU_COMPARE_COL, ImageFileView::OnCompareCol)
232 EVT_MENU(IFMENU_FILTER_INVERTVALUES, ImageFileView::OnInvertValues)
233 EVT_MENU(IFMENU_FILTER_SQUARE, ImageFileView::OnSquare)
234 EVT_MENU(IFMENU_FILTER_SQRT, ImageFileView::OnSquareRoot)
235 EVT_MENU(IFMENU_FILTER_LOG, ImageFileView::OnLog)
236 EVT_MENU(IFMENU_FILTER_EXP, ImageFileView::OnExp)
237 EVT_MENU(IFMENU_FILTER_FOURIER, ImageFileView::OnFourier)
238 EVT_MENU(IFMENU_FILTER_INVERSE_FOURIER, ImageFileView::OnInverseFourier)
239 EVT_MENU(IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER, ImageFileView::OnShuffleFourierToNaturalOrder)
240 EVT_MENU(IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER, ImageFileView::OnShuffleNaturalToFourierOrder)
241 EVT_MENU(IFMENU_IMAGE_ADD, ImageFileView::OnAdd)
242 EVT_MENU(IFMENU_IMAGE_SUBTRACT, ImageFileView::OnSubtract)
243 EVT_MENU(IFMENU_IMAGE_MULTIPLY, ImageFileView::OnMultiply)
244 EVT_MENU(IFMENU_IMAGE_DIVIDE, ImageFileView::OnDivide)
245 EVT_MENU(IFMENU_IMAGE_SCALESIZE, ImageFileView::OnScaleSize)
246 #if wxUSE_GLCANVAS
247 EVT_MENU(IFMENU_IMAGE_CONVERT3D, ImageFileView::OnConvert3d)
248 #endif
249 #ifdef HAVE_FFT
250 EVT_MENU(IFMENU_FILTER_FFT, ImageFileView::OnFFT)
251 EVT_MENU(IFMENU_FILTER_IFFT, ImageFileView::OnIFFT)
252 EVT_MENU(IFMENU_FILTER_FFT_ROWS, ImageFileView::OnFFTRows)
253 EVT_MENU(IFMENU_FILTER_IFFT_ROWS, ImageFileView::OnIFFTRows)
254 EVT_MENU(IFMENU_FILTER_FFT_COLS, ImageFileView::OnFFTCols)
255 EVT_MENU(IFMENU_FILTER_IFFT_COLS, ImageFileView::OnIFFTCols)
256 #endif
257 EVT_MENU(IFMENU_FILTER_MAGNITUDE, ImageFileView::OnMagnitude)
258 EVT_MENU(IFMENU_FILTER_PHASE, ImageFileView::OnPhase)
259 EVT_MENU(IFMENU_FILTER_REAL, ImageFileView::OnReal)
260 EVT_MENU(IFMENU_FILTER_IMAGINARY, ImageFileView::OnImaginary)
261 EVT_MENU(IFMENU_PLOT_ROW, ImageFileView::OnPlotRow)
262 EVT_MENU(IFMENU_PLOT_COL, ImageFileView::OnPlotCol)
263 #ifdef HAVE_FFT
264 EVT_MENU(IFMENU_PLOT_FFT_ROW, ImageFileView::OnPlotFFTRow)
265 EVT_MENU(IFMENU_PLOT_FFT_COL, ImageFileView::OnPlotFFTCol)
266 #endif
267 EVT_MENU(IFMENU_PLOT_HISTOGRAM, ImageFileView::OnPlotHistogram)
268 END_EVENT_TABLE()
269
270 ImageFileView::ImageFileView() 
271   :  wxView(), m_pBitmap(0), m_pFrame(0), m_pCanvas(0), m_pFileMenu(0),
272      m_pFilterMenu(0), m_bMinSpecified(false), m_bMaxSpecified(false),
273      m_iDefaultExportFormatID(ImageFile::EXPORT_FORMAT_PNG)
274 {}
275
276 ImageFileView::~ImageFileView()
277 {
278   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
279   GetDocumentManager()->ActivateView(this, FALSE, TRUE);
280 }
281
282
283 void
284 ImageFileView::OnProperties (wxCommandEvent& event)
285 {
286   const ImageFile& rIF = GetDocument()->getImageFile();
287   if (rIF.nx() == 0 || rIF.ny() == 0)
288     *theApp->getLog() << "Properties: empty imagefile\n";
289   else {
290     const std::string rFilename = m_pFrame->GetTitle().c_str();
291     std::ostringstream os;
292     double min, max, mean, mode, median, stddev;
293     rIF.statistics (rIF.getArray(), min, max, mean, mode, median, stddev);
294     os << "Filename: " << rFilename << "\n";
295     os << "Size: (" << rIF.nx() << "," << rIF.ny() << ")\n";
296     os << "Data type: ";
297     if (rIF.isComplex())
298       os << "Complex\n";
299     else
300       os << "Real\n";
301     os << "Minimum: "<<min<<"\nMaximum: "<<max<<"\nMean: "<<mean<<"\nMedian: "<<median<<"\nMode: "<<mode<<"\nStandard Deviation: "<<stddev << "\n";
302     if (rIF.isComplex()) {
303       rIF.statistics (rIF.getImaginaryArray(), min, max, mean, mode, median, stddev);
304       os << "Imaginary: min: "<<min<<"\nmax: "<<max<<"\nmean: "<<mean<<"\nmedian: "<<median<<"\nmode: "<<mode<<"\nstddev: "<<stddev << "\n";
305     }
306     if (rIF.nLabels() > 0) {
307       rIF.printLabelsBrief (os);
308     }
309     *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
310     wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Imagefile Properties", wxOK | wxICON_INFORMATION);
311     dialogMsg.ShowModal();
312   }
313   GetDocument()->Activate();
314 }
315
316 void 
317 ImageFileView::OnScaleAuto (wxCommandEvent& event)
318 {
319   const ImageFile& rIF = GetDocument()->getImageFile();
320   double min, max, mean, mode, median, stddev;
321   rIF.statistics(min, max, mean, mode, median, stddev);
322   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
323   int iRetVal = dialogAutoScale.ShowModal();
324   if (iRetVal == wxID_OK) {
325     m_bMinSpecified = true;
326     m_bMaxSpecified = true;
327     double dMin, dMax;
328     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
329       m_dMinPixel = dMin;
330       m_dMaxPixel = dMax;
331       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
332       GetDocument()->UpdateAllViews (this);
333     }
334   }
335   GetDocument()->Activate();
336 }
337
338 void 
339 ImageFileView::OnScaleMinMax (wxCommandEvent& event)
340 {
341   const ImageFile& rIF = GetDocument()->getImageFile();
342   double min, max;
343   if (! m_bMinSpecified && ! m_bMaxSpecified)
344     rIF.getMinMax (min, max);
345   
346   if (m_bMinSpecified)
347     min = m_dMinPixel;
348   if (m_bMaxSpecified)
349     max = m_dMaxPixel;
350   
351   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Image Minimum & Maximum", min, max);
352   int retVal = dialogMinMax.ShowModal();
353   if (retVal == wxID_OK) {
354     m_bMinSpecified = true;
355     m_bMaxSpecified = true;
356     m_dMinPixel = dialogMinMax.getMinimum();
357     m_dMaxPixel = dialogMinMax.getMaximum();
358     GetDocument()->UpdateAllViews (this);
359   }
360   GetDocument()->Activate();
361 }
362
363 void 
364 ImageFileView::OnScaleFull (wxCommandEvent& event)
365 {
366   if (m_bMinSpecified || m_bMaxSpecified) {
367     m_bMinSpecified = false;
368     m_bMaxSpecified = false;
369     GetDocument()->UpdateAllViews (this);
370   }
371   GetDocument()->Activate();
372 }
373
374 void
375 ImageFileView::OnCompare (wxCommandEvent& event)
376 {
377   std::vector<ImageFileDocument*> vecIF;
378   theApp->getCompatibleImages (GetDocument(), vecIF);
379   
380   if (vecIF.size() == 0) {
381     wxMessageBox("There are no compatible image files open for comparision", "No comparison images");
382   } else {
383     DialogGetComparisonImage dialogGetCompare(getFrameForChild(), "Get Comparison Image", vecIF, true);
384     
385     if (dialogGetCompare.ShowModal() == wxID_OK) {
386       const ImageFile& rIF = GetDocument()->getImageFile();
387       ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
388       const ImageFile& rCompareIF = pCompareDoc->getImageFile();
389       std::ostringstream os;
390       double min, max, mean, mode, median, stddev;
391       rIF.statistics (min, max, mean, mode, median, stddev);
392       os << GetFrame()->GetTitle().c_str() << ": minimum=" << min << ", maximum=" << max << ", mean=" << mean << ", mode=" << mode << ", median=" << median << ", stddev=" << stddev << "\n";
393       rCompareIF.statistics (min, max, mean, mode, median, stddev);
394       os << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": minimum=" << min << ", maximum=" << max << ", mean=" << mean << ", mode=" << mode << ", median=" << median << ", stddev=" << stddev << "\n";
395       double d, r, e;
396       rIF.comparativeStatistics (rCompareIF, d, r, e);
397       os << "Comparative Statistics: d=" << d << ", r=" << r << ", e=" << e << "\n";
398       *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
399       if (dialogGetCompare.getMakeDifferenceImage()) {
400         ImageFile* pDifferenceImage = new ImageFile;
401         
402         pDifferenceImage->setArraySize (rIF.nx(), rIF.ny());
403         if (! rIF.subtractImages (rCompareIF, *pDifferenceImage)) {
404           *theApp->getLog() << "Unable to subtract images\n";
405           delete pDifferenceImage;
406           return;
407         }
408         ImageFileDocument* pDifferenceDoc = theApp->newImageDoc();
409         if (! pDifferenceDoc) {
410           sys_error (ERR_SEVERE, "Unable to create image file");
411           return;
412         }
413         pDifferenceDoc->setImageFile (pDifferenceImage);
414         
415         wxString s = GetFrame()->GetTitle() + ": ";
416         pDifferenceImage->labelsCopy (rIF, s.c_str());
417         s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
418         pDifferenceImage->labelsCopy (rCompareIF, s.c_str());
419         std::ostringstream osLabel;
420         osLabel << "Compare image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() 
421           << " and " << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": "
422           << os.str().c_str();
423         pDifferenceImage->labelAdd (os.str().c_str());
424         if (theApp->getAskDeleteNewDocs())
425           pDifferenceDoc->Modify (true);
426         pDifferenceDoc->UpdateAllViews(this);
427         pDifferenceDoc->getView()->setInitialClientSize();
428         pDifferenceDoc->Activate();
429       }
430       wxMessageBox(os.str().c_str(), "Image Comparison");
431     }
432   }
433 }
434
435 void
436 ImageFileView::OnInvertValues (wxCommandEvent& event)
437 {
438   ImageFile& rIF = GetDocument()->getImageFile();
439   rIF.invertPixelValues (rIF);
440   rIF.labelAdd ("Invert Pixel Values");
441   if (theApp->getAskDeleteNewDocs())
442     GetDocument()->Modify (true);
443   GetDocument()->UpdateAllViews (this);
444   GetDocument()->Activate();
445 }
446
447 void
448 ImageFileView::OnSquare (wxCommandEvent& event)
449 {
450   ImageFile& rIF = GetDocument()->getImageFile();
451   rIF.square (rIF);
452   rIF.labelAdd ("Square Pixel Values");
453   if (theApp->getAskDeleteNewDocs())
454     GetDocument()->Modify (true);
455   GetDocument()->UpdateAllViews (this);
456   GetDocument()->Activate();
457 }
458
459 void
460 ImageFileView::OnSquareRoot (wxCommandEvent& event)
461 {
462   ImageFile& rIF = GetDocument()->getImageFile();
463   rIF.sqrt (rIF);
464   rIF.labelAdd ("Square-root Pixel Values");
465   if (theApp->getAskDeleteNewDocs())
466     GetDocument()->Modify (true);
467   GetDocument()->UpdateAllViews (this);
468   GetDocument()->Activate();
469 }
470
471 void
472 ImageFileView::OnLog (wxCommandEvent& event)
473 {
474   ImageFile& rIF = GetDocument()->getImageFile();
475   rIF.log (rIF);
476   rIF.labelAdd ("Logrithm base-e Pixel Values");
477   if (theApp->getAskDeleteNewDocs())
478     GetDocument()->Modify (true);
479   GetDocument()->UpdateAllViews (this);
480   GetDocument()->Activate();
481 }
482
483 void
484 ImageFileView::OnExp (wxCommandEvent& event)
485 {
486   ImageFile& rIF = GetDocument()->getImageFile();
487   rIF.exp (rIF);
488   rIF.labelAdd ("Exponent base-e Pixel Values");
489   if (theApp->getAskDeleteNewDocs())
490     GetDocument()->Modify (true);
491   GetDocument()->UpdateAllViews (this);
492   GetDocument()->Activate();
493 }
494
495 void
496 ImageFileView::OnAdd (wxCommandEvent& event)
497 {
498   std::vector<ImageFileDocument*> vecIF;
499   theApp->getCompatibleImages (GetDocument(), vecIF);
500   
501   if (vecIF.size() == 0) {
502     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
503   } else {
504     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Add", vecIF, false);
505     
506     if (dialogGetCompare.ShowModal() == wxID_OK) {
507       ImageFile& rIF = GetDocument()->getImageFile();
508       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
509       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
510       ImageFileDocument* pNewDoc = theApp->newImageDoc();
511       if (! pNewDoc) {
512         sys_error (ERR_SEVERE, "Unable to create image file");
513         return;
514       }
515       ImageFile& newImage = pNewDoc->getImageFile();  
516       newImage.setArraySize (rIF.nx(), rIF.ny());
517       rIF.addImages (rRHSIF, newImage);
518       std::ostringstream os;
519       os << "Add image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
520         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
521       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
522       newImage.labelsCopy (rIF, s.c_str());
523       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
524       newImage.labelsCopy (rRHSIF, s.c_str());
525       newImage.labelAdd (os.str().c_str());
526       *theApp->getLog() << os.str().c_str() << "\n";
527       if (theApp->getAskDeleteNewDocs())
528         pNewDoc->Modify (true);
529       pNewDoc->UpdateAllViews (this);
530       pNewDoc->getView()->setInitialClientSize();
531       pNewDoc->Activate();
532     }
533   }
534 }
535
536 void
537 ImageFileView::OnSubtract (wxCommandEvent& event)
538 {
539   std::vector<ImageFileDocument*> vecIF;
540   theApp->getCompatibleImages (GetDocument(), vecIF);
541   
542   if (vecIF.size() == 0) {
543     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
544   } else {
545     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Subtract", vecIF, false);
546     
547     if (dialogGetCompare.ShowModal() == wxID_OK) {
548       ImageFile& rIF = GetDocument()->getImageFile();
549       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
550       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
551       ImageFileDocument* pNewDoc = theApp->newImageDoc();
552       if (! pNewDoc) {
553         sys_error (ERR_SEVERE, "Unable to create image file");
554         return;
555       }
556       ImageFile& newImage = pNewDoc->getImageFile();  
557       newImage.setArraySize (rIF.nx(), rIF.ny());
558       rIF.subtractImages (rRHSIF, newImage);
559       std::ostringstream os;
560       os << "Subtract image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
561         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
562       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
563       newImage.labelsCopy (rIF, s.c_str());
564       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
565       newImage.labelsCopy (rRHSIF, s.c_str());
566       newImage.labelAdd (os.str().c_str());
567       *theApp->getLog() << os.str().c_str() << "\n";
568       if (theApp->getAskDeleteNewDocs())
569         pNewDoc->Modify (true);
570       pNewDoc->UpdateAllViews (this);
571       pNewDoc->getView()->setInitialClientSize();
572       pNewDoc->Activate();
573     }
574   }
575 }
576
577 void
578 ImageFileView::OnMultiply (wxCommandEvent& event)
579 {
580   std::vector<ImageFileDocument*> vecIF;
581   theApp->getCompatibleImages (GetDocument(), vecIF);
582   
583   if (vecIF.size() == 0) {
584     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
585   } else {
586     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Multiply", vecIF, false);
587     
588     if (dialogGetCompare.ShowModal() == wxID_OK) {
589       ImageFile& rIF = GetDocument()->getImageFile();
590       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
591       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
592       ImageFileDocument* pNewDoc = theApp->newImageDoc();
593       if (! pNewDoc) {
594         sys_error (ERR_SEVERE, "Unable to create image file");
595         return;
596       }
597       ImageFile& newImage = pNewDoc->getImageFile();  
598       newImage.setArraySize (rIF.nx(), rIF.ny());
599       rIF.multiplyImages (rRHSIF, newImage);
600       std::ostringstream os;
601       os << "Multiply image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and " 
602         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
603       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
604       newImage.labelsCopy (rIF, s.c_str());
605       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
606       newImage.labelsCopy (rRHSIF, s.c_str());
607       newImage.labelAdd (os.str().c_str());
608       *theApp->getLog() << os.str().c_str() << "\n";
609       if (theApp->getAskDeleteNewDocs())
610         pNewDoc->Modify (true);
611       pNewDoc->UpdateAllViews (this);
612       pNewDoc->getView()->setInitialClientSize();
613       pNewDoc->Activate();
614     }
615   }
616 }
617
618 void
619 ImageFileView::OnDivide (wxCommandEvent& event)
620 {
621   std::vector<ImageFileDocument*> vecIF;
622   theApp->getCompatibleImages (GetDocument(), vecIF);
623   
624   if (vecIF.size() == 0) {
625     wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
626   } else {
627     DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Divide", vecIF, false);
628     
629     if (dialogGetCompare.ShowModal() == wxID_OK) {
630       ImageFile& rIF = GetDocument()->getImageFile();
631       ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
632       const ImageFile& rRHSIF = pRHSDoc->getImageFile();
633       ImageFileDocument* pNewDoc = theApp->newImageDoc();
634       if (! pNewDoc) {
635         sys_error (ERR_SEVERE, "Unable to create image file");
636         return;
637       }
638       ImageFile& newImage = pNewDoc->getImageFile();  
639       newImage.setArraySize (rIF.nx(), rIF.ny());
640       rIF.divideImages (rRHSIF, newImage);
641       std::ostringstream os;
642       os << "Divide image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " by " 
643         << pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
644       wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
645       newImage.labelsCopy (rIF, s.c_str());
646       s = pRHSDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
647       newImage.labelsCopy (rRHSIF, s.c_str());
648       newImage.labelAdd (os.str().c_str());
649       *theApp->getLog() << os.str().c_str() << "\n";
650       if (theApp->getAskDeleteNewDocs())
651         pNewDoc->Modify (true);
652       pNewDoc->UpdateAllViews (this);
653       pNewDoc->getView()->setInitialClientSize();
654       pNewDoc->Activate();
655     }
656   }
657 }
658
659
660 #ifdef HAVE_FFT
661 void
662 ImageFileView::OnFFT (wxCommandEvent& event)
663 {
664   ImageFile& rIF = GetDocument()->getImageFile();
665   rIF.fft (rIF);
666   rIF.labelAdd ("FFT Image");
667   m_bMinSpecified = false;
668   m_bMaxSpecified = false;
669   if (theApp->getAskDeleteNewDocs())
670     GetDocument()->Modify (true);
671   GetDocument()->UpdateAllViews (this);
672   GetDocument()->Activate();
673 }
674
675 void
676 ImageFileView::OnIFFT (wxCommandEvent& event)
677 {
678   ImageFile& rIF = GetDocument()->getImageFile();
679   rIF.ifft (rIF);
680   rIF.labelAdd ("IFFT Image");
681   m_bMinSpecified = false;
682   m_bMaxSpecified = false;
683   if (theApp->getAskDeleteNewDocs())
684     GetDocument()->Modify (true);
685   GetDocument()->UpdateAllViews (this);
686   GetDocument()->Activate();
687 }
688
689 void
690 ImageFileView::OnFFTRows (wxCommandEvent& event)
691 {
692   ImageFile& rIF = GetDocument()->getImageFile();
693   rIF.fftRows (rIF);
694   rIF.labelAdd ("FFT Rows");
695   m_bMinSpecified = false;
696   m_bMaxSpecified = false;
697   if (theApp->getAskDeleteNewDocs())
698     GetDocument()->Modify (true);
699   GetDocument()->UpdateAllViews (this);
700   GetDocument()->Activate();
701 }
702
703 void
704 ImageFileView::OnIFFTRows (wxCommandEvent& event)
705 {
706   ImageFile& rIF = GetDocument()->getImageFile();
707   rIF.ifftRows (rIF);
708   rIF.labelAdd ("IFFT Rows");
709   m_bMinSpecified = false;
710   m_bMaxSpecified = false;
711   if (theApp->getAskDeleteNewDocs())
712     GetDocument()->Modify (true);
713   GetDocument()->UpdateAllViews (this);
714   GetDocument()->Activate();
715 }
716
717 void
718 ImageFileView::OnFFTCols (wxCommandEvent& event)
719 {
720   ImageFile& rIF = GetDocument()->getImageFile();
721   rIF.fftCols (rIF);
722   rIF.labelAdd ("FFT Columns");
723   m_bMinSpecified = false;
724   m_bMaxSpecified = false;
725   if (theApp->getAskDeleteNewDocs())
726     GetDocument()->Modify (true);
727   GetDocument()->UpdateAllViews (this);
728   GetDocument()->Activate();
729 }
730
731 void
732 ImageFileView::OnIFFTCols (wxCommandEvent& event)
733 {
734   ImageFile& rIF = GetDocument()->getImageFile();
735   rIF.ifftCols (rIF);
736   rIF.labelAdd ("IFFT Columns");
737   m_bMinSpecified = false;
738   m_bMaxSpecified = false;
739   if (theApp->getAskDeleteNewDocs())
740     GetDocument()->Modify (true);
741   GetDocument()->UpdateAllViews (this);
742   GetDocument()->Activate();
743 }
744 #endif
745
746 void
747 ImageFileView::OnFourier (wxCommandEvent& event)
748 {
749   ImageFile& rIF = GetDocument()->getImageFile();
750   wxProgressDialog dlgProgress (wxString("Fourier"), wxString("Fourier Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
751   rIF.fourier (rIF);
752   rIF.labelAdd ("Fourier Image");
753   m_bMinSpecified = false;
754   m_bMaxSpecified = false;
755   if (theApp->getAskDeleteNewDocs())
756     GetDocument()->Modify (true);
757   GetDocument()->UpdateAllViews (this);
758   GetDocument()->Activate();
759 }
760
761 void
762 ImageFileView::OnInverseFourier (wxCommandEvent& event)
763 {
764   ImageFile& rIF = GetDocument()->getImageFile();
765   wxProgressDialog dlgProgress (wxString("Inverse Fourier"), wxString("Inverse Fourier Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
766   rIF.inverseFourier (rIF);
767   rIF.labelAdd ("Inverse Fourier Image");
768   m_bMinSpecified = false;
769   m_bMaxSpecified = false;
770   if (theApp->getAskDeleteNewDocs())
771     GetDocument()->Modify (true);
772   GetDocument()->UpdateAllViews (this);
773   GetDocument()->Activate();
774 }
775
776 void
777 ImageFileView::OnShuffleNaturalToFourierOrder (wxCommandEvent& event)
778 {
779   ImageFile& rIF = GetDocument()->getImageFile();
780   Fourier::shuffleNaturalToFourierOrder (rIF);
781   rIF.labelAdd ("Shuffle Natural To Fourier Order");
782   m_bMinSpecified = false;
783   m_bMaxSpecified = false;
784   if (theApp->getAskDeleteNewDocs())
785     GetDocument()->Modify (true);
786   GetDocument()->UpdateAllViews (this);
787   GetDocument()->Activate();
788 }
789
790 void
791 ImageFileView::OnShuffleFourierToNaturalOrder (wxCommandEvent& event)
792 {
793   ImageFile& rIF = GetDocument()->getImageFile();
794   Fourier::shuffleFourierToNaturalOrder (rIF);
795   rIF.labelAdd ("Shuffle Fourier To Natural Order");
796   m_bMinSpecified = false;
797   m_bMaxSpecified = false;
798   if (theApp->getAskDeleteNewDocs())
799     GetDocument()->Modify (true);
800   GetDocument()->UpdateAllViews (this);
801   GetDocument()->Activate();
802 }
803
804 void
805 ImageFileView::OnMagnitude (wxCommandEvent& event)
806 {
807   ImageFile& rIF = GetDocument()->getImageFile();
808   rIF.magnitude (rIF);
809   rIF.labelAdd ("Magnitude");
810   m_bMinSpecified = false;
811   m_bMaxSpecified = false;
812   if (theApp->getAskDeleteNewDocs())
813     GetDocument()->Modify (true);
814   GetDocument()->UpdateAllViews (this);
815   GetDocument()->Activate();
816 }
817
818 void
819 ImageFileView::OnPhase (wxCommandEvent& event)
820 {
821   ImageFile& rIF = GetDocument()->getImageFile();
822   if (rIF.isComplex()) {
823     rIF.phase (rIF);
824     rIF.labelAdd ("Phase of complex-image");
825     m_bMinSpecified = false;
826     m_bMaxSpecified = false;
827     if (theApp->getAskDeleteNewDocs())
828       GetDocument()->Modify (true);
829     GetDocument()->UpdateAllViews (this);
830   }
831   GetDocument()->Activate();
832 }
833
834 void
835 ImageFileView::OnReal (wxCommandEvent& event)
836 {
837   ImageFile& rIF = GetDocument()->getImageFile();
838   if (rIF.isComplex()) {
839     rIF.real (rIF);
840     rIF.labelAdd ("Real component of complex-image");
841     m_bMinSpecified = false;
842     m_bMaxSpecified = false;
843     if (theApp->getAskDeleteNewDocs())
844       GetDocument()->Modify (true);
845     GetDocument()->UpdateAllViews (this);
846   }
847   GetDocument()->Activate();
848 }
849
850 void
851 ImageFileView::OnImaginary (wxCommandEvent& event)
852 {
853   ImageFile& rIF = GetDocument()->getImageFile();
854   if (rIF.isComplex()) {
855     rIF.imaginary (rIF);
856     rIF.labelAdd ("Imaginary component of complex-image");
857     m_bMinSpecified = false;
858     m_bMaxSpecified = false;
859     if (theApp->getAskDeleteNewDocs())
860       GetDocument()->Modify (true);
861     GetDocument()->UpdateAllViews (this);
862   }
863   GetDocument()->Activate();
864 }
865
866
867 ImageFileCanvas* 
868 ImageFileView::CreateCanvas (wxFrame* parent)
869 {
870   ImageFileCanvas* pCanvas = new ImageFileCanvas (this, parent, wxPoint(-1,-1),
871                                                   wxSize(-1,-1), 0);
872   pCanvas->SetBackgroundColour(*wxWHITE);
873   pCanvas->Clear();
874   
875   return pCanvas;
876 }
877
878 #if CTSIM_MDI
879 wxDocMDIChildFrame*
880 #else
881 wxDocChildFrame*
882 #endif
883 ImageFileView::CreateChildFrame(wxDocument *doc, wxView *view)
884 {
885 #if CTSIM_MDI
886   wxDocMDIChildFrame* subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
887 #else
888   wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
889 #endif
890   theApp->setIconForFrame (subframe);
891
892   m_pFileMenu = new wxMenu;
893   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
894   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
895   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
896   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
897   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
898   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
899   m_pFileMenu->Append(wxID_REVERT, "Re&vert");
900   
901   m_pFileMenu->AppendSeparator();
902   m_pFileMenu->Append(IFMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
903   m_pFileMenu->Append(IFMENU_FILE_EXPORT, "Expor&t...");
904   
905   m_pFileMenu->AppendSeparator();
906   m_pFileMenu->Append(wxID_PRINT, "&Print...");
907   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
908   m_pFileMenu->Append(wxID_PREVIEW, "Print Preview");
909   m_pFileMenu->AppendSeparator();
910   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
911   m_pFileMenu->AppendSeparator();
912   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
913   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
914   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
915   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
916   
917   wxMenu* edit_menu = new wxMenu;
918   edit_menu->Append(IFMENU_EDIT_COPY, "Copy\tCtrl-C");
919   edit_menu->Append(IFMENU_EDIT_CUT, "Cut\tCtrl-X");
920   edit_menu->Append(IFMENU_EDIT_PASTE, "Paste\tCtrl-V");
921   
922   wxMenu *view_menu = new wxMenu;
923   view_menu->Append(IFMENU_VIEW_SCALE_MINMAX, "Display Scale S&et...\tCtrl-E");
924   view_menu->Append(IFMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
925   view_menu->Append(IFMENU_VIEW_SCALE_FULL, "Display F&ull Scale\tCtrl-U");
926   
927   m_pFilterMenu = new wxMenu;
928   m_pFilterMenu->Append (IFMENU_FILTER_INVERTVALUES, "In&vert Values");
929   m_pFilterMenu->Append (IFMENU_FILTER_SQUARE, "&Square");
930   m_pFilterMenu->Append (IFMENU_FILTER_SQRT, "Square &Root");
931   m_pFilterMenu->Append (IFMENU_FILTER_LOG, "&Log");
932   m_pFilterMenu->Append (IFMENU_FILTER_EXP, "E&xp");
933   m_pFilterMenu->AppendSeparator();
934 #ifdef HAVE_FFT
935   m_pFilterMenu->Append (IFMENU_FILTER_FFT, "2-D &FFT\tCtrl-2");
936   m_pFilterMenu->Append (IFMENU_FILTER_IFFT, "2-D &IFFT\tAlt-2");
937   m_pFilterMenu->Append (IFMENU_FILTER_FFT_ROWS, "FFT Rows");
938   m_pFilterMenu->Append (IFMENU_FILTER_IFFT_ROWS, "IFFT Rows");
939   m_pFilterMenu->Append (IFMENU_FILTER_FFT_COLS, "FFT Columns");
940   m_pFilterMenu->Append (IFMENU_FILTER_IFFT_COLS, "IFFT Columns");
941   m_pFilterMenu->Append (IFMENU_FILTER_FOURIER, "2-D F&ourier");
942   m_pFilterMenu->Append (IFMENU_FILTER_INVERSE_FOURIER, "2-D Inverse Fo&urier");
943 #else
944   m_pFilterMenu->Append (IFMENU_FILTER_FOURIER, "&Fourier");
945   m_pFilterMenu->Append (IFMENU_FILTER_INVERSE_FOURIER, "&Inverse Fourier");
946 #endif
947   m_pFilterMenu->Append (IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER, "Shuffl&e Fourier to Natural Order");
948   m_pFilterMenu->Append (IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER, "Shuffle &Natural to Fourier Order");
949   m_pFilterMenu->AppendSeparator();
950   m_pFilterMenu->Append (IFMENU_FILTER_MAGNITUDE, "&Magnitude");
951   m_pFilterMenu->Append (IFMENU_FILTER_PHASE, "&Phase");
952   m_pFilterMenu->Append (IFMENU_FILTER_REAL, "Re&al");
953   m_pFilterMenu->Append (IFMENU_FILTER_IMAGINARY, "Ima&ginary");
954   
955   wxMenu* image_menu = new wxMenu;
956   image_menu->Append (IFMENU_IMAGE_ADD, "&Add...");
957   image_menu->Append (IFMENU_IMAGE_SUBTRACT, "&Subtract...");
958   image_menu->Append (IFMENU_IMAGE_MULTIPLY, "&Multiply...");
959   image_menu->Append (IFMENU_IMAGE_DIVIDE, "&Divide...");
960   image_menu->AppendSeparator();
961   image_menu->Append (IFMENU_IMAGE_SCALESIZE, "S&cale Size...");
962 #if wxUSE_GLCANVAS
963   image_menu->Append (IFMENU_IMAGE_CONVERT3D, "Convert &3-D\tCtrl-3");
964 #endif
965   
966   m_pMenuAnalyze = new wxMenu;
967   m_pMenuAnalyze->Append (IFMENU_PLOT_ROW, "Plot &Row");
968   m_pMenuAnalyze->Append (IFMENU_PLOT_COL, "Plot &Column");
969   m_pMenuAnalyze->Append (IFMENU_PLOT_HISTOGRAM, "Plot &Histogram");
970   m_pMenuAnalyze->AppendSeparator();
971   m_pMenuAnalyze->Append (IFMENU_PLOT_FFT_ROW, "P&lot FFT Row");
972   m_pMenuAnalyze->Append (IFMENU_PLOT_FFT_COL, "Plo&t FFT Column");
973   m_pMenuAnalyze->AppendSeparator();
974   m_pMenuAnalyze->Append (IFMENU_COMPARE_IMAGES, "Compare &Images...");
975   m_pMenuAnalyze->Append (IFMENU_COMPARE_ROW, "Compare Ro&w");
976   m_pMenuAnalyze->Append (IFMENU_COMPARE_COL, "Compare Colu&mn");
977   m_pMenuAnalyze->Enable (IFMENU_PLOT_ROW, false);
978   m_pMenuAnalyze->Enable (IFMENU_PLOT_COL, false);
979   m_pMenuAnalyze->Enable (IFMENU_COMPARE_ROW, false);
980   m_pMenuAnalyze->Enable (IFMENU_COMPARE_COL, false);
981   m_pMenuAnalyze->Enable (IFMENU_PLOT_FFT_ROW, false);
982   m_pMenuAnalyze->Enable (IFMENU_PLOT_FFT_COL, false);
983   
984   wxMenu *help_menu = new wxMenu;
985   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
986   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
987   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
988   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
989   
990   wxMenuBar *menu_bar = new wxMenuBar;
991   
992   menu_bar->Append(m_pFileMenu, "&File");
993   menu_bar->Append(edit_menu, "&Edit");
994   menu_bar->Append(view_menu, "&View");
995   menu_bar->Append(image_menu, "&Image");
996   menu_bar->Append(m_pFilterMenu, "Fi&lter");
997   menu_bar->Append(m_pMenuAnalyze, "&Analyze");
998   menu_bar->Append(help_menu, "&Help");
999   
1000   subframe->SetMenuBar(menu_bar);
1001   
1002   subframe->Centre(wxBOTH);
1003   
1004   wxAcceleratorEntry accelEntries[10];
1005   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('A'), IFMENU_VIEW_SCALE_AUTO);
1006   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('U'), IFMENU_VIEW_SCALE_FULL);
1007   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('E'), IFMENU_VIEW_SCALE_MINMAX);
1008   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('I'), IFMENU_FILE_PROPERTIES);
1009   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('C'), IFMENU_EDIT_COPY);
1010   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('X'), IFMENU_EDIT_CUT);
1011   accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('V'), IFMENU_EDIT_PASTE);
1012   int iEntry = 7;
1013 #ifdef HAVE_FFT
1014   accelEntries[iEntry++].Set (wxACCEL_CTRL, static_cast<int>('2'), IFMENU_FILTER_FFT);
1015   accelEntries[iEntry++].Set (wxACCEL_ALT,  static_cast<int>('2'), IFMENU_FILTER_IFFT);
1016 #endif
1017 #if wxUSE_GLCANVAS
1018   accelEntries[iEntry++].Set (wxACCEL_CTRL, static_cast<int>('3'), IFMENU_IMAGE_CONVERT3D);
1019 #endif
1020
1021   wxAcceleratorTable accelTable (iEntry, accelEntries);
1022   subframe->SetAcceleratorTable (accelTable);
1023   
1024   return subframe;
1025 }
1026
1027
1028 bool 
1029 ImageFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
1030 {
1031   m_bMinSpecified = false;
1032   m_bMaxSpecified = false;
1033   m_dAutoScaleFactor = 1.;
1034   
1035   m_pFrame = CreateChildFrame(doc, this);
1036   SetFrame (m_pFrame);
1037   m_pCanvas = CreateCanvas (m_pFrame);
1038   m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
1039   m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
1040   m_pFrame->SetTitle("ImageFileView");
1041
1042   m_pFrame->Show(true);
1043   Activate(true);
1044   
1045   return true;
1046 }
1047
1048 void 
1049 ImageFileView::setInitialClientSize ()
1050 {
1051   if (m_pFrame && m_pCanvas) {
1052     wxSize bestSize = m_pCanvas->GetBestSize();
1053     
1054     m_pFrame->SetClientSize (bestSize);
1055     m_pFrame->Show (true);
1056     m_pFrame->SetFocus();
1057   }
1058 }  
1059
1060 void 
1061 ImageFileView::OnDraw (wxDC* dc)
1062 {
1063   if (m_pBitmap && m_pBitmap->Ok())
1064     dc->DrawBitmap(*m_pBitmap, 0, 0, false);
1065   
1066   int xCursor, yCursor;
1067   if (m_pCanvas->GetCurrentCursor (xCursor, yCursor))
1068     m_pCanvas->DrawRubberBandCursor (*dc, xCursor, yCursor);
1069 }
1070
1071
1072 void 
1073 ImageFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
1074 {
1075   const ImageFile& rIF = GetDocument()->getImageFile();
1076   if (m_pFilterMenu && rIF.isComplex()) {
1077     m_pFilterMenu->Enable(IFMENU_FILTER_REAL, true);
1078     m_pFilterMenu->Enable(IFMENU_FILTER_IMAGINARY, true);
1079     m_pFilterMenu->Enable(IFMENU_FILTER_PHASE, true);
1080   } else {
1081     m_pFilterMenu->Enable(IFMENU_FILTER_REAL, false);
1082     m_pFilterMenu->Enable(IFMENU_FILTER_IMAGINARY, false);
1083     m_pFilterMenu->Enable(IFMENU_FILTER_PHASE, false);
1084   }
1085   ImageFileArrayConst v = rIF.getArray();
1086   int nx = rIF.nx();
1087   int ny = rIF.ny();
1088   if (v != NULL && nx != 0 && ny != 0) {
1089     if (! m_bMinSpecified || ! m_bMaxSpecified) {
1090       double min, max;
1091       rIF.getMinMax (min, max);
1092       if (! m_bMinSpecified)
1093         m_dMinPixel = min;
1094       if (! m_bMaxSpecified)
1095         m_dMaxPixel = max;
1096     }
1097     double scaleWidth = m_dMaxPixel - m_dMinPixel;
1098     
1099     unsigned char* imageData = new unsigned char [nx * ny * 3];
1100     if (! imageData) {
1101       sys_error (ERR_SEVERE, "Unable to allocate memory for Image display");
1102       return;
1103     }
1104     for (int ix = 0; ix < nx; ix++) {
1105       for (int iy = 0; iy < ny; iy++) {
1106         double scaleValue = ((v[ix][iy] - m_dMinPixel) / scaleWidth) * 255;
1107         int intensity = static_cast<int>(scaleValue + 0.5);
1108         intensity = clamp (intensity, 0, 255);
1109         int baseAddr = ((ny - 1 - iy) * nx + ix) * 3;
1110         imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
1111       }
1112     }
1113     wxImage image (nx, ny, imageData, true);
1114     if (m_pBitmap) {
1115       delete m_pBitmap;
1116       m_pBitmap = NULL;
1117     }
1118     m_pBitmap = new wxBitmap (image);
1119     delete imageData;
1120     m_pCanvas->SetScrollbars(20, 20, nx/20, ny/20);
1121     m_pCanvas->SetBackgroundColour(*wxWHITE);
1122   } 
1123   
1124   if (m_pCanvas)
1125     m_pCanvas->Refresh();
1126 }
1127
1128 bool 
1129 ImageFileView::OnClose (bool deleteWindow)
1130 {
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   if (m_pBitmap)
1161     pBitmapObject->SetBitmap (*m_pBitmap);
1162   
1163   if (wxTheClipboard->Open()) {
1164     wxTheClipboard->SetData (pBitmapObject);
1165     wxTheClipboard->Close();
1166   }
1167 }
1168
1169 void
1170 ImageFileView::OnEditCut (wxCommandEvent& event)
1171 {
1172   OnEditCopy (event);
1173   ImageFile& rIF = GetDocument()->getImageFile();
1174   int nx = rIF.nx();
1175   int ny = rIF.ny();
1176   ImageFile* pIF = new ImageFile (nx, ny);
1177   pIF->arrayDataClear();
1178   GetDocument()->setImageFile (pIF); // deletes old IF
1179   OnUpdate(this, NULL);
1180   GetDocument()->UpdateAllViews();
1181   if (theApp->getAskDeleteNewDocs())
1182     GetDocument()->Modify (true);
1183 }
1184
1185 void
1186 ImageFileView::OnEditPaste (wxCommandEvent& event)
1187 {
1188   ImageFile& rIF = GetDocument()->getImageFile();
1189   
1190   if (wxTheClipboard->Open()) {
1191     wxBitmap bitmap;
1192     if (wxTheClipboard->IsSupported (wxDF_BITMAP)) {
1193       wxBitmapDataObject bitmapObject;
1194       wxTheClipboard->GetData (bitmapObject);
1195       bitmap = bitmapObject.GetBitmap ();
1196     }
1197     wxTheClipboard->Close();
1198     
1199     int nx = rIF.nx();
1200     int ny = rIF.ny();
1201     bool bMonochrome = false;
1202
1203     if (bitmap.Ok() == true && bitmap.GetWidth() == nx && bitmap.GetHeight() == ny) {
1204       wxImage image (bitmap.ConvertToImage());
1205       double dScale3 = 3 * 255;
1206       unsigned char* pixels = image.GetData();
1207       ImageFileArray v = rIF.getArray();
1208       for (unsigned int ix = 0; ix < rIF.nx(); ix++) {
1209         for (unsigned int iy = 0; iy < rIF.ny(); iy++) {
1210           unsigned int iBase = 3 * (iy * nx + ix);
1211           if (ix == 0 && iy == 0 && (pixels[iBase] == pixels[iBase+1] && pixels[iBase+1] == pixels[iBase+2]))
1212             bMonochrome = true;
1213           if (bMonochrome) {
1214             v[ix][ny - 1 - iy] = (pixels[iBase]+pixels[iBase+1]+pixels[iBase+2]) / dScale3;
1215           } else {
1216             double dR = pixels[iBase] / 255.;
1217             double dG = pixels[iBase+1] / 255.;
1218             double dB = pixels[iBase+2] / 255.;
1219             v[ix][ny - 1 - iy] = ImageFile::colorToGrayscale (dR, dG, dB);
1220           }
1221         }
1222       }
1223       OnUpdate(this, NULL);
1224       GetDocument()->UpdateAllViews();
1225       if (theApp->getAskDeleteNewDocs())
1226         GetDocument()->Modify(true);
1227     }
1228   }
1229 }
1230
1231 void
1232 ImageFileView::OnExport (wxCommandEvent& event)
1233 {
1234   ImageFile& rIF = GetDocument()->getImageFile();
1235   ImageFileArrayConst v = rIF.getArray();
1236   int nx = rIF.nx();
1237   int ny = rIF.ny();
1238   if (v != NULL && nx != 0 && ny != 0) {
1239     if (! m_bMinSpecified || ! m_bMaxSpecified) {
1240       double min, max;
1241       rIF.getMinMax (min, max);
1242       if (! m_bMinSpecified)
1243         m_dMinPixel = min;
1244       if (! m_bMaxSpecified)
1245         m_dMaxPixel = max;
1246     }
1247     
1248     DialogExportParameters dialogExport (getFrameForChild(), m_iDefaultExportFormatID);
1249     if (dialogExport.ShowModal() == wxID_OK) {
1250       wxString strFormatName (dialogExport.getFormatName ());
1251       m_iDefaultExportFormatID = ImageFile::convertExportFormatNameToID (strFormatName.c_str());
1252       
1253       wxString strExt;
1254       wxString strWildcard;
1255       if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PGM || m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PGMASCII) {
1256         strExt = ".pgm";
1257         strWildcard = "PGM Files (*.pgm)|*.pgm";
1258       }
1259 #ifdef HAVE_PNG
1260       else if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PNG || m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PNG16) {
1261         strExt = ".png";
1262         strWildcard = "PNG Files (*.png)|*.png";
1263       }
1264 #endif
1265 #ifdef HAVE_CTN_DICOM
1266       else if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_DICOM) {
1267         strExt = "";
1268         strWildcard = "DICOM Files (*.*)|*.*";
1269       }
1270 #endif
1271       else if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_TEXT) {
1272         strExt = ".txt";
1273         strWildcard = "Text (*.txt)|*.txt";
1274       }
1275       else {
1276         strExt = "";
1277         strWildcard = "Miscellaneous (*.*)|*.*";
1278       }
1279       
1280       const wxString& strFilename = wxFileSelector (wxString("Export Filename"), wxString(""), 
1281         wxString(""), strExt, strWildcard, wxOVERWRITE_PROMPT | wxHIDE_READONLY | wxSAVE);
1282       if (strFilename) {
1283         rIF.exportImage (strFormatName.c_str(), strFilename.c_str(), 1, 1, m_dMinPixel, m_dMaxPixel);
1284         *theApp->getLog() << "Exported file " << strFilename << "\n";
1285       }
1286     }
1287   }
1288 }
1289
1290 void
1291 ImageFileView::OnScaleSize (wxCommandEvent& event)
1292 {
1293   ImageFile& rIF = GetDocument()->getImageFile();
1294   unsigned int iOldNX = rIF.nx();
1295   unsigned int iOldNY = rIF.ny();
1296   
1297   DialogGetXYSize dialogGetXYSize (getFrameForChild(), "Set New X & Y Dimensions", iOldNX, iOldNY);
1298   if (dialogGetXYSize.ShowModal() == wxID_OK) {
1299     unsigned int iNewNX = dialogGetXYSize.getXSize();
1300     unsigned int iNewNY = dialogGetXYSize.getYSize();
1301     std::ostringstream os;
1302     os << "Scale Size from (" << iOldNX << "," << iOldNY << ") to (" << iNewNX << "," << iNewNY << ")";
1303     ImageFileDocument* pScaledDoc = theApp->newImageDoc();
1304     if (! pScaledDoc) {
1305       sys_error (ERR_SEVERE, "Unable to create image file");
1306       return;
1307     }
1308     ImageFile& rScaledIF = pScaledDoc->getImageFile();
1309     rScaledIF.setArraySize (iNewNX, iNewNY);
1310     rScaledIF.labelsCopy (rIF);
1311     rScaledIF.labelAdd (os.str().c_str());
1312     rIF.scaleImage (rScaledIF);
1313     *theApp->getLog() << os.str().c_str() << "\n";
1314     if (theApp->getAskDeleteNewDocs())
1315       pScaledDoc->Modify (true);
1316     pScaledDoc->UpdateAllViews (this);
1317     pScaledDoc->getView()->setInitialClientSize();
1318     pScaledDoc->Activate();
1319   }
1320 }
1321
1322 #if wxUSE_GLCANVAS
1323 void
1324 ImageFileView::OnConvert3d (wxCommandEvent& event)
1325 {
1326   ImageFile& rIF = GetDocument()->getImageFile();
1327   Graph3dFileDocument* pGraph3d = theApp->newGraph3dDoc();
1328   pGraph3d->getView()->getFrame()->Show (false);
1329   pGraph3d->setBadFileOpen();
1330   pGraph3d->createFromImageFile (rIF);
1331   pGraph3d->UpdateAllViews();
1332   pGraph3d->getView()->getFrame()->Show (true);
1333   pGraph3d->getView()->Activate(true);
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), m_pView(v)
1962 {
1963 }
1964
1965 PhantomCanvas::~PhantomCanvas ()
1966 {
1967   m_pView = NULL;
1968 }
1969
1970 void 
1971 PhantomCanvas::OnDraw (wxDC& dc)
1972 {
1973   if (m_pView)
1974     m_pView->OnDraw(& dc);
1975 }
1976
1977 wxSize
1978 PhantomCanvas::GetBestSize() const
1979 {
1980   if (! m_pView)
1981     return wxSize(0,0);
1982   
1983   int xSize, ySize;
1984   theApp->getMainFrame()->GetClientSize (&xSize, &ySize);
1985   xSize = maxValue<int> (xSize, ySize);
1986 #ifdef CTSIM_MDI
1987   ySize = xSize = (xSize / 4);
1988 #else
1989   xSize = ySize = static_cast<int>(ySize * .7);
1990 #endif
1991
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 = new PhantomCanvas (this, parent, wxPoint(-1,-1), 
2267                                               wxSize(-1,-1), 0);
2268   pCanvas->SetBackgroundColour(*wxWHITE);
2269   pCanvas->Clear();
2270   
2271   return pCanvas;
2272 }
2273
2274 #if CTSIM_MDI
2275 wxDocMDIChildFrame*
2276 #else
2277 wxDocChildFrame*
2278 #endif
2279 PhantomFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2280 {
2281 #if CTSIM_MDI
2282   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
2283 #else
2284   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
2285 #endif
2286   theApp->setIconForFrame (subframe);
2287   
2288   m_pFileMenu = new wxMenu;
2289   
2290   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
2291   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
2292   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
2293   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
2294   m_pFileMenu->Append(wxID_CLOSE, "&Close");
2295   
2296   m_pFileMenu->AppendSeparator();
2297   m_pFileMenu->Append(PHMMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
2298   
2299   m_pFileMenu->AppendSeparator();
2300   m_pFileMenu->Append(wxID_PRINT, "&Print...");
2301   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
2302   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
2303   m_pFileMenu->AppendSeparator();
2304   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
2305   m_pFileMenu->AppendSeparator();
2306   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
2307   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
2308   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
2309   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
2310   
2311   wxMenu *process_menu = new wxMenu;
2312   process_menu->Append(PHMMENU_PROCESS_RASTERIZE, "&Rasterize...\tCtrl-R");
2313   process_menu->Append(PHMMENU_PROCESS_PROJECTIONS, "&Projections...\tCtrl-J");
2314   
2315   wxMenu *help_menu = new wxMenu;
2316   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
2317   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
2318   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
2319   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
2320   
2321   wxMenuBar *menu_bar = new wxMenuBar;
2322   
2323   menu_bar->Append(m_pFileMenu, "&File");
2324   menu_bar->Append(process_menu, "&Process");
2325   menu_bar->Append(help_menu, "&Help");
2326   
2327   subframe->SetMenuBar(menu_bar);
2328   subframe->Centre(wxBOTH);
2329   
2330   wxAcceleratorEntry accelEntries[3];
2331   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('J'), PHMMENU_PROCESS_PROJECTIONS);
2332   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('R'), PHMMENU_PROCESS_RASTERIZE);
2333   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('I'), PHMMENU_FILE_PROPERTIES);
2334   wxAcceleratorTable accelTable (3, accelEntries);
2335   subframe->SetAcceleratorTable (accelTable);
2336   
2337   return subframe;
2338 }
2339
2340
2341 bool 
2342 PhantomFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
2343 {
2344   m_pFrame = CreateChildFrame(doc, this);
2345   SetFrame(m_pFrame);
2346   m_pCanvas = CreateCanvas (m_pFrame);
2347   m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
2348   m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
2349   m_pFrame->SetTitle ("PhantomFileView");
2350
2351   m_pFrame->Show(true);
2352   Activate(true);
2353   
2354   return true;
2355 }
2356
2357 void 
2358 PhantomFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
2359 {
2360   if (m_pCanvas)
2361     m_pCanvas->Refresh();
2362 }
2363
2364 bool 
2365 PhantomFileView::OnClose (bool deleteWindow)
2366 {
2367   if (! GetDocument() || ! GetDocument()->Close())
2368     return false;
2369   
2370   Activate(false);
2371   if (m_pCanvas) {
2372     m_pCanvas->setView(NULL);
2373     m_pCanvas = NULL;
2374   }
2375   wxString s(wxTheApp->GetAppName());
2376   if (m_pFrame)
2377     m_pFrame->SetTitle(s);
2378   
2379   SetFrame(NULL);
2380   
2381   if (deleteWindow) {
2382     delete m_pFrame;
2383     m_pFrame = NULL;
2384     if (GetDocument() && GetDocument()->getBadFileOpen())
2385       ::wxYield();  // wxWindows bug workaround
2386   }
2387   
2388   return true;
2389 }
2390
2391 void
2392 PhantomFileView::OnDraw (wxDC* dc)
2393 {
2394   int xsize, ysize;
2395   m_pCanvas->GetClientSize (&xsize, &ysize);
2396   SGPDriver driver (dc, xsize, ysize);
2397   SGP sgp (driver);
2398   const Phantom& rPhantom = GetDocument()->getPhantom();
2399   sgp.setColor (C_RED);
2400   rPhantom.show (sgp);
2401 }
2402
2403 // ProjectionCanvas
2404
2405 ProjectionFileCanvas::ProjectionFileCanvas (ProjectionFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
2406 : wxScrolledWindow(frame, -1, pos, size, style)
2407 {
2408   m_pView = v;
2409 }
2410
2411 ProjectionFileCanvas::~ProjectionFileCanvas ()
2412 {
2413   m_pView = NULL;
2414 }
2415
2416 void 
2417 ProjectionFileCanvas::OnDraw(wxDC& dc)
2418 {
2419   if (m_pView)
2420     m_pView->OnDraw(& dc);
2421 }
2422
2423 wxSize
2424 ProjectionFileCanvas::GetBestSize () const
2425 {
2426   const int iMinX = 50;
2427   const int iMinY = 20;
2428   wxSize bestSize (iMinX,iMinY);
2429
2430   if (m_pView) {
2431     Projections& rProj = m_pView->GetDocument()->getProjections();
2432     bestSize.Set (rProj.nDet(), rProj.nView());
2433   }
2434   
2435   if (bestSize.x > 800)
2436     bestSize.x = 800;
2437   if (bestSize.y > 800)
2438     bestSize.y = 800;
2439
2440   if (bestSize.x < iMinX)
2441     bestSize.x = iMinX;
2442   if (bestSize.y < iMinY)
2443     bestSize.y = iMinY;
2444
2445   return bestSize;
2446 }
2447
2448
2449 // ProjectionFileView
2450
2451 IMPLEMENT_DYNAMIC_CLASS(ProjectionFileView, wxView)
2452
2453 BEGIN_EVENT_TABLE(ProjectionFileView, wxView)
2454 EVT_MENU(PJMENU_FILE_PROPERTIES, ProjectionFileView::OnProperties)
2455 EVT_MENU(PJMENU_RECONSTRUCT_FBP, ProjectionFileView::OnReconstructFBP)
2456 EVT_MENU(PJMENU_RECONSTRUCT_FBP_REBIN, ProjectionFileView::OnReconstructFBPRebin)
2457 EVT_MENU(PJMENU_RECONSTRUCT_FOURIER, ProjectionFileView::OnReconstructFourier)
2458 EVT_MENU(PJMENU_CONVERT_RECTANGULAR, ProjectionFileView::OnConvertRectangular)
2459 EVT_MENU(PJMENU_CONVERT_POLAR, ProjectionFileView::OnConvertPolar)
2460 EVT_MENU(PJMENU_CONVERT_FFT_POLAR, ProjectionFileView::OnConvertFFTPolar)
2461 EVT_MENU(PJMENU_CONVERT_PARALLEL, ProjectionFileView::OnConvertParallel)
2462 EVT_MENU(PJMENU_PLOT_TTHETA_SAMPLING, ProjectionFileView::OnPlotTThetaSampling)
2463 EVT_MENU(PJMENU_PLOT_HISTOGRAM, ProjectionFileView::OnPlotHistogram)
2464   // EVT_MENU(PJMENU_ARTIFACT_REDUCTION, ProjectionFileView::OnArtifactReduction)
2465 END_EVENT_TABLE()
2466
2467
2468 ProjectionFileView::ProjectionFileView() 
2469   : wxView(), m_pBitmap(0), m_pFrame(0), m_pCanvas(0), m_pFileMenu(0)
2470 {
2471 #ifdef DEBUG
2472   m_iDefaultNX = 115;
2473   m_iDefaultNY = 115;
2474 #else
2475   m_iDefaultNX = 256;
2476   m_iDefaultNY = 256;
2477 #endif
2478   
2479   m_iDefaultFilter = SignalFilter::FILTER_ABS_BANDLIMIT;
2480   m_dDefaultFilterParam = 1.;
2481 #if HAVE_FFTW
2482   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_RFFTW;
2483   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_INVERSE_FOURIER;
2484 #else
2485   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_CONVOLUTION;
2486   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT;
2487 #endif
2488   m_iDefaultZeropad = 1;
2489   m_iDefaultBackprojector = Backprojector::BPROJ_IDIFF;
2490   m_iDefaultInterpolation = Backprojector::INTERP_LINEAR;
2491   m_iDefaultInterpParam = 1;
2492   m_iDefaultTrace = Trace::TRACE_NONE;
2493   
2494   m_iDefaultPolarNX = 256;
2495   m_iDefaultPolarNY = 256;
2496   m_iDefaultPolarInterpolation = Projections::POLAR_INTERP_BILINEAR;
2497   m_iDefaultPolarZeropad = 1;
2498 }
2499
2500 ProjectionFileView::~ProjectionFileView()
2501 {
2502   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
2503   GetDocumentManager()->ActivateView(this, FALSE, TRUE);;
2504 }
2505
2506 void
2507 ProjectionFileView::OnProperties (wxCommandEvent& event)
2508 {
2509   const Projections& rProj = GetDocument()->getProjections();
2510   std::ostringstream os;
2511   rProj.printScanInfo(os);
2512   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
2513   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Projection File Properties", wxOK | wxICON_INFORMATION);
2514   dialogMsg.ShowModal();
2515   GetDocument()->Activate();
2516 }
2517
2518
2519 void
2520 ProjectionFileView::OnConvertRectangular (wxCommandEvent& event)
2521 {
2522   Projections& rProj = GetDocument()->getProjections();
2523   
2524   int nDet = rProj.nDet();
2525   int nView = rProj.nView();
2526   ImageFile* pIF = new ImageFile (nDet, nView);
2527   ImageFileArray v = pIF->getArray();
2528   for (int iv = 0; iv < nView; iv++) {
2529     DetectorValue* detval = rProj.getDetectorArray(iv).detValues();
2530     
2531     for (int id = 0; id < nDet; id++)
2532       v[id][iv] = detval[id];
2533   }
2534   
2535   ImageFileDocument* pRectDoc = theApp->newImageDoc ();
2536   if (! pRectDoc) {
2537     sys_error (ERR_SEVERE, "Unable to create image file");
2538     return;
2539   }
2540   pRectDoc->setImageFile (pIF);
2541   pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2542   std::ostringstream os;
2543   os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to rectangular image";
2544   *theApp->getLog() << os.str().c_str() << "\n";
2545   pIF->labelAdd (os.str().c_str());
2546   if (theApp->getAskDeleteNewDocs())
2547     pRectDoc->Modify (true);
2548   pRectDoc->UpdateAllViews();
2549   pRectDoc->getView()->setInitialClientSize();
2550   pRectDoc->Activate();
2551 }
2552
2553 void
2554 ProjectionFileView::OnConvertPolar (wxCommandEvent& event)
2555 {
2556   Projections& rProj = GetDocument()->getProjections();
2557   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2558     m_iDefaultPolarInterpolation, -1, IDH_DLG_POLAR);
2559   if (dialogPolar.ShowModal() == wxID_OK) {
2560     wxProgressDialog dlgProgress (wxString("Convert Polar"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2561     wxString strInterpolation (dialogPolar.getInterpolationName());
2562     m_iDefaultPolarNX = dialogPolar.getXSize();
2563     m_iDefaultPolarNY = dialogPolar.getYSize();
2564     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2565     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2566     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2567     
2568     if (! rProj.convertPolar (*pIF, m_iDefaultPolarInterpolation)) {
2569       delete pIF;
2570       *theApp->getLog() << "Error converting to Polar\n";
2571       return;
2572     }
2573     
2574     pPolarDoc = theApp->newImageDoc ();
2575     if (! pPolarDoc) {
2576       sys_error (ERR_SEVERE, "Unable to create image file");
2577       return;
2578     }
2579     pPolarDoc->setImageFile (pIF);
2580     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2581     std::ostringstream os;
2582     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to polar image: xSize=" 
2583       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2584       << strInterpolation.c_str();
2585     *theApp->getLog() << os.str().c_str() << "\n";
2586     pIF->labelAdd (os.str().c_str());
2587     if (theApp->getAskDeleteNewDocs())
2588       pPolarDoc->Modify (true);
2589     pPolarDoc->UpdateAllViews ();
2590     pPolarDoc->getView()->setInitialClientSize();
2591     pPolarDoc->Activate();
2592   }
2593 }
2594
2595 void
2596 ProjectionFileView::OnConvertFFTPolar (wxCommandEvent& event)
2597 {
2598   Projections& rProj = GetDocument()->getProjections();
2599   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Convert to FFT Polar", m_iDefaultPolarNX, m_iDefaultPolarNY,
2600     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad, IDH_DLG_FFT_POLAR);
2601   if (dialogPolar.ShowModal() == wxID_OK) {
2602     wxProgressDialog dlgProgress (wxString("Convert FFT Polar"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2603     wxString strInterpolation (dialogPolar.getInterpolationName());
2604     m_iDefaultPolarNX = dialogPolar.getXSize();
2605     m_iDefaultPolarNY = dialogPolar.getYSize();
2606     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2607     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2608     
2609     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2610     if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
2611       delete pIF;
2612       *theApp->getLog() << "Error converting to polar\n";
2613       return;
2614     }
2615     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2616     if (! pPolarDoc) {
2617       sys_error (ERR_SEVERE, "Unable to create image file");
2618       return;
2619     }
2620     pPolarDoc->setImageFile (pIF);
2621     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2622     std::ostringstream os;
2623     os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to FFT polar image: xSize=" 
2624       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2625       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2626     *theApp->getLog() << os.str().c_str() << "\n";
2627     pIF->labelAdd (os.str().c_str());
2628     if (theApp->getAskDeleteNewDocs())
2629       pPolarDoc->Modify (true);
2630     pPolarDoc->UpdateAllViews (this);
2631     pPolarDoc->getView()->setInitialClientSize();
2632     pPolarDoc->Activate();
2633   }
2634 }
2635
2636 void
2637 ProjectionFileView::OnPlotTThetaSampling (wxCommandEvent& event)
2638 {
2639   DialogGetThetaRange dlgTheta (this->getFrame(), ParallelRaysums::THETA_RANGE_UNCONSTRAINED);
2640   if (dlgTheta.ShowModal() != wxID_OK)
2641     return;
2642   
2643   int iThetaRange = dlgTheta.getThetaRange();
2644   
2645   Projections& rProj = GetDocument()->getProjections();
2646   ParallelRaysums parallel (&rProj, iThetaRange);
2647   PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
2648   PlotFile& rPlot = pPlotDoc->getPlotFile();
2649   ParallelRaysums::CoordinateContainer& coordContainer = parallel.getCoordinates();
2650   double* pdT = new double [parallel.getNumCoordinates()];
2651   double* pdTheta = new double [parallel.getNumCoordinates()];
2652   
2653   for (int i = 0; i < parallel.getNumCoordinates(); i++) {
2654     pdT[i] = coordContainer[i]->m_dT;
2655     pdTheta[i] = coordContainer[i]->m_dTheta;
2656   }
2657   rPlot.setCurveSize (2, parallel.getNumCoordinates(), true);
2658   rPlot.addEzsetCommand ("title T-Theta Sampling");
2659   rPlot.addEzsetCommand ("xlabel T");
2660   rPlot.addEzsetCommand ("ylabel Theta");
2661   rPlot.addEzsetCommand ("curve 1");
2662   if (rProj.nDet() < 50 && rProj.nView() < 50)
2663     rPlot.addEzsetCommand ("symbol 1"); // x symbol
2664   else
2665     rPlot.addEzsetCommand ("symbol 6"); // point symbol
2666   rPlot.addEzsetCommand ("noline");
2667   rPlot.addColumn (0, pdT);
2668   rPlot.addColumn (1, pdTheta);
2669   delete pdT;
2670   delete pdTheta;
2671   if (theApp->getAskDeleteNewDocs())
2672     pPlotDoc->Modify (true);
2673   pPlotDoc->getView()->getFrame()->Show(true);
2674   pPlotDoc->UpdateAllViews ();
2675   pPlotDoc->Activate();
2676 }
2677
2678
2679 void
2680 ProjectionFileView::OnPlotHistogram (wxCommandEvent& event)
2681
2682   Projections& rProj = GetDocument()->getProjections();
2683   int nDet = rProj.nDet();
2684   int nView = rProj.nView();
2685   
2686   if (nDet < 1 || nView < 1)
2687     return;
2688
2689   PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
2690   if (! pPlotDoc) {
2691     sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
2692     return;
2693   }
2694     
2695   DetectorValue* pdDetval = rProj.getDetectorArray(0).detValues();
2696   double dMin = pdDetval[0], dMax = pdDetval[0];
2697
2698   for (int iv = 0; iv < nView; iv++) {
2699     pdDetval = rProj.getDetectorArray(iv).detValues();
2700     for (int id = 0; id < nDet; id++) {
2701       double dV = pdDetval[id];
2702       if (dV < dMin)
2703         dMin = dV;
2704       else if (dV > dMax)
2705         dMax = dV;
2706     }
2707   }
2708
2709   double* pX = new double [NUMBER_HISTOGRAM_BINS];
2710   double* pY = new double [NUMBER_HISTOGRAM_BINS];
2711   double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
2712     
2713   for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
2714     pX[i] = dMin + (i + 0.5) * dBinWidth;
2715     pY[i] = 0;
2716   }
2717   for (int j = 0; j < nView; j++) {
2718     pdDetval = rProj.getDetectorArray(j).detValues();
2719     for (int id = 0; id < nDet; id++) {
2720       int iBin = nearest<int> ((pdDetval[id] - dMin) / dBinWidth);
2721       if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
2722         pY[iBin] += 1;
2723     }
2724   }      
2725   PlotFile& rPlotFile = pPlotDoc->getPlotFile();
2726   std::ostringstream os;
2727   os << "Histogram";
2728   std::string title("title ");
2729   title += os.str();
2730   rPlotFile.addEzsetCommand (title.c_str());
2731   rPlotFile.addEzsetCommand ("xlabel Detector Value");
2732   rPlotFile.addEzsetCommand ("ylabel Count");
2733   rPlotFile.addEzsetCommand ("box");
2734   rPlotFile.addEzsetCommand ("grid");
2735   rPlotFile.setCurveSize (2, NUMBER_HISTOGRAM_BINS);
2736   rPlotFile.addColumn (0, pX);
2737   rPlotFile.addColumn (1, pY);
2738   rPlotFile.addDescription (rProj.remark());
2739   os << " plot of " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
2740   *theApp->getLog() << os.str().c_str() << "\n";
2741   rPlotFile.addDescription (os.str().c_str());
2742   delete pX;
2743   delete pY;
2744   if (theApp->getAskDeleteNewDocs())
2745     pPlotDoc->Modify (true);
2746   pPlotDoc->getView()->getFrame()->Show(true);
2747   pPlotDoc->UpdateAllViews ();
2748   pPlotDoc->Activate();
2749 }
2750
2751
2752 void
2753 ProjectionFileView::OnConvertParallel (wxCommandEvent& event)
2754 {
2755   Projections& rProj = GetDocument()->getProjections();
2756   if (rProj.geometry() == Scanner::GEOMETRY_PARALLEL) {
2757     wxMessageBox ("Projections are already parallel", "Error");
2758     return;
2759   }
2760   wxProgressDialog dlgProgress (wxString("Convert to Parallel"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2761   Projections* pProjNew = rProj.interpolateToParallel();
2762   ProjectionFileDocument* pProjDocNew = theApp->newProjectionDoc();
2763   pProjDocNew->setProjections (pProjNew);  
2764   
2765   if (ProjectionFileView* projView = pProjDocNew->getView()) {
2766     projView->OnUpdate (projView, NULL);
2767     if (projView->getCanvas())
2768       projView->getCanvas()->SetClientSize (pProjNew->nDet(), pProjNew->nView());
2769     if (wxFrame* pFrame = projView->getFrame()) {
2770       pFrame->Show(true);
2771       pFrame->SetFocus();
2772       pFrame->Raise();
2773     }
2774     GetDocumentManager()->ActivateView (projView, true, false);
2775   }
2776   if (theApp->getAskDeleteNewDocs())
2777     pProjDocNew-> Modify(true);
2778   pProjDocNew->UpdateAllViews (this);
2779   pProjDocNew->getView()->setInitialClientSize();
2780   pProjDocNew->Activate();
2781 }
2782
2783 void
2784 ProjectionFileView::OnReconstructFourier (wxCommandEvent& event)
2785 {
2786   Projections& rProj = GetDocument()->getProjections();
2787   DialogGetConvertPolarParameters dialogPolar (getFrameForChild(), "Fourier Reconstruction", m_iDefaultPolarNX, m_iDefaultPolarNY,
2788     m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad, IDH_DLG_RECON_FOURIER);
2789   if (dialogPolar.ShowModal() == wxID_OK) {
2790     wxProgressDialog dlgProgress (wxString("Reconstruction Fourier"), wxString("Reconstruction Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
2791     wxString strInterpolation (dialogPolar.getInterpolationName());
2792     m_iDefaultPolarNX = dialogPolar.getXSize();
2793     m_iDefaultPolarNY = dialogPolar.getYSize();
2794     m_iDefaultPolarZeropad = dialogPolar.getZeropad();
2795     ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
2796     
2797     m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
2798     if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
2799       delete pIF;
2800       *theApp->getLog() << "Error converting to polar\n";
2801       return;
2802     }
2803 #ifdef HAVE_FFT
2804     pIF->ifft(*pIF);
2805 #endif
2806     pIF->magnitude(*pIF);
2807     Fourier::shuffleFourierToNaturalOrder (*pIF);
2808
2809     ImageFileDocument* pPolarDoc = theApp->newImageDoc();
2810     if (! pPolarDoc) {
2811       sys_error (ERR_SEVERE, "Unable to create image file");
2812       return;
2813     }
2814     pPolarDoc->setImageFile (pIF);
2815     pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
2816     std::ostringstream os;
2817     os << "Reconstruct Fourier " << GetFrame()->GetTitle().c_str() << ": xSize=" 
2818       << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation=" 
2819       << strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
2820     *theApp->getLog() << os.str().c_str() << "\n";
2821     pIF->labelAdd (os.str().c_str());
2822     if (theApp->getAskDeleteNewDocs())
2823       pPolarDoc->Modify (true);
2824     pPolarDoc->UpdateAllViews ();
2825     pPolarDoc->getView()->setInitialClientSize();
2826     pPolarDoc->Activate();
2827   }
2828 }
2829
2830 void
2831 ProjectionFileView::OnReconstructFBPRebin (wxCommandEvent& event)
2832 {
2833   Projections& rProj = GetDocument()->getProjections();
2834   doReconstructFBP (rProj, true);
2835 }
2836
2837 void
2838 ProjectionFileView::OnReconstructFBP (wxCommandEvent& event)
2839 {
2840   Projections& rProj = GetDocument()->getProjections();
2841   doReconstructFBP (rProj, false);
2842 }
2843
2844 void
2845 ProjectionFileView::doReconstructFBP (const Projections& rProj, bool bRebinToParallel)
2846 {
2847   ReconstructionROI defaultROI;
2848   defaultROI.m_dXMin = -rProj.phmLen() / 2;
2849   defaultROI.m_dXMax = defaultROI.m_dXMin + rProj.phmLen();
2850   defaultROI.m_dYMin = -rProj.phmLen() / 2;
2851   defaultROI.m_dYMax = defaultROI.m_dYMin + rProj.phmLen();
2852   
2853   DialogGetReconstructionParameters dialogReconstruction (getFrameForChild(), m_iDefaultNX, m_iDefaultNY, 
2854     m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration, 
2855     m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector, 
2856     m_iDefaultTrace,  &defaultROI);
2857   
2858   int retVal = dialogReconstruction.ShowModal();
2859   if (retVal != wxID_OK)
2860     return;
2861   
2862   m_iDefaultNX = dialogReconstruction.getXSize();
2863   m_iDefaultNY = dialogReconstruction.getYSize();
2864   wxString optFilterName = dialogReconstruction.getFilterName();
2865   m_iDefaultFilter = SignalFilter::convertFilterNameToID (optFilterName.c_str());
2866   m_dDefaultFilterParam = dialogReconstruction.getFilterParam();
2867   wxString optFilterMethodName = dialogReconstruction.getFilterMethodName();
2868   m_iDefaultFilterMethod = ProcessSignal::convertFilterMethodNameToID(optFilterMethodName.c_str());
2869   m_iDefaultZeropad = dialogReconstruction.getZeropad();
2870   wxString optFilterGenerationName = dialogReconstruction.getFilterGenerationName();
2871   m_iDefaultFilterGeneration = ProcessSignal::convertFilterGenerationNameToID (optFilterGenerationName.c_str());
2872   wxString optInterpName = dialogReconstruction.getInterpName();
2873   m_iDefaultInterpolation = Backprojector::convertInterpNameToID (optInterpName.c_str());
2874   m_iDefaultInterpParam = dialogReconstruction.getInterpParam();
2875   wxString optBackprojectName = dialogReconstruction.getBackprojectName();
2876   m_iDefaultBackprojector = Backprojector::convertBackprojectNameToID (optBackprojectName.c_str());
2877   m_iDefaultTrace = dialogReconstruction.getTrace();
2878   dialogReconstruction.getROI (&defaultROI);
2879   
2880   if (m_iDefaultNX <= 0 && m_iDefaultNY <= 0) 
2881     return;
2882   
2883   std::ostringstream os;
2884   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();
2885   if (bRebinToParallel)
2886     os << "; Interpolate to Parallel";
2887   
2888   Timer timerRecon;
2889   ImageFile* pImageFile = NULL;
2890   if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
2891     pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
2892     Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(), 
2893       m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), 
2894       optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, 
2895       &defaultROI, bRebinToParallel);
2896     
2897     ReconstructDialog* pDlgReconstruct = new ReconstructDialog (*pReconstructor, rProj, *pImageFile, m_iDefaultTrace, getFrameForChild());
2898     for (int iView = 0; iView < rProj.nView(); iView++) {
2899       ::wxYield();
2900       if (pDlgReconstruct->isCancelled() || ! pDlgReconstruct->reconstructView (iView, true)) {
2901         delete pDlgReconstruct;
2902         delete pReconstructor;
2903         return;
2904       }
2905       ::wxYield();
2906       ::wxYield();
2907       while (pDlgReconstruct->isPaused()) {
2908         ::wxYield();
2909         ::wxUsleep(50);
2910       }
2911     }
2912     pReconstructor->postProcessing();
2913     delete pDlgReconstruct;
2914     delete pReconstructor;
2915   } else {
2916 #if HAVE_WXTHREADS
2917     if (theApp->getUseBackgroundTasks()) {
2918       ReconstructorSupervisorThread* pReconstructor = new ReconstructorSupervisorThread (this, m_iDefaultNX, 
2919         m_iDefaultNY, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(), 
2920         m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam, 
2921         optBackprojectName.c_str(), os.str().c_str(), &defaultROI, bRebinToParallel);
2922       if (pReconstructor->Create() != wxTHREAD_NO_ERROR) {
2923         sys_error (ERR_SEVERE, "Error creating reconstructor thread");
2924         delete pReconstructor;
2925         return;
2926       }
2927       pReconstructor->SetPriority (60);
2928       pReconstructor->Run();
2929       return;
2930     } else 
2931 #endif
2932     {
2933       pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
2934       wxProgressDialog dlgProgress (wxString("Reconstruction"), wxString("Reconstruction Progress"), rProj.nView() + 1, getFrameForChild(), wxPD_CAN_ABORT );
2935       Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(), 
2936         m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), 
2937         optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, 
2938         &defaultROI, bRebinToParallel);
2939       
2940       for (int iView = 0; iView < rProj.nView(); iView++) {
2941         pReconstructor->reconstructView (iView, 1);
2942         if ((iView + 1) % ITER_PER_UPDATE == 0) 
2943           if (! dlgProgress.Update (iView + 1)) {
2944             delete pReconstructor;
2945             return; // don't make new window, thread will do this
2946           }
2947       }
2948       pReconstructor->postProcessing();
2949       delete pReconstructor;
2950     }
2951   }
2952   ImageFileDocument* pReconDoc = theApp->newImageDoc();
2953   if (! pReconDoc) {
2954     sys_error (ERR_SEVERE, "Unable to create image file");
2955     return;
2956   }
2957   *theApp->getLog() << os.str().c_str() << "\n";
2958   pImageFile->labelAdd (rProj.getLabel());
2959   pImageFile->labelAdd (os.str().c_str(), timerRecon.timerEnd());    
2960
2961   pReconDoc->setImageFile (pImageFile);
2962   if (theApp->getAskDeleteNewDocs())
2963     pReconDoc->Modify (true);
2964   pReconDoc->UpdateAllViews();
2965   pReconDoc->getView()->setInitialClientSize();
2966   pReconDoc->Activate();
2967 }
2968
2969
2970 void
2971 ProjectionFileView::OnArtifactReduction (wxCommandEvent& event)
2972 {
2973 }
2974
2975
2976 ProjectionFileCanvas* 
2977 ProjectionFileView::CreateCanvas (wxFrame *parent)
2978 {
2979   ProjectionFileCanvas* pCanvas;
2980   int width, height;
2981   parent->GetClientSize(&width, &height);
2982   
2983   pCanvas = new ProjectionFileCanvas (this, parent, wxPoint(-1,-1), wxSize(width, height), 0);
2984   
2985   pCanvas->SetScrollbars(20, 20, 50, 50);
2986   pCanvas->SetBackgroundColour(*wxWHITE);
2987   pCanvas->Clear();
2988   
2989   return pCanvas;
2990 }
2991
2992 #if CTSIM_MDI
2993 wxDocMDIChildFrame*
2994 #else
2995 wxDocChildFrame*
2996 #endif
2997 ProjectionFileView::CreateChildFrame(wxDocument *doc, wxView *view)
2998 {
2999 #ifdef CTSIM_MDI
3000   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
3001 #else
3002   wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
3003 #endif
3004   theApp->setIconForFrame (subframe);
3005   
3006   m_pFileMenu = new wxMenu;
3007   
3008   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3009   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3010   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3011   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3012   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3013   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3014   
3015   m_pFileMenu->AppendSeparator();
3016   m_pFileMenu->Append(PJMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
3017   
3018   m_pFileMenu->AppendSeparator();
3019   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3020   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3021   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3022   m_pFileMenu->AppendSeparator();
3023   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3024   m_pFileMenu->AppendSeparator();
3025   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3026   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3027   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3028   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3029   
3030   wxMenu *convert_menu = new wxMenu;
3031   convert_menu->Append (PJMENU_CONVERT_RECTANGULAR, "&Rectangular Image");
3032   convert_menu->Append (PJMENU_CONVERT_POLAR, "&Polar Image...\tCtrl-L");
3033   convert_menu->Append (PJMENU_CONVERT_FFT_POLAR, "FF&T->Polar Image...\tCtrl-T");
3034   convert_menu->AppendSeparator();
3035   convert_menu->Append (PJMENU_CONVERT_PARALLEL, "&Interpolate to Parallel");
3036   
3037   //  wxMenu* filter_menu = new wxMenu;
3038   //  filter_menu->Append (PJMENU_ARTIFACT_REDUCTION, "&Artifact Reduction");
3039   
3040   wxMenu* analyze_menu = new wxMenu;
3041   analyze_menu->Append (PJMENU_PLOT_HISTOGRAM, "&Plot Histogram");
3042   analyze_menu->Append (PJMENU_PLOT_TTHETA_SAMPLING, "Plot T-T&heta Sampling...\tCtrl-H");
3043
3044   wxMenu *reconstruct_menu = new wxMenu;
3045   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP, "&Filtered Backprojection...\tCtrl-R", "Reconstruct image using filtered backprojection");
3046   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FBP_REBIN, "Filtered &Backprojection (Rebin to Parallel)...\tCtrl-B", "Reconstruct image using filtered backprojection");
3047   // still buggy
3048   //   reconstruct_menu->Append (PJMENU_RECONSTRUCT_FOURIER, "&Fourier...\tCtrl-E", "Reconstruct image using inverse Fourier");
3049   
3050   wxMenu *help_menu = new wxMenu;
3051   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3052   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3053   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3054   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3055   
3056   wxMenuBar *menu_bar = new wxMenuBar;
3057   
3058   menu_bar->Append (m_pFileMenu, "&File");
3059   menu_bar->Append (convert_menu, "&Convert");
3060   //  menu_bar->Append (filter_menu, "Fi&lter");
3061   menu_bar->Append (analyze_menu, "&Analyze");
3062   menu_bar->Append (reconstruct_menu, "&Reconstruct");
3063   menu_bar->Append (help_menu, "&Help");
3064   
3065   subframe->SetMenuBar(menu_bar);  
3066   subframe->Centre(wxBOTH);
3067   
3068   wxAcceleratorEntry accelEntries[7];
3069   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('L'), PJMENU_CONVERT_POLAR);
3070   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('T'), PJMENU_CONVERT_FFT_POLAR);
3071   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('R'), PJMENU_RECONSTRUCT_FBP);
3072   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('B'), PJMENU_RECONSTRUCT_FBP_REBIN);
3073   accelEntries[4].Set (wxACCEL_CTRL, static_cast<int>('E'), PJMENU_RECONSTRUCT_FOURIER);
3074   accelEntries[5].Set (wxACCEL_CTRL, static_cast<int>('I'), PJMENU_FILE_PROPERTIES);
3075   accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('H'), PJMENU_PLOT_TTHETA_SAMPLING);
3076   wxAcceleratorTable accelTable (7, accelEntries);
3077   subframe->SetAcceleratorTable (accelTable);
3078   
3079   return subframe;
3080 }
3081
3082
3083 bool 
3084 ProjectionFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
3085 {
3086   m_pFrame = CreateChildFrame(doc, this);
3087   SetFrame(m_pFrame);
3088   m_pCanvas = CreateCanvas (m_pFrame);
3089   m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
3090   m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
3091   m_pFrame->SetTitle ("ProjectionFileView");
3092
3093   m_pFrame->Show(true);
3094   Activate(true);
3095   
3096   return true;
3097 }
3098
3099 void 
3100 ProjectionFileView::OnDraw (wxDC* dc)
3101 {
3102   if (m_pBitmap && m_pBitmap->Ok())
3103     dc->DrawBitmap (*m_pBitmap, 0, 0, false);
3104 }
3105
3106
3107 void 
3108 ProjectionFileView::setInitialClientSize ()
3109 {
3110   if (m_pFrame && m_pCanvas) {
3111     wxSize bestSize = m_pCanvas->GetBestSize();
3112
3113     m_pFrame->SetClientSize (bestSize);
3114     m_pFrame->Show (true);
3115     m_pFrame->SetFocus();
3116   }
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     if (m_pBitmap) {
3159       delete m_pBitmap;
3160       m_pBitmap = NULL;
3161     }
3162     m_pBitmap = new wxBitmap (image);
3163     delete imageData;
3164   }
3165   
3166     m_pCanvas->SetScrollbars(20, 20, nDet/20, nView/20);
3167     m_pCanvas->SetBackgroundColour(*wxWHITE);
3168
3169     if (m_pCanvas)
3170       m_pCanvas->Refresh();
3171 }
3172
3173 bool 
3174 ProjectionFileView::OnClose (bool deleteWindow)
3175 {
3176   //GetDocumentManager()->ActivateView (this, false, true);
3177   if (! GetDocument() || ! GetDocument()->Close())
3178     return false;
3179   
3180   Activate(false);
3181   if (m_pCanvas) {
3182         m_pCanvas->setView(NULL);
3183     m_pCanvas = NULL;
3184   }
3185   wxString s(wxTheApp->GetAppName());
3186   if (m_pFrame)
3187     m_pFrame->SetTitle(s);
3188   
3189   SetFrame(NULL);
3190   
3191   if (deleteWindow) {
3192     delete m_pFrame;
3193     m_pFrame = NULL;
3194     if (GetDocument() && GetDocument()->getBadFileOpen())
3195       ::wxYield();  // wxWindows bug workaround
3196   }
3197   
3198   return true;
3199 }
3200
3201
3202
3203 // PlotFileCanvas
3204 PlotFileCanvas::PlotFileCanvas (PlotFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
3205   : wxScrolledWindow(frame, -1, pos, size, style), m_pView(v)
3206 {
3207 }
3208
3209 PlotFileCanvas::~PlotFileCanvas ()
3210 {
3211 }
3212
3213 wxSize
3214 PlotFileCanvas::GetBestSize() const
3215 {
3216   return wxSize (500, 300);
3217 }
3218
3219
3220 void 
3221 PlotFileCanvas::OnDraw(wxDC& dc)
3222 {
3223   if (m_pView)
3224     m_pView->OnDraw(& dc);
3225 }
3226
3227
3228 // PlotFileView
3229
3230 IMPLEMENT_DYNAMIC_CLASS(PlotFileView, wxView)
3231
3232 BEGIN_EVENT_TABLE(PlotFileView, wxView)
3233 EVT_MENU(PLOTMENU_FILE_PROPERTIES, PlotFileView::OnProperties)
3234 EVT_MENU(PLOTMENU_VIEW_SCALE_MINMAX, PlotFileView::OnScaleMinMax)
3235 EVT_MENU(PLOTMENU_VIEW_SCALE_AUTO, PlotFileView::OnScaleAuto)
3236 EVT_MENU(PLOTMENU_VIEW_SCALE_FULL, PlotFileView::OnScaleFull)
3237 END_EVENT_TABLE()
3238
3239 PlotFileView::PlotFileView() 
3240 : wxView(), m_pFrame(0), m_pCanvas(0), m_pEZPlot(0), m_pFileMenu(0), 
3241   m_bMinSpecified(false), m_bMaxSpecified(false)
3242 {
3243 }
3244
3245 PlotFileView::~PlotFileView()
3246 {
3247   if (m_pEZPlot)
3248     delete m_pEZPlot;
3249   
3250   GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);  
3251   GetDocumentManager()->ActivateView(this, FALSE, TRUE);
3252 }
3253
3254 void
3255 PlotFileView::OnProperties (wxCommandEvent& event)
3256 {
3257   const PlotFile& rPlot = GetDocument()->getPlotFile();
3258   std::ostringstream os;
3259   os << "Columns: " << rPlot.getNumColumns() << ", Records: " << rPlot.getNumRecords() << "\n";
3260   rPlot.printHeadersBrief (os);
3261   *theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<<\n";
3262   wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(), "Plot File Properties", wxOK | wxICON_INFORMATION);
3263   dialogMsg.ShowModal();
3264   GetDocument()->Activate();
3265 }
3266
3267
3268 void 
3269 PlotFileView::OnScaleAuto (wxCommandEvent& event)
3270 {
3271   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3272   double min, max, mean, mode, median, stddev;
3273   rPlotFile.statistics (1, min, max, mean, mode, median, stddev);
3274   DialogAutoScaleParameters dialogAutoScale (getFrameForChild(), mean, mode, median, stddev, m_dAutoScaleFactor);
3275   int iRetVal = dialogAutoScale.ShowModal();
3276   if (iRetVal == wxID_OK) {
3277     m_bMinSpecified = true;
3278     m_bMaxSpecified = true;
3279     double dMin, dMax;
3280     if (dialogAutoScale.getMinMax (&dMin, &dMax)) {
3281       m_dMinPixel = dMin;
3282       m_dMaxPixel = dMax;
3283       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
3284       OnUpdate (this, NULL);
3285     }
3286   }
3287   GetDocument()->Activate();
3288 }
3289
3290 void 
3291 PlotFileView::OnScaleMinMax (wxCommandEvent& event)
3292 {
3293   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3294   double min;
3295   double max;
3296   
3297   if (! m_bMinSpecified || ! m_bMaxSpecified) {
3298     if (! rPlotFile.getMinMax (1, min, max)) {
3299       *theApp->getLog() << "Error: unable to find Min/Max\n";
3300       return;
3301     }
3302   }
3303   
3304   if (m_bMinSpecified)
3305     min = m_dMinPixel;
3306   if (m_bMaxSpecified)
3307     max = m_dMaxPixel;
3308   
3309   DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Y-axis Minimum & Maximum", min, max);
3310   int retVal = dialogMinMax.ShowModal();
3311   if (retVal == wxID_OK) {
3312     m_bMinSpecified = true;
3313     m_bMaxSpecified = true;
3314     m_dMinPixel = dialogMinMax.getMinimum();
3315     m_dMaxPixel = dialogMinMax.getMaximum();
3316     OnUpdate (this, NULL);
3317   }
3318   GetDocument()->Activate();
3319 }
3320
3321 void 
3322 PlotFileView::OnScaleFull (wxCommandEvent& event)
3323 {
3324   if (m_bMinSpecified || m_bMaxSpecified) {
3325     m_bMinSpecified = false;
3326     m_bMaxSpecified = false;
3327     OnUpdate (this, NULL);
3328   }
3329   GetDocument()->Activate();
3330 }
3331
3332
3333 PlotFileCanvas* 
3334 PlotFileView::CreateCanvas (wxFrame* parent)
3335 {
3336   PlotFileCanvas* pCanvas;
3337   
3338   pCanvas = new PlotFileCanvas (this, parent, wxPoint(-1,-1), wxSize(-1,-1), 0);  
3339   pCanvas->SetBackgroundColour(*wxWHITE);
3340   pCanvas->Clear();
3341   
3342   return pCanvas;
3343 }
3344
3345 #if CTSIM_MDI
3346 wxDocMDIChildFrame*
3347 #else
3348 wxDocChildFrame*
3349 #endif
3350 PlotFileView::CreateChildFrame(wxDocument *doc, wxView *view)
3351 {
3352 #ifdef CTSIM_MDI
3353   wxDocMDIChildFrame *subframe = new wxDocMDIChildFrame (doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
3354 #else
3355   wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
3356 #endif
3357   theApp->setIconForFrame (subframe);
3358   
3359   m_pFileMenu = new wxMenu;
3360   
3361   m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
3362   m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
3363   m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
3364   m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
3365   m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
3366   m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
3367   
3368   m_pFileMenu->AppendSeparator();
3369   m_pFileMenu->Append(PLOTMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
3370   
3371   m_pFileMenu->AppendSeparator();
3372   m_pFileMenu->Append(wxID_PRINT, "&Print...");
3373   m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
3374   m_pFileMenu->Append(wxID_PREVIEW, "Print Pre&view");
3375   m_pFileMenu->AppendSeparator();
3376   m_pFileMenu->Append(MAINMENU_IMPORT, "&Import...\tCtrl-M");
3377   m_pFileMenu->AppendSeparator();
3378   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3379   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3380   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3381   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3382   
3383   wxMenu *view_menu = new wxMenu;
3384   view_menu->Append(PLOTMENU_VIEW_SCALE_MINMAX, "Display Scale &Set...\tCtrl-E");
3385   view_menu->Append(PLOTMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
3386   view_menu->Append(PLOTMENU_VIEW_SCALE_FULL, "Display &Full Scale\tCtrl-U");
3387   
3388   wxMenu *help_menu = new wxMenu;
3389   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3390   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3391   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3392   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3393   
3394   wxMenuBar *menu_bar = new wxMenuBar;
3395   
3396   menu_bar->Append(m_pFileMenu, "&File");
3397   menu_bar->Append(view_menu, "&View");
3398   menu_bar->Append(help_menu, "&Help");
3399   
3400   subframe->SetMenuBar(menu_bar);
3401   subframe->Centre(wxBOTH);
3402   
3403   wxAcceleratorEntry accelEntries[4];
3404   accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('E'), PLOTMENU_VIEW_SCALE_MINMAX);
3405   accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('A'), PLOTMENU_VIEW_SCALE_AUTO);
3406   accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('U'), PLOTMENU_VIEW_SCALE_FULL);
3407   accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('I'), PLOTMENU_FILE_PROPERTIES);
3408   wxAcceleratorTable accelTable (4, accelEntries);
3409   subframe->SetAcceleratorTable (accelTable);
3410   
3411   return subframe;
3412 }
3413
3414
3415 bool 
3416 PlotFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
3417 {
3418   m_bMinSpecified = false;
3419   m_bMaxSpecified = false;
3420   m_dAutoScaleFactor = 1.;
3421   
3422   m_pFrame = CreateChildFrame(doc, this);
3423   SetFrame(m_pFrame);
3424   m_pCanvas = CreateCanvas (m_pFrame);
3425   m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
3426   m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
3427   m_pFrame->SetTitle ("Plot File");
3428   
3429   m_pFrame->Show(true);
3430   Activate(true);
3431   
3432   return true;
3433 }
3434
3435 void 
3436 PlotFileView::setInitialClientSize ()
3437 {
3438   if (m_pFrame && m_pCanvas) {
3439     wxSize bestSize = m_pCanvas->GetBestSize();
3440     
3441     m_pFrame->SetClientSize (bestSize);
3442     m_pFrame->Show (true);
3443     m_pFrame->SetFocus();
3444   }
3445 }  
3446
3447
3448 void 
3449 PlotFileView::OnDraw (wxDC* dc)
3450 {
3451   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3452   const int iNColumns = rPlotFile.getNumColumns();
3453   const int iNRecords = rPlotFile.getNumRecords();
3454   
3455   if (iNColumns > 0 && iNRecords > 0) {
3456     int xsize, ysize;
3457     m_pCanvas->GetClientSize (&xsize, &ysize);
3458     SGPDriver driver (dc, xsize, ysize);
3459     SGP sgp (driver);
3460     if (m_pEZPlot)
3461       m_pEZPlot->plot (&sgp);
3462   }
3463 }
3464
3465
3466 void 
3467 PlotFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
3468 {
3469   const PlotFile& rPlotFile = GetDocument()->getPlotFile();
3470   const int iNColumns = rPlotFile.getNumColumns();
3471   const int iNRecords = rPlotFile.getNumRecords();
3472   const bool bScatterPlot = rPlotFile.getIsScatterPlot();
3473   
3474   if (iNColumns > 0 && iNRecords > 0) {
3475     if (m_pEZPlot)
3476       delete m_pEZPlot;
3477     m_pEZPlot = new EZPlot;
3478     
3479     for (unsigned int iEzset = 0; iEzset < rPlotFile.getNumEzsetCommands(); iEzset++)
3480       m_pEZPlot->ezset (rPlotFile.getEzsetCommand (iEzset));
3481     
3482     if (m_bMinSpecified) {
3483       std::ostringstream os;
3484       os << "ymin " << m_dMinPixel;
3485       m_pEZPlot->ezset (os.str());
3486     }
3487     
3488     if (m_bMaxSpecified) {
3489       std::ostringstream os;
3490       os << "ymax " << m_dMaxPixel;
3491       m_pEZPlot->ezset (os.str());
3492     }
3493     
3494     m_pEZPlot->ezset("box");
3495     m_pEZPlot->ezset("grid");
3496     
3497     double* pdX = new double [iNRecords];
3498     double* pdY = new double [iNRecords];
3499     if (! bScatterPlot) {
3500       rPlotFile.getColumn (0, pdX);
3501       
3502       for (int iCol = 1; iCol < iNColumns; iCol++) {
3503         rPlotFile.getColumn (iCol, pdY);
3504         m_pEZPlot->addCurve (pdX, pdY, iNRecords);
3505       }
3506     } else {
3507       rPlotFile.getColumn (0, pdX);
3508       rPlotFile.getColumn (1, pdY);
3509       m_pEZPlot->addCurve (pdX, pdY, iNRecords);
3510     }
3511     delete pdX;
3512     delete pdY;
3513   }
3514   
3515   if (m_pCanvas)
3516     m_pCanvas->Refresh();
3517 }
3518
3519 bool 
3520 PlotFileView::OnClose (bool deleteWindow)
3521 {
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(-1,-1), 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(-1,-1), 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   m_pFileMenu->AppendSeparator();
3635   m_pFileMenu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
3636   m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
3637   GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
3638   GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
3639   
3640   wxMenu *help_menu = new wxMenu;
3641   help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
3642   help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
3643   help_menu->Append (IDH_QUICKSTART, "&Quick Start");
3644   help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
3645   
3646   wxMenuBar *menu_bar = new wxMenuBar;
3647   
3648   menu_bar->Append(m_pFileMenu, "&File");
3649   menu_bar->Append(help_menu, "&Help");
3650   
3651   subframe->SetMenuBar(menu_bar);
3652   subframe->Centre(wxBOTH);
3653   
3654   return subframe;
3655 }
3656
3657
3658 // Define a constructor for my text subwindow
3659 TextFileCanvas::TextFileCanvas (TextFileView* v, wxFrame* frame, const wxPoint& pos, const wxSize& size, long style)
3660 : wxTextCtrl (frame, -1, "", pos, size, style), m_pView(v)
3661 {
3662 }
3663
3664 TextFileCanvas::~TextFileCanvas ()
3665 {
3666   m_pView = NULL;
3667 }
3668
3669 wxSize
3670 TextFileCanvas::GetBestSize() const
3671 {
3672   int xSize, ySize;
3673   theApp->getMainFrame()->GetClientSize (&xSize, &ySize);
3674   xSize = maxValue<int> (xSize, ySize);
3675 #ifdef CTSIM_MDI
3676   ySize = xSize = (xSize / 4);
3677 #else
3678   ySize = xSize;
3679 #endif
3680   return wxSize (xSize, ySize);
3681 }