Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (33.4 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.commands.UploadFileCommand;
23
import gr.ebs.gss.client.rest.GetCommand;
24
import gr.ebs.gss.client.rest.RestCommand;
25
import gr.ebs.gss.client.rest.resource.FileResource;
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.OthersResource;
29
import gr.ebs.gss.client.rest.resource.RestResource;
30
import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
31
import gr.ebs.gss.client.rest.resource.SharedResource;
32
import gr.ebs.gss.client.rest.resource.TrashFolderResource;
33
import gr.ebs.gss.client.rest.resource.TrashResource;
34
import gr.ebs.gss.client.rest.resource.UserResource;
35
import gr.ebs.gss.client.rest.resource.UserSearchResource;
36
import gwtquery.plugins.draggable.client.DraggableOptions;
37
import gwtquery.plugins.draggable.client.StopDragException;
38
import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction;
39
import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption;
40
import gwtquery.plugins.draggable.client.events.DragContext;
41
import gwtquery.plugins.draggable.client.events.DragStartEvent;
42
import gwtquery.plugins.draggable.client.events.DragStopEvent;
43
import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler;
44
import gwtquery.plugins.draggable.client.events.DragStopEvent.DragStopEventHandler;
45
import gwtquery.plugins.droppable.client.gwt.DragAndDropCellTable;
46
import gwtquery.plugins.droppable.client.gwt.DragAndDropColumn;
47

    
48
import java.util.ArrayList;
49
import java.util.Collections;
50
import java.util.Comparator;
51
import java.util.Iterator;
52
import java.util.List;
53

    
54
import com.google.gwt.cell.client.AbstractCell;
55
import com.google.gwt.cell.client.ImageResourceCell;
56
import com.google.gwt.cell.client.SafeHtmlCell;
57
import com.google.gwt.cell.client.TextCell;
58
import com.google.gwt.cell.client.ValueUpdater;
59
import com.google.gwt.core.client.GWT;
60
import com.google.gwt.core.client.Scheduler;
61
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
62
import com.google.gwt.dom.client.Style.Cursor;
63
import com.google.gwt.event.dom.client.ClickEvent;
64
import com.google.gwt.event.dom.client.ClickHandler;
65
import com.google.gwt.http.client.URL;
66
import com.google.gwt.i18n.client.DateTimeFormat;
67
import com.google.gwt.resources.client.ClientBundle;
68
import com.google.gwt.resources.client.ImageResource;
69
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
70
import com.google.gwt.safehtml.shared.SafeHtml;
71
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
72
import com.google.gwt.user.cellview.client.CellTable;
73
import com.google.gwt.user.cellview.client.GssSimplePager;
74
import com.google.gwt.user.client.DOM;
75
import com.google.gwt.user.client.DeferredCommand;
76
import com.google.gwt.user.client.Event;
77
import com.google.gwt.user.client.Window;
78
import com.google.gwt.user.client.ui.AbstractImagePrototype;
79
import com.google.gwt.user.client.ui.Button;
80
import com.google.gwt.user.client.ui.Composite;
81
import com.google.gwt.user.client.ui.HorizontalPanel;
82
import com.google.gwt.user.client.ui.VerticalPanel;
83
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
84
import com.google.gwt.view.client.ListDataProvider;
85
import com.google.gwt.view.client.MultiSelectionModel;
86
import com.google.gwt.view.client.ProvidesKey;
87
import com.google.gwt.view.client.SelectionChangeEvent;
88
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
89

    
90
/**
91
 * A composite that displays the list of files in a particular folder.
92
 */
93
public class FileList extends Composite {
94
        ListDataProvider<FileResource> provider = new ListDataProvider<FileResource>();
95
        interface TableResources extends DragAndDropCellTable.Resources {
96
            @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
97
            TableStyle cellTableStyle();
98
          }
99
        
100
        static interface Templates extends SafeHtmlTemplates {
101
            Templates INSTANCE = GWT.create(Templates.class);
102

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

    
114
        private String showingStats = "";
115

    
116
        private int startIndex = 0;
117

    
118
        /**
119
         * A constant that denotes the completion of an IncrementalCommand.
120
         */
121
        public static final boolean DONE = false;
122

    
123
        
124
        
125
        private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
126

    
127
        /**
128
         * Specifies that the images available for this composite will be the ones
129
         * available in FileContextMenu.
130
         */
131
        public interface Images extends ClientBundle,FileContextMenu.Images, CellTreeView.Images {
132

    
133
                @Source("gr/ebs/gss/resources/blank.gif")
134
                ImageResource blank();
135

    
136
                @Source("gr/ebs/gss/resources/asc.png")
137
                ImageResource asc();
138

    
139
                @Source("gr/ebs/gss/resources/desc.png")
140
                ImageResource desc();
141

    
142
                @Source("gr/ebs/gss/resources/mimetypes/document_shared.png")
143
                ImageResource documentShared();
144

    
145
                @Source("gr/ebs/gss/resources/mimetypes/kcmfontinst.png")
146
                ImageResource wordprocessor();
147

    
148
                @Source("gr/ebs/gss/resources/mimetypes/log.png")
149
                ImageResource spreadsheet();
150

    
151
                @Source("gr/ebs/gss/resources/mimetypes/kpresenter_kpr.png")
152
                ImageResource presentation();
153

    
154
                @Source("gr/ebs/gss/resources/mimetypes/acroread.png")
155
                ImageResource pdf();
156

    
157
                @Source("gr/ebs/gss/resources/mimetypes/image.png")
158
                ImageResource image();
159

    
160
                @Source("gr/ebs/gss/resources/mimetypes/video2.png")
161
                ImageResource video();
162

    
163
                @Source("gr/ebs/gss/resources/mimetypes/knotify.png")
164
                ImageResource audio();
165

    
166
                @Source("gr/ebs/gss/resources/mimetypes/html.png")
167
                ImageResource html();
168

    
169
                @Source("gr/ebs/gss/resources/mimetypes/txt.png")
170
                ImageResource txt();
171

    
172
                @Source("gr/ebs/gss/resources/mimetypes/ark2.png")
173
                ImageResource zip();
174

    
175
                @Source("gr/ebs/gss/resources/mimetypes/kcmfontinst_shared.png")
176
                ImageResource wordprocessorShared();
177

    
178
                @Source("gr/ebs/gss/resources/mimetypes/log_shared.png")
179
                ImageResource spreadsheetShared();
180

    
181
                @Source("gr/ebs/gss/resources/mimetypes/kpresenter_kpr_shared.png")
182
                ImageResource presentationShared();
183

    
184
                @Source("gr/ebs/gss/resources/mimetypes/acroread_shared.png")
185
                ImageResource pdfShared();
186

    
187
                @Source("gr/ebs/gss/resources/mimetypes/image_shared.png")
188
                ImageResource imageShared();
189

    
190
                @Source("gr/ebs/gss/resources/mimetypes/video2_shared.png")
191
                ImageResource videoShared();
192

    
193
                @Source("gr/ebs/gss/resources/mimetypes/knotify_shared.png")
194
                ImageResource audioShared();
195

    
196
                @Source("gr/ebs/gss/resources/mimetypes/html_shared.png")
197
                ImageResource htmlShared();
198

    
199
                @Source("gr/ebs/gss/resources/mimetypes/txt_shared.png")
200
                ImageResource txtShared();
201

    
202
                @Source("gr/ebs/gss/resources/mimetypes/ark2_shared.png")
203
                ImageResource zipShared();
204

    
205
        }
206
        
207
        DragStopEventHandler dragStop = new DragStopEventHandler() {
208
                
209
                @Override
210
                public void onDragStop(DragStopEvent event) {
211
                        GWT.log("DRAG STOPPED");
212
                        
213
                }
214
        };
215
        
216
        private static class ContactCell extends AbstractCell<gr.ebs.gss.client.rest.resource.FileResource> {
217

    
218
            /**
219
             * The html of the image used for contacts.
220
             * 
221
             */
222
            private final String imageHtml;
223

    
224
            public ContactCell(ImageResource image) {
225
              this.imageHtml = AbstractImagePrototype.create(image).getHTML();
226
            }
227

    
228
            
229

    
230
                
231

    
232
            @Override
233
            public void render(Context context, FileResource value, SafeHtmlBuilder sb) {
234
              // Value can be null, so do a null check..
235
              if (value == null) {
236
                return;
237
              }
238

    
239
              sb.appendHtmlConstant("<table>");
240

    
241
              // Add the contact image.
242
              sb.appendHtmlConstant("<tr><td rowspan='3'>");
243
              sb.appendHtmlConstant(imageHtml);
244
              sb.appendHtmlConstant("</td>");
245

    
246
              // Add the name and address.
247
              DisplayHelper.log("value.getName()");
248
              sb.appendHtmlConstant("<td style='font-size:95%;' id='"+value.getName()+"'>");
249
              sb.appendEscaped(value.getName());
250
              sb.appendHtmlConstant("</td></tr><tr><td>");
251
              sb.appendEscaped(value.getFileSizeAsString());
252
              sb.appendHtmlConstant("</td></tr></table>");
253
            }
254

    
255

    
256
          }
257
        /**
258
         * Retrieve the celltable.
259
         *
260
         * @return the celltable
261
         */
262
        public DragAndDropCellTable<FileResource> getCelltable() {
263
                return celltable;
264
        }
265
        
266
        
267
        /**
268
         * The number of files in this folder.
269
         */
270
        int folderFileCount;
271

    
272
        /**
273
         * Total folder size
274
         */
275
        long folderTotalSize;
276

    
277
        /**
278
         * A cache of the files in the list.
279
         */
280
        private List<FileResource> files;
281

    
282
        /**
283
         * The widget's image bundle.
284
         */
285
        private final Images images;
286
        
287
        private FileContextMenu menuShowing;
288
        private DragAndDropCellTable<FileResource> celltable;
289
        private final MultiSelectionModel<FileResource> selectionModel;
290
        private final List<SortableHeader> allHeaders = new ArrayList<SortableHeader>();
291
        SortableHeader nameHeader;
292
        GssSimplePager pager;
293
        GssSimplePager pagerTop;
294
        Button uploadButton;
295
        /**
296
         * Construct the file list widget. This entails setting up the widget
297
         * layout, fetching the number of files in the current folder from the
298
         * server and filling the local file cache of displayed files with data from
299
         * the server, as well.
300
         *
301
         * @param _images
302
         */
303
        public FileList(Images _images) {
304
                images = _images;
305
                DragAndDropCellTable.Resources resources = GWT.create(TableResources.class);
306
                ProvidesKey<FileResource> keyProvider = new ProvidesKey<FileResource>(){
307

    
308
                        @Override
309
                        public Object getKey(FileResource item) {
310
                                return item.getUri();
311
                        }
312
                        
313
                };
314
                celltable = new DragAndDropCellTable<FileResource>(GSS.VISIBLE_FILE_COUNT,resources,keyProvider);
315
                
316
                DragAndDropColumn<FileResource, ImageResource> status = new DragAndDropColumn<FileResource, ImageResource>(new ImageResourceCell(){
317
                        @Override
318
                  public boolean handlesSelection() {
319
                            return false;
320
                          }
321
                }) {
322
                  @Override
323
                  public ImageResource getValue(FileResource entity) {
324
                    return getFileIcon(entity);
325
                  }
326
                  
327
               };
328
            celltable.addColumn(status,"");
329
            
330
            initDragOperation(status);
331
                final DragAndDropColumn<FileResource,SafeHtml> nameColumn = new DragAndDropColumn<FileResource,SafeHtml>(new SafeHtmlCell()) {
332

    
333

    
334
                        @Override
335
                        public SafeHtml getValue(FileResource object) {
336
                                SafeHtmlBuilder sb = new SafeHtmlBuilder();
337
                                if (object.getContentType().endsWith("png") || object.getContentType().endsWith("gif") || object.getContentType().endsWith("jpeg") ){                                        
338
                                        sb.appendHtmlConstant("<span id='fileList."+ object.getName() +"'>");
339
                                        sb.appendEscaped(object.getName());
340
                                        sb.appendHtmlConstant("</span>");
341
                                        sb.appendHtmlConstant(" <a href='" +
342
                                GSS.get().getTopPanel().getFileMenu().getDownloadURL(object) +
343
                                "' title='" + object.getOwner() + " : " + object.getPath() + object.getName() +
344
                                "' rel='lytebox[mnf]' " +
345
                                "onclick='myLytebox.start(this, false, false); return false;'>" +
346
                                "(view)" + "</a>");
347
                                        
348
                                        
349
                                }
350
                                else{                                        
351
                                        sb.appendHtmlConstant("<span id='fileList."+ object.getName() +"'>");
352
                                        sb.appendEscaped(object.getName());
353
                                        sb.appendHtmlConstant("</span>");
354
                                }
355
                                
356
                                return sb.toSafeHtml();
357
                        }
358
                        
359
                };
360
                initDragOperation(nameColumn);
361
                celltable.addColumn(nameColumn,nameHeader = new SortableHeader("Name"));
362
                allHeaders.add(nameHeader);
363
                //nameHeader.setSorted(true);
364
                //nameHeader.toggleReverseSort();
365
                nameHeader.setUpdater(new FileValueUpdater(nameHeader, "name"));
366
                celltable.redrawHeaders();
367
                
368
                
369
            
370
            
371
            SortableHeader aheader;
372
            DragAndDropColumn<FileResource,String> aColumn;
373
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
374
                        @Override
375
                        public String getValue(FileResource object) {
376
                                return GSS.get().findUserFullName(object.getOwner());
377
                        }                        
378
                },aheader = new SortableHeader("Owner"));
379
                initDragOperation(aColumn);
380
                allHeaders.add(aheader);
381
                aheader.setUpdater(new FileValueUpdater(aheader, "owner"));
382
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
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
                initDragOperation(aColumn);
390
                allHeaders.add(aheader);
391
                
392
                aheader.setUpdater(new FileValueUpdater(aheader, "path"));        
393
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
394
                        @Override
395
                        public String getValue(FileResource object) {
396
                                if(object.isVersioned())
397
                                        return object.getVersion().toString();
398
                                return "-";
399
                        }                        
400
                },aheader = new SortableHeader("Version"));
401
                initDragOperation(aColumn);
402
                allHeaders.add(aheader);
403
                aheader.setUpdater(new FileValueUpdater(aheader, "version"));
404
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
405
                        @Override
406
                        public String getValue(FileResource object) {
407
                                // TODO Auto-generated method stub
408
                                return object.getFileSizeAsString();
409
                        }                        
410
                },aheader = new SortableHeader("Size"));
411
                initDragOperation(aColumn);
412
                allHeaders.add(aheader);
413
                aheader.setUpdater(new FileValueUpdater(aheader, "size"));        
414
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
415
                        @Override
416
                        public String getValue(FileResource object) {
417
                                return formatter.format(object.getModificationDate());
418
                        }                        
419
                },aheader = new SortableHeader("Last Modified"));
420
                allHeaders.add(aheader);
421
                aheader.setUpdater(new FileValueUpdater(aheader, "date"));
422
               
423
                
424
                provider.addDataDisplay(celltable);
425
                celltable.addDragStopHandler(dragStop);
426
                celltable.addDragStartHandler(new DragStartEventHandler() {
427

    
428
                      public void onDragStart(DragStartEvent event) {
429
                        FileResource value = event.getDraggableData();
430
                        
431
                        com.google.gwt.dom.client.Element helper = event.getHelper();
432
                        SafeHtmlBuilder sb = new SafeHtmlBuilder();
433
                        sb.appendHtmlConstant("<b>");
434
                        DisplayHelper.log(value.getName());
435
                        if(getSelectedFiles().size()==1)
436
                                sb.appendEscaped(value.getName());
437
                        else
438
                                sb.appendEscaped(getSelectedFiles().size()+" files");
439
                        sb.appendHtmlConstant("</b>");
440
                        helper.setInnerHTML(sb.toSafeHtml().asString());
441

    
442
                      }
443
                    });
444
                
445
                
446
                
447
                
448
                
449
                
450
                VerticalPanel vp = new VerticalPanel();
451
                vp.setWidth("100%");
452
                pagerTop = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
453
                pagerTop.setDisplay(celltable);                
454
                vp.add(pagerTop);
455
                celltable.setWidth("100%");
456
                vp.add(celltable);
457
                pager = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
458
                pager.setDisplay(celltable);
459
                HorizontalPanel topPanel = new HorizontalPanel();
460
                topPanel.add(pager);
461
                uploadButton=new Button("<span id='topMenu.file.upload'>" + AbstractImagePrototype.create(images.fileUpdate()).getHTML() + "&nbsp;Upload</span>");
462
                uploadButton.addClickHandler(new ClickHandler() {
463
                        
464
                        @Override
465
                        public void onClick(ClickEvent event) {
466
                                new UploadFileCommand(null).execute();
467
                        }
468
                });
469
                topPanel.add(uploadButton);
470
                vp.add(topPanel);
471
                vp.setCellWidth(celltable, "100%");
472
                
473
                initWidget(vp);
474
                pager.setVisible(false);
475
                pagerTop.setVisible(false);
476

    
477
                celltable.setStyleName("gss-List");
478
                selectionModel = new MultiSelectionModel<FileResource>(keyProvider);
479
                
480

    
481
                 Handler selectionHandler = new SelectionChangeEvent.Handler() { 
482
             @Override 
483
             public void onSelectionChange(com.google.gwt.view.client.SelectionChangeEvent event) {
484
                     if(getSelectedFiles().size()==1)
485
                             GSS.get().setCurrentSelection(getSelectedFiles().get(0));
486
                     else
487
                             GSS.get().setCurrentSelection(getSelectedFiles());
488
             }
489
         };
490
         selectionModel.addSelectionChangeHandler(selectionHandler);
491
         
492
                celltable.setSelectionModel(selectionModel,GSSSelectionEventManager.<FileResource>createDefaultManager());
493
                celltable.setPageSize(GSS.VISIBLE_FILE_COUNT);
494
                
495
                //celltable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
496
                Scheduler.get().scheduleIncremental(new RepeatingCommand() {
497

    
498
                        @Override
499
                        public boolean execute() {
500
                                return fetchRootFolder();
501
                        }
502
                });
503
                sinkEvents(Event.ONCONTEXTMENU);
504
                sinkEvents(Event.ONMOUSEUP);
505
                sinkEvents(Event.ONMOUSEDOWN);
506
                sinkEvents(Event.ONCLICK);
507
                sinkEvents(Event.ONKEYDOWN);
508
                sinkEvents(Event.ONDBLCLICK);
509
                GSS.preventIESelection();
510
        }
511
        
512
        //public native void fireClickEvent(Element element) /*-{
513
          //  var evObj = $doc.createEvent('MouseEvents');
514
            //evObj.initEvent('click', true, true);
515
            //element.dispatchEvent(evObj);
516
          //}-*/;
517
        
518
        
519
        
520
         public List<FileResource> getSelectedFiles() {
521
         return new ArrayList<FileResource>(selectionModel.getSelectedSet());
522
         }
523
        
524
         private void initDragOperation(DragAndDropColumn<?, ?> column) {
525

    
526
                    // retrieve draggableOptions on the column
527
                    DraggableOptions draggableOptions = column.getDraggableOptions();
528
                    // use template to construct the helper. The content of the div will be set
529
                    // after
530
                    draggableOptions.setHelper($(Templates.INSTANCE.outerHelper().asString()));
531
                    //draggableOptions.setZIndex(100);
532
                    // opacity of the helper
533
                    draggableOptions.setAppendTo("body"); 
534
                    //draggableOptions.setOpacity((float) 0.8);
535
                    draggableOptions.setContainment("document");
536
                    // cursor to use during the drag operation
537
                    draggableOptions.setCursor(Cursor.MOVE);
538
                    // set the revert option
539
                    draggableOptions.setRevert(RevertOption.ON_INVALID_DROP);
540
                    // prevents dragging when user click on the category drop-down list
541
                    draggableOptions.setCancel("select");
542
                    
543
                    
544
                    draggableOptions.setOnBeforeDragStart(new DragFunction() {
545
                                
546
                                @Override
547
                                public void f(DragContext context) {
548
                                         FileResource value = context.getDraggableData();
549
                                     if(!selectionModel.isSelected(value)){
550
                                               throw new StopDragException();
551
                                      }
552
                                        
553
                                }
554
                        });
555
                  }
556
        
557
         public void showContextMenu(Event event){
558
                 menuShowing = new FileContextMenu(images, false, true);
559
                        menuShowing=menuShowing.onEmptyEvent(event);
560
         }
561
        @Override
562
        public void onBrowserEvent(Event event) {
563
                
564
                if (files == null || files.size() == 0) {
565
                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
566
                                menuShowing = new FileContextMenu(images, false, true);
567
                                menuShowing=menuShowing.onEmptyEvent(event);
568
                                event.preventDefault();
569
                                event.cancelBubble(true);
570
                        }
571
                        return;
572
                }
573
                if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
574
                        GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
575
                        menuShowing =  new FileContextMenu(images, false, false);
576
                        menuShowing=menuShowing.onEvent(event);
577
                        event.cancelBubble(true);
578
                        event.preventDefault();
579
                } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
580
                        menuShowing = new FileContextMenu(images, false, true);
581
                        menuShowing=menuShowing.onEmptyEvent(event);
582
                        event.cancelBubble(true);
583
                        event.preventDefault();
584
                } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
585
                        if (getSelectedFiles().size() == 1) {
586
                                GSS app = GSS.get();
587
                                FileResource file = getSelectedFiles().get(0);
588
                                String dateString = RestCommand.getDate();
589
                                String resource = file.getUri().substring(app.getApiPath().length() - 1, file.getUri().length());
590
                                String sig = app.getCurrentUserResource().getUsername() + " " +
591
                                                RestCommand.calculateSig("GET", dateString, resource,
592
                                                RestCommand.base64decode(app.getToken()));
593
                                Window.open(file.getUri() + "?Authorization=" + URL.encodeComponent(sig) + "&Date=" + URL.encodeComponent(dateString), "_blank", "");
594
                                event.preventDefault();
595
                                return;
596
                        }
597
                super.onBrowserEvent(event);
598
        }
599

    
600
        /**
601
         * Retrieve the root folder for the current user.
602
         *
603
         * @return true if the retrieval was successful
604
         */
605
        protected boolean fetchRootFolder() {
606
                UserResource user = GSS.get().getCurrentUserResource();
607
                if (user == null)
608
                        return !DONE;
609
                // Update cache and clear selection.
610
                updateFileCache(true);
611
                return DONE;
612
        }
613

    
614

    
615
        /**
616
         * Update the display of the file list.
617
         */
618
        void update(boolean sort) {
619
                int count = folderFileCount;
620
                int max = startIndex + GSS.VISIBLE_FILE_COUNT;
621
                if (max > count)
622
                        max = count;
623
                folderTotalSize = 0;
624
                
625
                copyListAndContinue(files);
626
                for(FileResource f : files){
627
                        folderTotalSize += f.getContentLength();
628
                }
629
                if (folderFileCount == 0) {
630
                        showingStats = "no files";
631
                } else if (folderFileCount < GSS.VISIBLE_FILE_COUNT) {
632
                        if (folderFileCount == 1)
633
                                showingStats = "1 file";
634
                        else
635
                                showingStats = folderFileCount + " files";
636
                        showingStats += " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
637
                } else {
638
                        showingStats = "" + (startIndex + 1) + " - " + max + " of " + count + " files" + " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
639
                }
640
                showCellTable();
641
                updateCurrentlyShowingStats();
642

    
643
        }
644

    
645
        /**
646
         * Return the proper icon based on the MIME type of the file.
647
         *
648
         * @param file
649
         * @return the icon
650
         */
651
        private ImageResource getFileIcon(FileResource file) {
652
                String mimetype = file.getContentType();
653
                boolean shared = false;
654
                if(GSS.get().getTreeView().getSelection()!=null && (GSS.get().getTreeView().getSelection() instanceof OtherUserResource || GSS.get().getTreeView().getSelection() instanceof OthersFolderResource)){
655
                        OtherUserResource otherUser = null;
656
                        if(GSS.get().getTreeView().getSelection() instanceof OtherUserResource)
657
                                otherUser = (OtherUserResource) GSS.get().getTreeView().getSelection();
658
                        else if (GSS.get().getTreeView().getSelection() instanceof OthersFolderResource){
659
                                otherUser = GSS.get().getTreeView().getOtherUserResourceOfOtherFolder((OthersFolderResource) GSS.get().getTreeView().getSelection());
660
                        }
661
                        if(otherUser ==null)
662
                                shared=false;
663
                        else{
664
                                String uname = otherUser.getUsername();
665
                                if(uname==null)
666
                                        uname = GSS.get().getTreeView().getOthers().getUsernameOfUri(otherUser.getUri());
667
                                if(uname != null)
668
                                        shared = file.isShared();
669
                        }
670
                }
671
                else
672
                        shared = file.isShared();
673
                if (mimetype == null)
674
                        return shared ? images.documentShared() : images.document();
675
                mimetype = mimetype.toLowerCase();
676
                if (mimetype.startsWith("application/pdf"))
677
                        return shared ? images.pdfShared() : images.pdf();
678
                else if (mimetype.endsWith("excel"))
679
                        return shared ? images.spreadsheetShared() : images.spreadsheet();
680
                else if (mimetype.endsWith("msword"))
681
                        return shared ? images.wordprocessorShared() : images.wordprocessor();
682
                else if (mimetype.endsWith("powerpoint"))
683
                        return shared ? images.presentationShared() : images.presentation();
684
                else if (mimetype.startsWith("application/zip") ||
685
                                        mimetype.startsWith("application/gzip") ||
686
                                        mimetype.startsWith("application/x-gzip") ||
687
                                        mimetype.startsWith("application/x-tar") ||
688
                                        mimetype.startsWith("application/x-gtar"))
689
                        return shared ? images.zipShared() : images.zip();
690
                else if (mimetype.startsWith("text/html"))
691
                        return shared ? images.htmlShared() : images.html();
692
                else if (mimetype.startsWith("text/plain"))
693
                        return shared ? images.txtShared() : images.txt();
694
                else if (mimetype.startsWith("image/"))
695
                        return shared ? images.imageShared() : images.image();
696
                else if (mimetype.startsWith("video/"))
697
                        return shared ? images.videoShared() : images.video();
698
                else if (mimetype.startsWith("audio/"))
699
                        return shared ? images.audioShared() : images.audio();
700
                return shared ? images.documentShared() : images.document();
701
        }
702

    
703
        /**
704
         * Update status panel with currently showing file stats.
705
         */
706
        public void updateCurrentlyShowingStats() {
707
                GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
708
        }
709
        
710
        public void updateFileCache(boolean clearSelection){
711
                if(clearSelection){
712
                        clearSelectedRows();
713
                }
714
                
715
                final RestResource folderItem = GSS.get().getTreeView().getSelection();
716
                // Validation.
717
                if (folderItem == null || folderItem.equals(GSS.get().getTreeView().getOthers())) {
718
                        setFiles(new ArrayList<FileResource>());
719
                        update(true);
720
                        return;
721
                }
722
                else if (folderItem instanceof RestResourceWrapper) {
723
                        setFiles(((RestResourceWrapper) folderItem).getResource().getFiles());
724
                        update(true);
725
                }
726
                else if (folderItem instanceof SharedResource) {
727
                        setFiles(((SharedResource) folderItem).getFiles());
728
                        update(true);
729
                }
730
                else if (folderItem instanceof OtherUserResource) {
731
                        setFiles(((OtherUserResource) folderItem).getFiles());
732
                        update(true);
733
                }
734
                else if (folderItem instanceof TrashResource) {
735
                        setFiles(((TrashResource) folderItem).getFiles());
736
                        update(true);
737
                }
738
        }
739
        
740

    
741
        /**
742
         * Fill the file cache with data.
743
         */
744
        public void setFiles(final List<FileResource> _files) {
745
                if (_files.size() > 0 && ! (GSS.get().getTreeView().getSelection() instanceof TrashResource)) {
746
                        files = new ArrayList<FileResource>();
747
                        for (FileResource fres : _files)
748
                                if (!fres.isDeleted())
749
                                        files.add(fres);
750
                }
751
                else
752
                        files = _files;
753
                Collections.sort(files, new Comparator<FileResource>() {
754

    
755
                        @Override
756
                        public int compare(FileResource arg0, FileResource arg1) {
757
                                return arg0.getName().compareTo(arg1.getName());
758
                        }
759

    
760
                });
761
                folderFileCount = files.size();
762
                
763
                nameHeader.setSorted(true);
764
                nameHeader.toggleReverseSort();
765
                for (SortableHeader otherHeader : allHeaders) {
766
                  if (otherHeader != nameHeader) {
767
                    otherHeader.setSorted(false);
768
                    otherHeader.setReverseSort(true);
769
                  }
770
                }
771
                //
772
        }
773

    
774
        
775

    
776
        
777
        /**
778
         * Does the list contains the requested filename
779
         *
780
         * @param fileName
781
         * @return true/false
782
         */
783
        public boolean contains(String fileName) {
784
                for (int i = 0; i < files.size(); i++)
785
                        if (files.get(i).getName().equals(fileName))
786
                                return true;
787
                return false;
788
        }
789

    
790
        public void clearSelectedRows() {
791
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
792
                while(it.hasNext()){
793
                        selectionModel.setSelected(it.next(),false);
794
                }
795
        }
796
        
797

    
798
        /**
799
         *
800
         */
801
        public void selectAllRows() {
802
                Iterator<FileResource> it = provider.getList().iterator();
803
                while(it.hasNext()){
804
                        selectionModel.setSelected(it.next(),true);
805
                }
806

    
807

    
808
        }
809

    
810
        
811
        private void sortFiles(final String sortingProperty, final boolean sortingType){
812
                Collections.sort(files, new Comparator<FileResource>() {
813

    
814
            @Override
815
            public int compare(FileResource arg0, FileResource arg1) {
816
                    AbstractImagePrototype descPrototype = AbstractImagePrototype.create(images.desc());
817
                    AbstractImagePrototype ascPrototype = AbstractImagePrototype.create(images.asc());
818
                    if (sortingType){
819
                            if (sortingProperty.equals("version")) {
820
                                    return arg0.getVersion().compareTo(arg1.getVersion());
821
                            } else if (sortingProperty.equals("owner")) {
822
                                    return arg0.getOwner().compareTo(arg1.getOwner());
823
                            } else if (sortingProperty.equals("date")) {
824
                                    return arg0.getModificationDate().compareTo(arg1.getModificationDate());
825
                            } else if (sortingProperty.equals("size")) {
826
                                    return arg0.getContentLength().compareTo(arg1.getContentLength());
827
                            } else if (sortingProperty.equals("name")) {
828
                                    return arg0.getName().compareTo(arg1.getName());
829
                            } else if (sortingProperty.equals("path")) {
830
                                    return arg0.getUri().compareTo(arg1.getUri());
831
                            } else {
832
                                    return arg0.getName().compareTo(arg1.getName());
833
                            }
834
                    }
835
                    else if (sortingProperty.equals("version")) {
836
                            
837
                            return arg1.getVersion().compareTo(arg0.getVersion());
838
                    } else if (sortingProperty.equals("owner")) {
839
                            
840
                            return arg1.getOwner().compareTo(arg0.getOwner());
841
                    } else if (sortingProperty.equals("date")) {
842
                            
843
                            return arg1.getModificationDate().compareTo(arg0.getModificationDate());
844
                    } else if (sortingProperty.equals("size")) {
845
                            
846
                            return arg1.getContentLength().compareTo(arg0.getContentLength());
847
                    } else if (sortingProperty.equals("name")) {
848
                            
849
                            return arg1.getName().compareTo(arg0.getName());
850
                    } else if (sortingProperty.equals("path")) {
851
                            
852
                            return arg1.getUri().compareTo(arg0.getUri());
853
                    } else {
854
                            
855
                            return arg1.getName().compareTo(arg0.getName());
856
                    }
857
            }
858

    
859
                });
860
        }
861
        
862
        final class FileValueUpdater implements ValueUpdater<String>{
863
                private String property;
864
                private SortableHeader header;
865
                /**
866
                 * 
867
                 */
868
                public FileValueUpdater(SortableHeader header,String property) {
869
                        this.property=property;
870
                        this.header=header;
871
                }
872
                @Override
873
                public void update(String value) {
874
                        header.setSorted(true);
875
                        header.toggleReverseSort();
876

    
877
                for (SortableHeader otherHeader : allHeaders) {
878
                  if (otherHeader != header) {
879
                    otherHeader.setSorted(false);
880
                    otherHeader.setReverseSort(true);
881
                  }
882
                }
883
                celltable.redrawHeaders();
884
                sortFiles(property, header.getReverseSort());
885
                FileList.this.update(true);                        
886
                }
887
                
888
        }
889
        /**
890
         * Creates a new ArrayList<FileResources> from the given files ArrayList 
891
         * in order that the input files remain untouched 
892
         * and continues to find user's full names of each FileResource element
893
         * in the new ArrayList
894
         *    
895
         * @param filesInput
896
         */
897
        private void copyListAndContinue(List<FileResource> filesInput){
898
                List<FileResource> copiedFiles = new ArrayList<FileResource>();                
899
                for(FileResource file : filesInput) {
900
                        copiedFiles.add(file);
901
                }
902
                handleFullNames(copiedFiles);
903
        }
904
        
905
        /**
906
         * Examines whether or not the user's full name exists in the 
907
         * userFullNameMap in the GSS.java for every element of the input list.
908
         * If the user's full name does not exist in the map then a command is being made.  
909
         * 
910
         * @param filesInput
911
         */
912
        private void handleFullNames(List<FileResource> filesInput){                
913
                if(filesInput.size() == 0){
914
                        showCellTable();
915
                        return;
916
                }                
917

    
918
                if(GSS.get().findUserFullName(filesInput.get(0).getOwner()) == null){
919
                        findFullNameAndUpdate(filesInput);                
920
                        return;
921
                }
922
                                
923
                if(filesInput.size() >= 1){
924
                        filesInput.remove(filesInput.get(0));
925
                        if(filesInput.isEmpty()){
926
                                showCellTable();                                
927
                        }else{
928
                                handleFullNames(filesInput);
929
                        }
930
                }                
931
        }
932
        
933
        /**
934
         * Makes a command to search for full name from a given username. 
935
         * Only after the completion of the command the celltable is shown
936
         * or the search for the next full name continues.
937
         *  
938
         * @param filesInput
939
         */
940
        private void findFullNameAndUpdate(final List<FileResource> filesInput){                
941
                String aUserName = filesInput.get(0).getOwner();
942
                String path = GSS.get().getApiPath() + "users/" + aUserName; 
943

    
944
                GetCommand<UserSearchResource> gg = new GetCommand<UserSearchResource>(UserSearchResource.class, path, false,null) {
945
                        @Override
946
                        public void onComplete() {
947
                                final UserSearchResource result = getResult();
948
                                for (UserResource user : result.getUsers()){
949
                                        String username = user.getUsername();
950
                                        String userFullName = user.getName();
951
                                        GSS.get().putUserToMap(username, userFullName);
952
                                        if(filesInput.size() >= 1){
953
                                                filesInput.remove(filesInput.get(0));
954
                                                if(filesInput.isEmpty()){
955
                                                        showCellTable();
956
                                                }else{
957
                                                        handleFullNames(filesInput);
958
                                                }                                                                                                
959
                                        }                                                                        
960
                                }
961
                        }
962
                        @Override
963
                        public void onError(Throwable t) {
964
                                GWT.log("", t);
965
                                GSS.get().displayError("Unable to fetch user's full name from the given username " + filesInput.get(0).getOwner());
966
                                if(filesInput.size() >= 1){
967
                                        filesInput.remove(filesInput.get(0));
968
                                        handleFullNames(filesInput);                                        
969
                                }
970
                        }
971
                };
972
                DeferredCommand.addCommand(gg);
973
        
974
        }
975
        /**
976
         * Shows the files in the cellTable 
977
         */
978

    
979
        private void showCellTable(){
980
                if(files.size()>GSS.VISIBLE_FILE_COUNT){
981
                        pager.setVisible(true);
982
                        pagerTop.setVisible(true);
983
                }
984
                else{
985
                        pagerTop.setVisible(false);
986
                        pager.setVisible(false);
987
                }
988
                RestResource selectedItem = GSS.get().getTreeView().getSelection();
989
                boolean uploadVisible = !(selectedItem != null && (selectedItem instanceof TrashResource || selectedItem instanceof TrashFolderResource || selectedItem instanceof SharedResource || selectedItem instanceof OthersResource || selectedItem instanceof OtherUserResource));
990
                uploadButton.setVisible(uploadVisible&&files.size()>=GSS.VISIBLE_FILE_COUNT);
991
                provider.setList(files);
992
                
993
                provider.refresh();
994
                
995
                //celltable.redraw();
996
                celltable.redrawHeaders();                
997
        }
998

    
999
        
1000
}