Finally displayed virtual folder hierarchy up to second level
[pithos-web-client] / src / gr / grnet / pithos / web / client / FileList.java
1 /*
2  * Copyright (c) 2011 Greek Research and Technology Network
3  */
4
5 package gr.grnet.pithos.web.client;
6
7 import static com.google.gwt.query.client.GQuery.$;
8
9 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
10 import gr.grnet.pithos.web.client.rest.GetCommand;
11 import gr.grnet.pithos.web.client.rest.RestCommand;
12 import gr.grnet.pithos.web.client.rest.resource.FileResource;
13 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
14 import gr.grnet.pithos.web.client.rest.resource.OthersFolderResource;
15 import gr.grnet.pithos.web.client.rest.resource.OthersResource;
16 import gr.grnet.pithos.web.client.rest.resource.RestResource;
17 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
18 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
19 import gr.grnet.pithos.web.client.rest.resource.TrashFolderResource;
20 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
21 import gr.grnet.pithos.web.client.rest.resource.UserResource;
22 import gr.grnet.pithos.web.client.rest.resource.UserSearchResource;
23 import gwtquery.plugins.draggable.client.DraggableOptions;
24 import gwtquery.plugins.draggable.client.StopDragException;
25 import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction;
26 import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption;
27 import gwtquery.plugins.draggable.client.events.DragContext;
28 import gwtquery.plugins.draggable.client.events.DragStartEvent;
29 import gwtquery.plugins.draggable.client.events.DragStopEvent;
30 import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler;
31 import gwtquery.plugins.draggable.client.events.DragStopEvent.DragStopEventHandler;
32 import gwtquery.plugins.droppable.client.gwt.DragAndDropCellTable;
33 import gwtquery.plugins.droppable.client.gwt.DragAndDropColumn;
34
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Iterator;
39 import java.util.List;
40
41 import com.google.gwt.cell.client.AbstractCell;
42 import com.google.gwt.cell.client.ImageResourceCell;
43 import com.google.gwt.cell.client.SafeHtmlCell;
44 import com.google.gwt.cell.client.TextCell;
45 import com.google.gwt.cell.client.ValueUpdater;
46 import com.google.gwt.core.client.GWT;
47 import com.google.gwt.core.client.Scheduler;
48 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
49 import com.google.gwt.dom.client.Style.Cursor;
50 import com.google.gwt.event.dom.client.ClickEvent;
51 import com.google.gwt.event.dom.client.ClickHandler;
52 import com.google.gwt.http.client.URL;
53 import com.google.gwt.i18n.client.DateTimeFormat;
54 import com.google.gwt.resources.client.ClientBundle;
55 import com.google.gwt.resources.client.ImageResource;
56 import com.google.gwt.safehtml.client.SafeHtmlTemplates;
57 import com.google.gwt.safehtml.shared.SafeHtml;
58 import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
59 import com.google.gwt.user.cellview.client.CellTable;
60 import com.google.gwt.user.cellview.client.GssSimplePager;
61 import com.google.gwt.user.client.DOM;
62 import com.google.gwt.user.client.DeferredCommand;
63 import com.google.gwt.user.client.Event;
64 import com.google.gwt.user.client.Window;
65 import com.google.gwt.user.client.ui.AbstractImagePrototype;
66 import com.google.gwt.user.client.ui.Button;
67 import com.google.gwt.user.client.ui.Composite;
68 import com.google.gwt.user.client.ui.HorizontalPanel;
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 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
75
76 /**
77  * A composite that displays the list of files in a particular folder.
78  */
79 public class FileList extends Composite {
80         ListDataProvider<FileResource> provider = new ListDataProvider<FileResource>();
81         interface TableResources extends DragAndDropCellTable.Resources {
82             @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
83             TableStyle cellTableStyle();
84           }
85         
86         static interface Templates extends SafeHtmlTemplates {
87             Templates INSTANCE = GWT.create(Templates.class);
88
89             @Template("<div id='dragHelper' style='border:1px solid black; background-color:#ffffff; color:black; width:150px;z-index:100'></div>")
90             SafeHtml outerHelper();
91
92         @Template("<span id='{0}'>{0}</span>")
93         public SafeHtml filenameSpan(String filename);
94
95         @Template("<a href='{0}' title='{1}' rel='lytebox[mnf]' onclick='myLytebox.start(this, false, false); return false;'>(view)</a>")
96         public SafeHtml viewLink(String link, String title);
97
98         @Template("<table><tr><td rowspan='3'>{0}</td><td style='font-size:95%;' id='{1}'>{1}</td></tr><tr><td>{2}</td></tr></table>")
99         public SafeHtml rendelContactCell(String imageHtml, String name, String fileSize);
100
101         @Template("<span id='{0}' class='{1}'>{2}</span>")
102         public SafeHtml spanWithIdAndClass(String id, String cssClass, String content);
103           }
104         
105         
106         /**
107            * The styles applied to the table.
108            */
109           interface TableStyle extends CellTable.Style {
110           }
111
112         private String showingStats = "";
113
114         private int startIndex = 0;
115
116         /**
117          * A constant that denotes the completion of an IncrementalCommand.
118          */
119         public static final boolean DONE = false;
120
121         
122         
123         private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
124
125         /**
126          * Specifies that the images available for this composite will be the ones
127          * available in FileContextMenu.
128          */
129         public interface Images extends ClientBundle,FileContextMenu.Images, CellTreeView.Images {
130
131                 @Source("gr/grnet/pithos/resources/blank.gif")
132                 ImageResource blank();
133
134                 @Source("gr/grnet/pithos/resources/asc.png")
135                 ImageResource asc();
136
137                 @Source("gr/grnet/pithos/resources/desc.png")
138                 ImageResource desc();
139
140                 @Source("gr/grnet/pithos/resources/mimetypes/document_shared.png")
141                 ImageResource documentShared();
142
143                 @Source("gr/grnet/pithos/resources/mimetypes/kcmfontinst.png")
144                 ImageResource wordprocessor();
145
146                 @Source("gr/grnet/pithos/resources/mimetypes/log.png")
147                 ImageResource spreadsheet();
148
149                 @Source("gr/grnet/pithos/resources/mimetypes/kpresenter_kpr.png")
150                 ImageResource presentation();
151
152                 @Source("gr/grnet/pithos/resources/mimetypes/acroread.png")
153                 ImageResource pdf();
154
155                 @Source("gr/grnet/pithos/resources/mimetypes/image.png")
156                 ImageResource image();
157
158                 @Source("gr/grnet/pithos/resources/mimetypes/video2.png")
159                 ImageResource video();
160
161                 @Source("gr/grnet/pithos/resources/mimetypes/knotify.png")
162                 ImageResource audio();
163
164                 @Source("gr/grnet/pithos/resources/mimetypes/html.png")
165                 ImageResource html();
166
167                 @Source("gr/grnet/pithos/resources/mimetypes/txt.png")
168                 ImageResource txt();
169
170                 @Source("gr/grnet/pithos/resources/mimetypes/ark2.png")
171                 ImageResource zip();
172
173                 @Source("gr/grnet/pithos/resources/mimetypes/kcmfontinst_shared.png")
174                 ImageResource wordprocessorShared();
175
176                 @Source("gr/grnet/pithos/resources/mimetypes/log_shared.png")
177                 ImageResource spreadsheetShared();
178
179                 @Source("gr/grnet/pithos/resources/mimetypes/kpresenter_kpr_shared.png")
180                 ImageResource presentationShared();
181
182                 @Source("gr/grnet/pithos/resources/mimetypes/acroread_shared.png")
183                 ImageResource pdfShared();
184
185                 @Source("gr/grnet/pithos/resources/mimetypes/image_shared.png")
186                 ImageResource imageShared();
187
188                 @Source("gr/grnet/pithos/resources/mimetypes/video2_shared.png")
189                 ImageResource videoShared();
190
191                 @Source("gr/grnet/pithos/resources/mimetypes/knotify_shared.png")
192                 ImageResource audioShared();
193
194                 @Source("gr/grnet/pithos/resources/mimetypes/html_shared.png")
195                 ImageResource htmlShared();
196
197                 @Source("gr/grnet/pithos/resources/mimetypes/txt_shared.png")
198                 ImageResource txtShared();
199
200                 @Source("gr/grnet/pithos/resources/mimetypes/ark2_shared.png")
201                 ImageResource zipShared();
202
203         }
204         
205         DragStopEventHandler dragStop = new DragStopEventHandler() {
206                 
207                 @Override
208                 public void onDragStop(DragStopEvent event) {
209                         GWT.log("DRAG STOPPED");
210                         
211                 }
212         };
213         
214         private static class ContactCell extends AbstractCell<gr.grnet.pithos.web.client.rest.resource.FileResource> {
215
216             /**
217              * The html of the image used for contacts.
218              * 
219              */
220             private final String imageHtml;
221
222             public ContactCell(ImageResource image) {
223               this.imageHtml = AbstractImagePrototype.create(image).getHTML();
224             }
225
226             
227
228                 
229
230             @Override
231             public void render(Context context, FileResource value, SafeHtmlBuilder sb) {
232               // Value can be null, so do a null check..
233               if (value == null) {
234                 return;
235               }
236
237           sb.append(Templates.INSTANCE.rendelContactCell(imageHtml, value.getName(), value.getFileSizeAsString()));
238             }
239
240
241           }
242         /**
243          * Retrieve the celltable.
244          *
245          * @return the celltable
246          */
247         public DragAndDropCellTable<FileResource> getCelltable() {
248                 return celltable;
249         }
250         
251         
252         /**
253          * The number of files in this folder.
254          */
255         int folderFileCount;
256
257         /**
258          * Total folder size
259          */
260         long folderTotalSize;
261
262         /**
263          * A cache of the files in the list.
264          */
265         private List<FileResource> files;
266
267         /**
268          * The widget's image bundle.
269          */
270         private final Images images;
271         
272         private FileContextMenu menuShowing;
273         private DragAndDropCellTable<FileResource> celltable;
274         private final MultiSelectionModel<FileResource> selectionModel;
275         private final List<SortableHeader> allHeaders = new ArrayList<SortableHeader>();
276         SortableHeader nameHeader;
277         GssSimplePager pagerBottom;
278         GssSimplePager pagerTop;
279         Button uploadButtonBottom;
280         Button uploadButtonTop;
281         /**
282          * Construct the file list widget. This entails setting up the widget
283          * layout, fetching the number of files in the current folder from the
284          * server and filling the local file cache of displayed files with data from
285          * the server, as well.
286          *
287          * @param _images
288          */
289         public FileList(Images _images) {
290                 images = _images;
291                 DragAndDropCellTable.Resources resources = GWT.create(TableResources.class);
292                 ProvidesKey<FileResource> keyProvider = new ProvidesKey<FileResource>(){
293
294                         @Override
295                         public Object getKey(FileResource item) {
296                                 return item.getUri();
297                         }
298                         
299                 };
300                 celltable = new DragAndDropCellTable<FileResource>(GSS.VISIBLE_FILE_COUNT,resources,keyProvider);
301                 
302                 DragAndDropColumn<FileResource, ImageResource> status = new DragAndDropColumn<FileResource, ImageResource>(new ImageResourceCell(){
303                         @Override
304                   public boolean handlesSelection() {
305                             return false;
306                           }
307                 }) {
308                   @Override
309                   public ImageResource getValue(FileResource entity) {
310                     return getFileIcon(entity);
311                   }
312                   
313                };
314             celltable.addColumn(status,"");
315             
316             initDragOperation(status);
317                 final DragAndDropColumn<FileResource,SafeHtml> nameColumn = new DragAndDropColumn<FileResource,SafeHtml>(new SafeHtmlCell()) {
318
319                         @Override
320                         public SafeHtml getValue(FileResource object) {
321                                 SafeHtmlBuilder sb = new SafeHtmlBuilder();
322                 sb.append(Templates.INSTANCE.filenameSpan(object.getName()));
323                                 if (object.getContentType().endsWith("png") || object.getContentType().endsWith("gif") || object.getContentType().endsWith("jpeg") ){
324                                         sb.appendHtmlConstant("&nbsp;").append(Templates.INSTANCE.viewLink(GSS.get().getTopPanel().getFileMenu().getDownloadURL(object), object.getOwner() + " : " + object.getPath() + object.getName()));
325                                 }
326                                 
327                                 return sb.toSafeHtml();
328                         }
329                         
330                 };
331                 initDragOperation(nameColumn);
332                 celltable.addColumn(nameColumn,nameHeader = new SortableHeader("Name"));
333                 allHeaders.add(nameHeader);
334                 //nameHeader.setSorted(true);
335                 //nameHeader.toggleReverseSort();
336                 nameHeader.setUpdater(new FileValueUpdater(nameHeader, "name"));
337                 celltable.redrawHeaders();
338                 
339                 
340             
341             
342             SortableHeader aheader;
343             DragAndDropColumn<FileResource,String> aColumn;
344                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
345                         @Override
346                         public String getValue(FileResource object) {
347                                 return GSS.get().findUserFullName(object.getOwner());
348                         }                       
349                 },aheader = new SortableHeader("Owner"));
350                 initDragOperation(aColumn);
351                 allHeaders.add(aheader);
352                 aheader.setUpdater(new FileValueUpdater(aheader, "owner"));
353                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
354                         @Override
355                         public String getValue(FileResource object) {
356                                 // TODO Auto-generated method stub
357                                 return object.getPath();
358                         }                       
359                 },aheader = new SortableHeader("Path"));
360                 initDragOperation(aColumn);
361                 allHeaders.add(aheader);
362                 
363                 aheader.setUpdater(new FileValueUpdater(aheader, "path"));      
364                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
365                         @Override
366                         public String getValue(FileResource object) {
367                                 if(object.isVersioned())
368                                         return object.getVersion().toString();
369                                 return "-";
370                         }                       
371                 },aheader = new SortableHeader("Version"));
372                 initDragOperation(aColumn);
373                 allHeaders.add(aheader);
374                 aheader.setUpdater(new FileValueUpdater(aheader, "version"));
375                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
376                         @Override
377                         public String getValue(FileResource object) {
378                                 // TODO Auto-generated method stub
379                                 return object.getFileSizeAsString();
380                         }                       
381                 },aheader = new SortableHeader("Size"));
382                 initDragOperation(aColumn);
383                 allHeaders.add(aheader);
384                 aheader.setUpdater(new FileValueUpdater(aheader, "size"));      
385                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
386                         @Override
387                         public String getValue(FileResource object) {
388                                 return formatter.format(object.getModificationDate());
389                         }                       
390                 },aheader = new SortableHeader("Last Modified"));
391                 allHeaders.add(aheader);
392                 aheader.setUpdater(new FileValueUpdater(aheader, "date"));
393                
394                 
395                 provider.addDataDisplay(celltable);
396                 celltable.addDragStopHandler(dragStop);
397                 celltable.addDragStartHandler(new DragStartEventHandler() {
398
399                       public void onDragStart(DragStartEvent event) {
400                         FileResource value = event.getDraggableData();
401                         
402                         com.google.gwt.dom.client.Element helper = event.getHelper();
403                         SafeHtmlBuilder sb = new SafeHtmlBuilder();
404                         sb.appendHtmlConstant("<b>");
405                         DisplayHelper.log(value.getName());
406                         if(getSelectedFiles().size()==1)
407                                 sb.appendEscaped(value.getName());
408                         else
409                                 sb.appendEscaped(getSelectedFiles().size()+" files");
410                         sb.appendHtmlConstant("</b>");
411                         helper.setInnerHTML(sb.toSafeHtml().asString());
412
413                       }
414                     });
415                 
416                 
417                 
418                 
419                 
420                 
421                 VerticalPanel vp = new VerticalPanel();
422                 vp.setWidth("100%");
423                 pagerTop = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
424                 pagerTop.setDisplay(celltable); 
425                 uploadButtonTop=new Button("<span id='topMenu.file.upload'>" + AbstractImagePrototype.create(images.fileUpdate()).getHTML() + "&nbsp;Upload</span>");
426                 uploadButtonTop.addClickHandler(new ClickHandler() {
427                         
428                         @Override
429                         public void onClick(ClickEvent event) {
430                                 new UploadFileCommand(null).execute();
431                         }
432                 });
433                 HorizontalPanel topPanel = new HorizontalPanel();
434                 topPanel.add(pagerTop);
435                 topPanel.add(uploadButtonTop);
436                 vp.add(topPanel);
437                 celltable.setWidth("100%");
438                 vp.add(celltable);
439                 pagerBottom = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
440                 pagerBottom.setDisplay(celltable);
441                 HorizontalPanel bottomPanel = new HorizontalPanel();
442                 bottomPanel.add(pagerBottom);
443                 uploadButtonBottom=new Button("<span id='topMenu.file.upload'>" + AbstractImagePrototype.create(images.fileUpdate()).getHTML() + "&nbsp;Upload</span>");
444                 uploadButtonBottom.addClickHandler(new ClickHandler() {
445                         
446                         @Override
447                         public void onClick(ClickEvent event) {
448                                 new UploadFileCommand(null).execute();
449                         }
450                 });
451                 bottomPanel.add(uploadButtonBottom);
452                 vp.add(bottomPanel);
453                 vp.setCellWidth(celltable, "100%");
454                 
455                 initWidget(vp);
456                 pagerBottom.setVisible(false);
457                 pagerTop.setVisible(false);
458
459                 celltable.setStyleName("pithos-List");
460                 selectionModel = new MultiSelectionModel<FileResource>(keyProvider);
461                 
462
463                  Handler selectionHandler = new SelectionChangeEvent.Handler() { 
464              @Override 
465              public void onSelectionChange(com.google.gwt.view.client.SelectionChangeEvent event) {
466                  if(getSelectedFiles().size()==1)
467                          GSS.get().setCurrentSelection(getSelectedFiles().get(0));
468                  else
469                          GSS.get().setCurrentSelection(getSelectedFiles());
470              }
471          };
472          selectionModel.addSelectionChangeHandler(selectionHandler);
473          
474                 celltable.setSelectionModel(selectionModel,GSSSelectionEventManager.<FileResource>createDefaultManager());
475                 celltable.setPageSize(GSS.VISIBLE_FILE_COUNT);
476                 
477 //              Scheduler.get().scheduleIncremental(new RepeatingCommand() {
478 //
479 //                      @Override
480 //                      public boolean execute() {
481 //                              return fetchRootFolder();
482 //                      }
483 //              });
484                 sinkEvents(Event.ONCONTEXTMENU);
485                 sinkEvents(Event.ONMOUSEUP);
486                 sinkEvents(Event.ONMOUSEDOWN);
487                 sinkEvents(Event.ONCLICK);
488                 sinkEvents(Event.ONKEYDOWN);
489                 sinkEvents(Event.ONDBLCLICK);
490                 GSS.preventIESelection();
491         }
492         
493
494         
495          public List<FileResource> getSelectedFiles() {
496          return new ArrayList<FileResource>(selectionModel.getSelectedSet());
497          }
498         
499          private void initDragOperation(DragAndDropColumn<?, ?> column) {
500
501                     // retrieve draggableOptions on the column
502                     DraggableOptions draggableOptions = column.getDraggableOptions();
503                     // use template to construct the helper. The content of the div will be set
504                     // after
505                     draggableOptions.setHelper($(Templates.INSTANCE.outerHelper().asString()));
506                     //draggableOptions.setZIndex(100);
507                     // opacity of the helper
508                     draggableOptions.setAppendTo("body"); 
509                     //draggableOptions.setOpacity((float) 0.8);
510                     draggableOptions.setContainment("document");
511                     // cursor to use during the drag operation
512                     draggableOptions.setCursor(Cursor.MOVE);
513                     // set the revert option
514                     draggableOptions.setRevert(RevertOption.ON_INVALID_DROP);
515                     // prevents dragging when user click on the category drop-down list
516                     draggableOptions.setCancel("select");
517                     
518                     
519                     draggableOptions.setOnBeforeDragStart(new DragFunction() {
520                                 
521                                 @Override
522                                 public void f(DragContext context) {
523                                          FileResource value = context.getDraggableData();
524                                      if(!selectionModel.isSelected(value)){
525                                         throw new StopDragException();
526                                       }
527                                         
528                                 }
529                         });
530                   }
531         
532          public void showContextMenu(Event event){
533                  menuShowing = new FileContextMenu(images, false, true);
534                         menuShowing=menuShowing.onEmptyEvent(event);
535          }
536         @Override
537         public void onBrowserEvent(Event event) {
538                 
539                 if (files == null || files.size() == 0) {
540                         if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
541                                 menuShowing = new FileContextMenu(images, false, true);
542                                 menuShowing=menuShowing.onEmptyEvent(event);
543                                 event.preventDefault();
544                                 event.cancelBubble(true);
545                         }
546                         return;
547                 }
548                 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
549                         GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
550                         menuShowing =  new FileContextMenu(images, false, false);
551                         menuShowing=menuShowing.onEvent(event);
552                         event.cancelBubble(true);
553                         event.preventDefault();
554                 } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
555                         menuShowing = new FileContextMenu(images, false, true);
556                         menuShowing=menuShowing.onEmptyEvent(event);
557                         event.cancelBubble(true);
558                         event.preventDefault();
559                 } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
560                         if (getSelectedFiles().size() == 1) {
561                                 GSS app = GSS.get();
562                                 FileResource file = getSelectedFiles().get(0);
563                                 String dateString = RestCommand.getDate();
564                                 String resource = file.getUri().substring(app.getApiPath().length() - 1, file.getUri().length());
565                                 String sig = app.getCurrentUserResource().getUsername() + " " +
566                                                 RestCommand.calculateSig("GET", dateString, resource,
567                                                 RestCommand.base64decode(app.getToken()));
568                                 Window.open(file.getUri() + "?Authorization=" + URL.encodeComponent(sig) + "&Date=" + URL.encodeComponent(dateString), "_blank", "");
569                                 event.preventDefault();
570                                 return;
571                         }
572                 super.onBrowserEvent(event);
573         }
574
575         /**
576          * Retrieve the root folder for the current user.
577          *
578          * @return true if the retrieval was successful
579          */
580         protected boolean fetchRootFolder() {
581                 UserResource user = GSS.get().getCurrentUserResource();
582                 if (user == null)
583                         return !DONE;
584                 // Update cache and clear selection.
585                 updateFileCache(true);
586                 return DONE;
587         }
588
589
590         /**
591          * Update the display of the file list.
592          */
593         void update(boolean sort) {
594                 int count = folderFileCount;
595                 int max = startIndex + GSS.VISIBLE_FILE_COUNT;
596                 if (max > count)
597                         max = count;
598                 folderTotalSize = 0;
599                 
600                 copyListAndContinue(files);
601                 for(FileResource f : files){
602                         folderTotalSize += f.getContentLength();
603                 }
604                 if (folderFileCount == 0) {
605                         showingStats = "no files";
606                 } else if (folderFileCount < GSS.VISIBLE_FILE_COUNT) {
607                         if (folderFileCount == 1)
608                                 showingStats = "1 file";
609                         else
610                                 showingStats = folderFileCount + " files";
611                         showingStats += " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
612                 } else {
613                         showingStats = "" + (startIndex + 1) + " - " + max + " of " + count + " files" + " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
614                 }
615                 showCellTable();
616                 updateCurrentlyShowingStats();
617
618         }
619
620         /**
621          * Return the proper icon based on the MIME type of the file.
622          *
623          * @param file
624          * @return the icon
625          */
626         private ImageResource getFileIcon(FileResource file) {
627                 String mimetype = file.getContentType();
628                 boolean shared = false;
629                 if(GSS.get().getTreeView().getSelection()!=null && (GSS.get().getTreeView().getSelection() instanceof OtherUserResource || GSS.get().getTreeView().getSelection() instanceof OthersFolderResource)){
630                         OtherUserResource otherUser = null;
631                         if(GSS.get().getTreeView().getSelection() instanceof OtherUserResource)
632                                 otherUser = (OtherUserResource) GSS.get().getTreeView().getSelection();
633                         else if (GSS.get().getTreeView().getSelection() instanceof OthersFolderResource){
634                                 otherUser = GSS.get().getTreeView().getOtherUserResourceOfOtherFolder((OthersFolderResource) GSS.get().getTreeView().getSelection());
635                         }
636                         if(otherUser ==null)
637                                 shared=false;
638                         else{
639                                 String uname = otherUser.getUsername();
640                                 if(uname==null)
641                                         uname = GSS.get().getTreeView().getOthers().getUsernameOfUri(otherUser.getUri());
642                                 if(uname != null)
643                                         shared = file.isShared();
644                         }
645                 }
646                 else
647                         shared = file.isShared();
648                 if (mimetype == null)
649                         return shared ? images.documentShared() : images.document();
650                 mimetype = mimetype.toLowerCase();
651                 if (mimetype.startsWith("application/pdf"))
652                         return shared ? images.pdfShared() : images.pdf();
653                 else if (mimetype.endsWith("excel"))
654                         return shared ? images.spreadsheetShared() : images.spreadsheet();
655                 else if (mimetype.endsWith("msword"))
656                         return shared ? images.wordprocessorShared() : images.wordprocessor();
657                 else if (mimetype.endsWith("powerpoint"))
658                         return shared ? images.presentationShared() : images.presentation();
659                 else if (mimetype.startsWith("application/zip") ||
660                                         mimetype.startsWith("application/gzip") ||
661                                         mimetype.startsWith("application/x-gzip") ||
662                                         mimetype.startsWith("application/x-tar") ||
663                                         mimetype.startsWith("application/x-gtar"))
664                         return shared ? images.zipShared() : images.zip();
665                 else if (mimetype.startsWith("text/html"))
666                         return shared ? images.htmlShared() : images.html();
667                 else if (mimetype.startsWith("text/plain"))
668                         return shared ? images.txtShared() : images.txt();
669                 else if (mimetype.startsWith("image/"))
670                         return shared ? images.imageShared() : images.image();
671                 else if (mimetype.startsWith("video/"))
672                         return shared ? images.videoShared() : images.video();
673                 else if (mimetype.startsWith("audio/"))
674                         return shared ? images.audioShared() : images.audio();
675                 return shared ? images.documentShared() : images.document();
676         }
677
678         /**
679          * Update status panel with currently showing file stats.
680          */
681         public void updateCurrentlyShowingStats() {
682                 GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
683         }
684         
685         public void updateFileCache(boolean clearSelection){
686                 if(clearSelection){
687                         clearSelectedRows();
688                 }
689                 
690                 final RestResource folderItem = GSS.get().getTreeView().getSelection();
691                 // Validation.
692                 if (folderItem == null || folderItem.equals(GSS.get().getTreeView().getOthers())) {
693                         setFiles(new ArrayList<FileResource>());
694                         update(true);
695                         return;
696                 }
697                 else if (folderItem instanceof RestResourceWrapper) {
698                         setFiles(((RestResourceWrapper) folderItem).getResource().getFiles());
699                         update(true);
700                 }
701                 else if (folderItem instanceof SharedResource) {
702                         setFiles(((SharedResource) folderItem).getFiles());
703                         update(true);
704                 }
705                 else if (folderItem instanceof OtherUserResource) {
706                         setFiles(((OtherUserResource) folderItem).getFiles());
707                         update(true);
708                 }
709                 else if (folderItem instanceof TrashResource) {
710                         setFiles(((TrashResource) folderItem).getFiles());
711                         update(true);
712                 }
713         }
714         
715
716         /**
717          * Fill the file cache with data.
718          */
719         public void setFiles(final List<FileResource> _files) {
720                 if (_files.size() > 0 && ! (GSS.get().getTreeView().getSelection() instanceof TrashResource)) {
721                         files = new ArrayList<FileResource>();
722                         for (FileResource fres : _files)
723                                 if (!fres.isDeleted())
724                                         files.add(fres);
725                 }
726                 else
727                         files = _files;
728                 Collections.sort(files, new Comparator<FileResource>() {
729
730                         @Override
731                         public int compare(FileResource arg0, FileResource arg1) {
732                                 return arg0.getName().compareTo(arg1.getName());
733                         }
734
735                 });
736                 folderFileCount = files.size();
737                 
738                 nameHeader.setSorted(true);
739                 nameHeader.toggleReverseSort();
740                 for (SortableHeader otherHeader : allHeaders) {
741                   if (otherHeader != nameHeader) {
742                     otherHeader.setSorted(false);
743                     otherHeader.setReverseSort(true);
744                   }
745                 }
746                 //
747         }
748
749         
750
751         
752         /**
753          * Does the list contains the requested filename
754          *
755          * @param fileName
756          * @return true/false
757          */
758         public boolean contains(String fileName) {
759                 for (int i = 0; i < files.size(); i++)
760                         if (files.get(i).getName().equals(fileName))
761                                 return true;
762                 return false;
763         }
764
765         public void clearSelectedRows() {
766                 Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
767                 while(it.hasNext()){
768                         selectionModel.setSelected(it.next(),false);
769                 }
770         }
771         
772
773         /**
774          *
775          */
776         public void selectAllRows() {
777                 Iterator<FileResource> it = provider.getList().iterator();
778                 while(it.hasNext()){
779                         selectionModel.setSelected(it.next(),true);
780                 }
781
782
783         }
784
785         
786         private void sortFiles(final String sortingProperty, final boolean sortingType){
787                 Collections.sort(files, new Comparator<FileResource>() {
788
789             @Override
790             public int compare(FileResource arg0, FileResource arg1) {
791                     AbstractImagePrototype descPrototype = AbstractImagePrototype.create(images.desc());
792                     AbstractImagePrototype ascPrototype = AbstractImagePrototype.create(images.asc());
793                     if (sortingType){
794                             if (sortingProperty.equals("version")) {
795                                     return arg0.getVersion().compareTo(arg1.getVersion());
796                             } else if (sortingProperty.equals("owner")) {
797                                     return arg0.getOwner().compareTo(arg1.getOwner());
798                             } else if (sortingProperty.equals("date")) {
799                                     return arg0.getModificationDate().compareTo(arg1.getModificationDate());
800                             } else if (sortingProperty.equals("size")) {
801                                     return arg0.getContentLength().compareTo(arg1.getContentLength());
802                             } else if (sortingProperty.equals("name")) {
803                                     return arg0.getName().compareTo(arg1.getName());
804                             } else if (sortingProperty.equals("path")) {
805                                     return arg0.getUri().compareTo(arg1.getUri());
806                             } else {
807                                     return arg0.getName().compareTo(arg1.getName());
808                             }
809                     }
810                     else if (sortingProperty.equals("version")) {
811                             
812                             return arg1.getVersion().compareTo(arg0.getVersion());
813                     } else if (sortingProperty.equals("owner")) {
814                             
815                             return arg1.getOwner().compareTo(arg0.getOwner());
816                     } else if (sortingProperty.equals("date")) {
817                             
818                             return arg1.getModificationDate().compareTo(arg0.getModificationDate());
819                     } else if (sortingProperty.equals("size")) {
820                             
821                             return arg1.getContentLength().compareTo(arg0.getContentLength());
822                     } else if (sortingProperty.equals("name")) {
823                             
824                             return arg1.getName().compareTo(arg0.getName());
825                     } else if (sortingProperty.equals("path")) {
826                             
827                             return arg1.getUri().compareTo(arg0.getUri());
828                     } else {
829                             
830                             return arg1.getName().compareTo(arg0.getName());
831                     }
832             }
833
834                 });
835         }
836         
837         final class FileValueUpdater implements ValueUpdater<String>{
838                 private String property;
839                 private SortableHeader header;
840                 /**
841                  * 
842                  */
843                 public FileValueUpdater(SortableHeader header,String property) {
844                         this.property=property;
845                         this.header=header;
846                 }
847                 @Override
848                 public void update(String value) {
849                         header.setSorted(true);
850                         header.toggleReverseSort();
851
852                 for (SortableHeader otherHeader : allHeaders) {
853                   if (otherHeader != header) {
854                     otherHeader.setSorted(false);
855                     otherHeader.setReverseSort(true);
856                   }
857                 }
858                 celltable.redrawHeaders();
859                 sortFiles(property, header.getReverseSort());
860                 FileList.this.update(true);                     
861                 }
862                 
863         }
864         /**
865          * Creates a new ArrayList<FileResources> from the given files ArrayList 
866          * in order that the input files remain untouched 
867          * and continues to find user's full names of each FileResource element
868          * in the new ArrayList
869          *    
870          * @param filesInput
871          */
872         private void copyListAndContinue(List<FileResource> filesInput){
873                 List<FileResource> copiedFiles = new ArrayList<FileResource>();         
874                 for(FileResource file : filesInput) {
875                         copiedFiles.add(file);
876                 }
877                 handleFullNames(copiedFiles);
878         }
879         
880         /**
881          * Examines whether or not the user's full name exists in the 
882          * userFullNameMap in the GSS.java for every element of the input list.
883          * If the user's full name does not exist in the map then a command is being made.  
884          * 
885          * @param filesInput
886          */
887         private void handleFullNames(List<FileResource> filesInput){            
888                 if(filesInput.size() == 0){
889                         showCellTable();
890                         return;
891                 }               
892
893                 if(GSS.get().findUserFullName(filesInput.get(0).getOwner()) == null){
894                         findFullNameAndUpdate(filesInput);              
895                         return;
896                 }
897                                 
898                 if(filesInput.size() >= 1){
899                         filesInput.remove(filesInput.get(0));
900                         if(filesInput.isEmpty()){
901                                 showCellTable();                                
902                         }else{
903                                 handleFullNames(filesInput);
904                         }
905                 }               
906         }
907         
908         /**
909          * Makes a command to search for full name from a given username. 
910          * Only after the completion of the command the celltable is shown
911          * or the search for the next full name continues.
912          *  
913          * @param filesInput
914          */
915         private void findFullNameAndUpdate(final List<FileResource> filesInput){                
916                 String aUserName = filesInput.get(0).getOwner();
917                 String path = GSS.get().getApiPath() + "users/" + aUserName; 
918
919                 GetCommand<UserSearchResource> gg = new GetCommand<UserSearchResource>(UserSearchResource.class, path, false,null) {
920                         @Override
921                         public void onComplete() {
922                                 final UserSearchResource result = getResult();
923                                 for (UserResource user : result.getUsers()){
924                                         String username = user.getUsername();
925                                         String userFullName = user.getName();
926                                         GSS.get().putUserToMap(username, userFullName);
927                                         if(filesInput.size() >= 1){
928                                                 filesInput.remove(filesInput.get(0));
929                                                 if(filesInput.isEmpty()){
930                                                         showCellTable();
931                                                 }else{
932                                                         handleFullNames(filesInput);
933                                                 }                                                                                               
934                                         }                                                                       
935                                 }
936                         }
937                         @Override
938                         public void onError(Throwable t) {
939                                 GWT.log("", t);
940                                 GSS.get().displayError("Unable to fetch user's full name from the given username " + filesInput.get(0).getOwner());
941                                 if(filesInput.size() >= 1){
942                                         filesInput.remove(filesInput.get(0));
943                                         handleFullNames(filesInput);                                    
944                                 }
945                         }
946                 };
947                 DeferredCommand.addCommand(gg);
948         
949         }
950         /**
951          * Shows the files in the cellTable 
952          */
953
954         private void showCellTable(){
955                 if(files.size()>GSS.VISIBLE_FILE_COUNT){
956                         pagerBottom.setVisible(true);
957                         pagerTop.setVisible(true);
958                 }
959                 else{
960                         pagerTop.setVisible(false);
961                         pagerBottom.setVisible(false);
962                 }
963                 RestResource selectedItem = GSS.get().getTreeView().getSelection();
964                 boolean uploadVisible = !(selectedItem != null && (selectedItem instanceof TrashResource || selectedItem instanceof TrashFolderResource || selectedItem instanceof SharedResource || selectedItem instanceof OthersResource || selectedItem instanceof OtherUserResource));
965                 uploadButtonBottom.setVisible(uploadVisible&&files.size()>=GSS.VISIBLE_FILE_COUNT);
966                 uploadButtonTop.setVisible(uploadVisible&&files.size()>=GSS.VISIBLE_FILE_COUNT);
967                 provider.setList(files);
968                 
969                 provider.refresh();
970                 
971                 //celltable.redraw();
972                 celltable.redrawHeaders();              
973         }
974
975         
976 }