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