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