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