Implemented trash without restore
[pithos-web-client] / src / gr / grnet / pithos / web / client / FileList.java
1 /*
2  * Copyright 2011 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35
36 package gr.grnet.pithos.web.client;
37
38 import gr.grnet.pithos.web.client.foldertree.File;
39 import gr.grnet.pithos.web.client.foldertree.Folder;
40 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
41
42 import java.util.ArrayList;
43 import java.util.Collections;
44 import java.util.Comparator;
45 import java.util.Iterator;
46 import java.util.List;
47
48 import com.google.gwt.cell.client.ImageResourceCell;
49 import com.google.gwt.cell.client.SafeHtmlCell;
50 import com.google.gwt.cell.client.TextCell;
51 import com.google.gwt.cell.client.ValueUpdater;
52 import com.google.gwt.core.client.GWT;
53 import com.google.gwt.event.dom.client.ContextMenuEvent;
54 import com.google.gwt.event.dom.client.ContextMenuHandler;
55 import com.google.gwt.i18n.client.DateTimeFormat;
56 import com.google.gwt.resources.client.ImageResource;
57 import com.google.gwt.safehtml.client.SafeHtmlTemplates;
58 import com.google.gwt.safehtml.shared.SafeHtml;
59 import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
60 import com.google.gwt.user.cellview.client.CellTable;
61 import com.google.gwt.user.cellview.client.Column;
62 import com.google.gwt.user.client.Event;
63 import com.google.gwt.user.client.ui.Composite;
64 import com.google.gwt.user.client.ui.VerticalPanel;
65 import com.google.gwt.view.client.ListDataProvider;
66 import com.google.gwt.view.client.MultiSelectionModel;
67 import com.google.gwt.view.client.ProvidesKey;
68
69 /**
70  * A composite that displays the list of files in a particular folder.
71  */
72 public class FileList extends Composite {
73
74         ListDataProvider<File> provider = new ListDataProvider<File>();
75
76     /**
77        * The styles applied to the table.
78        */
79     interface TableStyle extends CellTable.Style {
80     }
81
82         interface TableResources extends CellTable.Resources {
83             @Override
84                 @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
85             TableStyle cellTableStyle();
86         }
87         
88         static interface Templates extends SafeHtmlTemplates {
89             Templates INSTANCE = GWT.create(Templates.class);
90
91             @Template("<div id='dragHelper' style='border:1px solid black; background-color:#ffffff; color:black; width:150px;z-index:100'></div>")
92             SafeHtml outerHelper();
93
94         @Template("<span id='{0}'>{0}</span>")
95         public SafeHtml filenameSpan(String filename);
96
97         @Template("<a href='{0}' title='{1}' rel='lytebox[mnf]' onclick='myLytebox.start(this, false, false); return false;'>(view)</a>")
98         public SafeHtml viewLink(String link, String title);
99
100         @Template("<table><tr><td rowspan='3'>{0}</td><td style='font-size:95%;' id='{1}'>{1}</td></tr><tr><td>{2}</td></tr></table>")
101         public SafeHtml rendelContactCell(String imageHtml, String name, String fileSize);
102
103         @Template("<span id='{0}' class='{1}'>{2}</span>")
104         public SafeHtml spanWithIdAndClass(String id, String cssClass, String content);
105         }
106
107         protected final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
108
109         /**
110          * Specifies that the images available for this composite will be the ones
111          * available in FileContextMenu.
112          */
113         public interface Images extends FolderTreeView.Images {
114
115                 @Source("gr/grnet/pithos/resources/blank.gif")
116                 ImageResource blank();
117
118                 @Source("gr/grnet/pithos/resources/asc.png")
119                 ImageResource asc();
120
121                 @Source("gr/grnet/pithos/resources/desc.png")
122                 ImageResource desc();
123
124                 @Source("gr/grnet/pithos/resources/mimetypes/document_shared.png")
125                 ImageResource documentShared();
126
127                 @Source("gr/grnet/pithos/resources/mimetypes/kcmfontinst.png")
128                 ImageResource wordprocessor();
129
130                 @Source("gr/grnet/pithos/resources/mimetypes/log.png")
131                 ImageResource spreadsheet();
132
133                 @Source("gr/grnet/pithos/resources/mimetypes/kpresenter_kpr.png")
134                 ImageResource presentation();
135
136                 @Source("gr/grnet/pithos/resources/mimetypes/acroread.png")
137                 ImageResource pdf();
138
139                 @Source("gr/grnet/pithos/resources/mimetypes/image.png")
140                 ImageResource image();
141
142                 @Source("gr/grnet/pithos/resources/mimetypes/video2.png")
143                 ImageResource video();
144
145                 @Source("gr/grnet/pithos/resources/mimetypes/knotify.png")
146                 ImageResource audio();
147
148                 @Source("gr/grnet/pithos/resources/mimetypes/html.png")
149                 ImageResource html();
150
151                 @Source("gr/grnet/pithos/resources/mimetypes/txt.png")
152                 ImageResource txt();
153
154                 @Source("gr/grnet/pithos/resources/mimetypes/ark2.png")
155                 ImageResource zip();
156
157                 @Source("gr/grnet/pithos/resources/mimetypes/kcmfontinst_shared.png")
158                 ImageResource wordprocessorShared();
159
160                 @Source("gr/grnet/pithos/resources/mimetypes/log_shared.png")
161                 ImageResource spreadsheetShared();
162
163                 @Source("gr/grnet/pithos/resources/mimetypes/kpresenter_kpr_shared.png")
164                 ImageResource presentationShared();
165
166                 @Source("gr/grnet/pithos/resources/mimetypes/acroread_shared.png")
167                 ImageResource pdfShared();
168
169                 @Source("gr/grnet/pithos/resources/mimetypes/image_shared.png")
170                 ImageResource imageShared();
171
172                 @Source("gr/grnet/pithos/resources/mimetypes/video2_shared.png")
173                 ImageResource videoShared();
174
175                 @Source("gr/grnet/pithos/resources/mimetypes/knotify_shared.png")
176                 ImageResource audioShared();
177
178                 @Source("gr/grnet/pithos/resources/mimetypes/html_shared.png")
179                 ImageResource htmlShared();
180
181                 @Source("gr/grnet/pithos/resources/mimetypes/txt_shared.png")
182                 ImageResource txtShared();
183
184                 @Source("gr/grnet/pithos/resources/mimetypes/ark2_shared.png")
185                 ImageResource zipShared();
186
187         }
188         
189         /**
190          * The number of files in this folder.
191          */
192         int folderFileCount;
193
194         /**
195          * Total folder size
196          */
197         long folderTotalSize;
198
199         /**
200          * A cache of the files in the list.
201          */
202         private List<File> files;
203
204         /**
205          * The widget's image bundle.
206          */
207         protected final Images images;
208         
209         protected CellTable<File> celltable;
210
211         private final MultiSelectionModel<File> selectionModel;
212
213         protected final List<SortableHeader> allHeaders = new ArrayList<SortableHeader>();
214
215         SortableHeader nameHeader;
216
217     FolderTreeView treeView;
218
219     protected Pithos app;
220
221     /**
222          * Construct the file list widget. This entails setting up the widget
223          * layout, fetching the number of files in the current folder from the
224          * server and filling the local file cache of displayed files with data from
225          * the server, as well.
226          *
227          * @param _images
228          */
229         public FileList(final Pithos _app, Images _images, FolderTreeView _treeView) {
230         app = _app;
231                 images = _images;
232         this.treeView = _treeView;
233
234         CellTable.Resources resources = GWT.create(TableResources.class);
235
236         ProvidesKey<File> keyProvider = new ProvidesKey<File>(){
237
238                         @Override
239                         public Object getKey(File item) {
240                                 return item.getUri();
241                         }
242                 };
243
244                 celltable = new CellTable<File>(10, resources, keyProvider);
245         celltable.setWidth("100%");
246         celltable.setStyleName("pithos-List");
247
248                 Column<File, ImageResource> status = new Column<File, ImageResource>(new ImageResourceCell() {
249                     @Override
250                 public boolean handlesSelection() {
251                     return false;
252                 }
253                 })
254         {
255                  @Override
256                  public ImageResource getValue(File entity) {
257                      return getFileIcon(entity);
258                  }
259             };
260             celltable.addColumn(status,"");
261
262         final Column<File,SafeHtml> nameColumn = new Column<File,SafeHtml>(new SafeHtmlCell()) {
263
264                         @Override
265                         public SafeHtml getValue(File object) {
266                                 SafeHtmlBuilder sb = new SafeHtmlBuilder();
267                 sb.append(Templates.INSTANCE.filenameSpan(object.getName()));
268                                 if (object.getContentType().endsWith("png") || object.getContentType().endsWith("gif") || object.getContentType().endsWith("jpeg")) {
269                                 sb.appendHtmlConstant("&nbsp;")
270                       .append(Templates.INSTANCE.viewLink(object.getUri(), object.getOwner() + " : " + object.getPath() + object.getName()));
271                                 }
272                                 
273                                 return sb.toSafeHtml();
274                         }
275                         
276                 };
277         celltable.addColumn(nameColumn, nameHeader = new SortableHeader("Name"));
278                 allHeaders.add(nameHeader);
279                 nameHeader.setUpdater(new FileValueUpdater(nameHeader, "name"));
280
281                 celltable.redrawHeaders();
282                 
283         Column<File,String> aColumn = new Column<File,String>(new TextCell()) {
284                         @Override
285                         public String getValue(File object) {
286                                 // TODO Auto-generated method stub
287                                 return object.getSizeAsString();
288                         }
289                 };
290         SortableHeader aheader = new SortableHeader("Size");
291         celltable.addColumn(aColumn, aheader);
292                 allHeaders.add(aheader);
293                 aheader.setUpdater(new FileValueUpdater(aheader, "size"));
294
295         aColumn = new Column<File,String>(new TextCell()) {
296                         @Override
297                         public String getValue(File object) {
298                                 return formatter.format(object.getLastModified());
299                         }
300                 };
301         aheader = new SortableHeader("Last Modified");
302                 celltable.addColumn(aColumn, aheader);
303                 allHeaders.add(aheader);
304                 aheader.setUpdater(new FileValueUpdater(aheader, "date"));
305                
306                 provider.addDataDisplay(celltable);
307
308                 VerticalPanel vp = new VerticalPanel();
309                 vp.setWidth("100%");
310
311         vp.add(celltable);
312
313                 vp.setCellWidth(celltable, "100%");
314         vp.addHandler(new ContextMenuHandler() {
315             @Override
316             public void onContextMenu(ContextMenuEvent event) {
317                 Folder selectedFolder = treeView.getSelection();
318                 if (!selectedFolder.isTrash()) {
319                     FileContextMenu contextMenu = new FileContextMenu(app, images, selectedFolder, getSelectedFiles(), false);
320                     int x = event.getNativeEvent().getClientX();
321                     int y = event.getNativeEvent().getClientY();
322                     contextMenu.setPopupPosition(x, y);
323                     contextMenu.show();
324                 }
325             }
326         }, ContextMenuEvent.getType());
327                 initWidget(vp);
328
329                 selectionModel = new MultiSelectionModel<File>(keyProvider);
330
331                 celltable.setSelectionModel(selectionModel, GSSSelectionEventManager.<File> createDefaultManager());
332 //              celltable.setPageSize(Pithos.VISIBLE_FILE_COUNT);
333                 
334                 sinkEvents(Event.ONCONTEXTMENU);
335 //              sinkEvents(Event.ONMOUSEUP);
336 //              sinkEvents(Event.ONMOUSEDOWN);
337 //              sinkEvents(Event.ONCLICK);
338 //              sinkEvents(Event.ONKEYDOWN);
339 //              sinkEvents(Event.ONDBLCLICK);
340                 Pithos.preventIESelection();
341         }
342
343         public List<File> getSelectedFiles() {
344         return new ArrayList<File>(selectionModel.getSelectedSet());
345         }
346         
347 //      @Override
348 //      public void onBrowserEvent(Event event) {
349 //
350 //              if (files == null || files.size() == 0) {
351 //                      if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
352 //                              contextMenu = new FileContextMenu(images, false, true);
353 //                contextMenu.show();
354 //                              event.preventDefault();
355 //                              event.cancelBubble(true);
356 //                      }
357 //                      return;
358 //              }
359 //              if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
360 //                      GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
361 //                      contextMenu =  new FileContextMenu(images, false, false);
362 //                      contextMenu = contextMenu.onEvent(event);
363 //                      event.cancelBubble(true);
364 //                      event.preventDefault();
365 //              } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
366 //                      contextMenu = new FileContextMenu(images, false, true);
367 //                      contextMenu = contextMenu.onEmptyEvent(event);
368 //                      event.cancelBubble(true);
369 //                      event.preventDefault();
370 //              } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
371 //                      if (getSelectedFiles().size() == 1) {
372 //                              Pithos app = app;
373 //                              File file = getSelectedFiles().get(0);
374 //                              Window.open(file.getUri(), "_blank", "");
375 //                              event.preventDefault();
376 //                              return;
377 //                      }
378 //              super.onBrowserEvent(event);
379 //      }
380
381         /**
382          * Update the display of the file list.
383          */
384         void update(@SuppressWarnings("unused") boolean sort) {
385                 showCellTable();
386         }
387
388         /**
389          * Return the proper icon based on the MIME type of the file.
390          *
391          * @param file
392          * @return the icon
393          */
394         protected ImageResource getFileIcon(File file) {
395                 String mimetype = file.getContentType();
396                 boolean shared = file.isShared();
397                 if (mimetype == null)
398                         return shared ? images.documentShared() : images.document();
399                 mimetype = mimetype.toLowerCase();
400                 if (mimetype.startsWith("application/pdf"))
401                         return shared ? images.pdfShared() : images.pdf();
402                 else if (mimetype.endsWith("excel"))
403                         return shared ? images.spreadsheetShared() : images.spreadsheet();
404                 else if (mimetype.endsWith("msword"))
405                         return shared ? images.wordprocessorShared() : images.wordprocessor();
406                 else if (mimetype.endsWith("powerpoint"))
407                         return shared ? images.presentationShared() : images.presentation();
408                 else if (mimetype.startsWith("application/zip") ||
409                                         mimetype.startsWith("application/gzip") ||
410                                         mimetype.startsWith("application/x-gzip") ||
411                                         mimetype.startsWith("application/x-tar") ||
412                                         mimetype.startsWith("application/x-gtar"))
413                         return shared ? images.zipShared() : images.zip();
414                 else if (mimetype.startsWith("text/html"))
415                         return shared ? images.htmlShared() : images.html();
416                 else if (mimetype.startsWith("text/plain"))
417                         return shared ? images.txtShared() : images.txt();
418                 else if (mimetype.startsWith("image/"))
419                         return shared ? images.imageShared() : images.image();
420                 else if (mimetype.startsWith("video/"))
421                         return shared ? images.videoShared() : images.video();
422                 else if (mimetype.startsWith("audio/"))
423                         return shared ? images.audioShared() : images.audio();
424                 return shared ? images.documentShared() : images.document();
425         }
426
427         /**
428          * Fill the file cache with data.
429          */
430         public void setFiles(final List<File> _files) {
431                 files = new ArrayList<File>();
432         for (File fres : _files)
433                         files.add(fres);
434                 Collections.sort(files, new Comparator<File>() {
435
436                         @Override
437                         public int compare(File arg0, File arg1) {
438                                 return arg0.getName().compareTo(arg1.getName());
439                         }
440
441                 });
442                 folderFileCount = files.size();
443                 
444                 nameHeader.setSorted(true);
445                 nameHeader.toggleReverseSort();
446                 for (SortableHeader otherHeader : allHeaders) {
447                 if (otherHeader != nameHeader) {
448                     otherHeader.setSorted(false);
449                     otherHeader.setReverseSort(true);
450                 }
451             }
452
453         provider.setList(files);
454         selectionModel.clear();
455         }
456
457         /**
458          * Does the list contains the requested filename
459          *
460          * @param fileName
461          * @return true/false
462          */
463         public boolean contains(String fileName) {
464                 for (int i = 0; i < files.size(); i++)
465                         if (files.get(i).getName().equals(fileName))
466                                 return true;
467                 return false;
468         }
469
470         public void clearSelectedRows() {
471                 Iterator<File> it = selectionModel.getSelectedSet().iterator();
472                 while(it.hasNext()){
473                         selectionModel.setSelected(it.next(),false);
474                 }
475         }
476         
477         /**
478          *
479          */
480         public void selectAllRows() {
481                 Iterator<File> it = provider.getList().iterator();
482                 while(it.hasNext()){
483                         selectionModel.setSelected(it.next(),true);
484                 }
485         }
486
487         protected void sortFiles(final String sortingProperty, final boolean sortingType){
488                 Collections.sort(files, new Comparator<File>() {
489
490             @Override
491             public int compare(File arg0, File arg1) {
492                     if (sortingType){
493                             if (sortingProperty.equals("version")) {
494                                     return arg0.getVersion() - arg1.getVersion();
495                             } else if (sortingProperty.equals("owner")) {
496                                     return arg0.getOwner().compareTo(arg1.getOwner());
497                             } else if (sortingProperty.equals("date")) {
498                                     return arg0.getLastModified().compareTo(arg1.getLastModified());
499                             } else if (sortingProperty.equals("size")) {
500                                     return (int) (arg0.getBytes() - arg1.getBytes());
501                             } else if (sortingProperty.equals("name")) {
502                                     return arg0.getName().compareTo(arg1.getName());
503                             } else if (sortingProperty.equals("path")) {
504                                     return arg0.getUri().compareTo(arg1.getUri());
505                             } else {
506                                     return arg0.getName().compareTo(arg1.getName());
507                             }
508                     }
509                     else if (sortingProperty.equals("version")) {
510                             
511                             return arg1.getVersion() - arg0.getVersion();
512                     } else if (sortingProperty.equals("owner")) {
513                             
514                             return arg1.getOwner().compareTo(arg0.getOwner());
515                     } else if (sortingProperty.equals("date")) {
516                             
517                             return arg1.getLastModified().compareTo(arg0.getLastModified());
518                     } else if (sortingProperty.equals("size")) {
519                             return (int) (arg1.getBytes() - arg0.getBytes());
520                     } else if (sortingProperty.equals("name")) {
521                             
522                             return arg1.getName().compareTo(arg0.getName());
523                     } else if (sortingProperty.equals("path")) {
524                             
525                             return arg1.getUri().compareTo(arg0.getUri());
526                     } else {
527                             
528                             return arg1.getName().compareTo(arg0.getName());
529                     }
530             }
531
532                 });
533         }
534         
535         final class FileValueUpdater implements ValueUpdater<String>{
536                 private String property;
537                 private SortableHeader header;
538                 /**
539                  * 
540                  */
541                 public FileValueUpdater(SortableHeader header,String property) {
542                         this.property=property;
543                         this.header=header;
544                 }
545                 @Override
546                 public void update(@SuppressWarnings("unused") String value) {
547                         header.setSorted(true);
548                         header.toggleReverseSort();
549
550                 for (SortableHeader otherHeader : allHeaders) {
551                   if (otherHeader != header) {
552                     otherHeader.setSorted(false);
553                     otherHeader.setReverseSort(true);
554                   }
555                 }
556                 celltable.redrawHeaders();
557                 sortFiles(property, header.getReverseSort());
558                 FileList.this.update(true);                     
559                 }
560                 
561         }
562
563         /**
564          * Shows the files in the cellTable 
565      */
566         private void showCellTable(){
567                 provider.setList(files);
568                 
569                 provider.refresh();
570                 
571                 //celltable.redraw();
572                 celltable.redrawHeaders();              
573         }
574 }