<commit_before>package org.gemoc.gemoc_language_workbench.extensions.sirius.modelloader;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.sirius.business.api.session.Session;
import org.eclipse.sirius.business.api.session.SessionManager;
import org.eclipse.sirius.common.tools.api.resource.ResourceSetFactory;
import org.eclipse.sirius.diagram.DDiagram;
import org.eclipse.sirius.diagram.business.internal.metamodel.spec.DSemanticDiagramSpec;
import org.eclipse.sirius.diagram.description.Layer;
import org.eclipse.sirius.diagram.tools.internal.command.ChangeLayerActivationCommand;
import org.eclipse.sirius.diagram.ui.tools.api.editor.DDiagramEditor;
import org.eclipse.sirius.diagram.ui.tools.api.graphical.edit.palette.ToolFilter;
import org.eclipse.sirius.ui.business.api.dialect.DialectUIManager;
import org.eclipse.sirius.viewpoint.DRepresentation;
import org.eclipse.sirius.viewpoint.DView;
import org.eclipse.sirius.viewpoint.description.tool.AbstractToolDescription;
import org.eclipse.ui.IEditorPart;
import org.eclipse.xtext.resource.XtextPlatformResourceURIHandler;
import org.eclipse.xtext.util.StringInputStream;
import org.gemoc.commons.eclipse.emf.EMFResource;
import org.gemoc.execution.engine.core.CommandExecution;
import org.gemoc.execution.engine.core.DebugURIHandler;
import org.gemoc.gemoc_language_workbench.api.core.ExecutionMode;
import org.gemoc.gemoc_language_workbench.api.core.IExecutionContext;
import org.gemoc.gemoc_language_workbench.api.core.IModelLoader;
import org.gemoc.gemoc_language_workbench.extensions.sirius.debug.DebugSessionFactory;
import org.gemoc.gemoc_language_workbench.extensions.sirius.services.AbstractGemocAnimatorServices;

import fr.obeo.dsl.debug.ide.sirius.ui.services.AbstractDSLDebuggerServices;

public class DefaultModelLoader implements IModelLoader {

	public final static String MODEL_ID = "org.gemoc.gemoc_modeling_workbench.ui.debugModel";

	public Resource loadModel(IExecutionContext context)
			throws RuntimeException {
		Resource resource = null;
		ResourceSet resourceSet;
		resourceSet = new ResourceSetImpl();
		resource = resourceSet.createResource(context.getRunConfiguration().getExecutedModelURI());		
		try {
			resource.load(null);
		} catch (IOException e) {
			new RuntimeException(e);
		}
		return resource;
	}
	
	public Resource loadModelForAnimation(IExecutionContext context)
			throws RuntimeException {
		Resource resource = null;
		ResourceSet resourceSet;
		if ( context.getRunConfiguration().getAnimatorURI() != null) {
			killPreviousSiriusSession(context.getRunConfiguration()
					.getAnimatorURI());
			Session session;
			try {
				session = openNewSiriusSession(context, context.getRunConfiguration()
						.getAnimatorURI());
				resourceSet = session.getTransactionalEditingDomain()
						.getResourceSet();
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}

			resource = resourceSet.getResources().get(0);
			return resource;
		} else 
		{	
			//animator not available; fall back to classic load
			return loadModel(context);
		}
	}

	private void killPreviousSiriusSession(URI sessionResourceURI) {
		Session session = SessionManager.INSTANCE
				.getExistingSession(sessionResourceURI);
		if (session != null) {
			session.close(new NullProgressMonitor());
			SessionManager.INSTANCE.remove(session);
		}
	}

	private Session openNewSiriusSession(IExecutionContext context, URI sessionResourceURI)
			throws CoreException 
	{
		boolean useMelange =context.getRunConfiguration().getMelangeQuery() != null && !context.getRunConfiguration().getMelangeQuery().isEmpty();	
		// calculating model URI as MelangeURI
		URI modelURI = useMelange ? context.getRunConfiguration().getExecutedModelAsMelangeURI() : context.getRunConfiguration().getExecutedModelURI();

		// create and configure resource set
		HashMap<String, String> nsURIMapping = getnsURIMapping(context); 
		final ResourceSet rs = createAndConfigureResourceSet(modelURI, nsURIMapping);
		
		// load model resource and resolve all proxies
		Resource r = rs.getResource(modelURI, true);
		
		// calculating aird URI
		URI airdURI = useMelange ? URI.createURI(sessionResourceURI.toString().replace("platform:/", "melange:/")): sessionResourceURI;		
		//URI airdURI = sessionResourceURI;

		// create and load sirius session
		final Session session = DebugSessionFactory.INSTANCE.createSession(rs, airdURI);
		final IProgressMonitor monitor = new NullProgressMonitor();
		final TransactionalEditingDomain editingDomain = session.getTransactionalEditingDomain();
		session.open(monitor);
		EcoreUtil.resolveAll(rs);
		// activating layers
		for (DView view : session.getSelectedViews()) {
			for (DRepresentation representation : view
					.getOwnedRepresentations()) {
				final DSemanticDiagramSpec diagram = (DSemanticDiagramSpec) representation;

				final List<EObject> elements = new ArrayList<EObject>();
				elements.add(diagram);
				
				final IEditorPart editorPart = DialectUIManager.INSTANCE.openEditor(session, representation,
						monitor);
				if (editorPart instanceof DDiagramEditor) {
					((DDiagramEditor)editorPart).getPaletteManager().addToolFilter(new ToolFilter() {
						
						@Override
						public boolean filter(DDiagram diagram, AbstractToolDescription tool) {
							return true;
						}
					});
				}
				
				RecordingCommand command = new RecordingCommand(
						editingDomain, "Activating animator and debug layers") {
					@Override
					protected void doExecute() {
						for (Layer l : diagram.getDescription()
								.getAdditionalLayers()) {
							boolean mustBeActive = AbstractDSLDebuggerServices.LISTENER
									.isRepresentationToRefresh(MODEL_ID,
											diagram.getDescription().getName(), l.getName())
											|| AbstractGemocAnimatorServices.ANIMATOR
											.isRepresentationToRefresh(
													diagram.getDescription().getName(),
													l.getName());
							if (mustBeActive
									&& !diagram.getActivatedLayers()
									.contains(l)) {
								ChangeLayerActivationCommand c = new ChangeLayerActivationCommand(
										editingDomain, diagram, l, monitor);
								c.execute();
							}
						}
					}
				};
				CommandExecution.execute(editingDomain, command);
			}
		}
		return session;
	}

	private ResourceSet createAndConfigureResourceSet(URI modelURI, HashMap<String, String> nsURIMapping) 
	{
		final ResourceSet rs = ResourceSetFactory.createFactory().createResourceSet(modelURI);
		// fix sirius to prevent non intentional model savings
		rs.getURIConverter().getURIHandlers().add(0, new DebugURIHandler());
		final String fileExtension = modelURI.fileExtension();
		// indicates which melange query should be added to the xml uri handler for a given extension 
		final XMLURIHandler handler = new XMLURIHandler(modelURI.query(), fileExtension); // use to resolve cross ref URI during XMI parsing
		handler.setResourceSet(rs);
		rs.getLoadOptions().put(XMLResource.OPTION_URI_HANDLER, handler);
		rs.setURIConverter(new MelangeURIConverter(fileExtension, nsURIMapping));
		return rs;
	}
<commit_msg>Fixed DefaultModelLoader to prevent save and to lock elements.<commit_after>package org.gemoc.gemoc_language_workbench.extensions.sirius.modelloader;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.sirius.business.api.session.Session;
import org.eclipse.sirius.business.api.session.SessionManager;
import org.eclipse.sirius.common.tools.api.resource.ResourceSetFactory;
import org.eclipse.sirius.diagram.DDiagram;
import org.eclipse.sirius.diagram.business.internal.metamodel.spec.DSemanticDiagramSpec;
import org.eclipse.sirius.diagram.description.Layer;
import org.eclipse.sirius.diagram.tools.internal.command.ChangeLayerActivationCommand;
import org.eclipse.sirius.diagram.ui.tools.api.editor.DDiagramEditor;
import org.eclipse.sirius.diagram.ui.tools.api.graphical.edit.palette.ToolFilter;
import org.eclipse.sirius.ui.business.api.dialect.DialectUIManager;
import org.eclipse.sirius.viewpoint.DRepresentation;
import org.eclipse.sirius.viewpoint.DView;
import org.eclipse.sirius.viewpoint.description.tool.AbstractToolDescription;
import org.eclipse.ui.IEditorPart;
import org.eclipse.xtext.resource.XtextPlatformResourceURIHandler;
import org.eclipse.xtext.util.StringInputStream;
import org.gemoc.commons.eclipse.emf.EMFResource;
import org.gemoc.execution.engine.core.CommandExecution;
import org.gemoc.execution.engine.core.DebugURIHandler;
import org.gemoc.gemoc_language_workbench.api.core.ExecutionMode;
import org.gemoc.gemoc_language_workbench.api.core.IExecutionContext;
import org.gemoc.gemoc_language_workbench.api.core.IModelLoader;
import org.gemoc.gemoc_language_workbench.extensions.sirius.debug.DebugSessionFactory;
import org.gemoc.gemoc_language_workbench.extensions.sirius.services.AbstractGemocAnimatorServices;

import fr.obeo.dsl.debug.ide.sirius.ui.services.AbstractDSLDebuggerServices;

public class DefaultModelLoader implements IModelLoader {

	public final static String MODEL_ID = "org.gemoc.gemoc_modeling_workbench.ui.debugModel";

	public Resource loadModel(IExecutionContext context)
			throws RuntimeException {
		Resource resource = null;
		ResourceSet resourceSet;
		resourceSet = new ResourceSetImpl();
		resource = resourceSet.createResource(context.getRunConfiguration().getExecutedModelURI());		
		try {
			resource.load(null);
		} catch (IOException e) {
			new RuntimeException(e);
		}
		return resource;
	}
	
	public Resource loadModelForAnimation(IExecutionContext context)
			throws RuntimeException {
		Resource resource = null;
		ResourceSet resourceSet;
		if ( context.getRunConfiguration().getAnimatorURI() != null) {
			killPreviousSiriusSession(context.getRunConfiguration()
					.getAnimatorURI());
			Session session;
			try {
				session = openNewSiriusSession(context, context.getRunConfiguration()
						.getAnimatorURI());
				resourceSet = session.getTransactionalEditingDomain()
						.getResourceSet();
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}

			resource = resourceSet.getResources().get(0);
			return resource;
		} else 
		{	
			//animator not available; fall back to classic load
			return loadModel(context);
		}
	}

	private void killPreviousSiriusSession(URI sessionResourceURI) {
		Session session = SessionManager.INSTANCE
				.getExistingSession(sessionResourceURI);
		if (session != null) {
			session.close(new NullProgressMonitor());
			SessionManager.INSTANCE.remove(session);
		}
	}

	private Session openNewSiriusSession(IExecutionContext context, URI sessionResourceURI)
			throws CoreException 
	{
		boolean useMelange =context.getRunConfiguration().getMelangeQuery() != null && !context.getRunConfiguration().getMelangeQuery().isEmpty();	
		// calculating model URI as MelangeURI
		URI modelURI = useMelange ? context.getRunConfiguration().getExecutedModelAsMelangeURI() : context.getRunConfiguration().getExecutedModelURI();

		// create and configure resource set
		HashMap<String, String> nsURIMapping = getnsURIMapping(context); 
		final ResourceSet rs = createAndConfigureResourceSet(modelURI, nsURIMapping);
		
		// load model resource and resolve all proxies
		Resource r = rs.getResource(modelURI, true);
		
		// calculating aird URI
		URI airdURI = useMelange ? URI.createURI(sessionResourceURI.toString().replace("platform:/", "melange:/")): sessionResourceURI;		
		//URI airdURI = sessionResourceURI;

		// create and load sirius session
		final Session session = DebugSessionFactory.INSTANCE.createSession(rs, airdURI);
		final IProgressMonitor monitor = new NullProgressMonitor();
		final TransactionalEditingDomain editingDomain = session.getTransactionalEditingDomain();
		session.open(monitor);
		EcoreUtil.resolveAll(rs);
		// activating layers
		for (DView view : session.getSelectedViews()) {
			for (DRepresentation representation : view
					.getOwnedRepresentations()) {
				final DSemanticDiagramSpec diagram = (DSemanticDiagramSpec) representation;

				final List<EObject> elements = new ArrayList<EObject>();
				elements.add(diagram);
				
				final IEditorPart editorPart = DialectUIManager.INSTANCE.openEditor(session, representation,
						monitor);
				if (editorPart instanceof DDiagramEditor) {
					((DDiagramEditor)editorPart).getPaletteManager().addToolFilter(new ToolFilter() {
						
						@Override
						public boolean filter(DDiagram diagram, AbstractToolDescription tool) {
							return true;
						}
					});
				}
				
				RecordingCommand command = new RecordingCommand(
						editingDomain, "Activating animator and debug layers") {
					@Override
					protected void doExecute() {
						for (Layer l : diagram.getDescription()
								.getAdditionalLayers()) {
							boolean mustBeActive = AbstractDSLDebuggerServices.LISTENER
									.isRepresentationToRefresh(MODEL_ID,
											diagram.getDescription().getName(), l.getName())
											|| AbstractGemocAnimatorServices.ANIMATOR
											.isRepresentationToRefresh(
													diagram.getDescription().getName(),
													l.getName());
							if (mustBeActive
									&& !diagram.getActivatedLayers()
									.contains(l)) {
								ChangeLayerActivationCommand c = new ChangeLayerActivationCommand(
										editingDomain, diagram, l, monitor);
								c.execute();
							}
						}
					}
				};
				CommandExecution.execute(editingDomain, command);
			}
		}
		return session;
	}

	private ResourceSet createAndConfigureResourceSet(URI modelURI, HashMap<String, String> nsURIMapping) 
	{
		final ResourceSet rs = ResourceSetFactory.createFactory().createResourceSet(modelURI);
		final String fileExtension = modelURI.fileExtension();
		// indicates which melange query should be added to the xml uri handler for a given extension 
		final XMLURIHandler handler = new XMLURIHandler(modelURI.query(), fileExtension); // use to resolve cross ref URI during XMI parsing
		handler.setResourceSet(rs);
		rs.getLoadOptions().put(XMLResource.OPTION_URI_HANDLER, handler);
		final MelangeURIConverter converter = new MelangeURIConverter(fileExtension, nsURIMapping);
		rs.setURIConverter(converter);
		// fix sirius to prevent non intentional model savings
		converter.getURIHandlers().add(0, new DebugURIHandler());
		return rs;
	}

{'fraction_non_alphanumeric': 0.09656988775318241, 'fraction_numerical': 0.0002508308772809933, 'mean_word_length': 4.884870848708487, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1096312', 'n_tokens_mistral': 5316, 'n_tokens_neox': 4583, 'n_words': 864}