| /*=============================================================================# |
| # Copyright (c) 2021 Stephan Wahlbrink and others. |
| # |
| # This program and the accompanying materials are made available under the |
| # terms of the Eclipse Public License 2.0 which is available at |
| # https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 |
| # which is available at https://www.apache.org/licenses/LICENSE-2.0. |
| # |
| # SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 |
| # |
| # Contributors: |
| # Stephan Wahlbrink - initial API and implementation |
| #=============================================================================*/ |
| |
| package org.eclipse.statet.ltk.ui.sourceediting.actions; |
| |
| import static org.eclipse.statet.jcommons.lang.ObjectUtils.nonNullAssert; |
| |
| import org.eclipse.core.commands.AbstractHandler; |
| import org.eclipse.jface.text.source.SourceViewer; |
| import org.eclipse.ui.IWorkbenchPart; |
| |
| import org.eclipse.statet.jcommons.lang.NonNullByDefault; |
| import org.eclipse.statet.jcommons.lang.Nullable; |
| |
| import org.eclipse.statet.ecommons.ui.util.UIAccess; |
| import org.eclipse.statet.ecommons.ui.workbench.WorkbenchUIUtils; |
| |
| import org.eclipse.statet.ltk.ui.sourceediting.SourceEditor; |
| |
| |
| @NonNullByDefault |
| public abstract class AbstractSourceEditorHandler extends AbstractHandler { |
| |
| |
| private final @Nullable SourceEditor editor; |
| |
| |
| public AbstractSourceEditorHandler() { |
| this.editor= null; |
| } |
| |
| public AbstractSourceEditorHandler(final SourceEditor editor) { |
| this.editor= nonNullAssert(editor); |
| } |
| |
| |
| protected @Nullable SourceEditor getSourceEditor(final @Nullable Object context) { |
| SourceEditor editor= this.editor; |
| if (editor != null) { |
| return editor; |
| } |
| final IWorkbenchPart part= WorkbenchUIUtils.getActivePart(context); |
| if (part != null) { |
| if (part instanceof SourceEditor) { |
| return (SourceEditor)part; |
| } |
| editor= part.getAdapter(SourceEditor.class); |
| if (editor != null) { |
| return editor; |
| } |
| } |
| return null; |
| } |
| |
| protected boolean isSupported(final SourceEditor sourceEditor) { |
| final SourceViewer viewer= sourceEditor.getViewer(); |
| return (UIAccess.isOkToUse(viewer) && viewer.getDocument() != null); |
| } |
| |
| |
| @Override |
| public void setEnabled(@Nullable final Object evaluationContext) { |
| final SourceEditor editor= getSourceEditor(evaluationContext); |
| if (editor == null || !isSupported(editor)) { |
| setBaseEnabled(false); |
| return; |
| } |
| |
| setBaseEnabled(true); |
| } |
| |
| |
| } |