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;
207 public void onModuleLoad() {
208 // Initialize the singleton before calling the constructors of the
209 // various widgets that might call GSS.get().
211 RootPanel.get().add(glassPanel, 0, 0);
212 parseUserCredentials();
213 dragController = new PickupDragController(RootPanel.get(), false) {
216 public void previewDragStart() throws VetoDragException {
217 super.previewDragStart();
218 if (context.selectedWidgets.isEmpty())
219 throw new VetoDragException();
221 if (context.draggable != null)
222 if (context.draggable instanceof DnDFocusPanel) {
223 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
224 // prevent drag and drop for trashed files and for
225 // unselected tree items
226 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
227 throw new VetoDragException();
228 else if (toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
229 throw new VetoDragException();
230 else if (toDrop.getItem() != null && !toDrop.getItem().isDraggable())
231 throw new VetoDragException();
233 } else if (context.draggable instanceof DnDSimpleFocusPanel) {
234 DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
235 // prevent drag and drop for trashed files and for
236 // unselected tree items
237 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
238 throw new VetoDragException();
243 protected Widget newDragProxy(DragContext aContext) {
244 AbsolutePanel container = new AbsolutePanel();
245 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
246 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
248 Widget widget = (Widget) iterator.next();
249 if (widget instanceof DnDFocusPanel) {
250 DnDFocusPanel book = (DnDFocusPanel) widget;
251 html = book.cloneHTML();
252 } else if (widget instanceof DnDSimpleFocusPanel) {
253 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
254 html = book.cloneHTML();
257 container.add(new Label("Drag ME"));
264 dragController.setBehaviorDragProxy(true);
265 dragController.setBehaviorMultipleSelection(false);
266 topPanel = new TopPanel(GSS.images);
267 topPanel.setWidth("100%");
269 messagePanel.setWidth("100%");
270 messagePanel.setVisible(false);
272 search = new Search(images);
273 searchStatus.add(search, DockPanel.WEST);
274 searchStatus.add(userDetailsPanel, DockPanel.EAST);
275 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
276 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
277 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
278 searchStatus.setWidth("100%");
280 fileList = new FileList(images);
282 searchResults = new SearchResults(images);
284 // Inner contains the various lists.
285 inner.setAnimationEnabled(true);
286 inner.getTabBar().addStyleName("gss-MainTabBar");
287 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
288 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
290 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
291 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
292 inner.setWidth("100%");
295 inner.addSelectionHandler(new SelectionHandler<Integer>() {
298 public void onSelection(SelectionEvent<Integer> event) {
299 int tabIndex = event.getSelectedItem();
300 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
303 // Files tab selected
304 fileList.clearSelectedRows();
305 fileList.updateCurrentlyShowingStats();
308 // Groups tab selected
309 groups.updateCurrentlyShowingStats();
310 updateHistory("Groups");
313 // Search tab selected
314 searchResults.clearSelectedRows();
315 searchResults.updateCurrentlyShowingStats();
316 updateHistory("Search");
321 // If the application starts with no history token, redirect to a new "Files" state
322 String initToken = History.getToken();
323 if(initToken.length() == 0)
324 History.newItem("Files");
325 // Add history listener to handle any history events
326 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() {
384 public void execute() {
385 onWindowResized(Window.getClientHeight());
391 * Fetches the User object for the specified username.
393 * @param username the username of the user
395 private void fetchUser(final String username) {
396 String path = getApiPath() + username + "/";
397 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
400 public void onComplete() {
401 currentUserResource = getResult();
402 final String announcement = currentUserResource.getAnnouncement();
403 if (announcement != null)
404 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() {
451 public void execute() {
458 * Redirect the user to the login page for authentication.
460 protected void authenticateUser() {
461 Configuration conf = (Configuration) GWT.create(Configuration.class);
462 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
466 * Clear the cookie and redirect the user to the logout page.
469 Configuration conf = (Configuration) GWT.create(Configuration.class);
470 String cookie = conf.authCookie();
471 String domain = Window.Location.getHostName();
472 String path = Window.Location.getPath();
473 Cookies.setCookie(cookie, "", null, domain, path, false);
474 Window.Location.assign(conf.logoutUrl());
478 * Creates an HTML fragment that places an image & caption together, for use
481 * @param imageProto an image prototype for an image
482 * @param caption the group caption
483 * @return the header HTML fragment
485 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
486 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>";
490 private void onWindowResized(int height) {
491 // Adjust the split panel to take up the available room in the window.
492 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
495 splitPanel.setHeight("" + newHeight);
499 public void onResize(ResizeEvent event) {
500 int height = event.getHeight();
501 onWindowResized(height);
504 public boolean isFileListShowing() {
505 int tab = inner.getTabBar().getSelectedTab();
511 public boolean isSearchResultsShowing() {
512 int tab = inner.getTabBar().getSelectedTab();
519 * Make the user list visible.
521 public void showUserList() {
526 * Make the file list visible.
528 public void showFileList() {
529 fileList.updateFileCache(false, true /*clear selection*/);
534 * Make the file list visible.
538 public void showFileList(boolean update) {
539 TreeItem currentFolder = getFolders().getCurrent();
540 if (currentFolder != null) {
541 List<FileResource> files = null;
542 Object cachedObject = currentFolder.getUserObject();
543 if (cachedObject instanceof FolderResource) {
544 FolderResource folder = (FolderResource) cachedObject;
545 files = folder.getFiles();
546 } else if (cachedObject instanceof TrashResource) {
547 TrashResource folder = (TrashResource) cachedObject;
548 files = folder.getFiles();
551 getFileList().setFiles(files);
553 fileList.updateFileCache(update, true /*clear selection*/);
558 * Make the search results visible.
560 * @param query the search query string
562 public void showSearchResults(String query) {
563 searchResults.updateFileCache(query);
564 searchResults.updateCurrentlyShowingStats();
569 * Display the 'loading' indicator.
571 public void showLoadingIndicator() {
572 topPanel.getLoading().setVisible(true);
576 * Hide the 'loading' indicator.
578 public void hideLoadingIndicator() {
579 topPanel.getLoading().setVisible(false);
583 * A native JavaScript method to reach out to the browser's window and
584 * invoke its resizeTo() method.
586 * @param x the new width
587 * @param y the new height
589 public static native void resizeTo(int x, int y) /*-{
594 * A helper method that returns true if the user's list is currently visible
595 * and false if it is hidden.
597 * @return true if the user list is visible
599 public boolean isUserListVisible() {
600 return inner.getTabBar().getSelectedTab() == 1;
604 * Display an error message.
606 * @param msg the message to display
608 public void displayError(String msg) {
609 messagePanel.displayError(msg);
613 * Display a warning message.
615 * @param msg the message to display
617 public void displayWarning(String msg) {
618 messagePanel.displayWarning(msg);
622 * Display an informational message.
624 * @param msg the message to display
626 public void displayInformation(String msg) {
627 messagePanel.displayInformation(msg);
631 * Retrieve the folders.
633 * @return the folders
635 public Folders getFolders() {
640 * Retrieve the search.
649 * Retrieve the currentSelection.
651 * @return the currentSelection
653 public Object getCurrentSelection() {
654 return currentSelection;
658 * Modify the currentSelection.
660 * @param newCurrentSelection the currentSelection to set
662 public void setCurrentSelection(Object newCurrentSelection) {
663 currentSelection = newCurrentSelection;
667 * Retrieve the groups.
671 public Groups getGroups() {
676 * Retrieve the fileList.
678 * @return the fileList
680 public FileList getFileList() {
684 public SearchResults getSearchResults() {
685 return searchResults;
689 * Retrieve the topPanel.
691 * @return the topPanel
693 TopPanel getTopPanel() {
698 * Retrieve the clipboard.
700 * @return the clipboard
702 public Clipboard getClipboard() {
706 public StatusPanel getStatusPanel() {
711 * Retrieve the userDetailsPanel.
713 * @return the userDetailsPanel
715 public UserDetailsPanel getUserDetailsPanel() {
716 return userDetailsPanel;
720 * Retrieve the dragController.
722 * @return the dragController
724 public PickupDragController getDragController() {
725 return dragController;
728 public String getToken() {
732 public String getWebDAVPassword() {
733 return webDAVPassword;
736 public void removeGlassPanel() {
737 glassPanel.removeFromParent();
741 * Retrieve the currentUserResource.
743 * @return the currentUserResource
745 public UserResource getCurrentUserResource() {
746 return currentUserResource;
750 * Modify the currentUserResource.
752 * @param newUser the new currentUserResource
754 public void setCurrentUserResource(UserResource newUser) {
755 currentUserResource = newUser;
758 public static native void preventIESelection() /*-{
759 $doc.body.onselectstart = function () { return false; };
762 public static native void enableIESelection() /*-{
763 if ($doc.body.onselectstart != null)
764 $doc.body.onselectstart = null;
768 * @return the absolute path of the API root URL
770 public String getApiPath() {
771 Configuration conf = (Configuration) GWT.create(Configuration.class);
772 return GWT.getModuleBaseURL() + conf.apiPath();
775 public void refreshWebDAVPassword() {
776 Configuration conf = (Configuration) GWT.create(Configuration.class);
777 String domain = Window.Location.getHostName();
778 String path = Window.Location.getPath();
779 String cookie = conf.webdavCookie();
780 webDAVPassword = Cookies.getCookie(cookie);
781 Cookies.setCookie(cookie, "", null, domain, path, false);
785 * History support for folder navigation
786 * adds a new browser history entry
790 public void updateHistory(String key){
791 // Replace any whitespace of the initial string to "+"
792 // String result = key.replaceAll("\\s","+");
793 // Add a new browser history entry.
794 // History.newItem(result);
795 History.newItem(key);
799 * This method examines the token input and add a "/" at the end in case it's omitted.
800 * This happens only in Files/trash/, Files/shared/, Files/others.
803 * @return the formated token with a "/" at the end or the same tokenInput parameter
806 private String handleSpecialFolderNames(String tokenInput){
807 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
808 if(pathsToCheck.contains(tokenInput))
809 return tokenInput + "/";
815 * Reject illegal resource names, like '.' or '..'.
817 static boolean isValidResourceName(String name) {
818 if (".".equals(name) || "..".equals(name))