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