blob: 5ae9db742eae8e2ded98d09dbc2d84110d47d0b0 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2007, 2020 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 <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.ltk.ui.sourceediting;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.statet.jcommons.collections.CopyOnWriteIdentityListSet;
/**
* History of structure selections.
*
* @see StructureSelectHandler
*/
public class StructureSelectionHistory {
private final ISourceEditor sourceEditor;
private final List<IRegion> history;
private final ISelectionChangedListener selectionListener;
private int selectionChangeListenerCounter;
private final CopyOnWriteIdentityListSet<IUpdate> updateActions= new CopyOnWriteIdentityListSet<>();
public StructureSelectionHistory(final ISourceEditor editor) {
this.sourceEditor= editor;
this.history= new ArrayList<>();
this.selectionListener= new ISelectionChangedListener() {
@Override
public void selectionChanged(final SelectionChangedEvent event) {
if (StructureSelectionHistory.this.selectionChangeListenerCounter == 0) {
flush();
}
}
};
this.sourceEditor.getViewer().getSelectionProvider().addSelectionChangedListener(this.selectionListener);
}
public void addUpdateListener(final IUpdate action) {
this.updateActions.add(action);
}
private final void updateState() {
for (final IUpdate action : this.updateActions.toList()) {
action.update();
}
}
public boolean isEmpty() {
return this.history.isEmpty();
}
public void remember(final IRegion range) {
this.history.add(range);
updateState();
}
public IRegion getLast() {
if (isEmpty()) {
return null;
}
final IRegion result= this.history.remove(this.history.size() - 1);
updateState();
return result;
}
public void flush() {
if (this.history.isEmpty()) {
return;
}
this.history.clear();
updateState();
}
public void ignoreSelectionChanges() {
this.selectionChangeListenerCounter++;
}
public void listenToSelectionChanges() {
this.selectionChangeListenerCounter--;
}
public void dispose() {
this.sourceEditor.getViewer().getSelectionProvider().removeSelectionChangedListener(this.selectionListener);
}
}