2 * Copyright (c) 2011 Greek Research and Technology Network
4 package gr.grnet.pithos.web.client;
6 import com.google.gwt.core.client.Scheduler;
7 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
8 import com.google.gwt.user.client.ui.DockPanel;
9 import com.google.gwt.user.client.ui.HasVerticalAlignment;
10 import gr.grnet.pithos.web.client.clipboard.Clipboard;
11 import gr.grnet.pithos.web.client.commands.GetUserCommand;
12 import gr.grnet.pithos.web.client.foldertree.AccountResource;
13 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
14 import gr.grnet.pithos.web.client.rest.GetRequest;
15 import gr.grnet.pithos.web.client.rest.RestException;
16 import gr.grnet.pithos.web.client.rest.resource.FileResource;
17 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
18 import gr.grnet.pithos.web.client.rest.resource.RestResource;
19 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
20 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
21 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
22 import gr.grnet.pithos.web.client.rest.resource.UserResource;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.List;
30 import com.google.gwt.core.client.EntryPoint;
31 import com.google.gwt.core.client.GWT;
32 import com.google.gwt.event.logical.shared.ResizeEvent;
33 import com.google.gwt.event.logical.shared.ResizeHandler;
34 import com.google.gwt.event.logical.shared.SelectionEvent;
35 import com.google.gwt.event.logical.shared.SelectionHandler;
36 import com.google.gwt.http.client.URL;
37 import com.google.gwt.i18n.client.DateTimeFormat;
38 import com.google.gwt.resources.client.ClientBundle;
39 import com.google.gwt.resources.client.ImageResource;
40 import com.google.gwt.user.client.Command;
41 import com.google.gwt.user.client.Cookies;
42 import com.google.gwt.user.client.DOM;
43 import com.google.gwt.user.client.DeferredCommand;
44 import com.google.gwt.user.client.Event;
45 import com.google.gwt.user.client.History;
46 import com.google.gwt.user.client.Window;
47 import com.google.gwt.user.client.ui.AbstractImagePrototype;
48 import com.google.gwt.user.client.ui.DecoratedTabPanel;
49 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
50 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
51 import com.google.gwt.user.client.ui.RootPanel;
52 import com.google.gwt.user.client.ui.TabPanel;
53 import com.google.gwt.user.client.ui.VerticalPanel;
56 * Entry point classes define <code>onModuleLoad()</code>.
58 public class GSS implements EntryPoint, ResizeHandler {
61 * A constant that denotes the completion of an IncrementalCommand.
63 public static final boolean DONE = false;
65 public static final int VISIBLE_FILE_COUNT = 25;
68 * Instantiate an application-level image bundle. This object will provide
69 * programmatic access to all the images needed by widgets.
71 private static Images images = (Images) GWT.create(Images.class);
73 public String getUsername() {
77 public void setAccount(AccountResource acct) {
81 public AccountResource getAccount() {
86 * An aggregate image bundle that pulls together all the images for this
87 * application into a single bundle.
89 public interface Images extends ClientBundle, TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images, Search.Images, CellTreeView.Images {
91 @Source("gr/grnet/pithos/resources/document.png")
92 ImageResource folders();
94 @Source("gr/grnet/pithos/resources/edit_group_22.png")
95 ImageResource groups();
97 @Source("gr/grnet/pithos/resources/search.png")
98 ImageResource search();
102 * The single GSS instance.
104 private static GSS singleton;
107 * Gets the singleton GSS instance.
109 * @return the GSS object
111 public static GSS get() {
112 if (GSS.singleton == null)
113 GSS.singleton = new GSS();
114 return GSS.singleton;
118 * The Application Clipboard implementation;
120 private Clipboard clipboard = new Clipboard();
122 private UserResource currentUserResource;
125 * The top panel that contains the menu bar.
127 private TopPanel topPanel;
130 * The panel that contains the various system messages.
132 private MessagePanel messagePanel = new MessagePanel(GSS.images);
135 * The bottom panel that contains the status bar.
137 private StatusPanel statusPanel = null;
140 * The top right panel that displays the logged in user details
142 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
145 * The file list widget.
147 private FileList fileList;
150 * The tab panel that occupies the right side of the screen.
152 private TabPanel inner = new DecoratedTabPanel(){
154 public void onBrowserEvent(com.google.gwt.user.client.Event event) {
155 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
156 if(isFileListShowing()){
157 getFileList().showContextMenu(event);
164 * The split panel that will contain the left and right panels.
166 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
169 * The widget that displays the tree of folders.
172 private CellTreeView treeView = null;
174 * The currently selected item in the application, for use by the Edit menu
175 * commands. Potential types are Folder, File, User and Group.
177 private Object currentSelection;
181 * The WebDAV password of the current user
183 private String webDAVPassword;
185 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
187 private String username = null;
190 * The authentication token of the current user.
192 private String token;
194 private FolderTreeView folderTreeView = new FolderTreeView();
196 private AccountResource account;
199 public void onModuleLoad() {
200 // Initialize the singleton before calling the constructors of the
201 // various widgets that might call GSS.get().
203 if (parseUserCredentials())
207 private void initialize() {
208 topPanel = new TopPanel(GSS.images);
209 topPanel.setWidth("100%");
211 messagePanel.setWidth("100%");
212 messagePanel.setVisible(false);
214 fileList = new FileList(images);
216 // Inner contains the various lists.
217 inner.sinkEvents(Event.ONCONTEXTMENU);
218 inner.setAnimationEnabled(true);
219 inner.getTabBar().addStyleName("pithos-MainTabBar");
220 inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
221 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
223 inner.setWidth("100%");
226 inner.addSelectionHandler(new SelectionHandler<Integer>() {
229 public void onSelection(SelectionEvent<Integer> event) {
230 int tabIndex = event.getSelectedItem();
233 fileList.updateCurrentlyShowingStats();
239 // Add the left and right panels to the split panel.
240 splitPanel.setLeftWidget(folderTreeView);
241 splitPanel.setRightWidget(inner);
242 splitPanel.setSplitPosition("25%");
243 splitPanel.setSize("100%", "100%");
244 splitPanel.addStyleName("pithos-splitPanel");
246 // Create a dock panel that will contain the menu bar at the top,
247 // the shortcuts to the left, the status bar at the bottom and the
248 // right panel taking the rest.
249 VerticalPanel outer = new VerticalPanel();
251 outer.add(messagePanel);
252 outer.add(splitPanel);
253 statusPanel = new StatusPanel(GSS.images);
254 outer.add(statusPanel);
255 outer.setWidth("100%");
256 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
260 // Hook the window resize event, so that we can adjust the UI.
261 Window.addResizeHandler(this);
262 // Clear out the window's built-in margin, because we want to take
263 // advantage of the entire client area.
264 Window.setMargin("0px");
265 // Finally, add the outer panel to the RootPanel, so that it will be
267 RootPanel.get().add(outer);
268 // Call the window resized handler to get the initial sizes setup. Doing
269 // this in a deferred command causes it to occur after all widgets'
270 // sizes have been computed by the browser.
271 DeferredCommand.addCommand(new Command() {
274 public void execute() {
275 onWindowResized(Window.getClientHeight());
281 * Parse and store the user credentials to the appropriate fields.
283 private boolean parseUserCredentials() {
284 Configuration conf = (Configuration) GWT.create(Configuration.class);
285 String cookie = conf.authCookie();
286 String auth = Cookies.getCookie(cookie);
292 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
293 if (authSplit.length != 2) {
298 username = authSplit[0];
299 token = authSplit[1];
306 * Redirect the user to the login page for authentication.
308 protected void authenticateUser() {
309 Configuration conf = (Configuration) GWT.create(Configuration.class);
311 // Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
312 Cookies.setCookie(conf.authCookie(), "demo" + conf.cookieSeparator() + "0000");
313 Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
317 * Clear the cookie and redirect the user to the logout page.
320 Configuration conf = (Configuration) GWT.create(Configuration.class);
321 String cookie = conf.authCookie();
322 String domain = Window.Location.getHostName();
323 String path = Window.Location.getPath();
324 Cookies.setCookie(cookie, "", null, domain, path, false);
325 String baseUrl = GWT.getModuleBaseURL();
326 String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
327 Window.Location.assign(homeUrl + conf.logoutUrl());
331 * Creates an HTML fragment that places an image & caption together, for use
334 * @param imageProto an image prototype for an image
335 * @param caption the group caption
336 * @return the header HTML fragment
338 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
339 String captionHTML = "<table class='caption' cellpadding='0' "
340 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
341 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
342 + caption + "</b></td></tr></table>";
346 private void onWindowResized(int height) {
347 // Adjust the split panel to take up the available room in the window.
348 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
351 splitPanel.setHeight("" + newHeight);
352 inner.setHeight("" + newHeight);
356 public void onResize(ResizeEvent event) {
357 int height = event.getHeight();
358 onWindowResized(height);
361 public boolean isFileListShowing() {
362 int tab = inner.getTabBar().getSelectedTab();
368 public boolean isSearchResultsShowing() {
369 int tab = inner.getTabBar().getSelectedTab();
376 * Make the user list visible.
378 public void showUserList() {
383 * Make the file list visible.
385 public void showFileList() {
386 fileList.updateFileCache(true /*clear selection*/);
391 * Make the file list visible.
395 public void showFileList(boolean update) {
397 getTreeView().refreshCurrentNode(true);
400 RestResource currentFolder = getTreeView().getSelection();
401 if(currentFolder!=null){
402 showFileList(currentFolder);
408 public void showFileList(RestResource r) {
409 showFileList(r,true);
412 public void showFileList(RestResource r, boolean clearSelection) {
413 RestResource currentFolder = r;
414 if(currentFolder!=null){
415 List<FileResource> files = null;
416 if (currentFolder instanceof RestResourceWrapper) {
417 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
418 files = folder.getResource().getFiles();
419 } else if (currentFolder instanceof TrashResource) {
420 TrashResource folder = (TrashResource) currentFolder;
421 files = folder.getFiles();
423 else if (currentFolder instanceof SharedResource) {
424 SharedResource folder = (SharedResource) currentFolder;
425 files = folder.getFiles();
427 else if (currentFolder instanceof OtherUserResource) {
428 OtherUserResource folder = (OtherUserResource) currentFolder;
429 files = folder.getFiles();
432 getFileList().setFiles(files);
434 getFileList().setFiles(new ArrayList<FileResource>());
436 fileList.updateFileCache(clearSelection /*clear selection*/);
441 * Display the 'loading' indicator.
443 public void showLoadingIndicator(String message, String path) {
445 String[] split = path.split("/");
446 message = message +" "+URL.decode(split[split.length-1]);
448 topPanel.getLoading().show(message);
452 * Hide the 'loading' indicator.
454 public void hideLoadingIndicator() {
455 topPanel.getLoading().hide();
459 * A native JavaScript method to reach out to the browser's window and
460 * invoke its resizeTo() method.
462 * @param x the new width
463 * @param y the new height
465 public static native void resizeTo(int x, int y) /*-{
470 * A helper method that returns true if the user's list is currently visible
471 * and false if it is hidden.
473 * @return true if the user list is visible
475 public boolean isUserListVisible() {
476 return inner.getTabBar().getSelectedTab() == 1;
480 * Display an error message.
482 * @param msg the message to display
484 public void displayError(String msg) {
485 messagePanel.displayError(msg);
489 * Display a warning message.
491 * @param msg the message to display
493 public void displayWarning(String msg) {
494 messagePanel.displayWarning(msg);
498 * Display an informational message.
500 * @param msg the message to display
502 public void displayInformation(String msg) {
503 messagePanel.displayInformation(msg);
507 * Retrieve the folders.
509 * @return the folders
511 public Folders getFolders() {
516 * Retrieve the currentSelection.
518 * @return the currentSelection
520 public Object getCurrentSelection() {
521 return currentSelection;
525 * Modify the currentSelection.
527 * @param newCurrentSelection the currentSelection to set
529 public void setCurrentSelection(Object newCurrentSelection) {
530 currentSelection = newCurrentSelection;
534 * Retrieve the fileList.
536 * @return the fileList
538 public FileList getFileList() {
543 * Retrieve the topPanel.
545 * @return the topPanel
547 TopPanel getTopPanel() {
552 * Retrieve the clipboard.
554 * @return the clipboard
556 public Clipboard getClipboard() {
560 public StatusPanel getStatusPanel() {
565 * Retrieve the userDetailsPanel.
567 * @return the userDetailsPanel
569 public UserDetailsPanel getUserDetailsPanel() {
570 return userDetailsPanel;
575 public String getToken() {
579 public String getWebDAVPassword() {
580 return webDAVPassword;
584 * Retrieve the currentUserResource.
586 * @return the currentUserResource
588 public UserResource getCurrentUserResource() {
589 return currentUserResource;
593 * Modify the currentUserResource.
595 * @param newUser the new currentUserResource
597 public void setCurrentUserResource(UserResource newUser) {
598 currentUserResource = newUser;
601 public static native void preventIESelection() /*-{
602 $doc.body.onselectstart = function () { return false; };
605 public static native void enableIESelection() /*-{
606 if ($doc.body.onselectstart != null)
607 $doc.body.onselectstart = null;
611 * @return the absolute path of the API root URL
613 public String getApiPath() {
614 Configuration conf = (Configuration) GWT.create(Configuration.class);
615 return conf.apiPath();
619 * Convert server date to local time according to browser timezone
620 * and format it according to localized pattern.
621 * Time is always formatted to 24hr format.
622 * NB: This assumes that server runs in UTC timezone. Otherwise
623 * we would need to adjust for server time offset as well.
628 public static String formatLocalDateTime(Date date) {
629 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
630 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
631 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
632 String datePart = dateFormatter.format(convertedDate);
633 String timePart = timeFormatter.format(convertedDate);
634 return datePart + " " + timePart;
638 * History support for folder navigation
639 * adds a new browser history entry
643 public void updateHistory(String key){
644 // Replace any whitespace of the initial string to "+"
645 // String result = key.replaceAll("\\s","+");
646 // Add a new browser history entry.
647 // History.newItem(result);
648 History.newItem(key);
652 * This method examines the token input and add a "/" at the end in case it's omitted.
653 * This happens only in Files/trash/, Files/shared/, Files/others.
656 * @return the formated token with a "/" at the end or the same tokenInput parameter
659 private String handleSpecialFolderNames(String tokenInput){
660 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
661 if(pathsToCheck.contains(tokenInput))
662 return tokenInput + "/";
668 * Reject illegal resource names, like '.' or '..' or slashes '/'.
670 static boolean isValidResourceName(String name) {
671 if (".".equals(name) || "..".equals(name) || name.contains("/"))
676 public void putUserToMap(String _userName, String _userFullName){
677 userFullNameMap.put(_userName, _userFullName);
680 public String findUserFullName(String _userName){
681 return userFullNameMap.get(_userName);
683 public String getUserFullName(String _userName) {
685 if (GSS.get().findUserFullName(_userName) == null)
686 //if there is no userFullName found then the map fills with the given _userName,
687 //so userFullName = _userName
688 GSS.get().putUserToMap(_userName, _userName);
689 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
690 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
691 GetUserCommand guc = new GetUserCommand(_userName);
694 return GSS.get().findUserFullName(_userName);
697 * Retrieve the treeView.
699 * @return the treeView
701 public CellTreeView getTreeView() {
705 public void onResourceUpdate(RestResource resource,boolean clearSelection){
706 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
707 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
708 showFileList(resource,clearSelection);