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