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.rest.GetCommand;
23 import gr.ebs.gss.client.rest.RestException;
24 import gr.ebs.gss.client.rest.resource.FileResource;
25 import gr.ebs.gss.client.rest.resource.FolderResource;
26 import gr.ebs.gss.client.rest.resource.OtherUserResource;
27 import gr.ebs.gss.client.rest.resource.OthersResource;
28 import gr.ebs.gss.client.rest.resource.RestResource;
29 import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
30 import gr.ebs.gss.client.rest.resource.TrashResource;
31 import gr.ebs.gss.client.rest.resource.UserResource;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Date;
36 import java.util.HashMap;
37 import java.util.List;
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.i18n.client.DateTimeFormat;
48 import com.google.gwt.resources.client.ClientBundle;
49 import com.google.gwt.resources.client.ImageResource;
50 import com.google.gwt.user.client.Command;
51 import com.google.gwt.user.client.Cookies;
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.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.HasHorizontalAlignment;
59 import com.google.gwt.user.client.ui.HasVerticalAlignment;
60 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
61 import com.google.gwt.user.client.ui.RootPanel;
62 import com.google.gwt.user.client.ui.TabPanel;
63 import com.google.gwt.user.client.ui.VerticalPanel;
65 * Entry point classes define <code>onModuleLoad()</code>.
67 public class GSS implements EntryPoint, ResizeHandler {
70 * A constant that denotes the completion of an IncrementalCommand.
72 public static final boolean DONE = false;
74 public static final int VISIBLE_FILE_COUNT = 100;
77 * Instantiate an application-level image bundle. This object will provide
78 * programmatic access to all the images needed by widgets.
80 private static Images images = (Images) GWT.create(Images.class);
82 private GlassPanel glassPanel = new GlassPanel();
85 * An aggregate image bundle that pulls together all the images for this
86 * application into a single bundle.
88 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, CellTreeView.Images {
90 @Source("gr/ebs/gss/resources/document.png")
91 ImageResource folders();
93 @Source("gr/ebs/gss/resources/edit_group_22.png")
94 ImageResource groups();
96 @Source("gr/ebs/gss/resources/search.png")
97 ImageResource search();
101 * The single GSS instance.
103 private static GSS singleton;
106 * Gets the singleton GSS instance.
108 * @return the GSS object
110 public static GSS get() {
111 if (GSS.singleton == null)
112 GSS.singleton = new GSS();
113 return GSS.singleton;
117 * The Application Clipboard implementation;
119 private Clipboard clipboard = new Clipboard();
121 private UserResource currentUserResource;
124 * The top panel that contains the menu bar.
126 private TopPanel topPanel;
129 * The panel that contains the various system messages.
131 private MessagePanel messagePanel = new MessagePanel(GSS.images);
134 * The bottom panel that contains the status bar.
136 private StatusPanel statusPanel = new StatusPanel(GSS.images);
139 * The top right panel that displays the logged in user details
141 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
144 * The file list widget.
146 private FileList fileList;
149 * The group list widget.
151 private Groups groups = new Groups(images);
154 * The search result widget.
156 private SearchResults searchResults;
159 * The tab panel that occupies the right side of the screen.
161 private TabPanel inner = new DecoratedTabPanel();
164 * The split panel that will contain the left and right panels.
166 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
169 * The horizontal panel that will contain the search and status panels.
171 private DockPanel searchStatus = new DockPanel();
176 private Search search;
179 * The widget that displays the tree of folders.
182 private CellTreeView treeView = new CellTreeView(images);
184 * The currently selected item in the application, for use by the Edit menu
185 * commands. Potential types are Folder, File, User and Group.
187 private Object currentSelection;
190 * The authentication token of the current user.
192 private String token;
195 * The WebDAV password of the current user
197 private String webDAVPassword;
201 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
204 public void onModuleLoad() {
205 // Initialize the singleton before calling the constructors of the
206 // various widgets that might call GSS.get().
208 RootPanel.get().add(glassPanel, 0, 0);
209 parseUserCredentials();
211 topPanel = new TopPanel(GSS.images);
212 topPanel.setWidth("100%");
214 messagePanel.setWidth("100%");
215 messagePanel.setVisible(false);
217 search = new Search(images);
218 searchStatus.add(search, DockPanel.WEST);
219 searchStatus.add(userDetailsPanel, DockPanel.EAST);
220 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
221 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
222 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
223 searchStatus.setWidth("100%");
225 fileList = new FileList(images);
227 searchResults = new SearchResults(images);
229 // Inner contains the various lists.
230 inner.setAnimationEnabled(true);
231 inner.getTabBar().addStyleName("gss-MainTabBar");
232 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
233 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
235 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
236 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
237 //inner.add(new CellTreeView(images), createHeaderHTML(AbstractImagePrototype.create(images.search()), "Cell tree sample"), true);
238 inner.setWidth("100%");
241 inner.addSelectionHandler(new SelectionHandler<Integer>() {
244 public void onSelection(SelectionEvent<Integer> event) {
245 int tabIndex = event.getSelectedItem();
246 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
249 // Files tab selected
250 fileList.clearSelectedRows();
251 fileList.updateCurrentlyShowingStats();
254 // Groups tab selected
255 groups.updateCurrentlyShowingStats();
256 updateHistory("Groups");
259 // Search tab selected
260 searchResults.clearSelectedRows();
261 searchResults.updateCurrentlyShowingStats();
262 updateHistory("Search");
267 // If the application starts with no history token, redirect to a new "Files" state
268 String initToken = History.getToken();
269 if(initToken.length() == 0)
270 History.newItem("Files");
271 // Add history listener to handle any history events
272 History.addValueChangeHandler(new ValueChangeHandler<String>() {
274 public void onValueChange(ValueChangeEvent<String> event) {
275 String tokenInput = event.getValue();
276 String historyToken = handleSpecialFolderNames(tokenInput);
278 if(historyToken.equals("Search"))
280 else if(historyToken.equals("Groups"))
282 else if(historyToken.equals("Files")|| historyToken.length()==0)
286 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
287 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
288 SelectionEvent.fire(popupTree, treeObj);
291 } catch (IndexOutOfBoundsException e) {
297 // Add the left and right panels to the split panel.
298 splitPanel.setLeftWidget(treeView);
299 splitPanel.setRightWidget(inner);
300 splitPanel.setSplitPosition("25%");
301 splitPanel.setSize("100%", "100%");
302 splitPanel.addStyleName("gss-splitPanel");
304 // Create a dock panel that will contain the menu bar at the top,
305 // the shortcuts to the left, the status bar at the bottom and the
306 // right panel taking the rest.
307 VerticalPanel outer = new VerticalPanel();
309 outer.add(searchStatus);
310 outer.add(messagePanel);
311 outer.add(splitPanel);
312 outer.add(statusPanel);
313 outer.setWidth("100%");
314 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
318 // Hook the window resize event, so that we can adjust the UI.
319 Window.addResizeHandler(this);
320 // Clear out the window's built-in margin, because we want to take
321 // advantage of the entire client area.
322 Window.setMargin("0px");
323 // Finally, add the outer panel to the RootPanel, so that it will be
325 RootPanel.get().add(outer);
326 // Call the window resized handler to get the initial sizes setup. Doing
327 // this in a deferred command causes it to occur after all widgets'
328 // sizes have been computed by the browser.
329 DeferredCommand.addCommand(new Command() {
332 public void execute() {
333 onWindowResized(Window.getClientHeight());
339 * Fetches the User object for the specified username.
341 * @param username the username of the user
343 private void fetchUser(final String username) {
344 String path = getApiPath() + username + "/";
345 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
348 public void onComplete() {
349 currentUserResource = getResult();
350 final String announcement = currentUserResource.getAnnouncement();
351 if (announcement != null)
352 DeferredCommand.addCommand(new Command() {
355 public void execute() {
356 displayInformation(announcement);
362 public void onError(Throwable t) {
363 GWT.log("Fetching user error", t);
364 if (t instanceof RestException)
365 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
367 GSS.get().displayError("System error fetching user data:" + t.getMessage());
371 DeferredCommand.addCommand(getUserCommand);
375 * Parse and store the user credentials to the appropriate fields.
377 private void parseUserCredentials() {
378 Configuration conf = (Configuration) GWT.create(Configuration.class);
379 String cookie = conf.authCookie();
380 String auth = Cookies.getCookie(cookie);
383 // Redundant, but silences warnings about possible auth NPE, below.
386 int sepIndex = auth.indexOf(conf.cookieSeparator());
389 token = auth.substring(sepIndex + 1);
390 final String username = auth.substring(0, sepIndex);
391 if (username == null)
394 refreshWebDAVPassword();
396 DeferredCommand.addCommand(new Command() {
399 public void execute() {
406 * Redirect the user to the login page for authentication.
408 protected void authenticateUser() {
409 Configuration conf = (Configuration) GWT.create(Configuration.class);
410 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
414 * Clear the cookie and redirect the user to the logout page.
417 Configuration conf = (Configuration) GWT.create(Configuration.class);
418 String cookie = conf.authCookie();
419 String domain = Window.Location.getHostName();
420 String path = Window.Location.getPath();
421 Cookies.setCookie(cookie, "", null, domain, path, false);
422 Window.Location.assign(conf.logoutUrl());
426 * Creates an HTML fragment that places an image & caption together, for use
429 * @param imageProto an image prototype for an image
430 * @param caption the group caption
431 * @return the header HTML fragment
433 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
434 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>";
438 private void onWindowResized(int height) {
439 // Adjust the split panel to take up the available room in the window.
440 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
443 splitPanel.setHeight("" + newHeight);
444 inner.setHeight("" + newHeight);
445 /*if(isFileListShowing()){
446 getFileList().setHeight("" + (newHeight-50));
451 public void onResize(ResizeEvent event) {
452 int height = event.getHeight();
453 onWindowResized(height);
456 public boolean isFileListShowing() {
457 int tab = inner.getTabBar().getSelectedTab();
463 public boolean isSearchResultsShowing() {
464 int tab = inner.getTabBar().getSelectedTab();
471 * Make the user list visible.
473 public void showUserList() {
478 * Make the file list visible.
480 public void showFileList() {
481 fileList.updateFileCache(false, true /*clear selection*/);
486 * Make the file list visible.
490 public void showFileList(boolean update) {
491 /*TreeItem currentFolder = getFolders().getCurrent();
492 if (currentFolder != null) {
493 List<FileResource> files = null;
494 Object cachedObject = currentFolder.getUserObject();
495 if (cachedObject instanceof FolderResource) {
496 FolderResource folder = (FolderResource) cachedObject;
497 files = folder.getFiles();
498 } else if (cachedObject instanceof TrashResource) {
499 TrashResource folder = (TrashResource) cachedObject;
500 files = folder.getFiles();
503 getFileList().setFiles(files);
505 RestResource currentFolder = getTreeView().getSelection();
506 GWT.log("SELECTED:"+currentFolder);
507 if(currentFolder!=null){
508 GWT.log("SELECTED:"+currentFolder.getClass());
509 List<FileResource> files = null;
510 if (currentFolder instanceof RestResourceWrapper) {
511 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
512 files = folder.getResource().getFiles();
513 } else if (currentFolder instanceof TrashResource) {
514 TrashResource folder = (TrashResource) currentFolder;
515 files = folder.getFiles();
517 else if(currentFolder instanceof OthersResource){
518 files = new ArrayList<FileResource>();
520 else if(currentFolder instanceof OtherUserResource){
521 files = ((OtherUserResource)currentFolder).getFiles();
524 getFileList().setFiles(files);
526 fileList.updateFileCache(update, true /*clear selection*/);
530 public void showFileList(RestResource r,boolean update) {
531 /*TreeItem currentFolder = getFolders().getCurrent();
532 if (currentFolder != null) {
533 List<FileResource> files = null;
534 Object cachedObject = currentFolder.getUserObject();
535 if (cachedObject instanceof FolderResource) {
536 FolderResource folder = (FolderResource) cachedObject;
537 files = folder.getFiles();
538 } else if (cachedObject instanceof TrashResource) {
539 TrashResource folder = (TrashResource) cachedObject;
540 files = folder.getFiles();
543 getFileList().setFiles(files);
545 RestResource currentFolder = r;
546 GWT.log("SELECTED:"+currentFolder);
547 if(currentFolder!=null){
548 List<FileResource> files = null;
549 if (currentFolder instanceof RestResourceWrapper) {
550 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
551 files = folder.getResource().getFiles();
552 } else if (currentFolder instanceof TrashResource) {
553 TrashResource folder = (TrashResource) currentFolder;
554 files = folder.getFiles();
557 getFileList().setFiles(files);
559 fileList.updateFileCache(update, true /*clear selection*/);
564 * Make the search results visible.
566 * @param query the search query string
568 public void showSearchResults(String query) {
569 searchResults.updateFileCache(query);
570 searchResults.updateCurrentlyShowingStats();
575 * Display the 'loading' indicator.
577 public void showLoadingIndicator() {
578 topPanel.getLoading().setVisible(true);
582 * Hide the 'loading' indicator.
584 public void hideLoadingIndicator() {
585 topPanel.getLoading().setVisible(false);
589 * A native JavaScript method to reach out to the browser's window and
590 * invoke its resizeTo() method.
592 * @param x the new width
593 * @param y the new height
595 public static native void resizeTo(int x, int y) /*-{
600 * A helper method that returns true if the user's list is currently visible
601 * and false if it is hidden.
603 * @return true if the user list is visible
605 public boolean isUserListVisible() {
606 return inner.getTabBar().getSelectedTab() == 1;
610 * Display an error message.
612 * @param msg the message to display
614 public void displayError(String msg) {
615 messagePanel.displayError(msg);
619 * Display a warning message.
621 * @param msg the message to display
623 public void displayWarning(String msg) {
624 messagePanel.displayWarning(msg);
628 * Display an informational message.
630 * @param msg the message to display
632 public void displayInformation(String msg) {
633 messagePanel.displayInformation(msg);
637 * Retrieve the folders.
639 * @return the folders
641 public Folders getFolders() {
646 * Retrieve the search.
655 * Retrieve the currentSelection.
657 * @return the currentSelection
659 public Object getCurrentSelection() {
660 return currentSelection;
664 * Modify the currentSelection.
666 * @param newCurrentSelection the currentSelection to set
668 public void setCurrentSelection(Object newCurrentSelection) {
669 currentSelection = newCurrentSelection;
673 * Retrieve the groups.
677 public Groups getGroups() {
682 * Retrieve the fileList.
684 * @return the fileList
686 public FileList getFileList() {
690 public SearchResults getSearchResults() {
691 return searchResults;
695 * Retrieve the topPanel.
697 * @return the topPanel
699 TopPanel getTopPanel() {
704 * Retrieve the clipboard.
706 * @return the clipboard
708 public Clipboard getClipboard() {
712 public StatusPanel getStatusPanel() {
717 * Retrieve the userDetailsPanel.
719 * @return the userDetailsPanel
721 public UserDetailsPanel getUserDetailsPanel() {
722 return userDetailsPanel;
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 * Convert server date to local time according to browser timezone
785 * and format it according to localized pattern.
786 * Time is always formatted to 24hr format.
787 * NB: This assumes that server runs in UTC timezone. Otherwise
788 * we would need to adjust for server time offset as well.
793 public static String formatLocalDateTime(Date date) {
794 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
795 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
796 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
797 String datePart = dateFormatter.format(convertedDate);
798 String timePart = timeFormatter.format(convertedDate);
799 return datePart + " " + timePart;
803 * History support for folder navigation
804 * adds a new browser history entry
808 public void updateHistory(String key){
809 // Replace any whitespace of the initial string to "+"
810 // String result = key.replaceAll("\\s","+");
811 // Add a new browser history entry.
812 // History.newItem(result);
813 History.newItem(key);
817 * This method examines the token input and add a "/" at the end in case it's omitted.
818 * This happens only in Files/trash/, Files/shared/, Files/others.
821 * @return the formated token with a "/" at the end or the same tokenInput parameter
824 private String handleSpecialFolderNames(String tokenInput){
825 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
826 if(pathsToCheck.contains(tokenInput))
827 return tokenInput + "/";
833 * Reject illegal resource names, like '.' or '..' or slashes '/'.
835 static boolean isValidResourceName(String name) {
836 if (".".equals(name) || "..".equals(name) || name.contains("/"))
841 public void putUserToMap(String _userName, String _userFullName){
842 userFullNameMap.put(_userName, _userFullName);
845 public String findUserFullName(String _userName){
846 return userFullNameMap.get(_userName);
850 * Retrieve the treeView.
852 * @return the treeView
854 public CellTreeView getTreeView() {
858 public void onResourceUpdate(RestResource resource){
859 if(resource instanceof RestResourceWrapper){
860 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
861 showFileList(resource,true);