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, CellTreeView.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();
252 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
253 if(aContext.draggable!=null && aContext.draggable.getParent()!= null && aContext.draggable.getParent() instanceof FileTable){
254 if(getFileList().getSelectedFiles().size()>1){
255 html=new HTML(getFileList().getSelectedFiles().size()+ " files");
260 proxy = new FileTable(1,8);
261 proxy.addStyleName("gss-List");
262 FileTable draggableTable = (FileTable) context.draggable.getParent();
263 int dragRow = FileTable.getWidgetRow(context.draggable, draggableTable);
264 FileTable.copyRow(draggableTable, proxy, dragRow, 0);
268 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
269 Widget widget = (Widget) iterator.next();
270 if (widget instanceof DnDFocusPanel) {
271 DnDFocusPanel book = (DnDFocusPanel) widget;
272 html = book.cloneHTML();
273 } else if (widget instanceof DnDSimpleFocusPanel) {
274 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
275 html = book.cloneHTML();
278 container.add(new Label("Drag ME"));
286 dragController.setBehaviorDragProxy(true);
287 dragController.setBehaviorMultipleSelection(false);
288 topPanel = new TopPanel(GSS.images);
289 topPanel.setWidth("100%");
291 messagePanel.setWidth("100%");
292 messagePanel.setVisible(false);
294 search = new Search(images);
295 searchStatus.add(search, DockPanel.WEST);
296 searchStatus.add(userDetailsPanel, DockPanel.EAST);
297 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
298 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
299 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
300 searchStatus.setWidth("100%");
302 fileList = new FileList(images);
304 searchResults = new SearchResults(images);
306 // Inner contains the various lists.
307 inner.setAnimationEnabled(true);
308 inner.getTabBar().addStyleName("gss-MainTabBar");
309 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
310 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
312 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
313 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
314 inner.add(new CellTreeView(images), createHeaderHTML(AbstractImagePrototype.create(images.search()), "Cell tree sample"), true);
315 inner.setWidth("100%");
318 inner.addSelectionHandler(new SelectionHandler<Integer>() {
321 public void onSelection(SelectionEvent<Integer> event) {
322 int tabIndex = event.getSelectedItem();
323 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
326 // Files tab selected
327 fileList.clearSelectedRows();
328 fileList.updateCurrentlyShowingStats();
331 // Groups tab selected
332 groups.updateCurrentlyShowingStats();
333 updateHistory("Groups");
336 // Search tab selected
337 searchResults.clearSelectedRows();
338 searchResults.updateCurrentlyShowingStats();
339 updateHistory("Search");
344 // If the application starts with no history token, redirect to a new "Files" state
345 String initToken = History.getToken();
346 if(initToken.length() == 0)
347 History.newItem("Files");
348 // Add history listener to handle any history events
349 History.addValueChangeHandler(new ValueChangeHandler<String>() {
351 public void onValueChange(ValueChangeEvent<String> event) {
352 String tokenInput = event.getValue();
353 String historyToken = handleSpecialFolderNames(tokenInput);
355 if(historyToken.equals("Search"))
357 else if(historyToken.equals("Groups"))
359 else if(historyToken.equals("Files")|| historyToken.length()==0)
362 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
363 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
364 SelectionEvent.fire(popupTree, treeObj);
366 } catch (IndexOutOfBoundsException e) {
372 // Add the left and right panels to the split panel.
373 splitPanel.setLeftWidget(folders);
374 splitPanel.setRightWidget(inner);
375 splitPanel.setSplitPosition("25%");
376 splitPanel.setSize("100%", "100%");
377 splitPanel.addStyleName("gss-splitPanel");
379 // Create a dock panel that will contain the menu bar at the top,
380 // the shortcuts to the left, the status bar at the bottom and the
381 // right panel taking the rest.
382 VerticalPanel outer = new VerticalPanel();
384 outer.add(searchStatus);
385 outer.add(messagePanel);
386 outer.add(splitPanel);
387 outer.add(statusPanel);
388 outer.setWidth("100%");
389 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
393 // Hook the window resize event, so that we can adjust the UI.
394 Window.addResizeHandler(this);
395 // Clear out the window's built-in margin, because we want to take
396 // advantage of the entire client area.
397 Window.setMargin("0px");
398 // Finally, add the outer panel to the RootPanel, so that it will be
400 RootPanel.get().add(outer);
401 // Call the window resized handler to get the initial sizes setup. Doing
402 // this in a deferred command causes it to occur after all widgets'
403 // sizes have been computed by the browser.
404 DeferredCommand.addCommand(new Command() {
407 public void execute() {
408 onWindowResized(Window.getClientHeight());
414 * Fetches the User object for the specified username.
416 * @param username the username of the user
418 private void fetchUser(final String username) {
419 String path = getApiPath() + username + "/";
420 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
423 public void onComplete() {
424 currentUserResource = getResult();
425 final String announcement = currentUserResource.getAnnouncement();
426 if (announcement != null)
427 DeferredCommand.addCommand(new Command() {
430 public void execute() {
431 displayInformation(announcement);
437 public void onError(Throwable t) {
438 GWT.log("Fetching user error", t);
439 if (t instanceof RestException)
440 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
442 GSS.get().displayError("System error fetching user data:" + t.getMessage());
446 DeferredCommand.addCommand(getUserCommand);
450 * Parse and store the user credentials to the appropriate fields.
452 private void parseUserCredentials() {
453 Configuration conf = (Configuration) GWT.create(Configuration.class);
454 String cookie = conf.authCookie();
455 String auth = Cookies.getCookie(cookie);
458 // Redundant, but silences warnings about possible auth NPE, below.
461 int sepIndex = auth.indexOf(conf.cookieSeparator());
464 token = auth.substring(sepIndex + 1);
465 final String username = auth.substring(0, sepIndex);
466 if (username == null)
469 refreshWebDAVPassword();
471 DeferredCommand.addCommand(new Command() {
474 public void execute() {
481 * Redirect the user to the login page for authentication.
483 protected void authenticateUser() {
484 Configuration conf = (Configuration) GWT.create(Configuration.class);
485 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
489 * Clear the cookie and redirect the user to the logout page.
492 Configuration conf = (Configuration) GWT.create(Configuration.class);
493 String cookie = conf.authCookie();
494 String domain = Window.Location.getHostName();
495 String path = Window.Location.getPath();
496 Cookies.setCookie(cookie, "", null, domain, path, false);
497 Window.Location.assign(conf.logoutUrl());
501 * Creates an HTML fragment that places an image & caption together, for use
504 * @param imageProto an image prototype for an image
505 * @param caption the group caption
506 * @return the header HTML fragment
508 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
509 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>";
513 private void onWindowResized(int height) {
514 // Adjust the split panel to take up the available room in the window.
515 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
518 splitPanel.setHeight("" + newHeight);
522 public void onResize(ResizeEvent event) {
523 int height = event.getHeight();
524 onWindowResized(height);
527 public boolean isFileListShowing() {
528 int tab = inner.getTabBar().getSelectedTab();
534 public boolean isSearchResultsShowing() {
535 int tab = inner.getTabBar().getSelectedTab();
542 * Make the user list visible.
544 public void showUserList() {
549 * Make the file list visible.
551 public void showFileList() {
552 fileList.updateFileCache(false, true /*clear selection*/);
557 * Make the file list visible.
561 public void showFileList(boolean update) {
562 TreeItem currentFolder = getFolders().getCurrent();
563 if (currentFolder != null) {
564 List<FileResource> files = null;
565 Object cachedObject = currentFolder.getUserObject();
566 if (cachedObject instanceof FolderResource) {
567 FolderResource folder = (FolderResource) cachedObject;
568 files = folder.getFiles();
569 } else if (cachedObject instanceof TrashResource) {
570 TrashResource folder = (TrashResource) cachedObject;
571 files = folder.getFiles();
574 getFileList().setFiles(files);
576 fileList.updateFileCache(update, true /*clear selection*/);
581 * Make the search results visible.
583 * @param query the search query string
585 public void showSearchResults(String query) {
586 searchResults.updateFileCache(query);
587 searchResults.updateCurrentlyShowingStats();
592 * Display the 'loading' indicator.
594 public void showLoadingIndicator() {
595 topPanel.getLoading().setVisible(true);
599 * Hide the 'loading' indicator.
601 public void hideLoadingIndicator() {
602 topPanel.getLoading().setVisible(false);
606 * A native JavaScript method to reach out to the browser's window and
607 * invoke its resizeTo() method.
609 * @param x the new width
610 * @param y the new height
612 public static native void resizeTo(int x, int y) /*-{
617 * A helper method that returns true if the user's list is currently visible
618 * and false if it is hidden.
620 * @return true if the user list is visible
622 public boolean isUserListVisible() {
623 return inner.getTabBar().getSelectedTab() == 1;
627 * Display an error message.
629 * @param msg the message to display
631 public void displayError(String msg) {
632 messagePanel.displayError(msg);
636 * Display a warning message.
638 * @param msg the message to display
640 public void displayWarning(String msg) {
641 messagePanel.displayWarning(msg);
645 * Display an informational message.
647 * @param msg the message to display
649 public void displayInformation(String msg) {
650 messagePanel.displayInformation(msg);
654 * Retrieve the folders.
656 * @return the folders
658 public Folders getFolders() {
663 * Retrieve the search.
672 * Retrieve the currentSelection.
674 * @return the currentSelection
676 public Object getCurrentSelection() {
677 return currentSelection;
681 * Modify the currentSelection.
683 * @param newCurrentSelection the currentSelection to set
685 public void setCurrentSelection(Object newCurrentSelection) {
686 currentSelection = newCurrentSelection;
690 * Retrieve the groups.
694 public Groups getGroups() {
699 * Retrieve the fileList.
701 * @return the fileList
703 public FileList getFileList() {
707 public SearchResults getSearchResults() {
708 return searchResults;
712 * Retrieve the topPanel.
714 * @return the topPanel
716 TopPanel getTopPanel() {
721 * Retrieve the clipboard.
723 * @return the clipboard
725 public Clipboard getClipboard() {
729 public StatusPanel getStatusPanel() {
734 * Retrieve the userDetailsPanel.
736 * @return the userDetailsPanel
738 public UserDetailsPanel getUserDetailsPanel() {
739 return userDetailsPanel;
743 * Retrieve the dragController.
745 * @return the dragController
747 public PickupDragController getDragController() {
748 return dragController;
751 public String getToken() {
755 public String getWebDAVPassword() {
756 return webDAVPassword;
759 public void removeGlassPanel() {
760 glassPanel.removeFromParent();
764 * Retrieve the currentUserResource.
766 * @return the currentUserResource
768 public UserResource getCurrentUserResource() {
769 return currentUserResource;
773 * Modify the currentUserResource.
775 * @param newUser the new currentUserResource
777 public void setCurrentUserResource(UserResource newUser) {
778 currentUserResource = newUser;
781 public static native void preventIESelection() /*-{
782 $doc.body.onselectstart = function () { return false; };
785 public static native void enableIESelection() /*-{
786 if ($doc.body.onselectstart != null)
787 $doc.body.onselectstart = null;
791 * @return the absolute path of the API root URL
793 public String getApiPath() {
794 Configuration conf = (Configuration) GWT.create(Configuration.class);
795 return GWT.getModuleBaseURL() + conf.apiPath();
798 public void refreshWebDAVPassword() {
799 Configuration conf = (Configuration) GWT.create(Configuration.class);
800 String domain = Window.Location.getHostName();
801 String path = Window.Location.getPath();
802 String cookie = conf.webdavCookie();
803 webDAVPassword = Cookies.getCookie(cookie);
804 Cookies.setCookie(cookie, "", null, domain, path, false);
808 * Convert server date to local time according to browser timezone
809 * and format it according to localized pattern.
810 * Time is always formatted to 24hr format.
811 * NB: This assumes that server runs in UTC timezone. Otherwise
812 * we would need to adjust for server time offset as well.
817 public static String formatLocalDateTime(Date date) {
818 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
819 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
820 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
821 String datePart = dateFormatter.format(convertedDate);
822 String timePart = timeFormatter.format(convertedDate);
823 return datePart + " " + timePart;
827 * History support for folder navigation
828 * adds a new browser history entry
832 public void updateHistory(String key){
833 // Replace any whitespace of the initial string to "+"
834 // String result = key.replaceAll("\\s","+");
835 // Add a new browser history entry.
836 // History.newItem(result);
837 History.newItem(key);
841 * This method examines the token input and add a "/" at the end in case it's omitted.
842 * This happens only in Files/trash/, Files/shared/, Files/others.
845 * @return the formated token with a "/" at the end or the same tokenInput parameter
848 private String handleSpecialFolderNames(String tokenInput){
849 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
850 if(pathsToCheck.contains(tokenInput))
851 return tokenInput + "/";
857 * Reject illegal resource names, like '.' or '..' or slashes '/'.
859 static boolean isValidResourceName(String name) {
860 if (".".equals(name) || "..".equals(name) || name.contains("/"))
865 public void putUserToMap(String _userName, String _userFullName){
866 userFullNameMap.put(_userName, _userFullName);
869 public String findUserFullName(String _userName){
870 return userFullNameMap.get(_userName);
873 public String getUserFullName(String _userName) {
874 if (GSS.get().findUserFullName(_userName) == null)
875 //if there is no userFullName found then the map fills with the given _userName,
876 //so userFullName = _userName
877 GSS.get().putUserToMap(_userName, _userName);
878 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
879 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
880 GetUserCommand guc = new GetUserCommand(_userName);
883 return GSS.get().findUserFullName(_userName);