]> Creatis software - creaImageIO.git/blob - src2/creaImageIOWxGimmickView.cpp
clean-up
[creaImageIO.git] / src2 / creaImageIOWxGimmickView.cpp
1 #include <creaImageIOPACSConnection.h>
2 #include <creaImageIOWxPACSConnectionPanel.h>
3 #include <creaImageIOWxGimmickView.h>
4 #include <creaImageIOWxTreeView.h>
5 #include <creaImageIOSystem.h>
6 #include <creaImageIOWxCustomizeConfigPanel.h>
7 #include <creaImageIOWxListenerPanel.h>
8 #include <creaImageIOWxEditFieldsPanel.h>
9 #include <creaImageIOWxAttributeSelectionPanel.h>
10 #include <creaImageIOWxDescriptorPanel.h>
11
12 using namespace crea;
13 // Icons
14 #include "icons/accept.xpm"
15 #include "icons/add.xpm"
16 #include "icons/folder-down.xpm"
17 #include "icons/page-down.xpm"
18 #include "icons/remove.xpm"
19 #include "icons/database-add.xpm"
20 #include "icons/create-database.xpm"
21 #include "icons/help.xpm"
22 #include "icons/synchronize.xpm"
23 #include "icons/settings.xpm"
24 #include "icons/tools.xpm"
25 //#include "icons/import.xpm"
26
27 #include <wx/imaglist.h>
28 #include <wx/popupwin.h>
29 #include<boost/filesystem/operations.hpp>
30 #if defined(BUILD_BRUKER)
31         #include "bruker2dicom.h"
32 #endif
33
34
35
36 namespace creaImageIO
37 {
38    
39   //======================================================================
40   // The ids of the different tools
41   enum
42     {
43         TOOL_ADDFILES_ID    = 1,
44         TOOL_ADDDIR_ID      = 2,
45         TOOL_ADDDATABASE_ID = 3,
46         TOOL_REMOVE_ID      = 4,
47         TOOL_SYNCHRONIZE_ID = 5,
48         TOOL_HELP_ID        = 6,
49         TOOL_SETTINGS_ID    = 7,
50         TOOL_TOOLS_ID       = 8,
51         TOOL_CREATEDB_ID    = 9,
52         TOOL_PACS_ID        = 10
53     };
54   //======================================================================
55
56   //================================================================
57   // 
58   const int icon_number = 11;
59   // Icon ids
60   typedef enum
61     {
62       Icon_create_database,
63       Icon_accept,
64       Icon_add,
65       Icon_folder_down,
66       Icon_page_down,
67       Icon_database_add,
68       Icon_remove,
69       Icon_synchronize,
70       Icon_help,
71       Icon_settings,
72       Icon_tools
73     }
74     icon_id;
75   //================================================================
76
77   //================================================================
78   /*
79   const icon_id Icon[5] = { Icon_Database,  
80                             Icon_Patient,
81                             Icon_Study,
82                             Icon_Series,
83                             Icon_Image };
84   */
85   //================================================================
86
87
88   //======================================================================
89   // CTor
90         WxGimmickView::WxGimmickView(boost::shared_ptr<Gimmick> gimmick,
91                                wxWindow *parent, 
92                                const wxWindowID id,
93                                const wxPoint& pos, 
94                                const wxSize& size,
95                                int min_dim,
96                                int max_dim,
97                                int number_of_threads)
98     : wxPanel(parent,id,pos,size),
99       GimmickView(gimmick, number_of_threads),
100       mProgressDialog(0),
101       mConstructed(false)
102   {
103     GimmickDebugMessage(1,"WxGimmickView::WxGimmickView"
104                         <<std::endl);
105     // Sets the current directory to the home dir
106     mCurrentDirectory =  std2wx(gimmick->GetHomeDirectory());
107
108      // Connect the AddProgress callback
109     gimmick->ConnectAddProgressObserver 
110      ( boost::bind( &WxGimmickView::OnAddProgress , this, _1 ) );
111
112     // Create the list of icons (mIcon)
113     CreateIconList();
114
115     // Global sizer
116     wxBoxSizer  *sizer = new wxBoxSizer(wxVERTICAL);
117
118     // Create the tool bar
119     CreateToolBar(); 
120     sizer->Add( mToolBar, 0, wxGROW, 0);
121
122     // Split part below toolbar into notebook for views and panel
123     // for preview, messages...
124     mSplitter = new wxSplitterWindow( this , -1);
125
126     // Notebook
127     mNotebook = new wxNotebook(mSplitter,
128                                -1, wxDefaultPosition, wxDefaultSize, 0);
129
130     //Gimmick
131     mGimmick=gimmick;
132
133     mSelectionMaxDimension = max_dim;
134     mSelectionMinDimension = min_dim;
135     
136     // Create the views
137     CreateTreeViews();
138
139     // Bottom panel 
140     mBottomPanel = new wxPanel(mSplitter,-1);
141     
142     wxBoxSizer *bottom_sizer = new wxBoxSizer(wxVERTICAL); //HORIZONTAL);
143     
144     
145     // Previewer
146     mViewer = new WxViewer(mBottomPanel, wxID_ANY, wxT("Gimmick! Viewer"),wxDefaultPosition, wxDefaultSize );
147         //pointers.push_back(new ImagePointerHolder(GetDefaultImage())
148         pointers.push_back(boost::shared_ptr<creaImageIO::ImagePointerHolder>(new ImagePointerHolder(GetDefaultImage())));
149
150         mViewer->SetImageVector(pointers);
151         mViewer->StartPlayer();
152
153
154     bottom_sizer->Add(mViewer,1,wxGROW,1);
155     //    mViewer->Show();
156
157     mText = new wxStaticText(mBottomPanel, wxID_ANY, wxT("Welcome to Gimmick!"));
158     bottom_sizer->Add(mText,0,wxGROW,0);
159
160           
161           
162     mBottomPanel->SetSizer(bottom_sizer);
163
164     // Splitting
165     int hsize = size.GetHeight();
166
167     int top_minsize = 450;
168     int bottom_minsize = 50;
169
170     mSplitter->SetMinimumPaneSize( bottom_minsize );
171     mSplitter->SplitHorizontally( mNotebook, mBottomPanel, 
172                                   top_minsize);
173
174     sizer->Add( mSplitter, 1, wxGROW, 0);
175
176     mProgressDialog=0;
177     SetSizer( sizer );     
178     SetAutoLayout(true);
179     Layout();
180     //mListener=new Listener();
181     //mListener->ConnectObserver(boost::bind( &WxGimmickView::OnDriveMount, this, _1 ) );
182     //mListener->Create();
183    // mListener->Run();
184    // mListener->Pause();
185
186     mConstructed = true;
187   }
188   //======================================================================
189
190   //======================================================================
191   /// Destructor
192   WxGimmickView::~WxGimmickView()
193   {
194         // stop the viewer before application exit.
195     mViewer->StopPlayer();
196     GimmickDebugMessage(1,"WxGimmickView::~WxGimmickView"
197                         <<std::endl);
198         delete mIcon;
199     //if(mListener->IsAlive())   {        mListener->Delete();    }
200   }
201   //======================================================================
202   
203   //======================================================================
204   /// Creates the tool bar
205   void WxGimmickView::CreateToolBar()
206   {
207     long style = wxTB_HORIZONTAL | wxNO_BORDER | wxTB_TEXT;
208     mToolBar = new wxToolBar(this,-1,wxDefaultPosition,wxDefaultSize,
209                              style);
210
211     mToolAddFile = mToolBar->AddTool( TOOL_ADDFILES_ID, 
212                                       _T("Add file(s)"),
213                                       mIcon->GetBitmap(Icon_page_down),
214                                       _T("Add one or more file to database")
215                                       );
216     mToolAddDir = mToolBar->AddTool( TOOL_ADDDIR_ID, 
217                                       _T("Add folder"),
218                                       mIcon->GetBitmap(Icon_folder_down),
219                                       _T("Add the content of a folder to database")
220                                       );
221     mToolAddDatabase = mToolBar->AddTool( TOOL_ADDDATABASE_ID, 
222                                       _T("Open database"),
223                                       mIcon->GetBitmap(Icon_database_add),
224                                       _T("Open a local or distant database")
225                                       );
226     mToolRemove = mToolBar->AddTool( TOOL_REMOVE_ID, 
227                                       _T("Remove"),
228                                       mIcon->GetBitmap(Icon_remove),
229                                       _T("Remove selected items")
230                                       );
231     mToolSynchronize = mToolBar->AddTool( TOOL_SYNCHRONIZE_ID, 
232                                       _T("Synchronize"),
233                                       mIcon->GetBitmap(Icon_synchronize),
234                                       _T("Synchronizes the database with disk")
235                                       );
236     mToolHelp = mToolBar->AddTool( TOOL_HELP_ID, 
237                                       _T("Help"),
238                                       mIcon->GetBitmap(Icon_help),
239                                       _T("Open help window")
240                                       );
241     mToolSettings = mToolBar->AddTool( TOOL_SETTINGS_ID, 
242                                       _T("System settings"),
243                                       mIcon->GetBitmap(Icon_settings),
244                                       _T("Allows the modification of various system settings")
245                                       );
246     mToolTools = mToolBar->AddTool( TOOL_TOOLS_ID, 
247                                       _T("Tools"),
248                                       mIcon->GetBitmap(Icon_tools),
249                                       _T("Applies tools to images")
250                                       );
251     mToolAddFile = mToolBar->AddTool( TOOL_CREATEDB_ID, 
252                                       _T("Create database"),
253                                       mIcon->GetBitmap(Icon_create_database),
254                                       _T("Create DB from an Attributes Descriptor file")
255                                       );
256 #if defined(BUILD_PACS)
257         mToolAddFile = mToolBar->AddTool( TOOL_PACS_ID, 
258                                       _T("PACS Connection,"),
259                                       mIcon->GetBitmap(Icon_create_database),
260                                       _T("Echo, Find and Get to a PACS")
261                                       );
262 #endif
263     //const wxBitmap& bitmap1, const wxString& shortHelpString = "", wxItemKind kind = wxITEM_NORMAL)
264
265     mToolBar->Realize();
266   }
267   //======================================================================
268
269  
270   //======================================================================
271   /// Create the tree view for TreeHandler provided
272   void WxGimmickView::CreateTreeView( TreeHandler* h)
273   {
274     std::string name(h->GetTree().GetAttribute("Name"));
275     GimmickMessage(2,"Creating the tree view for '"<<
276                    name<<"'"<<std::endl);
277     // Create the WxTreeView
278     WxTreeView* view = new WxTreeView(h, this, mNotebook, -1);
279
280     // TO DO : TEST THAT A VIEW WITH SAME NAME IS NOT
281     // ALREADY IN THE MAP
282     GetTreeViewMap()[name] = view;
283
284     // Add Notebook page
285     mNotebook->AddPage( view, crea::std2wx(name) );
286         
287   }
288
289   //======================================================================
290   void WxGimmickView::GetSelectedImages(std::vector<vtkImageData*>& s, int dim)
291   {
292         std::vector<std::string> files;
293         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetSelectedAsString(files);
294         ReadImagesNotThreaded(s, files, dim);
295   }
296
297   //======================================================================
298   void WxGimmickView::GetSelectedImagesInVector(std::vector<vtkImageData*>& s, int dim)
299   {
300         std::vector<std::string> files;
301         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetSelectedAsString(files);
302         ReadImagesNotThreadedInVector(s, files, dim);
303   }
304   //======================================================================
305
306   //======================================================================
307   void WxGimmickView::GetSelectedFiles(std::vector<std::string>& s)
308   {
309         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetSelectedAsString(s);
310   }
311   //======================================================================
312
313   //======================================================================
314   void WxGimmickView::GetImages(int dim, 
315                                 const std::vector<std::string>& files, 
316                                 std::vector<vtkImageData*>& s)
317   {
318         ReadImagesNotThreaded(s,files,dim);
319   }
320   //======================================================================
321
322
323   //=================================================
324   void WxGimmickView::CreateIconList()
325   {
326     // Size of the icons;
327     int size = 16;
328
329     wxIcon icons[20];
330     // should correspond to Icon_xxx enum
331     icons[Icon_accept]          = wxIcon(accept_xpm);
332     icons[Icon_add]             = wxIcon(add_xpm);
333     icons[Icon_folder_down]     = wxIcon(folder_down_xpm);
334     icons[Icon_page_down]       = wxIcon(page_down_xpm);
335     icons[Icon_remove]          = wxIcon(remove_xpm);
336     icons[Icon_database_add]    = wxIcon(database_add_xpm);
337     icons[Icon_help]            = wxIcon(help_xpm);
338     icons[Icon_synchronize]     = wxIcon(synchronize_xpm);
339     icons[Icon_create_database] = wxIcon(create_database_xpm);
340     icons[Icon_settings]        = wxIcon(settings_xpm);
341     icons[Icon_tools]           = wxIcon(tools_xpm);
342
343     //   unsigned int NbIcons = 8;
344     // Make an image list containing small icons
345     mIcon = new wxImageList(size,size,true);
346     
347     // Make all icons the same size = size of the first one
348     int sizeOrig = icons[0].GetWidth();
349     for ( size_t i = 0; i < icon_number; i++ )
350       {
351         if ( size == sizeOrig )
352           {
353             mIcon->Add(icons[i]);
354           }
355         else
356           {
357             mIcon->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));
358           }
359       }
360   }
361   //=================================================
362
363
364   //=================================================
365   void WxGimmickView::OnAddFiles(wxCommandEvent& event)
366   {
367     mViewer->StopPlayer();
368     long style = wxOPEN | wxFILE_MUST_EXIST | wxFD_MULTIPLE;
369     std::string wc("*");
370     wxFileDialog* FD = new wxFileDialog( 0, 
371                                          _T("Select file"),
372                                          _T(""),
373                                          _T(""),
374                                          crea::std2wx(wc),
375                                          style,
376                                          wxDefaultPosition);
377     
378     if (FD->ShowModal()==wxID_OK)
379       {
380         wxBusyCursor busy;
381
382         wxArrayString files;
383         FD->GetPaths(files);
384         unsigned int i;
385         std::vector<std::string> filenames;
386         for (i=0;i<files.GetCount();++i)
387         {
388           filenames.push_back(wx2std(files[i]));
389           GimmickMessage(2,"Adding File "<<files[i]<<"."<<std::endl);
390         }
391
392         mProgressDialog = 
393           new wxProgressDialog(_T("Adding file(s)"),
394                                _T(""),
395                                1000,
396                                this,
397                                wxPD_ELAPSED_TIME |
398                                // wxPD_ESTIMATED_TIME |
399                                // wxPD_REMAINING_TIME |
400                                wxPD_CAN_ABORT );
401
402         // TO DO : select the current tree handler
403         mGimmick->AddFiles(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),filenames);
404
405         mProgressDialog->Pulse(_T("Updating view..."));
406
407         UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
408         delete mProgressDialog;
409         DisplayAddSummary();    
410
411       }
412         mViewer->StartPlayer(); 
413   }
414   //=================================================
415
416   //=================================================
417   void WxGimmickView::OnAddDir(wxCommandEvent& event)
418   {
419     mViewer->StopPlayer();
420         std::string name = crea::wx2std(mNotebook->GetCurrentPage()->GetName());
421     long style = wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST;
422     wxDirDialog* FD = 
423          new wxDirDialog( 0, 
424                        _T("Select directory"),
425                        mCurrentDirectory,
426                        style);
427     
428     if (FD->ShowModal()==wxID_OK)
429     {
430         std::string dirname = wx2std (FD->GetPath());
431         bool recurse =  isNeedRecursive(dirname);
432         if (recurse)
433         {
434              recurse = wxMessageBox(_T("Recurse into sub-directories ?"), _T("Scan directory"), wxYES_NO,this ) == wxYES ? true : false;
435         }
436
437                 wxBusyCursor busy;
438                 wxString title(_T("Adding directory"));
439                 if (recurse) 
440                 title = _T("Adding directory (recursive)");
441                 mProgressDialog = 
442                 new wxProgressDialog(_T("Adding directory"),
443                                         _T(""),
444                                         NumberFilesToAdd(dirname,recurse),
445                                         this,
446                                         wxPD_ELAPSED_TIME | 
447                                         wxPD_SMOOTH |
448                                         // wxPD_ESTIMATED_TIME |
449                                         // wxPD_REMAINING_TIME |
450                                         wxPD_CAN_ABORT );
451
452                 mCurrentDirectory = FD->GetPath();  
453                 mGimmick->AddDir(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),dirname,recurse);
454                 mProgressDialog->Pulse(_T("Updating view..."));
455
456                 UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
457                 delete mProgressDialog;
458                 DisplayAddSummary();
459           }
460     mViewer->StartPlayer();
461   }
462
463
464   //=================================================
465   // Determines number of files potentially to add to database
466    int WxGimmickView::NumberFilesToAdd(const std::string &dirpath, bool recursive)
467   {
468            int nb = 0;
469            if ( !boost::filesystem::exists( dirpath ) ) return nb;
470            boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
471            for ( boost::filesystem::directory_iterator itr( dirpath );  itr != end_itr;  ++itr )
472           {
473                 // If is directory & recurse : do recurse
474                 if ( boost::filesystem::is_directory(itr->status()) )
475                 {
476                         if (recursive) 
477                         {
478                                 nb += NumberFilesToAdd(itr->string(), recursive);
479                         }
480                 }
481                 else
482                 {
483                         nb++;
484                 }
485           }
486         return nb;
487   }
488
489    //=================================================
490    // Test a directory to know if contains sub-directory to analyze
491   bool WxGimmickView::isNeedRecursive(std::string i_name)
492   {
493       boost::filesystem::directory_iterator iter(i_name), end_iter;
494           bool bfindir = false;
495                   for(; iter != end_iter; ++iter)
496                   {
497                           if(boost::filesystem::is_directory(*iter))
498                           {
499                                   return true;
500                           }
501                   }
502                   return false;
503   }
504   //=================================================
505
506   //=================================================
507   void WxGimmickView::OnSelectionChange(const std::vector<tree::Node*>& sel, bool isSelection, int selection, bool needProcess)
508   {      
509     GimmickDebugMessage(5,
510                         "WxGimmickView::OnSelectionChange"
511                         <<std::endl);
512     wxBusyCursor busy;
513         bool valid=true;
514         
515         if(sel.size()==0)
516         {
517                 valid= ValidateSelected(NULL,
518                                 mSelectionMinDimension,
519                                 mSelectionMaxDimension );
520         }
521         else if(needProcess)
522         {
523                 ResetExtent();
524                 std::vector<tree::Node*>::const_iterator i;
525                 for(i=sel.begin();i!=sel.end()&&valid;++i)
526                 {
527                         valid= ValidateSelected((*i),
528                                 mSelectionMinDimension,
529                                 mSelectionMaxDimension );
530                 }
531         }
532         else if(isSelection)
533         {
534                 valid= ValidateSelected(sel.front(),
535                                 mSelectionMinDimension,
536                                 mSelectionMaxDimension );
537         }
538         else
539         {
540                 ResetExtent();
541                 std::vector<tree::Node*>::const_iterator i;
542                 for(i=sel.begin();i!=sel.end()&&valid;++i)
543                 {
544                         valid= ValidateSelected((*i),
545                                 mSelectionMinDimension,
546                                 mSelectionMaxDimension );
547                 }
548         }
549         mText->SetLabel(crea::std2wx(GetMessage()));
550     /*if(valid)
551       {
552         ReadImageThreaded(sel);
553       }
554     else
555       {
556                   ClearSelection();
557       }*/
558         ReadImageThreaded(sel);
559    }
560
561   //==================================================
562
563   //==================================================
564   ///Reads Images (Threaded)
565   void WxGimmickView::ReadImageThreaded(const std::vector<tree::Node*>& sel)
566   {     
567    GimmickDebugMessage(5,
568                        "ReadImageThreaded"
569                        <<std::endl);
570    int maxprio = GetMaximalPriority();
571    int prio = maxprio + 2000;
572
573    if(sel.size()>0)
574    {
575    //First load the selected images
576    mCurImageItemToShow = sel.front();
577    pointers.clear();
578    int index = 0;
579    std::vector<tree::Node*>::const_iterator selected;
580    for(selected=sel.begin();selected!=sel.end();++selected)
581      {
582        GimmickDebugMessage(5,
583                            "Requesting image from selected "
584                            <<(*selected)->GetAttribute("FullFileName")
585                            <<std::endl);
586            //ImagePointerHolder* ph=new ImagePointerHolder(GetDefaultImage());
587            boost::shared_ptr<ImagePointerHolder> ph(new ImagePointerHolder(GetDefaultImage()));
588            pointers.push_back(ph);
589        RequestReading(*selected,prio,index,ph);
590        //       AddEntryToMap(*selected);
591        prio--;
592        index++;
593      }
594         mViewer->SetImageVector(pointers);
595         //Going up
596         prio = maxprio + 20;
597         std::vector<tree::Node*> up;
598         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetNodes(up,true);
599         std::vector<tree::Node*>::iterator iterUp;
600         for(iterUp=up.begin();iterUp!=up.end();++iterUp)
601         {
602                 GimmickDebugMessage(5,
603                                 "Requesting image from neighbors up "
604                                 <<(*iterUp)->GetAttribute("FullFileName")
605                                 <<std::endl);
606 //              ImagePointerHolder* ph=new ImagePointerHolder(GetDefaultImage());
607                 boost::shared_ptr<ImagePointerHolder> ph(new ImagePointerHolder(GetDefaultImage()));
608                 RequestReading(*iterUp,prio,-1,ph);
609                 //              AddEntryToMap(*iterUp);
610                 prio--;
611                 if (prio == maxprio) break;
612         }
613
614         //Going down
615         prio = maxprio + 19;
616         std::vector<tree::Node*> down;
617         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetNodes(down,false);
618         std::vector<tree::Node*>::iterator iterDown;
619         for(iterDown=down.begin();iterDown!=down.end();++iterDown)
620         {
621                 GimmickDebugMessage(5,
622                                 "Requesting image from neighbors down "
623                                 <<(*iterDown)->GetAttribute("FullFileName")
624                                 <<std::endl);
625                 //ImagePointerHolder* ph=new ImagePointerHolder(GetDefaultImage());
626                 boost::shared_ptr<ImagePointerHolder> ph(new ImagePointerHolder(GetDefaultImage()));
627                 RequestReading(*iterDown,prio,-1,ph);
628                 //              AddEntryToMap(*iterDown);
629                 prio--;
630                 if (prio == maxprio) break;
631         }
632    }
633    else
634    {
635            pointers.clear();
636            //ImagePointerHolder* ph=new ImagePointerHolder(GetDefaultImage());
637            boost::shared_ptr<ImagePointerHolder> ph(new ImagePointerHolder(GetDefaultImage()));
638            pointers.push_back(ph);
639            mViewer->SetImageVector(pointers);
640    }
641   }
642
643   //==================================================
644
645   //==================================================
646
647   //==================================================
648    void  WxGimmickView::OnInternalIdle()
649    {
650      if (!mConstructed) return;
651      static bool first_time = true;
652      if (false)
653      {
654        first_time = false;
655      }
656    //   GimmickMessage(1,"WxGimmickView : Refresh viewer"<<std::endl);
657         //  mViewer->StartPlayer();
658      if(mViewer)
659      {
660         mViewer->RefreshIfNecessary();
661      }
662   }
663
664    //==================================================
665
666   //==================================================
667    void  WxGimmickView::ClearSelection()
668    {
669         pointers.clear();
670         pointers.push_back(boost::shared_ptr<creaImageIO::ImagePointerHolder>(new ImagePointerHolder(GetDefaultImage())));
671         //pointers.push_back(new ImagePointerHolder(GetDefaultImage()));
672         mViewer->SetImageVector(pointers);
673         mViewer->RefreshIfNecessary();
674         ResetExtent();
675   }
676
677   //=================================================
678  
679   //=================================================
680   void WxGimmickView::OnRemove(wxCommandEvent& event)
681   {
682         //TODO Select current tree handler       
683      wxBusyCursor busy;
684          std::string remove;
685          mGimmick->GetSetting(SETTINGS_REMOVE_PATIENT_DISPLAY,remove);
686          GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->RemoveSelected(remove);
687          mGimmick->UpdateSetting(SETTINGS_REMOVE_PATIENT_DISPLAY,remove);
688      ClearSelection();
689   }
690   //=================================================
691
692
693   //=================================================
694   void WxGimmickView::AddIgnoreFile(tree::Node* toRemove)
695   {
696      mGimmick->RemoveFile(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),toRemove);
697    //  GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->UpdateLevel(1);
698   }
699
700   //=================================================
701   void WxGimmickView::CopyFiles(const std::vector<std::string>& filenames)
702   {
703      mGimmick->CopyFiles(filenames, crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())));
704      wxMessageBox(std2wx("The selected files have been copied"),_T("Copy files"),wxOK,this);
705   }
706
707    //=================================================
708   void WxGimmickView::AddDir(std::string dirName)
709   {
710      mProgressDialog = new wxProgressDialog(_T("Adding directory"),_T(""),1000,this,wxPD_ELAPSED_TIME |wxPD_CAN_ABORT );
711      mCurrentDirectory = crea::std2wx(dirName);
712      mGimmick->AddDir(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),dirName,true);
713      mProgressDialog->Pulse(_T("Updating view..."));
714
715      UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
716      delete mProgressDialog;
717      DisplayAddSummary();
718   }
719
720    //=================================================
721   void WxGimmickView::OnSynchronize(wxCommandEvent& event)
722   {       
723     wxBusyCursor busy;
724     const wxString choices[] = { _T("Check database for files deletion and addition and give a report."), 
725                                 _T("Check database for files deletion, addition and attributes change. Then give a report."), 
726                                 _T("Repair database (remove deleted files and add new files)."), 
727                                 _T("Repair database (remove deleted files, add new files and reset changed attributes).") } ;
728
729     wxSingleChoiceDialog dialog(this,
730                                 _T("Select one of the following synchronization actions:\n")
731                                 _T("Please note that, due to the heavy amount of operations required, this action might take a while."),
732                                 _T("Synchronization Settings"),
733                                 WXSIZEOF(choices), choices);
734
735     //dialog.SetSelection(0);
736
737     if (dialog.ShowModal() == wxID_OK)
738     {
739                         wxBusyCursor busy;
740         int sel=dialog.GetSelection();
741         bool repair=false;
742         bool checkAttributes=false;
743         if(sel==2 || sel==3){repair=true;}
744         if(sel==1 || sel==3){checkAttributes=true;}
745         std::string mess=mGimmick->Synchronize(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),repair, checkAttributes);
746         wxMessageBox(std2wx(mess),_T("Synchronization result"),wxOK,this);
747         if(sel==2 || sel==3){
748                 GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->UpdateLevel(1);
749         }
750                 
751     }
752   }
753   //=================================================
754
755   //=================================================
756   void WxGimmickView::OnSettings(wxCommandEvent& event)
757   {
758     wxDialog* dial= new wxDialog (this,-1,_T("System Settings"),wxDefaultPosition, wxSize(450,220));
759     wxBoxSizer  *siz = new wxBoxSizer(wxVERTICAL);
760     // Notebook
761     wxNotebook* nb= new wxNotebook(dial, -1, wxDefaultPosition, wxDefaultSize, 0);
762     
763     siz->Add( nb,1,wxGROW  ,0);  
764     CreateSettingsDialog(nb,dial);
765     dial->SetSizer(siz);
766     dial->ShowModal();
767   }
768
769   //=================================================
770   void WxGimmickView::OnImportExport(wxCommandEvent &Event)
771   {
772         wxBusyCursor busy;
773         // Test if one image is selected => export
774         // if not =>import
775     if (GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))])
776         {
777                 ExportImages();
778         }
779         else
780         {
781                 ImportImages();
782         }
783   }
784
785   void WxGimmickView::ExportImages()
786   {
787                 //Archive selection: name, emplacement
788                 //same process than copy local but to a zip
789                 // if settings are yes "always ask for descriptor addition", ask
790                 // if settings are yes, adding descriptor
791   }
792
793   void WxGimmickView::ImportImages()
794   {
795                 //Find the *.zip
796                 //dezip
797                 // Contain a descriptor.text
798                 // create a new database, and add to database
799                 // if not, add to current database
800                 // 
801   }
802
803   //=================================================
804   //AndresDonadio
805   void WxGimmickView::OnTools(wxCommandEvent& event)
806   {
807         mViewer->StopPlayer();
808                 
809         wxDialog* dial = new wxDialog (this,-1,_T("Tools"),wxDefaultPosition, wxSize(550,350));
810
811         wxSizer* buttonsSizer = dial->CreateSeparatedButtonSizer(wxOK|wxCANCEL);
812         wxNotebook* nb= new wxNotebook(dial, -1, wxDefaultPosition, wxDefaultSize, 0);
813         wxBoxSizer *dialSizer = new wxBoxSizer(wxVERTICAL);     
814         dialSizer->Add(nb,1,wxGROW,0);
815         dialSizer->Add(buttonsSizer,0,wxGROW);
816
817 #if defined(BUILD_BRUKER)
818         //First page: Bruker Image Reader
819         WxGimmickTools * gimmickTools = new WxGimmickTools(nb, mCurrentDirectory);
820         nb->AddPage( gimmickTools, _T("Bruker Image Reader") );
821 #endif
822
823         dial->SetSizer(dialSizer, true);
824         dial->Layout();
825         dial->ShowModal();
826
827         if (dial->GetReturnCode() == wxID_OK)
828         {
829 #if defined(BUILD_BRUKER)
830                 if (nb->GetSelection()==0)//Selection: Bruker Image Reader
831                 {
832                         std::string inputDir  = crea::wx2std(gimmickTools->getInputDir());
833                         std::string outputDir = crea::wx2std(gimmickTools->getOutputDir());
834                         
835                         bool addToDB = gimmickTools->getAddToDBCheckBoxValue();
836
837                         if (inputDir.compare("")!=0 && outputDir.compare("")!=0)
838                         {
839                                 if ( wxMessageBox(_T("Depending on the amount of Data the process can take between 1 and 5 minutes. Do you want to continue?"),
840                                                   _T("Please confirm"), wxICON_QUESTION | wxYES_NO) == wxYES )
841                                 {
842                                         Bruker2Dicom b2d;    
843                                         b2d.SetInputDirectory(inputDir);
844                                         b2d.SetOutputDirectory(outputDir);
845                                         b2d.SetConvertModeToDicom();
846                                         b2d.verbose=false;
847                                         b2d.Execute();
848
849                                         if (addToDB)
850                                         {
851                                                 mProgressDialog = new wxProgressDialog(_T("Adding directory"),_T(""),1000,this,wxPD_ELAPSED_TIME |wxPD_CAN_ABORT );
852                                                 mCurrentDirectory = gimmickTools->getOutputDir();
853                                                 mGimmick->AddDir(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),outputDir,true);
854                                                 mProgressDialog->Pulse(_T("Updating view..."));
855
856                                                 UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
857                                                 delete mProgressDialog;
858                                                 DisplayAddSummary();
859                                         }       
860                                 }
861                         }
862                         else
863                         {
864                                 wxMessageBox(_T("One or both of the directory fields are empty"),_T("Empty Fields"),wxOK,this);
865                         }
866         }
867         delete gimmickTools;
868 #endif
869         }
870         mViewer->StartPlayer();
871   }
872
873   //=================================================
874
875   void WxGimmickView::CreateSettingsDialog(wxNotebook* nb, wxDialog* dial)
876   {
877           //First page: Customization of configurations
878           //Copy Path string
879           std::string cp;
880           mGimmick->GetSetting(SETTINGS_COPY_PATH,cp);
881           //Database Path String
882           std::string dp;
883           mGimmick->GetSetting(SETTINGS_DBPATH,dp);
884           //Syncronization Event String
885           std::string se;
886           mGimmick->GetSetting(SETTINGS_SYNC_EVENT,se);
887           //Syncronization Frequency String
888           std::string sf;
889           mGimmick->GetSetting(SETTINGS_SYNC_FREQ,sf);
890
891           WxCustomizeConfigPanel * customConfig=new WxCustomizeConfigPanel(nb,dial,this,cp,dp,se,sf);
892
893           nb->AddPage( customConfig, crea::std2wx("Customize Configuration") );
894
895           //Second page: Creation of Databases
896           /*wxPanel* databaseCreation=new wxPanel(nb);
897           nb->AddPage( databaseCreation, crea::std2wx("Create Database") );*/
898
899           //Second page (temporary): Connection to PACS
900           WxPACSConnectionPanel* pacs=new WxPACSConnectionPanel(nb,dial, this);
901           nb->AddPage( pacs, crea::std2wx("Connect to PACS") );
902
903           //Third page: CD/DVD Watch
904           WxListenerPanel* cdWatch=new WxListenerPanel(nb,dial, this, mListener->IsPaused());
905           nb->AddPage( cdWatch, crea::std2wx("CD/DVD") );
906
907           //Fourth page: Selection of attributes to show
908           std::vector<std::string> shown;
909           std::vector<std::string> nShown;
910           GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetAttributes(shown,nShown,1);
911           int nLev=GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetNumberOfLevels();
912           WxAttributeSelectionPanel* attSelection=new WxAttributeSelectionPanel(nb,dial,this,shown,nShown,nLev);
913           nb->AddPage( attSelection, crea::std2wx("Selection of Attributes") );
914   }
915
916   //===================================================================
917   void WxGimmickView::GetVisibleAttributes(std::vector<std::string>& shown, 
918           std::vector<std::string>& nShown, int level)
919   {
920           GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetAttributes(shown,nShown,level);
921   }
922
923   //===================================================================
924   void WxGimmickView::OnAttributesChanged(const std::vector<std::string>& nShown, int level)
925   {
926           GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->SetNonVisibleAttributes(nShown,level);
927           std::vector<std::string> n=nShown;
928           GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->CreateCtrl(n,level);
929   }
930   //===================================================================
931   void WxGimmickView::OnSaveSettingsCallback(const std::string& copyPath,
932           const std::string& dbPath,
933           const std::string& syncEvent,
934           const std::string& syncFreq)
935   {
936           mGimmick->UpdateSetting(SETTINGS_COPY_PATH,copyPath);
937           mGimmick->UpdateSetting(SETTINGS_DBPATH,dbPath);
938           mGimmick->UpdateSetting(SETTINGS_SYNC_EVENT,syncEvent);
939           mGimmick->UpdateSetting(SETTINGS_SYNC_FREQ,syncFreq);
940   }
941
942   //===================================================================
943   void WxGimmickView::OnListenerCallback(const std::string& drive, bool addFiles, bool removeFiles)
944   {
945          mListener->SetMonitoredDrive(drive);
946          mListener->SetAddFilesState(addFiles);
947          mListener->SetRemoveFilesState(removeFiles);
948   }
949
950   //========================================================================
951
952   void WxGimmickView::OnDriveMount(bool mount)
953   {
954           GimmickMessage(1, "Gimmick::OnDriveMount"<<std::endl);
955           std::string drive;
956           mListener->GetMonitoredDrive(drive);
957           
958           if(mount)
959           {
960                 mViewer->StopPlayer();
961                 wxBusyCursor busy;
962                 wxString title(_T("Adding drive"));
963                 mProgressDialog = 
964                 new wxProgressDialog(_T("Adding drive"),
965                                         _T(""),
966                                         1000,
967                                         this,
968                                         wxPD_ELAPSED_TIME |
969                                         //                             wxPD_ESTIMATED_TIME | 
970                                         //                             wxPD_REMAINING_TIME |
971                                         wxPD_CAN_ABORT );
972                 mCurrentDirectory = crea::std2wx(drive);
973                 mGimmick->AddDir(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),drive,true);
974                 mProgressDialog->Pulse(_T("Updating view..."));
975                 
976                 UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
977                 delete mProgressDialog;
978                 DisplayAddSummary();
979                 mViewer->StartPlayer();  
980           }
981           else
982           {  
983                   mGimmick->DeleteDrive(drive);
984                   UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
985           } 
986   }
987
988    //========================================================================
989
990   void WxGimmickView::StartListeningThread()
991   {
992           mListener->Resume();
993   }
994
995    //========================================================================
996
997   void WxGimmickView::StopListeningThread()
998   {
999           mListener->Pause();
1000   }
1001
1002   //========================================================================
1003   void WxGimmickView::CreateEditFieldsDialog(tree::Node* node, std::vector<std::string> names, std::vector<std::string> keys)
1004   {
1005     wxDialog* dial= new wxDialog (this,-1,crea::std2wx("Edit Fields for node "+node->GetLabel()),wxDefaultPosition, wxSize(350,155));
1006     wxBoxSizer  *siz = new wxBoxSizer(wxVERTICAL);
1007     WxEditFieldsPanel* ef = new WxEditFieldsPanel(dial, dial, this, node, names, keys);
1008
1009     siz->Add( ef,1,wxGROW  ,0); 
1010     dial->SetSizer(siz);
1011     dial->ShowModal();  
1012   }
1013
1014   //========================================================================
1015   void WxGimmickView::OnFieldsEdited(tree::Node* node, const std::string& name, const std::string& key, const std::string& val)
1016   {
1017      mGimmick->EditField(node, crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())), name, key, val);
1018      UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
1019   }
1020
1021   //=================================================
1022   /// AddProgress Gimmick callback
1023   void WxGimmickView::OnAddProgress( Gimmick::AddProgress& p)
1024   {
1025     char mess[200];
1026     sprintf(mess,"%i dirs : %i files :\n            %i handled - %i added",
1027            p.GetNumberScannedDirs(),
1028            p.GetNumberScannedFiles(),
1029            p.GetNumberHandledFiles(),
1030            p.GetNumberAddedFiles());
1031     //    std::cout << "OnAddProgress "<<mess<<std::endl;
1032     wxString s(wxString::From8BitData(mess));
1033     //  std::cout << "Pulse"<<std::endl;
1034     if (!mProgressDialog->Pulse(s)) 
1035       {
1036         p.SetStop();
1037       }
1038     //  std::cout << "OnAddProgress ok"<<std::endl;
1039   }
1040   //=================================================
1041
1042   //=================================================
1043   void WxGimmickView::DisplayAddSummary()
1044   {
1045     const Gimmick::AddProgress& p = mGimmick->GetAddProgress();
1046     std::stringstream mess;
1047     mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs()  << "\n";
1048     mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
1049     mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
1050     mess << "Files\tadded  \t: " << p.GetNumberAddedFiles()   << "\n\n";
1051     wxMessageBox(std2wx(mess.str()),_T("Addition result"),wxOK,this);
1052   }
1053
1054   ////////////////////////////////////////////////
1055   // Add a DB to application                    //
1056   // @param event : WxEvent                     //
1057   // @return : -                                //
1058   ////////////////////////////////////////////////
1059   void WxGimmickView::OnAddDB(wxCommandEvent& event)
1060   {
1061           //Select DB
1062           long style = wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST;
1063           std::string wc("*.sqlite3*");
1064           wxFileDialog* FD = new wxFileDialog( 0, 
1065                                          _T("Select file"),
1066                                          _T(""),
1067                                          _T(""),
1068                                          crea::std2wx(wc),
1069                                          style,
1070                                          wxDefaultPosition);
1071     
1072     if (FD->ShowModal()==wxID_OK)
1073         {
1074                 wxBusyCursor busy;
1075                 wxArrayString files;
1076                 FD->GetPaths(files);
1077                 std::stringstream st;
1078                 for(int i = 0; i< files.size(); i++)
1079                 {
1080                         //get name of DB (file name)
1081                   size_t pos = files[i].find_last_of(_T("\\"));
1082                   std::string name = crea::wx2std(files[i].substr(pos+1));
1083                   pos = name.find_last_of(".");
1084                   name = name.substr(0,pos);
1085                   //create TreeHandler
1086                   mGimmick->addDB(name, crea::wx2std(files[i]));
1087                   //create TreeView
1088                   CreateSingleTreeView(name);
1089                 }
1090         }
1091   }
1092     ////////////////////////////////////////////////////
1093   // Create a DB from an Attributes Descriptor files  //
1094   // @param event : WxEvent                                     //
1095   // @return : -                                                //
1096   //////////////////////////////////////////////////
1097   void WxGimmickView::OnCreateDB(wxCommandEvent& event)
1098   {
1099         //  PACSConnection("");
1100         WxDescriptorPanel * DescriptorPan = new WxDescriptorPanel(this, mGimmick->GetHomeDirectory());
1101         DescriptorPan->Layout();
1102         if ( DescriptorPan->ShowModal() == ID_DSCP_APPLY)
1103         {
1104                 wxBusyCursor busy;
1105                 std::string file(DescriptorPan->GetDescriptor());
1106                 if (!file.empty())
1107                 {
1108                         size_t pos = file.find_last_of("\\");
1109                         std::string name = file.substr(pos+1);
1110                         std::string directory = file.substr(0,pos);
1111                         pos = name.find_last_of(".");
1112                         name = name.substr(0,pos);
1113                         //get directory to store DB
1114                         directory +=  "\\" + name + ".sqlite3";
1115                         //create createDB
1116                         mGimmick->createDB(name, file,directory);
1117                         //create TreeHandler
1118                         mGimmick->addDB(name, directory);
1119                         //create TreeView
1120                         CreateSingleTreeView(name);
1121                 }
1122         }
1123   }
1124
1125    //=================================================
1126
1127    //=================================================
1128   BEGIN_EVENT_TABLE(WxGimmickView, wxPanel)
1129     EVT_TOOL(TOOL_CREATEDB_ID, WxGimmickView::OnCreateDB)
1130     EVT_TOOL(TOOL_ADDFILES_ID, WxGimmickView::OnAddFiles)
1131     EVT_TOOL(TOOL_ADDDIR_ID, WxGimmickView::OnAddDir)
1132     EVT_TOOL(TOOL_ADDDATABASE_ID, WxGimmickView::OnAddDB)
1133     EVT_TOOL(TOOL_REMOVE_ID, WxGimmickView::OnRemove)
1134     EVT_TOOL(TOOL_SYNCHRONIZE_ID, WxGimmickView::OnSynchronize)
1135     EVT_TOOL(TOOL_SETTINGS_ID, WxGimmickView::OnSettings)
1136     EVT_TOOL(TOOL_TOOLS_ID, WxGimmickView::OnTools)
1137   END_EVENT_TABLE()
1138   //=================================================
1139
1140 } // EO namespace creaImageIO
1141