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