Finished restore-from-trash functionality
[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                 FileContextMenu contextMenu = new FileContextMenu(app, images, selectedFolder, getSelectedFiles(), false);
319                 int x = event.getNativeEvent().getClientX();
320                 int y = event.getNativeEvent().getClientY();
321                 contextMenu.setPopupPosition(x, y);
322                 contextMenu.show();
323             }
324         }, ContextMenuEvent.getType());
325                 initWidget(vp);
326
327                 selectionModel = new MultiSelectionModel<File>(keyProvider);
328
329                 celltable.setSelectionModel(selectionModel, GSSSelectionEventManager.<File> createDefaultManager());
330 //              celltable.setPageSize(Pithos.VISIBLE_FILE_COUNT);
331                 
332                 sinkEvents(Event.ONCONTEXTMENU);
333 //              sinkEvents(Event.ONMOUSEUP);
334 //              sinkEvents(Event.ONMOUSEDOWN);
335 //              sinkEvents(Event.ONCLICK);
336 //              sinkEvents(Event.ONKEYDOWN);
337 //              sinkEvents(Event.ONDBLCLICK);
338                 Pithos.preventIESelection();
339         }
340
341         public List<File> getSelectedFiles() {
342         return new ArrayList<File>(selectionModel.getSelectedSet());
343         }
344         
345 //      @Override
346 //      public void onBrowserEvent(Event event) {
347 //
348 //              if (files == null || files.size() == 0) {
349 //                      if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
350 //                              contextMenu = new FileContextMenu(images, false, true);
351 //                contextMenu.show();
352 //                              event.preventDefault();
353 //                              event.cancelBubble(true);
354 //                      }
355 //                      return;
356 //              }
357 //              if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
358 //                      GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
359 //                      contextMenu =  new FileContextMenu(images, false, false);
360 //                      contextMenu = contextMenu.onEvent(event);
361 //                      event.cancelBubble(true);
362 //                      event.preventDefault();
363 //              } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
364 //                      contextMenu = new FileContextMenu(images, false, true);
365 //                      contextMenu = contextMenu.onEmptyEvent(event);
366 //                      event.cancelBubble(true);
367 //                      event.preventDefault();
368 //              } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
369 //                      if (getSelectedFiles().size() == 1) {
370 //                              Pithos app = app;
371 //                              File file = getSelectedFiles().get(0);
372 //                              Window.open(file.getUri(), "_blank", "");
373 //                              event.preventDefault();
374 //                              return;
375 //                      }
376 //              super.onBrowserEvent(event);
377 //      }
378
379         /**
380          * Update the display of the file list.
381          */
382         void update(@SuppressWarnings("unused") boolean sort) {
383                 showCellTable();
384         }
385
386         /**
387          * Return the proper icon based on the MIME type of the file.
388          *
389          * @param file
390          * @return the icon
391          */
392         protected ImageResource getFileIcon(File file) {
393                 String mimetype = file.getContentType();
394                 boolean shared = file.isShared();
395                 if (mimetype == null)
396                         return shared ? images.documentShared() : images.document();
397                 mimetype = mimetype.toLowerCase();
398                 if (mimetype.startsWith("application/pdf"))
399                         return shared ? images.pdfShared() : images.pdf();
400                 else if (mimetype.endsWith("excel"))
401                         return shared ? images.spreadsheetShared() : images.spreadsheet();
402                 else if (mimetype.endsWith("msword"))
403                         return shared ? images.wordprocessorShared() : images.wordprocessor();
404                 else if (mimetype.endsWith("powerpoint"))
405                         return shared ? images.presentationShared() : images.presentation();
406                 else if (mimetype.startsWith("application/zip") ||
407                                         mimetype.startsWith("application/gzip") ||
408                                         mimetype.startsWith("application/x-gzip") ||
409                                         mimetype.startsWith("application/x-tar") ||
410                                         mimetype.startsWith("application/x-gtar"))
411                         return shared ? images.zipShared() : images.zip();
412                 else if (mimetype.startsWith("text/html"))
413                         return shared ? images.htmlShared() : images.html();
414                 else if (mimetype.startsWith("text/plain"))
415                         return shared ? images.txtShared() : images.txt();
416                 else if (mimetype.startsWith("image/"))
417                         return shared ? images.imageShared() : images.image();
418                 else if (mimetype.startsWith("video/"))
419                         return shared ? images.videoShared() : images.video();
420                 else if (mimetype.startsWith("audio/"))
421                         return shared ? images.audioShared() : images.audio();
422                 return shared ? images.documentShared() : images.document();
423         }
424
425         /**
426          * Fill the file cache with data.
427          */
428         public void setFiles(final List<File> _files) {
429                 files = new ArrayList<File>();
430         for (File fres : _files)
431                         files.add(fres);
432                 Collections.sort(files, new Comparator<File>() {
433
434                         @Override
435                         public int compare(File arg0, File arg1) {
436                                 return arg0.getName().compareTo(arg1.getName());
437                         }
438
439                 });
440                 folderFileCount = files.size();
441                 
442                 nameHeader.setSorted(true);
443                 nameHeader.toggleReverseSort();
444                 for (SortableHeader otherHeader : allHeaders) {
445                 if (otherHeader != nameHeader) {
446                     otherHeader.setSorted(false);
447                     otherHeader.setReverseSort(true);
448                 }
449             }
450
451         provider.setList(files);
452         selectionModel.clear();
453         }
454
455         /**
456          * Does the list contains the requested filename
457          *
458          * @param fileName
459          * @return true/false
460          */
461         public boolean contains(String fileName) {
462                 for (int i = 0; i < files.size(); i++)
463                         if (files.get(i).getName().equals(fileName))
464                                 return true;
465                 return false;
466         }
467
468         public void clearSelectedRows() {
469                 Iterator<File> it = selectionModel.getSelectedSet().iterator();
470                 while(it.hasNext()){
471                         selectionModel.setSelected(it.next(),false);
472                 }
473         }
474         
475         /**
476          *
477          */
478         public void selectAllRows() {
479                 Iterator<File> it = provider.getList().iterator();
480                 while(it.hasNext()){
481                         selectionModel.setSelected(it.next(),true);
482                 }
483         }
484
485         protected void sortFiles(final String sortingProperty, final boolean sortingType){
486                 Collections.sort(files, new Comparator<File>() {
487
488             @Override
489             public int compare(File arg0, File arg1) {
490                     if (sortingType){
491                             if (sortingProperty.equals("version")) {
492                                     return arg0.getVersion() - arg1.getVersion();
493                             } else if (sortingProperty.equals("owner")) {
494                                     return arg0.getOwner().compareTo(arg1.getOwner());
495                             } else if (sortingProperty.equals("date")) {
496                                     return arg0.getLastModified().compareTo(arg1.getLastModified());
497                             } else if (sortingProperty.equals("size")) {
498                                     return (int) (arg0.getBytes() - arg1.getBytes());
499                             } else if (sortingProperty.equals("name")) {
500                                     return arg0.getName().compareTo(arg1.getName());
501                             } else if (sortingProperty.equals("path")) {
502                                     return arg0.getUri().compareTo(arg1.getUri());
503                             } else {
504                                     return arg0.getName().compareTo(arg1.getName());
505                             }
506                     }
507                     else if (sortingProperty.equals("version")) {
508                             
509                             return arg1.getVersion() - arg0.getVersion();
510                     } else if (sortingProperty.equals("owner")) {
511                             
512                             return arg1.getOwner().compareTo(arg0.getOwner());
513                     } else if (sortingProperty.equals("date")) {
514                             
515                             return arg1.getLastModified().compareTo(arg0.getLastModified());
516                     } else if (sortingProperty.equals("size")) {
517                             return (int) (arg1.getBytes() - arg0.getBytes());
518                     } else if (sortingProperty.equals("name")) {
519                             
520                             return arg1.getName().compareTo(arg0.getName());
521                     } else if (sortingProperty.equals("path")) {
522                             
523                             return arg1.getUri().compareTo(arg0.getUri());
524                     } else {
525                             
526                             return arg1.getName().compareTo(arg0.getName());
527                     }
528             }
529
530                 });
531         }
532         
533         final class FileValueUpdater implements ValueUpdater<String>{
534                 private String property;
535                 private SortableHeader header;
536                 /**
537                  * 
538                  */
539                 public FileValueUpdater(SortableHeader header,String property) {
540                         this.property=property;
541                         this.header=header;
542                 }
543                 @Override
544                 public void update(@SuppressWarnings("unused") String value) {
545                         header.setSorted(true);
546                         header.toggleReverseSort();
547
548                 for (SortableHeader otherHeader : allHeaders) {
549                   if (otherHeader != header) {
550                     otherHeader.setSorted(false);
551                     otherHeader.setReverseSort(true);
552                   }
553                 }
554                 celltable.redrawHeaders();
555                 sortFiles(property, header.getReverseSort());
556                 FileList.this.update(true);                     
557                 }
558                 
559         }
560
561         /**
562          * Shows the files in the cellTable 
563      */
564         private void showCellTable(){
565                 provider.setList(files);
566                 
567                 provider.refresh();
568                 
569                 //celltable.redraw();
570                 celltable.redrawHeaders();              
571         }
572 }