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