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.RestResource;
27 import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
28 import gr.ebs.gss.client.rest.resource.TrashResource;
29 import gr.ebs.gss.client.rest.resource.UserResource;
31 import java.util.Arrays;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.List;
36 import com.google.gwt.core.client.EntryPoint;
37 import com.google.gwt.core.client.GWT;
38 import com.google.gwt.event.logical.shared.ResizeEvent;
39 import com.google.gwt.event.logical.shared.ResizeHandler;
40 import com.google.gwt.event.logical.shared.SelectionEvent;
41 import com.google.gwt.event.logical.shared.SelectionHandler;
42 import com.google.gwt.event.logical.shared.ValueChangeEvent;
43 import com.google.gwt.event.logical.shared.ValueChangeHandler;
44 import com.google.gwt.i18n.client.DateTimeFormat;
45 import com.google.gwt.resources.client.ClientBundle;
46 import com.google.gwt.resources.client.ImageResource;
47 import com.google.gwt.user.client.Command;
48 import com.google.gwt.user.client.Cookies;
49 import com.google.gwt.user.client.DeferredCommand;
50 import com.google.gwt.user.client.History;
51 import com.google.gwt.user.client.Window;
52 import com.google.gwt.user.client.ui.AbstractImagePrototype;
53 import com.google.gwt.user.client.ui.DecoratedTabPanel;
54 import com.google.gwt.user.client.ui.DockPanel;
55 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
56 import com.google.gwt.user.client.ui.HasVerticalAlignment;
57 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
58 import com.google.gwt.user.client.ui.RootPanel;
59 import com.google.gwt.user.client.ui.TabPanel;
60 import com.google.gwt.user.client.ui.VerticalPanel;
62 * Entry point classes define <code>onModuleLoad()</code>.
64 public class GSS implements EntryPoint, ResizeHandler {
67 * A constant that denotes the completion of an IncrementalCommand.
69 public static final boolean DONE = false;
71 public static final int VISIBLE_FILE_COUNT = 100;
74 * Instantiate an application-level image bundle. This object will provide
75 * programmatic access to all the images needed by widgets.
77 private static Images images = (Images) GWT.create(Images.class);
79 private GlassPanel glassPanel = new GlassPanel();
82 * An aggregate image bundle that pulls together all the images for this
83 * application into a single bundle.
85 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 {
87 @Source("gr/ebs/gss/resources/document.png")
88 ImageResource folders();
90 @Source("gr/ebs/gss/resources/edit_group_22.png")
91 ImageResource groups();
93 @Source("gr/ebs/gss/resources/search.png")
94 ImageResource search();
98 * The single GSS instance.
100 private static GSS singleton;
103 * Gets the singleton GSS instance.
105 * @return the GSS object
107 public static GSS get() {
108 if (GSS.singleton == null)
109 GSS.singleton = new GSS();
110 return GSS.singleton;
114 * The Application Clipboard implementation;
116 private Clipboard clipboard = new Clipboard();
118 private UserResource currentUserResource;
121 * The top panel that contains the menu bar.
123 private TopPanel topPanel;
126 * The panel that contains the various system messages.
128 private MessagePanel messagePanel = new MessagePanel(GSS.images);
131 * The bottom panel that contains the status bar.
133 private StatusPanel statusPanel = new StatusPanel(GSS.images);
136 * The top right panel that displays the logged in user details
138 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
141 * The file list widget.
143 private FileList fileList;
146 * The group list widget.
148 private Groups groups = new Groups(images);
151 * The search result widget.
153 private SearchResults searchResults;
156 * The tab panel that occupies the right side of the screen.
158 private TabPanel inner = new DecoratedTabPanel();
161 * The split panel that will contain the left and right panels.
163 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
166 * The horizontal panel that will contain the search and status panels.
168 private DockPanel searchStatus = new DockPanel();
173 private Search search;
176 * The widget that displays the tree of folders.
179 private CellTreeView treeView = new CellTreeView(images);
181 * The currently selected item in the application, for use by the Edit menu
182 * commands. Potential types are Folder, File, User and Group.
184 private Object currentSelection;
187 * The authentication token of the current user.
189 private String token;
192 * The WebDAV password of the current user
194 private String webDAVPassword;
198 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
201 public void onModuleLoad() {
202 // Initialize the singleton before calling the constructors of the
203 // various widgets that might call GSS.get().
205 RootPanel.get().add(glassPanel, 0, 0);
206 parseUserCredentials();
208 topPanel = new TopPanel(GSS.images);
209 topPanel.setWidth("100%");
211 messagePanel.setWidth("100%");
212 messagePanel.setVisible(false);
214 search = new Search(images);
215 searchStatus.add(search, DockPanel.WEST);
216 searchStatus.add(userDetailsPanel, DockPanel.EAST);
217 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
218 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
219 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
220 searchStatus.setWidth("100%");
222 fileList = new FileList(images);
224 searchResults = new SearchResults(images);
226 // Inner contains the various lists.
227 inner.setAnimationEnabled(true);
228 inner.getTabBar().addStyleName("gss-MainTabBar");
229 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
230 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
232 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
233 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
234 //inner.add(new CellTreeView(images), createHeaderHTML(AbstractImagePrototype.create(images.search()), "Cell tree sample"), true);
235 inner.setWidth("100%");
238 inner.addSelectionHandler(new SelectionHandler<Integer>() {
241 public void onSelection(SelectionEvent<Integer> event) {
242 int tabIndex = event.getSelectedItem();
243 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
246 // Files tab selected
247 fileList.clearSelectedRows();
248 fileList.updateCurrentlyShowingStats();
251 // Groups tab selected
252 groups.updateCurrentlyShowingStats();
253 updateHistory("Groups");
256 // Search tab selected
257 searchResults.clearSelectedRows();
258 searchResults.updateCurrentlyShowingStats();
259 updateHistory("Search");
264 // If the application starts with no history token, redirect to a new "Files" state
265 String initToken = History.getToken();
266 if(initToken.length() == 0)
267 History.newItem("Files");
268 // Add history listener to handle any history events
269 History.addValueChangeHandler(new ValueChangeHandler<String>() {
271 public void onValueChange(ValueChangeEvent<String> event) {
272 String tokenInput = event.getValue();
273 String historyToken = handleSpecialFolderNames(tokenInput);
275 if(historyToken.equals("Search"))
277 else if(historyToken.equals("Groups"))
279 else if(historyToken.equals("Files")|| historyToken.length()==0)
283 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
284 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
285 SelectionEvent.fire(popupTree, treeObj);
288 } catch (IndexOutOfBoundsException e) {
294 // Add the left and right panels to the split panel.
295 splitPanel.setLeftWidget(treeView);
296 splitPanel.setRightWidget(inner);
297 splitPanel.setSplitPosition("25%");
298 splitPanel.setSize("100%", "100%");
299 splitPanel.addStyleName("gss-splitPanel");
301 // Create a dock panel that will contain the menu bar at the top,
302 // the shortcuts to the left, the status bar at the bottom and the
303 // right panel taking the rest.
304 VerticalPanel outer = new VerticalPanel();
306 outer.add(searchStatus);
307 outer.add(messagePanel);
308 outer.add(splitPanel);
309 outer.add(statusPanel);
310 outer.setWidth("100%");
311 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
315 // Hook the window resize event, so that we can adjust the UI.
316 Window.addResizeHandler(this);
317 // Clear out the window's built-in margin, because we want to take
318 // advantage of the entire client area.
319 Window.setMargin("0px");
320 // Finally, add the outer panel to the RootPanel, so that it will be
322 RootPanel.get().add(outer);
323 // Call the window resized handler to get the initial sizes setup. Doing
324 // this in a deferred command causes it to occur after all widgets'
325 // sizes have been computed by the browser.
326 DeferredCommand.addCommand(new Command() {
329 public void execute() {
330 onWindowResized(Window.getClientHeight());
336 * Fetches the User object for the specified username.
338 * @param username the username of the user
340 private void fetchUser(final String username) {
341 String path = getApiPath() + username + "/";
342 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
345 public void onComplete() {
346 currentUserResource = getResult();
347 final String announcement = currentUserResource.getAnnouncement();
348 if (announcement != null)
349 DeferredCommand.addCommand(new Command() {
352 public void execute() {
353 displayInformation(announcement);
359 public void onError(Throwable t) {
360 GWT.log("Fetching user error", t);
361 if (t instanceof RestException)
362 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
364 GSS.get().displayError("System error fetching user data:" + t.getMessage());
368 DeferredCommand.addCommand(getUserCommand);
372 * Parse and store the user credentials to the appropriate fields.
374 private void parseUserCredentials() {
375 Configuration conf = (Configuration) GWT.create(Configuration.class);
376 String cookie = conf.authCookie();
377 String auth = Cookies.getCookie(cookie);
380 // Redundant, but silences warnings about possible auth NPE, below.
383 int sepIndex = auth.indexOf(conf.cookieSeparator());
386 token = auth.substring(sepIndex + 1);
387 final String username = auth.substring(0, sepIndex);
388 if (username == null)
391 refreshWebDAVPassword();
393 DeferredCommand.addCommand(new Command() {
396 public void execute() {
403 * Redirect the user to the login page for authentication.
405 protected void authenticateUser() {
406 Configuration conf = (Configuration) GWT.create(Configuration.class);
407 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
411 * Clear the cookie and redirect the user to the logout page.
414 Configuration conf = (Configuration) GWT.create(Configuration.class);
415 String cookie = conf.authCookie();
416 String domain = Window.Location.getHostName();
417 String path = Window.Location.getPath();
418 Cookies.setCookie(cookie, "", null, domain, path, false);
419 Window.Location.assign(conf.logoutUrl());
423 * Creates an HTML fragment that places an image & caption together, for use
426 * @param imageProto an image prototype for an image
427 * @param caption the group caption
428 * @return the header HTML fragment
430 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
431 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>";
435 private void onWindowResized(int height) {
436 // Adjust the split panel to take up the available room in the window.
437 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
440 splitPanel.setHeight("" + newHeight);
441 inner.setHeight("" + newHeight);
442 /*if(isFileListShowing()){
443 getFileList().setHeight("" + (newHeight-50));
448 public void onResize(ResizeEvent event) {
449 int height = event.getHeight();
450 onWindowResized(height);
453 public boolean isFileListShowing() {
454 int tab = inner.getTabBar().getSelectedTab();
460 public boolean isSearchResultsShowing() {
461 int tab = inner.getTabBar().getSelectedTab();
468 * Make the user list visible.
470 public void showUserList() {
475 * Make the file list visible.
477 public void showFileList() {
478 fileList.updateFileCache(false, true /*clear selection*/);
483 * Make the file list visible.
487 public void showFileList(boolean update) {
488 /*TreeItem currentFolder = getFolders().getCurrent();
489 if (currentFolder != null) {
490 List<FileResource> files = null;
491 Object cachedObject = currentFolder.getUserObject();
492 if (cachedObject instanceof FolderResource) {
493 FolderResource folder = (FolderResource) cachedObject;
494 files = folder.getFiles();
495 } else if (cachedObject instanceof TrashResource) {
496 TrashResource folder = (TrashResource) cachedObject;
497 files = folder.getFiles();
500 getFileList().setFiles(files);
502 RestResource currentFolder = getTreeView().getSelection();
503 GWT.log("SELECTED:"+currentFolder);
504 if(currentFolder!=null){
505 List<FileResource> files = null;
506 if (currentFolder instanceof RestResourceWrapper) {
507 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
508 files = folder.getResource().getFiles();
509 } else if (currentFolder instanceof TrashResource) {
510 TrashResource folder = (TrashResource) currentFolder;
511 files = folder.getFiles();
514 getFileList().setFiles(files);
516 fileList.updateFileCache(update, true /*clear selection*/);
520 public void showFileList(RestResource r,boolean update) {
521 /*TreeItem currentFolder = getFolders().getCurrent();
522 if (currentFolder != null) {
523 List<FileResource> files = null;
524 Object cachedObject = currentFolder.getUserObject();
525 if (cachedObject instanceof FolderResource) {
526 FolderResource folder = (FolderResource) cachedObject;
527 files = folder.getFiles();
528 } else if (cachedObject instanceof TrashResource) {
529 TrashResource folder = (TrashResource) cachedObject;
530 files = folder.getFiles();
533 getFileList().setFiles(files);
535 RestResource currentFolder = r;
536 GWT.log("SELECTED:"+currentFolder);
537 if(currentFolder!=null){
538 List<FileResource> files = null;
539 if (currentFolder instanceof RestResourceWrapper) {
540 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
541 files = folder.getResource().getFiles();
542 } else if (currentFolder instanceof TrashResource) {
543 TrashResource folder = (TrashResource) currentFolder;
544 files = folder.getFiles();
547 getFileList().setFiles(files);
549 fileList.updateFileCache(update, true /*clear selection*/);
554 * Make the search results visible.
556 * @param query the search query string
558 public void showSearchResults(String query) {
559 searchResults.updateFileCache(query);
560 searchResults.updateCurrentlyShowingStats();
565 * Display the 'loading' indicator.
567 public void showLoadingIndicator() {
568 topPanel.getLoading().setVisible(true);
572 * Hide the 'loading' indicator.
574 public void hideLoadingIndicator() {
575 topPanel.getLoading().setVisible(false);
579 * A native JavaScript method to reach out to the browser's window and
580 * invoke its resizeTo() method.
582 * @param x the new width
583 * @param y the new height
585 public static native void resizeTo(int x, int y) /*-{
590 * A helper method that returns true if the user's list is currently visible
591 * and false if it is hidden.
593 * @return true if the user list is visible
595 public boolean isUserListVisible() {
596 return inner.getTabBar().getSelectedTab() == 1;
600 * Display an error message.
602 * @param msg the message to display
604 public void displayError(String msg) {
605 messagePanel.displayError(msg);
609 * Display a warning message.
611 * @param msg the message to display
613 public void displayWarning(String msg) {
614 messagePanel.displayWarning(msg);
618 * Display an informational message.
620 * @param msg the message to display
622 public void displayInformation(String msg) {
623 messagePanel.displayInformation(msg);
627 * Retrieve the folders.
629 * @return the folders
631 public Folders getFolders() {
636 * Retrieve the search.
645 * Retrieve the currentSelection.
647 * @return the currentSelection
649 public Object getCurrentSelection() {
650 return currentSelection;
654 * Modify the currentSelection.
656 * @param newCurrentSelection the currentSelection to set
658 public void setCurrentSelection(Object newCurrentSelection) {
659 currentSelection = newCurrentSelection;
663 * Retrieve the groups.
667 public Groups getGroups() {
672 * Retrieve the fileList.
674 * @return the fileList
676 public FileList getFileList() {
680 public SearchResults getSearchResults() {
681 return searchResults;
685 * Retrieve the topPanel.
687 * @return the topPanel
689 TopPanel getTopPanel() {
694 * Retrieve the clipboard.
696 * @return the clipboard
698 public Clipboard getClipboard() {
702 public StatusPanel getStatusPanel() {
707 * Retrieve the userDetailsPanel.
709 * @return the userDetailsPanel
711 public UserDetailsPanel getUserDetailsPanel() {
712 return userDetailsPanel;
717 public String getToken() {
721 public String getWebDAVPassword() {
722 return webDAVPassword;
725 public void removeGlassPanel() {
726 glassPanel.removeFromParent();
730 * Retrieve the currentUserResource.
732 * @return the currentUserResource
734 public UserResource getCurrentUserResource() {
735 return currentUserResource;
739 * Modify the currentUserResource.
741 * @param newUser the new currentUserResource
743 public void setCurrentUserResource(UserResource newUser) {
744 currentUserResource = newUser;
747 public static native void preventIESelection() /*-{
748 $doc.body.onselectstart = function () { return false; };
751 public static native void enableIESelection() /*-{
752 if ($doc.body.onselectstart != null)
753 $doc.body.onselectstart = null;
757 * @return the absolute path of the API root URL
759 public String getApiPath() {
760 Configuration conf = (Configuration) GWT.create(Configuration.class);
761 return GWT.getModuleBaseURL() + conf.apiPath();
764 public void refreshWebDAVPassword() {
765 Configuration conf = (Configuration) GWT.create(Configuration.class);
766 String domain = Window.Location.getHostName();
767 String path = Window.Location.getPath();
768 String cookie = conf.webdavCookie();
769 webDAVPassword = Cookies.getCookie(cookie);
770 Cookies.setCookie(cookie, "", null, domain, path, false);
774 * Convert server date to local time according to browser timezone
775 * and format it according to localized pattern.
776 * Time is always formatted to 24hr format.
777 * NB: This assumes that server runs in UTC timezone. Otherwise
778 * we would need to adjust for server time offset as well.
783 public static String formatLocalDateTime(Date date) {
784 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
785 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
786 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
787 String datePart = dateFormatter.format(convertedDate);
788 String timePart = timeFormatter.format(convertedDate);
789 return datePart + " " + timePart;
793 * History support for folder navigation
794 * adds a new browser history entry
798 public void updateHistory(String key){
799 // Replace any whitespace of the initial string to "+"
800 // String result = key.replaceAll("\\s","+");
801 // Add a new browser history entry.
802 // History.newItem(result);
803 History.newItem(key);
807 * This method examines the token input and add a "/" at the end in case it's omitted.
808 * This happens only in Files/trash/, Files/shared/, Files/others.
811 * @return the formated token with a "/" at the end or the same tokenInput parameter
814 private String handleSpecialFolderNames(String tokenInput){
815 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
816 if(pathsToCheck.contains(tokenInput))
817 return tokenInput + "/";
823 * Reject illegal resource names, like '.' or '..' or slashes '/'.
825 static boolean isValidResourceName(String name) {
826 if (".".equals(name) || "..".equals(name) || name.contains("/"))
831 public void putUserToMap(String _userName, String _userFullName){
832 userFullNameMap.put(_userName, _userFullName);
835 public String findUserFullName(String _userName){
836 return userFullNameMap.get(_userName);
840 * Retrieve the treeView.
842 * @return the treeView
844 public CellTreeView getTreeView() {
848 public void onResourceUpdate(RestResource resource){
849 if(resource instanceof RestResourceWrapper){
850 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
851 showFileList(resource,true);