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