Statistics
| Branch: | Tag: | Revision:

root / src / gr / ebs / gss / client / FileList.java @ a5f972b3

History | View | Annotate | Download (30.6 kB)

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.OtherUserResource;
27
import gr.ebs.gss.client.rest.resource.OthersFolderResource;
28
import gr.ebs.gss.client.rest.resource.RestResource;
29
import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
30
import gr.ebs.gss.client.rest.resource.SharedResource;
31
import gr.ebs.gss.client.rest.resource.TrashResource;
32
import gr.ebs.gss.client.rest.resource.UserResource;
33
import gr.ebs.gss.client.rest.resource.UserSearchResource;
34
import gwtquery.plugins.draggable.client.DraggableOptions;
35
import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption;
36
import gwtquery.plugins.draggable.client.events.DragStartEvent;
37
import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler;
38
import gwtquery.plugins.droppable.client.gwt.DragAndDropCellTable;
39
import gwtquery.plugins.droppable.client.gwt.DragAndDropColumn;
40

    
41
import java.util.ArrayList;
42
import java.util.Collections;
43
import java.util.Comparator;
44
import java.util.Iterator;
45
import java.util.List;
46

    
47
import com.google.gwt.cell.client.AbstractCell;
48
import com.google.gwt.cell.client.ImageResourceCell;
49
import com.google.gwt.cell.client.TextCell;
50
import com.google.gwt.cell.client.ValueUpdater;
51
import com.google.gwt.core.client.GWT;
52
import com.google.gwt.core.client.Scheduler;
53
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
54
import com.google.gwt.dom.client.Style.Cursor;
55
import com.google.gwt.http.client.URL;
56
import com.google.gwt.i18n.client.DateTimeFormat;
57
import com.google.gwt.resources.client.ClientBundle;
58
import com.google.gwt.resources.client.ImageResource;
59
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
60
import com.google.gwt.safehtml.shared.SafeHtml;
61
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
62
import com.google.gwt.user.cellview.client.CellTable;
63
import com.google.gwt.user.cellview.client.Column;
64
import com.google.gwt.user.cellview.client.TextColumn;
65
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
66
import com.google.gwt.user.client.DOM;
67
import com.google.gwt.user.client.DeferredCommand;
68
import com.google.gwt.user.client.Event;
69
import com.google.gwt.user.client.Window;
70
import com.google.gwt.user.client.ui.AbstractImagePrototype;
71
import com.google.gwt.user.client.ui.Composite;
72
import com.google.gwt.user.client.ui.Grid;
73
import com.google.gwt.user.client.ui.HTML;
74
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
75
import com.google.gwt.user.client.ui.HorizontalPanel;
76
import com.google.gwt.user.client.ui.VerticalPanel;
77
import com.google.gwt.user.client.ui.Widget;
78
import com.google.gwt.view.client.MultiSelectionModel;
79
import com.google.gwt.view.client.ProvidesKey;
80
import com.google.gwt.view.client.SelectionChangeEvent;
81
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
82

    
83
/**
84
 * A composite that displays the list of files in a particular folder.
85
 */
86
public class FileList extends Composite {
87

    
88
        interface TableResources extends DragAndDropCellTable.Resources {
89
            @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
90
            TableStyle cellTableStyle();
91
          }
92
        
93
        static interface Templates extends SafeHtmlTemplates {
94
            Templates INSTANCE = GWT.create(Templates.class);
95

    
96
            @Template("<div id='dragHelper' style='border:1px solid black; background-color:#ffffff; color:black; width:150px;z-index:100'></div>")
97
            SafeHtml outerHelper();
98
          }
99
        
100
        
101
        /**
102
           * The styles applied to the table.
103
           */
104
          interface TableStyle extends CellTable.Style {
105
          }
106

    
107
        private String showingStats = "";
108

    
109
        private int startIndex = 0;
110

    
111
        /**
112
         * A constant that denotes the completion of an IncrementalCommand.
113
         */
114
        public static final boolean DONE = false;
115

    
116
        
117
        
118
        private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
119

    
120
        /**
121
         * Specifies that the images available for this composite will be the ones
122
         * available in FileContextMenu.
123
         */
124
        public interface Images extends ClientBundle,FileContextMenu.Images, CellTreeView.Images {
125

    
126
                @Source("gr/ebs/gss/resources/blank.gif")
127
                ImageResource blank();
128

    
129
                @Source("gr/ebs/gss/resources/asc.png")
130
                ImageResource asc();
131

    
132
                @Source("gr/ebs/gss/resources/desc.png")
133
                ImageResource desc();
134

    
135
                @Source("gr/ebs/gss/resources/mimetypes/document_shared.png")
136
                ImageResource documentShared();
137

    
138
                @Source("gr/ebs/gss/resources/mimetypes/kcmfontinst.png")
139
                ImageResource wordprocessor();
140

    
141
                @Source("gr/ebs/gss/resources/mimetypes/log.png")
142
                ImageResource spreadsheet();
143

    
144
                @Source("gr/ebs/gss/resources/mimetypes/kpresenter_kpr.png")
145
                ImageResource presentation();
146

    
147
                @Source("gr/ebs/gss/resources/mimetypes/acroread.png")
148
                ImageResource pdf();
149

    
150
                @Source("gr/ebs/gss/resources/mimetypes/image.png")
151
                ImageResource image();
152

    
153
                @Source("gr/ebs/gss/resources/mimetypes/video2.png")
154
                ImageResource video();
155

    
156
                @Source("gr/ebs/gss/resources/mimetypes/knotify.png")
157
                ImageResource audio();
158

    
159
                @Source("gr/ebs/gss/resources/mimetypes/html.png")
160
                ImageResource html();
161

    
162
                @Source("gr/ebs/gss/resources/mimetypes/txt.png")
163
                ImageResource txt();
164

    
165
                @Source("gr/ebs/gss/resources/mimetypes/ark2.png")
166
                ImageResource zip();
167

    
168
                @Source("gr/ebs/gss/resources/mimetypes/kcmfontinst_shared.png")
169
                ImageResource wordprocessorShared();
170

    
171
                @Source("gr/ebs/gss/resources/mimetypes/log_shared.png")
172
                ImageResource spreadsheetShared();
173

    
174
                @Source("gr/ebs/gss/resources/mimetypes/kpresenter_kpr_shared.png")
175
                ImageResource presentationShared();
176

    
177
                @Source("gr/ebs/gss/resources/mimetypes/acroread_shared.png")
178
                ImageResource pdfShared();
179

    
180
                @Source("gr/ebs/gss/resources/mimetypes/image_shared.png")
181
                ImageResource imageShared();
182

    
183
                @Source("gr/ebs/gss/resources/mimetypes/video2_shared.png")
184
                ImageResource videoShared();
185

    
186
                @Source("gr/ebs/gss/resources/mimetypes/knotify_shared.png")
187
                ImageResource audioShared();
188

    
189
                @Source("gr/ebs/gss/resources/mimetypes/html_shared.png")
190
                ImageResource htmlShared();
191

    
192
                @Source("gr/ebs/gss/resources/mimetypes/txt_shared.png")
193
                ImageResource txtShared();
194

    
195
                @Source("gr/ebs/gss/resources/mimetypes/ark2_shared.png")
196
                ImageResource zipShared();
197

    
198
        }
199
        private static class ContactCell extends AbstractCell<gr.ebs.gss.client.rest.resource.FileResource> {
200

    
201
            /**
202
             * The html of the image used for contacts.
203
             * 
204
             */
205
            private final String imageHtml;
206

    
207
            public ContactCell(ImageResource image) {
208
              this.imageHtml = AbstractImagePrototype.create(image).getHTML();
209
            }
210

    
211
            
212

    
213
                
214

    
215
            @Override
216
            public void render(Context context, FileResource value, SafeHtmlBuilder sb) {
217
              // Value can be null, so do a null check..
218
              if (value == null) {
219
                return;
220
              }
221

    
222
              sb.appendHtmlConstant("<table>");
223

    
224
              // Add the contact image.
225
              sb.appendHtmlConstant("<tr><td rowspan='3'>");
226
              sb.appendHtmlConstant(imageHtml);
227
              sb.appendHtmlConstant("</td>");
228

    
229
              // Add the name and address.
230
              sb.appendHtmlConstant("<td style='font-size:95%;'>");
231
              sb.appendEscaped(value.getName());
232
              sb.appendHtmlConstant("</td></tr><tr><td>");
233
              sb.appendEscaped(value.getFileSizeAsString());
234
              sb.appendHtmlConstant("</td></tr></table>");
235
            }
236

    
237

    
238
          }
239
        /**
240
         * Retrieve the celltable.
241
         *
242
         * @return the celltable
243
         */
244
        public DragAndDropCellTable<FileResource> getCelltable() {
245
                return celltable;
246
        }
247
        /**
248
         * A label with the number of files in this folder.
249
         */
250
        private HTML countLabel = new HTML();
251

    
252
        /**
253
         * The table widget with the file list.
254
         */
255
        //private FileTable table = new FileTable(GSS.VISIBLE_FILE_COUNT + 1, 8);
256

    
257
        /**
258
         * The navigation bar for paginating the results.
259
         */
260
        private HorizontalPanel navBar = new HorizontalPanel();
261

    
262
        /**
263
         * The number of files in this folder.
264
         */
265
        int folderFileCount;
266

    
267
        /**
268
         * Total folder size
269
         */
270
        long folderTotalSize;
271

    
272
        /**
273
         * A cache of the files in the list.
274
         */
275
        private List<FileResource> files;
276

    
277
        /**
278
         * The widget's image bundle.
279
         */
280
        private final Images images;
281
        VerticalPanel panel;
282
        
283
        private FileContextMenu menuShowing;
284
        private DragAndDropCellTable<FileResource> celltable;
285
        private final MultiSelectionModel<FileResource> selectionModel;
286
        private final List<SortableHeader> allHeaders = new ArrayList<SortableHeader>();
287
        SortableHeader nameHeader;
288
        /**
289
         * Construct the file list widget. This entails setting up the widget
290
         * layout, fetching the number of files in the current folder from the
291
         * server and filling the local file cache of displayed files with data from
292
         * the server, as well.
293
         *
294
         * @param _images
295
         */
296
        public FileList(Images _images) {
297
                images = _images;
298
                DragAndDropCellTable.Resources resources = GWT.create(TableResources.class);
299
                
300
                
301
                // Create the 'navigation' bar at the upper-right.
302
                HorizontalPanel innerNavBar = new HorizontalPanel();
303
                innerNavBar.setStyleName("gss-ListNavBar");
304
                innerNavBar.setSpacing(8);
305
                innerNavBar.add(countLabel);
306
                navBar.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
307
                navBar.add(innerNavBar);
308
                navBar.setWidth("100%");
309
                ProvidesKey<FileResource> keyProvider = new ProvidesKey<FileResource>(){
310

    
311
                        @Override
312
                        public Object getKey(FileResource item) {
313
                                return item.getUri();
314
                        }
315
                        
316
                };
317
                final DragAndDropColumn<FileResource,String> nameColumn = new DragAndDropColumn<FileResource,String>(new TextCell()) {
318

    
319
                        @Override
320
                        public String getValue(FileResource object) {
321
                                // TODO Auto-generated method stub
322
                                return object.getName();
323
                        }
324
                        
325
                        
326
                };
327
                initDragOperation(nameColumn);
328
                celltable = new DragAndDropCellTable<FileResource>(100,resources,keyProvider){
329
                        @Override
330
                        protected void onBrowserEvent2(Event event) {
331
                                /*if (DOM.eventGetType((Event) event) == Event.ONMOUSEDOWN && DOM.eventGetButton((Event) event) == NativeEvent.BUTTON_RIGHT){
332
                                        fireClickEvent((Element) event.getEventTarget().cast());                                        
333
                                }*/
334
                                super.onBrowserEvent2(event);
335
                        }
336
                };
337
                celltable.addDragStartHandler(new DragStartEventHandler() {
338

    
339
                      public void onDragStart(DragStartEvent event) {
340
                        FileResource value = event.getDraggableData();
341
                        if(!selectionModel.isSelected(value)){
342
                                event.getHelper().removeFromParent();
343
                                return;
344
                        }
345
                        
346
                        com.google.gwt.dom.client.Element helper = event.getHelper();
347
                        
348
                        SafeHtmlBuilder sb = new SafeHtmlBuilder();
349
                        // reuse the contact cell to render the inner html of the drag helper.
350
                        ///new CotactCell(images.blank()).render(new Context(0,0, value), value, sb);
351
                        sb.appendHtmlConstant("<b>");
352
                        sb.appendEscaped(value.getName());
353
                        sb.appendHtmlConstant("</b>");
354
                        helper.setInnerHTML(sb.toSafeHtml().asString());
355

    
356
                      }
357
                    });
358
                Column<FileResource, ImageResource> status = new Column<FileResource, ImageResource>(new ImageResourceCell()) {
359
                  @Override
360
                  public ImageResource getValue(FileResource entity) {
361
                    return getFileIcon(entity);
362
                  }
363
               };
364
               celltable.addColumn(status,"");
365
                
366
                
367
                celltable.addColumn(nameColumn,nameHeader = new SortableHeader("Name"));
368
                allHeaders.add(nameHeader);
369
                nameHeader.setSorted(true);
370
                nameHeader.toggleReverseSort();
371
                nameHeader.setUpdater(new FileValueUpdater(nameHeader, "name"));
372
                celltable.redrawHeaders();
373
                SortableHeader aheader;
374
                celltable.addColumn(new TextColumn<FileResource>() {
375
                        @Override
376
                        public String getValue(FileResource object) {
377
                                return GSS.get().findUserFullName(object.getOwner());
378
                        }                        
379
                },aheader = new SortableHeader("Owner"));
380
                allHeaders.add(aheader);
381
                aheader.setUpdater(new FileValueUpdater(aheader, "owner"));
382
                celltable.addColumn(new TextColumn<FileResource>() {
383
                        @Override
384
                        public String getValue(FileResource object) {
385
                                // TODO Auto-generated method stub
386
                                return object.getPath();
387
                        }                        
388
                },aheader = new SortableHeader("Path"));
389
                allHeaders.add(aheader);
390
                aheader.setUpdater(new FileValueUpdater(aheader, "path"));        
391
                celltable.addColumn(new TextColumn<FileResource>() {
392
                        @Override
393
                        public String getValue(FileResource object) {
394
                                // TODO Auto-generated method stub
395
                                return object.getVersion().toString();
396
                        }                        
397
                },aheader = new SortableHeader("Version"));
398
                allHeaders.add(aheader);
399
                aheader.setUpdater(new FileValueUpdater(aheader, "version"));
400
                celltable.addColumn(new TextColumn<FileResource>() {
401
                        @Override
402
                        public String getValue(FileResource object) {
403
                                // TODO Auto-generated method stub
404
                                return object.getFileSizeAsString();
405
                        }                        
406
                },aheader = new SortableHeader("Size"));
407
                allHeaders.add(aheader);
408
                aheader.setUpdater(new FileValueUpdater(aheader, "size"));        
409
                celltable.addColumn(new TextColumn<FileResource>() {
410
                        @Override
411
                        public String getValue(FileResource object) {
412
                                return formatter.format(object.getModificationDate());
413
                        }                        
414
                },aheader = new SortableHeader("Last Modified"));
415
                allHeaders.add(aheader);
416
                aheader.setUpdater(new FileValueUpdater(aheader, "date"));
417
                
418
                initWidget(celltable);
419
                setStyleName("gss-List");
420
                selectionModel = new MultiSelectionModel<FileResource>();
421
                
422

    
423
                 Handler selectionHandler = new SelectionChangeEvent.Handler() { 
424
             @Override 
425
             public void onSelectionChange(com.google.gwt.view.client.SelectionChangeEvent event) {
426
                     if(getSelectedFiles().size()==1)
427
                             GSS.get().setCurrentSelection(getSelectedFiles().get(0));
428
                     else
429
                             GSS.get().setCurrentSelection(getSelectedFiles());
430
                                 //contextMenu.setFiles(getSelectedFiles());
431
             }
432
         };
433
         selectionModel.addSelectionChangeHandler(selectionHandler);
434
         
435
                celltable.setSelectionModel(selectionModel,GSSSelectionEventManager.<FileResource>createDefaultManager());
436
                celltable.setPageSize(GSS.VISIBLE_FILE_COUNT);
437
                celltable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
438
                Scheduler.get().scheduleIncremental(new RepeatingCommand() {
439

    
440
                        @Override
441
                        public boolean execute() {
442
                                return fetchRootFolder();
443
                        }
444
                });
445
                sinkEvents(Event.ONCONTEXTMENU);
446
                sinkEvents(Event.ONMOUSEUP);
447
                sinkEvents(Event.ONMOUSEDOWN);
448
                sinkEvents(Event.ONCLICK);
449
                sinkEvents(Event.ONKEYDOWN);
450
                sinkEvents(Event.ONDBLCLICK);
451
                GSS.preventIESelection();
452
        }
453
        
454
        //public native void fireClickEvent(Element element) /*-{
455
          //  var evObj = $doc.createEvent('MouseEvents');
456
            //evObj.initEvent('click', true, true);
457
            //element.dispatchEvent(evObj);
458
          //}-*/;
459

    
460
         public List<FileResource> getSelectedFiles() {
461
         return new ArrayList<FileResource>(selectionModel.getSelectedSet());
462
         }
463
        
464
         private void initDragOperation(DragAndDropColumn<?, ?> column) {
465

    
466
                    // retrieve draggableOptions on the column
467
                    DraggableOptions draggableOptions = column.getDraggableOptions();
468
                    // use template to construct the helper. The content of the div will be set
469
                    // after
470
                    draggableOptions.setHelper($(Templates.INSTANCE.outerHelper().asString()));
471
                    //draggableOptions.setZIndex(100);
472
                    // opacity of the helper
473
                    draggableOptions.setAppendTo("body"); 
474
                    //draggableOptions.setOpacity((float) 0.8);
475
                    draggableOptions.setContainment("document");
476
                    // cursor to use during the drag operation
477
                    draggableOptions.setCursor(Cursor.MOVE);
478
                    // set the revert option
479
                    draggableOptions.setRevert(RevertOption.ON_INVALID_DROP);
480
                    // prevents dragging when user click on the category drop-down list
481
                    draggableOptions.setCancel("select");
482
                  }
483
        
484

    
485
        @Override
486
        public void onBrowserEvent(Event event) {
487
                
488
                if (files == null || files.size() == 0) {
489
                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
490
                                menuShowing = new FileContextMenu(images, false, true);
491
                                menuShowing=menuShowing.onEmptyEvent(event);
492
                        }
493
                        return;
494
                }
495
                if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
496
                        GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
497
                        menuShowing =  new FileContextMenu(images, false, false);
498
                        menuShowing=menuShowing.onEvent(event);
499
                } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
500
                        menuShowing = new FileContextMenu(images, false, true);
501
                        menuShowing=menuShowing.onEmptyEvent(event);
502
                } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
503
                        if (getSelectedFiles().size() == 1) {
504
                                GSS app = GSS.get();
505
                                FileResource file = getSelectedFiles().get(0);
506
                                String dateString = RestCommand.getDate();
507
                                String resource = file.getUri().substring(app.getApiPath().length() - 1, file.getUri().length());
508
                                String sig = app.getCurrentUserResource().getUsername() + " " +
509
                                                RestCommand.calculateSig("GET", dateString, resource,
510
                                                RestCommand.base64decode(app.getToken()));
511
                                Window.open(file.getUri() + "?Authorization=" + URL.encodeComponent(sig) + "&Date=" + URL.encodeComponent(dateString), "_blank", "");
512
                                event.preventDefault();
513
                                return;
514
                        }
515
                super.onBrowserEvent(event);
516
        }
517

    
518
        /**
519
         * Retrieve the root folder for the current user.
520
         *
521
         * @return true if the retrieval was successful
522
         */
523
        protected boolean fetchRootFolder() {
524
                UserResource user = GSS.get().getCurrentUserResource();
525
                if (user == null)
526
                        return !DONE;
527
                // Update cache and clear selection.
528
                updateFileCache(true);
529
                return DONE;
530
        }
531

    
532

    
533
        /**
534
         * Update the display of the file list.
535
         */
536
        void update(boolean sort) {
537
                int count = folderFileCount;
538
                int max = startIndex + GSS.VISIBLE_FILE_COUNT;
539
                if (max > count)
540
                        max = count;
541
                folderTotalSize = 0;
542
                
543
                copyListAndContinue(files);
544
                for(FileResource f : files){
545
                        folderTotalSize += f.getContentLength();
546
                }
547
                if (folderFileCount == 0) {
548
                        showingStats = "no files";
549
                } else if (folderFileCount < GSS.VISIBLE_FILE_COUNT) {
550
                        if (folderFileCount == 1)
551
                                showingStats = "1 file";
552
                        else
553
                                showingStats = folderFileCount + " files";
554
                        showingStats += " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
555
                } else {
556
                        showingStats = "" + (startIndex + 1) + " - " + max + " of " + count + " files" + " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
557
                }
558
                updateCurrentlyShowingStats();
559

    
560
        }
561

    
562
        /**
563
         * Return the proper icon based on the MIME type of the file.
564
         *
565
         * @param file
566
         * @return the icon
567
         */
568
        private ImageResource getFileIcon(FileResource file) {
569
                String mimetype = file.getContentType();
570
                boolean shared = false;
571
                //TODO: FETCH USER OF OTHER FOLDER ITEM
572
                //if(GSS.get().getTreeView().getSelection()!=null && (GSS.get().getTreeView().getSelection() instanceof OtherUserResource || GSS.get().getTreeView().getSelection() instanceof OthersFolderResource))
573
                /*Folders folders = GSS.get().getFolders();
574
                if(folders.getCurrent() != null && folders.isOthersSharedItem(folders.getCurrent())){
575
                        DnDTreeItem otherUser = (DnDTreeItem) folders.getUserOfSharedItem(folders.getCurrent());
576
                        if(otherUser==null)
577
                                shared = false;
578
                        else{
579
                                String uname = otherUser.getOtherUserResource().getUsername();
580
                                if(uname==null)
581
                                        uname = ((DnDTreeItem)folders.getSharesItem()).getOthersResource().getUsernameOfUri(otherUser.getOtherUserResource().getUri());
582
                                if(uname != null)
583
                                        shared = file.isShared();
584
                        }
585
                }
586
                else*/
587
                        shared = file.isShared();
588
                if (mimetype == null)
589
                        return shared ? images.documentShared() : images.document();
590
                mimetype = mimetype.toLowerCase();
591
                if (mimetype.startsWith("application/pdf"))
592
                        return shared ? images.pdfShared() : images.pdf();
593
                else if (mimetype.endsWith("excel"))
594
                        return shared ? images.spreadsheetShared() : images.spreadsheet();
595
                else if (mimetype.endsWith("msword"))
596
                        return shared ? images.wordprocessorShared() : images.wordprocessor();
597
                else if (mimetype.endsWith("powerpoint"))
598
                        return shared ? images.presentationShared() : images.presentation();
599
                else if (mimetype.startsWith("application/zip") ||
600
                                        mimetype.startsWith("application/gzip") ||
601
                                        mimetype.startsWith("application/x-gzip") ||
602
                                        mimetype.startsWith("application/x-tar") ||
603
                                        mimetype.startsWith("application/x-gtar"))
604
                        return shared ? images.zipShared() : images.zip();
605
                else if (mimetype.startsWith("text/html"))
606
                        return shared ? images.htmlShared() : images.html();
607
                else if (mimetype.startsWith("text/plain"))
608
                        return shared ? images.txtShared() : images.txt();
609
                else if (mimetype.startsWith("image/"))
610
                        return shared ? images.imageShared() : images.image();
611
                else if (mimetype.startsWith("video/"))
612
                        return shared ? images.videoShared() : images.video();
613
                else if (mimetype.startsWith("audio/"))
614
                        return shared ? images.audioShared() : images.audio();
615
                return shared ? images.documentShared() : images.document();
616
        }
617

    
618
        /**
619
         * Update status panel with currently showing file stats.
620
         */
621
        public void updateCurrentlyShowingStats() {
622
                GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
623
        }
624

    
625
        public void updateFileCache(boolean updateSelectedFolder, final boolean clearSelection) {
626
                updateFileCache(updateSelectedFolder, clearSelection, null);
627
        }
628

    
629
        public void updateFileCache(boolean updateSelectedFolder, final boolean clearSelection, final String newFilename) {
630
                if (!updateSelectedFolder && !GSS.get().getTreeView().getSelection().equals(GSS.get().getTreeView().getTrash()))
631
                        updateFileCache(clearSelection);
632
                else if (GSS.get().getTreeView().getSelection() != null) {
633
                        final RestResource selectedResource = GSS.get().getTreeView().getSelection(); 
634
                        if (selectedResource instanceof RestResourceWrapper) {
635
                                
636
                                update(true);
637
                        }
638
                }
639
                updateFileCache(clearSelection);
640
        }
641

    
642

    
643
        private void updateFileCache(boolean clearSelection) {
644
                updateFileCache(clearSelection, null);
645
        }
646

    
647
        /**
648
         * Update the file cache with data from the server.
649
         *
650
         * @param newFilename the new name of the previously selected file,
651
         *                         if a rename operation has taken place
652
         */
653
        private void updateFileCache(boolean clearSelection, String newFilename) {
654
                if (clearSelection)
655
                        clearSelectedRows();
656
                startIndex = 0;
657
                final RestResource folderItem = GSS.get().getTreeView().getSelection();
658
                // Validation.
659
                if (folderItem == null || folderItem.equals(GSS.get().getTreeView().getOthers())) {
660
                        setFiles(new ArrayList<FileResource>());
661
                        update(true);
662
                        return;
663
                }
664
                if (folderItem instanceof RestResourceWrapper) {
665
                        setFiles(((RestResourceWrapper) folderItem).getResource().getFiles());
666
                        update(true);
667
                }
668
                if (folderItem instanceof SharedResource) {
669
                        setFiles(((SharedResource) folderItem).getFiles());
670
                        update(true);
671
                }
672
                if (folderItem instanceof TrashResource) {
673
                        setFiles(((TrashResource) folderItem).getFiles());
674
                        update(true);
675
                }
676
        }
677

    
678
        /**
679
         * Fill the file cache with data.
680
         */
681
        public void setFiles(final List<FileResource> _files) {
682
                if (_files.size() > 0 && ! (GSS.get().getTreeView().getSelection() instanceof TrashResource)) {
683
                        files = new ArrayList<FileResource>();
684
                        for (FileResource fres : _files)
685
                                if (!fres.isDeleted())
686
                                        files.add(fres);
687
                }
688
                else
689
                        files = _files;
690
                Collections.sort(files, new Comparator<FileResource>() {
691

    
692
                        @Override
693
                        public int compare(FileResource arg0, FileResource arg1) {
694
                                return arg0.getName().compareTo(arg1.getName());
695
                        }
696

    
697
                });
698
                folderFileCount = files.size();
699
        }
700

    
701
        
702

    
703
        
704
        /**
705
         * Does the list contains the requested filename
706
         *
707
         * @param fileName
708
         * @return true/false
709
         */
710
        public boolean contains(String fileName) {
711
                for (int i = 0; i < files.size(); i++)
712
                        if (files.get(i).getName().equals(fileName))
713
                                return true;
714
                return false;
715
        }
716

    
717
        public void clearSelectedRows() {
718
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
719
                while(it.hasNext()){
720
                        selectionModel.setSelected(it.next(),false);
721
                }
722
        }
723

    
724
        /**
725
         *
726
         */
727
        public void selectAllRows() {
728
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
729
                while(it.hasNext()){
730
                        selectionModel.setSelected(it.next(),true);
731
                }
732

    
733

    
734
        }
735

    
736
        
737
        private void sortFiles(final String sortingProperty, final boolean sortingType){
738
                Collections.sort(files, new Comparator<FileResource>() {
739

    
740
            @Override
741
            public int compare(FileResource arg0, FileResource arg1) {
742
                    AbstractImagePrototype descPrototype = AbstractImagePrototype.create(images.desc());
743
                    AbstractImagePrototype ascPrototype = AbstractImagePrototype.create(images.asc());
744
                    if (sortingType){
745
                            if (sortingProperty.equals("version")) {
746
                                    return arg0.getVersion().compareTo(arg1.getVersion());
747
                            } else if (sortingProperty.equals("owner")) {
748
                                    return arg0.getOwner().compareTo(arg1.getOwner());
749
                            } else if (sortingProperty.equals("date")) {
750
                                    return arg0.getModificationDate().compareTo(arg1.getModificationDate());
751
                            } else if (sortingProperty.equals("size")) {
752
                                    return arg0.getContentLength().compareTo(arg1.getContentLength());
753
                            } else if (sortingProperty.equals("name")) {
754
                                    return arg0.getName().compareTo(arg1.getName());
755
                            } else if (sortingProperty.equals("path")) {
756
                                    return arg0.getUri().compareTo(arg1.getUri());
757
                            } else {
758
                                    return arg0.getName().compareTo(arg1.getName());
759
                            }
760
                    }
761
                    else if (sortingProperty.equals("version")) {
762
                            
763
                            return arg1.getVersion().compareTo(arg0.getVersion());
764
                    } else if (sortingProperty.equals("owner")) {
765
                            
766
                            return arg1.getOwner().compareTo(arg0.getOwner());
767
                    } else if (sortingProperty.equals("date")) {
768
                            
769
                            return arg1.getModificationDate().compareTo(arg0.getModificationDate());
770
                    } else if (sortingProperty.equals("size")) {
771
                            
772
                            return arg1.getContentLength().compareTo(arg0.getContentLength());
773
                    } else if (sortingProperty.equals("name")) {
774
                            
775
                            return arg1.getName().compareTo(arg0.getName());
776
                    } else if (sortingProperty.equals("path")) {
777
                            
778
                            return arg1.getUri().compareTo(arg0.getUri());
779
                    } else {
780
                            
781
                            return arg1.getName().compareTo(arg0.getName());
782
                    }
783
            }
784

    
785
                });
786
        }
787
        
788
        final class FileValueUpdater implements ValueUpdater<String>{
789
                private String property;
790
                private SortableHeader header;
791
                /**
792
                 * 
793
                 */
794
                public FileValueUpdater(SortableHeader header,String property) {
795
                        this.property=property;
796
                        this.header=header;
797
                }
798
                @Override
799
                public void update(String value) {
800
                        header.setSorted(true);
801
                        header.toggleReverseSort();
802

    
803
                for (SortableHeader otherHeader : allHeaders) {
804
                  if (otherHeader != header) {
805
                    otherHeader.setSorted(false);
806
                    otherHeader.setReverseSort(true);
807
                  }
808
                }
809
                celltable.redrawHeaders();
810
                sortFiles(property, header.getReverseSort());
811
                FileList.this.update(true);                        
812
                }
813
                
814
        }
815
        /**
816
         * Creates a new ArrayList<FileResources> from the given files ArrayList 
817
         * in order that the input files remain untouched 
818
         * and continues to find user's full names of each FileResource element
819
         * in the new ArrayList
820
         *    
821
         * @param filesInput
822
         */
823
        private void copyListAndContinue(List<FileResource> filesInput){
824
                List<FileResource> copiedFiles = new ArrayList<FileResource>();                
825
                for(FileResource file : filesInput) {
826
                        copiedFiles.add(file);
827
                }
828
                handleFullNames(copiedFiles);
829
        }
830
        
831
        /**
832
         * Examines whether or not the user's full name exists in the 
833
         * userFullNameMap in the GSS.java for every element of the input list.
834
         * If the user's full name does not exist in the map then a command is being made.  
835
         * 
836
         * @param filesInput
837
         */
838
        private void handleFullNames(List<FileResource> filesInput){                
839
                if(filesInput.size() == 0){
840
                        showCellTable();
841
                        return;
842
                }                
843

    
844
                if(GSS.get().findUserFullName(filesInput.get(0).getOwner()) == null){
845
                        findFullNameAndUpdate(filesInput);                
846
                        return;
847
                }
848
                                
849
                if(filesInput.size() >= 1){
850
                        filesInput.remove(filesInput.get(0));
851
                        if(filesInput.isEmpty()){
852
                                showCellTable();                                
853
                        }else{
854
                                handleFullNames(filesInput);
855
                        }
856
                }                
857
        }
858
        
859
        /**
860
         * Makes a command to search for full name from a given username. 
861
         * Only after the completion of the command the celltable is shown
862
         * or the search for the next full name continues.
863
         *  
864
         * @param filesInput
865
         */
866
        private void findFullNameAndUpdate(final List<FileResource> filesInput){                
867
                String aUserName = filesInput.get(0).getOwner();
868
                String path = GSS.get().getApiPath() + "users/" + aUserName; 
869

    
870
                GetCommand<UserSearchResource> gg = new GetCommand<UserSearchResource>(UserSearchResource.class, path, false,null) {
871
                        @Override
872
                        public void onComplete() {
873
                                final UserSearchResource result = getResult();
874
                                for (UserResource user : result.getUsers()){
875
                                        String username = user.getUsername();
876
                                        String userFullName = user.getName();
877
                                        GSS.get().putUserToMap(username, userFullName);
878
                                        if(filesInput.size() >= 1){
879
                                                filesInput.remove(filesInput.get(0));
880
                                                if(filesInput.isEmpty()){
881
                                                        showCellTable();
882
                                                }else{
883
                                                        handleFullNames(filesInput);
884
                                                }                                                                                                
885
                                        }                                                                        
886
                                }
887
                        }
888
                        @Override
889
                        public void onError(Throwable t) {
890
                                GWT.log("", t);
891
                                GSS.get().displayError("Unable to fetch user's full name from the given username " + filesInput.get(0).getOwner());
892
                                if(filesInput.size() >= 1){
893
                                        filesInput.remove(filesInput.get(0));
894
                                        handleFullNames(filesInput);                                        
895
                                }
896
                        }
897
                };
898
                DeferredCommand.addCommand(gg);
899
        
900
        }
901
        /**
902
         * Shows the files in the cellTable 
903
         */
904

    
905
        private void showCellTable(){
906
                celltable.setRowCount(files.size());
907
                celltable.setRowData(0,files);
908
                celltable.redrawHeaders();                
909
        }
910

    
911
        
912
}