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.commands.GetUserCommand;
23 import gr.ebs.gss.client.dnd.DnDFocusPanel;
24 import gr.ebs.gss.client.dnd.DnDSimpleFocusPanel;
25 import gr.ebs.gss.client.rest.GetCommand;
26 import gr.ebs.gss.client.rest.RestException;
27 import gr.ebs.gss.client.rest.resource.FileResource;
28 import gr.ebs.gss.client.rest.resource.FolderResource;
29 import gr.ebs.gss.client.rest.resource.TrashResource;
30 import gr.ebs.gss.client.rest.resource.UserResource;
32 import java.util.Arrays;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
37 import com.allen_sauer.gwt.dnd.client.DragContext;
38 import com.allen_sauer.gwt.dnd.client.PickupDragController;
39 import com.allen_sauer.gwt.dnd.client.VetoDragException;
40 import com.google.gwt.core.client.EntryPoint;
41 import com.google.gwt.core.client.GWT;
42 import com.google.gwt.event.logical.shared.ResizeEvent;
43 import com.google.gwt.event.logical.shared.ResizeHandler;
44 import com.google.gwt.event.logical.shared.SelectionEvent;
45 import com.google.gwt.event.logical.shared.SelectionHandler;
46 import com.google.gwt.event.logical.shared.ValueChangeEvent;
47 import com.google.gwt.event.logical.shared.ValueChangeHandler;
48 import com.google.gwt.resources.client.ClientBundle;
49 import com.google.gwt.resources.client.ImageResource;
50 import com.google.gwt.user.client.Command;
51 import com.google.gwt.user.client.Cookies;
52 import com.google.gwt.user.client.DOM;
53 import com.google.gwt.user.client.DeferredCommand;
54 import com.google.gwt.user.client.History;
55 import com.google.gwt.user.client.Window;
56 import com.google.gwt.user.client.ui.AbsolutePanel;
57 import com.google.gwt.user.client.ui.AbstractImagePrototype;
58 import com.google.gwt.user.client.ui.DecoratedTabPanel;
59 import com.google.gwt.user.client.ui.DockPanel;
60 import com.google.gwt.user.client.ui.HTML;
61 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
62 import com.google.gwt.user.client.ui.HasVerticalAlignment;
63 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
64 import com.google.gwt.user.client.ui.Label;
65 import com.google.gwt.user.client.ui.RootPanel;
66 import com.google.gwt.user.client.ui.TabPanel;
67 import com.google.gwt.user.client.ui.TreeItem;
68 import com.google.gwt.user.client.ui.VerticalPanel;
69 import com.google.gwt.user.client.ui.Widget;
72 * Entry point classes define <code>onModuleLoad()</code>.
74 public class GSS implements EntryPoint, ResizeHandler {
77 * A constant that denotes the completion of an IncrementalCommand.
79 public static final boolean DONE = false;
81 public static final int VISIBLE_FILE_COUNT = 100;
84 * Instantiate an application-level image bundle. This object will provide
85 * programmatic access to all the images needed by widgets.
87 private static Images images = (Images) GWT.create(Images.class);
89 private GlassPanel glassPanel = new GlassPanel();
92 * An aggregate image bundle that pulls together all the images for this
93 * application into a single bundle.
95 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 {
97 @Source("gr/ebs/gss/resources/document.png")
98 ImageResource folders();
100 @Source("gr/ebs/gss/resources/edit_group_22.png")
101 ImageResource groups();
103 @Source("gr/ebs/gss/resources/search.png")
104 ImageResource search();
108 * The single GSS instance.
110 private static GSS singleton;
113 * Gets the singleton GSS instance.
115 * @return the GSS object
117 public static GSS get() {
118 if (GSS.singleton == null)
119 GSS.singleton = new GSS();
120 return GSS.singleton;
124 * The Application Clipboard implementation;
126 private Clipboard clipboard = new Clipboard();
128 private UserResource currentUserResource;
131 * The top panel that contains the menu bar.
133 private TopPanel topPanel;
136 * The panel that contains the various system messages.
138 private MessagePanel messagePanel = new MessagePanel(GSS.images);
141 * The bottom panel that contains the status bar.
143 private StatusPanel statusPanel = new StatusPanel(GSS.images);
146 * The top right panel that displays the logged in user details
148 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
151 * The file list widget.
153 private FileList fileList;
156 * The group list widget.
158 private Groups groups = new Groups(images);
161 * The search result widget.
163 private SearchResults searchResults;
166 * The tab panel that occupies the right side of the screen.
168 private TabPanel inner = new DecoratedTabPanel();
171 * The split panel that will contain the left and right panels.
173 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
176 * The horizontal panel that will contain the search and status panels.
178 private DockPanel searchStatus = new DockPanel();
183 private Search search;
186 * The widget that displays the tree of folders.
188 private Folders folders = new Folders(images);
191 * The currently selected item in the application, for use by the Edit menu
192 * commands. Potential types are Folder, File, User and Group.
194 private Object currentSelection;
197 * The authentication token of the current user.
199 private String token;
202 * The WebDAV password of the current user
204 private String webDAVPassword;
206 private PickupDragController dragController;
208 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
211 public void onModuleLoad() {
212 // Initialize the singleton before calling the constructors of the
213 // various widgets that might call GSS.get().
215 RootPanel.get().add(glassPanel, 0, 0);
216 parseUserCredentials();
217 dragController = new PickupDragController(RootPanel.get(), false) {
220 public void previewDragStart() throws VetoDragException {
221 super.previewDragStart();
222 if (context.selectedWidgets.isEmpty())
223 throw new VetoDragException();
225 if (context.draggable != null)
226 if (context.draggable instanceof DnDFocusPanel) {
227 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
228 // prevent drag and drop for trashed files and for
229 // unselected tree items
230 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
231 throw new VetoDragException();
232 else if (toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
233 throw new VetoDragException();
234 else if (toDrop.getItem() != null && !toDrop.getItem().isDraggable())
235 throw new VetoDragException();
237 } else if (context.draggable instanceof DnDSimpleFocusPanel) {
238 DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
239 // prevent drag and drop for trashed files and for
240 // unselected tree items
241 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
242 throw new VetoDragException();
247 protected Widget newDragProxy(DragContext aContext) {
248 AbsolutePanel container = new AbsolutePanel();
249 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
250 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
252 Widget widget = (Widget) iterator.next();
253 if (widget instanceof DnDFocusPanel) {
254 DnDFocusPanel book = (DnDFocusPanel) widget;
255 html = book.cloneHTML();
256 } else if (widget instanceof DnDSimpleFocusPanel) {
257 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
258 html = book.cloneHTML();
261 container.add(new Label("Drag ME"));
268 dragController.setBehaviorDragProxy(true);
269 dragController.setBehaviorMultipleSelection(false);
270 topPanel = new TopPanel(GSS.images);
271 topPanel.setWidth("100%");
273 messagePanel.setWidth("100%");
274 messagePanel.setVisible(false);
276 search = new Search(images);
277 searchStatus.add(search, DockPanel.WEST);
278 searchStatus.add(userDetailsPanel, DockPanel.EAST);
279 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
280 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
281 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
282 searchStatus.setWidth("100%");
284 fileList = new FileList(images);
286 searchResults = new SearchResults(images);
288 // Inner contains the various lists.
289 inner.setAnimationEnabled(true);
290 inner.getTabBar().addStyleName("gss-MainTabBar");
291 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
292 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
294 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
295 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
296 inner.setWidth("100%");
299 inner.addSelectionHandler(new SelectionHandler<Integer>() {
302 public void onSelection(SelectionEvent<Integer> event) {
303 int tabIndex = event.getSelectedItem();
304 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
307 // Files tab selected
308 fileList.clearSelectedRows();
309 fileList.updateCurrentlyShowingStats();
312 // Groups tab selected
313 groups.updateCurrentlyShowingStats();
314 updateHistory("Groups");
317 // Search tab selected
318 searchResults.clearSelectedRows();
319 searchResults.updateCurrentlyShowingStats();
320 updateHistory("Search");
325 // If the application starts with no history token, redirect to a new "Files" state
326 String initToken = History.getToken();
327 if(initToken.length() == 0)
328 History.newItem("Files");
329 // Add history listener to handle any history events
330 History.addValueChangeHandler(new ValueChangeHandler<String>() {
332 public void onValueChange(ValueChangeEvent<String> event) {
333 String tokenInput = event.getValue();
334 String historyToken = handleSpecialFolderNames(tokenInput);
336 if(historyToken.equals("Search"))
338 else if(historyToken.equals("Groups"))
340 else if(historyToken.equals("Files")|| historyToken.length()==0)
343 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
344 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
345 SelectionEvent.fire(popupTree, treeObj);
347 } catch (IndexOutOfBoundsException e) {
353 // Add the left and right panels to the split panel.
354 splitPanel.setLeftWidget(folders);
355 splitPanel.setRightWidget(inner);
356 splitPanel.setSplitPosition("25%");
357 splitPanel.setSize("100%", "100%");
358 splitPanel.addStyleName("gss-splitPanel");
360 // Create a dock panel that will contain the menu bar at the top,
361 // the shortcuts to the left, the status bar at the bottom and the
362 // right panel taking the rest.
363 VerticalPanel outer = new VerticalPanel();
365 outer.add(searchStatus);
366 outer.add(messagePanel);
367 outer.add(splitPanel);
368 outer.add(statusPanel);
369 outer.setWidth("100%");
370 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
374 // Hook the window resize event, so that we can adjust the UI.
375 Window.addResizeHandler(this);
376 // Clear out the window's built-in margin, because we want to take
377 // advantage of the entire client area.
378 Window.setMargin("0px");
379 // Finally, add the outer panel to the RootPanel, so that it will be
381 RootPanel.get().add(outer);
382 // Call the window resized handler to get the initial sizes setup. Doing
383 // this in a deferred command causes it to occur after all widgets'
384 // sizes have been computed by the browser.
385 DeferredCommand.addCommand(new Command() {
388 public void execute() {
389 onWindowResized(Window.getClientHeight());
395 * Fetches the User object for the specified username.
397 * @param username the username of the user
399 private void fetchUser(final String username) {
400 String path = getApiPath() + username + "/";
401 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
404 public void onComplete() {
405 currentUserResource = getResult();
406 final String announcement = currentUserResource.getAnnouncement();
407 if (announcement != null)
408 DeferredCommand.addCommand(new Command() {
411 public void execute() {
412 displayInformation(announcement);
418 public void onError(Throwable t) {
419 GWT.log("Fetching user error", t);
420 if (t instanceof RestException)
421 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
423 GSS.get().displayError("System error fetching user data:" + t.getMessage());
427 DeferredCommand.addCommand(getUserCommand);
431 * Parse and store the user credentials to the appropriate fields.
433 private void parseUserCredentials() {
434 Configuration conf = (Configuration) GWT.create(Configuration.class);
435 String cookie = conf.authCookie();
436 String auth = Cookies.getCookie(cookie);
439 // Redundant, but silences warnings about possible auth NPE, below.
442 int sepIndex = auth.indexOf(conf.cookieSeparator());
445 token = auth.substring(sepIndex + 1);
446 final String username = auth.substring(0, sepIndex);
447 if (username == null)
450 refreshWebDAVPassword();
452 DeferredCommand.addCommand(new Command() {
455 public void execute() {
462 * Redirect the user to the login page for authentication.
464 protected void authenticateUser() {
465 Configuration conf = (Configuration) GWT.create(Configuration.class);
466 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
470 * Clear the cookie and redirect the user to the logout page.
473 Configuration conf = (Configuration) GWT.create(Configuration.class);
474 String cookie = conf.authCookie();
475 String domain = Window.Location.getHostName();
476 String path = Window.Location.getPath();
477 Cookies.setCookie(cookie, "", null, domain, path, false);
478 Window.Location.assign(conf.logoutUrl());
482 * Creates an HTML fragment that places an image & caption together, for use
485 * @param imageProto an image prototype for an image
486 * @param caption the group caption
487 * @return the header HTML fragment
489 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
490 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>";
494 private void onWindowResized(int height) {
495 // Adjust the split panel to take up the available room in the window.
496 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
499 splitPanel.setHeight("" + newHeight);
503 public void onResize(ResizeEvent event) {
504 int height = event.getHeight();
505 onWindowResized(height);
508 public boolean isFileListShowing() {
509 int tab = inner.getTabBar().getSelectedTab();
515 public boolean isSearchResultsShowing() {
516 int tab = inner.getTabBar().getSelectedTab();
523 * Make the user list visible.
525 public void showUserList() {
530 * Make the file list visible.
532 public void showFileList() {
533 fileList.updateFileCache(false, true /*clear selection*/);
538 * Make the file list visible.
542 public void showFileList(boolean update) {
543 TreeItem currentFolder = getFolders().getCurrent();
544 if (currentFolder != null) {
545 List<FileResource> files = null;
546 Object cachedObject = currentFolder.getUserObject();
547 if (cachedObject instanceof FolderResource) {
548 FolderResource folder = (FolderResource) cachedObject;
549 files = folder.getFiles();
550 } else if (cachedObject instanceof TrashResource) {
551 TrashResource folder = (TrashResource) cachedObject;
552 files = folder.getFiles();
555 getFileList().setFiles(files);
557 fileList.updateFileCache(update, true /*clear selection*/);
562 * Make the search results visible.
564 * @param query the search query string
566 public void showSearchResults(String query) {
567 searchResults.updateFileCache(query);
568 searchResults.updateCurrentlyShowingStats();
573 * Display the 'loading' indicator.
575 public void showLoadingIndicator() {
576 topPanel.getLoading().setVisible(true);
580 * Hide the 'loading' indicator.
582 public void hideLoadingIndicator() {
583 topPanel.getLoading().setVisible(false);
587 * A native JavaScript method to reach out to the browser's window and
588 * invoke its resizeTo() method.
590 * @param x the new width
591 * @param y the new height
593 public static native void resizeTo(int x, int y) /*-{
598 * A helper method that returns true if the user's list is currently visible
599 * and false if it is hidden.
601 * @return true if the user list is visible
603 public boolean isUserListVisible() {
604 return inner.getTabBar().getSelectedTab() == 1;
608 * Display an error message.
610 * @param msg the message to display
612 public void displayError(String msg) {
613 messagePanel.displayError(msg);
617 * Display a warning message.
619 * @param msg the message to display
621 public void displayWarning(String msg) {
622 messagePanel.displayWarning(msg);
626 * Display an informational message.
628 * @param msg the message to display
630 public void displayInformation(String msg) {
631 messagePanel.displayInformation(msg);
635 * Retrieve the folders.
637 * @return the folders
639 public Folders getFolders() {
644 * Retrieve the search.
653 * Retrieve the currentSelection.
655 * @return the currentSelection
657 public Object getCurrentSelection() {
658 return currentSelection;
662 * Modify the currentSelection.
664 * @param newCurrentSelection the currentSelection to set
666 public void setCurrentSelection(Object newCurrentSelection) {
667 currentSelection = newCurrentSelection;
671 * Retrieve the groups.
675 public Groups getGroups() {
680 * Retrieve the fileList.
682 * @return the fileList
684 public FileList getFileList() {
688 public SearchResults getSearchResults() {
689 return searchResults;
693 * Retrieve the topPanel.
695 * @return the topPanel
697 TopPanel getTopPanel() {
702 * Retrieve the clipboard.
704 * @return the clipboard
706 public Clipboard getClipboard() {
710 public StatusPanel getStatusPanel() {
715 * Retrieve the userDetailsPanel.
717 * @return the userDetailsPanel
719 public UserDetailsPanel getUserDetailsPanel() {
720 return userDetailsPanel;
724 * Retrieve the dragController.
726 * @return the dragController
728 public PickupDragController getDragController() {
729 return dragController;
732 public String getToken() {
736 public String getWebDAVPassword() {
737 return webDAVPassword;
740 public void removeGlassPanel() {
741 glassPanel.removeFromParent();
745 * Retrieve the currentUserResource.
747 * @return the currentUserResource
749 public UserResource getCurrentUserResource() {
750 return currentUserResource;
754 * Modify the currentUserResource.
756 * @param newUser the new currentUserResource
758 public void setCurrentUserResource(UserResource newUser) {
759 currentUserResource = newUser;
762 public static native void preventIESelection() /*-{
763 $doc.body.onselectstart = function () { return false; };
766 public static native void enableIESelection() /*-{
767 if ($doc.body.onselectstart != null)
768 $doc.body.onselectstart = null;
772 * @return the absolute path of the API root URL
774 public String getApiPath() {
775 Configuration conf = (Configuration) GWT.create(Configuration.class);
776 return GWT.getModuleBaseURL() + conf.apiPath();
779 public void refreshWebDAVPassword() {
780 Configuration conf = (Configuration) GWT.create(Configuration.class);
781 String domain = Window.Location.getHostName();
782 String path = Window.Location.getPath();
783 String cookie = conf.webdavCookie();
784 webDAVPassword = Cookies.getCookie(cookie);
785 Cookies.setCookie(cookie, "", null, domain, path, false);
789 * History support for folder navigation
790 * adds a new browser history entry
794 public void updateHistory(String key){
795 // Replace any whitespace of the initial string to "+"
796 // String result = key.replaceAll("\\s","+");
797 // Add a new browser history entry.
798 // History.newItem(result);
799 History.newItem(key);
803 * This method examines the token input and add a "/" at the end in case it's omitted.
804 * This happens only in Files/trash/, Files/shared/, Files/others.
807 * @return the formated token with a "/" at the end or the same tokenInput parameter
810 private String handleSpecialFolderNames(String tokenInput){
811 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
812 if(pathsToCheck.contains(tokenInput))
813 return tokenInput + "/";
819 * Reject illegal resource names, like '.' or '..' or slashes '/'.
821 static boolean isValidResourceName(String name) {
822 if (".".equals(name) || "..".equals(name) || name.contains("/"))
827 public void putUserToMap(String _userName, String _userFullName){
828 userFullNameMap.put(_userName, _userFullName);
831 public String findUserFullName(String _userName){
832 return userFullNameMap.get(_userName);
835 public String getUserFullName(String _userName) {
836 if (GSS.get().findUserFullName(_userName) == null)
837 //if there is no userFullName found then the map fills with the given _userName,
838 //so userFullName = _userName
839 GSS.get().putUserToMap(_userName, _userName);
840 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
841 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
842 GetUserCommand guc = new GetUserCommand(_userName);
845 return GSS.get().findUserFullName(_userName);