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