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