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.Date;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
38 import com.allen_sauer.gwt.dnd.client.DragContext;
39 import com.allen_sauer.gwt.dnd.client.PickupDragController;
40 import com.allen_sauer.gwt.dnd.client.VetoDragException;
41 import com.google.gwt.core.client.EntryPoint;
42 import com.google.gwt.core.client.GWT;
43 import com.google.gwt.event.logical.shared.ResizeEvent;
44 import com.google.gwt.event.logical.shared.ResizeHandler;
45 import com.google.gwt.event.logical.shared.SelectionEvent;
46 import com.google.gwt.event.logical.shared.SelectionHandler;
47 import com.google.gwt.event.logical.shared.ValueChangeEvent;
48 import com.google.gwt.event.logical.shared.ValueChangeHandler;
49 import com.google.gwt.i18n.client.DateTimeFormat;
50 import com.google.gwt.resources.client.ClientBundle;
51 import com.google.gwt.resources.client.ImageResource;
52 import com.google.gwt.user.client.Command;
53 import com.google.gwt.user.client.Cookies;
54 import com.google.gwt.user.client.DOM;
55 import com.google.gwt.user.client.DeferredCommand;
56 import com.google.gwt.user.client.History;
57 import com.google.gwt.user.client.Window;
58 import com.google.gwt.user.client.ui.AbsolutePanel;
59 import com.google.gwt.user.client.ui.AbstractImagePrototype;
60 import com.google.gwt.user.client.ui.DecoratedTabPanel;
61 import com.google.gwt.user.client.ui.DockPanel;
62 import com.google.gwt.user.client.ui.HTML;
63 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
64 import com.google.gwt.user.client.ui.HasVerticalAlignment;
65 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
66 import com.google.gwt.user.client.ui.Label;
67 import com.google.gwt.user.client.ui.RootPanel;
68 import com.google.gwt.user.client.ui.TabPanel;
69 import com.google.gwt.user.client.ui.TreeItem;
70 import com.google.gwt.user.client.ui.VerticalPanel;
71 import com.google.gwt.user.client.ui.Widget;
74 * Entry point classes define <code>onModuleLoad()</code>.
76 public class GSS implements EntryPoint, ResizeHandler {
79 * A constant that denotes the completion of an IncrementalCommand.
81 public static final boolean DONE = false;
83 public static final int VISIBLE_FILE_COUNT = 100;
86 * Instantiate an application-level image bundle. This object will provide
87 * programmatic access to all the images needed by widgets.
89 private static Images images = (Images) GWT.create(Images.class);
91 private GlassPanel glassPanel = new GlassPanel();
94 * An aggregate image bundle that pulls together all the images for this
95 * application into a single bundle.
97 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 {
99 @Source("gr/ebs/gss/resources/document.png")
100 ImageResource folders();
102 @Source("gr/ebs/gss/resources/edit_group_22.png")
103 ImageResource groups();
105 @Source("gr/ebs/gss/resources/search.png")
106 ImageResource search();
110 * The single GSS instance.
112 private static GSS singleton;
115 * Gets the singleton GSS instance.
117 * @return the GSS object
119 public static GSS get() {
120 if (GSS.singleton == null)
121 GSS.singleton = new GSS();
122 return GSS.singleton;
126 * The Application Clipboard implementation;
128 private Clipboard clipboard = new Clipboard();
130 private UserResource currentUserResource;
133 * The top panel that contains the menu bar.
135 private TopPanel topPanel;
138 * The panel that contains the various system messages.
140 private MessagePanel messagePanel = new MessagePanel(GSS.images);
143 * The bottom panel that contains the status bar.
145 private StatusPanel statusPanel = new StatusPanel(GSS.images);
148 * The top right panel that displays the logged in user details
150 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
153 * The file list widget.
155 private FileList fileList;
158 * The group list widget.
160 private Groups groups = new Groups(images);
163 * The search result widget.
165 private SearchResults searchResults;
168 * The tab panel that occupies the right side of the screen.
170 private TabPanel inner = new DecoratedTabPanel();
173 * The split panel that will contain the left and right panels.
175 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
178 * The horizontal panel that will contain the search and status panels.
180 private DockPanel searchStatus = new DockPanel();
185 private Search search;
188 * The widget that displays the tree of folders.
190 private Folders folders = new Folders(images);
193 * The currently selected item in the application, for use by the Edit menu
194 * commands. Potential types are Folder, File, User and Group.
196 private Object currentSelection;
199 * The authentication token of the current user.
201 private String token;
204 * The WebDAV password of the current user
206 private String webDAVPassword;
208 private PickupDragController dragController;
210 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
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 if(book.getFiles().size()>1)
258 html=new HTML(book.getFiles().size()+ " files");
260 html = book.cloneHTML();
261 } else if (widget instanceof DnDSimpleFocusPanel) {
262 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
263 if(book.getFiles().size()>1)
264 html=new HTML(book.getFiles().size()+ " files");
266 html = book.cloneHTML();
269 container.add(new Label("Drag ME"));
276 dragController.setBehaviorDragProxy(true);
277 dragController.setBehaviorMultipleSelection(false);
278 topPanel = new TopPanel(GSS.images);
279 topPanel.setWidth("100%");
281 messagePanel.setWidth("100%");
282 messagePanel.setVisible(false);
284 search = new Search(images);
285 searchStatus.add(search, DockPanel.WEST);
286 searchStatus.add(userDetailsPanel, DockPanel.EAST);
287 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
288 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
289 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
290 searchStatus.setWidth("100%");
292 fileList = new FileList(images);
294 searchResults = new SearchResults(images);
296 // Inner contains the various lists.
297 inner.setAnimationEnabled(true);
298 inner.getTabBar().addStyleName("gss-MainTabBar");
299 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
300 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
302 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
303 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
304 inner.setWidth("100%");
307 inner.addSelectionHandler(new SelectionHandler<Integer>() {
310 public void onSelection(SelectionEvent<Integer> event) {
311 int tabIndex = event.getSelectedItem();
312 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
315 // Files tab selected
316 fileList.clearSelectedRows();
317 fileList.updateCurrentlyShowingStats();
320 // Groups tab selected
321 groups.updateCurrentlyShowingStats();
322 updateHistory("Groups");
325 // Search tab selected
326 searchResults.clearSelectedRows();
327 searchResults.updateCurrentlyShowingStats();
328 updateHistory("Search");
333 // If the application starts with no history token, redirect to a new "Files" state
334 String initToken = History.getToken();
335 if(initToken.length() == 0)
336 History.newItem("Files");
337 // Add history listener to handle any history events
338 History.addValueChangeHandler(new ValueChangeHandler<String>() {
340 public void onValueChange(ValueChangeEvent<String> event) {
341 String tokenInput = event.getValue();
342 String historyToken = handleSpecialFolderNames(tokenInput);
344 if(historyToken.equals("Search"))
346 else if(historyToken.equals("Groups"))
348 else if(historyToken.equals("Files")|| historyToken.length()==0)
351 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
352 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
353 SelectionEvent.fire(popupTree, treeObj);
355 } catch (IndexOutOfBoundsException e) {
361 // Add the left and right panels to the split panel.
362 splitPanel.setLeftWidget(folders);
363 splitPanel.setRightWidget(inner);
364 splitPanel.setSplitPosition("25%");
365 splitPanel.setSize("100%", "100%");
366 splitPanel.addStyleName("gss-splitPanel");
368 // Create a dock panel that will contain the menu bar at the top,
369 // the shortcuts to the left, the status bar at the bottom and the
370 // right panel taking the rest.
371 VerticalPanel outer = new VerticalPanel();
373 outer.add(searchStatus);
374 outer.add(messagePanel);
375 outer.add(splitPanel);
376 outer.add(statusPanel);
377 outer.setWidth("100%");
378 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
382 // Hook the window resize event, so that we can adjust the UI.
383 Window.addResizeHandler(this);
384 // Clear out the window's built-in margin, because we want to take
385 // advantage of the entire client area.
386 Window.setMargin("0px");
387 // Finally, add the outer panel to the RootPanel, so that it will be
389 RootPanel.get().add(outer);
390 // Call the window resized handler to get the initial sizes setup. Doing
391 // this in a deferred command causes it to occur after all widgets'
392 // sizes have been computed by the browser.
393 DeferredCommand.addCommand(new Command() {
396 public void execute() {
397 onWindowResized(Window.getClientHeight());
403 * Fetches the User object for the specified username.
405 * @param username the username of the user
407 private void fetchUser(final String username) {
408 String path = getApiPath() + username + "/";
409 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
412 public void onComplete() {
413 currentUserResource = getResult();
414 final String announcement = currentUserResource.getAnnouncement();
415 if (announcement != null)
416 DeferredCommand.addCommand(new Command() {
419 public void execute() {
420 displayInformation(announcement);
426 public void onError(Throwable t) {
427 GWT.log("Fetching user error", t);
428 if (t instanceof RestException)
429 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
431 GSS.get().displayError("System error fetching user data:" + t.getMessage());
435 DeferredCommand.addCommand(getUserCommand);
439 * Parse and store the user credentials to the appropriate fields.
441 private void parseUserCredentials() {
442 Configuration conf = (Configuration) GWT.create(Configuration.class);
443 String cookie = conf.authCookie();
444 String auth = Cookies.getCookie(cookie);
447 // Redundant, but silences warnings about possible auth NPE, below.
450 int sepIndex = auth.indexOf(conf.cookieSeparator());
453 token = auth.substring(sepIndex + 1);
454 final String username = auth.substring(0, sepIndex);
455 if (username == null)
458 refreshWebDAVPassword();
460 DeferredCommand.addCommand(new Command() {
463 public void execute() {
470 * Redirect the user to the login page for authentication.
472 protected void authenticateUser() {
473 Configuration conf = (Configuration) GWT.create(Configuration.class);
474 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
478 * Clear the cookie and redirect the user to the logout page.
481 Configuration conf = (Configuration) GWT.create(Configuration.class);
482 String cookie = conf.authCookie();
483 String domain = Window.Location.getHostName();
484 String path = Window.Location.getPath();
485 Cookies.setCookie(cookie, "", null, domain, path, false);
486 Window.Location.assign(conf.logoutUrl());
490 * Creates an HTML fragment that places an image & caption together, for use
493 * @param imageProto an image prototype for an image
494 * @param caption the group caption
495 * @return the header HTML fragment
497 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
498 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>";
502 private void onWindowResized(int height) {
503 // Adjust the split panel to take up the available room in the window.
504 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
507 splitPanel.setHeight("" + newHeight);
511 public void onResize(ResizeEvent event) {
512 int height = event.getHeight();
513 onWindowResized(height);
516 public boolean isFileListShowing() {
517 int tab = inner.getTabBar().getSelectedTab();
523 public boolean isSearchResultsShowing() {
524 int tab = inner.getTabBar().getSelectedTab();
531 * Make the user list visible.
533 public void showUserList() {
538 * Make the file list visible.
540 public void showFileList() {
541 fileList.updateFileCache(false, true /*clear selection*/);
546 * Make the file list visible.
550 public void showFileList(boolean update) {
551 TreeItem currentFolder = getFolders().getCurrent();
552 if (currentFolder != null) {
553 List<FileResource> files = null;
554 Object cachedObject = currentFolder.getUserObject();
555 if (cachedObject instanceof FolderResource) {
556 FolderResource folder = (FolderResource) cachedObject;
557 files = folder.getFiles();
558 } else if (cachedObject instanceof TrashResource) {
559 TrashResource folder = (TrashResource) cachedObject;
560 files = folder.getFiles();
563 getFileList().setFiles(files);
565 fileList.updateFileCache(update, true /*clear selection*/);
570 * Make the search results visible.
572 * @param query the search query string
574 public void showSearchResults(String query) {
575 searchResults.updateFileCache(query);
576 searchResults.updateCurrentlyShowingStats();
581 * Display the 'loading' indicator.
583 public void showLoadingIndicator() {
584 topPanel.getLoading().setVisible(true);
588 * Hide the 'loading' indicator.
590 public void hideLoadingIndicator() {
591 topPanel.getLoading().setVisible(false);
595 * A native JavaScript method to reach out to the browser's window and
596 * invoke its resizeTo() method.
598 * @param x the new width
599 * @param y the new height
601 public static native void resizeTo(int x, int y) /*-{
606 * A helper method that returns true if the user's list is currently visible
607 * and false if it is hidden.
609 * @return true if the user list is visible
611 public boolean isUserListVisible() {
612 return inner.getTabBar().getSelectedTab() == 1;
616 * Display an error message.
618 * @param msg the message to display
620 public void displayError(String msg) {
621 messagePanel.displayError(msg);
625 * Display a warning message.
627 * @param msg the message to display
629 public void displayWarning(String msg) {
630 messagePanel.displayWarning(msg);
634 * Display an informational message.
636 * @param msg the message to display
638 public void displayInformation(String msg) {
639 messagePanel.displayInformation(msg);
643 * Retrieve the folders.
645 * @return the folders
647 public Folders getFolders() {
652 * Retrieve the search.
661 * Retrieve the currentSelection.
663 * @return the currentSelection
665 public Object getCurrentSelection() {
666 return currentSelection;
670 * Modify the currentSelection.
672 * @param newCurrentSelection the currentSelection to set
674 public void setCurrentSelection(Object newCurrentSelection) {
675 currentSelection = newCurrentSelection;
679 * Retrieve the groups.
683 public Groups getGroups() {
688 * Retrieve the fileList.
690 * @return the fileList
692 public FileList getFileList() {
696 public SearchResults getSearchResults() {
697 return searchResults;
701 * Retrieve the topPanel.
703 * @return the topPanel
705 TopPanel getTopPanel() {
710 * Retrieve the clipboard.
712 * @return the clipboard
714 public Clipboard getClipboard() {
718 public StatusPanel getStatusPanel() {
723 * Retrieve the userDetailsPanel.
725 * @return the userDetailsPanel
727 public UserDetailsPanel getUserDetailsPanel() {
728 return userDetailsPanel;
732 * Retrieve the dragController.
734 * @return the dragController
736 public PickupDragController getDragController() {
737 return dragController;
740 public String getToken() {
744 public String getWebDAVPassword() {
745 return webDAVPassword;
748 public void removeGlassPanel() {
749 glassPanel.removeFromParent();
753 * Retrieve the currentUserResource.
755 * @return the currentUserResource
757 public UserResource getCurrentUserResource() {
758 return currentUserResource;
762 * Modify the currentUserResource.
764 * @param newUser the new currentUserResource
766 public void setCurrentUserResource(UserResource newUser) {
767 currentUserResource = newUser;
770 public static native void preventIESelection() /*-{
771 $doc.body.onselectstart = function () { return false; };
774 public static native void enableIESelection() /*-{
775 if ($doc.body.onselectstart != null)
776 $doc.body.onselectstart = null;
780 * @return the absolute path of the API root URL
782 public String getApiPath() {
783 Configuration conf = (Configuration) GWT.create(Configuration.class);
784 return GWT.getModuleBaseURL() + conf.apiPath();
787 public void refreshWebDAVPassword() {
788 Configuration conf = (Configuration) GWT.create(Configuration.class);
789 String domain = Window.Location.getHostName();
790 String path = Window.Location.getPath();
791 String cookie = conf.webdavCookie();
792 webDAVPassword = Cookies.getCookie(cookie);
793 Cookies.setCookie(cookie, "", null, domain, path, false);
797 * Convert server date to local time according to browser timezone
798 * and format it according to localized pattern.
799 * Time is always formatted to 24hr format.
800 * NB: This assumes that server runs in UTC timezone. Otherwise
801 * we would need to adjust for server time offset as well.
806 public static String formatLocalDateTime(Date date) {
807 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
808 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
809 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
810 String datePart = dateFormatter.format(convertedDate);
811 String timePart = timeFormatter.format(convertedDate);
812 return datePart + " " + timePart;
816 * History support for folder navigation
817 * adds a new browser history entry
821 public void updateHistory(String key){
822 // Replace any whitespace of the initial string to "+"
823 // String result = key.replaceAll("\\s","+");
824 // Add a new browser history entry.
825 // History.newItem(result);
826 History.newItem(key);
830 * This method examines the token input and add a "/" at the end in case it's omitted.
831 * This happens only in Files/trash/, Files/shared/, Files/others.
834 * @return the formated token with a "/" at the end or the same tokenInput parameter
837 private String handleSpecialFolderNames(String tokenInput){
838 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
839 if(pathsToCheck.contains(tokenInput))
840 return tokenInput + "/";
846 * Reject illegal resource names, like '.' or '..' or slashes '/'.
848 static boolean isValidResourceName(String name) {
849 if (".".equals(name) || "..".equals(name) || name.contains("/"))
854 public void putUserToMap(String _userName, String _userFullName){
855 userFullNameMap.put(_userName, _userFullName);
858 public String findUserFullName(String _userName){
859 return userFullNameMap.get(_userName);
862 public String getUserFullName(String _userName) {
863 if (GSS.get().findUserFullName(_userName) == null)
864 //if there is no userFullName found then the map fills with the given _userName,
865 //so userFullName = _userName
866 GSS.get().putUserToMap(_userName, _userName);
867 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
868 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
869 GetUserCommand guc = new GetUserCommand(_userName);
872 return GSS.get().findUserFullName(_userName);