]> Creatis software - creaImageIO.git/blob - src2/creaImageIOWxGimmickView.cpp
Add GetSelectImagesInVector()
[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     // Notebook
127     mNotebook = new wxNotebook(mSplitter,
128                                -1, wxDefaultPosition, wxDefaultSize, 0);
129
130     //Gimmick
131     mGimmick=gimmick;
132
133     mSelectionMaxDimension = max_dim;
134     mSelectionMinDimension = min_dim;
135     
136     // Create the views
137     CreateTreeViews();
138
139     // Bottom panel 
140     mBottomPanel = new wxPanel(mSplitter,-1);
141     
142     wxBoxSizer *bottom_sizer = new wxBoxSizer(wxVERTICAL); //HORIZONTAL);
143     
144     
145     // Previewer
146     mViewer = new WxViewer(mBottomPanel, wxID_ANY, wxT("Gimmick! Viewer"),wxDefaultPosition, wxDefaultSize );
147         //pointers.push_back(new ImagePointerHolder(GetDefaultImage())
148         pointers.push_back(boost::shared_ptr<creaImageIO::ImagePointerHolder>(new ImagePointerHolder(GetDefaultImage())));
149
150         mViewer->SetImageVector(pointers);
151         mViewer->StartPlayer();
152
153
154     bottom_sizer->Add(mViewer,1,wxGROW,1);
155     //    mViewer->Show();
156
157     mText = new wxStaticText(mBottomPanel, wxID_ANY, wxT("Welcome to Gimmick!"));
158     bottom_sizer->Add(mText,0,wxGROW,0);
159
160           
161           
162     mBottomPanel->SetSizer(bottom_sizer);
163
164     // Splitting
165     int hsize = size.GetHeight();
166
167     int top_minsize = 450;
168     int bottom_minsize = 50;
169
170     mSplitter->SetMinimumPaneSize( bottom_minsize );
171     mSplitter->SplitHorizontally( mNotebook, mBottomPanel, 
172                                   top_minsize);
173
174     sizer->Add( mSplitter, 1, wxGROW, 0);
175
176     mProgressDialog=0;
177     SetSizer( sizer );     
178     SetAutoLayout(true);
179     Layout();
180     mListener=new Listener();
181     mListener->ConnectObserver(boost::bind( &WxGimmickView::OnDriveMount, this, _1 ) );
182     mListener->Create();
183     mListener->Run();
184     mListener->Pause();
185
186     mConstructed = true;
187   }
188   //======================================================================
189
190   //======================================================================
191   /// Destructor
192   WxGimmickView::~WxGimmickView()
193   {
194         // stop the viewer before application exit.
195     mViewer->StopPlayer();
196     GimmickDebugMessage(1,"WxGimmickView::~WxGimmickView"
197                         <<std::endl);
198         delete mIcon;
199     if(mListener->IsAlive())
200     {
201         mListener->Delete();
202     }
203   }
204   //======================================================================
205   
206   //======================================================================
207   /// Creates the tool bar
208   void WxGimmickView::CreateToolBar()
209   {
210     long style = wxTB_HORIZONTAL | wxNO_BORDER | wxTB_TEXT;
211     mToolBar = new wxToolBar(this,-1,wxDefaultPosition,wxDefaultSize,
212                              style);
213
214     mToolAddFile = mToolBar->AddTool( TOOL_ADDFILES_ID, 
215                                       _T("Add file(s)"),
216                                       mIcon->GetBitmap(Icon_page_down),
217                                       _T("Add one or more file to database")
218                                       );
219     mToolAddDir = mToolBar->AddTool( TOOL_ADDDIR_ID, 
220                                       _T("Add folder"),
221                                       mIcon->GetBitmap(Icon_folder_down),
222                                       _T("Add the content of a folder to database")
223                                       );
224     mToolAddDatabase = mToolBar->AddTool( TOOL_ADDDATABASE_ID, 
225                                       _T("Open database"),
226                                       mIcon->GetBitmap(Icon_database_add),
227                                       _T("Open a local or distant database")
228                                       );
229     mToolRemove = mToolBar->AddTool( TOOL_REMOVE_ID, 
230                                       _T("Remove"),
231                                       mIcon->GetBitmap(Icon_remove),
232                                       _T("Remove selected items")
233                                       );
234     mToolSynchronize = mToolBar->AddTool( TOOL_SYNCHRONIZE_ID, 
235                                       _T("Synchronize"),
236                                       mIcon->GetBitmap(Icon_synchronize),
237                                       _T("Synchronizes the database with disk")
238                                       );
239     mToolHelp = mToolBar->AddTool( TOOL_HELP_ID, 
240                                       _T("Help"),
241                                       mIcon->GetBitmap(Icon_help),
242                                       _T("Open help window")
243                                       );
244     mToolSettings = mToolBar->AddTool( TOOL_SETTINGS_ID, 
245                                       _T("System settings"),
246                                       mIcon->GetBitmap(Icon_settings),
247                                       _T("Allows the modification of various system settings")
248                                       );
249     mToolTools = mToolBar->AddTool( TOOL_TOOLS_ID, 
250                                       _T("Tools"),
251                                       mIcon->GetBitmap(Icon_tools),
252                                       _T("Applies tools to images")
253                                       );
254     mToolAddFile = mToolBar->AddTool( TOOL_CREATEDB_ID, 
255                                       _T("Create database"),
256                                       mIcon->GetBitmap(Icon_create_database),
257                                       _T("Create DB from an Attributes Descriptor file")
258                                       );
259 #if defined(BUILD_PACS)
260         mToolAddFile = mToolBar->AddTool( TOOL_PACS_ID, 
261                                       _T("PACS Connection,"),
262                                       mIcon->GetBitmap(Icon_create_database),
263                                       _T("Echo, Find and Get to a PACS")
264                                       );
265 #endif
266     //const wxBitmap& bitmap1, const wxString& shortHelpString = "", wxItemKind kind = wxITEM_NORMAL)
267
268     mToolBar->Realize();
269   }
270   //======================================================================
271
272  
273   //======================================================================
274   /// Create the tree view for TreeHandler provided
275   void WxGimmickView::CreateTreeView( TreeHandler* h)
276   {
277     std::string name(h->GetTree().GetAttribute("Name"));
278     GimmickMessage(2,"Creating the tree view for '"<<
279                    name<<"'"<<std::endl);
280     // Create the WxTreeView
281     WxTreeView* view = new WxTreeView(h, this, mNotebook, -1);
282
283     // TO DO : TEST THAT A VIEW WITH SAME NAME IS NOT
284     // ALREADY IN THE MAP
285     GetTreeViewMap()[name] = view;
286
287     // Add Notebook page
288     mNotebook->AddPage( view, crea::std2wx(name) );
289         
290   }
291
292   //======================================================================
293   void WxGimmickView::GetSelectedImages(std::vector<vtkImageData*>& s, int dim)
294   {
295         std::vector<std::string> files;
296         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetSelectedAsString(files);
297         ReadImagesNotThreaded(s, files, dim);
298   }
299
300   //======================================================================
301   void WxGimmickView::GetSelectedImagesInVector(std::vector<vtkImageData*>& s, int dim)
302   {
303         std::vector<std::string> files;
304         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetSelectedAsString(files);
305         ReadImagesNotThreadedInVector(s, files, dim);
306   }
307   //======================================================================
308
309   //======================================================================
310   void WxGimmickView::GetSelectedFiles(std::vector<std::string>& s)
311   {
312         GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))]->GetSelectedAsString(s);
313   }
314   //======================================================================
315
316   //======================================================================
317   void WxGimmickView::GetImages(int dim, 
318                                 const std::vector<std::string>& files, 
319                                 std::vector<vtkImageData*>& s)
320   {
321         ReadImagesNotThreaded(s,files,dim);
322   }
323   //======================================================================
324
325
326   //=================================================
327   void WxGimmickView::CreateIconList()
328   {
329     // Size of the icons;
330     int size = 16;
331
332     wxIcon icons[20];
333     // should correspond to Icon_xxx enum
334     icons[Icon_accept]          = wxIcon(accept_xpm);
335     icons[Icon_add]             = wxIcon(add_xpm);
336     icons[Icon_folder_down]     = wxIcon(folder_down_xpm);
337     icons[Icon_page_down]       = wxIcon(page_down_xpm);
338     icons[Icon_remove]          = wxIcon(remove_xpm);
339     icons[Icon_database_add]    = wxIcon(database_add_xpm);
340     icons[Icon_help]            = wxIcon(help_xpm);
341     icons[Icon_synchronize]     = wxIcon(synchronize_xpm);
342     icons[Icon_create_database] = wxIcon(create_database_xpm);
343     icons[Icon_settings]        = wxIcon(settings_xpm);
344     icons[Icon_tools]           = wxIcon(tools_xpm);
345
346     //   unsigned int NbIcons = 8;
347     // Make an image list containing small icons
348     mIcon = new wxImageList(size,size,true);
349     
350     // Make all icons the same size = size of the first one
351     int sizeOrig = icons[0].GetWidth();
352     for ( size_t i = 0; i < icon_number; i++ )
353       {
354         if ( size == sizeOrig )
355           {
356             mIcon->Add(icons[i]);
357           }
358         else
359           {
360             mIcon->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));
361           }
362       }
363   }
364   //=================================================
365
366
367   //=================================================
368   void WxGimmickView::OnAddFiles(wxCommandEvent& event)
369   {
370     mViewer->StopPlayer();
371     long style = wxOPEN | wxFILE_MUST_EXIST | wxFD_MULTIPLE;
372     std::string wc("*");
373     wxFileDialog* FD = new wxFileDialog( 0, 
374                                          _T("Select file"),
375                                          _T(""),
376                                          _T(""),
377                                          crea::std2wx(wc),
378                                          style,
379                                          wxDefaultPosition);
380     
381     if (FD->ShowModal()==wxID_OK)
382       {
383         wxBusyCursor busy;
384
385         wxArrayString files;
386         FD->GetPaths(files);
387         unsigned int i;
388         std::vector<std::string> filenames;
389         for (i=0;i<files.GetCount();++i)
390         {
391           filenames.push_back(wx2std(files[i]));
392           GimmickMessage(2,"Adding File "<<files[i]<<"."<<std::endl);
393         }
394
395         mProgressDialog = 
396           new wxProgressDialog(_T("Adding file(s)"),
397                                _T(""),
398                                1000,
399                                this,
400                                wxPD_ELAPSED_TIME |
401                                // wxPD_ESTIMATED_TIME |
402                                // wxPD_REMAINING_TIME |
403                                wxPD_CAN_ABORT );
404
405         // TO DO : select the current tree handler
406         mGimmick->AddFiles(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),filenames);
407
408         mProgressDialog->Pulse(_T("Updating view..."));
409
410         UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
411         delete mProgressDialog;
412         DisplayAddSummary();    
413
414       }
415         mViewer->StartPlayer(); 
416   }
417   //=================================================
418
419   //=================================================
420   void WxGimmickView::OnAddDir(wxCommandEvent& event)
421   {
422     mViewer->StopPlayer();
423         std::string name = crea::wx2std(mNotebook->GetCurrentPage()->GetName());
424     long style = wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST;
425     wxDirDialog* FD = 
426          new wxDirDialog( 0, 
427                        _T("Select directory"),
428                        mCurrentDirectory,
429                        style);
430     
431     if (FD->ShowModal()==wxID_OK)
432     {
433         std::string dirname = wx2std (FD->GetPath());
434         bool recurse =  isNeedRecursive(dirname);
435         if (recurse)
436         {
437              recurse = wxMessageBox(_T("Recurse into sub-directories ?"), _T("Scan directory"), wxYES_NO,this ) == wxYES ? true : false;
438         }
439
440                 wxBusyCursor busy;
441                 wxString title(_T("Adding directory"));
442                 if (recurse) 
443                 title = _T("Adding directory (recursive)");
444                 mProgressDialog = 
445                 new wxProgressDialog(_T("Adding directory"),
446                                         _T(""),
447                                         NumberFilesToAdd(dirname,recurse),
448                                         this,
449                                         wxPD_ELAPSED_TIME | 
450                                         wxPD_SMOOTH |
451                                         // wxPD_ESTIMATED_TIME |
452                                         // wxPD_REMAINING_TIME |
453                                         wxPD_CAN_ABORT );
454
455                 mCurrentDirectory = FD->GetPath();  
456                 mGimmick->AddDir(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),dirname,recurse);
457                 mProgressDialog->Pulse(_T("Updating view..."));
458
459                 UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
460                 delete mProgressDialog;
461                 DisplayAddSummary();
462           }
463     mViewer->StartPlayer();
464   }
465
466
467   //=================================================
468   // Determines number of files potentially to add to database
469    int WxGimmickView::NumberFilesToAdd(const std::string &dirpath, bool recursive)
470   {
471            int nb = 0;
472            if ( !boost::filesystem::exists( dirpath ) ) return nb;
473            boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
474            for ( boost::filesystem::directory_iterator itr( dirpath );  itr != end_itr;  ++itr )
475           {
476                 // If is directory & recurse : do recurse
477                 if ( boost::filesystem::is_directory(itr->status()) )
478                 {
479                         if (recursive) 
480                         {
481                                 nb += NumberFilesToAdd(itr->string(), recursive);
482                         }
483                 }
484                 else
485                 {
486                         nb++;
487                 }
488           }
489         return nb;
490   }
491
492    //=================================================
493    // Test a directory to know if contains sub-directory to analyze
494   bool WxGimmickView::isNeedRecursive(std::string i_name)
495   {
496       boost::filesystem::directory_iterator iter(i_name), end_iter;
497           bool bfindir = false;
498                   for(; iter != end_iter; ++iter)
499                   {
500                           if(boost::filesystem::is_directory(*iter))
501                           {
502                                   return true;
503                           }
504                   }
505                   return false;
506   }
507   //=================================================
508
509   //=================================================
510   void WxGimmickView::OnSelectionChange(const std::vector<tree::Node*>& sel, bool isSelection, int selection, bool needProcess)
511   {      
512     GimmickDebugMessage(5,
513                         "WxGimmickView::OnSelectionChange"
514                         <<std::endl);
515     wxBusyCursor busy;
516         bool valid=true;
517         
518         if(sel.size()==0)
519         {
520                 valid= ValidateSelected(NULL,
521                                 mSelectionMinDimension,
522                                 mSelectionMaxDimension );
523         }
524         else if(needProcess)
525         {
526                 ResetExtent();
527                 std::vector<tree::Node*>::const_iterator i;
528                 for(i=sel.begin();i!=sel.end()&&valid;++i)
529                 {
530                         valid= ValidateSelected((*i),
531                                 mSelectionMinDimension,
532                                 mSelectionMaxDimension );
533                 }
534         }
535         else if(isSelection)
536         {
537                 valid= ValidateSelected(sel.front(),
538                                 mSelectionMinDimension,
539                                 mSelectionMaxDimension );
540         }
541         else
542         {
543                 ResetExtent();
544                 std::vector<tree::Node*>::const_iterator i;
545                 for(i=sel.begin();i!=sel.end()&&valid;++i)
546                 {
547                         valid= ValidateSelected((*i),
548                                 mSelectionMinDimension,
549                                 mSelectionMaxDimension );
550                 }
551         }
552         mText->SetLabel(crea::std2wx(GetMessage()));
553     /*if(valid)
554       {
555         ReadImageThreaded(sel);
556       }
557     else
558       {
559                   ClearSelection();
560       }*/
561         ReadImageThreaded(sel);
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   //=================================================
769   void WxGimmickView::OnImportExport(wxCommandEvent &Event)
770   {
771         wxBusyCursor busy;
772         // Test if one image is selected => export
773         // if not =>import
774     if (GetTreeViewMap()[crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection()))])
775         {
776                 ExportImages();
777         }
778         else
779         {
780                 ImportImages();
781         }
782   }
783
784   void WxGimmickView::ExportImages()
785   {
786                 //Archive selection: name, emplacement
787                 //same process than copy local but to a zip
788                 // if settings are yes "always ask for descriptor addition", ask
789                 // if settings are yes, adding descriptor
790   }
791
792   void WxGimmickView::ImportImages()
793   {
794                 //Find the *.zip
795                 //dezip
796                 // Contain a descriptor.text
797                 // create a new database, and add to database
798                 // if not, add to current database
799                 // 
800   }
801
802   //=================================================
803   //AndresDonadio
804   void WxGimmickView::OnTools(wxCommandEvent& event)
805   {
806         mViewer->StopPlayer();
807                 
808         wxDialog* dial = new wxDialog (this,-1,_T("Tools"),wxDefaultPosition, wxSize(550,350));
809
810         wxSizer* buttonsSizer = dial->CreateSeparatedButtonSizer(wxOK|wxCANCEL);
811         wxNotebook* nb= new wxNotebook(dial, -1, wxDefaultPosition, wxDefaultSize, 0);
812         wxBoxSizer *dialSizer = new wxBoxSizer(wxVERTICAL);     
813         dialSizer->Add(nb,1,wxGROW,0);
814         dialSizer->Add(buttonsSizer,0,wxGROW);
815
816 #if defined(BUILD_BRUKER)
817         //First page: Bruker Image Reader
818         WxGimmickTools * gimmickTools = new WxGimmickTools(nb, mCurrentDirectory);
819         nb->AddPage( gimmickTools, _T("Bruker Image Reader") );
820 #endif
821
822         dial->SetSizer(dialSizer, true);
823         dial->Layout();
824         dial->ShowModal();
825
826         if (dial->GetReturnCode() == wxID_OK)
827         {
828 #if defined(BUILD_BRUKER)
829                 if (nb->GetSelection()==0)//Selection: Bruker Image Reader
830                 {
831                         std::string inputDir  = crea::wx2std(gimmickTools->getInputDir());
832                         std::string outputDir = crea::wx2std(gimmickTools->getOutputDir());
833                         
834                         bool addToDB = gimmickTools->getAddToDBCheckBoxValue();
835
836                         if (inputDir.compare("")!=0 && outputDir.compare("")!=0)
837                         {
838                                 if ( wxMessageBox(_T("Depending on the amount of Data the process can take between 1 and 5 minutes. Do you want to continue?"),
839                                                   _T("Please confirm"), wxICON_QUESTION | wxYES_NO) == wxYES )
840                                 {
841                                         Bruker2Dicom b2d;    
842                                         b2d.SetInputDirectory(inputDir);
843                                         b2d.SetOutputDirectory(outputDir);
844                                         b2d.SetConvertModeToDicom();
845                                         b2d.verbose=false;
846                                         b2d.Execute();
847
848                                         if (addToDB)
849                                         {
850                                                 mProgressDialog = new wxProgressDialog(_T("Adding directory"),_T(""),1000,this,wxPD_ELAPSED_TIME |wxPD_CAN_ABORT );
851                                                 mCurrentDirectory = gimmickTools->getOutputDir();
852                                                 mGimmick->AddDir(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),outputDir,true);
853                                                 mProgressDialog->Pulse(_T("Updating view..."));
854
855                                                 UpdateTreeViewLevel(crea::wx2std(mNotebook->GetPageText(mNotebook->GetSelection())),1);
856                                                 delete mProgressDialog;
857                                                 DisplayAddSummary();
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         mViewer->StartPlayer();
870   }
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