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