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.rest.GetCommand;
24 import gr.ebs.gss.client.rest.RestException;
25 import gr.ebs.gss.client.rest.resource.FileResource;
26 import gr.ebs.gss.client.rest.resource.OtherUserResource;
27 import gr.ebs.gss.client.rest.resource.RestResource;
28 import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
29 import gr.ebs.gss.client.rest.resource.SharedResource;
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.DOM;
53 import com.google.gwt.user.client.DeferredCommand;
54 import com.google.gwt.user.client.Event;
55 import com.google.gwt.user.client.History;
56 import com.google.gwt.user.client.Window;
57 import com.google.gwt.user.client.ui.AbstractImagePrototype;
58 import com.google.gwt.user.client.ui.DecoratedTabPanel;
59 import com.google.gwt.user.client.ui.DockPanel;
60 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
61 import com.google.gwt.user.client.ui.HasVerticalAlignment;
62 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
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.VerticalPanel;
67 * Entry point classes define <code>onModuleLoad()</code>.
69 public class GSS implements EntryPoint, ResizeHandler {
72 * A constant that denotes the completion of an IncrementalCommand.
74 public static final boolean DONE = false;
76 public static final int VISIBLE_FILE_COUNT = 25;
79 * Instantiate an application-level image bundle. This object will provide
80 * programmatic access to all the images needed by widgets.
82 private static Images images = (Images) GWT.create(Images.class);
84 private GlassPanel glassPanel = new GlassPanel();
87 * An aggregate image bundle that pulls together all the images for this
88 * application into a single bundle.
90 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 {
92 @Source("gr/ebs/gss/resources/document.png")
93 ImageResource folders();
95 @Source("gr/ebs/gss/resources/edit_group_22.png")
96 ImageResource groups();
98 @Source("gr/ebs/gss/resources/search.png")
99 ImageResource search();
103 * The single GSS instance.
105 private static GSS singleton;
108 * Gets the singleton GSS instance.
110 * @return the GSS object
112 public static GSS get() {
113 if (GSS.singleton == null)
114 GSS.singleton = new GSS();
115 return GSS.singleton;
119 * The Application Clipboard implementation;
121 private Clipboard clipboard = new Clipboard();
123 private UserResource currentUserResource;
126 * The top panel that contains the menu bar.
128 private TopPanel topPanel;
131 * The panel that contains the various system messages.
133 private MessagePanel messagePanel = new MessagePanel(GSS.images);
136 * The bottom panel that contains the status bar.
138 private StatusPanel statusPanel = new StatusPanel(GSS.images);
141 * The top right panel that displays the logged in user details
143 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
146 * The file list widget.
148 private FileList fileList;
151 * The group list widget.
153 private Groups groups = new Groups(images);
156 * The search result widget.
158 private SearchResults searchResults;
161 * The tab panel that occupies the right side of the screen.
163 private TabPanel inner = new DecoratedTabPanel(){
165 public void onBrowserEvent(com.google.gwt.user.client.Event event) {
166 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
167 if(isFileListShowing()){
168 getFileList().showContextMenu(event);
175 * The split panel that will contain the left and right panels.
177 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
180 * The horizontal panel that will contain the search and status panels.
182 private DockPanel searchStatus = new DockPanel();
187 private Search search;
190 * The widget that displays the tree of folders.
193 private CellTreeView treeView = new CellTreeView(images);
195 * The currently selected item in the application, for use by the Edit menu
196 * commands. Potential types are Folder, File, User and Group.
198 private Object currentSelection;
201 * The authentication token of the current user.
203 private String token;
206 * The WebDAV password of the current user
208 private String webDAVPassword;
212 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
215 public void onModuleLoad() {
216 // Initialize the singleton before calling the constructors of the
217 // various widgets that might call GSS.get().
219 RootPanel.get().add(glassPanel, 0, 0);
220 parseUserCredentials();
222 topPanel = new TopPanel(GSS.images);
223 topPanel.setWidth("100%");
225 messagePanel.setWidth("100%");
226 messagePanel.setVisible(false);
228 search = new Search(images);
229 searchStatus.add(search, DockPanel.WEST);
230 searchStatus.add(userDetailsPanel, DockPanel.EAST);
231 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
232 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
233 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
234 searchStatus.setWidth("100%");
236 fileList = new FileList(images);
238 searchResults = new SearchResults(images);
240 // Inner contains the various lists.
241 inner.sinkEvents(Event.ONCONTEXTMENU);
242 inner.setAnimationEnabled(true);
243 inner.getTabBar().addStyleName("gss-MainTabBar");
244 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
245 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
247 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
248 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
249 //inner.add(new CellTreeView(images), createHeaderHTML(AbstractImagePrototype.create(images.search()), "Cell tree sample"), true);
250 inner.setWidth("100%");
253 inner.addSelectionHandler(new SelectionHandler<Integer>() {
256 public void onSelection(SelectionEvent<Integer> event) {
257 int tabIndex = event.getSelectedItem();
258 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
261 // Files tab selected
262 fileList.clearSelectedRows();
263 fileList.updateCurrentlyShowingStats();
266 // Groups tab selected
267 groups.updateCurrentlyShowingStats();
268 updateHistory("Groups");
271 // Search tab selected
272 searchResults.clearSelectedRows();
273 searchResults.updateCurrentlyShowingStats();
274 updateHistory("Search");
279 // If the application starts with no history token, redirect to a new "Files" state
280 String initToken = History.getToken();
281 if(initToken.length() == 0)
282 History.newItem("Files");
283 // Add history listener to handle any history events
284 History.addValueChangeHandler(new ValueChangeHandler<String>() {
286 public void onValueChange(ValueChangeEvent<String> event) {
287 String tokenInput = event.getValue();
288 String historyToken = handleSpecialFolderNames(tokenInput);
290 if(historyToken.equals("Search"))
292 else if(historyToken.equals("Groups"))
294 else if(historyToken.equals("Files")|| historyToken.length()==0)
298 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
299 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
300 SelectionEvent.fire(popupTree, treeObj);
303 } catch (IndexOutOfBoundsException e) {
309 // Add the left and right panels to the split panel.
310 splitPanel.setLeftWidget(treeView);
311 splitPanel.setRightWidget(inner);
312 splitPanel.setSplitPosition("25%");
313 splitPanel.setSize("100%", "100%");
314 splitPanel.addStyleName("gss-splitPanel");
316 // Create a dock panel that will contain the menu bar at the top,
317 // the shortcuts to the left, the status bar at the bottom and the
318 // right panel taking the rest.
319 VerticalPanel outer = new VerticalPanel();
321 outer.add(searchStatus);
322 outer.add(messagePanel);
323 outer.add(splitPanel);
324 outer.add(statusPanel);
325 outer.setWidth("100%");
326 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
330 // Hook the window resize event, so that we can adjust the UI.
331 Window.addResizeHandler(this);
332 // Clear out the window's built-in margin, because we want to take
333 // advantage of the entire client area.
334 Window.setMargin("0px");
335 // Finally, add the outer panel to the RootPanel, so that it will be
337 RootPanel.get().add(outer);
338 // Call the window resized handler to get the initial sizes setup. Doing
339 // this in a deferred command causes it to occur after all widgets'
340 // sizes have been computed by the browser.
341 DeferredCommand.addCommand(new Command() {
344 public void execute() {
345 onWindowResized(Window.getClientHeight());
351 * Fetches the User object for the specified username.
353 * @param username the username of the user
355 private void fetchUser(final String username) {
356 String path = getApiPath() + username + "/";
357 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
360 public void onComplete() {
362 currentUserResource = getResult();
363 final String announcement = currentUserResource.getAnnouncement();
364 if (announcement != null)
365 DeferredCommand.addCommand(new Command() {
368 public void execute() {
369 displayInformation(announcement);
375 public void onError(Throwable t) {
376 GWT.log("Fetching user error", t);
377 if (t instanceof RestException)
378 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
380 GSS.get().displayError("System error fetching user data:" + t.getMessage());
384 DeferredCommand.addCommand(getUserCommand);
388 * Parse and store the user credentials to the appropriate fields.
390 private void parseUserCredentials() {
391 Configuration conf = (Configuration) GWT.create(Configuration.class);
392 String cookie = conf.authCookie();
393 String auth = Cookies.getCookie(cookie);
396 // Redundant, but silences warnings about possible auth NPE, below.
399 int sepIndex = auth.indexOf(conf.cookieSeparator());
402 token = auth.substring(sepIndex + 1);
403 final String username = auth.substring(0, sepIndex);
404 if (username == null)
407 refreshWebDAVPassword();
409 DeferredCommand.addCommand(new Command() {
412 public void execute() {
419 * Redirect the user to the login page for authentication.
421 protected void authenticateUser() {
422 Configuration conf = (Configuration) GWT.create(Configuration.class);
423 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
427 * Clear the cookie and redirect the user to the logout page.
430 Configuration conf = (Configuration) GWT.create(Configuration.class);
431 String cookie = conf.authCookie();
432 String domain = Window.Location.getHostName();
433 String path = Window.Location.getPath();
434 Cookies.setCookie(cookie, "", null, domain, path, false);
435 Window.Location.assign(conf.logoutUrl());
439 * Creates an HTML fragment that places an image & caption together, for use
442 * @param imageProto an image prototype for an image
443 * @param caption the group caption
444 * @return the header HTML fragment
446 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
447 String captionHTML = "<table class='caption' cellpadding='0' "
448 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
449 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
450 + caption + "</b></td></tr></table>";
454 private void onWindowResized(int height) {
455 // Adjust the split panel to take up the available room in the window.
456 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
459 splitPanel.setHeight("" + newHeight);
460 inner.setHeight("" + newHeight);
461 /*if(isFileListShowing()){
462 getFileList().setHeight("" + (newHeight-50));
467 public void onResize(ResizeEvent event) {
468 int height = event.getHeight();
469 onWindowResized(height);
472 public boolean isFileListShowing() {
473 int tab = inner.getTabBar().getSelectedTab();
479 public boolean isSearchResultsShowing() {
480 int tab = inner.getTabBar().getSelectedTab();
487 * Make the user list visible.
489 public void showUserList() {
494 * Make the file list visible.
496 public void showFileList() {
497 fileList.updateFileCache(true /*clear selection*/);
502 * Make the file list visible.
506 public void showFileList(boolean update) {
508 getTreeView().refreshCurrentNode();
511 RestResource currentFolder = getTreeView().getSelection();
512 if(currentFolder!=null){
513 showFileList(currentFolder);
519 public void showFileList(RestResource r) {
520 RestResource currentFolder = r;
521 if(currentFolder!=null){
522 List<FileResource> files = null;
523 if (currentFolder instanceof RestResourceWrapper) {
524 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
525 files = folder.getResource().getFiles();
526 } else if (currentFolder instanceof TrashResource) {
527 TrashResource folder = (TrashResource) currentFolder;
528 files = folder.getFiles();
530 else if (currentFolder instanceof SharedResource) {
531 SharedResource folder = (SharedResource) currentFolder;
532 files = folder.getFiles();
534 else if (currentFolder instanceof OtherUserResource) {
535 OtherUserResource folder = (OtherUserResource) currentFolder;
536 files = folder.getFiles();
539 getFileList().setFiles(files);
541 getFileList().setFiles(new ArrayList<FileResource>());
543 fileList.updateFileCache(true /*clear selection*/);
548 * Make the search results visible.
550 * @param query the search query string
552 public void showSearchResults(String query) {
553 searchResults.updateFileCache(query);
554 searchResults.updateCurrentlyShowingStats();
559 * Display the 'loading' indicator.
561 public void showLoadingIndicator() {
562 topPanel.getLoading().setVisible(true);
566 * Hide the 'loading' indicator.
568 public void hideLoadingIndicator() {
569 topPanel.getLoading().setVisible(false);
573 * A native JavaScript method to reach out to the browser's window and
574 * invoke its resizeTo() method.
576 * @param x the new width
577 * @param y the new height
579 public static native void resizeTo(int x, int y) /*-{
584 * A helper method that returns true if the user's list is currently visible
585 * and false if it is hidden.
587 * @return true if the user list is visible
589 public boolean isUserListVisible() {
590 return inner.getTabBar().getSelectedTab() == 1;
594 * Display an error message.
596 * @param msg the message to display
598 public void displayError(String msg) {
599 messagePanel.displayError(msg);
603 * Display a warning message.
605 * @param msg the message to display
607 public void displayWarning(String msg) {
608 messagePanel.displayWarning(msg);
612 * Display an informational message.
614 * @param msg the message to display
616 public void displayInformation(String msg) {
617 messagePanel.displayInformation(msg);
621 * Retrieve the folders.
623 * @return the folders
625 public Folders getFolders() {
630 * Retrieve the search.
639 * Retrieve the currentSelection.
641 * @return the currentSelection
643 public Object getCurrentSelection() {
644 return currentSelection;
648 * Modify the currentSelection.
650 * @param newCurrentSelection the currentSelection to set
652 public void setCurrentSelection(Object newCurrentSelection) {
653 currentSelection = newCurrentSelection;
657 * Retrieve the groups.
661 public Groups getGroups() {
666 * Retrieve the fileList.
668 * @return the fileList
670 public FileList getFileList() {
674 public SearchResults getSearchResults() {
675 return searchResults;
679 * Retrieve the topPanel.
681 * @return the topPanel
683 TopPanel getTopPanel() {
688 * Retrieve the clipboard.
690 * @return the clipboard
692 public Clipboard getClipboard() {
696 public StatusPanel getStatusPanel() {
701 * Retrieve the userDetailsPanel.
703 * @return the userDetailsPanel
705 public UserDetailsPanel getUserDetailsPanel() {
706 return userDetailsPanel;
711 public String getToken() {
715 public String getWebDAVPassword() {
716 return webDAVPassword;
719 public void removeGlassPanel() {
720 glassPanel.removeFromParent();
724 * Retrieve the currentUserResource.
726 * @return the currentUserResource
728 public UserResource getCurrentUserResource() {
729 return currentUserResource;
733 * Modify the currentUserResource.
735 * @param newUser the new currentUserResource
737 public void setCurrentUserResource(UserResource newUser) {
738 currentUserResource = newUser;
741 public static native void preventIESelection() /*-{
742 $doc.body.onselectstart = function () { return false; };
745 public static native void enableIESelection() /*-{
746 if ($doc.body.onselectstart != null)
747 $doc.body.onselectstart = null;
751 * @return the absolute path of the API root URL
753 public String getApiPath() {
754 Configuration conf = (Configuration) GWT.create(Configuration.class);
755 return GWT.getModuleBaseURL() + conf.apiPath();
758 public void refreshWebDAVPassword() {
759 Configuration conf = (Configuration) GWT.create(Configuration.class);
760 String domain = Window.Location.getHostName();
761 String path = Window.Location.getPath();
762 String cookie = conf.webdavCookie();
763 webDAVPassword = Cookies.getCookie(cookie);
764 Cookies.setCookie(cookie, "", null, domain, path, false);
768 * Convert server date to local time according to browser timezone
769 * and format it according to localized pattern.
770 * Time is always formatted to 24hr format.
771 * NB: This assumes that server runs in UTC timezone. Otherwise
772 * we would need to adjust for server time offset as well.
777 public static String formatLocalDateTime(Date date) {
778 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
779 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
780 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
781 String datePart = dateFormatter.format(convertedDate);
782 String timePart = timeFormatter.format(convertedDate);
783 return datePart + " " + timePart;
787 * History support for folder navigation
788 * adds a new browser history entry
792 public void updateHistory(String key){
793 // Replace any whitespace of the initial string to "+"
794 // String result = key.replaceAll("\\s","+");
795 // Add a new browser history entry.
796 // History.newItem(result);
797 History.newItem(key);
801 * This method examines the token input and add a "/" at the end in case it's omitted.
802 * This happens only in Files/trash/, Files/shared/, Files/others.
805 * @return the formated token with a "/" at the end or the same tokenInput parameter
808 private String handleSpecialFolderNames(String tokenInput){
809 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
810 if(pathsToCheck.contains(tokenInput))
811 return tokenInput + "/";
817 * Reject illegal resource names, like '.' or '..' or slashes '/'.
819 static boolean isValidResourceName(String name) {
820 if (".".equals(name) || "..".equals(name) || name.contains("/"))
825 public void putUserToMap(String _userName, String _userFullName){
826 userFullNameMap.put(_userName, _userFullName);
829 public String findUserFullName(String _userName){
830 return userFullNameMap.get(_userName);
832 public String getUserFullName(String _userName) {
834 if (GSS.get().findUserFullName(_userName) == null)
835 //if there is no userFullName found then the map fills with the given _userName,
836 //so userFullName = _userName
837 GSS.get().putUserToMap(_userName, _userName);
838 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
839 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
840 GetUserCommand guc = new GetUserCommand(_userName);
843 return GSS.get().findUserFullName(_userName);
846 * Retrieve the treeView.
848 * @return the treeView
850 public CellTreeView getTreeView() {
854 public void onResourceUpdate(RestResource resource){
855 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
856 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
857 showFileList(resource);