/** @generated */ public boolean performFinish() { LinkedList<IFile> affectedFiles = new LinkedList<IFile>(); IFile diagramFile = myFileCreationPage.createNewFile(); de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorUtil.setCharset( diagramFile); affectedFiles.add(diagramFile); URI diagramModelURI = URI.createPlatformResourceURI(diagramFile.getFullPath().toString(), true); ResourceSet resourceSet = myEditingDomain.getResourceSet(); final Resource diagramResource = resourceSet.createResource(diagramModelURI); AbstractTransactionalCommand command = new AbstractTransactionalCommand( myEditingDomain, de.tud.cs.st.vespucci.vespucci_model.diagram.part.Messages .VespucciNewDiagramFileWizard_InitDiagramCommand, affectedFiles) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { int diagramVID = de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciVisualIDRegistry .getDiagramVisualID(diagramRootElementSelectionPage.getModelElement()); if (diagramVID != de.tud.cs.st.vespucci.vespucci_model.diagram.edit.parts.ShapesDiagramEditPart .VISUAL_ID) { return CommandResult.newErrorCommandResult( de.tud.cs.st.vespucci.vespucci_model.diagram.part.Messages .VespucciNewDiagramFileWizard_IncorrectRootError); } Diagram diagram = ViewService.createDiagram( diagramRootElementSelectionPage.getModelElement(), de.tud.cs.st.vespucci.vespucci_model.diagram.edit.parts.ShapesDiagramEditPart .MODEL_ID, de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin .DIAGRAM_PREFERENCES_HINT); diagramResource.getContents().add(diagram); diagramResource.getContents().add(diagram.getElement()); return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); diagramResource.save( de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorUtil .getSaveOptions()); de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorUtil.openDiagram( diagramResource); } catch (ExecutionException e) { de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } catch (IOException ex) { de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin.getInstance() .logError("Save operation failed for: " + diagramModelURI, ex); // $NON-NLS-1$ } catch (PartInitException ex) { de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin.getInstance() .logError("Unable to open editor", ex); // $NON-NLS-1$ } return true; }
@SuppressWarnings("unchecked") protected void moveData(final IStructuredSelection structuredSelection) { final MoveDataWizard moveDataWizard = new MoveDataWizard((DataAware) getEObject()); if (new WizardDialog(Display.getDefault().getActiveShell(), moveDataWizard).open() == Dialog.OK) { final DataAware dataAware = moveDataWizard.getSelectedDataAwareElement(); try { final MoveDataCommand cmd = new MoveDataCommand( getEditingDomain(), (DataAware) getEObject(), structuredSelection.toList(), dataAware); OperationHistoryFactory.getOperationHistory().execute(cmd, null, null); if (!(cmd.getCommandResult().getStatus().getSeverity() == Status.OK)) { final List<Object> data = (List<Object>) cmd.getCommandResult().getReturnValue(); String dataNames = ""; for (final Object d : data) { dataNames = dataNames + ((Element) d).getName() + ","; } dataNames = dataNames.substring(0, dataNames.length() - 1); MessageDialog.openWarning( Display.getDefault().getActiveShell(), Messages.PromoteDataWarningTitle, Messages.bind(Messages.PromoteDataWarningMessage, dataNames)); } } catch (final ExecutionException e1) { BonitaStudioLog.error(e1); } refresh(); } }
private void updateCallBlock(final CallNode node, final ListEntry entry) { final TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(diagramEditPart.getModel()); AbstractTransactionalCommand command = new AbstractTransactionalCommand(editingDomain, "Update CallNode", Collections.EMPTY_LIST) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { String startNode = entry.getMessage(); ListEntry parent = entry.getParent(); String callFlow = parent.getMessage() + "-" + startNode; node.setName(callFlow.substring(callFlow.lastIndexOf("-") + 1)); node.setFlowName(callFlow); return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new SubProgressMonitor(new NullProgressMonitor(), 1), null); } catch (ExecutionException e) { Neuro4jDiagramEditorPlugin.getInstance() .logError("Unable to update call node", e); // $NON-NLS-1$ } }
/** * Run as transaction. * * @param diResourceSet the di resource set */ protected void runAsTransaction(final DiResourceSet diResourceSet) { // Get the uml element to which the newly created diagram will be attached. // Create the diagram final Resource modelResource = diResourceSet.getModelResource(); TransactionalEditingDomain editingDomain = diResourceSet.getTransactionalEditingDomain(); AbstractTransactionalCommand command = new AbstractTransactionalCommand( editingDomain, "Initialize model", Collections.EMPTY_LIST) { @Override protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { CommandResult commandResult = CommandResult.newErrorCommandResult("Error during diagram creation"); EObject model = getRootElement(modelResource); attachModelToResource(model, modelResource); initializeModel(model); return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); } catch (ExecutionException e) { e.printStackTrace(); } }
/** * Permet de créer la région en 0,0 pour le diagramme * * @generated NOT */ @Override public void activate() { super.activate(); AbstractEMFOperation emfOp = new AbstractEMFOperation(getEditingDomain(), "Location setting") { @Override protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { // TODO Auto-generated method stub // Recupération du layout et mis a jour en (0,0) Location lc = (Location) ((Node) getModel()).getLayoutConstraint(); lc.setX(0); lc.setY(0); return Status.OK_STATUS; } }; IStatus status; try { status = OperationHistoryFactory.getOperationHistory().execute(emfOp, null, null); } catch (ExecutionException e) { status = new Status(IStatus.ERROR, ImaginDataDiagramEditorPlugin.ID, "Setting location failed", e); } if (status.getCode() == IStatus.WARNING || status.getCode() == IStatus.ERROR) { ImaginDataDiagramEditorPlugin.getInstance().getLog().log(status); } }
/** * The <code>AbstractTextEditor</code> implementation of this <code>IWorkbenchPart</code> method * may be extended by subclasses. Subclasses must call <code>super.dispose()</code>. * * <p>Note that many methods may return <code>null</code> after the editor is disposed. */ @Override public void dispose() { if (fTitleImage != null) { fTitleImage.dispose(); fTitleImage = null; } disposeDocumentProvider(); if (fSourceViewer != null) { fSourceViewer = null; } if (fConfiguration != null) fConfiguration = null; IOperationHistory history = OperationHistoryFactory.getOperationHistory(); if (history != null) { if (fNonLocalOperationApprover != null) history.removeOperationApprover(fNonLocalOperationApprover); if (fLinearUndoViolationApprover != null) history.removeOperationApprover(fLinearUndoViolationApprover); } fNonLocalOperationApprover = null; fLinearUndoViolationApprover = null; super.dispose(); }
/** * This method should be called within a workspace modify operation since it creates resources. * * @generated */ public static Resource createDiagram( URI diagramURI, URI modelURI, final String diagramName, final String diagramNameWithoutExtension, final EClass initialObject, final String encoding, IProgressMonitor progressMonitor) { TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain(); progressMonitor.beginTask(Messages.UMLDiagramEditorUtil_CreateDiagramProgressTask, 3); final Resource diagramResource = editingDomain.getResourceSet().createResource(diagramURI); final Resource modelResource = editingDomain.getResourceSet().createResource(modelURI); AbstractTransactionalCommand command = new AbstractTransactionalCommand( editingDomain, Messages.UMLDiagramEditorUtil_CreateDiagramCommandLabel, Collections.EMPTY_LIST) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { Package model = createInitialModel(initialObject, diagramNameWithoutExtension); attachModelToResource(model, modelResource); Diagram diagram = ViewService.createDiagram( model, PackageEditPart.MODEL_ID, UMLDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); if (diagram != null) { diagramResource.getContents().add(diagram); diagram.setName(diagramName); diagram.setElement(model); } try { modelResource.save( org.eclipse.uml2.diagram.csd.part.UMLDiagramEditorUtil.getSaveOptions(encoding)); diagramResource.save( org.eclipse.uml2.diagram.csd.part.UMLDiagramEditorUtil.getSaveOptions(encoding)); } catch (IOException e) { UMLDiagramEditorPlugin.getInstance() .logError("Unable to store model and diagram resources", e); // $NON-NLS-1$ } return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new SubProgressMonitor(progressMonitor, 1), null); } catch (ExecutionException e) { UMLDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } setCharset(WorkspaceSynchronizer.getFile(modelResource)); setCharset(WorkspaceSynchronizer.getFile(diagramResource)); return diagramResource; }
@Override public void dispose() { OperationHistoryFactory.getOperationHistory().removeOperationHistoryListener(historyListener); sessionManager.removeSarosSessionListener(sessionListener); editorManager.removeActivityListener(activityListener); enabled = false; eclipseHistory.removeOperationApprover(operationBlocker); editorManager.removeSharedEditorListener(sharedEditorListener); }
public UndoManager(ISarosSessionManager sessionManager, EditorManager editorManager) { if (log.isDebugEnabled()) DefaultOperationHistory.DEBUG_OPERATION_HISTORY_APPROVAL = true; OperationHistoryFactory.getOperationHistory().addOperationHistoryListener(historyListener); sessionManager.addSarosSessionListener(sessionListener); this.sessionManager = sessionManager; editorManager.addActivityListener(this.activityListener); addProvider(editorManager); this.editorManager = editorManager; editorManager.addSharedEditorListener(sharedEditorListener); }
public boolean performFinish() { AbstractTransactionalCommand command = new AbstractTransactionalCommand(myEditingDomain, "Creating new product's project", null) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { try { ProductGenerator productGenerator = new ProductGenerator( diagramRoot, variativitySelectionPage.getText(), filePath, variativitySelectionPage.getCheckedElements()); if (productDiagramRoot != null) { List<String> oldPages = new ArrayList<String>(); DiagramContainer container = new DiagramContainer(productDiagramRoot); for (Page page : container.getPageElements()) { oldPages.add(page.getSource()); } productGenerator.setOldPages(oldPages); } productGenerator.generate(); initDiagramFile(); IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (ProjectOperationException e) { e.printStackTrace(); return CommandResult.newErrorCommandResult(e.getMessage()); } catch (Exception e) { e.printStackTrace(); return CommandResult.newErrorCommandResult(e.getMessage()); } return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); } catch (ExecutionException e) { PlwebDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } return true; }
/** @generated */ public static Resource createDiagram(URI diagramURI, IProgressMonitor progressMonitor) { TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain(); progressMonitor.beginTask(Messages.RoxgtDiagramEditorUtil_CreateDiagramProgressTask, 3); final Resource diagramResource = editingDomain.getResourceSet().createResource(diagramURI); final String diagramName = diagramURI.lastSegment(); AbstractTransactionalCommand command = new AbstractTransactionalCommand( editingDomain, Messages.RoxgtDiagramEditorUtil_CreateDiagramCommandLabel, Collections.EMPTY_LIST) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { Graph model = createInitialModel(); attachModelToResource(model, diagramResource); Diagram diagram = ViewService.createDiagram( model, GraphEditPart.MODEL_ID, RoxgtDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); if (diagram != null) { diagramResource.getContents().add(diagram); diagram.setName(diagramName); diagram.setElement(model); } try { diagramResource.save(org.roxgt.diagram.part.RoxgtDiagramEditorUtil.getSaveOptions()); } catch (IOException e) { RoxgtDiagramEditorPlugin.getInstance() .logError("Unable to store model and diagram resources", e); // $NON-NLS-1$ } return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new SubProgressMonitor(progressMonitor, 1), null); } catch (ExecutionException e) { RoxgtDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } return diagramResource; }
protected void initDiagramFile() throws CoreException { List<IFile> affectedFiles = new LinkedList<IFile>(); final IFile diagramFile = createNewFile(); PlwebDiagramEditorUtil.setCharset(diagramFile); affectedFiles.add(diagramFile); URI diagramModelURI = URI.createPlatformResourceURI(diagramFile.getFullPath().toString(), true); TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain(); ResourceSet resourceSet = editingDomain.getResourceSet(); final Resource diagramResource = resourceSet.createResource(diagramModelURI); AbstractTransactionalCommand command = new AbstractTransactionalCommand( editingDomain, Messages.PlwebNewDiagramFileWizard_InitDiagramCommand, affectedFiles) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { DiagramRoot element = getElement(getEditingDomain()); int diagramVID = PlwebVisualIDRegistry.getDiagramVisualID(element); if (diagramVID != DiagramRootEditPart.VISUAL_ID) { return CommandResult.newErrorCommandResult( Messages.PlwebNewDiagramFileWizard_IncorrectRootError); } Diagram diagram = ViewService.createDiagram( element, DiagramRootEditPart.MODEL_ID, PlwebDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); diagramResource.getContents().add(diagram); return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); diagramResource.save(PlwebDiagramEditorUtil.getSaveOptions()); PlwebDiagramEditorUtil.openDiagram(diagramResource); } catch (ExecutionException e) { PlwebDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } catch (IOException ex) { PlwebDiagramEditorPlugin.getInstance() .logError("Save operation failed for: " + diagramModelURI, ex); // $NON-NLS-1$ } catch (PartInitException ex) { PlwebDiagramEditorPlugin.getInstance().logError("Unable to open editor", ex); // $NON-NLS-1$ } }
/** * Execute the passed Runnable within a command * * @param label * @param command */ public static void exec(TransactionalEditingDomain domain, String label, final Runnable command) { // do works, undo does not (but is selectable in Papyrus Model explorer) IOperationHistory history = OperationHistoryFactory.getOperationHistory(); try { history.execute( new AbstractTransactionalCommand(domain, label, Collections.EMPTY_LIST) { @Override public CommandResult doExecuteWithResult(IProgressMonitor dummy, IAdaptable info) { command.run(); return CommandResult.newOKCommandResult(); } }, null, null); } catch (ExecutionException e) { e.printStackTrace(); } }
/** * 设置是否添加到记忆库 * * @param selectedRowIds * @param state "yes" or "no"; */ public void changeSendToTmState(List<String> selectedRowIds, String state) { IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); try { operationHistory.execute( new SendTOTmOperation( "send-to-tm", xliffEditor.getTable(), selectedRowIds, xliffEditor.getXLFHandler(), state), null, null); } catch (ExecutionException e) { LOGGER.error("", e); MessageDialog.openError( xliffEditor.getSite().getShell(), Messages.getString("utils.NattableUtil.msgTitle2"), e.getMessage()); e.printStackTrace(); } }
/** * 改变Target的状态 * * @param state 状态值("new", "final", "translated", "signed-off", "needs-adaptation", * "needs-review-adaptation", "needs-l10n", "needs-review-l10n", "needs-translation", * "needs-review-translation"); */ public void changeTgtState( final List<String> selectedRowIds, final String state, IProgressMonitor monitor) { if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask(Messages.getString("utils.NattableUtil.task4"), 1); monitor.worked(1); final IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); final IProgressMonitor monitor2 = monitor; Display.getDefault() .syncExec( new Runnable() { public void run() { try { operationHistory.execute( new StateOperation( "State", xliffEditor.getTable(), selectedRowIds, xliffEditor.getXLFHandler(), state), monitor2, null); } catch (ExecutionException e) { LOGGER.error("", e); MessageDialog.openError( xliffEditor.getSite().getShell(), Messages.getString("utils.NattableUtil.msgTitle2"), e.getMessage()); e.printStackTrace(); } } }); monitor.done(); }
/** @generated */ public boolean performFinish() { CreateViewRequest.ViewDescriptor viewDescriptor = new CreateViewRequest.ViewDescriptor( new EObjectAdapter(referencedElementSelectionPage.getModelElement()), Node.class, null, EMFProfileDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); ICommand command = new CreateCommand(editingDomain, viewDescriptor, referencedElementSelectionPage.getView()); command = command.compose( new EMFProfileCreateShortcutDecorationsCommand( editingDomain, referencedElementSelectionPage.getView(), viewDescriptor)); try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); } catch (ExecutionException ee) { EMFProfileDiagramEditorPlugin.getInstance() .logError("Unable to create shortcut", ee); // $NON-NLS-1$ } return true; }
/** 合并文本段 ; */ public void mergeSegment() { XLFHandler handler = xliffEditor.getXLFHandler(); List<String> lstRowId = xliffEditor.getSelectedRowIds(); List<String> lstAllRowId = xliffEditor.getXLFHandler().getAllRowIds(); Shell shell = xliffEditor.getSite().getShell(); if (lstRowId.size() < 2) { MessageDialog.openInformation( shell, Messages.getString("utils.NattableUtil.mergeSegment.msgTitle"), Messages.getString("utils.NattableUtil.mergeSegment.msg1")); return; } Collections.sort(lstRowId, new SortRowIdComparator()); Collections.sort(lstAllRowId, new SortRowIdComparator()); String rowId1 = lstRowId.get(0); String fileName = RowIdUtil.getFileNameByRowId(rowId1); if (fileName == null) { return; } if (handler.isLocked(rowId1)) { MessageDialog.openInformation( shell, Messages.getString("utils.NattableUtil.mergeSegment.msgTitle"), Messages.getString("utils.NattableUtil.mergeSegment.msg3")); return; } for (int i = 1; i < lstRowId.size(); i++) { String rowId = lstRowId.get(i); if (handler.isLocked(rowId)) { MessageDialog.openInformation( shell, Messages.getString("utils.NattableUtil.mergeSegment.msgTitle"), Messages.getString("utils.NattableUtil.mergeSegment.msg3")); return; } String fileName2 = RowIdUtil.getFileNameByRowId(rowId); // 数组集合必须在一个文件中才能合并 if (fileName2 == null || !fileName.equals(fileName2)) { MessageDialog.openInformation( shell, Messages.getString("utils.NattableUtil.mergeSegment.msgTitle"), Messages.getString("utils.NattableUtil.mergeSegment.msg4")); return; } // 判断所选文本段是否连续 String strCurTuId = RowIdUtil.getTUIdByRowId(rowId); String strPreTuId = RowIdUtil.getTUIdByRowId(lstRowId.get(i - 1)); if (strCurTuId == null || strPreTuId == null) { return; } if ((lstAllRowId.indexOf(rowId) - lstAllRowId.indexOf(lstRowId.get(i - 1))) != 1) { MessageDialog.openInformation( shell, Messages.getString("utils.NattableUtil.mergeSegment.msgTitle"), Messages.getString("utils.NattableUtil.mergeSegment.msg5")); return; } else { String curOriginal = RowIdUtil.getOriginalByRowId(rowId); String preOriginal = RowIdUtil.getOriginalByRowId(lstRowId.get(i - 1)); if (!curOriginal.equals(preOriginal)) { MessageDialog.openInformation( shell, Messages.getString("utils.NattableUtil.mergeSegment.msgTitle"), Messages.getString("utils.NattableUtil.mergeSegment.msg5")); return; } } } // Bug #2373:选择全部文本段合并后,无显示内容 if (lstRowId.size() == xliffEditor.getXLFHandler().getRowIds().size()) { xliffEditor.jumpToRow(0); } MergeSegmentOperation mergeOper = new MergeSegmentOperation("merge segment", xliffEditor, handler, lstRowId); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); try { operationHistory.execute(mergeOper, null, null); } catch (Exception e) { LOGGER.error("", e); } }
// just for testing protected UndoManager() { DefaultOperationHistory.DEBUG_OPERATION_HISTORY_APPROVAL = true; OperationHistoryFactory.getOperationHistory().addOperationHistoryListener(historyListener); }
/** * This UndoManager is not an implementation of the Eclipse IUndoManager. It only listens to the * internal Eclipse UndoManager, catches every Typing Operation about to be undone and calls instead * this.undo(). Warning: After the first Undo the Undo button stays activated, even if there is * nothing to undo. This is caused by design because we cancel the regular Eclipse Undo operation. * So there is always something to undo in the Eclipse History and the button is never deactivated. * TODO This UndoManager is switched off currently. To activate it it has to be added to the * PicoContainer in Saros.class. */ @Component(module = "undo") public class UndoManager extends AbstractActivityProvider implements Disposable { private static final Logger log = Logger.getLogger(UndoManager.class); protected List<TextEditActivity> expectedActivities = new LinkedList<TextEditActivity>(); /** * Every IUndoableOperation has a label to classify it. Typing operations have this label - as * long as Eclipse doesn't change the label. */ protected static final String TYPING_LABEL = "Typing"; @Inject protected PreferenceUtils preferences; protected ISarosSessionManager sessionManager; protected ISarosSession sarosSession; protected InclusionTransformation transformation = new GOTOInclusionTransformation(); /** The concurrent OperationHistory */ protected OperationHistory undoHistory = new OperationHistory(); protected IOperationHistory eclipseHistory = OperationHistoryFactory.getOperationHistory(); protected IUndoContext context = IOperationHistory.GLOBAL_UNDO_CONTEXT; protected EditorManager editorManager; protected List<IActivityProvider> providers = new LinkedList<IActivityProvider>(); protected SPath currentActiveEditor = null; /** This UndoManager is disabled when not in a Saros session. */ protected boolean enabled; /** * To avoid splitting local operations in too many pieces, the local operations that are added to * the history are combined with the subsequent ones. A combined operation begins when Eclipse * triggered the OPERATION_ADDED history event and ends right before the next one. */ protected Operation currentLocalCompositeOperation = null; /** The currentLocalAtomicOperation is the latest operation that was applied locally. */ protected Operation currentLocalAtomicOperation = null; /** * The most important part of the undo integration. If an Undo/Redo is triggered the Eclipse * history consults all of its IOperationApprover whether the Undo / Redo may be applied. We veto * it and call this.undo() / this.redo() instead. */ protected IOperationApprover operationBlocker = new IOperationApprover() { protected String opInfo(IUndoableOperation operation) { return ("new " + operation.getLabel() + ": " + operation); } @Override public IStatus proceedRedoing( final IUndoableOperation operation, IOperationHistory history, IAdaptable info) { if (!enabled) return Status.OK_STATUS; if (currentActiveEditor == null) { log.info("Redo called on an unknown editor"); return Status.OK_STATUS; } if (log.isDebugEnabled()) log.debug(opInfo(operation)); if (operation.getLabel().equals(TYPING_LABEL) || operation.getLabel().equals(NullOperation.LABEL)) { updateCurrentLocalAtomicOperation(null); storeCurrentLocalOperation(); SWTUtils.runSafeSWTSync( log, new Runnable() { @Override public void run() { log.debug("redoing operation " + operation); redo(currentActiveEditor); /* * For reactivating redo an undo has to be simulated, so * the Eclipse history knows, there is something to * redo. */ if (undoHistory.canRedo(currentActiveEditor)) simulateUndo(); } }); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } @Override public IStatus proceedUndoing( final IUndoableOperation operation, IOperationHistory history, IAdaptable info) { if (!enabled) return Status.OK_STATUS; if (currentActiveEditor == null) { log.info("Undo called on an unknown editor"); return Status.OK_STATUS; } if (log.isDebugEnabled()) log.debug(opInfo(operation)); if (operation.getLabel().equals(TYPING_LABEL)) { updateCurrentLocalAtomicOperation(null); storeCurrentLocalOperation(); SWTUtils.runSafeSWTSync( log, new Runnable() { @Override public void run() { log.debug("undoing operation " + operation); undo(currentActiveEditor); if (undoHistory.canRedo(currentActiveEditor)) simulateUndo(); } }); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; /** * A NullOperation is an IUndoableOperation that can be executed, undone and redone without having * any effect, except returning OK_STATUS. */ protected static class NullOperation extends AbstractOperation { /* * The user shouldn't see a difference in the label between normal * typing operations and NullOperations. But we should be able to * distinguish them. So a single space is added to the typing label. */ public static final String LABEL = TYPING_LABEL + " "; public NullOperation() { super(LABEL); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.OK_STATUS; } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.OK_STATUS; } } /** * The UndoManager only works during a running Saros session. Otherwise the Eclipse UndoManager * has to manage Undos and Redos. This SessionListener enables and disables the UndoManager and * does cleanup works at the begin and the end of a session. */ protected ISarosSessionListener sessionListener = new AbstractSarosSessionListener() { @Override public void sessionStarted(ISarosSession newSarosSession) { undoHistory.clear(); newSarosSession.addActivityProvider(UndoManager.this); enabled = preferences.isConcurrentUndoActivated(); eclipseHistory.addOperationApprover(operationBlocker); UndoManager.this.sarosSession = newSarosSession; } @Override public void sessionEnded(ISarosSession oldSarosSession) { oldSarosSession.removeActivityProvider(UndoManager.this); undoHistory.clear(); enabled = false; eclipseHistory.removeOperationApprover(operationBlocker); UndoManager.this.sarosSession = null; currentLocalCompositeOperation = null; currentLocalAtomicOperation = null; } }; /** * Updates the local current active editor. If the editor changes the current local operation is * stored in history. */ protected ISharedEditorListener sharedEditorListener = new AbstractSharedEditorListener() { @Override public void activeEditorChanged(User user, SPath newActiveEditor) { if (!user.isLocal() || ObjectUtils.equals(currentActiveEditor, newActiveEditor)) return; updateCurrentLocalAtomicOperation(null); storeCurrentLocalOperation(); currentActiveEditor = newActiveEditor; } @Override public void editorRemoved(User user, SPath closedEditor) { if (ObjectUtils.equals(currentActiveEditor, closedEditor)) { updateCurrentLocalAtomicOperation(null); storeCurrentLocalOperation(); currentActiveEditor = null; } undoHistory.clearEditorHistory(closedEditor); } }; protected IActivityListener activityListener = new IActivityListener() { @Override public void activityCreated(final IActivity activity) { SWTUtils.runSafeSWTSync( log, new Runnable() { @Override public void run() { activity.dispatch(activityReceiver); } }); } }; protected IActivityReceiver activityReceiver = new AbstractActivityReceiver() { /** @return true if the given Activity was created locally */ protected boolean local(IActivity activity) { return activity.getSource().isLocal(); } /** Updates the current local operation and adds remote operations to the undo history. */ @Override public void receive(TextEditActivity textEditActivity) { if (!enabled) return; /* * When performing an undo/redo there are fired Activities which are * expected and have to be ignored when coming back. */ if (expectedActivities.remove(textEditActivity)) return; Operation operation = textEditActivity.toOperation(); if (!local(textEditActivity)) { if (currentLocalCompositeOperation != null) currentLocalCompositeOperation = transformation.transform( currentLocalCompositeOperation, operation, Boolean.FALSE); if (currentLocalAtomicOperation != null) { currentLocalAtomicOperation = transformation.transform(currentLocalAtomicOperation, operation, Boolean.FALSE); } log.debug("adding remote " + operation + " to history"); undoHistory.add(textEditActivity.getPath(), Type.REMOTE, operation); } else { if (!textEditActivity.getPath().equals(currentActiveEditor)) { log.error( "Editor of the local TextEditActivity is not the current " + "active editor. Possibly the current active editor is not" + " up to date."); return; } updateCurrentLocalAtomicOperation(operation); } return; } }; public IOperationHistoryListener historyListener = new IOperationHistoryListener() { @Override public void historyNotification(OperationHistoryEvent event) { if (!enabled) return; /* * OPERATION_ADDED is triggered when Eclipse adds a new operation to * its history. We do the same on this event. */ if (event.getEventType() == OperationHistoryEvent.OPERATION_ADDED) { storeCurrentLocalOperation(); updateCurrentLocalAtomicOperation(null); } /* * OPERATION_CHANGED is triggered when Eclipse changes the operation * that is recently added to its history. For example: Eclipse adds * Insert(3,"A") to its operation and later on the user enters B at * position 4. If Eclipse decides not to add a new Undo step it * changes the most recent operation in history to Insert(3, "AB") */ if (event.getEventType() == OperationHistoryEvent.OPERATION_CHANGED) { updateCurrentLocalAtomicOperation(null); } } }; public UndoManager(ISarosSessionManager sessionManager, EditorManager editorManager) { if (log.isDebugEnabled()) DefaultOperationHistory.DEBUG_OPERATION_HISTORY_APPROVAL = true; OperationHistoryFactory.getOperationHistory().addOperationHistoryListener(historyListener); sessionManager.addSarosSessionListener(sessionListener); this.sessionManager = sessionManager; editorManager.addActivityListener(this.activityListener); addProvider(editorManager); this.editorManager = editorManager; editorManager.addSharedEditorListener(sharedEditorListener); } // just for testing protected UndoManager() { DefaultOperationHistory.DEBUG_OPERATION_HISTORY_APPROVAL = true; OperationHistoryFactory.getOperationHistory().addOperationHistoryListener(historyListener); } /** @return operation that reverts the effect of the latest local operation in the given editor */ protected Operation calcUndoOperation(SPath editor) { if (!undoHistory.canUndo(editor)) return new NoOperation(); // nothing to undo Operation lastLocal = undoHistory.getLatestLocal(editor); assert lastLocal != null; Operation undoOperation = lastLocal.invert(); for (EditorHistoryEntry entry : undoHistory.entriesToLatestLocal(editor)) { Operation operation = entry.getOperation(); undoOperation = transformation.transform(undoOperation, operation, Boolean.TRUE); log.debug("transformed undo: " + undoOperation); } undoHistory.replaceType(editor, lastLocal, Type.LOCAL, Type.REMOTE); // it is not relevant any more, so it is set remote undoHistory.add(editor, Type.REDOABLE, undoOperation); // save for redo return undoOperation; } /** @return operation that reverts the effect of the latest undo in the given editor */ protected Operation calcRedoOperation(SPath editor) { if (!undoHistory.canRedo(editor)) return new NoOperation(); // nothing to redo Operation lastUndo = undoHistory.getLatestRedoable(editor); assert lastUndo != null; Operation redoOperation = lastUndo.invert(); for (EditorHistoryEntry entry : undoHistory.entriesToLatestRedoable(editor)) { redoOperation = transformation.transform(redoOperation, entry.getOperation(), Boolean.TRUE); } undoHistory.replaceType(editor, lastUndo, Type.REDOABLE, Type.REMOTE); // it is not relevant any more, so it is set remote undoHistory.add(editor, Type.LOCAL, redoOperation); log.debug("adding " + lastUndo + " (cause: redo internal)"); return redoOperation; } protected void undo(SPath editor) { Operation op = calcUndoOperation(editor); log.debug("calculated undo: " + op); // don't waste the network if (op instanceof NoOperation) { log.debug("nothing to undo in " + editor); return; } for (TextEditActivity activity : op.toTextEdit(editor, sarosSession.getLocalUser())) { log.debug("undone: " + activity + " in " + editor); fireActivity(activity); } } protected void redo(SPath editor) { Operation op = calcRedoOperation(editor); for (TextEditActivity activity : op.toTextEdit(editor, sarosSession.getLocalUser())) { log.debug("redone: " + activity + " in " + editor); fireActivity(activity); } } @Override public void dispose() { OperationHistoryFactory.getOperationHistory().removeOperationHistoryListener(historyListener); sessionManager.removeSarosSessionListener(sessionListener); editorManager.removeActivityListener(activityListener); enabled = false; eclipseHistory.removeOperationApprover(operationBlocker); editorManager.removeSharedEditorListener(sharedEditorListener); } public OperationHistory getHistory() { return this.undoHistory; } public void addProvider(IActivityProvider provider) { if (!providers.contains(provider)) providers.add(provider); } public void removeProvider(IActivityProvider provider) { providers.remove(provider); } protected void fireActivity(TextEditActivity activity) { expectedActivities.add(activity); List<ITextOperation> textOps = activity.toOperation().getTextOperations(); IFile file = ((EclipseFileImpl) currentActiveEditor.getFile()).getDelegate(); FileEditorInput input = new FileEditorInput(file); IDocumentProvider provider = EditorManager.getDocumentProvider(input); try { provider.connect(input); } catch (CoreException e) { log.error("Could not connect to a document provider on file '" + file.toString() + "':", e); return; } try { IDocument doc = provider.getDocument(input); if (doc == null) { log.error( "Could not connect to a document provider on file '" + file.toString() + "':", new StackTrace()); return; } for (ITextOperation textOp : textOps) { try { if (textOp instanceof DeleteOperation) doc.replace(textOp.getPosition(), textOp.getTextLength(), ""); if (textOp instanceof InsertOperation) doc.replace(textOp.getPosition(), 0, textOp.getText()); } catch (BadLocationException e) { log.error("Invalid location for " + textOp); } } } finally { provider.disconnect(input); } } @Override public void exec(IActivity activity) { activity.dispatch(activityReceiver); } /** * Adds an undone NullOperation (i.e. has no effects on executing, undoing or redoing) to the * Eclipse IOperationHistory to be sure that redoing is possible. This is necessary for the UI * Redo possibility being activated. */ protected void simulateUndo() { IUndoableOperation auxOp = new NullOperation(); try { auxOp.addContext(context); eclipseHistory.execute(auxOp, null, null); eclipseHistory.undo(context, null, null); if (!eclipseHistory.canRedo(context)) log.error("Simulating Undo failed"); } catch (ExecutionException e) { log.error("Simulating Undo failed"); } } /** * Adds the current local composite operation to the undo history (if not null) and resets it * afterwards. */ protected void storeCurrentLocalOperation() { if (currentLocalCompositeOperation == null) return; if (currentActiveEditor == null) { log.warn("Cannot store current local operation. Current active editor is unknown"); return; } undoHistory.add(currentActiveEditor, Type.LOCAL, currentLocalCompositeOperation); currentLocalCompositeOperation = null; log.debug("stored current local operation"); } /** * Integrates the current local atomic operation in the current local composite operation and * replaces the atomic operation by the given operation. */ protected void updateCurrentLocalAtomicOperation(Operation newMRO) { if (currentLocalCompositeOperation == null) { currentLocalCompositeOperation = currentLocalAtomicOperation; } else if (currentLocalAtomicOperation != null) currentLocalCompositeOperation = new SplitOperation(currentLocalCompositeOperation, currentLocalAtomicOperation); currentLocalAtomicOperation = newMRO; } }
public void start() { if (getActiveLinkedMode() != null) { // for safety; should already be handled in RenameDartElementAction fgActiveLinkedMode.startFullDialog(); return; } ISourceViewer viewer = fEditor.getViewer(); IDocument document = viewer.getDocument(); fOriginalSelection = viewer.getSelectedRange(); int offset = fOriginalSelection.x; try { DartUnit root = ASTProvider.getASTProvider().getAST(getCompilationUnit(), ASTProvider.WAIT_YES, null); fLinkedPositionGroup = new LinkedPositionGroup(); DartNode selectedNode = NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y); if (!(selectedNode instanceof DartIdentifier)) { return; // TODO: show dialog } DartIdentifier nameNode = (DartIdentifier) selectedNode; if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); fStartingUndoOperation = operationHistory.getUndoOperation(undoContext); } } fOriginalName = nameNode.getName(); final int pos = nameNode.getSourceInfo().getOffset(); DartNode[] sameNodes = LinkedNodeFinder.findByNode(root, nameNode); // TODO: copied from LinkedNamesAssistProposal#apply(..): // sort for iteration order, starting with the node @ offset Arrays.sort( sameNodes, new Comparator<DartNode>() { @Override public int compare(DartNode o1, DartNode o2) { return rank(o1) - rank(o2); } /** * Returns the absolute rank of an <code>DartNode</code>. Nodes preceding <code>pos * </code> are ranked last. * * @param node the node to compute the rank for * @return the rank of the node with respect to the invocation offset */ private int rank(DartNode node) { int relativeRank = node.getSourceInfo().getOffset() + node.getSourceInfo().getLength() - pos; if (relativeRank < 0) { return Integer.MAX_VALUE + relativeRank; } else { return relativeRank; } } }); for (int i = 0; i < sameNodes.length; i++) { DartNode elem = sameNodes[i]; LinkedPosition linkedPosition = new LinkedPosition( document, elem.getSourceInfo().getOffset(), elem.getSourceInfo().getLength(), i); if (i == 0) { fNamePosition = linkedPosition; } fLinkedPositionGroup.addPosition(linkedPosition); } fLinkedModeModel = new LinkedModeModel(); fLinkedModeModel.addGroup(fLinkedPositionGroup); fLinkedModeModel.forceInstall(); fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor)); fLinkedModeModel.addLinkingListener(new EditorSynchronizer()); LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer); ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE); ui.setExitPolicy(new ExitPolicy(document)); ui.enter(); viewer.setSelectedRange( fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer; registry.register(fFocusEditingSupport); } openSecondaryPopup(); // startAnimation(); fgActiveLinkedMode = this; } catch (BadLocationException e) { DartToolsPlugin.log(e); } }
public void start() { if (getActiveLinkedMode() != null) { // for safety; should already be handled in RenameDartElementAction fgActiveLinkedMode.startFullDialog(); return; } ISourceViewer viewer = fEditor.getViewer(); IDocument document = viewer.getDocument(); fOriginalSelection = viewer.getSelectedRange(); int offset = fOriginalSelection.x; try { fLinkedPositionGroup = new LinkedPositionGroup(); prepareElement(); if (fDartElement == null) { return; } if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); fStartingUndoOperation = operationHistory.getUndoOperation(undoContext); } } fOriginalName = nameNode.getName(); final int pos = nameNode.getOffset(); final List<ASTNode> sameNodes = Lists.newArrayList(); nameNode .getRoot() .accept( new RecursiveASTVisitor<Void>() { @Override public Void visitSimpleIdentifier(SimpleIdentifier node) { Element element = node.getElement(); element = getCanonicalElement(element); if (Objects.equal(element, fDartElement)) { sameNodes.add(node); } return super.visitSimpleIdentifier(node); } }); // TODO: copied from LinkedNamesAssistProposal#apply(..): // sort for iteration order, starting with the node @ offset Collections.sort( sameNodes, new Comparator<ASTNode>() { @Override public int compare(ASTNode o1, ASTNode o2) { return rank(o1) - rank(o2); } /** * Returns the absolute rank of an <code>ASTNode</code>. Nodes preceding <code>pos * </code> are ranked last. * * @param node the node to compute the rank for * @return the rank of the node with respect to the invocation offset */ private int rank(ASTNode node) { int relativeRank = node.getOffset() + node.getLength() - pos; if (relativeRank < 0) { return Integer.MAX_VALUE + relativeRank; } else { return relativeRank; } } }); for (int i = 0; i < sameNodes.size(); i++) { ASTNode elem = sameNodes.get(i); LinkedPosition linkedPosition = new LinkedPosition(document, elem.getOffset(), elem.getLength(), i); if (i == 0) { fNamePosition = linkedPosition; } fLinkedPositionGroup.addPosition(linkedPosition); } fLinkedModeModel = new LinkedModeModel(); fLinkedModeModel.addGroup(fLinkedPositionGroup); fLinkedModeModel.forceInstall(); fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor)); fLinkedModeModel.addLinkingListener(new EditorSynchronizer()); LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer); ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE); ui.setExitPolicy(new ExitPolicy(document)); ui.enter(); viewer.setSelectedRange( fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer; registry.register(fFocusEditingSupport); } openSecondaryPopup(); // startAnimation(); fgActiveLinkedMode = this; } catch (BadLocationException e) { DartToolsPlugin.log(e); } }
@Override public boolean performFinish() { _wizardPage.setPageComplete(false); TransactionalEditingDomain myEditingDomain = DataModelerUtils.getDataModelerEditingDomain(); _schema = _wizardPage.getSchema(); if (_schema.eIsProxy()) _schema = (ESchema) EcoreUtil.resolve(_schema, myEditingDomain.getResourceSet()); if (!_schema.eIsProxy()) _resource = _schema.eResource(); if (_resource == null) return true; String path = _resource.getURI().toPlatformString(true); LinkedList<IFile> affectedFiles = new LinkedList<IFile>(); IResource workspaceResource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(path)); if (workspaceResource instanceof IFile) affectedFiles.add((IFile) workspaceResource); AbstractTransactionalCommand command = new AbstractTransactionalCommand( myEditingDomain, "Comando de creación de diagramas", //$NON-NLS-1$ affectedFiles) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { _diagram = ViewService.createDiagram( _schema, SchemaEditPart.MODEL_ID, DatamodelerDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); _diagram.setName(_wizardPage.getDiagramName()); _resource.getContents().add(_diagram); return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); _resource.save(DatamodelerDiagramEditorUtil.getSaveOptions()); final URI diagramURI = EcoreUtil.getURI(_diagram); Display.getCurrent() .asyncExec( new Runnable() { @Override public void run() { if (diagramURI.toPlatformString(true) != null) try { UtilsDataModelerUI.openDiagram(diagramURI, _diagram.getName()); } catch (PartInitException ex) { DatamodelerDiagramEditorPlugin.getInstance() .logError("Unable to open editor", ex); // $NON-NLS-1$ } } }); } catch (ExecutionException e) { DatamodelerDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } catch (IOException ex) { DatamodelerDiagramEditorPlugin.getInstance() .logError("Save operation failed for: " + _resource.getURI(), ex); // $NON-NLS-1$ } return true; }