2 * Copyright 2007, 2008, 2009, 2010 Electronic Business Systems Ltd.
4 * This file is part of GSS.
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.
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.
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/>.
19 package gr.ebs.gss.client;
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;
31 import java.util.Arrays;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import com.allen_sauer.gwt.dnd.client.DragContext;
37 import com.allen_sauer.gwt.dnd.client.PickupDragController;
38 import com.allen_sauer.gwt.dnd.client.VetoDragException;
39 import com.google.gwt.core.client.EntryPoint;
40 import com.google.gwt.core.client.GWT;
41 import com.google.gwt.event.logical.shared.ResizeEvent;
42 import com.google.gwt.event.logical.shared.ResizeHandler;
43 import com.google.gwt.event.logical.shared.SelectionEvent;
44 import com.google.gwt.event.logical.shared.SelectionHandler;
45 import com.google.gwt.event.logical.shared.ValueChangeEvent;
46 import com.google.gwt.event.logical.shared.ValueChangeHandler;
47 import com.google.gwt.resources.client.ClientBundle;
48 import com.google.gwt.resources.client.ImageResource;
49 import com.google.gwt.user.client.Command;
50 import com.google.gwt.user.client.Cookies;
51 import com.google.gwt.user.client.DOM;
52 import com.google.gwt.user.client.DeferredCommand;
53 import com.google.gwt.user.client.History;
54 import com.google.gwt.user.client.Window;
55 import com.google.gwt.user.client.ui.AbsolutePanel;
56 import com.google.gwt.user.client.ui.AbstractImagePrototype;
57 import com.google.gwt.user.client.ui.DecoratedTabPanel;
58 import com.google.gwt.user.client.ui.DockPanel;
59 import com.google.gwt.user.client.ui.HTML;
60 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
61 import com.google.gwt.user.client.ui.HasVerticalAlignment;
62 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
63 import com.google.gwt.user.client.ui.Label;
64 import com.google.gwt.user.client.ui.RootPanel;
65 import com.google.gwt.user.client.ui.TabPanel;
66 import com.google.gwt.user.client.ui.TreeItem;
67 import com.google.gwt.user.client.ui.VerticalPanel;
68 import com.google.gwt.user.client.ui.Widget;
71 * Entry point classes define <code>onModuleLoad()</code>.
73 public class GSS implements EntryPoint, ResizeHandler {
76 * A constant that denotes the completion of an IncrementalCommand.
78 public static final boolean DONE = false;
80 public static final int VISIBLE_FILE_COUNT = 100;
83 * Instantiate an application-level image bundle. This object will provide
84 * programmatic access to all the images needed by widgets.
86 private static Images images = (Images) GWT.create(Images.class);
88 private GlassPanel glassPanel = new GlassPanel();
91 * An aggregate image bundle that pulls together all the images for this
92 * application into a single bundle.
94 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 {
96 @Source("gr/ebs/gss/resources/document.png")
97 ImageResource folders();
99 @Source("gr/ebs/gss/resources/edit_group_22.png")
100 ImageResource groups();
102 @Source("gr/ebs/gss/resources/search.png")
103 ImageResource search();
107 * The single GSS instance.
109 private static GSS singleton;
112 * Gets the singleton GSS instance.
114 * @return the GSS object
116 public static GSS get() {
117 if (GSS.singleton == null)
118 GSS.singleton = new GSS();
119 return GSS.singleton;
123 * The Application Clipboard implementation;
125 private Clipboard clipboard = new Clipboard();
127 private UserResource currentUserResource;
130 * The top panel that contains the menu bar.
132 private TopPanel topPanel;
135 * The panel that contains the various system messages.
137 private MessagePanel messagePanel = new MessagePanel(GSS.images);
140 * The bottom panel that contains the status bar.
142 private StatusPanel statusPanel = new StatusPanel(GSS.images);
145 * The top right panel that displays the logged in user details
147 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
150 * The file list widget.
152 private FileList fileList;
155 * The group list widget.
157 private Groups groups = new Groups(images);
160 * The search result widget.
162 private SearchResults searchResults;
165 * The tab panel that occupies the right side of the screen.
167 private TabPanel inner = new DecoratedTabPanel();
170 * The split panel that will contain the left and right panels.
172 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
175 * The horizontal panel that will contain the search and status panels.
177 private DockPanel searchStatus = new DockPanel();
182 private Search search;
185 * The widget that displays the tree of folders.
187 private Folders folders = new Folders(images);
190 * The currently selected item in the application, for use by the Edit menu
191 * commands. Potential types are Folder, File, User and Group.
193 private Object currentSelection;
196 * The authentication token of the current user.
198 private String token;
201 * The WebDAV password of the current user
203 private String webDAVPassword;
205 private PickupDragController dragController;
207 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
210 public void onModuleLoad() {
211 // Initialize the singleton before calling the constructors of the
212 // various widgets that might call GSS.get().
214 RootPanel.get().add(glassPanel, 0, 0);
215 parseUserCredentials();
216 dragController = new PickupDragController(RootPanel.get(), false) {
219 public void previewDragStart() throws VetoDragException {
220 super.previewDragStart();
221 if (context.selectedWidgets.isEmpty())
222 throw new VetoDragException();
224 if (context.draggable != null)
225 if (context.draggable instanceof DnDFocusPanel) {
226 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
227 // prevent drag and drop for trashed files and for
228 // unselected tree items
229 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
230 throw new VetoDragException();
231 else if (toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
232 throw new VetoDragException();
233 else if (toDrop.getItem() != null && !toDrop.getItem().isDraggable())
234 throw new VetoDragException();
236 } else if (context.draggable instanceof DnDSimpleFocusPanel) {
237 DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
238 // prevent drag and drop for trashed files and for
239 // unselected tree items
240 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
241 throw new VetoDragException();
246 protected Widget newDragProxy(DragContext aContext) {
247 AbsolutePanel container = new AbsolutePanel();
248 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
249 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
251 Widget widget = (Widget) iterator.next();
252 if (widget instanceof DnDFocusPanel) {
253 DnDFocusPanel book = (DnDFocusPanel) widget;
254 html = book.cloneHTML();
255 } else if (widget instanceof DnDSimpleFocusPanel) {
256 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
257 html = book.cloneHTML();
260 container.add(new Label("Drag ME"));
267 dragController.setBehaviorDragProxy(true);
268 dragController.setBehaviorMultipleSelection(false);
269 topPanel = new TopPanel(GSS.images);
270 topPanel.setWidth("100%");
272 messagePanel.setWidth("100%");
273 messagePanel.setVisible(false);
275 search = new Search(images);
276 searchStatus.add(search, DockPanel.WEST);
277 searchStatus.add(userDetailsPanel, DockPanel.EAST);
278 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
279 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
280 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
281 searchStatus.setWidth("100%");
283 fileList = new FileList(images);
285 searchResults = new SearchResults(images);
287 // Inner contains the various lists.
288 inner.setAnimationEnabled(true);
289 inner.getTabBar().addStyleName("gss-MainTabBar");
290 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
291 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
293 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
294 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
295 inner.setWidth("100%");
298 inner.addSelectionHandler(new SelectionHandler<Integer>() {
301 public void onSelection(SelectionEvent<Integer> event) {
302 int tabIndex = event.getSelectedItem();
303 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
306 // Files tab selected
307 fileList.clearSelectedRows();
308 fileList.updateCurrentlyShowingStats();
311 // Groups tab selected
312 groups.updateCurrentlyShowingStats();
313 updateHistory("Groups");
316 // Search tab selected
317 searchResults.clearSelectedRows();
318 searchResults.updateCurrentlyShowingStats();
319 updateHistory("Search");
324 // If the application starts with no history token, redirect to a new "Files" state
325 String initToken = History.getToken();
326 if(initToken.length() == 0)
327 History.newItem("Files");
328 // Add history listener to handle any history events
329 History.addValueChangeHandler(new ValueChangeHandler<String>() {
331 public void onValueChange(ValueChangeEvent<String> event) {
332 String tokenInput = event.getValue();
333 String historyToken = handleSpecialFolderNames(tokenInput);
335 if(historyToken.equals("Search"))
337 else if(historyToken.equals("Groups"))
339 else if(historyToken.equals("Files")|| historyToken.length()==0)
342 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
343 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
344 SelectionEvent.fire(popupTree, treeObj);
346 } catch (IndexOutOfBoundsException e) {
352 // Add the left and right panels to the split panel.
353 splitPanel.setLeftWidget(folders);
354 splitPanel.setRightWidget(inner);
355 splitPanel.setSplitPosition("25%");
356 splitPanel.setSize("100%", "100%");
357 splitPanel.addStyleName("gss-splitPanel");
359 // Create a dock panel that will contain the menu bar at the top,
360 // the shortcuts to the left, the status bar at the bottom and the
361 // right panel taking the rest.
362 VerticalPanel outer = new VerticalPanel();
364 outer.add(searchStatus);
365 outer.add(messagePanel);
366 outer.add(splitPanel);
367 outer.add(statusPanel);
368 outer.setWidth("100%");
369 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
373 // Hook the window resize event, so that we can adjust the UI.
374 Window.addResizeHandler(this);
375 // Clear out the window's built-in margin, because we want to take
376 // advantage of the entire client area.
377 Window.setMargin("0px");
378 // Finally, add the outer panel to the RootPanel, so that it will be
380 RootPanel.get().add(outer);
381 // Call the window resized handler to get the initial sizes setup. Doing
382 // this in a deferred command causes it to occur after all widgets'
383 // sizes have been computed by the browser.
384 DeferredCommand.addCommand(new Command() {
387 public void execute() {
388 onWindowResized(Window.getClientHeight());
394 * Fetches the User object for the specified username.
396 * @param username the username of the user
398 private void fetchUser(final String username) {
399 String path = getApiPath() + username + "/";
400 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
403 public void onComplete() {
404 currentUserResource = getResult();
405 final String announcement = currentUserResource.getAnnouncement();
406 if (announcement != null)
407 DeferredCommand.addCommand(new Command() {
410 public void execute() {
411 displayInformation(announcement);
417 public void onError(Throwable t) {
418 GWT.log("Fetching user error", t);
419 if (t instanceof RestException)
420 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
422 GSS.get().displayError("System error fetching user data:" + t.getMessage());
426 DeferredCommand.addCommand(getUserCommand);
430 * Parse and store the user credentials to the appropriate fields.
432 private void parseUserCredentials() {
433 Configuration conf = (Configuration) GWT.create(Configuration.class);
434 String cookie = conf.authCookie();
435 String auth = Cookies.getCookie(cookie);
438 // Redundant, but silences warnings about possible auth NPE, below.
441 int sepIndex = auth.indexOf(conf.cookieSeparator());
444 token = auth.substring(sepIndex + 1);
445 final String username = auth.substring(0, sepIndex);
446 if (username == null)
449 refreshWebDAVPassword();
451 DeferredCommand.addCommand(new Command() {
454 public void execute() {
461 * Redirect the user to the login page for authentication.
463 protected void authenticateUser() {
464 Configuration conf = (Configuration) GWT.create(Configuration.class);
465 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
469 * Clear the cookie and redirect the user to the logout page.
472 Configuration conf = (Configuration) GWT.create(Configuration.class);
473 String cookie = conf.authCookie();
474 String domain = Window.Location.getHostName();
475 String path = Window.Location.getPath();
476 Cookies.setCookie(cookie, "", null, domain, path, false);
477 Window.Location.assign(conf.logoutUrl());
481 * Creates an HTML fragment that places an image & caption together, for use
484 * @param imageProto an image prototype for an image
485 * @param caption the group caption
486 * @return the header HTML fragment
488 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
489 String captionHTML = "<table class='caption' cellpadding='0' " + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() + "</td><td class='rcaption'><b style='white-space:nowrap'> " + caption + "</b></td></tr></table>";
493 private void onWindowResized(int height) {
494 // Adjust the split panel to take up the available room in the window.
495 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
498 splitPanel.setHeight("" + newHeight);
502 public void onResize(ResizeEvent event) {
503 int height = event.getHeight();
504 onWindowResized(height);
507 public boolean isFileListShowing() {
508 int tab = inner.getTabBar().getSelectedTab();
514 public boolean isSearchResultsShowing() {
515 int tab = inner.getTabBar().getSelectedTab();
522 * Make the user list visible.
524 public void showUserList() {
529 * Make the file list visible.
531 public void showFileList() {
532 fileList.updateFileCache(false, true /*clear selection*/);
537 * Make the file list visible.
541 public void showFileList(boolean update) {
542 TreeItem currentFolder = getFolders().getCurrent();
543 if (currentFolder != null) {
544 List<FileResource> files = null;
545 Object cachedObject = currentFolder.getUserObject();
546 if (cachedObject instanceof FolderResource) {
547 FolderResource folder = (FolderResource) cachedObject;
548 files = folder.getFiles();
549 } else if (cachedObject instanceof TrashResource) {
550 TrashResource folder = (TrashResource) cachedObject;
551 files = folder.getFiles();
554 getFileList().setFiles(files);
556 fileList.updateFileCache(update, true /*clear selection*/);
561 * Make the search results visible.
563 * @param query the search query string
565 public void showSearchResults(String query) {
566 searchResults.updateFileCache(query);
567 searchResults.updateCurrentlyShowingStats();
572 * Display the 'loading' indicator.
574 public void showLoadingIndicator() {
575 topPanel.getLoading().setVisible(true);
579 * Hide the 'loading' indicator.
581 public void hideLoadingIndicator() {
582 topPanel.getLoading().setVisible(false);
586 * A native JavaScript method to reach out to the browser's window and
587 * invoke its resizeTo() method.
589 * @param x the new width
590 * @param y the new height
592 public static native void resizeTo(int x, int y) /*-{
597 * A helper method that returns true if the user's list is currently visible
598 * and false if it is hidden.
600 * @return true if the user list is visible
602 public boolean isUserListVisible() {
603 return inner.getTabBar().getSelectedTab() == 1;
607 * Display an error message.
609 * @param msg the message to display
611 public void displayError(String msg) {
612 messagePanel.displayError(msg);
616 * Display a warning message.
618 * @param msg the message to display
620 public void displayWarning(String msg) {
621 messagePanel.displayWarning(msg);
625 * Display an informational message.
627 * @param msg the message to display
629 public void displayInformation(String msg) {
630 messagePanel.displayInformation(msg);
634 * Retrieve the folders.
636 * @return the folders
638 public Folders getFolders() {
643 * Retrieve the search.
652 * Retrieve the currentSelection.
654 * @return the currentSelection
656 public Object getCurrentSelection() {
657 return currentSelection;
661 * Modify the currentSelection.
663 * @param newCurrentSelection the currentSelection to set
665 public void setCurrentSelection(Object newCurrentSelection) {
666 currentSelection = newCurrentSelection;
670 * Retrieve the groups.
674 public Groups getGroups() {
679 * Retrieve the fileList.
681 * @return the fileList
683 public FileList getFileList() {
687 public SearchResults getSearchResults() {
688 return searchResults;
692 * Retrieve the topPanel.
694 * @return the topPanel
696 TopPanel getTopPanel() {
701 * Retrieve the clipboard.
703 * @return the clipboard
705 public Clipboard getClipboard() {
709 public StatusPanel getStatusPanel() {
714 * Retrieve the userDetailsPanel.
716 * @return the userDetailsPanel
718 public UserDetailsPanel getUserDetailsPanel() {
719 return userDetailsPanel;
723 * Retrieve the dragController.
725 * @return the dragController
727 public PickupDragController getDragController() {
728 return dragController;
731 public String getToken() {
735 public String getWebDAVPassword() {
736 return webDAVPassword;
739 public void removeGlassPanel() {
740 glassPanel.removeFromParent();
744 * Retrieve the currentUserResource.
746 * @return the currentUserResource
748 public UserResource getCurrentUserResource() {
749 return currentUserResource;
753 * Modify the currentUserResource.
755 * @param newUser the new currentUserResource
757 public void setCurrentUserResource(UserResource newUser) {
758 currentUserResource = newUser;
761 public static native void preventIESelection() /*-{
762 $doc.body.onselectstart = function () { return false; };
765 public static native void enableIESelection() /*-{
766 if ($doc.body.onselectstart != null)
767 $doc.body.onselectstart = null;
771 * @return the absolute path of the API root URL
773 public String getApiPath() {
774 Configuration conf = (Configuration) GWT.create(Configuration.class);
775 return GWT.getModuleBaseURL() + conf.apiPath();
778 public void refreshWebDAVPassword() {
779 Configuration conf = (Configuration) GWT.create(Configuration.class);
780 String domain = Window.Location.getHostName();
781 String path = Window.Location.getPath();
782 String cookie = conf.webdavCookie();
783 webDAVPassword = Cookies.getCookie(cookie);
784 Cookies.setCookie(cookie, "", null, domain, path, false);
788 * History support for folder navigation
789 * adds a new browser history entry
793 public void updateHistory(String key){
794 // Replace any whitespace of the initial string to "+"
795 // String result = key.replaceAll("\\s","+");
796 // Add a new browser history entry.
797 // History.newItem(result);
798 History.newItem(key);
802 * This method examines the token input and add a "/" at the end in case it's omitted.
803 * This happens only in Files/trash/, Files/shared/, Files/others.
806 * @return the formated token with a "/" at the end or the same tokenInput parameter
809 private String handleSpecialFolderNames(String tokenInput){
810 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
811 if(pathsToCheck.contains(tokenInput))
812 return tokenInput + "/";
818 * Reject illegal resource names, like '.' or '..'.
820 static boolean isValidResourceName(String name) {
821 if (".".equals(name) || "..".equals(name))
826 public void putUserToMap(String _userName, String _userFullName){
827 userFullNameMap.put(_userName, _userFullName);
830 public String findUserFullName(String _userName){
831 return userFullNameMap.get(_userName);
834 public boolean hasUserFullName(String _userName) {
835 String userFullNameFromMap = GSS.get().findUserFullName(_userName);
836 if (userFullNameFromMap == null)