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