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.HashMap;
32 import java.util.Iterator;
33 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 * A map that stores a set of String URI and the corresponding object
202 * in order history functionality to be implemented.
204 private Map<String, Object> map = new HashMap<String, Object>();
207 * The WebDAV password of the current user
209 private String webDAVPassword;
211 private PickupDragController dragController;
213 public void onModuleLoad() {
214 // Initialize the singleton before calling the constructors of the
215 // various widgets that might call GSS.get().
217 RootPanel.get().add(glassPanel, 0, 0);
218 parseUserCredentials();
219 dragController = new PickupDragController(RootPanel.get(), false) {
222 public void previewDragStart() throws VetoDragException {
223 super.previewDragStart();
224 if (context.selectedWidgets.isEmpty())
225 throw new VetoDragException();
227 if (context.draggable != null)
228 if (context.draggable instanceof DnDFocusPanel) {
229 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
230 // prevent drag and drop for trashed files and for
231 // unselected tree items
232 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
233 throw new VetoDragException();
234 else if (toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
235 throw new VetoDragException();
236 else if (toDrop.getItem() != null && !toDrop.getItem().isDraggable())
237 throw new VetoDragException();
239 } else if (context.draggable instanceof DnDSimpleFocusPanel) {
240 DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
241 // prevent drag and drop for trashed files and for
242 // unselected tree items
243 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
244 throw new VetoDragException();
249 protected Widget newDragProxy(DragContext aContext) {
250 AbsolutePanel container = new AbsolutePanel();
251 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
252 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
254 Widget widget = (Widget) iterator.next();
255 if (widget instanceof DnDFocusPanel) {
256 DnDFocusPanel book = (DnDFocusPanel) widget;
257 html = book.cloneHTML();
258 } else if (widget instanceof DnDSimpleFocusPanel) {
259 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
260 html = book.cloneHTML();
263 container.add(new Label("Drag ME"));
270 dragController.setBehaviorDragProxy(true);
271 dragController.setBehaviorMultipleSelection(false);
272 topPanel = new TopPanel(GSS.images);
273 topPanel.setWidth("100%");
275 messagePanel.setWidth("100%");
276 messagePanel.setVisible(false);
278 search = new Search(images);
279 searchStatus.add(search, DockPanel.WEST);
280 searchStatus.add(userDetailsPanel, DockPanel.EAST);
281 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
282 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
283 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
284 searchStatus.setWidth("100%");
286 fileList = new FileList(images);
288 searchResults = new SearchResults(images);
290 // Inner contains the various lists.
291 inner.setAnimationEnabled(true);
292 inner.getTabBar().addStyleName("gss-MainTabBar");
293 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
294 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
296 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
297 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
298 inner.setWidth("100%");
301 inner.addSelectionHandler(new SelectionHandler<Integer>() {
304 public void onSelection(SelectionEvent<Integer> event) {
305 int tabIndex = event.getSelectedItem();
306 TreeItem treeItem = GSS.get().getFolders().getCurrent();
309 // Files tab selected
310 fileList.clearSelectedRows();
311 fileList.updateCurrentlyShowingStats();
314 // Groups tab selected
315 groups.updateCurrentlyShowingStats();
316 updateHistory("Groups", treeItem);
319 // Search tab selected
320 searchResults.clearSelectedRows();
321 searchResults.updateCurrentlyShowingStats();
322 updateHistory("Search", treeItem);
327 // If the application starts with no history token, redirect to a new "Files" state
328 String initToken = History.getToken();
329 if(initToken.length() == 0)
330 History.newItem("Files");
332 // Add history listener to handle any history events
333 History.addValueChangeHandler(new ValueChangeHandler<String>() {
334 public void onValueChange(ValueChangeEvent<String> event) {
335 String historyToken = event.getValue();
337 if(historyToken.equals("Search"))
339 else if(historyToken.equals("Groups"))
341 else if(historyToken.equals("Files")|| historyToken.length()==0)
344 SelectionEvent.fire(GSS.get().getFolders().getPopupTree(), (TreeItem) getHistoryItem(historyToken));
345 } catch (IndexOutOfBoundsException e) {
351 // Add the left and right panels to the split panel.
352 splitPanel.setLeftWidget(folders);
353 splitPanel.setRightWidget(inner);
354 splitPanel.setSplitPosition("25%");
355 splitPanel.setSize("100%", "100%");
356 splitPanel.addStyleName("gss-splitPanel");
358 // Create a dock panel that will contain the menu bar at the top,
359 // the shortcuts to the left, the status bar at the bottom and the
360 // right panel taking the rest.
361 VerticalPanel outer = new VerticalPanel();
363 outer.add(searchStatus);
364 outer.add(messagePanel);
365 outer.add(splitPanel);
366 outer.add(statusPanel);
367 outer.setWidth("100%");
368 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
372 // Hook the window resize event, so that we can adjust the UI.
373 Window.addResizeHandler(this);
374 // Clear out the window's built-in margin, because we want to take
375 // advantage of the entire client area.
376 Window.setMargin("0px");
377 // Finally, add the outer panel to the RootPanel, so that it will be
379 RootPanel.get().add(outer);
380 // Call the window resized handler to get the initial sizes setup. Doing
381 // this in a deferred command causes it to occur after all widgets'
382 // sizes have been computed by the browser.
383 DeferredCommand.addCommand(new Command() {
385 public void execute() {
386 onWindowResized(Window.getClientHeight());
392 * Fetches the User object for the specified username.
394 * @param username the username of the user
396 private void fetchUser(final String username) {
397 String path = getApiPath() + username + "/";
398 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
401 public void onComplete() {
402 currentUserResource = getResult();
403 final String announcement = currentUserResource.getAnnouncement();
404 if (announcement != null)
405 DeferredCommand.addCommand(new Command() {
407 public void execute() {
408 displayInformation(announcement);
414 public void onError(Throwable t) {
415 GWT.log("Fetching user error", t);
416 if (t instanceof RestException)
417 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
419 GSS.get().displayError("System error fetching user data:" + t.getMessage());
423 DeferredCommand.addCommand(getUserCommand);
427 * Parse and store the user credentials to the appropriate fields.
429 private void parseUserCredentials() {
430 Configuration conf = (Configuration) GWT.create(Configuration.class);
431 String cookie = conf.authCookie();
432 String auth = Cookies.getCookie(cookie);
435 // Redundant, but silences warnings about possible auth NPE, below.
438 int sepIndex = auth.indexOf(conf.cookieSeparator());
441 token = auth.substring(sepIndex + 1);
442 final String username = auth.substring(0, sepIndex);
443 if (username == null)
446 refreshWebDAVPassword();
448 DeferredCommand.addCommand(new Command() {
450 public void execute() {
457 * Redirect the user to the login page for authentication.
459 protected void authenticateUser() {
460 Configuration conf = (Configuration) GWT.create(Configuration.class);
461 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
465 * Clear the cookie and redirect the user to the logout page.
468 Configuration conf = (Configuration) GWT.create(Configuration.class);
469 String cookie = conf.authCookie();
470 String domain = Window.Location.getHostName();
471 String path = Window.Location.getPath();
472 Cookies.setCookie(cookie, "", null, domain, path, false);
473 Window.Location.assign(conf.logoutUrl());
477 * Creates an HTML fragment that places an image & caption together, for use
480 * @param imageProto an image prototype for an image
481 * @param caption the group caption
482 * @return the header HTML fragment
484 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
485 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>";
489 private void onWindowResized(int height) {
490 // Adjust the split panel to take up the available room in the window.
491 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
494 splitPanel.setHeight("" + newHeight);
498 public void onResize(ResizeEvent event) {
499 int height = event.getHeight();
500 onWindowResized(height);
503 public boolean isFileListShowing() {
504 int tab = inner.getTabBar().getSelectedTab();
510 public boolean isSearchResultsShowing() {
511 int tab = inner.getTabBar().getSelectedTab();
518 * Make the user list visible.
520 public void showUserList() {
525 * Make the file list visible.
527 public void showFileList() {
528 fileList.updateFileCache(false, true /*clear selection*/);
533 * Make the file list visible.
537 public void showFileList(boolean update) {
538 TreeItem currentFolder = getFolders().getCurrent();
539 if (currentFolder != null) {
540 List<FileResource> files = null;
541 Object cachedObject = currentFolder.getUserObject();
542 if (cachedObject instanceof FolderResource) {
543 FolderResource folder = (FolderResource) cachedObject;
544 files = folder.getFiles();
545 } else if (cachedObject instanceof TrashResource) {
546 TrashResource folder = (TrashResource) cachedObject;
547 files = folder.getFiles();
550 getFileList().setFiles(files);
552 fileList.updateFileCache(update, true /*clear selection*/);
557 * Make the search results visible.
559 * @param query the search query string
561 public void showSearchResults(String query) {
562 searchResults.updateFileCache(query);
563 searchResults.updateCurrentlyShowingStats();
568 * Display the 'loading' indicator.
570 public void showLoadingIndicator() {
571 topPanel.getLoading().setVisible(true);
575 * Hide the 'loading' indicator.
577 public void hideLoadingIndicator() {
578 topPanel.getLoading().setVisible(false);
582 * A native JavaScript method to reach out to the browser's window and
583 * invoke its resizeTo() method.
585 * @param x the new width
586 * @param y the new height
588 public static native void resizeTo(int x, int y) /*-{
593 * A helper method that returns true if the user's list is currently visible
594 * and false if it is hidden.
596 * @return true if the user list is visible
598 public boolean isUserListVisible() {
599 return inner.getTabBar().getSelectedTab() == 1;
603 * Display an error message.
605 * @param msg the message to display
607 public void displayError(String msg) {
608 messagePanel.displayError(msg);
612 * Display a warning message.
614 * @param msg the message to display
616 public void displayWarning(String msg) {
617 messagePanel.displayWarning(msg);
621 * Display an informational message.
623 * @param msg the message to display
625 public void displayInformation(String msg) {
626 messagePanel.displayInformation(msg);
630 * Retrieve the folders.
632 * @return the folders
634 public Folders getFolders() {
639 * Retrieve the search.
648 * Retrieve the currentSelection.
650 * @return the currentSelection
652 public Object getCurrentSelection() {
653 return currentSelection;
657 * Modify the currentSelection.
659 * @param newCurrentSelection the currentSelection to set
661 public void setCurrentSelection(Object newCurrentSelection) {
662 currentSelection = newCurrentSelection;
666 * Retrieve the groups.
670 public Groups getGroups() {
675 * Retrieve the fileList.
677 * @return the fileList
679 public FileList getFileList() {
683 public SearchResults getSearchResults() {
684 return searchResults;
688 * Retrieve the topPanel.
690 * @return the topPanel
692 TopPanel getTopPanel() {
697 * Retrieve the clipboard.
699 * @return the clipboard
701 public Clipboard getClipboard() {
705 public StatusPanel getStatusPanel() {
710 * Retrieve the userDetailsPanel.
712 * @return the userDetailsPanel
714 public UserDetailsPanel getUserDetailsPanel() {
715 return userDetailsPanel;
719 * Retrieve the dragController.
721 * @return the dragController
723 public PickupDragController getDragController() {
724 return dragController;
727 public String getToken() {
731 public String getWebDAVPassword() {
732 return webDAVPassword;
735 public void removeGlassPanel() {
736 glassPanel.removeFromParent();
740 * Retrieve the currentUserResource.
742 * @return the currentUserResource
744 public UserResource getCurrentUserResource() {
745 return currentUserResource;
749 * Modify the currentUserResource.
751 * @param newUser the new currentUserResource
753 public void setCurrentUserResource(UserResource newUser) {
754 currentUserResource = newUser;
757 public static native void preventIESelection() /*-{
758 $doc.body.onselectstart = function () { return false; };
761 public static native void enableIESelection() /*-{
762 if ($doc.body.onselectstart != null)
763 $doc.body.onselectstart = null;
767 * @return the absolute path of the API root URL
769 public String getApiPath() {
770 Configuration conf = (Configuration) GWT.create(Configuration.class);
771 return GWT.getModuleBaseURL() + conf.apiPath();
774 public void refreshWebDAVPassword() {
775 Configuration conf = (Configuration) GWT.create(Configuration.class);
776 String domain = Window.Location.getHostName();
777 String path = Window.Location.getPath();
778 String cookie = conf.webdavCookie();
779 webDAVPassword = Cookies.getCookie(cookie);
780 Cookies.setCookie(cookie, "", null, domain, path, false);
784 * @return Object of the corresponding String URI which is stored in the history map
786 public Object getHistoryItem(String key){
791 * Replaces any whitespace in the given string to "+"
792 * Sets a pair of key - object in the History (using a map)
793 * and adds a new browser history entry
797 public void updateHistory(String key, Object obj){
798 // Replace any whitespace of the initial string to "+"
799 String result = key.replaceAll("\\s","+");
800 // Add a new pair key - object in the History map.
801 map.put(result, obj);
802 // Add a new browser history entry.
803 History.newItem(result);