fix sharing icon and popup for my shared items and others
[pithos] / src / gr / ebs / gss / client / GSS.java
1 /*
2  * Copyright 2007, 2008, 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.client;
20
21 import gr.ebs.gss.client.clipboard.Clipboard;
22 import gr.ebs.gss.client.dnd.DnDFocusPanel;
23 import gr.ebs.gss.client.dnd.DnDSimpleFocusPanel;
24 import gr.ebs.gss.client.rest.GetCommand;
25 import gr.ebs.gss.client.rest.RestException;
26 import gr.ebs.gss.client.rest.resource.FileResource;
27 import gr.ebs.gss.client.rest.resource.FolderResource;
28 import gr.ebs.gss.client.rest.resource.TrashResource;
29 import gr.ebs.gss.client.rest.resource.UserResource;
30
31 import java.util.Iterator;
32 import java.util.List;
33
34 import com.allen_sauer.gwt.dnd.client.DragContext;
35 import com.allen_sauer.gwt.dnd.client.PickupDragController;
36 import com.allen_sauer.gwt.dnd.client.VetoDragException;
37 import com.google.gwt.core.client.EntryPoint;
38 import com.google.gwt.core.client.GWT;
39 import com.google.gwt.event.logical.shared.ResizeEvent;
40 import com.google.gwt.event.logical.shared.ResizeHandler;
41 import com.google.gwt.event.logical.shared.SelectionEvent;
42 import com.google.gwt.event.logical.shared.SelectionHandler;
43 import com.google.gwt.resources.client.ClientBundle;
44 import com.google.gwt.resources.client.ImageResource;
45 import com.google.gwt.user.client.Command;
46 import com.google.gwt.user.client.Cookies;
47 import com.google.gwt.user.client.DOM;
48 import com.google.gwt.user.client.DeferredCommand;
49 import com.google.gwt.user.client.Window;
50 import com.google.gwt.user.client.ui.AbsolutePanel;
51 import com.google.gwt.user.client.ui.AbstractImagePrototype;
52 import com.google.gwt.user.client.ui.DecoratedTabPanel;
53 import com.google.gwt.user.client.ui.DockPanel;
54 import com.google.gwt.user.client.ui.HTML;
55 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
56 import com.google.gwt.user.client.ui.HasVerticalAlignment;
57 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
58 import com.google.gwt.user.client.ui.Label;
59 import com.google.gwt.user.client.ui.RootPanel;
60 import com.google.gwt.user.client.ui.TabPanel;
61 import com.google.gwt.user.client.ui.TreeItem;
62 import com.google.gwt.user.client.ui.VerticalPanel;
63 import com.google.gwt.user.client.ui.Widget;
64
65
66 /**
67  * Entry point classes define <code>onModuleLoad()</code>.
68  */
69 public class GSS implements EntryPoint, ResizeHandler {
70
71         /**
72          * A constant that denotes the completion of an IncrementalCommand.
73          */
74         public static final boolean DONE = false;
75
76         public static final int VISIBLE_FILE_COUNT = 100;
77
78         /**
79          * Instantiate an application-level image bundle. This object will provide
80          * programmatic access to all the images needed by widgets.
81          */
82         private static Images images = (Images) GWT.create(Images.class);
83         private GlassPanel glassPanel = new GlassPanel();
84
85         /**
86          * An aggregate image bundle that pulls together all the images for this
87          * application into a single bundle.
88          */
89         public interface Images extends ClientBundle,TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, GroupMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images,  SearchResults.Images, Search.Images, Groups.Images, Folders.Images {
90
91                 @Source("gr/ebs/gss/resources/document.png")
92                 ImageResource folders();
93
94                 @Source("gr/ebs/gss/resources/edit_group_22.png")
95                 ImageResource groups();
96
97                 @Source("gr/ebs/gss/resources/search.png")
98                 ImageResource search();
99         }
100
101         /**
102          * The single GSS instance.
103          */
104         private static GSS singleton;
105
106         /**
107          * Gets the singleton GSS instance.
108          *
109          * @return the GSS object
110          */
111         public static GSS get() {
112                 if (GSS.singleton == null)
113                         GSS.singleton = new GSS();
114                 return GSS.singleton;
115         }
116
117         /**
118          * The Application Clipboard implementation;
119          */
120         private Clipboard clipboard = new Clipboard();
121
122         private UserResource currentUserResource;
123
124         /**
125          * The top panel that contains the menu bar.
126          */
127         private TopPanel topPanel;
128
129         /**
130          * The panel that contains the various system messages.
131          */
132         private MessagePanel messagePanel = new MessagePanel(GSS.images);
133
134         /**
135          * The bottom panel that contains the status bar.
136          */
137         private StatusPanel statusPanel = new StatusPanel(GSS.images);
138
139         /**
140          * The top right panel that displays the logged in user details
141          */
142         private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
143
144         /**
145          * The file list widget.
146          */
147         private FileList fileList;
148
149         /**
150          * The group list widget.
151          */
152         private Groups groups  = new Groups(images);
153
154         /**
155          * The search result widget.
156          */
157         private SearchResults searchResults;
158
159         /**
160          * The tab panel that occupies the right side of the screen.
161          */
162         private TabPanel inner = new DecoratedTabPanel();
163
164         /**
165          * The split panel that will contain the left and right panels.
166          */
167         private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
168
169         /**
170          * The horizontal panel that will contain the search and status panels.
171          */
172         private DockPanel searchStatus = new DockPanel();
173
174         /**
175          * The search widget.
176          */
177         private Search search;
178
179         /**
180          * The widget that displays the tree of folders.
181          */
182         private Folders folders = new Folders(images);
183
184         /**
185          * The currently selected item in the application, for use by the Edit menu
186          * commands. Potential types are Folder, File, User and Group.
187          */
188         private Object currentSelection;
189
190         /**
191          * The authentication token of the current user.
192          */
193         private String token;
194
195         /**
196          * The WebDAV password of the current user
197          */
198         private String webDAVPassword;
199
200         private PickupDragController dragController;
201
202         public void onModuleLoad() {
203                 // Initialize the singleton before calling the constructors of the
204                 // various widgets that might call GSS.get().
205                 singleton = this;
206                 RootPanel.get().add(glassPanel, 0, 0);
207                 parseUserCredentials();
208                 dragController = new PickupDragController(RootPanel.get(), false) {
209
210                         @Override
211                         public void previewDragStart() throws VetoDragException {
212                             super.previewDragStart();
213                             if (context.selectedWidgets.isEmpty())
214                                         throw new VetoDragException();
215
216                             if(context.draggable != null)
217                                         if(context.draggable instanceof DnDFocusPanel){
218                                                 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
219                                                 //prevent drag and drop for trashed files and for unselected tree items
220                                                 if(toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
221                                                         throw new VetoDragException();
222                                                 else if(toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
223                                                         throw new VetoDragException();
224                                                 else if(toDrop.getItem() != null && !toDrop.getItem().isDraggable())
225                                                         throw new VetoDragException();
226
227                                     }
228                                 else if(context.draggable instanceof DnDSimpleFocusPanel){
229                                         DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
230                                                 //prevent drag and drop for trashed files and for unselected tree items
231                                                 if(toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
232                                                         throw new VetoDragException();
233                                 }
234                           }
235
236                         @Override
237                         protected Widget newDragProxy(DragContext aContext) {
238                                 AbsolutePanel container = new AbsolutePanel();
239                                 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
240                                 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
241                                         HTML html = null;
242                                         Widget widget = (Widget) iterator.next();
243                                         if(widget instanceof DnDFocusPanel){
244                                                 DnDFocusPanel book = (DnDFocusPanel) widget;
245                                                 html = book.cloneHTML();
246                                         }
247                                         else if(widget instanceof DnDSimpleFocusPanel){
248                                                 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
249                                                 html = book.cloneHTML();
250                                         }
251                                         if(html == null)
252                                                 container.add(new Label("Drag ME"));
253                                         else
254                                                 container.add(html);
255                                 }
256                                 return container;
257                         }
258                 };
259                 dragController.setBehaviorDragProxy(true);
260                 dragController.setBehaviorMultipleSelection(false);
261                 topPanel = new TopPanel(GSS.images);
262                 topPanel.setWidth("100%");
263
264                 messagePanel.setWidth("100%");
265                 messagePanel.setVisible(false);
266
267                 search = new Search(images);
268                 searchStatus.add(search, DockPanel.WEST);
269                 searchStatus.add(userDetailsPanel, DockPanel.EAST);
270                 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
271                 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
272                 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
273                 searchStatus.setWidth("100%");
274
275                 fileList = new FileList(images);
276
277                 searchResults = new SearchResults(images);
278
279                 // Inner contains the various lists.
280                 inner.setAnimationEnabled(true);
281                 inner.getTabBar().addStyleName("gss-MainTabBar");
282                 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
283                 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
284
285                 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
286                 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
287                 inner.setWidth("100%");
288                 inner.selectTab(0);
289
290                 inner.addSelectionHandler(new SelectionHandler<Integer>() {
291
292                         @Override
293                         public void onSelection(SelectionEvent<Integer> event) {
294                                 int tabIndex= event.getSelectedItem();
295                                 switch (tabIndex) {
296                                 case 0:
297                                         fileList.clearSelectedRows();
298                                         fileList.updateCurrentlyShowingStats();
299                                         break;
300                                 case 1:
301                                         groups.updateCurrentlyShowingStats();
302                                         break;
303                                 case 2:
304                                         searchResults.clearSelectedRows();
305                                         searchResults.updateCurrentlyShowingStats();
306                                         break;
307                         }
308                         }
309                 });
310
311                 // Add the left and right panels to the split panel.
312                 splitPanel.setLeftWidget(folders);
313                 splitPanel.setRightWidget(inner);
314                 splitPanel.setSplitPosition("25%");
315                 splitPanel.setSize("100%", "100%");
316                 splitPanel.addStyleName("gss-splitPanel");
317
318                 // Create a dock panel that will contain the menu bar at the top,
319                 // the shortcuts to the left, the status bar at the bottom and the
320                 // right panel taking the rest.
321                 VerticalPanel outer = new VerticalPanel();
322                 outer.add(topPanel);
323                 outer.add(searchStatus);
324                 outer.add(messagePanel);
325                 outer.add(splitPanel);
326                 outer.add(statusPanel);
327                 outer.setWidth("100%");
328                 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
329
330                 outer.setSpacing(4);
331
332                 // Hook the window resize event, so that we can adjust the UI.
333                 Window.addResizeHandler(this);
334                 // Clear out the window's built-in margin, because we want to take
335                 // advantage of the entire client area.
336                 Window.setMargin("0px");
337                 // Finally, add the outer panel to the RootPanel, so that it will be
338                 // displayed.
339                 RootPanel.get().add(outer);
340                 // Call the window resized handler to get the initial sizes setup. Doing
341                 // this in a deferred command causes it to occur after all widgets'
342                 // sizes have been computed by the browser.
343                 DeferredCommand.addCommand(new Command() {
344                         public void execute() {
345                                 onWindowResized(Window.getClientHeight());
346                         }
347                 });
348         }
349
350         /**
351          * Fetches the User object for the specified username.
352          *
353          * @param username the username of the user
354          */
355         private void fetchUser(final String username) {
356                 String path = getApiPath() + username + "/";
357                 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null){
358
359                         @Override
360                         public void onComplete() {
361                                 currentUserResource = getResult();
362                                 final String announcement = currentUserResource.getAnnouncement();
363                                 if (announcement != null)
364                                         DeferredCommand.addCommand(new Command() {
365                                                 public void execute() {
366                                                         displayInformation(announcement);
367                                                 }
368                                         });
369                         }
370
371                         @Override
372                         public void onError(Throwable t) {
373                                 GWT.log("Fetching user error", t);
374                                 if(t instanceof RestException)
375                                         GSS.get().displayError("No user found:"+((RestException)t).getHttpStatusText());
376                                 else
377                                         GSS.get().displayError("System error fetching user data:"+t.getMessage());
378                                 authenticateUser();
379                         }
380                 };
381                 DeferredCommand.addCommand(getUserCommand);
382         }
383
384         /**
385          * Parse and store the user credentials to the appropriate fields.
386          */
387         private void parseUserCredentials() {
388                 Configuration conf = (Configuration) GWT.create(Configuration.class);
389                 String cookie = conf.authCookie();
390                 String auth = Cookies.getCookie(cookie);
391                 String domain = Window.Location.getHostName();
392                 String path = Window.Location.getPath();
393                 Cookies.setCookie(cookie, "", null, domain, path, false);
394                 if (auth == null) {
395                         authenticateUser();
396                         // Redundant, but silences warnings about possible auth NPE, below.
397                         return;
398                 }
399                 int sepIndex = auth.indexOf(conf.cookieSeparator());
400                 if (sepIndex == -1)
401                         authenticateUser();
402                 token = auth.substring(sepIndex + 1, auth.length());
403                 final String username = auth.substring(0, sepIndex);
404                 if (username == null)
405                         authenticateUser();
406
407                 refreshWebDAVPassword();
408
409                 DeferredCommand.addCommand(new Command() {
410                         public void execute() {
411                                 fetchUser(username);
412                         }
413                 });
414         }
415
416         /**
417          * Redirect the user to the login page for authentication.
418          */
419         protected void authenticateUser() {
420                 Configuration conf = (Configuration) GWT.create(Configuration.class);
421                 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
422         }
423
424         /**
425          * Redirect the user to the logout page.
426          */
427         void logout() {
428                 Configuration conf = (Configuration) GWT.create(Configuration.class);
429                 Window.Location.assign(conf.logoutUrl());
430         }
431
432         /**
433          * Creates an HTML fragment that places an image & caption together, for use
434          * in a group header.
435          *
436          * @param imageProto an image prototype for an image
437          * @param caption the group caption
438          * @return the header HTML fragment
439          */
440         private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
441                 String captionHTML = "<table class='caption' cellpadding='0' " +
442                                 "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() +
443                                 "</td><td class='rcaption'><b style='white-space:nowrap'>&nbsp;" +
444                                 caption + "</b></td></tr></table>";
445                 return captionHTML;
446         }
447
448
449         private void onWindowResized(int height) {
450                 // Adjust the split panel to take up the available room in the window.
451                 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
452                 if (newHeight < 1)
453                         newHeight = 1;
454                 splitPanel.setHeight("" + newHeight);
455         }
456
457         @Override
458         public void onResize(ResizeEvent event) {
459                 int height = event.getHeight();
460                 onWindowResized(height);
461         }
462
463         public boolean isFileListShowing(){
464                 int tab = inner.getTabBar().getSelectedTab();
465                 if(tab == 0) return true;
466                 return false;
467         }
468
469         public boolean isSearchResultsShowing(){
470                 int tab = inner.getTabBar().getSelectedTab();
471                 if(tab == 2) return true;
472                 return false;
473         }
474
475         /**
476          * Make the user list visible.
477          */
478         public void showUserList() {
479                 inner.selectTab(1);
480         }
481
482         /**
483          * Make the file list visible.
484          */
485         public void showFileList() {
486                 fileList.updateFileCache(false, true /*clear selection*/);
487                 inner.selectTab(0);
488         }
489
490         /**
491          * Make the file list visible.
492          * @param update
493          */
494         public void showFileList(boolean update) {
495                 TreeItem currentFolder = getFolders().getCurrent();
496                 if (currentFolder != null) {
497                         List<FileResource> files = null;
498                         Object cachedObject = currentFolder.getUserObject();
499                         if (cachedObject instanceof FolderResource) {
500                                 FolderResource folder = (FolderResource) cachedObject;
501                                 files = folder.getFiles();
502                         } else if (cachedObject instanceof TrashResource) {
503                                 TrashResource folder = (TrashResource) cachedObject;
504                                 files = folder.getFiles();
505                         }
506                         if (files != null)
507                                 getFileList().setFiles(files);
508                 }
509                 fileList.updateFileCache(update, true /*clear selection*/);
510                 inner.selectTab(0);
511         }
512
513         /**
514          * Make the search results visible.
515          * @param query the search query string
516          */
517         public void showSearchResults(String query) {
518                 searchResults.updateFileCache(query);
519                 searchResults.updateCurrentlyShowingStats();
520                 inner.selectTab(2);
521         }
522
523         /**
524          * Display the 'loading' indicator.
525          */
526         public void showLoadingIndicator() {
527                 topPanel.getLoading().setVisible(true);
528         }
529
530         /**
531          * Hide the 'loading' indicator.
532          */
533         public void hideLoadingIndicator() {
534                 topPanel.getLoading().setVisible(false);
535         }
536
537         /**
538          * A native JavaScript method to reach out to the browser's window and
539          * invoke its resizeTo() method.
540          *
541          * @param x the new width
542          * @param y the new height
543          */
544         public static native void resizeTo(int x, int y) /*-{
545          $wnd.resizeTo(x,y);
546         }-*/;
547
548         /**
549          * A helper method that returns true if the user's list is currently visible
550          * and false if it is hidden.
551          *
552          * @return true if the user list is visible
553          */
554         public boolean isUserListVisible() {
555                 return inner.getTabBar().getSelectedTab() == 1;
556         }
557
558         /**
559          * Display an error message.
560          *
561          * @param msg the message to display
562          */
563         public void displayError(String msg) {
564                 messagePanel.displayError(msg);
565         }
566
567         /**
568          * Display a warning message.
569          *
570          * @param msg the message to display
571          */
572         public void displayWarning(String msg) {
573                 messagePanel.displayWarning(msg);
574         }
575
576         /**
577          * Display an informational message.
578          *
579          * @param msg the message to display
580          */
581         public void displayInformation(String msg) {
582                 messagePanel.displayInformation(msg);
583         }
584
585         /**
586          * Retrieve the folders.
587          *
588          * @return the folders
589          */
590         public Folders getFolders() {
591                 return folders;
592         }
593
594         /**
595          * Retrieve the search.
596          *
597          * @return the search
598          */
599         Search getSearch() {
600                 return search;
601         }
602
603         /**
604          * Retrieve the currentSelection.
605          *
606          * @return the currentSelection
607          */
608         public Object getCurrentSelection() {
609                 return currentSelection;
610         }
611
612         /**
613          * Modify the currentSelection.
614          *
615          * @param newCurrentSelection the currentSelection to set
616          */
617         public void setCurrentSelection(Object newCurrentSelection) {
618                 currentSelection = newCurrentSelection;
619         }
620
621         /**
622          * Retrieve the groups.
623          *
624          * @return the groups
625          */
626         public Groups getGroups() {
627                 return groups;
628         }
629
630         /**
631          * Retrieve the fileList.
632          *
633          * @return the fileList
634          */
635         public FileList getFileList() {
636                 return fileList;
637         }
638
639         public SearchResults getSearchResults(){
640                 return searchResults;
641         }
642
643         /**
644          * Retrieve the topPanel.
645          *
646          * @return the topPanel
647          */
648         TopPanel getTopPanel() {
649                 return topPanel;
650         }
651
652         /**
653          * Retrieve the clipboard.
654          *
655          * @return the clipboard
656          */
657         public Clipboard getClipboard() {
658                 return clipboard;
659         }
660
661
662         public StatusPanel getStatusPanel(){
663                 return statusPanel;
664         }
665
666
667         /**
668          * Retrieve the userDetailsPanel.
669          *
670          * @return the userDetailsPanel
671          */
672         public UserDetailsPanel getUserDetailsPanel() {
673                 return userDetailsPanel;
674         }
675
676         /**
677          * Retrieve the dragController.
678          *
679          * @return the dragController
680          */
681         public PickupDragController getDragController() {
682                 return dragController;
683         }
684
685         public String getToken(){
686                 return token;
687         }
688
689         public String getWebDAVPassword() {
690                 return webDAVPassword;
691         }
692
693         public void removeGlassPanel(){
694                 glassPanel.removeFromParent();
695         }
696
697         /**
698          * Retrieve the currentUserResource.
699          *
700          * @return the currentUserResource
701          */
702         public UserResource getCurrentUserResource() {
703                 return currentUserResource;
704         }
705
706         /**
707          * Modify the currentUserResource.
708          *
709          * @param newUser the new currentUserResource
710          */
711         public void setCurrentUserResource(UserResource newUser) {
712                 currentUserResource = newUser;
713         }
714
715         public static native void preventIESelection() /*-{
716         $doc.body.onselectstart = function () { return false; };
717         }-*/;
718
719         public static native void enableIESelection() /*-{
720                 if ($doc.body.onselectstart != null)
721                         $doc.body.onselectstart = null;
722         }-*/;
723
724         /**
725          * @return the absolute path of the API root URL
726          */
727         public String getApiPath() {
728                 Configuration conf = (Configuration) GWT.create(Configuration.class);
729                 return GWT.getModuleBaseURL() + conf.apiPath();
730         }
731
732         public void refreshWebDAVPassword() {
733                 Configuration conf = (Configuration) GWT.create(Configuration.class);
734                 String domain = Window.Location.getHostName();
735                 String path = Window.Location.getPath();
736                 String cookie = conf.webdavCookie();
737                 webDAVPassword = Cookies.getCookie(cookie);
738                 Cookies.setCookie(cookie, "", null, domain, path, false);
739         }
740
741
742 }