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