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.Iterator;
33 import java.util.List;
35 import com.allen_sauer.gwt.dnd.client.DragContext;
36 import com.allen_sauer.gwt.dnd.client.PickupDragController;
37 import com.allen_sauer.gwt.dnd.client.VetoDragException;
38 import com.google.gwt.core.client.EntryPoint;
39 import com.google.gwt.core.client.GWT;
40 import com.google.gwt.event.logical.shared.ResizeEvent;
41 import com.google.gwt.event.logical.shared.ResizeHandler;
42 import com.google.gwt.event.logical.shared.SelectionEvent;
43 import com.google.gwt.event.logical.shared.SelectionHandler;
44 import com.google.gwt.event.logical.shared.ValueChangeEvent;
45 import com.google.gwt.event.logical.shared.ValueChangeHandler;
46 import com.google.gwt.resources.client.ClientBundle;
47 import com.google.gwt.resources.client.ImageResource;
48 import com.google.gwt.user.client.Command;
49 import com.google.gwt.user.client.Cookies;
50 import com.google.gwt.user.client.DOM;
51 import com.google.gwt.user.client.DeferredCommand;
52 import com.google.gwt.user.client.History;
53 import com.google.gwt.user.client.Window;
54 import com.google.gwt.user.client.ui.AbsolutePanel;
55 import com.google.gwt.user.client.ui.AbstractImagePrototype;
56 import com.google.gwt.user.client.ui.DecoratedTabPanel;
57 import com.google.gwt.user.client.ui.DockPanel;
58 import com.google.gwt.user.client.ui.HTML;
59 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
60 import com.google.gwt.user.client.ui.HasVerticalAlignment;
61 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
62 import com.google.gwt.user.client.ui.Label;
63 import com.google.gwt.user.client.ui.RootPanel;
64 import com.google.gwt.user.client.ui.TabPanel;
65 import com.google.gwt.user.client.ui.TreeItem;
66 import com.google.gwt.user.client.ui.VerticalPanel;
67 import com.google.gwt.user.client.ui.Widget;
70 * Entry point classes define <code>onModuleLoad()</code>.
72 public class GSS implements EntryPoint, ResizeHandler {
75 * A constant that denotes the completion of an IncrementalCommand.
77 public static final boolean DONE = false;
79 public static final int VISIBLE_FILE_COUNT = 100;
82 * Instantiate an application-level image bundle. This object will provide
83 * programmatic access to all the images needed by widgets.
85 private static Images images = (Images) GWT.create(Images.class);
87 private GlassPanel glassPanel = new GlassPanel();
90 * An aggregate image bundle that pulls together all the images for this
91 * application into a single bundle.
93 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 {
95 @Source("gr/ebs/gss/resources/document.png")
96 ImageResource folders();
98 @Source("gr/ebs/gss/resources/edit_group_22.png")
99 ImageResource groups();
101 @Source("gr/ebs/gss/resources/search.png")
102 ImageResource search();
106 * The single GSS instance.
108 private static GSS singleton;
111 * Gets the singleton GSS instance.
113 * @return the GSS object
115 public static GSS get() {
116 if (GSS.singleton == null)
117 GSS.singleton = new GSS();
118 return GSS.singleton;
122 * The Application Clipboard implementation;
124 private Clipboard clipboard = new Clipboard();
126 private UserResource currentUserResource;
129 * The top panel that contains the menu bar.
131 private TopPanel topPanel;
134 * The panel that contains the various system messages.
136 private MessagePanel messagePanel = new MessagePanel(GSS.images);
139 * The bottom panel that contains the status bar.
141 private StatusPanel statusPanel = new StatusPanel(GSS.images);
144 * The top right panel that displays the logged in user details
146 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
149 * The file list widget.
151 private FileList fileList;
154 * The group list widget.
156 private Groups groups = new Groups(images);
159 * The search result widget.
161 private SearchResults searchResults;
164 * The tab panel that occupies the right side of the screen.
166 private TabPanel inner = new DecoratedTabPanel();
169 * The split panel that will contain the left and right panels.
171 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
174 * The horizontal panel that will contain the search and status panels.
176 private DockPanel searchStatus = new DockPanel();
181 private Search search;
184 * The widget that displays the tree of folders.
186 private Folders folders = new Folders(images);
189 * The currently selected item in the application, for use by the Edit menu
190 * commands. Potential types are Folder, File, User and Group.
192 private Object currentSelection;
195 * The authentication token of the current user.
197 private String token;
200 * The WebDAV password of the current user
202 private String webDAVPassword;
204 private PickupDragController dragController;
206 public void onModuleLoad() {
207 // Initialize the singleton before calling the constructors of the
208 // various widgets that might call GSS.get().
210 RootPanel.get().add(glassPanel, 0, 0);
211 parseUserCredentials();
212 dragController = new PickupDragController(RootPanel.get(), false) {
215 public void previewDragStart() throws VetoDragException {
216 super.previewDragStart();
217 if (context.selectedWidgets.isEmpty())
218 throw new VetoDragException();
220 if (context.draggable != null)
221 if (context.draggable instanceof DnDFocusPanel) {
222 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
223 // prevent drag and drop for trashed files and for
224 // unselected tree items
225 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
226 throw new VetoDragException();
227 else if (toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
228 throw new VetoDragException();
229 else if (toDrop.getItem() != null && !toDrop.getItem().isDraggable())
230 throw new VetoDragException();
232 } else if (context.draggable instanceof DnDSimpleFocusPanel) {
233 DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
234 // prevent drag and drop for trashed files and for
235 // unselected tree items
236 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
237 throw new VetoDragException();
242 protected Widget newDragProxy(DragContext aContext) {
243 AbsolutePanel container = new AbsolutePanel();
244 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
245 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
247 Widget widget = (Widget) iterator.next();
248 if (widget instanceof DnDFocusPanel) {
249 DnDFocusPanel book = (DnDFocusPanel) widget;
250 html = book.cloneHTML();
251 } else if (widget instanceof DnDSimpleFocusPanel) {
252 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
253 html = book.cloneHTML();
256 container.add(new Label("Drag ME"));
263 dragController.setBehaviorDragProxy(true);
264 dragController.setBehaviorMultipleSelection(false);
265 topPanel = new TopPanel(GSS.images);
266 topPanel.setWidth("100%");
268 messagePanel.setWidth("100%");
269 messagePanel.setVisible(false);
271 search = new Search(images);
272 searchStatus.add(search, DockPanel.WEST);
273 searchStatus.add(userDetailsPanel, DockPanel.EAST);
274 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
275 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
276 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
277 searchStatus.setWidth("100%");
279 fileList = new FileList(images);
281 searchResults = new SearchResults(images);
283 // Inner contains the various lists.
284 inner.setAnimationEnabled(true);
285 inner.getTabBar().addStyleName("gss-MainTabBar");
286 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
287 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
289 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
290 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
291 inner.setWidth("100%");
294 inner.addSelectionHandler(new SelectionHandler<Integer>() {
297 public void onSelection(SelectionEvent<Integer> event) {
298 int tabIndex = event.getSelectedItem();
299 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
302 // Files tab selected
303 fileList.clearSelectedRows();
304 fileList.updateCurrentlyShowingStats();
307 // Groups tab selected
308 groups.updateCurrentlyShowingStats();
309 updateHistory("Groups");
312 // Search tab selected
313 searchResults.clearSelectedRows();
314 searchResults.updateCurrentlyShowingStats();
315 updateHistory("Search");
320 // If the application starts with no history token, redirect to a new "Files" state
321 String initToken = History.getToken();
322 if(initToken.length() == 0)
323 History.newItem("Files");
326 // Add history listener to handle any history events
327 History.addValueChangeHandler(new ValueChangeHandler<String>() {
328 public void onValueChange(ValueChangeEvent<String> event) {
329 String tokenInput = event.getValue();
330 String historyToken = handleSpecialFolderNames(tokenInput);
332 if(historyToken.equals("Search"))
334 else if(historyToken.equals("Groups"))
336 else if(historyToken.equals("Files")|| historyToken.length()==0)
339 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
340 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
341 SelectionEvent.fire(popupTree, treeObj);
343 } catch (IndexOutOfBoundsException e) {
349 // Add the left and right panels to the split panel.
350 splitPanel.setLeftWidget(folders);
351 splitPanel.setRightWidget(inner);
352 splitPanel.setSplitPosition("25%");
353 splitPanel.setSize("100%", "100%");
354 splitPanel.addStyleName("gss-splitPanel");
356 // Create a dock panel that will contain the menu bar at the top,
357 // the shortcuts to the left, the status bar at the bottom and the
358 // right panel taking the rest.
359 VerticalPanel outer = new VerticalPanel();
361 outer.add(searchStatus);
362 outer.add(messagePanel);
363 outer.add(splitPanel);
364 outer.add(statusPanel);
365 outer.setWidth("100%");
366 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
370 // Hook the window resize event, so that we can adjust the UI.
371 Window.addResizeHandler(this);
372 // Clear out the window's built-in margin, because we want to take
373 // advantage of the entire client area.
374 Window.setMargin("0px");
375 // Finally, add the outer panel to the RootPanel, so that it will be
377 RootPanel.get().add(outer);
378 // Call the window resized handler to get the initial sizes setup. Doing
379 // this in a deferred command causes it to occur after all widgets'
380 // sizes have been computed by the browser.
381 DeferredCommand.addCommand(new Command() {
383 public void execute() {
384 onWindowResized(Window.getClientHeight());
390 * Fetches the User object for the specified username.
392 * @param username the username of the user
394 private void fetchUser(final String username) {
395 String path = getApiPath() + username + "/";
396 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
399 public void onComplete() {
400 currentUserResource = getResult();
401 final String announcement = currentUserResource.getAnnouncement();
402 if (announcement != null)
403 DeferredCommand.addCommand(new Command() {
405 public void execute() {
406 displayInformation(announcement);
412 public void onError(Throwable t) {
413 GWT.log("Fetching user error", t);
414 if (t instanceof RestException)
415 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
417 GSS.get().displayError("System error fetching user data:" + t.getMessage());
421 DeferredCommand.addCommand(getUserCommand);
425 * Parse and store the user credentials to the appropriate fields.
427 private void parseUserCredentials() {
428 Configuration conf = (Configuration) GWT.create(Configuration.class);
429 String cookie = conf.authCookie();
430 String auth = Cookies.getCookie(cookie);
433 // Redundant, but silences warnings about possible auth NPE, below.
436 int sepIndex = auth.indexOf(conf.cookieSeparator());
439 token = auth.substring(sepIndex + 1);
440 final String username = auth.substring(0, sepIndex);
441 if (username == null)
444 refreshWebDAVPassword();
446 DeferredCommand.addCommand(new Command() {
448 public void execute() {
455 * Redirect the user to the login page for authentication.
457 protected void authenticateUser() {
458 Configuration conf = (Configuration) GWT.create(Configuration.class);
459 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
463 * Clear the cookie and redirect the user to the logout page.
466 Configuration conf = (Configuration) GWT.create(Configuration.class);
467 String cookie = conf.authCookie();
468 String domain = Window.Location.getHostName();
469 String path = Window.Location.getPath();
470 Cookies.setCookie(cookie, "", null, domain, path, false);
471 Window.Location.assign(conf.logoutUrl());
475 * Creates an HTML fragment that places an image & caption together, for use
478 * @param imageProto an image prototype for an image
479 * @param caption the group caption
480 * @return the header HTML fragment
482 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
483 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>";
487 private void onWindowResized(int height) {
488 // Adjust the split panel to take up the available room in the window.
489 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
492 splitPanel.setHeight("" + newHeight);
496 public void onResize(ResizeEvent event) {
497 int height = event.getHeight();
498 onWindowResized(height);
501 public boolean isFileListShowing() {
502 int tab = inner.getTabBar().getSelectedTab();
508 public boolean isSearchResultsShowing() {
509 int tab = inner.getTabBar().getSelectedTab();
516 * Make the user list visible.
518 public void showUserList() {
523 * Make the file list visible.
525 public void showFileList() {
526 fileList.updateFileCache(false, true /*clear selection*/);
531 * Make the file list visible.
535 public void showFileList(boolean update) {
536 TreeItem currentFolder = getFolders().getCurrent();
537 if (currentFolder != null) {
538 List<FileResource> files = null;
539 Object cachedObject = currentFolder.getUserObject();
540 if (cachedObject instanceof FolderResource) {
541 FolderResource folder = (FolderResource) cachedObject;
542 files = folder.getFiles();
543 } else if (cachedObject instanceof TrashResource) {
544 TrashResource folder = (TrashResource) cachedObject;
545 files = folder.getFiles();
548 getFileList().setFiles(files);
550 fileList.updateFileCache(update, true /*clear selection*/);
555 * Make the search results visible.
557 * @param query the search query string
559 public void showSearchResults(String query) {
560 searchResults.updateFileCache(query);
561 searchResults.updateCurrentlyShowingStats();
566 * Display the 'loading' indicator.
568 public void showLoadingIndicator() {
569 topPanel.getLoading().setVisible(true);
573 * Hide the 'loading' indicator.
575 public void hideLoadingIndicator() {
576 topPanel.getLoading().setVisible(false);
580 * A native JavaScript method to reach out to the browser's window and
581 * invoke its resizeTo() method.
583 * @param x the new width
584 * @param y the new height
586 public static native void resizeTo(int x, int y) /*-{
591 * A helper method that returns true if the user's list is currently visible
592 * and false if it is hidden.
594 * @return true if the user list is visible
596 public boolean isUserListVisible() {
597 return inner.getTabBar().getSelectedTab() == 1;
601 * Display an error message.
603 * @param msg the message to display
605 public void displayError(String msg) {
606 messagePanel.displayError(msg);
610 * Display a warning message.
612 * @param msg the message to display
614 public void displayWarning(String msg) {
615 messagePanel.displayWarning(msg);
619 * Display an informational message.
621 * @param msg the message to display
623 public void displayInformation(String msg) {
624 messagePanel.displayInformation(msg);
628 * Retrieve the folders.
630 * @return the folders
632 public Folders getFolders() {
637 * Retrieve the search.
646 * Retrieve the currentSelection.
648 * @return the currentSelection
650 public Object getCurrentSelection() {
651 return currentSelection;
655 * Modify the currentSelection.
657 * @param newCurrentSelection the currentSelection to set
659 public void setCurrentSelection(Object newCurrentSelection) {
660 currentSelection = newCurrentSelection;
664 * Retrieve the groups.
668 public Groups getGroups() {
673 * Retrieve the fileList.
675 * @return the fileList
677 public FileList getFileList() {
681 public SearchResults getSearchResults() {
682 return searchResults;
686 * Retrieve the topPanel.
688 * @return the topPanel
690 TopPanel getTopPanel() {
695 * Retrieve the clipboard.
697 * @return the clipboard
699 public Clipboard getClipboard() {
703 public StatusPanel getStatusPanel() {
708 * Retrieve the userDetailsPanel.
710 * @return the userDetailsPanel
712 public UserDetailsPanel getUserDetailsPanel() {
713 return userDetailsPanel;
717 * Retrieve the dragController.
719 * @return the dragController
721 public PickupDragController getDragController() {
722 return dragController;
725 public String getToken() {
729 public String getWebDAVPassword() {
730 return webDAVPassword;
733 public void removeGlassPanel() {
734 glassPanel.removeFromParent();
738 * Retrieve the currentUserResource.
740 * @return the currentUserResource
742 public UserResource getCurrentUserResource() {
743 return currentUserResource;
747 * Modify the currentUserResource.
749 * @param newUser the new currentUserResource
751 public void setCurrentUserResource(UserResource newUser) {
752 currentUserResource = newUser;
755 public static native void preventIESelection() /*-{
756 $doc.body.onselectstart = function () { return false; };
759 public static native void enableIESelection() /*-{
760 if ($doc.body.onselectstart != null)
761 $doc.body.onselectstart = null;
765 * @return the absolute path of the API root URL
767 public String getApiPath() {
768 Configuration conf = (Configuration) GWT.create(Configuration.class);
769 return GWT.getModuleBaseURL() + conf.apiPath();
772 public void refreshWebDAVPassword() {
773 Configuration conf = (Configuration) GWT.create(Configuration.class);
774 String domain = Window.Location.getHostName();
775 String path = Window.Location.getPath();
776 String cookie = conf.webdavCookie();
777 webDAVPassword = Cookies.getCookie(cookie);
778 Cookies.setCookie(cookie, "", null, domain, path, false);
782 * History support for folder navigation
783 * adds a new browser history entry
787 public void updateHistory(String key){
788 // Replace any whitespace of the initial string to "+"
789 // String result = key.replaceAll("\\s","+");
790 // Add a new browser history entry.
791 // History.newItem(result);
792 History.newItem(key);
796 * This method examines the token input and add a "/" at the end in case it's omitted.
797 * This happens only in Files/trash/, Files/shared/, Files/others.
800 * @return the formated token with a "/" at the end or the same tokenInput parameter
803 public String handleSpecialFolderNames(String tokenInput){
804 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
805 if(pathsToCheck.contains(tokenInput))
806 return tokenInput + "/";