r191: *** empty log message ***
[ctsim.git] / src / views.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          view.cpp
5 **   Purpose:       View & Canvas routines for CTSim program
6 **   Programmer:    Kevin Rosenberg
7 **   Date Started:  July 2000
8 **
9 **  This is part of the CTSim program
10 **  Copyright (C) 1983-2000 Kevin Rosenberg
11 **
12 **  $Id: views.cpp,v 1.22 2000/09/07 01:28:33 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 #ifdef __GNUG__
29 // #pragma implementation
30 #endif
31
32 // For compilers that support precompilation, includes "wx/wx.h".
33 #include "wx/wxprec.h"
34
35 #ifdef __BORLANDC__
36 #pragma hdrstop
37 #endif
38
39 #ifndef WX_PRECOMP
40 #include "wx/wx.h"
41 #endif
42
43 #if !wxUSE_DOC_VIEW_ARCHITECTURE
44 #error You must set wxUSE_DOC_VIEW_ARCHITECTURE to 1 in setup.h!
45 #endif
46
47 #include "wx/image.h"
48 #include "wx/progdlg.h"
49
50 #include "ct.h"
51 #include "ctsim.h"
52 #include "docs.h"
53 #include "views.h"
54 #include "dialogs.h"
55 #include "dlgprojections.h"
56 #include "dlgreconstruct.h"
57 #include <sstream>
58 #include "backprojectors.h"
59 #include "reconstruct.h"
60 #include "timer.h"
61
62 // ImageFileCanvas
63
64 BEGIN_EVENT_TABLE(ImageFileCanvas, wxScrolledWindow)
65     EVT_MOUSE_EVENTS(ImageFileCanvas::OnMouseEvent)
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)
71 {
72     m_pView = v;
73 }
74
75 void 
76 ImageFileCanvas::OnDraw(wxDC& dc)
77 {
78     if (m_pView)
79         m_pView->OnDraw(& dc);
80 }
81
82 void 
83 ImageFileCanvas::OnMouseEvent(wxMouseEvent& event)
84 {
85     if (! m_pView)
86         return;
87     
88     wxClientDC dc(this);
89     PrepareDC(dc);
90     
91     wxPoint pt(event.GetLogicalPosition(dc));
92
93     if (event.LeftIsDown()) {
94         const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
95         ImageFileArrayConst v = rIF.getArray();
96         int nx = rIF.nx();
97         int ny = rIF.ny();
98
99         if (pt.x >= 0 && pt.x < nx && pt.y >= 0 & pt.y < ny) {
100           ostringstream os;
101           os << "Image value (" << pt.x << "," << pt.y << ") = " << v[pt.x][ny - 1 - pt.y] << "\n";
102             *theApp->getLog() << os.str().c_str();
103         } else
104             *theApp->getLog() << "Mouse out of image range (" << pt.x << "," << pt.y << ")\n";
105             
106     }
107 }
108
109
110 // ImageFileView
111
112 IMPLEMENT_DYNAMIC_CLASS(ImageFileView, wxView)
113
114 BEGIN_EVENT_TABLE(ImageFileView, wxView)
115   EVT_MENU(IFMENU_FILE_PROPERTIES, ImageFileView::OnProperties)
116   EVT_MENU(IFMENU_VIEW_SCALE_MINMAX, ImageFileView::OnScaleMinMax)
117   EVT_MENU(IFMENU_VIEW_SCALE_AUTO, ImageFileView::OnScaleAuto)
118 END_EVENT_TABLE()
119
120 ImageFileView::ImageFileView(void) 
121   : wxView(), m_canvas(NULL), m_frame(NULL), m_bMinSpecified(false), m_bMaxSpecified(false)
122 {
123 }
124
125 ImageFileView::~ImageFileView(void)
126 {
127 }
128
129 void
130 ImageFileView::OnProperties (wxCommandEvent& event)
131 {
132   double min, max, mean, mode, median, stddev;
133   const ImageFile& rIF = GetDocument()->getImageFile();
134   if (rIF.nx() == 0 || rIF.ny() == 0)
135     *theApp->getLog() << "Properties: empty imagefile\n";
136   else {
137     const string& rFilename = rIF.getFilename();
138     rIF.statistics (min, max, mean, mode, median, stddev);
139     ostringstream os;
140     os << "file: " << rFilename << "\nmin: "<<min<<"\nmax: "<<max<<"\nmean: "<<mean<<"\nmode: "<<mode<<"\nstddev: "<<stddev << "\n";
141     *theApp->getLog() << os.str().c_str();
142     wxMessageDialog dialogMsg (m_frame, os.str().c_str(), "Imagefile Properties", wxOK | wxICON_INFORMATION);
143     dialogMsg.ShowModal();
144   }
145 }
146
147 void 
148 ImageFileView::OnScaleAuto (wxCommandEvent& event)
149 {
150     const ImageFile& rIF = GetDocument()->getImageFile();
151     DialogAutoScaleParameters dialogAutoScale (m_frame, rIF, m_dAutoScaleFactor);
152     int iRetVal = dialogAutoScale.ShowModal();
153     if (iRetVal == wxID_OK) {
154       m_bMinSpecified = true;
155       m_bMaxSpecified = true;
156       double dMin, dMax;
157       dialogAutoScale.getMinMax (&dMin, &dMax);
158       m_dMinPixel = dMin;
159       m_dMaxPixel = dMax;
160       m_dAutoScaleFactor = dialogAutoScale.getAutoScaleFactor();
161       OnUpdate (this, NULL);
162     }
163 }
164
165 void 
166 ImageFileView::OnScaleMinMax (wxCommandEvent& event)
167 {
168     const ImageFile& rIF = GetDocument()->getImageFile();
169     double min, max;
170     if (! m_bMinSpecified && ! m_bMaxSpecified)
171       rIF.getMinMax (min, max);
172
173     if (m_bMinSpecified)
174       min = m_dMinPixel;
175     if (m_bMaxSpecified)
176       max = m_dMaxPixel;
177
178     DialogGetImageMinMax dialogMinMax (m_frame, rIF, min, max);
179     int retVal = dialogMinMax.ShowModal();
180     if (retVal == wxID_OK) {
181       m_bMinSpecified = true;
182       m_bMaxSpecified = true;
183       m_dMinPixel = dialogMinMax.getMinimum();
184       m_dMaxPixel = dialogMinMax.getMaximum();
185       OnUpdate (this, NULL);
186     }
187 }
188
189
190 ImageFileCanvas* 
191 ImageFileView::CreateCanvas (wxView *view, wxFrame *parent)
192 {
193     ImageFileCanvas* pCanvas;
194     int width, height;
195     parent->GetClientSize(&width, &height);
196     
197     pCanvas = new ImageFileCanvas (dynamic_cast<ImageFileView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
198     
199     pCanvas->SetScrollbars(20, 20, 50, 50);
200     pCanvas->SetBackgroundColour(*wxWHITE);
201     pCanvas->Clear();
202     
203     return pCanvas;
204 }
205
206 wxFrame*
207 ImageFileView::CreateChildFrame(wxDocument *doc, wxView *view)
208 {
209     wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "ImageFile Frame", wxPoint(-1, -1), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
210     
211     wxMenu *file_menu = new wxMenu;
212     
213     file_menu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...");
214     file_menu->Append(wxID_OPEN, "&Open...");
215     file_menu->Append(wxID_SAVE, "&Save");
216     file_menu->Append(wxID_SAVEAS, "Save &As...");
217     file_menu->Append(wxID_CLOSE, "&Close");
218     
219     file_menu->AppendSeparator();
220     file_menu->Append(IFMENU_FILE_PROPERTIES, "P&roperties");
221
222     file_menu->AppendSeparator();
223     file_menu->Append(wxID_PRINT, "&Print...");
224     file_menu->Append(wxID_PRINT_SETUP, "Print &Setup...");
225     file_menu->Append(wxID_PREVIEW, "Print Pre&view");
226     
227     wxMenu *view_menu = new wxMenu;
228     view_menu->Append(IFMENU_VIEW_SCALE_MINMAX, "Display Scale &Set...");
229     view_menu->Append(IFMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...");
230     
231     wxMenu *help_menu = new wxMenu;
232     help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
233     
234     wxMenuBar *menu_bar = new wxMenuBar;
235     
236     menu_bar->Append(file_menu, "&File");
237     menu_bar->Append(view_menu, "&View");
238     menu_bar->Append(help_menu, "&Help");
239     
240     subframe->SetMenuBar(menu_bar);
241     
242     subframe->Centre(wxBOTH);
243     
244     return subframe;
245 }
246
247
248 bool 
249 ImageFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
250 {
251     m_frame = CreateChildFrame(doc, this);
252     SetFrame(m_frame);
253     
254     m_bMinSpecified = false;
255     m_bMaxSpecified = false;
256     m_dAutoScaleFactor = 1.;
257
258     int width, height;
259     m_frame->GetClientSize(&width, &height);
260     m_frame->SetTitle("ImageFileView");
261     m_canvas = CreateCanvas(this, m_frame);
262
263 #ifdef __X__
264     int x, y;  // X requires a forced resize
265     m_frame->GetSize(&x, &y);
266     m_frame->SetSize(-1, -1, x, y);
267 #endif
268
269     m_frame->Show(true);
270     Activate(true);
271     
272     return true;
273 }
274
275 void 
276 ImageFileView::OnDraw (wxDC* dc)
277 {
278   if (m_bitmap.Ok())
279     dc->DrawBitmap(m_bitmap, 0, 0, false);
280 }
281
282
283 void 
284 ImageFileView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
285 {
286     const ImageFile& rIF = dynamic_cast<ImageFileDocument*>(GetDocument())->getImageFile();
287     ImageFileArrayConst v = rIF.getArray();
288     int nx = rIF.nx();
289     int ny = rIF.ny();
290     if (v != NULL && nx != 0 && ny != 0) {
291         if (! m_bMinSpecified || ! m_bMaxSpecified) {
292             double min, max;
293             rIF.getMinMax (min, max);
294             if (! m_bMinSpecified)
295                 m_dMinPixel = min;
296             if (! m_bMaxSpecified)
297                 m_dMaxPixel = max;
298         }
299         double scaleWidth = m_dMaxPixel - m_dMinPixel;
300     
301         unsigned char* imageData = new unsigned char [nx * ny * 3];
302         for (int ix = 0; ix < nx; ix++) {
303             for (int iy = 0; iy < ny; iy++) {
304                 double scaleValue = ((v[ix][iy] - m_dMinPixel) / scaleWidth) * 255;
305                 int intensity = static_cast<int>(scaleValue + 0.5);
306                 intensity = clamp (intensity, 0, 255);
307                 int baseAddr = ((ny - 1 - iy) * nx + ix) * 3;
308                 imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
309             }
310         }
311         wxImage image (nx, ny, imageData, true);
312         m_bitmap = image.ConvertToBitmap();
313         delete imageData;
314         int xSize = nx;
315         int ySize = ny;
316         xSize = clamp (xSize, 0, 800);
317         ySize = clamp (ySize, 0, 800);
318         m_frame->SetClientSize (xSize, ySize);
319         m_canvas->SetScrollbars(20, 20, nx/20, ny/20);
320         m_canvas->SetBackgroundColour(*wxWHITE);
321     } 
322
323     if (m_canvas)
324         m_canvas->Refresh();
325 }
326
327 bool 
328 ImageFileView::OnClose (bool deleteWindow)
329 {
330     if (!GetDocument()->Close())
331         return false;
332
333     m_canvas->Clear();
334     m_canvas->m_pView = NULL;
335     m_canvas = NULL;
336     wxString s(theApp->GetAppName());
337     if (m_frame)
338       m_frame->SetTitle(s);
339     SetFrame(NULL);
340
341     Activate(false);
342     
343     if (deleteWindow) {
344         delete m_frame;
345         return true;
346     }
347     return true;
348 }
349
350
351
352 // PhantomCanvas
353
354 PhantomCanvas::PhantomCanvas (PhantomView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
355   : wxScrolledWindow(frame, -1, pos, size, style)
356 {
357     m_pView = v;
358 }
359
360 void 
361 PhantomCanvas::OnDraw(wxDC& dc)
362 {
363     if (m_pView)
364         m_pView->OnDraw(& dc);
365 }
366
367
368 // PhantomView
369
370 IMPLEMENT_DYNAMIC_CLASS(PhantomView, wxView)
371
372 BEGIN_EVENT_TABLE(PhantomView, wxView)
373     EVT_MENU(PHMMENU_FILE_PROPERTIES, PhantomView::OnProperties)
374     EVT_MENU(PHMMENU_PROCESS_RASTERIZE, PhantomView::OnRasterize)
375     EVT_MENU(PHMMENU_PROCESS_PROJECTIONS, PhantomView::OnProjections)
376 END_EVENT_TABLE()
377
378 PhantomView::PhantomView(void) 
379   : wxView(), m_canvas(NULL), m_frame(NULL)
380 {
381     m_iDefaultNDet = 367;
382     m_iDefaultNView = 320;
383     m_iDefaultNSample = 2;
384     m_dDefaultRotation = 2;
385     m_dDefaultFocalLength = 2;
386     m_dDefaultFieldOfView = 1;
387     m_iDefaultGeometry = Scanner::GEOMETRY_PARALLEL;
388     m_iDefaultTrace = Trace::TRACE_NONE;
389 }
390
391 PhantomView::~PhantomView(void)
392 {
393 }
394
395 void
396 PhantomView::OnProperties (wxCommandEvent& event)
397 {
398   const int idPhantom = GetDocument()->getPhantomID();
399   const string& namePhantom = GetDocument()->getPhantomName();
400   ostringstream os;
401   os << "Phantom " << namePhantom << " (" << idPhantom << ")\n";
402   *theApp->getLog() << os.str().c_str();
403 #if DEBUG
404   const Phantom& rPhantom = GetDocument()->getPhantom();
405   rPhantom.print();
406 #endif
407 }
408
409
410 void
411 PhantomView::OnProjections (wxCommandEvent& event)
412 {
413   DialogGetProjectionParameters dialogProjection (m_frame, m_iDefaultNDet, m_iDefaultNView, m_iDefaultNSample, m_dDefaultRotation, m_dDefaultFocalLength, m_dDefaultFieldOfView, m_iDefaultGeometry, m_iDefaultTrace);
414   int retVal = dialogProjection.ShowModal();
415   if (retVal == wxID_OK) {
416     m_iDefaultNDet = dialogProjection.getNDet();
417     m_iDefaultNView = dialogProjection.getNView();
418     m_iDefaultNSample = dialogProjection.getNSamples();
419     m_iDefaultTrace = dialogProjection.getTrace();
420     m_dDefaultRotation = dialogProjection.getRotAngle();
421     m_dDefaultFocalLength = dialogProjection.getFocalLengthRatio();
422     m_dDefaultFieldOfView = dialogProjection.getFieldOfViewRatio();
423     wxString sGeometry = dialogProjection.getGeometry();
424     m_iDefaultGeometry = Scanner::convertGeometryNameToID (sGeometry.c_str());
425
426     if (m_iDefaultNDet > 0 && m_iDefaultNView > 0 && sGeometry != "") {
427       const Phantom& rPhantom = GetDocument()->getPhantom();
428       ProjectionFileDocument* pProjectionDoc = dynamic_cast<ProjectionFileDocument*>(theApp->getDocManager()->CreateDocument("untitled.pj", wxDOC_SILENT));
429       Projections& rProj = pProjectionDoc->getProjections();
430       Scanner theScanner (rPhantom, sGeometry.c_str(), m_iDefaultNDet, m_iDefaultNView, m_iDefaultNSample, m_dDefaultRotation, m_dDefaultFocalLength, m_dDefaultFieldOfView);
431       if (theScanner.fail()) {
432         *theApp->getLog() << "Failed making scanner: " << theScanner.failMessage().c_str() << "\n";
433         return;
434       }
435       rProj.initFromScanner (theScanner);
436       m_dDefaultRotation /= PI;  // convert back to PI units
437
438       if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
439         ProjectionsDialog dialogProjections (theScanner, rProj, rPhantom, m_iDefaultTrace, dynamic_cast<wxWindow*>(m_frame));
440         for (int iView = 0; iView < rProj.nView(); iView++) {
441           ::wxYield();
442           ::wxYield();
443           if (dialogProjections.isCancelled() || ! dialogProjections.projectView (iView)) {
444             pProjectionDoc->DeleteAllViews();
445             return;
446           }
447           ::wxYield();
448           ::wxYield();
449           while (dialogProjections.isPaused()) {
450               ::wxYield();
451               ::wxUsleep(50);
452           }
453         }
454       } else {
455         wxProgressDialog dlgProgress (wxString("Projection"), wxString("Projection Progress"), rProj.nView() + 1, m_frame, wxPD_CAN_ABORT);
456         for (int i = 0; i < rProj.nView(); i++) {
457           theScanner.collectProjections (rProj, rPhantom, i, 1, true, m_iDefaultTrace);
458           if (! dlgProgress.Update (i+1)) {
459             pProjectionDoc->DeleteAllViews();
460             return;
461           }
462         }
463       }
464
465       ostringstream os;
466       os << "Projections for " << rPhantom.name() << ": nDet=" << m_iDefaultNDet << ", nView=" << m_iDefaultNView << ", nSamples=" << m_iDefaultNSample << ", RotAngle=" << m_dDefaultRotation << ", FocalLengthRatio=" << m_dDefaultFocalLength << ", FieldOfViewRatio=" << m_dDefaultFieldOfView << ", Geometry=" << sGeometry.c_str() << "\n";
467       rProj.setRemark (os.str());
468       *theApp->getLog() << os.str().c_str();
469
470       m_frame->Lower();
471       ::wxYield();
472       if (wxView* pView = pProjectionDoc->GetFirstView()) {
473         if (wxFrame* pFrame = pView->GetFrame()) {
474           pFrame->SetFocus();
475           pFrame->Raise();
476         }
477         theApp->getDocManager()->ActivateView (pView, true, false);
478       }
479       ::wxYield();
480       pProjectionDoc->Modify(true);
481       pProjectionDoc->UpdateAllViews(this);
482     }
483   }
484 }
485
486
487 void
488 PhantomView::OnRasterize (wxCommandEvent& event)
489 {
490   DialogGetRasterParameters dialogRaster (m_frame, 256, 256, 1);
491   int retVal = dialogRaster.ShowModal();
492   if (retVal == wxID_OK) {
493     int xSize = dialogRaster.getXSize();
494     int ySize = dialogRaster.getYSize();
495     int nSamples = dialogRaster.getNSamples();
496     if (nSamples < 1)
497       nSamples = 1;
498     if (xSize > 0 && ySize > 0) {
499       const Phantom& rPhantom = GetDocument()->getPhantom();
500       ImageFileDocument* pRasterDoc = dynamic_cast<ImageFileDocument*>(theApp->getDocManager()->CreateDocument("untitled.if", wxDOC_SILENT));
501       ImageFile& imageFile = pRasterDoc->getImageFile();
502
503       imageFile.setArraySize (xSize, ySize);
504       wxProgressDialog dlgProgress (wxString("Rasterize"), wxString("Rasterization Progress"), imageFile.nx() + 1, m_frame, wxPD_CAN_ABORT);
505       for (unsigned int i = 0; i < imageFile.nx(); i++) {
506         rPhantom.convertToImagefile (imageFile, nSamples, Trace::TRACE_NONE, i, 1, true);
507         if (! dlgProgress.Update(i+1)) {
508           pRasterDoc->DeleteAllViews();
509           return;
510         }
511       }
512       pRasterDoc->Modify(true);
513       pRasterDoc->UpdateAllViews(this);
514
515       ostringstream os;
516       os << "Rasterize Phantom " << rPhantom.name() << ": XSize=" << xSize << ", YSize=" << ySize << ", nSamples=" << nSamples << "\n";
517       *theApp->getLog() << os.str().c_str();
518     }
519   }
520 }
521
522
523 PhantomCanvas* 
524 PhantomView::CreateCanvas (wxView *view, wxFrame *parent)
525 {
526     PhantomCanvas* pCanvas;
527     int width, height;
528     parent->GetClientSize(&width, &height);
529     
530     pCanvas = new PhantomCanvas (dynamic_cast<PhantomView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
531     
532     pCanvas->SetBackgroundColour(*wxWHITE);
533     pCanvas->Clear();
534     
535     return pCanvas;
536 }
537
538 wxFrame*
539 PhantomView::CreateChildFrame(wxDocument *doc, wxView *view)
540 {
541     wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(10, 10), wxSize(256, 256), wxDEFAULT_FRAME_STYLE);
542     
543     wxMenu *file_menu = new wxMenu;
544     
545     file_menu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...");
546     file_menu->Append(wxID_OPEN, "&Open...");
547     file_menu->Append(wxID_CLOSE, "&Close");
548     
549     file_menu->AppendSeparator();
550     file_menu->Append(PHMMENU_FILE_PROPERTIES, "P&roperties");
551
552     file_menu->AppendSeparator();
553     file_menu->Append(wxID_PRINT, "&Print...");
554     file_menu->Append(wxID_PRINT_SETUP, "Print &Setup...");
555     file_menu->Append(wxID_PREVIEW, "Print Pre&view");
556     
557     wxMenu *process_menu = new wxMenu;
558     process_menu->Append(PHMMENU_PROCESS_RASTERIZE, "&Rasterize...");
559     process_menu->Append(PHMMENU_PROCESS_PROJECTIONS, "&Projections...");
560
561     wxMenu *help_menu = new wxMenu;
562     help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents");
563     help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
564     
565     wxMenuBar *menu_bar = new wxMenuBar;
566     
567     menu_bar->Append(file_menu, "&File");
568     menu_bar->Append(process_menu, "&Process");
569     menu_bar->Append(help_menu, "&Help");
570     
571     subframe->SetMenuBar(menu_bar);
572     
573     subframe->Centre(wxBOTH);
574     
575     return subframe;
576 }
577
578
579 bool 
580 PhantomView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
581 {
582     m_frame = CreateChildFrame(doc, this);
583     SetFrame(m_frame);
584
585     int width, height;
586     m_frame->GetClientSize(&width, &height);
587     m_frame->SetTitle("PhantomView");
588     m_canvas = CreateCanvas(this, m_frame);
589
590 #ifdef __X__
591     int x, y;  // X requires a forced resize
592     m_frame->GetSize(&x, &y);
593     m_frame->SetSize(-1, -1, x, y);
594 #endif
595
596     m_frame->Show(true);
597     Activate(true);
598
599     return true;
600 }
601
602
603 void 
604 PhantomView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
605 {
606     if (m_canvas)
607         m_canvas->Refresh();
608 }
609
610 bool 
611 PhantomView::OnClose (bool deleteWindow)
612 {
613     if (!GetDocument()->Close())
614         return false;
615
616     m_canvas->Clear();
617     m_canvas->m_pView = NULL;
618     m_canvas = NULL;
619     wxString s(wxTheApp->GetAppName());
620     if (m_frame)
621       m_frame->SetTitle(s);
622     SetFrame(NULL);
623
624     Activate(false);
625     
626     if (deleteWindow) {
627         delete m_frame;
628         return true;
629     }
630     return true;
631 }
632
633 void
634 PhantomView::OnDraw (wxDC* dc)
635 {
636   int xsize, ysize;
637   m_canvas->GetClientSize (&xsize, &ysize);
638   SGPDriver driver (dc, xsize, ysize);
639   SGP sgp (driver);
640   const Phantom& rPhantom = GetDocument()->getPhantom();
641   sgp.setColor (C_RED);
642   rPhantom.show (sgp);
643 }
644
645 // ProjectionCanvas
646
647 ProjectionFileCanvas::ProjectionFileCanvas (ProjectionFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style)
648   : wxScrolledWindow(frame, -1, pos, size, style)
649 {
650     m_pView = v;
651 }
652
653 void 
654 ProjectionFileCanvas::OnDraw(wxDC& dc)
655 {
656     if (m_pView)
657         m_pView->OnDraw(& dc);
658 }
659
660 // ProjectionFileView
661
662 IMPLEMENT_DYNAMIC_CLASS(ProjectionFileView, wxView)
663
664 BEGIN_EVENT_TABLE(ProjectionFileView, wxView)
665     EVT_MENU(PJMENU_FILE_PROPERTIES, ProjectionFileView::OnProperties)
666     EVT_MENU(PJMENU_PROCESS_RECONSTRUCT, ProjectionFileView::OnReconstruct)
667 END_EVENT_TABLE()
668
669 ProjectionFileView::ProjectionFileView(void) 
670   : wxView(), m_canvas(NULL), m_frame(NULL)
671 {
672     m_iDefaultNX = 256;
673     m_iDefaultNY = 256;
674   m_iDefaultFilter = SignalFilter::FILTER_ABS_BANDLIMIT;
675   m_dDefaultFilterParam = 1.;
676 #if HAVE_FFTW
677   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_RFFTW;
678   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_INVERSE_FOURIER;
679 #else
680   m_iDefaultFilterMethod = ProcessSignal::FILTER_METHOD_CONVOLUTION;
681   m_iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT;
682 #endif
683   m_iDefaultZeropad = 1;
684   m_iDefaultBackprojector = Backprojector::BPROJ_IDIFF3;
685   m_iDefaultInterpolation = Backprojector::INTERP_LINEAR;
686   m_iDefaultInterpParam = 1;
687   m_iDefaultTrace = Trace::TRACE_NONE;
688 }
689
690 ProjectionFileView::~ProjectionFileView(void)
691 {
692 }
693
694 void
695 ProjectionFileView::OnProperties (wxCommandEvent& event)
696 {
697   const Projections& rProj = GetDocument()->getProjections();
698   ostringstream os;
699   rProj.printScanInfo(os);
700   *theApp->getLog() << os.str().c_str();
701   wxMessageDialog dialogMsg (m_frame, os.str().c_str(), "Projection File Properties", wxOK | wxICON_INFORMATION);
702   dialogMsg.ShowModal();
703 }
704
705
706 void
707 ProjectionFileView::OnReconstruct (wxCommandEvent& event)
708 {
709   DialogGetReconstructionParameters dialogReconstruction (m_frame, m_iDefaultNX, m_iDefaultNY, m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration, m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector, m_iDefaultTrace);
710
711   int retVal = dialogReconstruction.ShowModal();
712   if (retVal == wxID_OK) {
713     m_iDefaultNX = dialogReconstruction.getXSize();
714     m_iDefaultNY = dialogReconstruction.getYSize();
715     wxString optFilterName = dialogReconstruction.getFilterName();
716     m_iDefaultFilter = SignalFilter::convertFilterNameToID (optFilterName.c_str());
717     m_dDefaultFilterParam = dialogReconstruction.getFilterParam();
718     wxString optFilterMethodName = dialogReconstruction.getFilterMethodName();
719     m_iDefaultFilterMethod = ProcessSignal::convertFilterMethodNameToID(optFilterMethodName.c_str());
720     m_iDefaultZeropad = dialogReconstruction.getZeropad();
721     wxString optFilterGenerationName = dialogReconstruction.getFilterGenerationName();
722     m_iDefaultFilterGeneration = ProcessSignal::convertFilterGenerationNameToID (optFilterGenerationName.c_str());
723     wxString optInterpName = dialogReconstruction.getInterpName();
724     m_iDefaultInterpolation = Backprojector::convertInterpNameToID (optInterpName.c_str());
725     m_iDefaultInterpParam = dialogReconstruction.getInterpParam();
726     wxString optBackprojectName = dialogReconstruction.getBackprojectName();
727     m_iDefaultBackprojector = Backprojector::convertBackprojectNameToID (optBackprojectName.c_str());
728     m_iDefaultTrace = dialogReconstruction.getTrace();
729     if (m_iDefaultNX > 0 && m_iDefaultNY > 0) {
730       ImageFileDocument* pReconDoc = dynamic_cast<ImageFileDocument*>(theApp->getDocManager()->CreateDocument("untitled.if", wxDOC_SILENT));
731       ImageFile& imageFile = pReconDoc->getImageFile();
732       const Projections& rProj = GetDocument()->getProjections();
733       imageFile.setArraySize (m_iDefaultNX, m_iDefaultNY);
734       Timer timerRecon;
735
736       if (m_iDefaultFilterMethod != ProcessSignal::FILTER_METHOD_CONVOLUTION && m_iDefaultFilterGeneration == ProcessSignal::FILTER_GENERATION_DIRECT && rProj.geometry() != Scanner::GEOMETRY_PARALLEL) {
737         wxMessageBox ("Sorry!\nCurrently, frequency-based filtering with direct filter generation is not support for geometries other than parallel.\nAborting command.", "Not Supported", wxOK | wxICON_WARNING, m_frame);
738         return;
739       }
740 #if 0
741       SGPDriver* pSGPDriver = NULL;
742       SGP* pSGP = NULL;
743       wxMemoryDC* pDCPlot = NULL;
744       wxBitmap bitmap;
745       if (m_iDefaultTrace >= Trace::TRACE_PLOT) {
746         bitmap.Create (500, 500);
747         pDCPlot = new wxMemoryDC;
748         pDCPlot->SelectObject (bitmap);
749         pSGPDriver = new SGPDriver (dynamic_cast<wxDC*>pDCPlot, 500, 500);
750         pSGP = new SGP (*pSGPDriver);
751       }
752       Reconstructor* pReconstruct = new Reconstructor (rProj, imageFile, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace, pSGP);
753       delete pSGP;
754 #else
755       Reconstructor* pReconstruct = new Reconstructor (rProj, imageFile, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace);
756 #endif
757
758       if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
759         ReconstructDialog* pDlgReconstruct = new ReconstructDialog (*pReconstruct, rProj, imageFile, m_iDefaultTrace, m_frame);
760         for (int iView = 0; iView < rProj.nView(); iView++) {
761           ::wxYield();
762           ::wxYield();
763           if (pDlgReconstruct->isCancelled() || ! pDlgReconstruct->reconstructView (iView)) {
764             delete pDlgReconstruct;
765             delete pReconstruct;
766             pReconDoc->DeleteAllViews();
767             return;
768           }
769           ::wxYield();
770           ::wxYield();
771           while (pDlgReconstruct->isPaused()) {
772               ::wxYield();
773               ::wxUsleep(50);
774           }
775         }
776         delete pDlgReconstruct;
777       } else {
778         wxProgressDialog dlgProgress (wxString("Reconstruction"), wxString("Reconstruction Progress"), rProj.nView() + 1, m_frame, wxPD_CAN_ABORT);
779         for (int i = 0; i < rProj.nView(); i++) {
780           pReconstruct->reconstructView (i, 1);
781           if (! dlgProgress.Update(i + 1)) {
782             delete pReconstruct;
783             pReconDoc->DeleteAllViews();
784             return;
785           }
786         }
787       }
788       delete pReconstruct;
789       pReconDoc->Modify(true);
790       pReconDoc->UpdateAllViews(this);
791       ostringstream os;
792       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() << "\n";
793       *theApp->getLog() << os.str().c_str();
794       imageFile.labelAdd (rProj.getLabel());
795       imageFile.labelAdd (Array2dFileLabel::L_HISTORY, os.str().c_str(), timerRecon.timerEnd());
796     }
797   }
798 }
799
800
801 ProjectionFileCanvas* 
802 ProjectionFileView::CreateCanvas (wxView *view, wxFrame *parent)
803 {
804     ProjectionFileCanvas* pCanvas;
805     int width, height;
806     parent->GetClientSize(&width, &height);
807     
808     pCanvas = new ProjectionFileCanvas (dynamic_cast<ProjectionFileView*>(view), parent, wxPoint(0, 0), wxSize(width, height), 0);
809     
810     pCanvas->SetScrollbars(20, 20, 50, 50);
811     pCanvas->SetBackgroundColour(*wxWHITE);
812     pCanvas->Clear();
813     
814     return pCanvas;
815 }
816
817 wxFrame*
818 ProjectionFileView::CreateChildFrame(wxDocument *doc, wxView *view)
819 {
820     wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(10, 10), wxSize(0, 0), wxDEFAULT_FRAME_STYLE);
821     
822     wxMenu *file_menu = new wxMenu;
823     
824     file_menu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...");
825     file_menu->Append(wxID_OPEN, "&Open...");
826     file_menu->Append(wxID_SAVE, "&Save");
827     file_menu->Append(wxID_SAVEAS, "Save &As...");
828     file_menu->Append(wxID_CLOSE, "&Close");
829     
830     file_menu->AppendSeparator();
831     file_menu->Append(PJMENU_FILE_PROPERTIES, "P&roperties");
832
833     file_menu->AppendSeparator();
834     file_menu->Append(wxID_PRINT, "&Print...");
835     file_menu->Append(wxID_PRINT_SETUP, "Print &Setup...");
836     file_menu->Append(wxID_PREVIEW, "Print Pre&view");
837     
838     wxMenu *process_menu = new wxMenu;
839     process_menu->Append(PJMENU_PROCESS_RECONSTRUCT, "R&econstruct...");
840
841     wxMenu *help_menu = new wxMenu;
842     help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents");
843     help_menu->AppendSeparator();
844     help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
845     
846     wxMenuBar *menu_bar = new wxMenuBar;
847     
848     menu_bar->Append(file_menu, "&File");
849     menu_bar->Append(process_menu, "&Process");
850     menu_bar->Append(help_menu, "&Help");
851     
852     subframe->SetMenuBar(menu_bar);
853     
854     subframe->Centre(wxBOTH);
855     
856     return subframe;
857 }
858
859
860 bool 
861 ProjectionFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
862 {
863     m_frame = CreateChildFrame(doc, this);
864     SetFrame(m_frame);
865     
866     int width, height;
867     m_frame->GetClientSize(&width, &height);
868     m_frame->SetTitle("ProjectionFileView");
869     m_canvas = CreateCanvas(this, m_frame);
870
871 #ifdef __X__
872     int x, y;  // X requires a forced resize
873     m_frame->GetSize(&x, &y);
874     m_frame->SetSize(-1, -1, x, y);
875 #endif
876
877     m_frame->Show(true);
878     Activate(true);
879     
880     return true;
881 }
882
883 void 
884 ProjectionFileView::OnDraw (wxDC* dc)
885 {
886     if (m_bitmap.Ok())
887         dc->DrawBitmap (m_bitmap, 0, 0, false);
888 }
889
890
891 void 
892 ProjectionFileView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
893 {
894     const Projections& rProj = GetDocument()->getProjections();
895     const int nDet = rProj.nDet();
896     const int nView = rProj.nView();
897     if (nDet != 0 && nView != 0) {
898         const DetectorArray& detarray = rProj.getDetectorArray(0);
899         const DetectorValue* detval = detarray.detValues();
900         double min = detval[0];
901         double max = detval[0];
902         for (int iy = 0; iy < nView; iy++) {
903             const DetectorArray& detarray = rProj.getDetectorArray(iy);
904             const DetectorValue* detval = detarray.detValues();
905             for (int ix = 0; ix < nDet; ix++) {
906                 if (min > detval[ix])
907                     min = detval[ix];
908                 else if (max < detval[ix])
909                     max = detval[ix];
910             }
911         }
912
913         unsigned char* imageData = new unsigned char [nDet * nView * 3];
914         double scale = (max - min) / 255;
915         for (int iy = 0; iy < nView; iy++) {
916             const DetectorArray& detarray = rProj.getDetectorArray(iy);
917             const DetectorValue* detval = detarray.detValues();
918             for (int ix = 0; ix < nDet; ix++) {
919                 int intensity = static_cast<int>(((detval[ix] - min) / scale) + 0.5);
920                 intensity = clamp(intensity, 0, 255);
921                 int baseAddr = (iy * nDet + ix) * 3;
922                 imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
923             }
924         }
925         wxImage image (nDet, nView, imageData, true);
926         m_bitmap = image.ConvertToBitmap();
927         delete imageData;
928         int xSize = nDet;
929         int ySize = nView;
930         xSize = clamp (xSize, 0, 800);
931         ySize = clamp (ySize, 0, 800);
932         m_frame->SetClientSize (xSize, ySize);
933         m_canvas->SetScrollbars (20, 20, nDet/20, nView/20);
934     }
935
936     if (m_canvas)
937         m_canvas->Refresh();
938 }
939
940 bool 
941 ProjectionFileView::OnClose (bool deleteWindow)
942 {
943     if (!GetDocument()->Close())
944         return false;
945
946     m_canvas->Clear();
947     m_canvas->m_pView = NULL;
948     m_canvas = NULL;
949     wxString s(wxTheApp->GetAppName());
950     if (m_frame)
951       m_frame->SetTitle(s);
952     SetFrame(NULL);
953
954     Activate(false);
955     
956     if (deleteWindow) {
957         delete m_frame;
958         return true;
959     }
960     return true;
961 }
962