Bug 497015 - History view not displayed if server is remote and
FileBasedChangePackages are used

* Enable lazy loading
* Enable via extension point or system property

Change-Id: I23795d0a6d3d586d8090d9abffa4ad5fbabd8d0d
Author:    Markus Barchfeld <markus.barchfeld@gmxde>
Signed-off-by: Markus Barchfeld <markus.barchfeld@gmx.de> [initial API and implementation]
diff --git a/bundles/org.eclipse.emf.emfstore.client.ui/plugin.xml b/bundles/org.eclipse.emf.emfstore.client.ui/plugin.xml
index 6fb2b9c..e78e263 100644
--- a/bundles/org.eclipse.emf.emfstore.client.ui/plugin.xml
+++ b/bundles/org.eclipse.emf.emfstore.client.ui/plugin.xml
@@ -6,6 +6,7 @@
   <extension-point id="historyBrowserComparator" name="HistoryBrowserComparator" schema="schema/historyBrowserComparator.exsd"/>
   <extension-point id="showPasswordControls" name="Show password controls" schema="schema/showPasswordControls.exsd"/>
   <extension-point id="uiRunnableProvider" name="UI Runnable Provider" schema="schema/uiRunnableProvider.exsd"/>
+  <extension-point id="enableLazyLoadingOfChangePackages" name="Enable lazy loading of change Packages" schema="schema/enableLazyLoadingOfChangePackages.exsd"/>
   <extension
         point="org.eclipse.ui.handlers">
       <handler
@@ -464,6 +465,28 @@
                    </and>
                 </visibleWhen>
              </command>
+             <command
+                   commandId="org.eclipse.emf.emfstore.client.ui.historybrowserview.loadChangePackages"
+                   label="Show details"
+                   style="push"
+                   tooltip="Show details about this revision">
+                <visibleWhen
+                      checkEnabled="true">
+                       <and>
+                         <systemTest
+                           property="org.eclipse.emf.emfstore.client.ui.enableLazyLoadingOfChangePackages"
+                           value="true">
+                         </systemTest>
+                      <iterate
+                            ifEmpty="false"
+                            operator="and">
+                         <instanceof
+                               value="org.eclipse.emf.emfstore.internal.server.model.versioning.HistoryInfo">
+                         </instanceof>
+                      </iterate>
+					</and>
+                </visibleWhen>
+             </command>
           </menuContribution>
           <menuContribution
                 locationURI="popup:org.eclipse.emf.emfstore.client.ui.views.RepositoryView?after=org.eclipse.emf.emfstore.internal.client.ui.repositorybrowser.ManageOrgUnits">
@@ -730,6 +753,11 @@
             name="CheckoutRevision">
       </command>
       <command
+            defaultHandler="org.eclipse.emf.emfstore.internal.client.ui.handlers.LoadChangePackagesHandler"
+            id="org.eclipse.emf.emfstore.client.ui.historybrowserview.loadChangePackages"
+            name="LoadChangePackages">
+      </command>
+      <command
             defaultHandler="org.eclipse.emf.emfstore.internal.client.ui.handlers.AddTagHandler"
             id="org.eclipse.emf.emfstore.client.ui.historybrowserview.addtag"
             name="AddTag">
diff --git a/bundles/org.eclipse.emf.emfstore.client.ui/schema/enableLazyLoadingOfChangePackages.exsd b/bundles/org.eclipse.emf.emfstore.client.ui/schema/enableLazyLoadingOfChangePackages.exsd
new file mode 100644
index 0000000..1ff692c
--- /dev/null
+++ b/bundles/org.eclipse.emf.emfstore.client.ui/schema/enableLazyLoadingOfChangePackages.exsd
@@ -0,0 +1,114 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.emf.emfstore.client.ui" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+      <appInfo>
+         <meta.schema plugin="org.eclipse.emf.emfstore.client.ui" id="enableLazyLoadingOfChangePackages" name="Enable lazy loading of change Packages"/>
+      </appInfo>
+      <documentation>
+         Enable lazy loading of change packages in the History Browser View. If enabled the initial list will only show history info (commit message, date, ...) but no change details. Change details can be loaded via context menu on the history info for one or more history infos.
+
+Per default lazy loading is disabled.
+      </documentation>
+   </annotation>
+
+   <element name="extension">
+      <annotation>
+         <appInfo>
+            <meta.element />
+         </appInfo>
+      </annotation>
+      <complexType>
+         <sequence>
+            <element ref="enablement"/>
+         </sequence>
+         <attribute name="point" type="string" use="required">
+            <annotation>
+               <documentation>
+                  
+               </documentation>
+            </annotation>
+         </attribute>
+         <attribute name="id" type="string">
+            <annotation>
+               <documentation>
+                  
+               </documentation>
+            </annotation>
+         </attribute>
+         <attribute name="name" type="string">
+            <annotation>
+               <documentation>
+                  
+               </documentation>
+               <appInfo>
+                  <meta.attribute translatable="true"/>
+               </appInfo>
+            </annotation>
+         </attribute>
+      </complexType>
+   </element>
+
+   <element name="enablement">
+      <complexType>
+         <attribute name="enabled" type="boolean" use="default" value="false">
+            <annotation>
+               <documentation>
+                  
+               </documentation>
+            </annotation>
+         </attribute>
+      </complexType>
+   </element>
+
+   <annotation>
+      <appInfo>
+         <meta.section type="since"/>
+      </appInfo>
+      <documentation>
+         1.9.0
+      </documentation>
+   </annotation>
+
+   <annotation>
+      <appInfo>
+         <meta.section type="examples"/>
+      </appInfo>
+      <documentation>
+         [Enter extension point usage example here.]
+      </documentation>
+   </annotation>
+
+   <annotation>
+      <appInfo>
+         <meta.section type="apiinfo"/>
+      </appInfo>
+      <documentation>
+         [Enter API information here.]
+      </documentation>
+   </annotation>
+
+   <annotation>
+      <appInfo>
+         <meta.section type="implementation"/>
+      </appInfo>
+      <documentation>
+         [Enter information about supplied implementation of this extension point.]
+      </documentation>
+   </annotation>
+
+   <annotation>
+      <appInfo>
+         <meta.section type="copyright"/>
+      </appInfo>
+      <documentation>
+         Copyright (c) 2011-2016 EclipseSource Muenchen GmbH and others.&lt;br/&gt;
+
+All rights reserved. This program and the accompanying materials
+are made available under the terms of the Eclipse Public License v1.0
+which accompanies this distribution, and is available at
+http://www.eclipse.org/legal/epl-v10.html
+      </documentation>
+   </annotation>
+
+</schema>
diff --git a/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/handlers/LoadChangePackagesHandler.java b/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/handlers/LoadChangePackagesHandler.java
new file mode 100644
index 0000000..1387521
--- /dev/null
+++ b/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/handlers/LoadChangePackagesHandler.java
@@ -0,0 +1,135 @@
+/*******************************************************************************
+ * Copyright (c) 2016 Metus GmbH
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * mbarchfe
+ ******************************************************************************/
+package org.eclipse.emf.emfstore.internal.client.ui.handlers;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.emf.emfstore.internal.client.model.ESWorkspaceProviderImpl;
+import org.eclipse.emf.emfstore.internal.client.model.ProjectSpace;
+import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.ConnectionManager;
+import org.eclipse.emf.emfstore.internal.client.ui.views.historybrowserview.HistoryBrowserView;
+import org.eclipse.emf.emfstore.internal.common.model.util.ModelUtil;
+import org.eclipse.emf.emfstore.internal.server.model.ProjectId;
+import org.eclipse.emf.emfstore.internal.server.model.SessionId;
+import org.eclipse.emf.emfstore.internal.server.model.versioning.AbstractChangePackage;
+import org.eclipse.emf.emfstore.internal.server.model.versioning.HistoryInfo;
+import org.eclipse.emf.emfstore.internal.server.model.versioning.PrimaryVersionSpec;
+import org.eclipse.emf.emfstore.server.exceptions.ESException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+/**
+ * Handler for getting a list of change packages for given {@link HistoryInfo}s .
+ *
+ * @author mbarchfe
+ *
+ */
+public class LoadChangePackagesHandler extends AbstractEMFStoreHandler {
+
+	/**
+	 * Gets the selection from an {@link ExecutionEvent}. Only elements which are instances of the given class will be
+	 * returned.
+	 *
+	 * @param event the event
+	 * @param clazz the type
+	 * @return the selection
+	 *
+	 * @param <T> the type
+	 */
+	@SuppressWarnings("unchecked")
+	public static <T> List<T> getSelection(ExecutionEvent event, Class<T> clazz) {
+		final List<T> result = new ArrayList<T>();
+		ISelection sel = HandlerUtil.getCurrentSelection(event);
+		if (sel == null) {
+			sel = HandlerUtil.getActiveMenuSelection(event);
+		}
+		if (sel instanceof IStructuredSelection) {
+			final IStructuredSelection structuredSelection = (IStructuredSelection) sel;
+			@SuppressWarnings("rawtypes")
+			final Iterator it = structuredSelection.iterator();
+			while (it.hasNext()) {
+				final Object selectedElement = it.next();
+				if (clazz.isInstance(selectedElement)) {
+					result.add((T) selectedElement);
+				}
+			}
+		}
+		return result;
+	}
+
+	@Override
+	public void handle() {
+
+		final IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+		final IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
+		if (activePage == null) {
+			return;
+		}
+
+		if (!(activePage.getActivePart() instanceof HistoryBrowserView)) {
+			return;
+		}
+
+		final HistoryBrowserView view = (HistoryBrowserView) activePage.getActivePart();
+		final ProjectSpace projectSpace = view.getProjectSpace();
+		final ESWorkspaceProviderImpl esWorkspaceProviderImpl = ESWorkspaceProviderImpl.getInstance();
+
+		final ConnectionManager connectionManager = esWorkspaceProviderImpl.getConnectionManager();
+
+		final ProjectId projectId = projectSpace.getProjectId();
+		final SessionId sessionId = projectSpace.getUsersession().getSessionId();
+
+		final List<HistoryInfo> historyInfos = getSelection(getEvent(), HistoryInfo.class);
+		for (final HistoryInfo historyInfo : historyInfos) {
+			final PrimaryVersionSpec fromSpec = ModelUtil.clone(historyInfo.getPreviousSpec());
+			final PrimaryVersionSpec toSpec = ModelUtil.clone(historyInfo.getPrimarySpec());
+			// e.g. local change would be invalid to send to server
+			if (!isValid(fromSpec) || !isValid(toSpec)) {
+				continue;
+			}
+
+			try {
+				final List<AbstractChangePackage> changes = connectionManager.getChanges(sessionId, projectId,
+					fromSpec,
+					toSpec);
+				// the result should be one change package, if there were more or none this would be suprising
+				if (changes.size() != 1) {
+					ModelUtil.log(
+						MessageFormat.format("Expected to retrieve one change package but got {0}", changes.size()), //$NON-NLS-1$
+						null, IStatus.ERROR);
+				} else {
+					historyInfo.setChangePackage(changes.get(0));
+				}
+			} catch (final ESException ex) {
+				ModelUtil.log(
+					MessageFormat.format("Could not load changes for history info {0}", historyInfo), //$NON-NLS-1$
+					ex, IStatus.ERROR);
+			}
+			view.refresh(historyInfo);
+		}
+
+	}
+
+	private boolean isValid(PrimaryVersionSpec spec) {
+		return spec != null && spec.getIdentifier() > -1;
+	}
+
+}
diff --git a/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/views/historybrowserview/HistoryBrowserView.java b/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/views/historybrowserview/HistoryBrowserView.java
index bedac2a..d83ead1 100644
--- a/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/views/historybrowserview/HistoryBrowserView.java
+++ b/bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/views/historybrowserview/HistoryBrowserView.java
@@ -26,6 +26,8 @@
 import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
 import org.eclipse.emf.emfstore.client.ESLocalProject;
 import org.eclipse.emf.emfstore.client.util.ESVoidCallable;
+import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPoint;
+import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPointException;
 import org.eclipse.emf.emfstore.internal.client.common.UnknownEMFStoreWorkloadCommand;
 import org.eclipse.emf.emfstore.internal.client.model.ESWorkspaceProviderImpl;
 import org.eclipse.emf.emfstore.internal.client.model.ProjectSpace;
@@ -149,6 +151,25 @@
 	private boolean isUnlinkedFromNavigator;
 	private Action showAllBranches;
 
+	// changes can be transferred with historyInfos. However, this must be avoided if the server sends
+	// FileBasedChangePackages which the client can not open
+	private final static Boolean isLazyLoadingChanges;
+	private static final String ENABLE_LAZY_LOADING_OF_CHANGE_PACKAGES_EXTENSION_POINT = "org.eclipse.emf.emfstore.client.ui.enableLazyLoadingOfChangePackages"; //$NON-NLS-1$
+
+	static {
+		Boolean result;
+		try {
+			result = new ESExtensionPoint(ENABLE_LAZY_LOADING_OF_CHANGE_PACKAGES_EXTENSION_POINT, true)
+				.getBoolean("enabled", false); //$NON-NLS-1$
+			// set system property to be in sync with extension point and to be queryable for menu point enablement
+			System.setProperty(ENABLE_LAZY_LOADING_OF_CHANGE_PACKAGES_EXTENSION_POINT, result.toString()); // $NON-NLS-1$
+		} catch (final ESExtensionPointException e) {
+			// if no extension is available, check for system property
+			result = Boolean.getBoolean(ENABLE_LAZY_LOADING_OF_CHANGE_PACKAGES_EXTENSION_POINT); // $NON-NLS-1$
+		}
+		isLazyLoadingChanges = result;
+	}
+
 	/**
 	 * {@inheritDoc}
 	 */
@@ -158,6 +179,7 @@
 
 	@Override
 	public void createPartControl(Composite parent) {
+
 		GridLayoutFactory.fillDefaults().applyTo(parent);
 
 		initNoProjectHint(parent);
@@ -288,6 +310,15 @@
 		viewer.setInput(infos);
 	}
 
+	/**
+	 * Refresh a history info. Useful if a change package has been loaded lazily.
+	 * 
+	 * @param historyInfo the {@link HistoryInfo} to refresh
+	 */
+	public void refresh(HistoryInfo historyInfo) {
+		viewer.refresh(historyInfo);
+	}
+
 	private void addBaseVersionTag(List<HistoryInfo> infos) {
 		final HistoryInfo historyInfo = getHistoryInfo(projectSpace.getBaseVersion());
 		if (historyInfo != null) {
@@ -373,7 +404,7 @@
 			UPPER_LIMIT,
 			LOWER_LIMIT,
 			showAllVersions,
-			true);
+			!isLazyLoadingChanges);
 		// TODO: proivde util method
 		final ESHistoryQuery<ESModelElementQuery> api = query.toAPI();
 		final List<ESHistoryInfo> infos = projectSpace.toAPI().getHistoryInfos(api, new NullProgressMonitor());
@@ -386,7 +417,7 @@
 				centerVersion,
 				UPPER_LIMIT,
 				LOWER_LIMIT,
-				showAllVersions, true, true, true);
+				showAllVersions, true, true, !isLazyLoadingChanges);
 		final List<ESHistoryInfo> infos = projectSpace.toAPI().getHistoryInfos(
 			rangeQuery.toAPI(),
 			new NullProgressMonitor());