| /*=============================================================================# |
| # Copyright (c) 2017, 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 <sw@wahlbrink.eu> - initial API and implementation |
| #=============================================================================*/ |
| |
| package org.eclipse.statet.ecommons.ui.util; |
| |
| import org.eclipse.core.databinding.observable.Diffs; |
| import org.eclipse.core.databinding.observable.list.ListDiffEntry; |
| import org.eclipse.core.databinding.observable.list.WritableList; |
| |
| import org.eclipse.statet.jcommons.lang.NonNull; |
| import org.eclipse.statet.jcommons.lang.NonNullByDefault; |
| |
| |
| @NonNullByDefault |
| public class InputHistory<E> extends WritableList<E>{ |
| |
| |
| private final int maxLength; |
| |
| |
| public InputHistory(final int maxLength) { |
| this.maxLength= maxLength; |
| } |
| |
| |
| public void append(final E element) { |
| checkRealm(); |
| |
| final int idx= this.wrappedList.indexOf(element); |
| switch (idx) { |
| case 0: |
| return; |
| case -1: |
| addToTop(element); |
| return; |
| default: |
| moveToTop(idx); |
| return; |
| } |
| } |
| |
| private void moveToTop(final int idx) { |
| if (idx == 0) { |
| return; |
| } |
| |
| final ListDiffEntry<E>[] diffs= new @NonNull ListDiffEntry[2]; |
| |
| final E element= this.wrappedList.remove(idx); |
| diffs[0]= Diffs.createListDiffEntry(idx, false, element); |
| this.wrappedList.add(0, element); |
| diffs[1]= Diffs.createListDiffEntry(0, true, element); |
| |
| fireListChange(Diffs.createListDiff(diffs)); |
| } |
| |
| private void addToTop(final E element) { |
| int size= this.wrappedList.size(); |
| final ListDiffEntry<E>[] diffs= new @NonNull ListDiffEntry[Math.max(size - this.maxLength + 2, 1)]; |
| |
| int iDiff= 0; |
| while (size >= this.maxLength) { |
| size--; |
| final E removed= this.wrappedList.remove(size); |
| diffs[iDiff++]= Diffs.createListDiffEntry(size, false, removed); |
| } |
| this.wrappedList.add(0, element); |
| diffs[iDiff++]= Diffs.createListDiffEntry(0, true, element); |
| |
| fireListChange(Diffs.createListDiff(diffs)); |
| } |
| |
| } |