Merge branch 'master' into uploadArea
[pithos-web-client] / src / gr / grnet / pithos / web / client / Pithos.java
index 9bfde32..d034e86 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2011 GRNET S.A. All rights reserved.
+ * Copyright 2011-2012 GRNET S.A. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or
  * without modification, are permitted provided that the following
@@ -34,6 +34,7 @@
  */
 package gr.grnet.pithos.web.client;
 
+import gr.grnet.pithos.web.client.PithosDisclosurePanel.Style;
 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
 import gr.grnet.pithos.web.client.foldertree.AccountResource;
 import gr.grnet.pithos.web.client.foldertree.File;
@@ -53,9 +54,6 @@ import gr.grnet.pithos.web.client.rest.GetRequest;
 import gr.grnet.pithos.web.client.rest.HeadRequest;
 import gr.grnet.pithos.web.client.rest.PutRequest;
 import gr.grnet.pithos.web.client.rest.RestException;
-import gr.grnet.pithos.web.client.tagtree.Tag;
-import gr.grnet.pithos.web.client.tagtree.TagTreeView;
-import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -66,6 +64,7 @@ import java.util.Set;
 import com.google.gwt.core.client.EntryPoint;
 import com.google.gwt.core.client.GWT;
 import com.google.gwt.core.client.Scheduler;
+import com.google.gwt.core.client.Scheduler.RepeatingCommand;
 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
 import com.google.gwt.event.dom.client.ClickEvent;
 import com.google.gwt.event.dom.client.ClickHandler;
@@ -77,13 +76,18 @@ import com.google.gwt.http.client.RequestCallback;
 import com.google.gwt.http.client.RequestException;
 import com.google.gwt.http.client.Response;
 import com.google.gwt.http.client.URL;
+import com.google.gwt.i18n.client.Dictionary;
 import com.google.gwt.i18n.client.NumberFormat;
 import com.google.gwt.json.client.JSONArray;
 import com.google.gwt.json.client.JSONObject;
 import com.google.gwt.json.client.JSONParser;
 import com.google.gwt.json.client.JSONString;
 import com.google.gwt.json.client.JSONValue;
+import com.google.gwt.resources.client.ClientBundle;
+import com.google.gwt.resources.client.CssResource;
 import com.google.gwt.resources.client.ImageResource;
+import com.google.gwt.resources.client.ClientBundle.Source;
+import com.google.gwt.resources.client.ImageResource.ImageOptions;
 import com.google.gwt.user.client.Command;
 import com.google.gwt.user.client.Cookies;
 import com.google.gwt.user.client.Event;
@@ -91,6 +95,8 @@ import com.google.gwt.user.client.History;
 import com.google.gwt.user.client.Window;
 import com.google.gwt.user.client.ui.AbstractImagePrototype;
 import com.google.gwt.user.client.ui.Button;
+import com.google.gwt.user.client.ui.Composite;
+import com.google.gwt.user.client.ui.FlowPanel;
 import com.google.gwt.user.client.ui.HTML;
 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
 import com.google.gwt.user.client.ui.HasVerticalAlignment;
@@ -110,6 +116,19 @@ public class Pithos implements EntryPoint, ResizeHandler {
        public static final String HOME_CONTAINER = "pithos";
 
        public static final String TRASH_CONTAINER = "trash";
+
+       public static final Configuration config = GWT.create(Configuration.class);
+       
+       public interface Style extends CssResource {
+               String commandAnchor();
+       }
+       
+       public interface Resources extends ClientBundle {
+               @Source("Pithos.css")
+               Style pithosCss();
+       }
+
+       public static Resources resources = GWT.create(Resources.class);
        
        /**
         * Instantiate an application-level image bundle. This object will provide
@@ -129,30 +148,28 @@ public class Pithos implements EntryPoint, ResizeHandler {
         return account;
     }
 
-    public void updateFolder(Folder f, boolean showfiles, Command callback) {
-        folderTreeView.updateFolder(f, showfiles, callback);
+    public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
+        folderTreeView.updateFolder(f, showfiles, callback, openParent);
     }
 
     public void updateGroupNode(Group group) {
         groupTreeView.updateGroupNode(group);
     }
 
-    public void updateSharedFolder(Folder f, boolean showfiles) {
-       mysharedTreeView.updateFolder(f, showfiles);
+    public void updateMySharedRoot() {
+       mysharedTreeView.updateRoot();
     }
     
-    public void updateOtherSharedFolder(Folder f, boolean showfiles) {
-       otherSharedTreeView.updateFolder(f, showfiles);
+    public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
+       mysharedTreeView.updateFolder(f, showfiles, callback);
+    }
+    
+    public void updateSharedFolder(Folder f, boolean showfiles) {
+       updateSharedFolder(f, showfiles, null);
     }
 
-    public List<Tag> getAllTags() {
-        List<Tag> tagList = new ArrayList<Tag>();
-        for (Folder f : account.getContainers()) {
-            for (String t : f.getTags()) {
-                tagList.add(new Tag(t));
-            }
-        }
-        return tagList;
+    public void updateOtherSharedFolder(Folder f, boolean showfiles) {
+       otherSharedTreeView.updateFolder(f, showfiles);
     }
 
     public MysharedTreeView getMySharedTreeView() {
@@ -169,9 +186,12 @@ public class Pithos implements EntryPoint, ResizeHandler {
                ImageResource folders();
 
                @Source("gr/grnet/pithos/resources/advancedsettings.png")
+               @ImageOptions(width=32, height=32)
                ImageResource tools();
        }
 
+       private Throwable error;
+       
        /**
         * The Application Clipboard implementation;
         */
@@ -185,7 +205,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
        /**
         * The panel that contains the various system messages.
         */
-       private MessagePanel messagePanel = new MessagePanel(Pithos.images);
+       private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
 
        /**
         * The bottom panel that contains the status bar.
@@ -238,29 +258,25 @@ public class Pithos implements EntryPoint, ResizeHandler {
     OtherSharedTreeView otherSharedTreeView = null;
 
     GroupTreeViewModel groupTreeViewModel;
-    private GroupTreeView groupTreeView;
+    GroupTreeView groupTreeView;
 
-    private TreeView selectedTree;
+    TreeView selectedTree;
     protected AccountResource account;
     
     Folder trash;
+    
+    List<Composite> treeViews = new ArrayList<Composite>();
 
     @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
     
-    Button upload;
-    
-    private HTML totalFiles;
-    
-    private HTML usedBytes;
+    public Button upload;
     
-    private HTML totalBytes;
+    private HTML numOfFiles;
     
-    private HTML usedPercent;
+    private Toolbar toolbar;
     
-    private HTML numOfFiles;
+    private FileUploadDialog fileUploadDialog;
     
-    private Button toolsButton;
-
        @Override
        public void onModuleLoad() {
                if (parseUserCredentials())
@@ -268,135 +284,125 @@ public class Pithos implements EntryPoint, ResizeHandler {
        }
 
     private void initialize() {
-        VerticalPanel outer = new VerticalPanel();
+       resources.pithosCss().ensureInjected();
+       boolean bareContent = Window.Location.getParameter("noframe") != null;
+       String contentWidth = bareContent ? "100%" : "75%";
+
+       VerticalPanel outer = new VerticalPanel();
         outer.setWidth("100%");
+       if (!bareContent) {
+               outer.addStyleName("pithos-outer");
+       }
 
-        topPanel = new TopPanel(this, Pithos.images);
-        topPanel.setWidth("100%");
-        outer.add(topPanel);
-        outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
+        if (!bareContent) {
+               topPanel = new TopPanel(this, Pithos.images);
+               topPanel.setWidth("100%");
+               outer.add(topPanel);
+               outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
+        }
         
-        messagePanel.setWidth("75%");
         messagePanel.setVisible(false);
         outer.add(messagePanel);
         outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
-
-
-        // Inner contains the various lists.
-        inner.sinkEvents(Event.ONCONTEXTMENU);
-        inner.setWidth("100%");
-
-        HorizontalPanel rightside = new HorizontalPanel();
-        rightside.addStyleName("pithos-rightSide");
-        rightside.setSpacing(5);
-
-        toolsButton = new Button(AbstractImagePrototype.create(images.tools()).getHTML());
-        toolsButton.addClickHandler(new ClickHandler() {
-                       
-                       @Override
-                       public void onClick(ClickEvent event) {
-                ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
-                if (!menu.isEmpty()) {
-                           menu.setPopupPosition(event.getClientX(), event.getClientY());
-                           menu.show();
-                }
-                       }
-               });
-        rightside.add(toolsButton);
-        rightside.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_LEFT);
+        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
+
+        HorizontalPanel header = new HorizontalPanel();
+        header.addStyleName("pithos-header");
+        header.setWidth(contentWidth);
+        if (bareContent)
+               header.addStyleName("pithos-header-noframe");
+        upload = new Button("Upload", new ClickHandler() {
+            @Override
+            public void onClick(ClickEvent event) {
+               if (getSelection() != null)
+                       new UploadFileCommand(Pithos.this, null, getSelection()).execute();
+            }
+        });
+        upload.addStyleName("pithos-uploadButton");
+        header.add(upload);
+        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
+        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
+
+        toolbar = new Toolbar(this);
+        header.add(toolbar);
+        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
+        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
         
         HorizontalPanel folderStatistics = new HorizontalPanel();
         folderStatistics.addStyleName("pithos-folderStatistics");
         numOfFiles = new HTML();
         folderStatistics.add(numOfFiles);
+        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
         HTML numOfFilesLabel = new HTML("&nbsp;Files");
         folderStatistics.add(numOfFilesLabel);
-        rightside.add(folderStatistics);
-        rightside.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
-
-        inner.add(rightside);
-        inner.setCellVerticalAlignment(rightside, HasVerticalAlignment.ALIGN_MIDDLE);
-        inner.setCellHeight(rightside, "60px");
+        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
+        header.add(folderStatistics);
+        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
+        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
+        header.setCellWidth(folderStatistics, "40px");
+        outer.add(header);
+        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
+        // Inner contains the various lists.nner
+        inner.sinkEvents(Event.ONCONTEXTMENU);
+        inner.setWidth("100%");
 
         folderTreeSelectionModel = new SingleSelectionModel<Folder>();
         folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
             @Override
-            public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
+            public void onSelectionChange(SelectionChangeEvent event) {
                 if (folderTreeSelectionModel.getSelectedObject() != null) {
                     deselectOthers(folderTreeView, folderTreeSelectionModel);
                     applyPermissions(folderTreeSelectionModel.getSelectedObject());
                     Folder f = folderTreeSelectionModel.getSelectedObject();
-                    showFiles(f);
+                       updateFolder(f, true, new Command() {
+                               
+                               @Override
+                               public void execute() {
+                                       updateStatistics();
+                               }
+                       }, true);
+                       showRelevantToolbarButtons();
                 }
+                               else {
+                                       if (getSelectedTree().equals(folderTreeView))
+                                               setSelectedTree(null);
+                                       if (getSelectedTree() == null)
+                                               showRelevantToolbarButtons();
+                               }
             }
         });
         selectionModels.add(folderTreeSelectionModel);
 
         folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
         folderTreeView = new FolderTreeView(folderTreeViewModel);
-
-        fileList = new FileList(this, images, folderTreeView);
+        treeViews.add(folderTreeView);
+        
+        fileList = new FileList(this, images);
         inner.add(fileList);
 
-        groupTreeViewModel = new GroupTreeViewModel(this);
-        groupTreeView = new GroupTreeView(groupTreeViewModel);
-
+        inner.add(createUploadArea());
+        
         trees = new VerticalPanel();
         trees.setWidth("100%");
-
-        VerticalPanel uploadButtonPanel = new VerticalPanel();
-        upload = new Button("Upload File", new ClickHandler() {
-            @Override
-            public void onClick(@SuppressWarnings("unused") ClickEvent event) {
-                new UploadFileCommand(Pithos.this, null, getSelection()).execute();
-            }
-        });
-        uploadButtonPanel.add(upload);
-        uploadButtonPanel.setWidth("100%");
-        uploadButtonPanel.setHeight("60px");
-        uploadButtonPanel.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_CENTER);
-        uploadButtonPanel.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
-        upload.addStyleName("pithos-uploadButton");
-        trees.add(uploadButtonPanel);
         
-        HorizontalPanel treeHeader = new HorizontalPanel();
-        treeHeader.addStyleName("pithos-treeHeader");
-        treeHeader.setWidth("100%");
-        treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
-        HorizontalPanel statistics = new HorizontalPanel();
-        statistics.add(new HTML("Total Objects:&nbsp;"));
-        totalFiles = new HTML();
-        statistics.add(totalFiles);
-        statistics.add(new HTML("&nbsp;|&nbsp;Used:&nbsp;"));
-        usedBytes = new HTML();
-        statistics.add(usedBytes);
-        statistics.add(new HTML("&nbsp;of&nbsp;"));
-        totalBytes = new HTML();
-        statistics.add(totalBytes);
-        statistics.add(new HTML("&nbsp;("));
-        usedPercent = new HTML();
-        statistics.add(usedPercent);
-        statistics.add(new HTML(")"));
-        treeHeader.add(statistics);
-        treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
-        trees.add(treeHeader);
-
-        trees.add(folderTreeView);
-        trees.add(groupTreeView);
         // Add the left and right panels to the split panel.
         splitPanel.setLeftWidget(trees);
         splitPanel.setRightWidget(inner);
-        splitPanel.setSplitPosition("35%");
+        splitPanel.setSplitPosition("219px");
         splitPanel.setSize("100%", "100%");
         splitPanel.addStyleName("pithos-splitPanel");
-        splitPanel.setWidth("75%");
+        splitPanel.setWidth(contentWidth);
         outer.add(splitPanel);
         outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
 
-        statusPanel = new StatusPanel();
-        statusPanel.setWidth("100%");
-        outer.add(statusPanel);
-        outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
+        if (!bareContent) {
+               statusPanel = new StatusPanel();
+               statusPanel.setWidth("100%");
+               outer.add(statusPanel);
+               outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
+        }
+        else
+               splitPanel.addStyleName("pithos-splitPanel-noframe");
 
         // Hook the window resize event, so that we can adjust the UI.
         Window.addResizeHandler(this);
@@ -434,6 +440,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
                                                        trash = f;
                                                        break;
                                                }
+                                   trees.add(folderTreeView);
                                    folderTreeViewModel.initialize(account, new Command() {
                                                                
                                                                @Override
@@ -441,106 +448,110 @@ public class Pithos implements EntryPoint, ResizeHandler {
                                                    createMySharedTree();
                                                                }
                                                        });
-                                   groupTreeViewModel.initialize();
-                                   showStatistics();
+
+                                   HorizontalPanel separator = new HorizontalPanel();
+                                   separator.addStyleName("pithos-statisticsSeparator");
+                                   separator.add(new HTML(""));
+                                   trees.add(separator);
+
+                                   groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
+                                   groupTreeView = new GroupTreeView(groupTreeViewModel);
+                                   treeViews.add(groupTreeView);
+                                   trees.add(groupTreeView);
+                                   folderTreeView.showStatistics(account);
                                }
                                        }
                                });
             }
         });
+        
+        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
+                       
+                       @Override
+                       public boolean execute() {
+                               Folder f = getSelection();
+                               if (f != null) {
+                                       if (getSelectedTree().equals(folderTreeView))
+                                               updateFolder(f, true, null, false);
+                                       else if (getSelectedTree().equals(mysharedTreeView))
+                                               updateSharedFolder(f, true);
+                               }
+                               return true;
+                       }
+               }, 3000);
     }
 
     public void applyPermissions(Folder f) {
        if (f != null) {
-               if (f.isInTrash())
+               if (f.isInTrash()) {
                        upload.setEnabled(false);
+                       hideUploadArea();
+               }
                else {
                        Boolean[] perms = f.getPermissions().get(username);
                        if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
                                upload.setEnabled(true);
+                               showUploadArea();
                        }
-                       else
+                       else {
                                upload.setEnabled(false);
+                               hideUploadArea();
+                       }
                }
        }
-       else
+       else {
                upload.setEnabled(false);
+               hideUploadArea();
+       }
        }
 
        @SuppressWarnings({ "rawtypes", "unchecked" })
        public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
        selectedTree = _selectedTree;
+       
         for (SingleSelectionModel s : selectionModels)
-            if (!s.equals(model))
+            if (!s.equals(model) && s.getSelectedObject() != null)
                 s.setSelected(s.getSelectedObject(), false);
     }
 
-    public void showFiles(Folder f) {
+    public void showFiles(final Folder f) {
         Set<File> files = f.getFiles();
         showFiles(files);
     }
 
     public void showFiles(Set<File> files) {
-        //Iterator<File> iter = files.iterator();
-        //fetchFile(iter, files);
         fileList.setFiles(new ArrayList<File>(files));
     }
 
-    protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
-        if (iter.hasNext()) {
-            File file = iter.next();
-            String path = file.getUri() + "?format=json";
-            GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
-                @Override
-                public void onSuccess(@SuppressWarnings("unused") File _result) {
-                    fetchFile(iter, files);
-                }
-
-                @Override
-                public void onError(Throwable t) {
-                    GWT.log("Error getting file", t);
-                    if (t instanceof RestException)
-                        displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
-                    else
-                        displayError("System error fetching file: " + t.getMessage());
-                }
-
-                               @Override
-                               protected void onUnauthorized(Response response) {
-                                       sessionExpired();
-                               }
-            };
-            getFile.setHeader("X-Auth-Token", "0000");
-            Scheduler.get().scheduleDeferred(getFile);
-        }
-        else
-            fileList.setFiles(new ArrayList<File>(files));
-    }
-
     /**
         * Parse and store the user credentials to the appropriate fields.
         */
        private boolean parseUserCredentials() {
-        username = Window.Location.getParameter("user");
-        token = Window.Location.getParameter("token");
         Configuration conf = (Configuration) GWT.create(Configuration.class);
-        if (username == null || username.length() == 0 || token == null || token.length() == 0) {
-            String cookie = conf.authCookie();
-            String auth = Cookies.getCookie(cookie);
-            if (auth == null) {
-                authenticateUser();
-                return false;
-            }
-                       String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
-                       if (authSplit.length != 2) {
-                           authenticateUser();
-                           return false;
-                       }
-                       username = authSplit[0];
-                       token = authSplit[1];
-                       return true;
+               Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
+        String cookie = otherProperties.get("authCookie");
+        String auth = Cookies.getCookie(cookie);
+        if (auth == null) {
+            authenticateUser();
+            return false;
         }
-               Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
+        if (auth.startsWith("\""))
+               auth = auth.substring(1);
+        if (auth.endsWith("\""))
+               auth = auth.substring(0, auth.length() - 1);
+               String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
+               if (authSplit.length != 2) {
+                   authenticateUser();
+                   return false;
+               }
+               username = authSplit[0];
+               token = authSplit[1];
+
+        String gotoUrl = Window.Location.getParameter("goto");
+               if (gotoUrl != null && gotoUrl.length() > 0) {
+                       Window.Location.assign(gotoUrl);
+                       return false;
+               }
                return true;
     }
 
@@ -548,8 +559,8 @@ public class Pithos implements EntryPoint, ResizeHandler {
         * Redirect the user to the login page for authentication.
         */
        protected void authenticateUser() {
-               Configuration conf = (Configuration) GWT.create(Configuration.class);
-        Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
+               Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
+        Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
        }
 
        protected void fetchAccount(final Command callback) {
@@ -566,6 +577,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
             @Override
             public void onError(Throwable t) {
                 GWT.log("Error getting account", t);
+                               setError(t);
                 if (t instanceof RestException)
                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
                 else
@@ -585,13 +597,14 @@ public class Pithos implements EntryPoint, ResizeHandler {
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
 
                        @Override
-                       public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
-                               showStatistics();
+                       public void onSuccess(AccountResource _result) {
+                               folderTreeView.showStatistics(account);
                        }
 
                        @Override
                        public void onError(Throwable t) {
                 GWT.log("Error getting account", t);
+                               setError(t);
                 if (t instanceof RestException)
                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
                 else
@@ -607,19 +620,11 @@ public class Pithos implements EntryPoint, ResizeHandler {
                Scheduler.get().scheduleDeferred(headAccount);
        }
 
-       protected void showStatistics() {
-       totalFiles.setHTML(String.valueOf(account.getNumberOfObjects()));
-       usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
-       totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
-       NumberFormat nf = NumberFormat.getPercentFormat();
-       usedPercent.setHTML(nf.format(account.getUsedPercentage()));
-       }
-
        protected void createHomeContainer(final AccountResource _account, final Command callback) {
         String path = "/" + Pithos.HOME_CONTAINER;
         PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
             @Override
-            public void onSuccess(@SuppressWarnings("unused") Resource result) {
+            public void onSuccess(Resource result) {
                if (!_account.hasTrashContainer())
                        createTrashContainer(callback);
                else
@@ -629,6 +634,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
             @Override
             public void onError(Throwable t) {
                 GWT.log("Error creating pithos", t);
+                               setError(t);
                 if (t instanceof RestException)
                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
                 else
@@ -648,13 +654,14 @@ public class Pithos implements EntryPoint, ResizeHandler {
         String path = "/" + Pithos.TRASH_CONTAINER;
         PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
             @Override
-            public void onSuccess(@SuppressWarnings("unused") Resource result) {
+            public void onSuccess(Resource result) {
                        fetchAccount(callback);
             }
 
             @Override
             public void onError(Throwable t) {
                 GWT.log("Error creating pithos", t);
+                               setError(t);
                 if (t instanceof RestException)
                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
                 else
@@ -688,7 +695,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
 
        protected void onWindowResized(int height) {
                // Adjust the split panel to take up the available room in the window.
-               int newHeight = height - splitPanel.getAbsoluteTop() - 60;
+               int newHeight = height - splitPanel.getAbsoluteTop();
                if (newHeight < 1)
                        newHeight = 1;
                splitPanel.setHeight("" + newHeight);
@@ -794,26 +801,27 @@ public class Pithos implements EntryPoint, ResizeHandler {
                History.newItem(key);
        }
 
-    public void deleteFolder(final Folder folder) {
+    public void deleteFolder(final Folder folder, final Command callback) {
         String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
         RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
         builder.setHeader("X-Auth-Token", getToken());
         try {
             builder.sendRequest("", new RequestCallback() {
                 @Override
-                public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
+                public void onResponseReceived(Request request, Response response) {
                     if (response.getStatusCode() == Response.SC_OK) {
                         JSONValue json = JSONParser.parseStrict(response.getText());
                         JSONArray array = json.isArray();
                         int i = 0;
                         if (array != null) {
-                            deleteObject(folder, i, array);
+                            deleteObject(folder, i, array, callback);
                         }
                     }
                 }
 
                 @Override
-                public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
+                public void onError(Request request, Throwable exception) {
+                       setError(exception);
                     displayError("System error unable to delete folder: " + exception.getMessage());
                 }
             });
@@ -822,21 +830,22 @@ public class Pithos implements EntryPoint, ResizeHandler {
         }
     }
 
-    void deleteObject(final Folder folder, final int i, final JSONArray array) {
+    void deleteObject(final Folder folder, final int i, final JSONArray array, final Command callback) {
         if (i < array.size()) {
             JSONObject o = array.get(i).isObject();
             if (o != null && !o.containsKey("subdir")) {
                 JSONString name = o.get("name").isString();
                 String path = "/" + folder.getContainer() + "/" + name.stringValue();
-                DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
+                DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
                     @Override
-                    public void onSuccess(@SuppressWarnings("unused") Resource result) {
-                        deleteObject(folder, i + 1, array);
+                    public void onSuccess(Resource result) {
+                        deleteObject(folder, i + 1, array, callback);
                     }
 
                     @Override
                     public void onError(Throwable t) {
                         GWT.log("", t);
+                                               setError(t);
                         displayError("System error unable to delete folder: " + t.getMessage());
                     }
 
@@ -857,7 +866,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
                 try {
                     builder.sendRequest("", new RequestCallback() {
                         @Override
-                        public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
+                        public void onResponseReceived(Request request, Response response) {
                             if (response.getStatusCode() == Response.SC_OK) {
                                 JSONValue json = JSONParser.parseStrict(response.getText());
                                 JSONArray array2 = json.isArray();
@@ -867,12 +876,13 @@ public class Pithos implements EntryPoint, ResizeHandler {
                                         array.set(l++, array2.get(j));
                                     }
                                 }
-                                deleteObject(folder, i + 1, array);
+                                deleteObject(folder, i + 1, array, callback);
                             }
                         }
 
                         @Override
-                        public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
+                        public void onError(Request request, Throwable exception) {
+                               setError(exception);
                             displayError("System error unable to delete folder: " + exception.getMessage());
                         }
                     });
@@ -883,21 +893,25 @@ public class Pithos implements EntryPoint, ResizeHandler {
         }
         else {
             String path = folder.getUri();
-            DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
+            DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
                 @Override
-                public void onSuccess(@SuppressWarnings("unused") Resource result) {
+                public void onSuccess(Resource result) {
                     updateFolder(folder.getParent(), true, new Command() {
                                                
                                                @Override
                                                public void execute() {
+                                                       folderTreeSelectionModel.setSelected(folder.getParent(), true);
                                                        updateStatistics();
+                                                       if (callback != null)
+                                                               callback.execute();
                                                }
-                                       });
+                                       }, true);
                 }
 
                 @Override
                 public void onError(Throwable t) {
                     GWT.log("", t);
+                                       setError(t);
                     if (t instanceof RestException) {
                        if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
                                displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
@@ -928,13 +942,14 @@ public class Pithos implements EntryPoint, ResizeHandler {
             String path = targetUri + "/" + file.getName();
             PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
                 @Override
-                public void onSuccess(@SuppressWarnings("unused") Resource result) {
+                public void onSuccess(Resource result) {
                     copyFiles(iter, targetUsername, targetUri, callback);
                 }
 
                 @Override
                 public void onError(Throwable t) {
                     GWT.log("", t);
+                                       setError(t);
                     if (t instanceof RestException) {
                         displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
                     }
@@ -948,9 +963,10 @@ public class Pithos implements EntryPoint, ResizeHandler {
                                }
             };
             copyFile.setHeader("X-Auth-Token", getToken());
-            copyFile.setHeader("X-Copy-From", file.getUri());
+            copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
             if (!file.getOwner().equals(targetUsername))
-               copyFile.setHeader("X-Source-Account", file.getOwner());
+               copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
+            copyFile.setHeader("Content-Type", file.getContentType());
             Scheduler.get().scheduleDeferred(copyFile);
         }
         else  if (callback != null) {
@@ -978,7 +994,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
         String path = targetUri + "/" + f.getName();
         PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
             @Override
-            public void onSuccess(@SuppressWarnings("unused") Resource result) {
+            public void onSuccess(Resource result) {
                GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
 
                                        @Override
@@ -996,6 +1012,7 @@ public class Pithos implements EntryPoint, ResizeHandler {
                                        @Override
                                        public void onError(Throwable t) {
                                GWT.log("", t);
+                                               setError(t);
                                if (t instanceof RestException) {
                                    displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
                                }
@@ -1015,7 +1032,8 @@ public class Pithos implements EntryPoint, ResizeHandler {
             @Override
             public void onError(Throwable t) {
                 GWT.log("", t);
-                if (t instanceof RestException) {
+                               setError(t);
+               if (t instanceof RestException) {
                     displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
                 }
                 else
@@ -1043,17 +1061,18 @@ public class Pithos implements EntryPoint, ResizeHandler {
        }
 
        public void updateTrash(boolean showFiles, Command callback) {
-               updateFolder(trash, showFiles, callback);
+               updateFolder(trash, showFiles, callback, true);
        }
 
        public void updateGroupsNode() {
                groupTreeView.updateGroupNode(null);
        }
 
-       public void addGroup(String groupname) {
+       public Group addGroup(String groupname) {
                Group newGroup = new Group(groupname);
                account.addGroup(newGroup);
                groupTreeView.updateGroupNode(null);
+               return newGroup;
        }
 
        public void removeGroup(Group group) {
@@ -1065,8 +1084,14 @@ public class Pithos implements EntryPoint, ResizeHandler {
                return selectedTree;
        }
        
+       public void setSelectedTree(TreeView selected) {
+               selectedTree = selected;
+       }
+
        public Folder getSelection() {
-               return selectedTree.getSelection();
+               if (selectedTree != null)
+                       return selectedTree.getSelection();
+               return null;
        }
 
        public void showFolderStatistics(int folderFileCount) {
@@ -1082,20 +1107,28 @@ public class Pithos implements EntryPoint, ResizeHandler {
        }
 
        public void updateRootFolder(Command callback) {
-               updateFolder(account.getPithos(), false, callback);
+               updateFolder(account.getPithos(), false, callback, true);
        }
 
        void createMySharedTree() {
                mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
                mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
                    @Override
-                   public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
+                   public void onSelectionChange(SelectionChangeEvent event) {
                        if (mysharedTreeSelectionModel.getSelectedObject() != null) {
                            deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
                            upload.setEnabled(false);
+                           hideUploadArea();
                            updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
+                                       showRelevantToolbarButtons();
                        }
-                   }
+                               else {
+                                       if (getSelectedTree().equals(mysharedTreeView))
+                                               setSelectedTree(null);
+                                       if (getSelectedTree() == null)
+                                               showRelevantToolbarButtons();
+                               }
+                   }
                });
                selectionModels.add(mysharedTreeSelectionModel);
                mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
@@ -1104,7 +1137,8 @@ public class Pithos implements EntryPoint, ResizeHandler {
                        @Override
                        public void execute() {
                            mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
-                               trees.insert(mysharedTreeView, 3);
+                               trees.insert(mysharedTreeView, 2);
+                               treeViews.add(mysharedTreeView);
                                createOtherSharedTree();
                        }
                });
@@ -1114,13 +1148,20 @@ public class Pithos implements EntryPoint, ResizeHandler {
                otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
                otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
                    @Override
-                   public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
+                   public void onSelectionChange(SelectionChangeEvent event) {
                        if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
                            deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
                            applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
                            updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
+                                       showRelevantToolbarButtons();
                        }
-                   }
+                               else {
+                                       if (getSelectedTree().equals(otherSharedTreeView))
+                                               setSelectedTree(null);
+                                       if (getSelectedTree() == null)
+                                               showRelevantToolbarButtons();
+                               }
+                   }
                });
                selectionModels.add(otherSharedTreeSelectionModel);
                otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
@@ -1129,18 +1170,270 @@ public class Pithos implements EntryPoint, ResizeHandler {
                        @Override
                        public void execute() {
                            otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
-                               trees.insert(otherSharedTreeView, 4);
+                               trees.insert(otherSharedTreeView, 1);
+                               treeViews.add(otherSharedTreeView);
                        }
                });
        }
 
-       public void logoff() {
-        Configuration conf = (Configuration) GWT.create(Configuration.class);
-               Cookies.removeCookie(conf.authCookie());
-               Cookies.removeCookie(conf.authTokenCookie(), "/");
-               for (String s: Cookies.getCookieNames())
-                       if (s.startsWith(conf.shibSessionCookiePrefix()))
-                               Cookies.removeCookie(s, "/");
-               Window.Location.assign(Window.Location.getPath());
+       public native void log1(String message)/*-{
+               $wnd.console.log(message);
+       }-*/;
+
+       public String getErrorData() {
+               if (error != null)
+                       return error.toString();
+               return "";
+       }
+       
+       public void setError(Throwable t) {
+               error = t;
+       }
+       
+       public void showRelevantToolbarButtons() {
+               toolbar.showRelevantButtons();
+       }
+
+       public FileUploadDialog getFileUploadDialog() {
+               if (fileUploadDialog == null)
+                       fileUploadDialog = new FileUploadDialog(this);
+               return fileUploadDialog;
+       }
+
+       public void hideUploadIndicator() {
+               upload.removeStyleName("pithos-uploadButton-loading");
+               upload.setTitle("");
+       }
+       
+       public void showUploadIndicator() {
+               upload.addStyleName("pithos-uploadButton-loading");
+               upload.setTitle("Upload in progress. Click for details.");
+       }
+
+       public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
+               if (folder == null) {
+                       if (callback != null)
+                               callback.execute();
+               }
+               else {
+                       HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
+       
+                               @Override
+                               public void onSuccess(Folder _result) {
+                                       if (callback != null)
+                                               callback.execute();
+                               }
+       
+                               @Override
+                               public void onError(Throwable t) {
+                               if (t instanceof RestException) {
+                                       if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
+                               final String path = folder.getUri();
+                               PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
+                                   @Override
+                                   public void onSuccess(Resource _result) {
+                                       scheduleFolderHeadCommand(folder, callback);
+                                   }
+       
+                                   @Override
+                                   public void onError(Throwable _t) {
+                                       GWT.log("", _t);
+                                                               setError(_t);
+                                       if(_t instanceof RestException){
+                                           displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
+                                       }
+                                       else
+                                           displayError("System error creating folder: " + _t.getMessage());
+                                   }
+       
+                                               @Override
+                                               protected void onUnauthorized(Response response) {
+                                                       sessionExpired();
+                                               }
+                               };
+                               newFolder.setHeader("X-Auth-Token", getToken());
+                               newFolder.setHeader("Content-Type", "application/folder");
+                               newFolder.setHeader("Accept", "*/*");
+                               newFolder.setHeader("Content-Length", "0");
+                               Scheduler.get().scheduleDeferred(newFolder);
+                                       }
+                                       else
+                                               displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
+                               }
+                               else
+                                   displayError("System error heading folder: " + t.getMessage());
+       
+                               GWT.log("Error heading folder", t);
+                                       setError(t);
+                               }
+       
+                               @Override
+                               protected void onUnauthorized(Response response) {
+                                       sessionExpired();
+                               }
+                       };
+                       headFolder.setHeader("X-Auth-Token", getToken());
+                       Scheduler.get().scheduleDeferred(headFolder);
+               }
        }
+
+       public void scheduleFileHeadCommand(File f, final Command callback) {
+               HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
+
+                       @Override
+                       public void onSuccess(File _result) {
+                               if (callback != null)
+                                       callback.execute();
+                       }
+
+                       @Override
+                       public void onError(Throwable t) {
+                       GWT.log("Error heading file", t);
+                               setError(t);
+                       if (t instanceof RestException)
+                           displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
+                       else
+                           displayError("System error heading file: " + t.getMessage());
+                       }
+
+                       @Override
+                       protected void onUnauthorized(Response response) {
+                               sessionExpired();
+                       }
+               };
+               headFile.setHeader("X-Auth-Token", getToken());
+               Scheduler.get().scheduleDeferred(headFile);
+       }
+
+       public boolean isMySharedSelected() {
+               return getSelectedTree().equals(getMySharedTreeView());
+       }
+       
+       private FlowPanel createUploadArea() {
+               FlowPanel area = new FlowPanel();
+               area.getElement().setId("container");
+               HTML list = new HTML();
+               list.getElement().setId("filelist");
+               area.add(list);
+               Scheduler.get().scheduleDeferred(new ScheduledCommand() {
+                       
+                       @Override
+                       public void execute() {
+                               setupUploadArea(Pithos.this, getToken());
+                       }
+               });
+               
+               return area;
+       }
+       
+       native void setupUploadArea(Pithos app, String token) /*-{
+               $wnd.$("#container").pluploadQueue({
+                       // General settings
+                       runtimes : 'html5',
+                       unique_names : true,
+                       multiple_queues: true,
+                       drop_element: 'filelist',
+                       
+                       preinit: {
+                               Init: function(up, info) {
+                                       if ($wnd.console && $wnd.console.log)
+                                               $wnd.console.log("Init fired");
+                                       up.settings.file_data_name = "X-Object-Data";                           
+                               }
+                       },
+                       
+                       init: {
+                               FilesAdded: function(up, files) {
+                                       $wnd.$('#container').css('border', '');
+                                       var api = app.@gr.grnet.pithos.web.client.Pithos::getApiPath()();
+                                       var folder = app.@gr.grnet.pithos.web.client.Pithos::getUploadFolder()();
+                                       var owner = folder.@gr.grnet.pithos.web.client.foldertree.Folder::getOwner()();
+                                       var uri = folder.@gr.grnet.pithos.web.client.foldertree.Folder::getUri()();
+                                       var path = api + owner + uri;
+                                       for (var j=0; j<files.length; j++) {
+                                               files[j].folder = folder;
+                                               files[j].url = path + "/" + files[j].name + "?X-Auth-Token=" + encodeURIComponent(token);
+                                       }
+                                       up.start();
+                               },
+                               
+                               BeforeUpload: function(up, file) {
+                                       if ($wnd.console && $wnd.console.log)
+                                               $wnd.console.log('About to upload ' + file.url);
+                                       up.settings.url = file.url;
+                               },
+                               
+                               FileUploaded: function(up, file, response) {
+                                       if ($wnd.console && $wnd.console.log) {
+                                               $wnd.console.log('File ' + file.name + ' uploaded');
+                                               $wnd.console.log('Response: ' + response);
+                                       }
+                                       up.removeFile(file);
+                                       var folder = app.@gr.grnet.pithos.web.client.Pithos::getUploadFolder()();
+                                       if (folder == file.folder)
+                                               app.@gr.grnet.pithos.web.client.Pithos::updateUploadFolder()();
+                               },
+                               
+                               UploadComplete: function(up, files) {
+                                       if ($wnd.console && $wnd.console.log)
+                                               $wnd.console.log('All files finished');
+                               },
+                               
+                               Error: function(up, error) {
+                                       if ($wnd.console && $wnd.console.log)
+                                               $wnd.console.log("Error occured:" + error);
+                               }
+                       }
+               });
+               var uploader = $wnd.$("#container").pluploadQueue();
+               if (uploader.runtime != 'html5')
+                       $wnd.$("#container").hide();
+               else {
+                       if ($wnd.console && $wnd.console.log) {
+                               $wnd.console.log(uploader);
+                               $wnd.console.log($wnd.plupload);
+                       }
+                       $wnd.$('.plupload_header').hide();
+                       $wnd.$('.plupload_filelist_header').hide();
+                       $wnd.$('#container_filelist').css('overflow-y', 'auto');
+                       $wnd.$('.plupload_filelist_footer').hide();
+                       $wnd.document.getElementById('container').addEventListener('dragenter', function(event) {
+                               $wnd.$('#container').css('border', '3px inset');
+                       }, false);
+                       $wnd.document.getElementById('container').addEventListener('dragleave', function(event) {
+                               $wnd.$('#container').css('border', '');
+                       }, false);
+               }
+       }-*/;
+       
+       private Folder getUploadFolder() {
+               if (folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
+                       return getSelection();
+               }
+               return null;
+       }
+       
+       private void updateUploadFolder() {
+               if (folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
+                       Folder f = getSelection();
+                       if (getSelectedTree().equals(getFolderTreeView()))
+                               updateFolder(f, true, new Command() {
+                               
+                                       @Override
+                                       public void execute() {
+                                               updateStatistics();
+                                       }
+                               }, false);
+                       else
+                               updateOtherSharedFolder(f, true);
+               }
+       }
+
+       public native void hideUploadArea() /*-{
+               $wnd.$("#container").hide();
+       }-*/;
+
+       public native void showUploadArea() /*-{
+               $wnd.$("#container").show();
+       }-*/;
 }