repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/dto/ProjectMembersInfo.java | shared/src/main/java/com/google/collide/dto/ProjectMembersInfo.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dto;
import com.google.collide.json.shared.JsonArray;
/**
* Returns the user details of a project members.
*/
public interface ProjectMembersInfo {
/**
* Returns details about project members.
*/
JsonArray<UserDetails> getMembers();
/**
* The number of users who are requesting membership to this project.
*/
int pendingMembersCount();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/dto/shared/CookieKeys.java | shared/src/main/java/com/google/collide/dto/shared/CookieKeys.java | package com.google.collide.dto.shared;
public class CookieKeys {
public static final String GWT_COMPILE_TARGET = "gwtc-target";
// public static final String OPEN_COMPILE_IN_IFRAME = "if";
// public static final String OPEN_COMPILE_IN_WINDOW = "ow";
// public static final String OPEN_COMPILE_IN_SELF = "is";
// public static final String DO_NOT_OPEN_COMPILE = "no";
public static final String GWT_LOG_LEVEL = "ll";
public static final char GWT_LOG_LEVEL_ALL = 'a';
public static final char GWT_LOG_LEVEL_SPAM = 's';
public static final char GWT_LOG_LEVEL_DEBUG = 'd';
public static final char GWT_LOG_LEVEL_TRACE = 't';
public static final char GWT_LOG_LEVEL_INFO = 'i';
public static final char GWT_LOG_LEVEL_WARN = 'w';
public static final char GWT_LOG_LEVEL_ERROR = 'e';
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/dto/shared/DocOpFactory.java | shared/src/main/java/com/google/collide/dto/shared/DocOpFactory.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dto.shared;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent.Delete;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.DocOpComponent.Retain;
import com.google.collide.dto.DocOpComponent.RetainLine;
// TODO: These should be moved to an Editor2-specific package
/**
*/
public interface DocOpFactory {
Delete createDelete(String text);
DocOp createDocOp();
Insert createInsert(String text);
Retain createRetain(int count, boolean hasTrailingNewline);
RetainLine createRetainLine(int lineCount);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/dto/shared/JsonFieldConstants.java | shared/src/main/java/com/google/collide/dto/shared/JsonFieldConstants.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dto.shared;
/**
* Shared constants for keys used in JSON serialized data between client and
* server.
*
*/
public class JsonFieldConstants {
/**
* The active client ID for the bootstrap session. This is unique per tab.
*/
public static final String SESSION_ACTIVE_ID = "activeClient";
/**
* The handle for the logged in user (email or name).
*/
public static final String SESSION_USERNAME = "name";
/**
* Unique user ID of the logged in user. This user may have multiple active tabs.
*/
public static final String SESSION_USER_ID = "sessionID";
/**
* The XSRF token used to validate senders of HTTP requests to the Frontend.
*/
public static final String XSRF_TOKEN = "xsrfToken";
/**
* The domain that we must talk to in order to fetch static file content.
*/
public static final String STATIC_FILE_CONTENT_DOMAIN = "staticContentDomain";
/**
* The URL for the user's profile image.
*/
public static final String PROFILE_IMAGE_URL = "profileImageUrl";
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/server/JsonStringSetAdapter.java | shared/src/main/java/com/google/collide/json/server/JsonStringSetAdapter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.server;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.common.collect.Lists;
import java.util.Set;
/**
* Server wrapper for a {@link Set} that implements
* {@link JsonStringSet}.
*
*/
public class JsonStringSetAdapter implements JsonStringSet {
private final Set<String> delegate;
public JsonStringSetAdapter(Set<String> delegate) {
this.delegate = delegate;
}
@Override
public boolean contains(String key) {
return delegate.contains(key);
}
@Override
public JsonArray<String> getKeys() {
return new JsonArrayListAdapter<String>(Lists.newArrayList(delegate));
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public void iterate(IterationCallback callback) {
for (String key : delegate) {
callback.onIteration(key);
}
}
@Override
public void add(String key) {
delegate.add(key);
}
@Override
public void addAll(JsonArray<String> keys) {
for (int i = 0, n = keys.size(); i < n; i++) {
add(keys.get(i));
}
}
@Override
public boolean remove(String key) {
return delegate.remove(key);
}
@Override
public void clear() {
delegate.clear();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof JsonStringSetAdapter) {
return delegate.equals(((JsonStringSetAdapter) obj).delegate);
}
return false;
}
@Override
public String toString() {
return delegate.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/server/JsonArrayListAdapter.java | shared/src/main/java/com/google/collide/json/server/JsonArrayListAdapter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.server;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonArrayIterator;
import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* Wraps a {@link List} for use on the server.
*/
public class JsonArrayListAdapter<T> implements JsonArray<T> {
private final List<T> delegate;
public JsonArrayListAdapter(List<T> delegate) {
this.delegate = delegate;
}
@Override
public void add(T item) {
delegate.add(item);
}
@Override
public void addAll(JsonArray<? extends T> array) {
for (int i = 0; i < array.size(); i++) {
add(array.get(i));
}
}
/**
* Returns this array as a {@link List}. The returned instance backs this
* array, so any changes made to the list will affect this array.
*
* If you have used this list as a sparse array you will end up with objects
* which are unsafe and cannot be casted. It is recommend you iterate and
* create your own list from the result.
*/
public List<T> asList() {
return delegate;
}
@Override
public void clear() {
delegate.clear();
}
@Override
public boolean contains(T item) {
return delegate.contains(item);
}
@Override
public JsonArray<T> copy() {
return new JsonArrayListAdapter<T>(new ArrayList<T>(delegate));
}
@Override
public T get(int index) {
return delegate.get(index);
}
@Override
public int indexOf(T item) {
return delegate.indexOf(item);
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public T peek() {
return get(delegate.size() - 1);
}
@Override
public T pop() {
return remove(delegate.size() - 1);
}
@Override
public T remove(int index) {
T result = get(index);
delegate.remove(index);
return result;
}
@Override
public boolean remove(T item) {
return delegate.remove(item);
}
@Override
public void reverse() {
Collections.reverse(delegate);
}
@Override
public void set(int index, T item) {
delegate.set(index, item);
}
@Override
public int size() {
return delegate.size();
}
@Override
public JsonArray<T> slice(int start, int end) {
JsonArray<T> sliced = new JsonArrayListAdapter<T>(new ArrayList<T>());
for (int i = start; i < end && i < size(); i++) {
sliced.add(get(i));
}
return sliced;
}
@Override
public void sort(Comparator<? super T> comparator) {
Collections.sort(delegate, comparator);
}
@Override
public JsonArray<T> splice(int index, int deleteCount) {
return spliceImpl(index, deleteCount, false, null);
}
@Override
public JsonArray<T> splice(int index, int deleteCount, T value) {
return spliceImpl(index, deleteCount, true, value);
}
private JsonArray<T> spliceImpl(int index, int deleteCount, boolean hasValue, T value) {
JsonArray<T> removedArray = new JsonArrayListAdapter<T>(new ArrayList<T>());
for (int i = deleteCount; i > 0; i--) {
removedArray.add(remove(index));
}
if (hasValue) {
delegate.add(index, value);
}
return removedArray;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; i < size(); i++) {
if (i > 0) {
sb.append(',');
}
T value = get(i);
sb.append(value == null ? "null" : value.toString());
}
sb.append(']');
return sb.toString();
}
@Override
public String join(String separator) {
return Joiner.on(separator).join(delegate);
}
@Override
public Iterable<T> asIterable() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new JsonArrayIterator<T>(JsonArrayListAdapter.this);
}
};
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/server/JsonIntegerMapAdapter.java | shared/src/main/java/com/google/collide/json/server/JsonIntegerMapAdapter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.server;
import com.google.collide.json.shared.JsonIntegerMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Server wrapper for a {@link Map} that implements
* {@link JsonIntegerMap}.
*
* @param <T> the type contained as value in the map
*/
public class JsonIntegerMapAdapter<T> implements JsonIntegerMap<T> {
private final Map<Integer, T> delegate;
public JsonIntegerMapAdapter(Map<Integer, T> delegate) {
this.delegate = delegate;
}
@Override
public boolean hasKey(int key) {
return delegate.containsKey(key);
}
@Override
public T get(int key) {
return delegate.get(key);
}
@Override
public void put(int key, T value) {
delegate.put(key, value);
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public void erase(int key) {
delegate.remove(key);
}
@Override
public void iterate(IterationCallback<T> cb) {
for (Entry<Integer, T> entry : delegate.entrySet()) {
cb.onIteration(entry.getKey().intValue(), entry.getValue());
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/server/JsonStringMapAdapter.java | shared/src/main/java/com/google/collide/json/server/JsonStringMapAdapter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.server;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.common.collect.Lists;
import java.util.Map;
/**
* Server wrapper for a {@link Map} that implements
* {@link JsonStringMap}.
*
*/
public class JsonStringMapAdapter<T> implements JsonStringMap<T> {
private final Map<String, T> delegate;
public JsonStringMapAdapter(Map<String, T> delegate) {
this.delegate = delegate;
}
@Override
public T get(String key) {
return delegate.get(key);
}
@Override
public JsonArray<String> getKeys() {
return new JsonArrayListAdapter<String>(Lists.newArrayList(delegate.keySet()));
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public void iterate(IterationCallback<T> callback) {
for (String key : delegate.keySet()) {
callback.onIteration(key, delegate.get(key));
}
}
@Override
public void put(String key, T value) {
delegate.put(key, value);
}
@Override
public void putAll(JsonStringMap<T> otherMap) {
JsonArray<String> keys = otherMap.getKeys();
for (int i = 0, n = keys.size(); i < n; i++) {
String key = keys.get(i);
put(key, otherMap.get(key));
}
}
@Override
public T remove(String key) {
return delegate.remove(key);
}
@Override
public boolean containsKey(String key) {
return delegate.containsKey(key);
}
@Override
public int size() {
return delegate.size();
}
@Override
public String toString() {
return delegate.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/client/JsoArrayListAdapter.java | shared/src/main/java/com/google/collide/json/client/JsoArrayListAdapter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.client;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* JSOArray backed implementation of a List that implements just enough of the
* interface to work with a {@link com.google.gwt.view.client.ListDataProvider}.
* We don't support all methods on List, just the ones we need to get the
* CellTree to work.
*
* Note that we don't directly subclass List since it would result in all
* references to List going through a dynamic dispatcher. So we simply wrap and
* delegate.
*
* CAVEAT: Using any methods on List not implemented will throw an unchecked
* runtime exception.
*
*/
public class JsoArrayListAdapter<T> implements List<T> {
/**
* Basic iterator interface for use with a JSOArrayListAdapter.
*/
public class JSOArrayListAdapterIterator implements Iterator<T> {
int currIndex = 0;
@Override
public boolean hasNext() {
return currIndex >= JsoArrayListAdapter.this.size();
}
@Override
public T next() {
currIndex += 1;
return JsoArrayListAdapter.this.get(currIndex);
}
@Override
public void remove() {
JsoArrayListAdapter.this.remove(currIndex);
}
}
private final JsoArray<T> delegate;
private final int fromIndex;
private final int toIndex;
public JsoArrayListAdapter(JsoArray<T> delegate) {
this(delegate, 0, delegate.size());
}
public JsoArrayListAdapter(JsoArray<T> delegate, int fromIndex, int toIndex) {
assert (fromIndex <= toIndex) : "fromIndex is > toIndex in JSOArrayListAdapter";
this.delegate = delegate;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
}
@Override
public void add(int index, T element) {
delegate.set(shiftIndex(index), element);
}
@Override
public boolean add(T e) {
delegate.add(e);
return true;
}
@Override
public boolean addAll(Collection<? extends T> c) {
// TODO Consider implementing this.
throw new RuntimeException("Method addAll is not yet supported for JSOArrayListAdapter!");
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
// TODO Consider implementing this.
throw new RuntimeException("Method addAll is not yet supported for JSOArrayListAdapter!");
}
@Override
public void clear() {
delegate.clear();
}
@Override
public boolean contains(Object o) {
// TODO Consider implementing this.
throw new RuntimeException("Method contains is not yet supported for JSOArrayListAdapter!");
}
@Override
public boolean containsAll(Collection<?> c) {
// TODO Consider implementing this.
throw new RuntimeException("Method containsAll is not yet supported for JSOArrayListAdapter!");
}
@Override
public T get(int index) {
return delegate.get(shiftIndex(index));
}
@Override
public int indexOf(Object o) {
// TODO Consider implementing this.
throw new RuntimeException("Method indexOf is not yet supported for JSOArrayListAdapter!");
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public Iterator<T> iterator() {
return new JSOArrayListAdapterIterator();
}
@Override
public int lastIndexOf(Object o) {
// TODO Consider implementing this.
throw new RuntimeException("Method lastIndexOf is not yet supported for JSOArrayListAdapter!");
}
@Override
public ListIterator<T> listIterator() {
// TODO Consider implementing this.
throw new RuntimeException("Method listIterator is not yet supported for JSOArrayListAdapter!");
}
@Override
public ListIterator<T> listIterator(int index) {
// TODO Consider implementing this.
throw new RuntimeException("Method listIterator is not yet supported for JSOArrayListAdapter!");
}
@Override
public T remove(int index) {
return delegate.remove(shiftIndex(index));
}
@Override
public boolean remove(Object o) {
// TODO Consider implementing this.
throw new RuntimeException(
"Method remove(Object) is not yet supported for JSOArrayListAdapter!");
}
@Override
public boolean removeAll(Collection<?> c) {
// TODO Consider implementing this.
throw new RuntimeException("Method removeAll is not yet supported for JSOArrayListAdapter!");
}
@Override
public boolean retainAll(Collection<?> c) {
// TODO Consider implementing this.
throw new RuntimeException("Method retainAll is not yet supported for JSOArrayListAdapter!");
}
@Override
public T set(int index, T element) {
// TODO Consider implementing this.
throw new RuntimeException("Method set is not yet supported for JSOArrayListAdapter!");
}
@Override
public int size() {
return toIndex - fromIndex;
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
// Needs to be a live view
return new JsoArrayListAdapter<T>(delegate, fromIndex, toIndex);
}
@Override
public Object[] toArray() {
// TODO Consider implementing this.
throw new RuntimeException("Method toArray is not yet supported for JSOArrayListAdapter!");
}
@Override
public <E> E[] toArray(E[] a) {
// TODO Consider implementing this.
throw new RuntimeException("Method toArray is not yet supported for JSOArrayListAdapter!");
}
private int shiftIndex(int index) {
return index + fromIndex;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/client/JsoArray.java | shared/src/main/java/com/google/collide/json/client/JsoArray.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.client;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonArrayIterator;
import com.google.gwt.core.client.JavaScriptObject;
/**
* Similar to {@link com.google.gwt.core.client.JsArray}, except
* {@link com.google.gwt.core.client.JsArray} only allows you to store <T
* extends JavaScriptObject>.
*
* This class is a native JS array that lets you store any Object.
*
* @param <T> the type of each entry in the array
*/
public class JsoArray<T> extends JavaScriptObject implements JsonArray<T> {
/**
* Concatenate 2 arrays.
*/
public static final native <T> JsoArray<T> concat(JsoArray<?> a, JsoArray<?> b) /*-{
return a.concat(b);
}-*/;
/**
* Constructs a new one.
*
* @param <M>
* @return the array
*/
public static native <M> JsoArray<M> create() /*-{
return [];
}-*/;
/**
* Casts a JsonArray to a JsoArray. Unsafe, but on client we know we always
* have a JsoArray.
*/
@SuppressWarnings("unchecked")
public static <M, T extends M> JsoArray<M> from(JsonArray<T> array) {
return (JsoArray<M>) array;
}
public static <M, T extends M> JsoArray<M> from(List<T> list) {
JsoArray<M> array = create();
for (T item : list) {
array.add(item);
}
return array;
}
/**
* Creates a JsoArray from a Java array.
*/
public static <M> JsoArray<M> from(M... array) {
JsoArray<M> result = create();
for (M s : array) {
result.add(s);
}
return result;
}
/**
* Invokes the native string split on a string and returns a JavaScript array.
* GWT's version of string.split() emulates Java behavior in JavaScript.
*/
public static native JsoArray<String> splitString(String str, String regexp) /*-{
return str.split(regexp);
}-*/;
protected JsoArray() {
}
/**
* Adds a value to the end of an array.
*
* @param value
*/
@Override
public final native void add(T value) /*-{
this.push(value);
}-*/;
/**
* Adds all of the elements in the given {@code array} to this array.
*/
@Override
public final void addAll(JsonArray<? extends T> array) {
for (int i = 0, n = array.size(); i < n; ++i) {
add(array.get(i));
}
}
@Override
public final void clear() {
setLength(0);
}
@Override
public final boolean contains(T value) {
for (int i = 0, n = size(); i < n; i++) {
if (equalsOrNull(value, get(i))) {
return true;
}
}
return false;
}
/**
* Returns a new array with the same contents as this array.
*/
@Override
public final native JsoArray<T> copy() /*-{
return this.slice(0);
}-*/;
/**
* Standard index accessor.
*
* @param index
* @return T stored at index
*/
@Override
public final native T get(int index) /*-{
return this[index];
}-*/;
@Override
public final native int indexOf(T item) /*-{
return this.indexOf(item);
}-*/;
/**
* @return whether or not this collection is empty
*/
@Override
public final native boolean isEmpty() /*-{
return (this.length == 0);
}-*/;
/**
* Uses "" as the separator.
*
* @return returns a string using the empty string as the separator.
*/
public final String join() {
return join("");
}
/**
* Concatenates the Array into a string using the supplied separator to
* delimit.
*
* @param sep
* @return The array converted to a String
*/
@Override
public final native String join(String sep) /*-{
return this.join(sep);
}-*/;
/**
* Returns the last element in the array.
*
* @return the last element
*/
@Override
public final native T peek() /*-{
return this[this.length - 1];
}-*/;
/**
* Pops the end of the array and returns is.
*
* @return a value T from the end of the array
*/
@Override
public final native T pop() /*-{
return this.pop();
}-*/;
/**
* @param index
* @return The element that was removed.
*/
@Override
public final T remove(int index) {
return splice(index, 1).get(0);
}
@Override
public final boolean remove(T value) {
for (int i = 0, n = size(); i < n; i++) {
if ((value != null && value.equals(get(i))) || (value == null && get(i) == null)) {
remove(i);
return true;
}
}
return false;
}
@Override
public final native void reverse() /*-{
this.reverse();
}-*/;
/**
* Sets a given value at a specified index.
*
* @param index
* @param value
*/
@Override
public final void set(int index, T value) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
}
nativeSet(index, value);
}
private native void nativeSet(int index, T value) /*-{
this[index] = value;
}-*/;
/**
* Reset the length of the array.
*
* @param newLength the new length of the array
*/
public final native void setLength(int newLength) /*-{
this.length = newLength;
}-*/;
public final native T shift() /*-{
return this.shift();
}-*/;
/**
* Prepends an item onto the array
*/
public final native int unshift(T value) /*-{
return this.unshift(value);
}-*/;
/**
* @return the length of the array
*/
@Override
public final native int size() /*-{
return this.length;
}-*/;
/**
* @param start
* @param end
* @return A sub-array starting at start (inclusive) and endint at the end
* index (exclusive).
*/
@Override
public final native JsoArray<T> slice(int start, int end) /*-{
return this.slice(start, end);
}-*/;
/**
* Sorts the array using the default browser sorting method. Mutates the
* array.
*/
public final native JsoArray<T> sort() /*-{
return this.sort();
}-*/;
@Override
public final native void sort(Comparator<? super T> comparator) /*-{
this.sort(function(a, b) {
return comparator.@java.util.Comparator::compare(Ljava/lang/Object;Ljava/lang/Object;)(a,b);
});
}-*/;
/**
* Removes n elements found at the specified index.
*
* @param index index at which we are removing
* @param n the number of elements we will remove starting at the index
* @return an array of elements that were removed
*/
@Override
public final native JsoArray<T> splice(int index, int n) /*-{
return this.splice(index, n);
}-*/;
/**
* Removes n elements found at the specified index. And then inserts the
* specified item at the index
*
* @param index index at which we are inserting/removing
* @param n the number of elements we will remove starting at the index
* @param item the item we want to add to the array at the index
* @return an array of elements that were removed
*/
@Override
public final native JsoArray<T> splice(int index, int n, T item) /*-{
return this.splice(index, n, item);
}-*/;
private boolean equalsOrNull(T a, T b) {
return a == b || (a != null && a.equals(b));
}
@Override
public final Iterable<T> asIterable() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new JsonArrayIterator<T>(JsoArray.this);
}
};
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/client/JsoStringSet.java | shared/src/main/java/com/google/collide/json/client/JsoStringSet.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.client;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
/**
* Client implementation of a set of strings.
*
*/
public class JsoStringSet implements JsonStringSet {
private static final String KEY_PREFIX = "#";
/**
* Convenience factory method.
*/
public static JsoStringSet create() {
return new JsoStringSet();
}
private Jso delegate = Jso.create();
private JsoStringSet() {
}
@Override
public final boolean contains(String key) {
return delegate.hasOwnProperty(toInternalKey(key));
}
@Override
public final JsonArray<String> getKeys() {
JsonArray<String> result = delegate.getKeys();
for (int i = 0, n = result.size(); i < n; ++i) {
result.set(i, toPublicKey(result.get(i)));
}
return result;
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public final void iterate(IterationCallback callback) {
JsonArray<String> keys = getKeys();
for (int i = 0, n = keys.size(); i < n; ++i) {
callback.onIteration(keys.get(i));
}
}
@Override
public final void add(String key) {
delegate.addField(toInternalKey(key), true);
}
@Override
public final void addAll(JsonArray<String> keys) {
for (int i = 0, n = keys.size(); i < n; ++i) {
add(keys.get(i));
}
}
@Override
public final boolean remove(String key) {
if (contains(key)) {
delegate.deleteField(toInternalKey(key));
return true;
}
return false;
}
@Override
public void clear() {
delegate = Jso.create();
}
private static String toInternalKey(String key) {
return KEY_PREFIX + key;
}
private static String toPublicKey(String key) {
return key.substring(KEY_PREFIX.length());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/client/JsoStringMap.java | shared/src/main/java/com/google/collide/json/client/JsoStringMap.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.client;
import com.google.collide.json.shared.JsonStringMap;
import com.google.gwt.core.client.JavaScriptObject;
/**
* This is used to satisfy DTO casting requirements.
*
* On the client, if you have a reference to JsonStringMap, or JsoStringMap
* (the JavaScriptObject backed impl), feel free to cross cast this to the more
* robust {@link com.google.collide.json.client.Jso}.
*
*/
public final class JsoStringMap<T> extends JavaScriptObject implements JsonStringMap<T> {
/*
* GWT dev mode adds a __gwt_ObjectId property to all objects. We have to call
* hasOwnProperty (which is overridden by GWT) when using for(in) loops to verify
* that the key is actually a property of the object, and not the __gwt_ObjectId
* set by Chrome dev mode.
*/
/**
* Convenience factory method.
*/
public static <T> JsoStringMap<T> create() {
return Jso.create().cast();
}
protected JsoStringMap() {
}
@Override
public native T get(String key) /*-{
return Object.prototype.hasOwnProperty.call(this, key) ? this[key] : undefined;
}-*/;
@Override
public native final JsoArray<String> getKeys() /*-{
keys = [];
for (key in this) {
if (Object.prototype.hasOwnProperty.call(this, key)) {
keys.push(key);
}
}
return keys;
}-*/;
@Override
public final native boolean isEmpty()/*-{
for (key in this) {
if (Object.prototype.hasOwnProperty.call(this, key)) {
return false;
}
}
return true;
}-*/;
/**
* Method for iterating through the contents of a Map.
*
* <p>{@code T} is the expected type of the values returned from the map.
* <b>Caveat:</b> if you have a map of heterogeneous types, you need to think
* what value of T you specify here.
*
* @param callback The callback object that gets called on each iteration.
*/
@Override
public native void iterate(IterationCallback<T> callback) /*-{
for (key in this) {
if (Object.prototype.hasOwnProperty.call(this, key)) {
callback.
@com.google.collide.json.shared.JsonStringMap.IterationCallback::onIteration(Ljava/lang/String;Ljava/lang/Object;)
(key, this[key]);
}
}
}-*/;
// TODO: We still have problem with "__proto__"
@Override
public native void put(String key, T value) /*-{
this[key] = value;
}-*/;
@Override
public void putAll(JsonStringMap<T> map) {
map.iterate(new IterationCallback<T>() {
@Override
public void onIteration(String key, T value) {
put(key, value);
}
});
}
@Override
public native T remove(String key) /*-{
if (!Object.prototype.hasOwnProperty.call(this, key)) {
return undefined;
}
var retVal = this[key];
delete this[key];
return retVal;
}-*/;
@Override
public native boolean containsKey(String key) /*-{
return Object.prototype.hasOwnProperty.call(this, key);
}-*/;
/**
* Returns the size of the map (the number of keys).
*
* <p>NB: This method is currently O(N) because it iterates over all keys.
*
* @return the size of the map.
*/
@Override
public final native int size() /*-{
size = 0;
for (key in this) {
if (Object.prototype.hasOwnProperty.call(this, key)) {
size++;
}
}
return size;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/json/client/Jso.java | shared/src/main/java/com/google/collide/json/client/Jso.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.client;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonObject;
import com.google.gwt.core.client.JavaScriptObject;
/**
* Utility class for JavaScriptObject construction and serialization. We try to
* keep all the nasty typesystem cludge with working with JavaScriptObject maps
* confined in this class. We rely on identical method body coalescing to keep
* the code small.
*
* TODO: Using the builder pattern like this for constructing JSOs
* on the client will cause a lot of boundary crossings. Revisit this as a
* potential perf optimization if we find ourselve spending a lot of time
* building objects for serialization.
*/
public class Jso extends JavaScriptObject implements JsonObject {
public static Jso create() {
return JavaScriptObject.createObject().cast();
}
/**
* Deserializes a JSON String and returns an overlay type.
*/
public static native <T extends Jso> T deserialize(String jsonString) /*-{
return JSON.parse(jsonString);
}-*/;
/**
* Serializes a JsonObject into a String.
*/
public static native String serialize(JavaScriptObject jso) /*-{
return JSON.stringify(jso);
}-*/;
protected Jso() {
}
@Override
public native final JsonObject addField(String key, boolean value) /*-{
this[key] = value;
return this;
}-*/;
@Override
public native final JsonObject addField(String key, double value) /*-{
this[key] = value;
return this;
}-*/;
@Override
public native final JsonObject addField(String key, int value) /*-{
this[key] = value;
return this;
}-*/;
@Override
public final JsonObject addField(String key, JsonArray<?> value) {
// Delegate to the JS impl
return addField(key, (Object) value);
}
@Override
public final JsonObject addField(String key, JsonObject value) {
// Delegate to the JS impl
return addField(key, (Object) value);
}
public native final Jso addField(String key, Object value) /*-{
this[key] = value;
return this;
}-*/;
@Override
public native final Jso addField(String key, String value) /*-{
this[key] = value;
return this;
}-*/;
public native final Jso addNullField(String key) /*-{
this[key] = null;
return this;
}-*/;
public native final Jso addUndefinedField(String key) /*-{
this[key] = undefined;
return this;
}-*/;
public native final Jso deleteField(String key) /*-{
delete this[key];
}-*/;
@Override
public final JsoArray<JsonObject> getArrayField(String key) {
return ((Jso) getObjectField(key)).cast();
}
@Override
public final boolean getBooleanField(String key) {
return getBooleanFieldImpl(key);
}
/**
* @return evaluated boolean value (casted to a boolean). This is useful for
* "optional" boolean fields to treat {@code undefined} values as
* {@code false}
*/
public final native boolean getFieldCastedToBoolean(String key) /*-{
return !!this[key];
}-*/;
@Override
public final int getIntField(String key) {
return getIntFieldImpl(key);
}
/**
* Evaluates a given property to an integer number. The {@code undefined} and
* {@code null} key values will be casted to zero.
*
* @return evaluated integer value (casted to integer)
*/
public final int getFieldCastedToInteger(String key) {
return (int) getFieldCastedToNumber(key);
}
/**
* Evaluates a given property to a number. The {@code undefined} and
* {@code null} key values will be casted to zero.
*
* @return evaluated number value (casted to number)
*/
private native double getFieldCastedToNumber(String key) /*-{
return +(this[key] || 0);
}-*/;
public native final JavaScriptObject getJsObjectField(String key) /*-{
return this[key];
}-*/;
/*
* GWT dev mode adds a __gwt_ObjectId property to all objects. We have to call
* hasOwnProperty (which is overridden by GWT) when using for(in) loops to verify
* that the key is actually a property of the object, and not the __gwt_ObjectId
* set by Chrome dev mode.
*/
@Override
public native final JsoArray<String> getKeys() /*-{
keys = [];
for (key in this) {
if (Object.prototype.hasOwnProperty.call(this, key)) {
keys.push(key);
}
}
return keys;
}-*/;
public native final boolean isEmpty() /*-{
for (key in this) {
if (Object.prototype.hasOwnProperty.call(this, key)) {
return false;
}
}
return true;
}-*/;
@Override
public native final JsonObject getObjectField(String key) /*-{
return this[key];
}-*/;
public native final Object getJavaObjectField(String key) /*-{
return this[key];
}-*/;
@Override
public native final String getStringField(String key) /*-{
return this[key];
}-*/;
/**
* @return evaluated string value (casted to string)
*/
public final native String getFieldCastedToString(String key) /*-{
return "" + this[key];
}-*/;
/**
* Checks to see if the specific key is present as a field/property on the
* Jso.
*
* You should guard calls to primitive type getters with this or else you
* might blow up at runtime (attempting to pass null as a return value for a
* primitive type).
*
* @param key
* @return whether or not
*/
public native final boolean hasOwnProperty(String key) /*-{
return this.hasOwnProperty(key);
}-*/;
public final String serialize() {
return Jso.serialize(this);
}
private native boolean getBooleanFieldImpl(String key) /*-{
return this[key];
}-*/;
private native int getIntFieldImpl(String key) /*-{
return this[key];
}-*/;
/**
* Removes the GWT development/hosted mode property "__gwt_ObjectId".
*/
public final void removeGwtObjectId() {
deleteField("__gwt_ObjectId");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/SelectionAnnotationUtils.java | shared/src/main/java/com/google/collide/shared/SelectionAnnotationUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared;
/**
* Selection annotation-related utility methods that are used by both the client
* and server.
*
*/
public class SelectionAnnotationUtils {
/** The annotation prefix */
public static final String PREFIX = "selection";
private static final String PREFIX_SLASH = PREFIX + "/";
/**
* @return the annotation key for the user with the given email.
*/
public static String computeAnnotationKey(String email) {
return PREFIX_SLASH + escapeEmail(email);
}
/**
* @return true if the given annotation key is a selection annotation, false
* otherwise
*/
public static boolean isSelectionAnnotation(String key) {
return key.startsWith(PREFIX_SLASH);
}
/**
* The '@' character is a reserved character in annotation keys, so we must
* replace that with another character.
*/
private static String escapeEmail(String email) {
return (email == null) ? "" : email.replaceAll("@", "#");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/FrontendConstants.java | shared/src/main/java/com/google/collide/shared/FrontendConstants.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared;
/**
* Yes. Another shared constants file across client and server.
*/
public final class FrontendConstants {
// TODO - might need to move these if the FE doesn't actually look at them
/** Constants relating to file upload */
public static final class UploadConstants {
/** The globally unique ID for this upload session */
public static final String SESSION_ID = "sessionId";
/** The ID of the workspace these files are uploading to */
public static final String WORKSPACE_ID = "workspaceId";
/** The workspace path for the file */
public static final String WORKSPACE_PATH = "workspacePath";
/** The number of file failures in the metadata */
public static final String FILE_FAILURE_SIZE = "fileFailureCount";
/** The prefix for each file path in the metadata */
public static final String FILE_FAILURE_PREFIX = "fileFailure";
/** The failure message for the upload */
public static final String FAILURE_MESSAGE = "failureMessage";
/** The string inside a path that will cause a simulated network failure */
public static final String SIMULATED_NETWORK_FAILURE_PATH_SUBSTRING = "simulateNetworkFailure";
/** The string inside a path that will cause a simulated processing failure */
public static final String SIMULATED_PROCESSING_FAILURE_PATH_SUBSTRING =
"simulateProcessingFailure";
}
/**
* The name of the header for attaching the bootstrap client id to each
* request.
*/
public static final String CLIENT_BOOTSTRAP_ID_HEADER = "X-Bootstrap-ClientId";
/**
* Path for provisioning a browser channel.
*/
public static final String BROWSER_CHANNEL_PATH = "/channel/comm";
/**
* Test Path required for provisioning a browser channel.
*/
public static final String BROWSER_CHANNEL_TEST_PATH = "/channel/test";
/**
* Query parameter sent with browser channel requests by the client to
* identify itself to the frontend.
*/
public static final String CLIENTID_PARAM_NAME = "clientId";
/**
* Query parameter used to name a resource in a given workspace.
*/
public static final String FILE_PARAM_NAME = "file";
/**
* Maximum allowed length of project names.
*/
public static final int MAX_PROJECT_NAME_LEN = 128;
/**
* Maximum allowed size for uploaded files.
*/
public static final long MAX_UPLOAD_FILE_SIZE = 4L * 1024 * 1024; // 4MB
/**
* The name of the header for attaching an XSRF token to each request.
*/
public static final String XSRF_TOKEN_HEADER = "X-Xsrf-Token";
/**
* The name of the header that we keep the Client->Frontend protocol version hash.
*/
public static final String CLIENT_VERSION_HASH_HEADER = "X-Version-Hash";
/**
* The default depth to load the file tree and sub-directories. A depth of -1 indicates infinite
* depth.
*/
public static final int DEFAULT_FILE_TREE_DEPTH = -1;
private FrontendConstants() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/Pair.java | shared/src/main/java/com/google/collide/shared/Pair.java | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.collide.shared;
import java.io.Serializable;
import java.util.Comparator;
import javax.annotation.Nullable;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
/**
* An immutable, semantic-free ordered pair of nullable values. These can be
* accessed using the {@link #getFirst} and {@link #getSecond} methods. Equality
* and hashing are defined in the natural way.
*
* <p>This type is devoid of semantics, best used for simple mechanical
* aggregations of unrelated values in implementation code. Avoid using it in
* your APIs, preferring an explicit type that conveys the exact semantics of
* the data. For example, instead of: <pre> {@code
*
* Pair<T, T> findMinAndMax(List<T> list) {...}}</pre>
*
* ... use: <pre> {@code
*
* Range<T> findRange(List<T> list) {...}}</pre>
*
* This usually involves creating a new custom value-object type. This is
* difficult to do "by hand" in Java, but avoid the temptation to extend {@code
* Pair} to accomplish this; consider using the utilities {@link
* com.google.common.labs.misc.ComparisonKeys} or {@link
* com.google.common.labs.misc.ValueType} to help you with this instead.
*/
@GwtCompatible(serializable = true)
public class Pair<A, B> implements Serializable {
/**
* Creates a new pair containing the given elements in order.
*/
public static <A, B> Pair<A, B> of(@Nullable A first, @Nullable B second) {
return new Pair<A, B>(first, second);
}
/**
* The first element of the pair; see also {@link #getFirst}.
*/
public final A first;
/**
* The second element of the pair; see also {@link #getSecond}.
*/
public final B second;
/**
* Constructor. It is usually easier to call {@link #of}.
*/
public Pair(@Nullable A first, @Nullable B second) {
this.first = first;
this.second = second;
}
/**
* Returns the first element of this pair; see also {@link #first}.
*/
public A getFirst() {
return first;
}
/**
* Returns the second element of this pair; see also {@link #second}.
*/
public B getSecond() {
return second;
}
/** Returns a function that yields {@link #first}. */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <A, B> Function<Pair<A, B>, A> firstFunction() {
// The safety of the unchecked conversion here is implied by the
// implementation of the PairFirstFunction which always returns the first
// element from a pair (which for Pair<A, B> is of type A).
return (Function) PairFirstFunction.INSTANCE;
}
/** Returns a function that yields {@link #second}. */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <A, B> Function<Pair<A, B>, B> secondFunction() {
// The safety of the unchecked conversion here is implied by the
// implementation of the PairSecondFunction which always returns the second
// element from a pair (which for Pair<A, B> is of type B).
return (Function) PairSecondFunction.INSTANCE;
}
/*
* If we use the enum singleton pattern for these functions, Flume's type
* inference chokes: http://b/4863010
*/
@SuppressWarnings("serial")
private static final class PairFirstFunction<A, B>
implements Function<Pair<A, B>, A>, Serializable {
static final PairFirstFunction<Object, Object> INSTANCE =
new PairFirstFunction<Object, Object>();
@Override
public A apply(Pair<A, B> from) {
return from.getFirst();
}
private Object readResolve() {
return INSTANCE;
}
}
@SuppressWarnings("serial")
private static final class PairSecondFunction<A, B>
implements Function<Pair<A, B>, B>, Serializable {
static final PairSecondFunction<Object, Object> INSTANCE =
new PairSecondFunction<Object, Object>();
@Override
public B apply(Pair<A, B> from) {
return from.getSecond();
}
private Object readResolve() {
return INSTANCE;
}
}
/**
* Returns a comparator that compares two Pair objects by comparing the
* result of {@link #getFirst()} for each.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <A extends Comparable, B> Comparator<Pair<A, B>>
compareByFirst() {
return (Comparator) FirstComparator.FIRST_COMPARATOR;
}
/**
* Returns a comparator that compares two Pair objects by comparing the
* result of {@link #getSecond()} for each.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <A, B extends Comparable> Comparator<Pair<A, B>>
compareBySecond() {
return (Comparator) SecondComparator.SECOND_COMPARATOR;
}
// uses raw Comparable to support classes defined without generics
@SuppressWarnings({ "unchecked", "rawtypes" })
private enum FirstComparator implements Comparator<Pair<Comparable, Object>> {
FIRST_COMPARATOR;
@Override
public int compare(Pair<Comparable, Object> pair1,
Pair<Comparable, Object> pair2) {
return pair1.getFirst().compareTo(pair2.getFirst());
}
}
// uses raw Comparable to support classes defined without generics
@SuppressWarnings({ "unchecked", "rawtypes" })
private enum SecondComparator
implements Comparator<Pair<Object, Comparable>> {
SECOND_COMPARATOR;
@Override
public int compare(Pair<Object, Comparable> pair1,
Pair<Object, Comparable> pair2) {
return pair1.getSecond().compareTo(pair2.getSecond());
}
}
// TODO: decide what level of commitment to make to this impl
@Override public boolean equals(@Nullable Object object) {
// TODO: it is possible we want to change this to
// if (object != null && object.getClass() == getClass()) {
if (object instanceof Pair) {
Pair<?,?> that = (Pair<?,?>) object;
return Objects.equal(this.first, that.first)
&& Objects.equal(this.second, that.second);
}
return false;
}
@Override public int hashCode() {
int hash1 = first == null ? 0 : first.hashCode();
int hash2 = second == null ? 0 : second.hashCode();
return 31 * hash1 + hash2;
}
/**
* {@inheritDoc}
*
* <p>This implementation returns a string in the form
* {@code (first, second)}, where {@code first} and {@code second} are the
* String representations of the first and second elements of this pair, as
* given by {@link String#valueOf(Object)}. Subclasses are free to override
* this behavior.
*/
@Override public String toString() {
// GWT doesn't support String.format().
return "(" + first + ", " + second + ")";
}
private static final long serialVersionUID = 747826592375603043L;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/TaggableLine.java | shared/src/main/java/com/google/collide/shared/TaggableLine.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared;
/**
* Abstraction of a line of code that can have tags associated with it.
*/
public interface TaggableLine {
<T> T getTag(String key);
<T> void putTag(String key, T value);
TaggableLine getPreviousLine();
boolean isFirstLine();
boolean isLastLine();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/MimeTypes.java | shared/src/main/java/com/google/collide/shared/MimeTypes.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
/**
* Simple map of file extensions to supported MIME-TYPEs.
*
*/
public class MimeTypes {
/** MIME type to force a download, rather than display-in-browser */
public static final String BINARY_MIMETYPE = "application/octet-stream";
/** MIME type for json payloads */
public static final String JSON = "application/json";
/** MIMEtype for zip archives */
public static final String ZIP_MIMETYPE = "application/zip";
private static final JsonStringMap<String> mimeTypes = JsonCollections.createMap();
private static final JsonStringMap<Boolean> imageMimeTypes = JsonCollections.createMap();
static {
mimeTypes.put("gif", "image/gif");
mimeTypes.put("jpg", "image/jpeg");
mimeTypes.put("jpeg", "image/jpeg");
mimeTypes.put("jpe", "image/jpeg");
mimeTypes.put("png", "image/png");
mimeTypes.put("ico", "image/x-icon");
mimeTypes.put("xml", "text/xml");
mimeTypes.put("html", "text/html");
mimeTypes.put("css", "text/css");
mimeTypes.put("txt", "text/plain");
mimeTypes.put("js", "application/javascript");
mimeTypes.put("json", JSON);
mimeTypes.put("svg", "image/svg+xml");
mimeTypes.put("zip", ZIP_MIMETYPE);
imageMimeTypes.put("image/gif", true);
imageMimeTypes.put("image/jpeg", true);
imageMimeTypes.put("image/png", true);
}
/**
* Returns the appropriate MIME-TYPE string for a given file extension. If the
* MIME-TYPE cannot be found, null is returned. It is the responsibility of
* callers to provide a suitable default.
*/
public static String getMimeType(String extension) {
return mimeTypes.get(extension.toLowerCase());
}
/**
* Takes in a mimetype and returns whether or not it smells like an image.
*/
public static boolean looksLikeImage(String mimeType) {
return imageMimeTypes.containsKey(mimeType);
}
/**
* Inspects the file extension and guesses an appropriate mime-type for
* serving the file.
*
* In the absence of a file extension, we simply assume it is text.
*/
public static String guessMimeType(String path, boolean assumeUtf8) {
String lastPathComponent = path.substring(path.lastIndexOf('/') + 1, path.length());
int extensionIndex = lastPathComponent.lastIndexOf('.');
String extension = "";
if (extensionIndex >= 0) {
extension = lastPathComponent.substring(extensionIndex + 1, lastPathComponent.length());
}
String mimeType = MimeTypes.getMimeType(extension);
if (mimeType == null) {
if (assumeUtf8) {
mimeType = MimeTypes.getMimeType("txt");
} else {
mimeType = MimeTypes.BINARY_MIMETYPE;
}
}
return mimeType;
}
private MimeTypes() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/SortedPositionMap.java | shared/src/main/java/com/google/collide/shared/util/SortedPositionMap.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.util.LineUtils;
import com.google.collide.shared.util.SortedList.Comparator;
import com.google.collide.shared.util.SortedList.OneWayComparator;
/**
* A map with a key of (line number, column) and an arbitrary value.
*
*/
public class SortedPositionMap<T> {
private class Entry {
private final int lineNumber;
private final int column;
private final T value;
private Entry(int lineNumber, int column, T value) {
this.lineNumber = lineNumber;
this.column = column;
this.value = value;
}
}
/**
* A class to be used as a cached one-way comparator instance.
*
* Methods on this class are NOT re-entrant (though I can't imagine a scenario
* where the execution would lead to re-entrancy.)
*/
private class Finder implements OneWayComparator<Entry> {
private int lineNumber;
private int column;
@Override
public int compareTo(Entry o) {
return LineUtils.comparePositions(lineNumber, column, o.lineNumber, o.column);
}
private Entry findEntry(int lineNumber, int column) {
this.lineNumber = lineNumber;
this.column = column;
return list.find(this);
}
private int findInsertionIndex(int lineNumber, int column) {
this.lineNumber = lineNumber;
this.column = column;
return list.findInsertionIndex(this);
}
}
private final Comparator<Entry> comparator = new Comparator<Entry>() {
@Override
public int compare(Entry a, Entry b) {
return LineUtils.comparePositions(a.lineNumber, a.column, b.lineNumber, b.column);
}
};
private final Finder finder = new Finder();
private final SortedList<Entry> list;
public SortedPositionMap() {
list = new SortedList<Entry>(comparator);
}
public T get(int lineNumber, int column) {
Entry entry = finder.findEntry(lineNumber, column);
return entry != null ? entry.value : null;
}
/**
* Puts the value at the given position, replacing any existing value (which
* will be returned).
*/
public T put(int lineNumber, int column, T value) {
Entry existingEntry = finder.findEntry(lineNumber, column);
if (existingEntry != null) {
list.remove(existingEntry);
}
list.add(new Entry(lineNumber, column, value));
return existingEntry != null ? existingEntry.value : null;
}
public void putAll(SortedPositionMap<T> positionToToken) {
for (int i = 0, n = positionToToken.list.size(); i < n; i++) {
Entry entry = positionToToken.list.get(i);
put(entry.lineNumber, entry.column, entry.value);
}
}
/**
* Removes the values in the given range (begin is inclusive, end is
* exclusive).
*/
public void removeRange(int beginLineNumber, int beginColumn, int endLineNumber, int endColumn) {
int index = finder.findInsertionIndex(beginLineNumber, beginColumn);
while (index < list.size()) {
Entry entry = list.get(index);
if (LineUtils.comparePositions(entry.lineNumber, entry.column, endLineNumber, endColumn)
>= 0) {
// This item is past the end, we're done!
return;
}
list.remove(index);
// No need to increment index since we just removed an item
}
}
public int size() {
return list.size();
}
public JsonArray<T> values() {
JsonArray<T> values = JsonCollections.createArray();
for (int i = 0, n = list.size(); i < n; i++) {
values.add(list.get(i).value);
}
return values;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/MathUtils.java | shared/src/main/java/com/google/collide/shared/util/MathUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
/**
* Utility methods for math-related functionality.
*/
public class MathUtils {
/**
* Returns whether the {@code number} is in the given inclusive range.
*/
public static boolean isInRangeInclusive(int number, int lowerBound, int upperBound) {
return lowerBound <= number && number <= upperBound;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/Timer.java | shared/src/main/java/com/google/collide/shared/util/Timer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
/**
* A timer that can be used by shared code.
*/
public interface Timer {
public interface Factory {
Timer createTimer(Runnable runnable);
}
void schedule(int delayMs);
void cancel();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/SharedLogUtils.java | shared/src/main/java/com/google/collide/shared/util/SharedLogUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
/**
* Utility methods for logging from shared code.
*/
public class SharedLogUtils {
public interface Implementation {
void markTimeline(Class<?> clazz, String label);
void info(Class<?> clazz, Object... objects);
void warn(Class<?> clazz, Object... objects);
void error(Class<?> clazz, Object... objects);
void debug(Class<?> clazz, Object... objects);
}
private static class NoopImplementation implements Implementation {
@Override
public void markTimeline(Class<?> clazz, String label) {
}
@Override
public void info(Class<?> clazz, Object... objects) {
}
@Override
public void debug(Class<?> clazz, Object... objects) {
}
@Override
public void error(Class<?> clazz, Object... objects) {
}
@Override
public void warn(Class<?> clazz, Object... objects) {
}
}
private static Implementation implementation = new NoopImplementation();
public static void setImplementation(Implementation implementation) {
SharedLogUtils.implementation = implementation;
}
public static void markTimeline(Class<?> clazz, String label) {
implementation.markTimeline(clazz, label);
}
public static void info(Class<?> clazz, Object... objects) {
implementation.info(clazz, objects);
}
public static void error(Class<?> clazz, Object... objects) {
implementation.error(clazz, objects);
}
public static void debug(Class<?> clazz, Object... objects) {
implementation.debug(clazz, objects);
}
public static void warn(Class<?> clazz, Object... objects) {
implementation.warn(clazz, objects);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/StringUtils.java | shared/src/main/java/com/google/collide/shared/util/StringUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import javax.annotation.Nonnull;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonIntegerMap;
/**
* Utility methods for string operations.
*
*/
public class StringUtils {
/**
* Map [N] -> string of N spaces. Used by {@link #getSpaces} to cache strings
* of spaces.
*/
private static final JsonIntegerMap<String> cachedSpaces = JsonCollections.createIntegerMap();
/**
* Interface that defines string utility methods used by shared code but have
* differing client and server implementations.
*/
public interface Implementation {
JsonArray<String> split(String string, String separator);
}
private static class PureJavaImplementation implements Implementation {
@Override
public JsonArray<String> split(String string, String separator) {
JsonArray<String> result = JsonCollections.createArray();
int sepLength = separator.length();
if (sepLength == 0) {
for (int i = 0, n = string.length(); i < n; i++) {
result.add(string.substring(i, i + 1));
}
return result;
}
int position = 0;
while (true) {
int index = string.indexOf(separator, position);
if (index == -1) {
result.add(string.substring(position));
return result;
}
result.add(string.substring(position, index));
position = index + sepLength;
}
}
}
/**
* By default, this is a pure java implementation, but can be set to a more
* optimized version by the client
*/
private static Implementation implementation = new PureJavaImplementation();
/**
* Sets the implementation for methods
*/
public static void setImplementation(Implementation implementation) {
StringUtils.implementation = implementation;
}
/**
* @return largest n such that
* {@code string1.substring(0, n).equals(string2.substring(0, n))}
*/
public static int findCommonPrefixLength(String string1, String string2) {
int limit = Math.min(string1.length(), string2.length());
int result = 0;
while (result < limit) {
if (string2.charAt(result) != string1.charAt(result)) {
break;
}
result++;
}
return result;
}
public static int countNumberOfOccurrences(String s, String pattern) {
int count = 0;
int i = 0;
while ((i = s.indexOf(pattern, i)) >= 0) {
count++;
i += pattern.length();
}
return count;
}
/**
* Check if a String ends with a specified suffix, ignoring case
*
* @param s the String to check, may be null
* @param suffix the suffix to find, may be null
* @return true if s ends with suffix or both s and suffix are null, false
* otherwise.
*/
public static boolean endsWithIgnoreCase(String s, String suffix) {
if (s == null || suffix == null) {
return (s == null && suffix == null);
}
if (suffix.length() > s.length()) {
return false;
}
return s.regionMatches(true, s.length() - suffix.length(), suffix, 0, suffix.length());
}
public static boolean looksLikeImage(String path) {
String lowercase = path.toLowerCase();
return lowercase.endsWith(".jpg") || lowercase.endsWith(".jpeg") || lowercase.endsWith(".ico")
|| lowercase.endsWith(".png") || lowercase.endsWith(".gif");
}
public static <T> String join(T[] items, String separator) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < items.length; i++) {
s.append(items[i]).append(separator);
}
s.setLength(s.length() - separator.length());
return s.toString();
}
public static <T> String join(JsonArray<T> items, String separator) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
s.append(items.get(i)).append(separator);
}
s.setLength(s.length() - separator.length());
return s.toString();
}
/**
* Check that string starts with specified prefix.
*
* <p>If {@code caseInsensitive == false} this check is equivalent
* to {@link String#startsWith(String)}.
*
* <p>Otherwise {@code prefix} should be lower-case and check ignores
* case of {@code string}.
*/
public static boolean startsWith(
@Nonnull String prefix, @Nonnull String string, boolean caseInsensitive) {
if (caseInsensitive) {
int prefixLength = prefix.length();
if (string.length() < prefixLength) {
return false;
}
return prefix.equals(string.substring(0, prefixLength).toLowerCase());
} else {
return string.startsWith(prefix);
}
}
/**
* @return the length of the starting whitespace for the line, or the string
* length if it is all whitespace
*/
public static int lengthOfStartingWhitespace(String s) {
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
// TODO: This currently only deals with ASCII whitespace.
// Read until a non-space
if (c != ' ' && c != '\t') {
return i;
}
}
return n;
}
/**
* @return first character in the string that is not a whitespace, or
* {@code 0} if there is no such characters
*/
public static char firstNonWhitespaceCharacter(String s) {
for (int i = 0, n = s.length(); i < n; ++i) {
char c = s.charAt(i);
if (!isWhitespace(c)) {
return c;
}
}
return 0;
}
/**
* @return last character in the string that is not a whitespace, or
* {@code 0} if there is no such characters
*/
public static char lastNonWhitespaceCharacter(String s) {
for (int i = s.length() - 1; i >= 0; --i) {
char c = s.charAt(i);
if (!isWhitespace(c)) {
return c;
}
}
return 0;
}
public static String nullToEmpty(String s) {
return s == null ? "" : s;
}
public static boolean isNullOrEmpty(String s) {
return s == null || "".equals(s);
}
public static boolean isNullOrWhitespace(String s) {
return s == null || "".equals(s.trim());
}
public static String trimNullToEmpty(String s) {
return s == null ? "" : s.trim();
}
public static String ensureNotEmpty(String s, String defaultStr) {
return isNullOrEmpty(s) ? defaultStr : s;
}
public static boolean isWhitespace(char ch) {
return (ch <= ' ');
}
public static boolean isAlpha(char ch) {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z');
}
public static boolean isNumeric(char ch) {
return ('0' <= ch && ch <= '9');
}
public static boolean isQuote(char ch) {
return ch == '\'' || ch == '\"';
}
public static boolean isAlphaNumOrUnderscore(char ch) {
return isAlpha(ch) || isNumeric(ch) || ch == '_';
}
public static long toLong(String longStr) {
return longStr == null ? 0 : Long.parseLong(longStr);
}
/**
* @return true, if both strings are empty or {@code null}, or if they are
* equal
*/
public static boolean equalStringsOrEmpty(String a, String b) {
return nullToEmpty(a).equals(nullToEmpty(b));
}
/**
* @return true, if the strings are not empty or {@code null}, and equal
*/
public static boolean equalNonEmptyStrings(String a, String b) {
return !isNullOrEmpty(a) && a.equals(b);
}
/**
* Splits with the contract of the contract of the JavaScript String.split().
*
* <p>More specifically: empty segments will be produced for adjacent and
* trailing separators.
*
* <p>If an empty string is used as the separator, the string is split
* between each character.
*
* <p>Examples:<ul>
* <li>{@code split("a", "a")} should produce {@code ["", ""]}
* <li>{@code split("a\n", "\n")} should produce {@code ["a", ""]}
* <li>{@code split("ab", "")} should produce {@code ["a", "b"]}
* </ul>
*/
public static JsonArray<String> split(String s, String separator) {
return implementation.split(s, separator);
}
/**
* @return the number of editor lines this text would take up
*/
public static int countNumberOfVisibleLines(String text) {
return countNumberOfOccurrences(text, "\n") + (text.endsWith("\n") ? 0 : 1);
}
public static String capitalizeFirstLetter(String s) {
if (!isNullOrEmpty(s)) {
s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
return s;
}
public static String ensureStartsWith(String s, String startText) {
if (isNullOrEmpty(s)) {
return startText;
} else if (!s.startsWith(startText)) {
return startText + s;
} else {
return s;
}
}
/**
* Like {@link String#substring(int)} but allows for the {@code count}
* parameter to extend past the string's bounds.
*/
public static String substringGuarded(String s, int position, int count) {
int sLength = s.length();
if (sLength - position <= count) {
return position == 0 ? s : s.substring(position);
} else {
return s.substring(position, position + count);
}
}
public static String repeatString(String s, int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append(s);
}
return builder.toString();
}
/**
* Gets a {@link String} consisting of the given number of spaces.
*
* <p>NB: The result is cached in {@link #cachedSpaces}.
*
* @param size the number of spaces
* @return a {@link String} consisting of {@code size} spaces
*/
public static String getSpaces(int size) {
if (cachedSpaces.hasKey(size)) {
return cachedSpaces.get(size);
}
char[] fill = new char[size];
for (int i = 0; i < size; i++) {
fill[i] = ' ';
}
String spaces = new String(fill);
cachedSpaces.put(size, spaces);
return spaces;
}
/**
* If this given string is of length {@code maxLength} or less, it will
* be returned as-is.
* Otherwise it will be trucated to {@code maxLength}, regardless of whether
* there are any space characters in the String. If an ellipsis is requested
* to be appended to the truncated String, the String will be truncated so
* that the ellipsis will also fit within maxLength.
* If no truncation was necessary, no ellipsis will be added.
* @param source the String to truncate if necessary
* @param maxLength the maximum number of characters to keep
* @param addEllipsis if true, and if the String had to be truncated,
* add "..." to the end of the String before returning. Additionally,
* the ellipsis will only be added if maxLength is greater than 3.
* @return the original string if it's length is less than or equal to
* maxLength, otherwise a truncated string as mentioned above
*/
public static String truncateAtMaxLength(String source, int maxLength,
boolean addEllipsis) {
if (source.length() <= maxLength) {
return source;
}
if (addEllipsis && maxLength > 3) {
return unicodePreservingSubstring(source, 0, maxLength - 3) + "...";
}
return unicodePreservingSubstring(source, 0, maxLength);
}
/**
* Normalizes {@code index} such that it respects Unicode character
* boundaries in {@code str}.
*
* <p>If {@code index} is the low surrogate of a unicode character,
* the method returns {@code index - 1}. Otherwise, {@code index} is
* returned.
*
* <p>In the case in which {@code index} falls in an invalid surrogate pair
* (e.g. consecutive low surrogates, consecutive high surrogates), or if
* if it is not a valid index into {@code str}, the original value of
* {@code index} is returned.
*
* @param str the String
* @param index the index to be normalized
* @return a normalized index that does not split a Unicode character
*/
private static int unicodePreservingIndex(String str, int index) {
if (index > 0 && index < str.length()) {
if (Character.isHighSurrogate(str.charAt(index - 1)) &&
Character.isLowSurrogate(str.charAt(index))) {
return index - 1;
}
}
return index;
}
/**
* Returns a substring of {@code str} that respects Unicode character
* boundaries.
*
* <p>The string will never be split between a [high, low] surrogate pair,
* as defined by {@link Character#isHighSurrogate} and
* {@link Character#isLowSurrogate}.
*
* <p>If {@code begin} or {@code end} are the low surrogate of a unicode
* character, it will be offset by -1.
*
* <p>This behavior guarantees that
* {@code str.equals(StringUtil.unicodePreservingSubstring(str, 0, n) +
* StringUtil.unicodePreservingSubstring(str, n, str.length())) } is
* true for all {@code n}.
* </pre>
*
* <p>This means that unlike {@link String#substring(int, int)}, the length of
* the returned substring may not necessarily be equivalent to
* {@code end - begin}.
*
* @param str the original String
* @param begin the beginning index, inclusive
* @param end the ending index, exclusive
* @return the specified substring, possibly adjusted in order to not
* split unicode surrogate pairs
* @throws IndexOutOfBoundsException if the {@code begin} is negative,
* or {@code end} is larger than the length of {@code str}, or
* {@code begin} is larger than {@code end}
*/
private static String unicodePreservingSubstring(
String str, int begin, int end) {
return str.substring(unicodePreservingIndex(str, begin),
unicodePreservingIndex(str, end));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/ErrorCallback.java | shared/src/main/java/com/google/collide/shared/util/ErrorCallback.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
/**
* Interface that is called when there is a failure executing some logic.
*/
public interface ErrorCallback {
void onError();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/TextUtils.java | shared/src/main/java/com/google/collide/shared/util/TextUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
/**
* Utility methods for text operations. This differs from {@link StringUtils} by
* operating on a higher-level (for example, words and identifiers).
*/
public class TextUtils {
/**
* Finds the next character which is not a mark or other character. Will
* return column if the end of the line is reached or column is a non-mark or
* other character.
*/
public static int findNextCharacterInclusive(String text, int column) {
MatchResult result = RegExpUtils.findMatchAfterIndex(
UnicodeUtils.regexpNotMarkOrOtherExcludingTabAndNewline, text, column - 1);
// if result is null, then it's likely we're at the \n (I think).
return result == null ? column : result.getIndex();
}
/**
* Finds the next character which is not a combining character.
*/
public static int findNonMarkNorOtherCharacter(String text, int column) {
/*
* If moving forward: if next character is combining mark, skip to next
* non-combining mark character, else go forward one character.
*/
if (column + 1 >= text.length()) {
return text.length() + 1;
}
MatchResult match = RegExpUtils.findMatchAfterIndex(
UnicodeUtils.regexpNotMarkOrOtherExcludingTabAndNewline, text, column);
if (match == null) {
return text.length() + 1;
} else {
return match.getIndex();
}
}
/**
* Finds the previous character which is not a combining character.
*/
public static int findPreviousNonMarkNorOtherCharacter(String text, int column) {
/*
* If moving backward: if previous character is combining mark, skip to
* before first non-combining mark character. If it isn't a combining mark,
* proceed back one character.
*/
if (column - 1 < 0) {
return -1;
}
MatchResult match = RegExpUtils.findMatchBeforeIndex(
UnicodeUtils.regexpNotMarkOrOtherExcludingTabAndNewline, text, column);
if (match == null) {
return -1;
} else {
return match.getIndex();
}
}
/**
* Finds the index of the next non-similar word. There are two groups of
* words: Javascript identifiers and the remaining non-whitespace characters.
*
* Consider the text "hello there". With {@code skipWhitespaceBeforeWord}
* true, the return value would be at the 't'. With it false, the return value
* would be at the ' '.
*
* Consider the text "someFunction(foo); // Test" and
* {@code skipWhitespaceBeforeWord} is true. findNextWord(text, 0) will return
* the index of the '(', since it is the first word that is not an identifier.
* findNextWord(text, 12) will return the 13 ('f' from "foo").
* findNextWord(text, 17) will return 19 ('/').
*
* @param skipWhitespaceBeforeWord true to skip the whitespace before the next
* word (thus returning the position of the first letter of the word),
* false to return the position of the first whitespace before the word
* @return the index according to {@code skipWhitespaceBeforeWord}, or if the
* given {@code column} is beyond the string's length, this will
* return the length plus one.
*/
public static int findNextWord(String text, int column, boolean skipWhitespaceBeforeWord) {
if (column + 1 >= text.length()) {
return text.length() + 1;
}
int initialColumn = column;
if (skipWhitespaceBeforeWord) {
column = skipNonwhitespaceSimilar(text, column, true);
column = skipWhitespace(text, column, true);
} else {
column = skipWhitespace(text, column, true);
column = skipNonwhitespaceSimilar(text, column, true);
}
return column;
}
/**
* Counts number of whitespaces at the beginning of line.
*/
public static int countWhitespacesAtTheBeginningOfLine(String text) {
MatchResult result = RegExpUtils.findMatchAfterIndex(
UnicodeUtils.regexpNotWhitespaceExcludingNewlineAndCarriageReturn, text, -1);
return result == null ? text.length() : result.getIndex();
}
/**
* Similar to {@link #findNextWord}, but searches backwards.
*
* <p>Character at {@code column} position is ignored, because it denotes the
* symbol after "cursor".
*/
public static int findPreviousWord(String text, int column, boolean skipWhitespaceBeforeWord) {
column--;
if (column < 0) {
return -1;
}
if (skipWhitespaceBeforeWord) {
column = skipNonwhitespaceSimilar(text, column, false);
column = skipWhitespace(text, column, false);
} else {
column = skipWhitespace(text, column, false);
if (column >= 0) {
column = skipNonwhitespaceSimilar(text, column, false);
}
}
column++;
return column;
}
/**
* Jumps to the previous or next best match given the parameters below. This
* may be inside the current word. For example, if the cursor is at index 1 in
* "hey bob", and moveByWord is called with returnCursorAtEnd=true, then the
* returned value will be 2 (y). If returnCursorAtEnd is false, it would
* return 4 (b).
*
* @param column the start column for the search
* @param forward true for forward match, false for backwards match
* @param returnCursorAtEnd if true, the cursor position returned will be for
* the last character of the next/previous word found
* @return the calculated column, -1 for no valid match found
*/
/*
* TODO: Make sure we look at this, it is only used by the {@link
* VimScheme} and I think it can be made significantly less complicated as
* well as use the {@link #findNextWord(String, int, boolean)} and {@link
* #findPreviousWord(String, int, boolean)} API.
*/
public static int moveByWord(
String text, int column, boolean forward, boolean returnCursorAtEnd) {
int curColumn = column;
int length = text.length();
int direction = forward ? 1 : -1;
boolean farWordEnd =
((direction == 1 && returnCursorAtEnd) || (direction == -1 && !returnCursorAtEnd));
boolean foundEarlyMatch = false;
if (!UnicodeUtils.isWhitespace(text.charAt(curColumn))) {
// land on the first whitespace character after the last letter
curColumn = skipNonwhitespaceSimilar(text, curColumn, forward);
if (farWordEnd && curColumn - direction != column) {
// found a match within the same word
curColumn -= direction; // go back to last non-whitespace character
foundEarlyMatch = true;
}
}
if (!foundEarlyMatch && curColumn >= 0 && curColumn < length) {
// land on the first non-whitespace character of the next word
curColumn = skipWhitespace(text, curColumn, forward);
if (farWordEnd && curColumn >= 0 && curColumn < length) {
// land on the last non-whitespace character of the next word
curColumn = skipNonwhitespaceSimilar(text, curColumn, forward) - direction;
}
}
if (curColumn < 0 || curColumn >= length) {
return -1;
}
return curColumn;
}
/**
* Returns the entire word that the cursor at {@code column} falls into, or
* null if the cursor is over whitespace.
*/
public static String getWordAtColumn(String text, int column) {
if (UnicodeUtils.isWhitespace(text.charAt(column))) {
return null;
}
int leftColumn = skipNonwhitespaceSimilar(text, column, false) + 1;
int rightColumn = skipNonwhitespaceSimilar(text, column, true);
if (leftColumn >= 0 && rightColumn < text.length()) {
return text.substring(leftColumn, rightColumn);
}
return null;
}
public static boolean isValidIdentifierCharacter(char c) {
return !RegExpUtils.resetAndTest(
UnicodeUtils.regexpNotJavascriptIdentifierCharacter, String.valueOf(c));
}
public static boolean isNonIdentifierAndNonWhitespace(char c) {
return RegExpUtils.resetAndTest(UnicodeUtils.regexpIdentifierOrWhitespace, String.valueOf(c));
}
private static int skipIdentifier(String text, int column, boolean forward) {
return directionalRegexp(
forward, UnicodeUtils.regexpNotJavascriptIdentifierCharacter, text, column);
}
public static int skipNonwhitespaceNonidentifier(String text, int column, boolean forward) {
if (column >= 0 && column < text.length()) {
return directionalRegexp(forward, UnicodeUtils.regexpIdentifierOrWhitespace, text, column);
}
return column;
}
private static int skipNonwhitespaceSimilar(String text, int column, boolean forward) {
if (isValidIdentifierCharacter(text.charAt(column))) {
return skipIdentifier(text, column, forward);
} else {
return skipNonwhitespaceNonidentifier(text, column, forward);
}
}
private static int skipWhitespace(String text, int column, boolean forward) {
// we only execute the whitespace skip if the current character is in fact
// whitespace
if (column >= 0 && column < text.length() && UnicodeUtils.isWhitespace(text.charAt(column))) {
return directionalRegexp(forward, UnicodeUtils.regexpNotWhitespace, text, column);
}
return column;
}
/**
* Depending on the supplied direction, it will call either
* findMatchAfterIndex or findMatchBeforeIndex. Once the result is obtained it
* will return either the match index or the appropriate bound column
* (text.length() or -1).
*/
private static int directionalRegexp(boolean forward, RegExp regexp, String text, int column) {
MatchResult result =
forward ? RegExpUtils.findMatchAfterIndex(regexp, text, column)
: RegExpUtils.findMatchBeforeIndex(regexp, text, column);
int fallback = forward ? text.length() : -1;
return result == null ? fallback : result.getIndex();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/Channel.java | shared/src/main/java/com/google/collide/shared/util/Channel.java | package com.google.collide.shared.util;
public interface Channel <T>{
public void send(T t);
public T receive();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/DebugUtil.java | shared/src/main/java/com/google/collide/shared/util/DebugUtil.java | package com.google.collide.shared.util;
public class DebugUtil {
public static String getFullStacktrace(Throwable t, String separator){
StringBuilder b = new StringBuilder();
for (StackTraceElement el : t.getStackTrace()){
b.append(toString(el));
b.append(separator);
}
Throwable cause = t.getCause();
if (cause != null&&t.getCause()!=t)
b.append(getFullStacktrace(t.getCause(), separator+" "));
return b.toString();
}
public static String toString(StackTraceElement el) {
return el.getClassName()+"."+el.getMethodName()+"("+el.getLineNumber()+"): "+el.getFileName();
}
public static String getCaller(){
return getCaller(10, "\n");
}
public static String getCaller(int limit){
return getCaller(limit, "\n");
}
public static String getCaller(int limit,String separator){
Throwable t = new Throwable();
t.fillInStackTrace();
StringBuilder b = new StringBuilder();
StackTraceElement[] trace = t.getStackTrace();
limit = Math.min(limit, trace.length);
for (int i = 0;++i<limit;){
b.append(toString(trace[i]));
b.append(separator);
}
return b.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/UnicodeUtils.java | shared/src/main/java/com/google/collide/shared/util/UnicodeUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.common.base.Joiner;
import com.google.gwt.regexp.shared.RegExp;
/**
* This is an import of the unicode character categories table. It can be used
* to create {@link RegExp} which match based on the type of character
* (something not available easily via the javascript regexp engine).
*
* <p>
* <h3>How-To</h3>This utility class is full of strings consisting of valid
* regular expression character ranges that identify the character classes in
* Unicode 6.0. The theory is pretty simple, pick the categories you are
* interested in and create a regular expression by using
* {@link CharacterClass#create(String...)} to create a character class which
* matches the provided groups or {@link CharacterClass#invert(String...)} which
* matches any characters but the provided groups. Once created, pass the
* {@link CharacterClass} into {@link #compile(CharacterClass...)} to compile
* them together into a single regular expression. By compiling two
* {@link CharacterClass} into a single regex you can exclude certain characters
* from a group (an example being {@link #javascriptIdentifierRegexp}).
* </p>
*
*/
/*
* This class is full of a lot of stuff that isn't used yet. The theory being
* any unused things will be stripped out by GWT as dead code.
*/
public class UnicodeUtils {
private final static String lowercaseRegexp = "\u0061-\u007A\u00AA\u00B5\u00BA\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137-\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148-\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C-\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA-\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9-\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC-\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF-\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F-\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0-\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB-\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE-\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D62-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6-\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FC7\u1FD0-\u1FD3\u1FD6-\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6-\u1FF7\u210A\u210E-\u210F\u2113\u212F\u2134\u2139\u213C-\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65-\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73-\u2C74\u2C76-\u2C7C\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3-\u2CE4\u2CEC\u2CEE\u2D00-\u2D25\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A";
private final static String uppercaseRegexp = "\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178-\u0179\u017B\u017D\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018B\u018E-\u0191\u0193-\u0194\u0196-\u0198\u019C-\u019D\u019F-\u01A0\u01A2\u01A4\u01A6-\u01A7\u01A9\u01AC\u01AE-\u01AF\u01B1-\u01B3\u01B5\u01B7-\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A-\u023B\u023D-\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E-\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9-\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0-\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E-\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D-\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uFF21-\uFF3A";
private final static String titlecaseLetterRegexp = "\u01C5\u01C8\u01CB\u01F2\u1F88-\u1F8F\u1F98-\u1F9F\u1FA8-\u1FAF\u1FBC\u1FCC\u1FFC";
private final static String modifierLetterRegexp = "\u02B0-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0374\u037A\u0559\u0640\u06E5-\u06E6\u07F4-\u07F5\u07FA\u081A\u0824\u0828\u0971\u0E46\u0EC6\u10FC\u17D7\u1843\u1AA7\u1C78-\u1C7D\u1D2C-\u1D61\u1D78\u1D9B-\u1DBF\u2071\u207F\u2090-\u209C\u2C7D\u2D6F\u2E2F\u3005\u3031-\u3035\u303B\u309D-\u309E\u30FC-\u30FE\uA015\uA4F8-\uA4FD\uA60C\uA67F\uA717-\uA71F\uA770\uA788\uA9CF\uAA70\uAADD\uFF70\uFF9E-\uFF9F";
private final static String letterWithoutCaseRegexp = "\u01BB\u01C0-\u01C3\u0294\u05D0-\u05EA\u05F0-\u05F2\u0620-\u063F\u0641-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u0800-\u0815\u0840-\u0858\u0904-\u0939\u093D\u0950\u0958-\u0961\u0972-\u0977\u0979-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0CF1-\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EDC-\u0EDD\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10D0-\u10FA\u1100-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17DC\u1820-\u1842\u1844-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1BC0-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C77\u1CE9-\u1CEC\u1CEE-\u1CF1\u2135-\u2138\u2D30-\u2D65\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3006\u303C\u3041-\u3096\u309F\u30A1-\u30FA\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400\u4DB5\u4E00\u9FCB\uA000-\uA014\uA016-\uA48C\uA4D0-\uA4F7\uA500-\uA60B\uA610-\uA61F\uA62A-\uA62B\uA66E\uA6A0-\uA6E5\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA6F\uAA71-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA2D\uFA30-\uFA6D\uFA70-\uFAD9\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF66-\uFF6F\uFF71-\uFF9D\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
private final static String nonSpacingMarkRegexp = "\u0300-\u036F\u0483-\u0487\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0900-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962-\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2-\u09E3\u0A01-\u0A02\u0A3C\u0A41-\u0A42\u0A47-\u0A48\u0A4B-\u0A4D\u0A51\u0A70-\u0A71\u0A75\u0A81-\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7-\u0AC8\u0ACD\u0AE2-\u0AE3\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62-\u0B63\u0B82\u0BC0\u0BCD\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55-\u0C56\u0C62-\u0C63\u0CBC\u0CBF\u0CC6\u0CCC-\u0CCD\u0CE2-\u0CE3\u0D41-\u0D44\u0D4D\u0D62-\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB-\u0EBC\u0EC8-\u0ECD\u0F18-\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86-\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039-\u103A\u103D-\u103E\u1058-\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193B\u1A17-\u1A18\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80-\u1B81\u1BA2-\u1BA5\u1BA8-\u1BA9\u1BE6\u1BE8-\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1DC0-\u1DE6\u1DFC-\u1DFF\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099-\u309A\uA66F\uA67C-\uA67D\uA6F0-\uA6F1\uA802\uA806\uA80B\uA825-\uA826\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uAA29-\uAA2E\uAA31-\uAA32\uAA35-\uAA36\uAA43\uAA4C\uAAB0\uAAB2-\uAAB4\uAAB7-\uAAB8\uAABE-\uAABF\uAAC1\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE26";
private final static String spacingCombiningMarkRegexp = "\u0903\u093B\u093E-\u0940\u0949-\u094C\u094E-\u094F\u0982-\u0983\u09BE-\u09C0\u09C7-\u09C8\u09CB-\u09CC\u09D7\u0A03\u0A3E-\u0A40\u0A83\u0ABE-\u0AC0\u0AC9\u0ACB-\u0ACC\u0B02-\u0B03\u0B3E\u0B40\u0B47-\u0B48\u0B4B-\u0B4C\u0B57\u0BBE-\u0BBF\u0BC1-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD7\u0C01-\u0C03\u0C41-\u0C44\u0C82-\u0C83\u0CBE\u0CC0-\u0CC4\u0CC7-\u0CC8\u0CCA-\u0CCB\u0CD5-\u0CD6\u0D02-\u0D03\u0D3E-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D57\u0D82-\u0D83\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DF2-\u0DF3\u0F3E-\u0F3F\u0F7F\u102B-\u102C\u1031\u1038\u103B-\u103C\u1056-\u1057\u1062-\u1064\u1067-\u106D\u1083-\u1084\u1087-\u108C\u108F\u109A-\u109C\u17B6\u17BE-\u17C5\u17C7-\u17C8\u1923-\u1926\u1929-\u192B\u1930-\u1931\u1933-\u1938\u19B0-\u19C0\u19C8-\u19C9\u1A19-\u1A1B\u1A55\u1A57\u1A61\u1A63-\u1A64\u1A6D-\u1A72\u1B04\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B44\u1B82\u1BA1\u1BA6-\u1BA7\u1BAA\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2-\u1BF3\u1C24-\u1C2B\u1C34-\u1C35\u1CE1\u1CF2\uA823-\uA824\uA827\uA880-\uA881\uA8B4-\uA8C3\uA952-\uA953\uA983\uA9B4-\uA9B5\uA9BA-\uA9BB\uA9BD-\uA9C0\uAA2F-\uAA30\uAA33-\uAA34\uAA4D\uAA7B\uABE3-\uABE4\uABE6-\uABE7\uABE9-\uABEA\uABEC";
private final static String enclosingMarkRegexp = "\u0488-\u0489\u20DD-\u20E0\u20E2-\u20E4\uA670-\uA672";
private final static String decimalDigitRegexp = "\u0030-\u0039\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19";
private final static String letterNumberRegexp = "\u16EE-\u16F0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303A\uA6E6-\uA6EF";
private final static String otherNumberRegexp = "\u00B2-\u00B3\u00B9\u00BC-\u00BE\u09F4-\u09F9\u0B72-\u0B77\u0BF0-\u0BF2\u0C78-\u0C7E\u0D70-\u0D75\u0F2A-\u0F33\u1369-\u137C\u17F0-\u17F9\u19DA\u2070\u2074-\u2079\u2080-\u2089\u2150-\u215F\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3192-\u3195\u3220-\u3229\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA830-\uA835";
private final static String dashPunctuationRegexp = "\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u301C\u3030\u30A0\uFE31-\uFE32\uFE58\uFE63\uFF0D";
private final static String openPuncutationRegexp = "\u0028\u005B\u007B\u0F3A\u0F3C\u169B\u201A\u201E\u2045\u207D\u208D\u2329\u2768\u276A\u276C\u276E\u2770\u2772\u2774\u27C5\u27E6\u27E8\u27EA\u27EC\u27EE\u2983\u2985\u2987\u2989\u298B\u298D\u298F\u2991\u2993\u2995\u2997\u29D8\u29DA\u29FC\u2E22\u2E24\u2E26\u2E28\u3008\u300A\u300C\u300E\u3010\u3014\u3016\u3018\u301A\u301D\uFD3E\uFE17\uFE35\uFE37\uFE39\uFE3B\uFE3D\uFE3F\uFE41\uFE43\uFE47\uFE59\uFE5B\uFE5D\uFF08\uFF3B\uFF5B\uFF5F\uFF62";
private final static String closePuncutationRegexp = "\u0029\u005D\u007D\u0F3B\u0F3D\u169C\u2046\u207E\u208E\u232A\u2769\u276B\u276D\u276F\u2771\u2773\u2775\u27C6\u27E7\u27E9\u27EB\u27ED\u27EF\u2984\u2986\u2988\u298A\u298C\u298E\u2990\u2992\u2994\u2996\u2998\u29D9\u29DB\u29FD\u2E23\u2E25\u2E27\u2E29\u3009\u300B\u300D\u300F\u3011\u3015\u3017\u3019\u301B\u301E-\u301F\uFD3F\uFE18\uFE36\uFE38\uFE3A\uFE3C\uFE3E\uFE40\uFE42\uFE44\uFE48\uFE5A\uFE5C\uFE5E\uFF09\uFF3D\uFF5D\uFF60\uFF63";
private final static String initialPunctuationRegexp = "\u00AB\u2018\u201B-\u201C\u201F\u2039\u2E02\u2E04\u2E09\u2E0C\u2E1C\u2E20";
private final static String finalPuncutationRegexp = "\u00BB\u2019\u201D\u203A\u2E03\u2E05\u2E0A\u2E0D\u2E1D\u2E21";
private final static String connectorPuncutationRegexp = "\u005F\u203F-\u2040\u2054\uFE33-\uFE34\uFE4D-\uFE4F\uFF3F";
/* \u005C is a '\' we have to repeat it twice to escape itself! */
private final static String punctuationOtherRegexp = "\u0021-\u0023\u0025-\u0027\u002A\u002C\u002E-\u002F\u003A-\u003B\u003F-\u0040\u005C\u005C\u00A1\u00B7\u00BF\u037E\u0387\u055A-\u055F\u0589\u05C0\u05C3\u05C6\u05F3-\u05F4\u0609-\u060A\u060C-\u060D\u061B\u061E-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964-\u0965\u0970\u0DF4\u0E4F\u0E5A-\u0E5B\u0F04-\u0F12\u0F85\u0FD0-\u0FD4\u0FD9-\u0FDA\u104A-\u104F\u10FB\u1361-\u1368\u166D-\u166E\u16EB-\u16ED\u1735-\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u1805\u1807-\u180A\u1944-\u1945\u1A1E-\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E-\u1C7F\u1CD3\u2016-\u2017\u2020-\u2027\u2030-\u2038\u203B-\u203E\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205E\u2CF9-\u2CFC\u2CFE-\u2CFF\u2D70\u2E00-\u2E01\u2E06-\u2E08\u2E0B\u2E0E-\u2E16\u2E18-\u2E19\u2E1B\u2E1E-\u2E1F\u2E2A-\u2E2E\u2E30-\u2E31\u3001-\u3003\u303D\u30FB\uA4FE-\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE-\uA8CF\uA8F8-\uA8FA\uA92E-\uA92F\uA95F\uA9C1-\uA9CD\uA9DE-\uA9DF\uAA5C-\uAA5F\uAADE-\uAADF\uABEB\uFE10-\uFE16\uFE19\uFE30\uFE45-\uFE46\uFE49-\uFE4C\uFE50-\uFE52\uFE54-\uFE57\uFE5F-\uFE61\uFE68\uFE6A-\uFE6B\uFF01-\uFF03\uFF05-\uFF07\uFF0A\uFF0C\uFF0E-\uFF0F\uFF1A-\uFF1B\uFF1F-\uFF20\uFF3C\uFF61\uFF64-\uFF65";
private final static String mathSymbolRegexp = "\u002B\u003C-\u003E\u007C\u007E\u00AC\u00B1\u00D7\u00F7\u03F6\u0606-\u0608\u2044\u2052\u207A-\u207C\u208A-\u208C\u2118\u2140-\u2144\u214B\u2190-\u2194\u219A-\u219B\u21A0\u21A3\u21A6\u21AE\u21CE-\u21CF\u21D2\u21D4\u21F4-\u22FF\u2308-\u230B\u2320-\u2321\u237C\u239B-\u23B3\u23DC-\u23E1\u25B7\u25C1\u25F8-\u25FF\u266F\u27C0-\u27C4\u27C7-\u27CA\u27CC\u27CE-\u27E5\u27F0-\u27FF\u2900-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2AFF\u2B30-\u2B44\u2B47-\u2B4C\uFB29\uFE62\uFE64-\uFE66\uFF0B\uFF1C-\uFF1E\uFF5C\uFF5E\uFFE2\uFFE9-\uFFEC";
private final static String currencySymbolRegexp = "\u0024\u00A2-\u00A5\u060B\u09F2-\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20B9\uA838\uFDFC\uFE69\uFF04\uFFE0-\uFFE1\uFFE5-\uFFE6";
private final static String modifierSymbolRegexp = "\u005E\u0060\u00A8\u00AF\u00B4\u00B8\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384-\u0385\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD-\u1FFE\u309B-\u309C\uA700-\uA716\uA720-\uA721\uA789-\uA78A\uFBB2-\uFBC1\uFF3E\uFF40\uFFE3";
private final static String otherSymbolRegexp = "\u00A6-\u00A7\u00A9\u00AE\u00B0\u00B6\u0482\u060E-\u060F\u06DE\u06E9\u06FD-\u06FE\u07F6\u09FA\u0B70\u0BF3-\u0BF8\u0BFA\u0C7F\u0D79\u0F01-\u0F03\u0F13-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FCF\u0FD5-\u0FD8\u109E-\u109F\u1360\u1390-\u1399\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114\u2116-\u2117\u211E-\u2123\u2125\u2127\u2129\u212E\u213A-\u213B\u214A\u214C-\u214D\u214F\u2195-\u2199\u219C-\u219F\u21A1-\u21A2\u21A4-\u21A5\u21A7-\u21AD\u21AF-\u21CD\u21D0-\u21D1\u21D3\u21D5-\u21F3\u2300-\u2307\u230C-\u231F\u2322-\u2328\u232B-\u237B\u237D-\u239A\u23B4-\u23DB\u23E2-\u23F3\u2400-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u25B6\u25B8-\u25C0\u25C2-\u25F7\u2600-\u266E\u2670-\u26FF\u2701-\u2767\u2794-\u27BF\u2800-\u28FF\u2B00-\u2B2F\u2B45-\u2B46\u2B50-\u2B59\u2CE5-\u2CEA\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3004\u3012-\u3013\u3020\u3036-\u3037\u303E-\u303F\u3190-\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u32FE\u3300-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA828-\uA82B\uA836-\uA837\uA839\uAA77-\uAA79\uFDFD\uFFE4\uFFE8\uFFED-\uFFEE\uFFFC-\uFFFD";
private final static String spaceSeparatorRegexp = "\u0020\u00A0\u1680\u180E\u2000-\u200A\u202F\u205F\u3000";
private final static String lineSeparatorRegexp = "\u2028";
private final static String paragraphSeparatorRegexp = "\u2029";
private final static String otherControlRegexp = "\u0000-\u001F\u007F-\u009F";
private final static String otherFormatRegexp = "\u00AD\u0600-\u0603\u06DD\u070F\u17B4-\u17B5\u200B-\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF\uFFF9-\uFFFB";
private final static String otherPrivateRegexp = "\uE000-\uF8FF";
private final static String otherSurrogateRegexp = "\uD800-\uDFFF";
private final static String otherUnassignedRegexp = "\u0378\u0379\u037F-\u0383\u038B\u038D\u03A2\u0526-\u0530\u0557\u0558\u0560\u0588\u058B-\u0590\u05C8-\u05CF\u05EB-\u05EF\u05F5-\u05FF\u0604\u0605\u061C\u061D\u0620\u065F\u070E\u074B\u074C\u07B2-\u07BF\u07FB-\u07FF\u082E\u082F\u083F-\u08FF\u093A\u093B\u094F\u0956\u0957\u0973-\u0978\u0980\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09FC-\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0\u0AF2-\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B55\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BFB-\u0C00\u0C04\u0C0D\u0C11\u0C29\u0C34\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5A-\u0C5F\u0C64\u0C65\u0C70-\u0C77\u0C80\u0C81\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0D01\u0D04\u0D0D\u0D11\u0D29\u0D3A-\u0D3C\u0D45\u0D49\u0D4E-\u0D56\u0D58-\u0D5F\u0D64\u0D65\u0D76-\u0D78\u0D80\u0D81\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DF1\u0DF5-\u0E00\u0E3B-\u0E3E\u0E5C-\u0E80\u0E83\u0E85\u0E86\u0E89\u0E8B\u0E8C\u0E8E-\u0E93\u0E98\u0EA0\u0EA4\u0EA6\u0EA8\u0EA9\u0EAC\u0EBA\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EDE-\u0EFF\u0F48\u0F6D-\u0F70\u0F8C-\u0F8F\u0F98\u0FBD\u0FCD\u0FD9-\u0FFF\u10C6-\u10CF\u10FD-\u10FF\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B-\u135E\u137D-\u137F\u139A-\u139F\u13F5-\u13FF\u169D-\u169F\u16F1-\u16FF\u170D\u1715-\u171F\u1737-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17DE\u17DF\u17EA-\u17EF\u17FA-\u17FF\u180F\u181A-\u181F\u1878-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191D-\u191F\u192C-\u192F\u193C-\u193F\u1941-\u1943\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19DD\u1A1C\u1A1D\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1A9F\u1AAE-\u1AFF\u1B4C-\u1B4F\u1B7D-\u1B7F\u1BAB-\u1BAD\u1BBA-\u1BFF\u1C38-\u1C3A\u1C4A-\u1C4C\u1C80-\u1CCF\u1CF3-\u1CFF\u1DE7-\u1DFC\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FC5\u1FD4\u1FD5\u1FDC\u1FF0\u1FF1\u1FF5\u1FFF\u2065-\u2069\u2072\u2073\u208F\u2095-\u209F\u20B9-\u20CF\u20F1-\u20FF\u218A-\u218F\u23E9-\u23FF\u2427-\u243F\u244B-\u245F\u26CE\u26E2\u26E4-\u26E7\u2700\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u275F\u2760\u2795-\u2797\u27B0\u27BF\u27CB\u27CD-\u27CF\u2B4D-\u2B4F\u2B5A-\u2BFF\u2C2F\u2C5F\u2CF2-\u2CF8\u2D26-\u2D2F\u2D66-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E32-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u2FFF\u3040\u3097\u3098\u3100-\u3104\u312E-\u3130\u318F\u31B8-\u31BF\u31E4-\u31EF\u321F\u32FF\u4DB6-\u4DBF\u9FCC-\u9FFF\uA48D-\uA48F\uA4C7-\uA4CF\uA62C-\uA63F\uA660\uA661\uA674-\uA67B\uA698-\uA69F\uA6F8-\uA6FF\uA78D-\uA7FA\uA82C-\uA82F\uA83A-\uA83F\uA878-\uA87F\uA8C5-\uA8CD\uA8DA-\uA8DF\uA8FC-\uA8FF\uA954-\uA95E\uA97D-\uA97F\uA9CE\uA9DA-\uA9DD\uA9E0-\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A\uAA5B\uAA7C-\uAA7F\uAAC3-\uAADA\uAAE0-\uABBF\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uFA2E\uFA2F\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD40-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFE\uFDFF\uFE1A-\uFE1F\uFE27-\uFE2F\uFE53\uFE67\uFE6C-\uFE6F\uFE75\uFEFD\uFEFE\uFF00\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFDF\uFFE7\uFFEF-\uFFF8\uFFFE\uFFFF";
// All Categories Strings
private final static String anyLetterRegexp = join(lowercaseRegexp,
uppercaseRegexp,
titlecaseLetterRegexp,
modifierLetterRegexp,
letterWithoutCaseRegexp,
letterNumberRegexp);
private final static String anyMarkRegexp =
join(nonSpacingMarkRegexp, spacingCombiningMarkRegexp, enclosingMarkRegexp);
private final static String anyNumberRegexp =
join(decimalDigitRegexp, letterNumberRegexp, otherNumberRegexp);
private final static String anyPuncutationRegexp = join(dashPunctuationRegexp,
openPuncutationRegexp,
closePuncutationRegexp,
initialPunctuationRegexp,
finalPuncutationRegexp,
connectorPuncutationRegexp,
punctuationOtherRegexp);
private final static String anySymbolRegexp =
join(mathSymbolRegexp, currencySymbolRegexp, modifierSymbolRegexp, otherSymbolRegexp);
private final static String anySeparatorRegExp =
join(spaceSeparatorRegexp, lineSeparatorRegexp, paragraphSeparatorRegexp);
private final static String anyOtherRegexp =
join(otherControlRegexp, otherFormatRegexp, otherPrivateRegexp, otherSurrogateRegexp,
otherUnassignedRegexp);
// Custom Categories
private final static String unicodeWhitespaceRegexp = join(spaceSeparatorRegexp,
lineSeparatorRegexp,
paragraphSeparatorRegexp,
"\u0085",
"\u0009",
"\\u000A-\\u000D");
private final static String javascriptIdentifierRegexp = join(nonSpacingMarkRegexp,
spacingCombiningMarkRegexp,
decimalDigitRegexp,
connectorPuncutationRegexp,
anyLetterRegexp,
"$_");
private final static String nonAsciiCharacter = join("\u0100-\uFFFF");
// Custom Regular Expressions
/**
* Matches any character which is not a Unicode mark.
*/
public final static RegExp regexpNotMark = compile(CharacterClass.invert(anyMarkRegexp));
/**
* Matches any character which is not a Unicode mark or other character
* excluding the tab character.
*/
public final static RegExp regexpNotMarkOrOtherExcludingTabAndNewline =
compile(CharacterClass.invert(anyMarkRegexp, anyOtherRegexp), CharacterClass.create("\t\n"));
/**
* Matches any non-ascii character, tab, or carriage return character. Also
* matches any marks following the character in a separate capturing group.
*/
public final static RegExp regexpNonAsciiTabOrCarriageReturn =
compile(
CharacterClass.concat(CharacterClass.create(nonAsciiCharacter, "\r\t"),
CharacterClass.Builder
.create()
.setCapturing(true)
.setOccurences(CharacterClass.Builder.Occurences.ZERO_OR_MORE)
.build(anyMarkRegexp, "\r")));
/**
* The official definition of whitespace according to unicode 6.0. Includes
* all separator type characters, + NEL, tab, line feed and carriage return.
*/
public final static RegExp regexpNotWhitespace =
compile(CharacterClass.invert(unicodeWhitespaceRegexp));
/**
* Valid character for a javascript identifier.
*/
public final static RegExp regexpNotJavascriptIdentifierCharacter =
compile(CharacterClass.invert(javascriptIdentifierRegexp));
/**
* Not a valid javascript identifier character or whitespace.
*/
public final static RegExp regexpIdentifierOrWhitespace =
compile(CharacterClass.create(unicodeWhitespaceRegexp, javascriptIdentifierRegexp));
/**
* The official definition of whitespace according to unicode 6.0 excluding \r
* and \n control characters.
*/
public final static RegExp regexpNotWhitespaceExcludingNewlineAndCarriageReturn =
compile(CharacterClass.invert(unicodeWhitespaceRegexp), CharacterClass.create("\r\n"));
/**
* Returns true if a character is whitespace according to Unicode 6.0.
*/
public static boolean isWhitespace(char c) {
return !RegExpUtils.resetAndTest(regexpNotWhitespace, String.valueOf(c));
}
/**
* Returns true if a chracter is whitespace according to Unicode 6.0
* (excluding the characters \r and \n).
*/
public static boolean isWhitespaceNonline(char c) {
return !RegExpUtils.resetAndTest(
regexpNotWhitespaceExcludingNewlineAndCarriageReturn, String.valueOf(c));
}
/**
* Simple helper class for strongly typed character classes. Just helps to
* prevent typos and makes it more clear on the intent of the creator.
*/
private static class CharacterClass {
public static CharacterClass create(String... characterClass) {
return Builder.NORMAL_CLASS.build(characterClass);
}
public static CharacterClass invert(String... characterClass) {
return Builder.INVERTED_CLASS.build(characterClass);
}
public static CharacterClass concat(CharacterClass... characterClasses) {
String concatenatedClasses = Joiner.on("").join(characterClasses);
return new CharacterClass(concatenatedClasses);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | true |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/RegExpUtils.java | shared/src/main/java/com/google/collide/shared/util/RegExpUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
/**
*/
public class RegExpUtils {
private static final RegExp regexpEscape = RegExp.compile("[.*?$^+|()\\[\\]{}\\\\]", "g");
private static final RegExp regexpWildcardEscape = RegExp.compile("[.$^+|()\\[\\]{}\\\\]", "g");
/**
* Escapes all regexp special characters in a string .+?*|()[]{}\
*
* @param pattern
* @return regexp safe string
*/
public static String escape(String pattern) {
return regexpEscape.replace(pattern, "\\$&");
}
/**
* Creates a regexp which will only allow a wildcard type search and will
* escape other extraneous regexp characters. IE: hel?? w*ld
*
* All regex characters in the pattern will be escaped. \S is substituted for
* ? and \S+ is substituted for *. Wildcard's can be escaped using backslashes
* so that they are treated as literals; likewise, backslashes immediately
* preceding a wildcard can be escaped so as to match a literal backslash.
* Backslashes not preceding a wildcard should not be escaped.
*
* TODO: Consider changing the regex from just \S to a class that
* more suitable for programming such as [^\s()+\[\].] or similar
*/
public static RegExp createRegExpForWildcardPattern(String wildcardPattern, String flags) {
return RegExp.compile(createRegExpStringForWildcardPattern(wildcardPattern), flags);
}
/**
* Creates a regular expression which will match the given wildcard pattern
*
* Backslashes can be used to escape a wildcard character and make it a
* literal; likewise, backslashes before wildcard characters can be escaped.
*/
private static String createRegExpStringForWildcardPattern(String wildcardPattern) {
String escaped = regexpWildcardEscape.replace(wildcardPattern, "\\$&");
/**
* We have already run the pattern through the naive regex escape which
* escapes all characters except the * and ?. This leads to double escaped \
* characters that we have to inspect to determine if the user escaped the
* wildcard or if we should replace it with it's regex equivalent.
*
* NOTE: * is replaced with \S+ (matches all non-whitespace characters) and
* ? is replaced with a single \S to match any non-whitespace
*/
RegExp mimicLookbehind = RegExp.compile("([\\\\]*)([?*])", "g");
StringBuilder wildcardStr = new StringBuilder(escaped);
for (MatchResult match = mimicLookbehind.exec(wildcardStr.toString()); match != null;
match = mimicLookbehind.exec(wildcardStr.toString())) {
// in some browsers an optional group is null, in others its empty string
if (match.getGroup(1) != null && !match.getGroup(1).isEmpty()) {
// We undo double-escaping of backslashes performed by the naive escape
int offset = match.getGroup(1).length() / 2;
wildcardStr.delete(match.getIndex(), match.getIndex() + offset);
/*
* An even number of slashes means the wildcard was not escaped so we
* must replace it with its regex equivalent.
*/
if (offset % 2 == 0) {
if (match.getGroup(2).equals("?")) {
wildcardStr.replace(match.getIndex() + offset, match.getIndex() + offset + 1, "\\S");
// we added 1 more character, so we remove 1 less from the index
offset -= 1;
} else {
wildcardStr.replace(match.getIndex() + offset, match.getIndex() + offset + 1, "\\S+");
// we added 2 characters, so we need to remove 2 less from the index
offset -= 2;
}
}
mimicLookbehind.setLastIndex(mimicLookbehind.getLastIndex() - offset);
} else if (match.getGroup(2).equals("?")) {
wildcardStr.replace(match.getIndex(), match.getIndex() + 1, "\\S");
mimicLookbehind.setLastIndex(mimicLookbehind.getLastIndex() + 1);
} else {
wildcardStr.replace(match.getIndex(), match.getIndex() + 1, "\\S+");
mimicLookbehind.setLastIndex(mimicLookbehind.getLastIndex() + 2);
}
}
return wildcardStr.toString();
}
/**
* Returns the number of matches found in a string by a regexp. If the regexp
* is not a global regexp this will return a maximum of 1. This does not
* setLastIndex(0) automatically, you must do it manually.
*
* @returns number of matches
*/
public static int getNumberOfMatches(RegExp regexp, String input) {
if (regexp == null || input == null || input.isEmpty()) {
return 0;
}
// if we don't check here we will loop forever
if (!regexp.getGlobal()) {
return regexp.test(input) ? 1 : 0;
}
int matches = 0;
for (MatchResult result = regexp.exec(input);
result != null && result.getGroup(0).length() != 0; result = regexp.exec(input)) {
matches++;
}
return matches;
}
public static MatchResult findMatchBeforeIndex(
RegExp regexp, String text, int exclusiveEndIndex) {
regexp.setLastIndex(0);
// Find the last match without going over our startIndex
MatchResult lastMatch = null;
for (MatchResult result = regexp.exec(text);
result != null && result.getIndex() < exclusiveEndIndex; result = regexp.exec(text)) {
lastMatch = result;
}
return lastMatch;
}
/**
* Find the next match after exclusiveStartIndex.
*/
public static MatchResult findMatchAfterIndex(
RegExp regexp, String text, int exclusiveStartIndex) {
regexp.setLastIndex(exclusiveStartIndex + 1);
return regexp.exec(text);
}
/**
* Resets the RegExp lastIndex to 0 and returns the number of matches found in
* a string by a regexp. If the regexp is not a global regexp this will return
* a maximum of 1. This does not setLastIndex(0) automatically, you must do it
* manually.
*
* @returns number of matches
*/
public static int resetAndGetNumberOfMatches(RegExp regexp, String input) {
regexp.setLastIndex(0);
return getNumberOfMatches(regexp, input);
}
/**
* Resets the RegExp lastIndex to 0 before testing. This is only useful for
* global RegExps.
*/
public static boolean resetAndTest(RegExp regexp, String input) {
regexp.setLastIndex(0);
return regexp.test(input);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/ListenerRegistrar.java | shared/src/main/java/com/google/collide/shared/util/ListenerRegistrar.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.collide.json.shared.JsonArray;
/**
* A manager to register or unregister listeners.
*/
public interface ListenerRegistrar<T> {
/**
* A handle to allow removing the added listener.
*/
public interface Remover {
void remove();
}
/**
* An object which helps to simplify management of multiple handlers that need
* to be removed. This is the recommended approach to managing removers as it
* guards against null checks and prevents forgetting to remove listeners.
*/
public static class RemoverManager implements Remover {
private JsonArray<Remover> handlers;
/**
* Tracks a new handler so that it can be removed in bulk.
*/
public RemoverManager track(Remover remover) {
if (handlers == null) {
handlers = JsonCollections.createArray();
}
handlers.add(remover);
return this;
}
/**
* Removes all tracked handlers and clears the stored list of handlers.
*/
@Override
public void remove() {
if (handlers == null) {
return;
}
for (int i = 0; i < handlers.size(); i++) {
handlers.get(i).remove();
}
handlers.clear();
}
}
/**
* Registers a new listener.
*/
Remover add(T listener);
/**
* Removes a listener. It is strongly preferred you use the {@link Remover}
* returned by {@link #add(Object)} instead of calling this method directly.
*/
void remove(T listener);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/ScopeMatcher.java | shared/src/main/java/com/google/collide/shared/util/ScopeMatcher.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
/**
* Searches lines of text to find the matching scopeEnd character. It will keep
* a stack of additional scopeStart characters it comes across to find the right
* scopeEnd. Examples of this are for finding matching { }, [ ] and ( ) pairs.
*/
public class ScopeMatcher {
private final boolean searchingForward;
private final char scopeEndChar;
private final char scopeStartChar;
private int stack = 0;
private int nextMatchColumn;
public ScopeMatcher(boolean searchingForward, char start, char end) {
this.searchingForward = searchingForward;
scopeStartChar = start;
scopeEndChar = end;
}
/**
* Search the next line for {@link #scopeEndChar}, keeping the {@link #stack}
* in mind.
*
* @param text
* @return columnIndex, or -1 if no match on this line.
*/
public int searchNextLine(String text) {
nextMatchColumn = searchingForward ? 0 : text.length() - 1;
while (true) {
if (isStartColumnNext(text)) {
stack++;
} else if (nextMatchColumn >= 0) {
stack--;
}
if (stack == 0 && nextMatchColumn >= 0) {
return nextMatchColumn;
} else if (nextMatchColumn == -1) {
break;
}
proceedForward();
}
return -1;
}
/**
* Move to the next occurrence of either {@link #scopeStartChar} or
* {@link #scopeEndChar} and update {@link #nextMatchColumn}.
*/
private boolean isStartColumnNext(String text) {
int startCharColumn;
if (searchingForward) {
startCharColumn = text.indexOf(scopeStartChar, nextMatchColumn);
nextMatchColumn = text.indexOf(scopeEndChar, nextMatchColumn);
if ((startCharColumn < nextMatchColumn || nextMatchColumn == -1) && startCharColumn != -1) {
nextMatchColumn = startCharColumn;
return true;
}
} else {
if (nextMatchColumn == -1) {
/*
* TODO: Firefox/Chrome bug where lastIndexOf with a
* negative offset parameter will return a match for the first
* character. http://code.google.com/p/google-web-toolkit/issues/detail?id=6615
*/
return false;
}
startCharColumn = text.lastIndexOf(scopeStartChar, nextMatchColumn);
nextMatchColumn = text.lastIndexOf(scopeEndChar, nextMatchColumn);
if ((startCharColumn > nextMatchColumn || nextMatchColumn == -1) && startCharColumn != -1) {
nextMatchColumn = startCharColumn;
return true;
}
}
return false;
}
private void proceedForward() {
if (searchingForward) {
nextMatchColumn++;
} else {
nextMatchColumn--;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/ListenerManager.java | shared/src/main/java/com/google/collide/shared/util/ListenerManager.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.collide.json.shared.JsonArray;
/**
* Lightweight manager for listeners that's designed to reduce boilerplate in
* classes that have listeners.
*
* The client stores a final member for this class, and exposes a {@code
* getListenerRegistrar()} with return type {@link ListenerRegistrar}. To
* dispatch, the client calls {@link #dispatch(Dispatcher)} with a custom
* dispatcher. (If the dispatches are frequent, consider keeping a single
* dispatcher instance whose state you set prior to passing it to the dispatch
* method.)
*
* @param <L> the type of the listener
*
*/
public class ListenerManager<L> implements ListenerRegistrar<L> {
/**
* Dispatches to a listener.
*
* @param <L> the type of the listener
*/
public interface Dispatcher<L> {
void dispatch(L listener);
}
/**
* Listener that is notified when clients are added or removed from this
* manager.
*/
public interface RegistrationListener<L> {
void onListenerAdded(L listener);
void onListenerRemoved(L listener);
}
public static <L> ListenerManager<L> create() {
return new ListenerManager<L>(null);
}
public static <L> ListenerManager<L> create(RegistrationListener<L> registrationListener) {
return new ListenerManager<L>(registrationListener);
}
private boolean isDispatching;
private final JsonArray<L> listeners;
/** Listeners that were added during a dispatch */
private final JsonArray<L> queuedListenerAdditions;
/** Listeners that were removed during a dispatch */
private final JsonArray<L> queuedListenerRemovals;
private final RegistrationListener<L> registrationListener;
private ListenerManager(RegistrationListener<L> registrationListener) {
this.listeners = JsonCollections.createArray();
this.queuedListenerAdditions = JsonCollections.createArray();
this.queuedListenerRemovals = JsonCollections.createArray();
this.registrationListener = registrationListener;
}
/**
* Adds a new listener to this event.
*/
@Override
public Remover add(final L listener) {
if (!isDispatching) {
addListenerImpl(listener);
} else {
if (!queuedListenerRemovals.remove(listener)) {
queuedListenerAdditions.add(listener);
}
}
return new Remover() {
@Override
public void remove() {
ListenerManager.this.remove(listener);
}
};
}
/**
* Dispatches this event to all listeners.
*/
public void dispatch(final Dispatcher<L> dispatcher) {
isDispatching = true;
try {
for (int i = 0, n = listeners.size(); i < n; i++) {
dispatcher.dispatch(listeners.get(i));
}
} finally {
isDispatching = false;
addQueuedListeners();
removeQueuedListeners();
}
}
/**
* Removes a listener from this manager.
*
* It is strongly preferred that you use the {@link ListenerRegistrar.Remover}
* returned by {@link #add(Object)} instead of calling this method directly.
*/
@Override
public void remove(L listener) {
if (!isDispatching) {
removeListenerImpl(listener);
} else {
if (!queuedListenerAdditions.remove(listener)) {
queuedListenerRemovals.add(listener);
}
}
}
/**
* Returns the number of listeners registered on this manager. This does not
* include those listeners that are queued to be added and it does include
* those listeners that are queued to be removed.
*/
public int getCount() {
return listeners.size();
}
/**
* Returns true if the listener manager is currently dispatching to listeners.
*/
public boolean isDispatching() {
return isDispatching;
}
private void addQueuedListeners() {
for (int i = 0, n = queuedListenerAdditions.size(); i < n; i++) {
addListenerImpl(queuedListenerAdditions.get(i));
}
queuedListenerAdditions.clear();
}
private void removeQueuedListeners() {
for (int i = 0, n = queuedListenerRemovals.size(); i < n; i++) {
removeListenerImpl(queuedListenerRemovals.get(i));
}
queuedListenerRemovals.clear();
}
private void addListenerImpl(final L listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
if (registrationListener != null) {
registrationListener.onListenerAdded(listener);
}
}
}
private void removeListenerImpl(final L listener) {
if (listeners.remove(listener) && registrationListener != null) {
registrationListener.onListenerRemoved(listener);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/PathUtils.java | shared/src/main/java/com/google/collide/shared/util/PathUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.common.base.Preconditions;
/**
* Utilities for working with workspace paths.
*/
public class PathUtils {
/**
* The root path of workspaces.
*/
public static final String WORKSPACE_ROOT = "/";
/**
* A visitor used to visit a path.
*/
public static interface PathVisitor {
/**
* Visits a path.
*
* @param path the path string
* @param name the name of the directory or file at this path
*/
public abstract void visit(String path, String name);
}
/**
* Normalizes a path by removing trailing slash, unless the path is the root path.
*
* @param path the path to the directory or file
*/
public static String normalizePath(String path) {
if (WORKSPACE_ROOT.equals(path)) {
return path;
}
if (path.isEmpty()) {
return WORKSPACE_ROOT;
}
int maybeSlash = path.length() - 1;
return path.charAt(maybeSlash) == '/' ? path.substring(0, maybeSlash) : path;
}
/**
* Walks every directory a path from the rootPath to the target path.
*
* @param path the path to walk
* @param rootPath the root to start walking, inclusive
* @param visitor the visitor that will be visited along the way
*/
public static void walk(String path, String rootPath, PathVisitor visitor) {
// Ensure that the path ends with a separator.
if (!path.endsWith("/")) {
path += "/";
}
rootPath = normalizePath(rootPath);
Preconditions.checkArgument(path.startsWith(rootPath),
"path \"" + path + "\" must be a descendent of rootPath \"" + rootPath + "\"");
int nextSlash = rootPath.length();
while (nextSlash != -1) {
String curPath = path.substring(0, nextSlash);
String name = "";
if (nextSlash > 0) {
int prevSlash = path.lastIndexOf("/", nextSlash - 1);
name = curPath.substring(prevSlash + 1);
}
// Visit the path.
visitor.visit(curPath, name);
// Iterate to the next child directory.
nextSlash = path.indexOf("/", nextSlash + 1);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/WorkspaceUtils.java | shared/src/main/java/com/google/collide/shared/util/WorkspaceUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import java.util.Comparator;
import com.google.collide.dto.WorkspaceInfo;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
/**
* Utilities for managing workspaces.
*/
public class WorkspaceUtils {
/**
* A node in a hierarchical tree of workspaces.
*/
public static class WorkspaceNode {
private final WorkspaceInfo workspace;
private final JsonArray<WorkspaceNode> children;
public WorkspaceNode(WorkspaceInfo workspace) {
this.workspace = workspace;
this.children = JsonCollections.createArray();
}
public void addChild(WorkspaceNode child) {
children.add(child);
}
public WorkspaceNode getChild(int index) {
return children.get(index);
}
public int getChildCount() {
return children.size();
}
/**
* Sort the direct children of this node.
*/
public void sortChildren(Comparator<? super WorkspaceNode> comparator) {
sortChildren(comparator, false);
}
/**
* Sort the children of this node and optionally sort the entire branch
* recursively.
*/
public void sortChildren(Comparator<? super WorkspaceNode> comparator, boolean recursive) {
// Sort the direct children.
children.sort(comparator);
// Recursively sort the branch children.
if (recursive) {
for (int i = 0; i < getChildCount(); i++) {
getChild(i).sortChildren(comparator, true);
}
}
}
public WorkspaceInfo getWorkspace() {
return workspace;
}
}
/**
* Take a flat list of workspaces and organize them into a hierarchy (or set
* or hierarchies) based on workspace parent IDs. The children within each
* node are not sorted. This method is O(n).
*
* @param workspaces the list of workspaces to organize
* @return a array of root workspace nodes
*/
public static JsonArray<WorkspaceNode> getWorkspaceHierarchy(
JsonArray<WorkspaceInfo> workspaces) {
/*
* Assume all workspaces are root nodes. Create a map of workspace IDs to
* their associated tree nodes.
*/
final JsonStringMap<WorkspaceNode> idToNode = JsonCollections.createMap();
final JsonArray<WorkspaceNode> rootNodes = JsonCollections.createArray();
for (int i = 0; i < workspaces.size(); i++) {
WorkspaceInfo value = workspaces.get(i);
WorkspaceNode node = new WorkspaceNode(value);
rootNodes.add(node);
idToNode.put(value.getId(), node);
}
/*
* Iterate over the list of workspaces and add each workspace as a child of
* its parent.
*/
int count = rootNodes.size();
for (int i = 0; i < count; i++) {
WorkspaceNode node = rootNodes.get(i);
WorkspaceInfo workspace = node.getWorkspace();
WorkspaceNode parentNode = idToNode.get(workspace.getParentId());
if (parentNode != null) {
parentNode.addChild(node);
// This node has a parent, so it is not a root node.
rootNodes.remove(i);
i--;
count--;
}
}
return rootNodes;
}
/**
* Take a flat list of workspaces and organize them into a hierarchy (or set
* or hierarchies) based on workspace parent IDs, then sort children within
* each node using the specified comparator.
*
* @param workspaces the list of workspaces to organize
* @return a array of root workspace nodes
*/
public static JsonArray<WorkspaceNode> getWorkspaceHierarchy(
JsonArray<WorkspaceInfo> workspaces, final Comparator<WorkspaceInfo> comparator) {
JsonArray<WorkspaceNode> rootNodes = getWorkspaceHierarchy(workspaces);
// Wrap the WorkspaceInfo comparator in a WorkspaceNode comparator.
Comparator<WorkspaceNode> nodeComparator = new Comparator<WorkspaceUtils.WorkspaceNode>() {
@Override
public int compare(WorkspaceNode o1, WorkspaceNode o2) {
return comparator.compare(o1.getWorkspace(), o2.getWorkspace());
}
};
// Sort each root node.
for (int i = 0; i < rootNodes.size(); i++) {
rootNodes.get(i).sortChildren(nodeComparator, true);
}
// Sort the list of root nodes.
rootNodes.sort(nodeComparator);
return rootNodes;
}
/**
* Returns the name of the trunk workspace given the name of the project.
*/
public static String createTrunkWorkspaceName(String projectName) {
return projectName + " source";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/JsonCollections.java | shared/src/main/java/com/google/collide/shared/util/JsonCollections.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.annotation.Nullable;
import com.google.collide.json.server.JsonArrayListAdapter;
import com.google.collide.json.server.JsonIntegerMapAdapter;
import com.google.collide.json.server.JsonStringMapAdapter;
import com.google.collide.json.server.JsonStringSetAdapter;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringSet;
import com.google.common.base.Equivalence;
import com.google.common.base.Objects;
import com.google.gwt.core.shared.GWT;
/**
* A set of static factory methods for lightweight collections.
*
*/
public final class JsonCollections {
public interface Implementation {
<T> JsonArray<T> createArray();
<T> JsonStringMap<T> createMap();
<T> JsonIntegerMap<T> createIntegerMap();
JsonStringSet createStringSet();
}
private static class PureJavaImplementation implements Implementation {
@Override
public <T> JsonArray<T> createArray() {
return new JsonArrayListAdapter<T>(new ArrayList<T>());
}
@Override
public <T> JsonStringMap<T> createMap() {
return new JsonStringMapAdapter<T>(new HashMap<String, T>());
}
@Override
public JsonStringSet createStringSet() {
return new JsonStringSetAdapter(new HashSet<String>());
}
@Override
public <T> JsonIntegerMap<T> createIntegerMap() {
return new JsonIntegerMapAdapter<T>(new HashMap<Integer, T>());
}
}
// If running in pure java (server code or tests) or in dev mode, use the pure java impl
private static Implementation implementation = !GWT.isClient() || !GWT.isScript() ?
new PureJavaImplementation() : null;
public static void setImplementation(Implementation implementation) {
JsonCollections.implementation = implementation;
}
public static <T> JsonArray<T> createArray() {
return implementation.createArray();
}
public static <T> JsonStringMap<T> createMap() {
return implementation.createMap();
}
public static <T> JsonIntegerMap<T> createIntegerMap() {
return implementation.createIntegerMap();
}
public static <T> JsonArray<T> createArray(T... items) {
JsonArray<T> array = createArray();
for (int i = 0, n = items.length; i < n; i++) {
array.add(items[i]);
}
return array;
}
public static <T> JsonArray<T> createArray(Iterable<T> items) {
JsonArray<T> array = createArray();
for (Iterator<T> it = items.iterator(); it.hasNext(); ) {
array.add(it.next());
}
return array;
}
public static JsonStringSet createStringSet() {
return implementation.createStringSet();
}
public static JsonStringSet createStringSet(String... items) {
JsonStringSet set = createStringSet();
for (int i = 0, n = items.length; i < n; i++) {
set.add(items[i]);
}
return set;
}
public static JsonStringSet createStringSet(Iterator<String> iterator) {
JsonStringSet set = createStringSet();
while (iterator.hasNext()) {
set.add(iterator.next());
}
return set;
}
// TODO: Is it used?
public static <T> void addAllMissing(JsonArray<T> self, JsonArray<T> b) {
if (b == null || self == b) {
return;
}
JsonArray<T> addList = createArray();
for (int i = 0, n = b.size(); i < n; i++) {
T addCandidate = b.get(i);
if (!self.contains(addCandidate)) {
addList.add(addCandidate);
}
}
self.addAll(addList);
}
/**
* Check if two lists are equal. The lists are equal if they are both the same
* size, and the items at every index are equal. Returns true if both lists
* are null.
*
* @param <T> the data type of the arrays
*/
public static <T> boolean equals(JsonArray<T> a, JsonArray<T> b) {
return equals(a, b, null);
}
/**
* Check if two lists are equal. The lists are equal if they are both the same
* size, and the items at every index are equal according to the provided
* equator. Returns true if both lists are null.
*
* @param equivalence if null the {@link Object#equals(Object)} is used to
* determine item equality.
*
* @param <T> the data type of the arrays
*/
public static <T> boolean equals(
JsonArray<T> a, JsonArray<T> b, @Nullable Equivalence<T> equivalence) {
if (a == b) {
// Same list or both null.
return true;
} else if (a == null || b == null) {
// One list is null, the other is not.
return false;
} else if (a.size() != b.size()) {
// Different sizes.
return false;
} else {
// Check the elements in the array.
for (int i = 0; i < a.size(); i++) {
T itemA = a.get(i);
T itemB = b.get(i);
// if the equator is null we just the equals method and some null checking
if (equivalence == null && !Objects.equal(itemA, itemB)) {
return false;
} else if (equivalence != null && !equivalence.equivalent(itemA, itemB)) {
return false;
}
}
return true;
}
}
/**
* Check if two maps are equal. The maps are equal if they have exactly the
* same set of keys value pairs.
*
* @param <T> the data type of the arrays
*/
public static <T> boolean equals(final JsonStringMap<T> a, final JsonStringMap<T> b) {
return equals(a, b, null);
}
/**
* Check if two maps are equal. The maps are equal if they have exactly the
* same set of keys value pairs. Checks the values using a custom
* {@link Equivalence} check.
*
* @param equivalence if null {@link Objects#equal(Object, Object)} is used to
* verify equivalence.
*
* @param <T> the data type of the arrays
*/
public static <T> boolean equals(
final JsonStringMap<T> a, final JsonStringMap<T> b, @Nullable Equivalence<T> equivalence) {
if (a == b) {
// Same map or both null.
return true;
} else if (a == null || b == null) {
// One map is null, the other is not.
return false;
} else {
JsonArray<String> keys = a.getKeys();
if (!equals(keys, b.getKeys())) {
return false;
}
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
T valueA = a.get(key);
T valueB = b.get(key);
boolean isNotEquivalent = (equivalence == null && !Objects.equal(valueA, valueB))
|| (equivalence != null && !equivalence.equivalent(valueA, valueB));
if (isNotEquivalent) {
return false;
}
}
return true;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/RoleUtils.java | shared/src/main/java/com/google/collide/shared/util/RoleUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.collide.dto.ProjectInfo;
import com.google.collide.dto.Role;
import com.google.collide.dto.WorkspaceInfo;
/**
* Utility methods for {@link Role} related functionality.
*/
public class RoleUtils {
/**
* A tool that authenticates a user.
*/
public static interface Authenticator {
/**
* Check if the user role satisfies the minimum required authorization.
*
* @param userRole the user role
* @return true if authorized, false if not authorized or userRole is null
*/
boolean isAuthorized(Role userRole);
}
/**
* A tool that authenticates a user for a project.
*/
public static interface ProjectAuthenticator extends Authenticator {
/**
* Check if the user role satisfies the minimum required authorization for
* the specified project.
*
* @param project the project to authorize
* @return true if authorized, false if not authorized or project is null
*/
boolean isAuthorized(ProjectInfo project);
}
/**
* A tool that authenticates a user for a workspace.
*/
public static interface WorkspaceAuthenticator extends Authenticator {
/**
* Check if the user role satisfies the minimum required authorization.
*
* @param workspace the workspace to authorize
* @return true if authorized, false if not authorized or workspace is null
*/
boolean isAuthorized(WorkspaceInfo workspace);
}
/**
* An authenticator that compares the user's role against an array of implied
* roles.
*/
private static class AuthenticatorImpl implements ProjectAuthenticator, WorkspaceAuthenticator {
private final Role[] impliedRoles;
private AuthenticatorImpl(Role... impliedRoles) {
this.impliedRoles = impliedRoles;
}
@Override
public boolean isAuthorized(Role userRole) {
for (Role aRole : impliedRoles) {
if (aRole.equals(userRole)) {
return true;
}
}
return false;
}
@Override
public boolean isAuthorized(ProjectInfo project) {
return (project == null) ? false : isAuthorized(project.getCurrentUserRole());
}
@Override
public boolean isAuthorized(WorkspaceInfo workspace) {
return (workspace == null) ? false : isAuthorized(workspace.getCurrentUserRole());
}
}
public static WorkspaceAuthenticator WORKSPACE_OWNER_AUTHENTICATOR = new AuthenticatorImpl(
Role.OWNER);
public static WorkspaceAuthenticator WORKSPACE_CONTRIBUTOR_AUTHENTICATOR = new AuthenticatorImpl(
Role.OWNER, Role.CONTRIBUTOR);
public static WorkspaceAuthenticator WORKSPACE_READER_AUTHENTICATOR = new AuthenticatorImpl(
Role.OWNER, Role.CONTRIBUTOR, Role.READER);
public static ProjectAuthenticator PROJECT_OWNER_AUTHENTICATOR =
new AuthenticatorImpl(Role.OWNER);
public static ProjectAuthenticator PROJECT_CONTRIBUTOR_AUTHENTICATOR = new AuthenticatorImpl(
Role.OWNER, Role.CONTRIBUTOR);
public static ProjectAuthenticator PROJECT_READER_AUTHENTICATOR = new AuthenticatorImpl(
Role.OWNER, Role.CONTRIBUTOR, Role.READER);
/**
* Checks if a workspace is read only for the current user.
*
* @param userRole the current users workspace role, or null if unknown
* @param forceReadOnly true to force read only
* @return true if user has read only permissions, or if forceReadOnly is true
*/
public static boolean isWorkspaceReadOnly(Role userRole, boolean forceReadOnly) {
boolean isReadOnlyForUser = forceReadOnly;
if (!isReadOnlyForUser) {
isReadOnlyForUser = !WORKSPACE_CONTRIBUTOR_AUTHENTICATOR.isAuthorized(userRole);
}
return isReadOnlyForUser;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/SortedList.java | shared/src/main/java/com/google/collide/shared/util/SortedList.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.collide.json.shared.JsonArray;
import com.google.common.base.Preconditions;
/**
* List that is sorted based on the given {@link Comparator}.
*
* Insertions and removal of an instance are O(N).
*
*/
public class SortedList<T> {
/**
* Compares two items and returns a value following the same contract as
* {@link Comparable#compareTo(Object)}.
*
* @param <T> the type of the items being compared
*/
public interface Comparator<T> {
int compare(T a, T b);
}
/**
* Compares some (opaque) value to other items' values. This can be used to
* efficiently find an item based on a value.
*
* @param <T> the type of items being compared
*/
public interface OneWayComparator<T> {
int compareTo(T o);
}
/**
* Simple {@link SortedList.OneWayComparator} that has an int-based value.
*/
public abstract static class OneWayIntComparator<T> implements OneWayComparator<T> {
protected int value;
public void setValue(int value) {
this.value = value;
}
}
/**
* Simple {@link SortedList.OneWayComparator} that has a double-based value.
*/
public static abstract class OneWayDoubleComparator<T> implements SortedList.OneWayComparator<T> {
protected double value;
public void setValue(double value) {
this.value = value;
}
}
private final class ComparatorDelegator implements OneWayComparator<T> {
T a;
@Override
public int compareTo(T o) {
return comparator.compare(a, o);
}
}
private static final boolean ENSURE_SORTED_PRECONDITIONS_ENABLED = false;
private final JsonArray<T> array;
private final Comparator<T> comparator;
private final ComparatorDelegator comparatorDelegator = new ComparatorDelegator();
public SortedList(Comparator<T> comparator) {
this.array = JsonCollections.createArray();
this.comparator = comparator;
}
/**
* Adds an item to the list. Performance is O(lg N).
*
* @param item item to add
* @return index at which item was added into the list
*/
public int add(T item) {
int index = findInsertionIndex(item);
array.splice(index, 0, item);
ensureSortedIfEnabled();
return index;
}
/**
* Clears the list.
*/
public void clear() {
array.clear();
}
/**
* Returns the first item in the list matched by the comparator, or null if
* there were no matches.
*/
public T find(OneWayComparator<T> comparator) {
int index = findInsertionIndex(comparator);
if (index < size()) {
T item = get(index);
if (comparator.compareTo(item) == 0) {
return item;
}
}
return null;
}
/**
* Returns the index where the item with the value would be inserted. The
* actual value is unknown to this method; it delegates comparison to the
* given {@code comparator}.
*
* If an item with the same value already exists in the list, the returned
* index will be the first appearance of the value in the list. If the value
* does not exist in the list, the returned index will be the first value
* greater than the value being compared, or the size of the list if there is
* no greater value.
*
* An alternate approach to the OneWayComparator used here is to have the
* SortedList take another type parameter for the type of the value, and have
* a findInsertionIndex(V value) method. Unfortunately, it is common to have
* primitives for the value, so we would be boxing unnecessarily.
*
* @see #findInsertionIndex(OneWayComparator, boolean)
*/
public int findInsertionIndex(OneWayComparator<T> comparator) {
/*
* Return the greater value, since that will be the insertion index.
* Remember that if we get here, lower > upper (look at the while loop
* above).
*/
return findInsertionIndex(comparator, true);
}
/**
* Returns the index where the item with the value would be inserted. The
* actual value is unknown to this method; it delegates comparison to the
* given {@code comparator}.
*
* If an item with the same value already exists in the list, the returned
* index will be the first appearance of the value in the list. If the value
* does not exist in the list, see {@code greaterItemIfNoMatch}.
*
* @param greaterItemIfNoMatch in the case that the given comparator's value
* does not match an item in the list exactly, this parameter defines
* which of the items to return. If true, the item that is greater than
* the comparator's value will be returned. If false, the item that is
* less than the comparator's value will be returned.
*/
public int findInsertionIndex(OneWayComparator<T> comparator, boolean greaterItemIfNoMatch) {
int insertionPoint = binarySearch(array, comparator);
if (insertionPoint >= 0) {
return insertionPoint;
}
insertionPoint = -insertionPoint - 1;
return greaterItemIfNoMatch ? insertionPoint : insertionPoint - 1;
}
/**
* @see #findInsertionIndex(OneWayComparator)
*/
public int findInsertionIndex(final T item) {
comparatorDelegator.a = item;
return findInsertionIndex(comparatorDelegator);
}
/**
* Finds index of a given item in the list, or {@code -1}, if not found.
*
* @param item the item to search for
* @return index of item in the list, or {@code -1} if not found
*/
public int findIndex(T item) {
for (int i = findInsertionIndex(item); i < array.size()
&& comparator.compare(item, array.get(i)) == 0; i++) {
if (array.get(i).equals(item)) {
return i;
}
}
return -1;
}
/**
* Returns the item at the given {@code index}.
*/
public T get(int index) {
return array.get(index);
}
/**
* Removes the item at the given {@code index}.
*/
public T remove(int index) {
T item = array.remove(index);
ensureSortedIfEnabled();
return item;
}
/**
* Removes the items starting at {@code index} through to the end.
*/
public JsonArray<T> removeThisAndFollowing(int index) {
JsonArray<T> items = removeSublist(index, array.size() - index);
ensureSortedIfEnabled();
return items;
}
/**
* Removes the items starting at {@code index} through to the end.
*/
public JsonArray<T> removeSublist(int index, int sublistSize) {
JsonArray<T> sublist = array.splice(index, sublistSize);
ensureSortedIfEnabled();
return sublist;
}
/**
* Removes the given {@code item}. Performance is O(lg N).
*/
public boolean remove(T item) {
int index = findIndex(item);
if (index >= 0) {
array.remove(index);
ensureSortedIfEnabled();
return true;
}
return false;
}
/**
* @return the size of this list
*/
public int size() {
return array.size();
}
/**
* @return copy of this list as an array
*/
public JsonArray<T> toArray() {
return array.copy();
}
/**
* Ensures that the item that is currently at index {@code index} is
* positioned properly in the list.
*
* If an item was changed and its position could now be stale, you should call
* this method.
*/
public void repositionItem(int index) {
// TODO: naive impl
T item = remove(index);
ensureSortedIfEnabled();
add(item);
ensureSortedIfEnabled();
}
public static <T> int binarySearch(JsonArray<T> array, OneWayComparator<T> comparator) {
int lower = 0;
int upper = array.size() - 1;
while (lower <= upper) {
int middle = lower + (upper - lower) / 2;
int c = comparator.compareTo(array.get(middle));
if (c < 0) {
upper = middle - 1;
} else if (c > 0) {
lower = middle + 1;
} else {
/*
* We have an exact match at middle, but there may be more exact matches
* before us, so we want to find the first exact match.
*/
// Move backward to the first non-equal value
int i = middle;
while (i >= 0 && comparator.compareTo(array.get(i)) == 0) {
i--;
}
// Forward one to the first equal value
return i + 1;
}
}
return -lower - 1;
}
public final void ensureSortedIfEnabled() {
if (ENSURE_SORTED_PRECONDITIONS_ENABLED) {
for (int i = 1; i < array.size(); i++) {
Preconditions.checkState(comparator.compare(array.get(i - 1), array.get(i)) <= 0);
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/util/Reorderer.java | shared/src/main/java/com/google/collide/shared/util/Reorderer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.util;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.collide.shared.util.Timer.Factory;
/**
* A utility class that accepts out-of-order versioned items and delivers them to an
* {@link ItemSink} in-order.
*/
public class Reorderer<T> {
public interface ItemSink<T> {
void onItem(T item, int version);
}
public interface TimeoutCallback {
void onTimeout(int lastVersionDispatched);
}
/**
* @param firstVersionToExpect the first version to expect
* @param timeoutMs the amount of time to wait before triggering the {@code timeoutCallback} for
* dropped items
*/
public static <T> Reorderer<T> create(int firstVersionToExpect, ItemSink<T> itemSink,
int timeoutMs, TimeoutCallback timeoutCallback, Factory timerFactory) {
return new Reorderer<T>(
firstVersionToExpect, itemSink, timeoutMs, timeoutCallback, timerFactory);
}
private boolean isQueueingUntilSkipToVersionCalled;
private int nextExpectedVersion;
private final ItemSink<T> itemSink;
private JsonIntegerMap<T> itemsByVersion = JsonCollections.createIntegerMap();
private boolean isTimeoutEnabled = true;
private final int timeoutMs;
private final TimeoutCallback timeoutCallback;
private final Timer timeoutTimer;
private final Runnable timeoutTimerRunnable = new Runnable() {
@Override
public void run() {
timeoutCallback.onTimeout(nextExpectedVersion - 1);
}
};
private Reorderer(int firstVersionToExpect, ItemSink<T> itemSink, int timeoutMs,
TimeoutCallback timeoutCallback, Timer.Factory timerFactory) {
this.itemSink = itemSink;
this.timeoutMs = timeoutMs;
this.timeoutCallback = timeoutCallback;
this.nextExpectedVersion = firstVersionToExpect;
timeoutTimer = timerFactory.createTimer(timeoutTimerRunnable);
}
public void cleanup() {
setTimeoutEnabled(false);
}
public int getNextExpectedVersion() {
return nextExpectedVersion;
}
/**
* Enables the timeout feature.
*
* <p>
* If there are out-of-order items queued, this will immediately start the timeout timer.
*/
public void setTimeoutEnabled(boolean isTimeoutEnabled) {
this.isTimeoutEnabled = isTimeoutEnabled;
if (isTimeoutEnabled) {
scheduleTimeoutIfEnabledAndNecessary();
} else {
cancelTimeout();
}
}
/**
* Allows the client to skip ahead to a version. For example, if a client fills in the gap
* out-of-band, this should be called afterward to begin reordering at the latest version.
*/
public void skipToVersion(int nextVersionToExpect) {
this.nextExpectedVersion = nextVersionToExpect;
isQueueingUntilSkipToVersionCalled = false;
// Cancel any pending timer (we'll re-set one later if necessary)
cancelTimeout();
// Remove items for old versions that we no longer care about
removeOldVersions(nextExpectedVersion - 1);
// See if we have any items at the new and following versions
dispatchQueuedStartingAtNextExpectedVersion();
scheduleTimeoutIfEnabledAndNecessary();
}
/*
* This is purposefully not a setXxx since canceling the queueing requires dispatching queued
* version, etc. and that's not a code path we're going to use immediately, so punting.
*/
public void queueUntilSkipToVersionIsCalled() {
isQueueingUntilSkipToVersionCalled = true;
}
private void removeOldVersions(final int maxVersionToRemove) {
// Simulate a set from a map
final JsonIntegerMap<Void> oldVersionsToRemove = JsonCollections.createIntegerMap();
itemsByVersion.iterate(new JsonIntegerMap.IterationCallback<T>() {
@Override
public void onIteration(int version, T val) {
if (version <= maxVersionToRemove) {
// Can't remove in-place, so queue for removal
oldVersionsToRemove.put(version, null);
}
}
});
oldVersionsToRemove.iterate(new JsonIntegerMap.IterationCallback<Void>() {
@Override
public void onIteration(int version, Void val) {
itemsByVersion.erase(version);
}
});
}
public void acceptItem(T item, int version) {
if (version < nextExpectedVersion) {
// Ignore, we've already passed this version onto our client
return;
}
final boolean hadPreviouslyStoredItems = !itemsByVersion.isEmpty();
itemsByVersion.put(version, item);
if (isQueueingUntilSkipToVersionCalled) {
// The item is stored, exit
return;
}
if (version == nextExpectedVersion) {
cancelTimeout();
dispatchQueuedStartingAtNextExpectedVersion();
/*
* E.g. previous to this call, nextExpectedVersion=3, we have queued 4, 5, 7. We move to
* nextExpectedVersion=6 and are now waiting on it to come in, so schedule a timeout.
*/
scheduleTimeoutIfEnabledAndNecessary();
} else {
if (!hadPreviouslyStoredItems) {
/*
* This is the first time we've missed the item at nextExpectedVersion. We wouldn't always
* want to do this when we receive a future item because that would keep resetting the
* timeout for the nextExpectedVersion item.
*
* For example, imagine we are waiting for v2 (assume it got dropped indefinitely). When we
* get v3, itemsByVersion will be empty, so we schedule a timeout. If/when we get v4, v5,
* v6, ..., we don't want to keep resetting the timeout for each item that comes in -- we'd
* never actually timeout in a busy session!
*/
scheduleTimeoutIfEnabled();
}
}
}
/**
* Dispatches to the {@link ItemSink}. This should be the ONLY place that dispatches given the
* subtle pause behavior that is possible.
*/
private void dispatchQueuedStartingAtNextExpectedVersion() {
for (; itemsByVersion.hasKey(nextExpectedVersion); nextExpectedVersion++) {
T item = itemsByVersion.get(nextExpectedVersion);
itemsByVersion.erase(nextExpectedVersion);
itemSink.onItem(item, nextExpectedVersion);
}
}
private void scheduleTimeoutIfEnabledAndNecessary() {
if (!itemsByVersion.isEmpty()) {
scheduleTimeoutIfEnabled();
}
}
private void scheduleTimeoutIfEnabled() {
if (isTimeoutEnabled) {
timeoutTimer.schedule(timeoutMs);
}
}
private void cancelTimeout() {
timeoutTimer.cancel();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/plugin/PublicService.java | shared/src/main/java/com/google/collide/shared/plugin/PublicService.java | package com.google.collide.shared.plugin;
import javax.inject.Provider;
public interface PublicService <S> extends Provider<S>{
Class<? super S> classKey();
int priority();
public static class DefaultServiceProvider <S> implements PublicService<S> {
private S service;
private Class<? super S> key;
public DefaultServiceProvider(Class<? super S> key, S service) {
this.service = service;
this.key = key;
}
@Override
public S get() {
return service;
}
@Override
public Class<? super S> classKey(){
return key;
}
@Override
public int priority() {
return Integer.MIN_VALUE;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/plugin/PublicServices.java | shared/src/main/java/com/google/collide/shared/plugin/PublicServices.java | package com.google.collide.shared.plugin;
import com.google.common.base.Preconditions;
import xapi.collect.X_Collect;
import xapi.collect.api.IntTo;
import xapi.fu.Out1;
import xapi.inject.X_Inject;
import javax.inject.Provider;
public class PublicServices {
private final IntTo<PublicService<?>> services;
private static final Out1<PublicServices> SINGLETON = X_Inject.singletonLazy(PublicServices.class);
//don't construct these, we're running statically
protected PublicServices() {
services = X_Collect.newList(PublicService.class);
}
@SuppressWarnings("unchecked")
public static <S> S getService(Class<? super S> serviceClass) {
PublicService<?> service = SINGLETON.out1().services.get(serviceClass.hashCode());
Preconditions.checkNotNull(service, "No service implementation registered for "+serviceClass);
return (S)service.get();
}
public static <S> PublicService<S> createProvider(
Class<? super S> serviceClass, S singleton) {
return new PublicService.DefaultServiceProvider<>(serviceClass, singleton);
}
public static <S> void registerService(
Class<? super S> serviceClass, PublicService<S> provider) {
IntTo<PublicService<?>> serviceMap = SINGLETON.out1().services;
PublicService<?> old = serviceMap.get(serviceClass.hashCode());
if (old != null) {
if (old.priority() > provider.priority())
return;
}
serviceMap.set(serviceClass.hashCode(), provider);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/metrics/CollideAction.java | shared/src/main/java/com/google/collide/shared/metrics/CollideAction.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.metrics;
/**
* The specific implementation of a Action. These are the specific Actions that can be performed in
* Collide.
*
*/
public enum CollideAction implements Action {
JOIN_COLLABORATIVE_SESSION,
POST_FEEDBACK,
CREATE_PROJECT,
DELETE_PROJECT,
OPEN_PROJECT,
CREATE_WORKSPACE,
OPEN_WORKSPACE,
DELETE_WORKSPACE,
CREATE_FILE,
OPEN_FILE,
DELETE_FILE,
SYNC_WORKSPACE,
RESOLVE_CONFLICT,
SEARCH,
SELECT_AUTOCOMPLETE_PROPOSAL,
TREE_CONFLICT,
FILE_CONFLICT,
FORK_WORKSPACE,
VISIT_LANDING_PAGE,
LOAD_TEMPLATE,
UPLOAD_FINISHED
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/metrics/Action.java | shared/src/main/java/com/google/collide/shared/metrics/Action.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.metrics;
/**
* An Action is something that is explicitly performed by the user. This is
* usually application specific. For example, when a user creates a domain
* object such as a "project", the corresponding action may be "CREATE_PROJECT".
*
* This is the base interface, which all Action interfaces and enums should
* implement.
*
* Currently, this interface is empty, but is used for type safety in the
* Metrics instrumentation class.
*
*
*/
public interface Action {
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/invalidations/InvalidationUtils.java | shared/src/main/java/com/google/collide/shared/invalidations/InvalidationUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.invalidations;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
/**
* Utilities to simplify working with invalidations.
*/
public class InvalidationUtils {
/** A set to prevent duplicated prefixes */
public static InvalidationObjectPrefix getInvalidationObjectPrefix(String objectName) {
for (int i = 1; i <= longestPrefixString; i++) {
String curPrefixString = objectName.substring(0, i);
if (PREFIX_BY_STRING.containsKey(curPrefixString)) {
return PREFIX_BY_STRING.get(curPrefixString);
}
}
throw new IllegalArgumentException("The given object name [" + objectName
+ "] does not match a prefix object from [" + PREFIX_BY_STRING.getKeys().join(", ") + "]");
}
/**
* A value identifying that the version of the object is unknown.
*/
public static final long UNKNOWN_VERSION = Long.MIN_VALUE;
/** The version returned when an object doesn't exist in the store */
public static final long INITIAL_OBJECT_VERSION = 1L;
/** Map of the prefix string to the */
private static final JsonStringMap<InvalidationObjectPrefix> PREFIX_BY_STRING =
JsonCollections.createMap();
private static int longestPrefixString;
/**
* A prefix to prepend to an id which defines a {@link InvalidationObjectId}. Prefixes must be
* unique so this class ensures that no duplicates are used.
*/
public enum InvalidationObjectPrefix {
/**
* This is a mutation to the file tree. ADD, DELETE, COPY(PASTE), and MOVE.
*/
FILE_TREE_MUTATION("fm"),
/**
* Notifies that the number of participants has changed.
*/
PARTICIPANTS_UPDATE("p"),
/**
* Invalidation of a path, or the entire workspace file tree and conflict listing.
*/
FILE_TREE_INVALIDATED("fr"),
/**
* Notifies that an upload session has ended.
*/
// TODO: Not sure if we still need this one?
END_UPLOAD_SESSION_FINISHED("uf");
private final String prefix;
private InvalidationObjectPrefix(String prefix) {
Preconditions.checkArgument(
isPrefixValid(prefix), "Prefix [" + prefix + "] conflicts with another Tango object");
this.prefix = prefix;
InvalidationUtils.longestPrefixString = Math.max(
InvalidationUtils.longestPrefixString, prefix.length());
InvalidationUtils.PREFIX_BY_STRING.put(prefix, this);
}
public String getPrefix() {
return prefix;
}
/** Helper function to ensure a previous is not currently used */
private static boolean isPrefixValid(final String prefix) {
for (String existingPrefix : InvalidationUtils.PREFIX_BY_STRING.getKeys().asIterable()) {
if (prefix.startsWith(existingPrefix) || existingPrefix.startsWith(prefix)) {
return false;
}
}
return true;
}
}
static {
// This ensures that the PREFIX_BY_STRING map is filled in when this class is loaded by the JVM
if (InvalidationObjectPrefix.FILE_TREE_MUTATION != null) {
InvalidationObjectPrefix.FILE_TREE_MUTATION.getPrefix();
}
}
private InvalidationUtils() {
// util class
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/invalidations/InvalidationObjectIdFactory.java | shared/src/main/java/com/google/collide/shared/invalidations/InvalidationObjectIdFactory.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.invalidations;
import com.google.collide.dto.EndUploadSessionFinished;
import com.google.collide.dto.WorkspaceTreeUpdate;
import com.google.collide.shared.invalidations.InvalidationObjectId.VersioningRequirement;
import com.google.collide.shared.invalidations.InvalidationUtils.InvalidationObjectPrefix;
/**
* A factory which can create a new {@link InvalidationObjectId}.
*
*/
public class InvalidationObjectIdFactory {
/** Creates an InvalidationObjectIdFactory ignoring the workspace id */
public static InvalidationObjectIdFactory create() {
return new InvalidationObjectIdFactory("IGNORED");
}
private final String workspaceId;
public InvalidationObjectIdFactory(String workspaceId) {
this.workspaceId = workspaceId;
}
public InvalidationObjectId<WorkspaceTreeUpdate> makeWorkspaceFileTreeId() {
return new InvalidationObjectId<WorkspaceTreeUpdate>(
InvalidationObjectPrefix.FILE_TREE_MUTATION, workspaceId, VersioningRequirement.PAYLOADS);
}
public InvalidationObjectId<String> makeFileTreeInvalidatedId() {
return new InvalidationObjectId<String>(InvalidationObjectPrefix.FILE_TREE_INVALIDATED,
workspaceId, VersioningRequirement.VERSION_ONLY);
}
public InvalidationObjectId<EndUploadSessionFinished> makeEndUploadSessionFinished(
String sessionId) {
return new InvalidationObjectId<EndUploadSessionFinished>(
InvalidationObjectPrefix.END_UPLOAD_SESSION_FINISHED, sessionId,
VersioningRequirement.PAYLOADS);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/invalidations/InvalidationObjectId.java | shared/src/main/java/com/google/collide/shared/invalidations/InvalidationObjectId.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.invalidations;
import com.google.collide.shared.invalidations.InvalidationUtils.InvalidationObjectPrefix;
/**
* An object which defines a tango object which can receive notifications or have notifications
* published.
*
* @param <T> The type of the payload for this object {@link Void} if no payload is required.
*/
public final class InvalidationObjectId<T> {
/**
* An enum which defines the version number and persistence requirements for a
* {@link InvalidationObjectId}. Currently these aren't really used but may be used in future
* implementations.
*/
public enum VersioningRequirement {
/**
* No version or payload data will be persisted and {@link System#currentTimeMillis()} will be
* used to assign version numbers.
* <p>
* Recommended for objects which are sending notifications to the client which do not require
* the ability to determine a notification was missed. These clients typically do not have
* payloads or have payloads which carry extra information and can be lost or dropped.
*/
NONE,
/**
* No payload data will be persisted; however, versions will be sequential.
* <p>
* Recommended for objects which require the ability to determine that a notification was missed
* but do not require the ability to retrieve any missed payloads.
*/
VERSION_ONLY,
/**
* Versions will be sequential and payloads will be persisted for each invalidation.
* <p>
* Recommended for objects which require the ability to determine that a notification was missed
* and the ability to retrieve any missed payloads.
*/
PAYLOADS
}
private final InvalidationObjectPrefix prefix;
private final String id;
private final String name;
private final VersioningRequirement versioningRequirement;
/**
* A string which indicates that there was no payload, this is only used when a
* {@link InvalidationObjectId} has uses {@link InvalidationUtils.VersioningRequirement#PAYLOADS}.
*/
public static final String EMPTY_PAYLOAD = "\0\3";
public InvalidationObjectId(
InvalidationObjectPrefix prefix, String id, VersioningRequirement versioningRequirement) {
this.prefix = prefix;
// TODO: if the id is a number pack it into an integer
this.id = id;
this.versioningRequirement = versioningRequirement;
this.name = prefix.getPrefix() + id;
}
/**
* @return the name of this object for use in registration.
*/
public String getName() {
return name;
}
public InvalidationObjectPrefix getPrefix() {
return prefix;
}
/**
* @return the id portion of this object, typically a workspaceId or projectId.
*/
public String getId() {
return id;
}
public VersioningRequirement getVersioningRequirement() {
return versioningRequirement;
}
/**
* Useful for logging so the full name is logged, use #getName for registering.
*/
@Override
public String toString() {
return prefix.toString() + "(" + name + ")";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/LineNumberAndColumn.java | shared/src/main/java/com/google/collide/shared/document/LineNumberAndColumn.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* A simple structure to store the line number and column.
*
*/
public final class LineNumberAndColumn implements Comparable<LineNumberAndColumn> {
public final int column;
public final int lineNumber;
public static LineNumberAndColumn from(int lineNumber, int column) {
return new LineNumberAndColumn(lineNumber, column);
}
@VisibleForTesting
public LineNumberAndColumn(int lineNumber, int column) {
this.lineNumber = lineNumber;
this.column = column;
}
@Override
public String toString() {
return "(" + lineNumber + ", " + column + ")";
}
@Override
public int compareTo(LineNumberAndColumn o) {
Preconditions.checkNotNull(o);
int result = this.lineNumber - o.lineNumber;
return result == 0 ? this.column - o.column : result;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/LineFinder.java | shared/src/main/java/com/google/collide/shared/document/LineFinder.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.util.LineUtils;
/*
* Implementation notes:
*
* - This class needs to efficiently resolve line numbers or lines. To do this,
* it relies heavily on anchors with line numbers in the document. Basically, it
* finds the closest anchor with line number, and then iterates to the line of
* interest. Most document edits will originate on a line with an anchor
* (local/collaborator cursors use anchors), so the common case is fast.
*/
/**
* Helper to efficiently resolve a line number given the line, or vice versa.
*/
public class LineFinder {
private final Document document;
LineFinder(Document document) {
this.document = document;
}
/**
* Finds the closest {@link LineInfo} for the given line number (must be
* within the document range). Use {@link #findLine(LineInfo, int)} if you
* know of a good starting point for the search.
*/
public LineInfo findLine(int targetLineNumber) {
if (targetLineNumber >= document.getLineCount()) {
throw new IndexOutOfBoundsException("Asking for " + targetLineNumber
+ " but document length is " + document.getLineCount());
}
int distanceFromFirstLine = targetLineNumber;
int distanceFromLastLine = document.getLineCount() - targetLineNumber - 1;
int distanceFromClosestLineAnchor;
Anchor closestLineAnchor =
document.getAnchorManager().findClosestAnchorWithLineNumber(targetLineNumber);
if (closestLineAnchor != null) {
distanceFromClosestLineAnchor =
Math.abs(closestLineAnchor.getLineInfo().number() - targetLineNumber);
} else {
distanceFromClosestLineAnchor = Integer.MAX_VALUE;
}
LineInfo lineInfo;
if (distanceFromClosestLineAnchor < distanceFromFirstLine
&& distanceFromClosestLineAnchor < distanceFromLastLine) {
lineInfo = closestLineAnchor.getLineInfo();
} else if (distanceFromFirstLine < distanceFromLastLine) {
lineInfo = new LineInfo(document.getFirstLine(), 0);
} else {
lineInfo = new LineInfo(document.getLastLine(), document.getLineCount() - 1);
}
return findLine(lineInfo, targetLineNumber);
}
public LineInfo findLine(Line line) {
Line forwardIteratingLine = line;
int forwardLineCount = 0;
Line backwardIteratingLine = line.getPreviousLine();
int backwardLineCount = 1;
while (forwardIteratingLine != null && backwardIteratingLine != null) {
LineInfo cachedLineInfo = LineUtils.getCachedLineInfo(forwardIteratingLine);
if (cachedLineInfo != null) {
return new LineInfo(line, cachedLineInfo.number() - forwardLineCount);
}
cachedLineInfo = LineUtils.getCachedLineInfo(backwardIteratingLine);
if (cachedLineInfo != null) {
return new LineInfo(line, cachedLineInfo.number() + backwardLineCount);
}
backwardIteratingLine = backwardIteratingLine.getPreviousLine();
backwardLineCount++;
forwardIteratingLine = forwardIteratingLine.getNextLine();
forwardLineCount++;
}
if (forwardIteratingLine == null) {
return new LineInfo(line, line.getDocument().getLineCount() - forwardLineCount);
} else {
return new LineInfo(line, backwardLineCount - 1);
}
}
/*
* TODO: really, this should be merged with the other findLine
* which would then just consider {@code begin} as another known line number
* to begin the search (along with top, bottom, and closest anchor).
*/
/**
* Finds the closest {@link LineInfo} for the given line number. This iterates
* from the given {@code begin}. Use {@link #findLine(int)} if you DO NOT know
* of a good starting point for the search.
*/
public LineInfo findLine(LineInfo begin, int targetLineNumber) {
if (targetLineNumber >= document.getLineCount()) {
throw new IndexOutOfBoundsException("Asking for " + targetLineNumber
+ " but document length is " + document.getLineCount());
}
if (begin == null) {
return findLine(targetLineNumber);
}
Line line = begin.line();
int number = begin.number();
// TODO: see if there's a closer anchor
if (number < targetLineNumber) {
while (line.getNextLine() != null && number < targetLineNumber) {
line = line.getNextLine();
number++;
}
} else if (number > targetLineNumber) {
while (line.getPreviousLine() != null && number > targetLineNumber) {
line = line.getPreviousLine();
number--;
}
}
return new LineInfo(line, number);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/Line.java | shared/src/main/java/com/google/collide/shared/document/Line.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.util.JsonCollections;
/*
* TODO: prevent leaks by forcing a clear on the tags when a line
* is detached.
*/
/**
* Model for a line of text (including the newline character) in a document.
*
* Lines by design do not know their line numbers since that would require a
* line insertion/deletion to iterate through all of the following lines to
* update the line numbers, thus making insertion/deletion slower operations
* than they have to be. The {@link LineFinder} can help to efficiently resolve
* a line number given the line, or vice versa.
*
* Lines can have tags attached to them by clients of this class.
*/
public class Line implements TaggableLine {
static Line create(Document document, String text) {
return new Line(document, text);
}
private boolean attached;
private final Document document;
private Line nextLine;
private Line previousLine;
// Not final so we can do O(1) clearTags
private JsonStringMap<Object> tags;
private String text;
private Line(Document document, String text) {
this.document = document;
this.text = text;
tags = JsonCollections.createMap();
}
public Document getDocument() {
return document;
}
public Line getNextLine() {
return nextLine;
}
@Override
public Line getPreviousLine() {
return previousLine;
}
/**
* Gets a tag set on this line with {@link #putTag}. This serves as storage
* for arbitrary objects for this line. For example, a document parser may
* store its snapshot here.
*
* It is the client's responsibility to ensure type safety, this method
* blindly casts as a convenience.
*
* @param key the unique identifier for this tag. In order to prevent
* namespace collisions, prefix this with the caller's fully qualified
* class name
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getTag(String key) {
return (T) tags.get(key);
}
@SuppressWarnings("unchecked")
public <T> T removeTag(String key) {
return (T) tags.remove(key);
}
public String getText() {
return text;
}
public boolean hasColumn(int column) {
return column >= 0 && column < text.length();
}
public boolean isAttached() {
return attached;
}
public int length() {
return text.length();
}
/**
* Puts a tag on this line.
*
* @see Line#getTag(String)
*/
@Override
public <T> void putTag(String key, T value) {
tags.put(key, value);
}
/**
* This is not public API and will eventually be hidden in the public
* interface
*/
public void clearTags() {
tags = JsonCollections.createMap();
}
@Override
public String toString() {
String trimmedText = text.trim();
return (trimmedText.length() > 50 ? trimmedText.substring(0, 50) + "..." : trimmedText);
}
@Override
public boolean isFirstLine() {
return getPreviousLine() == null;
}
@Override
public boolean isLastLine() {
return getNextLine() == null;
}
void setAttached(boolean attached) {
this.attached = attached;
}
void setNextLine(Line nextLine) {
this.nextLine = nextLine;
}
void setPreviousLine(Line previousLine) {
this.previousLine = previousLine;
}
void setText(String text) {
this.text = text;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/DocumentMutatorImpl.java | shared/src/main/java/com/google/collide/shared/document/DocumentMutatorImpl.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.TextChange.Type;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.document.util.LineUtils;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Preconditions;
/**
* Mutator for the document that provides high-level document mutation API. The
* {@link Document} delegates to this class to actually perform the mutations.
*/
class DocumentMutatorImpl implements DocumentMutator {
private class TextDeleter {
private final JsonArray<Anchor> anchorsInDeletedRangeToRemove = JsonCollections.createArray();
private final JsonArray<Anchor> anchorsInDeletedRangeToShift = JsonCollections.createArray();
private final JsonArray<Anchor> anchorsLeftoverFromLastLine = JsonCollections.createArray();
private int column;
private int deleteCountForCurLine;
private final int firstLineColumn;
private final Line firstLine;
private final int firstLineNumber;
private final String firstLineChunk;
private Line curLine;
private int curLineNumber;
private int remainingDeleteCount;
private TextDeleter(Line line, int lineNumber, int column, String deletedText) {
firstLine = this.curLine = line;
firstLineNumber = this.curLineNumber = lineNumber;
firstLineColumn = this.column = column;
this.remainingDeleteCount = deletedText.length();
firstLineChunk = line.getText().substring(0, column);
}
void delete() {
JsonArray<Line> removedLines = JsonCollections.createArray();
boolean wasNewlineCharDeleted = deleteFromCurLine(true);
// All deletes on subsequent lines will start at column 0
if (remainingDeleteCount > 0) {
column = 0;
do {
iterateToNextLine();
wasNewlineCharDeleted = deleteFromCurLine(false);
removedLines.add(curLine);
} while (remainingDeleteCount > 0);
}
if (wasNewlineCharDeleted) {
/*
* Must join the next line with the current line. Setting
* deleteCountForLine = 0 will have a nice effect of naturally joining
* the line.
*/
iterateToNextLine();
column = 0;
deleteCountForCurLine = 0;
removeLineImpl(curLine);
removedLines.add(curLine);
}
// Move any leftover text on the last line to the first line
boolean lastLineIsEmpty = curLine.getText().length() == 0;
boolean lastLineWillHaveLeftoverText =
deleteCountForCurLine < curLine.getText().length();
int lastLineFirstUntouchedColumn = column + deleteCountForCurLine;
if (lastLineWillHaveLeftoverText || lastLineIsEmpty) {
anchorManager.handleTextDeletionLastLineLeftover(anchorsLeftoverFromLastLine, firstLine,
curLine, lastLineFirstUntouchedColumn);
}
String lastLineChunk = curLine.getText().substring(lastLineFirstUntouchedColumn);
firstLine.setText(firstLineChunk + lastLineChunk);
int numberOfDeletedLines = curLineNumber - firstLineNumber;
anchorManager.handleTextDeletionFinished(anchorsInDeletedRangeToRemove,
anchorsInDeletedRangeToShift, anchorsLeftoverFromLastLine, firstLine, firstLineNumber,
firstLineColumn, numberOfDeletedLines, lastLineFirstUntouchedColumn);
if (numberOfDeletedLines > 0) {
document.commitLineCountChange(-numberOfDeletedLines);
document.dispatchLineRemoved(firstLineNumber + 1, removedLines);
}
}
/**
* Deletes the current line's text to be deleted.
*
* @return whether a newline character was deleted
*/
private boolean deleteFromCurLine(boolean isFirstLine) {
int maxDeleteCountForCurLine = curLine.getText().length() - column;
deleteCountForCurLine = Math.min(maxDeleteCountForCurLine, remainingDeleteCount);
anchorManager.handleTextPredeletionForLine(curLine, column, deleteCountForCurLine,
anchorsInDeletedRangeToRemove, anchorsInDeletedRangeToShift, isFirstLine);
/*
* All lines but the first should be removed from the document (either
* they have no text remaining, or in the case of a partial selection on
* the last line, the leftover text will be moved to the first line.)
*/
if (!isFirstLine) {
removeLineImpl(curLine);
}
remainingDeleteCount -= deleteCountForCurLine;
int lastCharDeletedIndex = column + deleteCountForCurLine - 1;
return lastCharDeletedIndex >= 0 ? curLine.getText().charAt(lastCharDeletedIndex) == '\n'
: false;
}
private void iterateToNextLine() {
curLine = curLine.getNextLine();
curLineNumber++;
ensureCurLine();
}
private void ensureCurLine() {
if (curLine == null) {
throw new IndexOutOfBoundsException(
"Reached end of document so could not delete the requested remaining "
+ remainingDeleteCount + " characters");
}
}
}
private AnchorManager anchorManager;
private final Document document;
private final JsonArray<TextChange> textChanges;
DocumentMutatorImpl(Document document) {
this.document = document;
this.anchorManager = document.getAnchorManager();
textChanges = JsonCollections.createArray();
}
@Override
public TextChange deleteText(Line line, int column, int deleteCount) {
return deleteText(line, document.getLineFinder().findLine(line).number(), column, deleteCount);
}
@Override
public TextChange deleteText(Line line, int lineNumber, int column, int deleteCount) {
if (deleteCount == 0) {
// Delete 0 is a NOOP.
return TextChange.createDeletion(line, lineNumber, column, "");
}
if (column >= line.getText().length()) {
throw new IndexOutOfBoundsException("Attempt to delete text at column " + column
+ " which is greater than line length " + line.getText().length() + "(line text is: "
+ line.getText() + ")");
}
String deletedText = document.getText(line, column, deleteCount);
beginHighLevelModification(TextChange.Type.DELETE, line, lineNumber, column, deletedText);
TextChange textChange = TextChange.createDeletion(line, lineNumber, column, deletedText);
textChanges.add(textChange);
deleteTextImpl(line, lineNumber, column, deletedText);
endHighLevelModification();
return textChange;
}
@Override
public TextChange insertText(Line line, int column, String text) {
return insertText(line, document.getLineFinder().findLine(line).number(), column, text);
}
@Override
public TextChange insertText(Line line, int lineNumber, int column, String text) {
if (column > LineUtils.getLastCursorColumn(line)) {
throw new IndexOutOfBoundsException("Attempt to insert text at column " + column
+ " which is greater than line length " + line.getText().length() + "(line text is: "
+ line.getText() + ")");
}
beginHighLevelModification(TextChange.Type.INSERT, line, lineNumber, column, text);
LineInfo lastLineModified = insertTextImpl(line, lineNumber, column, text);
TextChange textChange =
TextChange.createInsertion(line, lineNumber, column, lastLineModified.line(),
lastLineModified.number(), text);
textChanges.add(textChange);
endHighLevelModification();
return textChange;
}
@Override
public TextChange insertText(Line line, int lineNumber, int column, String text,
boolean canReplaceSelection) {
// This (lowest-level) document mutator should never replace the selection
return insertText(line, lineNumber, column, text);
}
private void beginHighLevelModification(
Type type, Line line, int lineNumber, int column, String text) {
// Clear any change-tracking state
textChanges.clear();
// Dispatch the pre-textchange event
document.dispatchPreTextChange(type, line, lineNumber, column, text);
}
private void endHighLevelModification() {
// Dispatch callbacks
document.dispatchTextChange(textChanges);
}
private LineInfo insertTextImpl(Line line, int lineNumber, int column, String text) {
if (!text.contains("\n")) {
insertTextOnOneLineImpl(line, column, text);
return new LineInfo(line, lineNumber);
} else {
return insertMultilineTextImpl(line, lineNumber, column, text);
}
}
private void insertTextOnOneLineImpl(Line line, int column, String text) {
// Add the text first
String oldText = line.getText();
String newText = oldText.substring(0, column) + text + oldText.substring(column);
line.setText(newText);
// Update the anchors
anchorManager.handleSingleLineTextInsertion(line, column, text.length());
}
/**
* @return the line info for the last line modified by this insertion
*/
private LineInfo insertMultilineTextImpl(Line line, int lineNumber, int column, String text) {
String lineText = line.getText();
Preconditions.checkArgument(lineText.endsWith("\n") ? column < lineText.length()
: column <= lineText.length(), "Given column is out-of-bounds");
JsonArray<Line> linesAdded = JsonCollections.createArray();
/*
* The given "line" has two chunks of text: from column 0 to the "column"
* (exclusive), and from the "column" to the end. The new contents of this
* line will be: its first chunk + the first line of the inserted text +
* newline. The second chunk will be used to form a brand new line whose
* contents are: the last line of the inserted text + the second chunk
* (which still consists of a newline if it had one originally). In between
* these two lines will be the inserted text's second line through to the
* second-to-last line.
*/
// First, split the line receiving the text
String firstChunk = lineText.substring(0, column);
String secondChunk = lineText.substring(column);
JsonArray<String> insertionLineTexts = StringUtils.split(text, "\n");
line.setText(firstChunk + insertionLineTexts.get(0) + "\n");
Line prevLine = line;
int prevLineNumber = lineNumber;
for (int i = 1, nMinusOne = insertionLineTexts.size() - 1; i < nMinusOne; i++) {
Line curLine = Line.create(document, insertionLineTexts.get(i) + "\n");
insertLineImpl(prevLine, curLine);
linesAdded.add(curLine);
prevLine = curLine;
prevLineNumber++;
}
/*
* Remember that if e.g. the insertion text is "a\n", the last item in the
* array will be the empty string
*/
String lastInsertionLineText = insertionLineTexts.get(insertionLineTexts.size() - 1);
String newLineText = lastInsertionLineText + secondChunk;
int secondChunkColumnInNewLine = lastInsertionLineText.length();
Line newLine = Line.create(document, newLineText);
insertLineImpl(prevLine, newLine);
linesAdded.add(newLine);
int newLineNumber = prevLineNumber + 1;
anchorManager.handleMultilineTextInsertion(line, lineNumber, column, newLine, newLineNumber,
secondChunkColumnInNewLine);
document.commitLineCountChange(linesAdded.size());
document.dispatchLineAdded(lineNumber + 1, linesAdded);
return new LineInfo(newLine, newLineNumber);
}
/**
* Low-level operation that inserts the given line after the previous line.
*
* @param previousLine the line after which {@code line} will be inserted
*/
private void insertLineImpl(Line previousLine, Line line) {
Line nextLine = previousLine.getNextLine();
// Update the linked list
previousLine.setNextLine(line);
line.setPreviousLine(previousLine);
if (nextLine != null) {
nextLine.setPreviousLine(line);
line.setNextLine(nextLine);
}
// Update document state
if (nextLine == document.getFirstLine()) {
document.setFirstLine(line);
}
if (previousLine == document.getLastLine()) {
document.setLastLine(line);
}
line.setAttached(true);
}
private void deleteTextImpl(final Line firstLine, final int firstLineNumber,
final int firstLineColumn, final String deletedText) {
Preconditions.checkArgument(firstLineColumn <= LineUtils.getLastCursorColumn(firstLine),
"The column is out-of-bounds");
new TextDeleter(firstLine, firstLineNumber, firstLineColumn, deletedText).delete();
}
/**
* A low-level operation that removes the line from the document. This method
* is meant to only be called by
* {@link #deleteTextImpl(Line, int, int, String)}.
*/
private void removeLineImpl(Line line) {
/*
* TODO: set detached state, and assert/throw exceptions if any
* one tries to operate on the detached line
*/
// Update the linked list and document's first and last lines
Line previousLine = line.getPreviousLine();
Line nextLine = line.getNextLine();
if (previousLine != null) {
previousLine.setNextLine(nextLine);
} else {
assert line == document.getFirstLine() :
"Line does not have a previous line, but line is not first line in document";
document.setFirstLine(nextLine);
}
if (nextLine != null) {
nextLine.setPreviousLine(previousLine);
} else {
assert line == document.getLastLine() :
"Line does not have a next line, but line is not last line in document";
document.setLastLine(previousLine);
}
line.setAttached(false);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/Position.java | shared/src/main/java/com/google/collide/shared/document/Position.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
/**
* A class to encapsulate a position in the document given in terms of a line
* and column.
*
* This should only be used by methods that return the pair. Methods that need
* to take a line and column as input should take them as separate parameters to
* reduce code complexity and object allocations.
*
* This class is immutable.
*
*/
public class Position {
private final LineInfo lineInfo;
private final int column;
public Position(LineInfo lineInfo, int column) {
// Defensively copy to ensure immutabilty
this.lineInfo = lineInfo.copy();
this.column = column;
}
public int getColumn() {
return column;
}
public Line getLine() {
return lineInfo.line();
}
/**
* Returns the line info object, if set by the creator.
*/
public LineInfo getLineInfo() {
// Defensively copy to ensure immutabilty
return lineInfo.copy();
}
public int getLineNumber() {
return lineInfo.number();
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + lineInfo.hashCode();
result = 37 * result + column;
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Position)) {
return false;
}
Position o = (Position) obj;
return lineInfo.equals(o.lineInfo) && column == o.column;
}
@Override
public String toString() {
return "Position(" + lineInfo + ", " + column + ")";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/DocumentMutator.java | shared/src/main/java/com/google/collide/shared/document/DocumentMutator.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
import javax.annotation.Nullable;
/**
* An interface that allows mutation of a document.
*/
public interface DocumentMutator {
/**
* Deletes the text from the given start point ({@code line} and
* {@code column}) with the given length ({@code deleteCount}). If the deleted
* text spans multiple lines, the {@link Line Lines} where the deletion
* started and ended may be joined and the deleted lines will be detached from
* the document.
*
* @param line the line containing the begin position for the delete
* @param column the column (inclusive) where the delete will begin
* @param deleteCount the number of characters (including newlines) to delete
* @return the change that led to the deletion of the text, or {@code null}
* if no changes applied
*/
@Nullable
TextChange deleteText(Line line, int column, int deleteCount);
/**
* Similar to {@link DocumentMutator#deleteText(Line, int, int)} but accepts a
* line number for more efficient deletion.
*
* @return {@code null} if no changes applied
*/
@Nullable
TextChange deleteText(Line line, int lineNumber, int column, int deleteCount);
/**
* Similar to
* {@link DocumentMutator#insertText(Line, int, int, String, boolean)} but
* uses the default behavior.
*
* @return {@code null} if no changes applied
*/
@Nullable
TextChange insertText(Line line, int column, String text);
/**
* Similar to {@link DocumentMutator#insertText(Line, int, String)} but
* accepts a line number for more efficient insertion.
*
* @return {@code null} if no changes applied
*/
@Nullable
TextChange insertText(Line line, int lineNumber, int column, String text);
/**
* Inserts the text starting at the given {@code line} and {@code column}. If
* the text spans multiple lines, multiple {@link Line Lines} will be created.
*
* @param canReplaceSelection whether the mutator is allowed to replace the
* selection (if it exists) with the given text. Passing true does not
* guarantee the mutator will choose to replace the selection; passing
* false guarantees the mutator will never replace the selection
* @return the change that led to the insertion of text; if the selection was
* replaced, this will only be the insertion text change, not the
* deletion text change; if selection was deleted, but nothing was
* inserted, then deletion text change is returned;
* {@code null} if no changes applied
*/
@Nullable
TextChange insertText(Line line, int lineNumber, int column, String text,
boolean canReplaceSelection);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/TextChange.java | shared/src/main/java/com/google/collide/shared/document/TextChange.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
/**
* Models a text change on the document.
*
*/
public class TextChange {
public enum Type {
INSERT, DELETE
}
public static TextChange createDeletion(Line line, int lineNumber, int column,
String deletedText) {
return new TextChange(Type.DELETE, line, lineNumber, column, line, lineNumber, deletedText);
}
public static TextChange createInsertion(Line line, int lineNumber, int column, Line lastLine,
int lastLineNumber, String text) {
return new TextChange(Type.INSERT, line, lineNumber, column, lastLine, lastLineNumber, text);
}
// This class implements equals and hashCode, make sure to update!
private final int column;
private final Line lastLine;
private final int lastLineNumber;
private final Line line;
private final int lineNumber;
private final String text;
private final Type type;
public TextChange(Type type, Line line, int lineNumber, int column, Line lastLine,
int lastLineNumber, String text) {
this.type = type;
this.line = line;
this.lineNumber = lineNumber;
this.column = column;
this.lastLine = lastLine;
this.lastLineNumber = lastLineNumber;
this.text = text;
}
public int getColumn() {
return column;
}
/**
* Returns the last line "touched", meaning the last line that was either
* created or mutated. For example, an insertion of "\n" would have
* {@link #getLine()} return the line receiving that insertion, and this
* method would return the newly inserted line.
*/
public Line getLastLine() {
return lastLine;
}
/**
* Returns the line number corresponding to {@link #getLastLine()}.
*/
public int getLastLineNumber() {
return lastLineNumber;
}
/**
* For insertations, returns the line that received the ending character
* of {@link #getText()}; for deletions, returns {@link #getLine()}.
*/
public Line getEndLine() {
if (type == Type.DELETE) {
return line;
}
return text.endsWith("\n") ? lastLine.getPreviousLine() : lastLine;
}
/**
* @return line number corresponding to {@link #getEndLine()}.
*/
public int getEndLineNumber() {
if (type == Type.DELETE) {
return lineNumber;
}
return text.endsWith("\n") ? lastLineNumber - 1 : lastLineNumber;
}
/**
* For insertions, returns the column where the last character of
* {@link #getText()} was inserted (on the {@link #getEndLine()});
* for deletions, returns {@link #getColumn()}.
*/
public int getEndColumn() {
if (type == Type.DELETE) {
return column;
}
// Need "- 1" in all returns below since we're returning an inclusive value
// If there were no newlines in the inserted text, it's simple
if (line == lastLine) {
return column + text.length() - 1;
}
/*
* If the last char of text is a newline, then it is endLine's last
* character
*/
if (text.endsWith("\n")) {
return getEndLine().getText().length() - 1;
}
/*
* If it is a non-newline character on a multi-line insertion, then find the
* length of the insertion text's last line
*/
int lastLineStartIndexInText = text.lastIndexOf('\n') + 1;
return text.length() - lastLineStartIndexInText - 1;
}
/**
* Returns the line that received the text change.
*/
public Line getLine() {
return line;
}
public int getLineNumber() {
return lineNumber;
}
public String getText() {
return text;
}
public Type getType() {
return type;
}
@Override
public String toString() {
// Calling type.toString() will prevent it from becoming a simple ordinal
switch (type) {
case INSERT:
return "I(" + column + ", " + text + ")";
case DELETE:
return "D(" + column + ", " + text + ")";
default:
return "Unknown type (ordinal is " + type.ordinal() + ")";
}
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + column;
result = 31 * result + lastLine.hashCode();
result = 31 * result + lastLineNumber;
result = 31 * result + line.hashCode();
result = 31 * result + lineNumber;
result = 31 * result + text.hashCode();
result = 31 * result + type.hashCode();
return result;
}
@Override
public boolean equals(Object otherObj) {
if (!(otherObj instanceof TextChange)) {
return false;
}
TextChange o = (TextChange) otherObj;
return o.column == column && o.lastLine == lastLine && o.lastLineNumber == lastLineNumber
&& o.line == line && o.lineNumber == lineNumber && o.text.equals(text)
&& o.type.equals(type);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/Document.java | shared/src/main/java/com/google/collide/shared/document/Document.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerManager.Dispatcher;
import com.google.collide.shared.util.ListenerRegistrar;
import com.google.collide.shared.util.StringUtils;
// TODO: need the preferred newline characters for the doc
/**
* Document model for the code editor.
*
* The document is modeled using a linked list of lines. (This allows for very fast line insertions
* and still good performance for other common editor operations.)
*
* During a text change, listeners will be called in this order:
* <ul>
* <li>{@link Anchor.ShiftListener}</li>
* <li>{@link Anchor.RemoveListener}</li>
* <li>{@link LineCountListener}</li>
* <li>{@link LineListener}</li>
* <li>{@link TextListener}</li>
* </ul>
*/
public class Document implements DocumentMutator {
/**
* A listener that is called when the number of lines in the document changes.
*
* See the callback ordering documented in {@link Document}.
*/
public interface LineCountListener {
void onLineCountChanged(Document document, int lineCount);
}
/**
* A listener that is called when a line is added or removed from the
* document.
*
* Note: In the case of a multiline insertion/deletion, this will be called
* once.
*
* See the callback ordering documented in {@link Document}.
*/
public interface LineListener {
/**
* @param lineNumber the line number of the first item in {@code addedLines}
* @param addedLines a contiguous list of lines that were added
*/
void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines);
/**
* @param lineNumber the previous line number of the first item in
* {@code removedLines}
* @param removedLines a contiguous list of (now detached) lines that were
* removed
*/
void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines);
}
/**
* A listener that is called when a text change occurs within a document.
*
* See the callback ordering documented in {@link Document}.
*/
public interface TextListener {
/**
* Note: You should not mutate the document within this callback, as this is
* not supported yet and can lead to other clients having stale position
* information inside the {@code textChanges}.
*
* Note: The {@link TextChange} contains a reference to the live
* {@link Line} from the document model. If you hold on to a reference after
* {@link #onTextChange} returns, beware that the contents of the
* {@link Line} could change, invalidating some of the state in the
* {@link TextChange}.
*/
void onTextChange(Document document, JsonArray<TextChange> textChanges);
}
/**
* A listener which is called before any changes are actually made to the
* document and any anchors are moved.
*/
public interface PreTextListener {
/**
* Note: You should not mutate the document within this callback, as this is
* not supported yet and can lead to other clients having stale position
* information inside the {@code textChanges}.
*
* <p>
* This callback is called synchronously with document mutations, the less
* work you can do the better.
*
* @param line The line the text change will take place on.
* @param lineNumber The line number of the line.
* @param column The column the text change will start at.
* @param text The text which is either being inserted or deleted.
* @param type The type of {@link TextChange} that will be occurring.
*/
void onPreTextChange(Document document,
TextChange.Type type,
Line line,
int lineNumber,
int column,
String text);
}
public static Document createEmpty() {
return new Document();
}
public static Document createFromString(
String contents) {
Document doc = createEmpty();
doc.insertText(doc.getFirstLine(), 0, 0, contents);
return doc;
}
private static int idCounter = 0;
private final AnchorManager anchorManager;
private Line firstLine;
private Line lastLine;
private int lineCount = 1;
private final ListenerManager<LineListener> lineListenerManager;
private final ListenerManager<LineCountListener> lineCountListenerManager;
private final LineFinder lineFinder;
private final DocumentMutatorImpl documentMutator;
private final ListenerManager<TextListener> textListenerManager;
private final ListenerManager<PreTextListener> preTextListenerManager;
private final int id = idCounter++;
private final JsonStringMap<Object> tags = JsonCollections.createMap();
private Document() {
firstLine = lastLine = Line.create(this, "");
firstLine.setAttached(true);
anchorManager = new AnchorManager();
documentMutator = new DocumentMutatorImpl(this);
lineListenerManager = ListenerManager.create();
lineCountListenerManager = ListenerManager.create();
lineFinder = new LineFinder(this);
textListenerManager = ListenerManager.create();
preTextListenerManager = ListenerManager.create();
}
public String asText() {
StringBuilder sb = new StringBuilder();
for (Line line = firstLine; line != null; line = line.getNextLine()) {
sb.append(line.getText());
}
return sb.toString();
}
@Override
public TextChange deleteText(Line line, int column, int deleteCount) {
return documentMutator.deleteText(line, column, deleteCount);
}
@Override
public TextChange deleteText(Line line, int lineNumber, int column, int deleteCount) {
return documentMutator.deleteText(line, lineNumber, column, deleteCount);
}
public AnchorManager getAnchorManager() {
return anchorManager;
}
public Line getFirstLine() {
return firstLine;
}
public LineInfo getFirstLineInfo() {
return new LineInfo(firstLine, 0);
}
public Line getLastLine() {
return lastLine;
}
public LineInfo getLastLineInfo() {
return new LineInfo(lastLine, getLastLineNumber());
}
public int getLastLineNumber() {
return lineCount - 1;
}
public int getLineCount() {
return lineCount;
}
public ListenerRegistrar<LineCountListener> getLineCountListenerRegistrar() {
return lineCountListenerManager;
}
public LineFinder getLineFinder() {
return lineFinder;
}
public ListenerRegistrar<LineListener> getLineListenerRegistrar() {
return lineListenerManager;
}
public String getText(Line line, int column, int count) {
assert column < line.getText().length();
StringBuilder s =
new StringBuilder(StringUtils.substringGuarded(line.getText(), column, count));
int remainingCount = count - s.length();
line = line.getNextLine();
while (remainingCount > 0 && line != null) {
String capturedLineText = StringUtils.substringGuarded(line.getText(), 0, remainingCount);
s.append(capturedLineText);
remainingCount -= capturedLineText.length();
line = line.getNextLine();
}
return s.toString();
}
public ListenerRegistrar<TextListener> getTextListenerRegistrar() {
return textListenerManager;
}
public ListenerRegistrar<PreTextListener> getPreTextListenerRegistrar() {
return preTextListenerManager;
}
@Override
public TextChange insertText(Line line, int column, String text) {
return documentMutator.insertText(line, column, text);
}
@Override
public TextChange insertText(Line line, int lineNumber, int column, String text) {
return documentMutator.insertText(line, lineNumber, column, text);
}
@Override
public TextChange insertText(Line line, int lineNumber, int column, String text,
boolean canReplaceSelection) {
return documentMutator.insertText(line, lineNumber, column, text, canReplaceSelection);
}
@Override
public String toString() {
return asText();
}
public String asDebugString() {
StringBuilder sb = new StringBuilder("Line count: " + getLineCount() + "\n");
for (Line line = firstLine; line != null; line = line.getNextLine()) {
sb.append(line.getText()).append("---\n");
}
return sb.toString();
}
public int getId() {
return id;
}
/**
* @see Line#putTag(String, Object)
*/
public <T> void putTag(String key, T value) {
tags.put(key, value);
}
/**
* @see Line#getTag(String)
*/
@SuppressWarnings("unchecked")
public <T> T getTag(String key) {
return (T) tags.get(key);
}
void commitLineCountChange(int lineCountDelta) {
if (lineCountDelta != 0) {
lineCount += lineCountDelta;
lineCountListenerManager.dispatch(new Dispatcher<Document.LineCountListener>() {
@Override
public void dispatch(LineCountListener listener) {
listener.onLineCountChanged(Document.this, lineCount);
}
});
}
}
void dispatchLineAdded(final int lineNumber, final JsonArray<Line> addedLines) {
lineListenerManager.dispatch(new Dispatcher<Document.LineListener>() {
@Override
public void dispatch(LineListener listener) {
listener.onLineAdded(Document.this, lineNumber, addedLines);
}
});
}
void dispatchLineRemoved(final int lineNumber, final JsonArray<Line> removedLines) {
lineListenerManager.dispatch(new Dispatcher<Document.LineListener>() {
@Override
public void dispatch(LineListener listener) {
listener.onLineRemoved(Document.this, lineNumber, removedLines);
}
});
}
void dispatchTextChange(final JsonArray<TextChange> textChanges) {
textListenerManager.dispatch(new Dispatcher<Document.TextListener>() {
@Override
public void dispatch(TextListener listener) {
listener.onTextChange(Document.this, textChanges);
}
});
}
void dispatchPreTextChange(final TextChange.Type type, final Line line, final int lineNumber,
final int column, final String text) {
preTextListenerManager.dispatch(new Dispatcher<Document.PreTextListener>() {
@Override
public void dispatch(PreTextListener listener) {
listener.onPreTextChange(Document.this, type, line, lineNumber, column, text);
}
});
}
void setFirstLine(Line line) {
assert line != null : "Line cannot be null";
firstLine = line;
}
void setLastLine(Line line) {
assert line != null : "Line cannot be null";
lastLine = line;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/LineInfo.java | shared/src/main/java/com/google/collide/shared/document/LineInfo.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
/*
* TODO: mutable lineinfos end up being expensive because the
* defensive copies. Make LineInfo immutable.
*/
/*
* TODO: I ended up passing LineInfo around frequently for a (line,
* lineNumber) pair just because it exists, but it leads to uglier code
* (lineInfo.number() instead of lineNumber) and more objects, reconsider this
* thing's use case (originally it was for returning a Line+LineNumber pair from
* a method
*/
/**
* A POJO for a {@link Line} and its line number. This is mostly for returning
* that pair of information, not for retaining longer-term since line numbers
* shift constantly, and this class will not get updated.
*
*/
public class LineInfo implements Comparable<LineInfo> {
private Line line;
private int number;
public LineInfo(Line line, int number) {
this.line = line;
this.number = number;
}
@Override
public int compareTo(LineInfo o) {
return number - o.number;
}
public LineInfo copy() {
return new LineInfo(line, number);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LineInfo)) {
return false;
}
LineInfo other = (LineInfo) obj;
return line.equals(other.line) && number == other.number;
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + number;
result = 37 * result + line.hashCode();
return result;
}
public Line line() {
return line;
}
public boolean moveToNext() {
return moveToImpl(line.getNextLine(), number + 1);
}
public boolean moveToPrevious() {
return moveToImpl(line.getPreviousLine(), number - 1);
}
public int number() {
return number;
}
@Override
public String toString() {
return "" + number + ": " + line.toString();
}
private boolean moveToImpl(Line newLine, int newNumber) {
if (newLine == null) {
return false;
}
line = newLine;
number = newNumber;
return true;
}
public boolean moveTo(boolean iterateForward) {
return iterateForward ? moveToNext() : moveToPrevious();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/PositionOutOfBoundsException.java | shared/src/main/java/com/google/collide/shared/document/PositionOutOfBoundsException.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document;
/**
* An exception that is thrown when the thrower has gone out of the document's
* bounds.
*
*/
public class PositionOutOfBoundsException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -709766127638236771L;
public PositionOutOfBoundsException(String message) {
super(message);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/util/LineUtils.java | shared/src/main/java/com/google/collide/shared/document/util/LineUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.util;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineFinder;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.document.PositionOutOfBoundsException;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.util.TextUtils;
import com.google.common.base.Preconditions;
/**
* Utility methods for line manipulations.
*/
public final class LineUtils {
/**
* Interface for a visitor of lines.
*/
public interface LineVisitor {
/**
* @return true to continue visiting more lines, false to abort the visit
*/
boolean accept(Line line, int lineNumber, int beginColumn, int endColumn);
}
/*
* TODO: Move to newly created PositionUtils (in a future
* standalone CL since this has a lot of callers)
*/
/**
* Returns a negative number if {@code a} is earlier than {@code b}, a
* positive number if {@code a} is later than {@code b}, and zero if they are
* the same.
*/
public static int comparePositions(int aLineNumber, int aColumn, int bLineNumber, int bColumn) {
int lineNumberDelta = aLineNumber - bLineNumber;
return lineNumberDelta != 0 ? lineNumberDelta : aColumn - bColumn;
}
/**
* Returns a cached {@link LineInfo} for this {@link Line} if it exists, or
* null.
*/
public static LineInfo getCachedLineInfo(Line line) {
Anchor anchorWithLineNumber =
line.getDocument().getAnchorManager().findAnchorWithLineNumber(line);
return anchorWithLineNumber != null ? anchorWithLineNumber.getLineInfo() : null;
}
/**
* Returns a cached line number for this line if it exists, or -1.
*/
public static int getCachedLineNumber(Line line) {
Anchor anchorWithLineNumber =
line.getDocument().getAnchorManager().findAnchorWithLineNumber(line);
return anchorWithLineNumber != null ? anchorWithLineNumber.getLineNumber() : -1;
}
/**
* Returns the last column (inclusive) of the line, or -1 if the line is
* empty.
*/
public static int getLastColumn(Line line) {
return line.getText().length() - 1;
}
/**
* Returns the first column for the given line where a cursor can be placed.
* This will skip any strange control characters or zero-width characters that
* are prefixing a line.
*/
public static int getFirstCursorColumn(Line line) {
String lineText = line.getText();
return TextUtils.findNonMarkNorOtherCharacter(lineText, -1);
}
/**
* Returns the max column for the given line where a cursor can be placed.
* This can also be thought of as the index after the last character in the
* line (the newline does not count as a character here.)
*/
public static int getLastCursorColumn(Line line) {
// "- 1" because we cannot position after the invisible newline
return getLastCursorColumn(line.getText());
}
/**
* @see #getLastCursorColumn(Line)
*/
public static int getLastCursorColumn(String lineText) {
return lineText.endsWith("\n") ? lineText.length() - 1 : lineText.length();
}
/**
* Iterates to and returns the line that is {@code relativePosition} away from
* the given {@code line}. If {@code relativePosition} is large, consider
* using {@link LineFinder}.
*/
public static Line getLine(Line line, int relativePosition) {
if (relativePosition > 0) {
for (; line != null && relativePosition > 0; relativePosition--) {
line = line.getNextLine();
}
} else {
for (; line != null && relativePosition < 0; relativePosition++) {
line = line.getPreviousLine();
}
}
return line;
}
/**
* Gets the number of characters (including newlines) in the given inclusive
* range.
*/
public static int getTextCount(Line beginLine, int beginColumn, Line endLine, int endColumn) {
Preconditions.checkArgument(beginLine.isAttached(), "beginLine must be attached");
Preconditions.checkArgument(endLine.isAttached(), "endLine must be attached");
if (beginLine == endLine) {
return endColumn - beginColumn + 1;
}
int count = beginLine.getText().length() - beginColumn;
Line line = beginLine.getNextLine();
while (line != null && line != endLine) {
count += line.getText().length();
line = line.getNextLine();
}
if (line == null) {
throw new IndexOutOfBoundsException("can't find endLine");
}
count += endColumn + 1;
return count;
}
/**
* Gets the text from the beginning position to the end position (inclusive).
*/
public static String getText(Line beginLine, int beginColumn, Line endLine, int endColumn) {
if (beginLine == endLine) {
return beginLine.getText().substring(beginColumn, endColumn + 1);
}
StringBuilder s = new StringBuilder(beginLine.getText().substring(beginColumn));
Line line = beginLine.getNextLine();
while (line != null && line != endLine) {
s.append(line.getText());
line = line.getNextLine();
}
if (line == null) {
throw new IndexOutOfBoundsException();
}
s.append(endLine.getText().substring(0, endColumn + 1));
return s.toString();
}
/**
* Returns a line number in the range of the document closest to the
* {@code targetLineNumber}.
*/
public static int getValidLineNumber(int targetLineNumber, Document document) {
int lastLineNumber = document.getLastLineNumber();
if (targetLineNumber <= 0) {
return 0;
} else if (targetLineNumber >= lastLineNumber) {
return lastLineNumber;
} else {
return targetLineNumber;
}
}
/**
* Returns the target column, or the max column for the line if the target
* column is too large, or 0 if the target column is negative.
*/
public static int rubberbandColumn(Line line, int targetColumn) {
return (int) rubberbandColumn(line, (double) targetColumn);
}
public static double rubberbandColumn(Line line, double targetColumn) {
if (targetColumn < 0) {
return 0;
}
int maxColumnFromLineText = getLastCursorColumn(line);
return maxColumnFromLineText < targetColumn ? maxColumnFromLineText : targetColumn;
}
static Position getPositionBackwards(Line line, int lineNumber, int column,
int numCharsToTraverse) {
while (numCharsToTraverse > 0) {
int remainingCharsOnThisLine = column;
/*
* In the case that remainingCharsOnLine == numCharsToTraverse, we want to
* move to the first column of this line
*/
if (remainingCharsOnThisLine < numCharsToTraverse) {
// Skip over this line
line = line.getPreviousLine();
if (line == null) {
throw new PositionOutOfBoundsException(
"Reached the document beginning, but still wanted to go " + numCharsToTraverse
+ " characters backwards.");
}
lineNumber--;
column = line.getText().length();
numCharsToTraverse -= remainingCharsOnThisLine;
} else {
// It's within this line
column -= numCharsToTraverse;
numCharsToTraverse = 0;
}
}
return new Position(new LineInfo(line, lineNumber), column);
}
static Position getPositionForward(Line line, int lineNumber, int column,
int numCharsToTraverse) {
while (numCharsToTraverse > 0) {
int remainingCharsOnThisLine = line.getText().length() - column;
/*
* In the case that remainingCharsOnLine == numCharsToTraverse, we want to
* move to the first column of the next line
*/
if (remainingCharsOnThisLine <= numCharsToTraverse) {
if (line.getNextLine() == null) {
/*
* For the last line we have no newline character and want to move to
* the line end
*/
if (remainingCharsOnThisLine < numCharsToTraverse) {
throw new PositionOutOfBoundsException(
"Reached the document end, but still wanted to go "
+ (numCharsToTraverse - remainingCharsOnThisLine) + " characters forward.");
} else {
column += numCharsToTraverse;
}
} else {
// Skip over this line
line = line.getNextLine();
lineNumber++;
column = 0;
}
numCharsToTraverse -= remainingCharsOnThisLine;
} else {
// It's within this line
column += numCharsToTraverse;
numCharsToTraverse = 0;
}
}
return new Position(new LineInfo(line, lineNumber), column);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/util/PositionUtils.java | shared/src/main/java/com/google/collide/shared/document/util/PositionUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.util;
import static com.google.collide.shared.document.util.LineUtils.getPositionBackwards;
import static com.google.collide.shared.document.util.LineUtils.getPositionForward;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.document.util.LineUtils.LineVisitor;
import com.google.collide.shared.util.JsonCollections;
/**
* Utility methods relating to {@link Position}.
*/
public final class PositionUtils {
public static int compare(Position a, Position b) {
return LineUtils.comparePositions(a.getLineNumber(), a.getColumn(), b.getLineNumber(),
b.getColumn());
}
public static Position[] getIntersection(Position[] a, Position[] b) {
// Ensure that A starts before B
if (compare(a[0], b[0]) > 0) {
return getIntersection(b, a);
}
if (compare(b[0], a[1]) > 0) {
// No intersection
return null;
}
Position earlierEnd = compare(a[1], b[1]) < 0 ? a[1] : b[1];
return new Position[] {b[0], earlierEnd};
}
public static JsonArray<Position[]> getDifference(Position[] a, Position[] b) {
// Ensure that A starts before B
int abStartComparison = compare(a[0], b[0]);
if (abStartComparison > 0) {
return getDifference(b, a);
}
if (compare(b[0], a[1]) > 0) {
// No intersection, so return both
return JsonCollections.createArray(a, b);
}
JsonArray<Position[]> difference = JsonCollections.createArray();
if (abStartComparison != 0) {
// Range from the start of A (inclusive) to the start of B (exclusive)
difference.add(new Position[] {a[0], getPosition(b[0], -1)});
}
int abEndComparison = compare(a[1], b[1]);
if (abEndComparison != 0) {
Position earlierEnd = abEndComparison < 0 ? a[1] : b[1];
Position laterEnd = abEndComparison < 0 ? b[1] : a[1];
difference.add(new Position[] {getPosition(earlierEnd, 1), laterEnd});
}
return difference;
}
/**
* Returns the position (line and column) which is {@code relativeOffset}
* characters (including newlines) away from the given starting position (
* {@code line} and {@code column}).
*
*/
public static Position getPosition(Line line, int lineNumber, int column, int relativeOffset) {
return relativeOffset < 0 ?
getPositionBackwards(line, lineNumber, column, -relativeOffset)
: getPositionForward(line, lineNumber, column, relativeOffset);
}
/**
* @see #getPosition(com.google.collide.shared.document.Line, int, int, int)
*/
public static Position getPosition(Position position, int relativeOffset) {
return relativeOffset < 0 ? getPositionBackwards(position.getLine(), position.getLineNumber(),
position.getColumn(), -relativeOffset) : getPositionForward(position.getLine(),
position.getLineNumber(), position.getColumn(), relativeOffset);
}
/* public static Position getPosition(Position start, int relativeOffset) {
return getPosition(start.getLine(), start.getLineNumber(), start.getColumn(),
relativeOffset);
}*/
/**
* Visit each line in order from start to end, calling lineVisitor.accept()
* for each line. If lineVisitor.accept returns false, stop execution, else
* continue until end is reached.
*
* This method can search backwards if start is later than end. In this case,
* ensure that start's column is exclusive.
*
* @param lineVisitor the {@code endColumn} given to the visitor is exclusive
* @param start if searching backwards, the column should be exclusive.
* @param end if searching forward, the column should be exclusive. If
* searching backwards, the column should be inclusive
*/
public static void visit(LineVisitor lineVisitor, Position start, Position end) {
if (start.getLine().equals(end.getLine())) {
lineVisitor
.accept(start.getLine(), start.getLineNumber(), start.getColumn(), end.getColumn());
return;
}
boolean iterateForward = compare(start, end) < 0;
if (iterateForward) {
if (!lineVisitor.accept(start.getLine(), start.getLineNumber(), start.getColumn(), start
.getLine().length())) {
return;
}
} else {
if (!lineVisitor.accept(start.getLine(), start.getLineNumber(), 0, start.getColumn())) {
return;
}
}
LineInfo curLine = start.getLineInfo();
curLine.moveTo(iterateForward);
while (curLine.line() != end.getLine()) {
if (!lineVisitor.accept(curLine.line(), curLine.number(), 0, curLine.line().length())) {
return;
}
if (!curLine.moveTo(iterateForward)) {
throw new IllegalStateException(
"Could not find the requested ending line while visiting position range");
}
}
if (iterateForward) {
lineVisitor.accept(end.getLine(), end.getLineNumber(), 0, end.getColumn());
} else {
lineVisitor.accept(end.getLine(), end.getLineNumber(), end.getColumn(),
end.getLine()
.length());
}
}
private PositionUtils() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/AnchorManager.java | shared/src/main/java/com/google/collide/shared/document/anchor/AnchorManager.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.anchor.InsertionPlacementStrategy.Placement;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.SortedList;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
// TODO: need to make an interface for the truly public methods
/**
* Manager for anchors within a document.
*
*/
public class AnchorManager {
/**
* Visitor that is called for each anchor in some collection of anchors.
*/
public interface AnchorVisitor {
void visitAnchor(Anchor anchor);
}
/*
* Much logic relies on the fact that in a line's anchor list, these will
* appear before anchors that care about column numbers.
*/
/**
* Constant value for the line number to indicate that the anchor does not
* care about its line number.
*/
public static final int IGNORE_LINE_NUMBER = -1;
/**
* Constant value for the column to indicate that the anchor does not have a
* column.
*
* This is useful for anchors that only care about knowing movements of
* lines, and not specific columns. For example, a viewport may use this for
* the viewport top and viewport bottom.
*/
public static final int IGNORE_COLUMN = -1;
private static final String LINE_TAG_ANCHORS = AnchorManager.class.getName() + ":Anchors";
private final LineAnchorList lineAnchors;
// TODO: not really public
public AnchorManager() {
lineAnchors = new LineAnchorList();
}
/**
* @param anchorType the type of the anchor
* @param line the line the anchor should attach to
* @param lineNumber the line number, or {@link #IGNORE_LINE_NUMBER} if this
* anchor is not interested in its line number
* @param column the column, or {@link #IGNORE_COLUMN} if this anchor is not
* positioned on a column
*/
public Anchor createAnchor(AnchorType anchorType, Line line, int lineNumber, int column) {
Anchor anchor = new Anchor(anchorType, line, lineNumber, column);
getAnchors(line).add(anchor);
if (lineNumber != IGNORE_LINE_NUMBER) {
lineAnchors.add(anchor);
}
return anchor;
}
/**
* Searches the given {@code line} for an anchor with a line number, or returns null.
*/
public Anchor findAnchorWithLineNumber(Line line) {
AnchorList anchors = getAnchorsOrNull(line);
if (anchors == null) {
return null;
}
for (int i = 0, n = anchors.size(); i < n; i++) {
if (anchors.get(i).hasLineNumber()) {
return anchors.get(i);
}
}
return null;
}
/**
* Finds the closest anchor with a line number, or null. The anchor may be
* positioned on another line.
*/
public Anchor findClosestAnchorWithLineNumber(int lineNumber) {
if (lineAnchors.size() == 0) {
return null;
}
int insertionIndex = lineAnchors.findInsertionIndex(lineNumber);
if (insertionIndex == lineAnchors.size()) {
return lineAnchors.get(insertionIndex - 1);
} else if (insertionIndex == 0) {
return lineAnchors.get(0);
}
int distanceFromPreviousAnchor =
lineNumber - lineAnchors.get(insertionIndex - 1).getLineNumber();
int distanceFromNextAnchor = lineAnchors.get(insertionIndex).getLineNumber() - lineNumber;
return distanceFromNextAnchor < distanceFromPreviousAnchor
? lineAnchors.get(insertionIndex) : lineAnchors.get(insertionIndex - 1);
}
/**
* Returns the list of anchors on the given line. The returned instance is the
* original list, not a copy.
*
* @see #getAnchorsOrNull(Line)
*/
@VisibleForTesting
public static AnchorList getAnchors(Line line) {
AnchorList columnAnchors = line.getTag(LINE_TAG_ANCHORS);
if (columnAnchors == null) {
columnAnchors = new AnchorList();
line.putTag(LINE_TAG_ANCHORS, columnAnchors);
}
return columnAnchors;
}
/**
* Returns the list of anchors on the given line (the returned instance is the
* original list, not a copy), or null if there are no anchors
*/
static AnchorList getAnchorsOrNull(Line line) {
return line.getTag(LINE_TAG_ANCHORS);
}
/**
* Returns anchors of the given type on the given line, or null if there are
* no anchors of any kind on the given line.
*/
public static JsonArray<Anchor> getAnchorsByTypeOrNull(Line line, AnchorType type) {
AnchorList anchorList = getAnchorsOrNull(line);
if (anchorList == null) {
return null;
}
JsonArray<Anchor> anchors = JsonCollections.createArray();
for (int i = 0; i < anchorList.size(); i++) {
Anchor anchor = anchorList.get(i);
if (type.equals(anchor.getType())) {
anchors.add(anchor);
}
}
return anchors;
}
@VisibleForTesting
public LineAnchorList getLineAnchors() {
return lineAnchors;
}
/**
* Finds the next anchor relative to the one given or null if there are no
* subsequent anchors.
*/
public Anchor getNextAnchor(Anchor anchor) {
return getAdjacentAnchor(anchor, null, true);
}
/**
* Finds the next anchor of the given type relative to the one given or null
* if there are no subsequent anchors of that type.
*/
public Anchor getNextAnchor(Anchor anchor, AnchorType type) {
return getAdjacentAnchor(anchor, type, true);
}
/**
* Finds the previous anchor relative to the one given or null if there are no
* preceding anchors.
*/
public Anchor getPreviousAnchor(Anchor anchor) {
return getAdjacentAnchor(anchor, null, false);
}
/**
* Finds the previous anchor of the given type relative to the one given or
* null if there are no preceding anchors of that type.
*/
public Anchor getPreviousAnchor(Anchor anchor, AnchorType type) {
return getAdjacentAnchor(anchor, type, false);
}
/**
* Private utility method that performs the search for getNextAnchor/getPreviousAnchor
*
* For now, the performance is O(lines + anchors)
*
* TODO: Instead we should consider maintaining a separate anchor.
* TODO: avoid recusrion list. This should let us easily achieve O(anchors)
* or better.
*
* @param anchor the @{link Anchor} anchor to start the search from
* @param type the @{link AnchorType} of the anchor, or null to capture any type.
* @param next true if the search is forwards, false for backwards
* @return the adjacent anchor, or null if no such anchor is found
*/
private Anchor getAdjacentAnchor(Anchor anchor, AnchorType type, boolean next) {
Line currentLine = anchor.getLine();
AnchorList list = getAnchors(currentLine);
// Special case for the same line
int insertionIndex = list.findInsertionIndex(anchor);
int lowerBound = next ? 0 : 1;
int upperBound = next ? list.size() - 2 : list.size() - 1;
if (insertionIndex >= lowerBound && insertionIndex <= upperBound) {
Anchor anchorInList = list.get(insertionIndex);
if (anchor == anchorInList) {
// We found the anchor in the list, and we have a neighbor to return
Anchor candidateAnchor;
if (next) {
candidateAnchor = list.get(insertionIndex + 1);
} else {
candidateAnchor = list.get(insertionIndex - 1);
}
// Enforce the type
if (type != null && !candidateAnchor.getType().equals(type)) {
return getAdjacentAnchor(candidateAnchor, type, next);
} else {
return candidateAnchor;
}
}
// Otherwise, the anchor must be on another line
}
currentLine = next ? currentLine.getNextLine() : currentLine.getPreviousLine();
while (currentLine != null) {
list = getAnchorsOrNull(currentLine);
if (list != null && list.size() > 0) {
Anchor candidateAnchor;
if (next) {
candidateAnchor = list.get(0);
} else {
candidateAnchor = list.get(list.size() - 1);
}
// Enforce the type
if (type != null && !candidateAnchor.getType().equals(type)) {
return getAdjacentAnchor(candidateAnchor, type, next);
} else {
return candidateAnchor;
}
}
currentLine = next ? currentLine.getNextLine() : currentLine.getPreviousLine();
}
return null;
}
// TODO: not public
public void handleTextPredeletionForLine(Line line, int column, int deleteCountForLine,
final JsonArray<Anchor> anchorsInDeletedRangeToRemove,
final JsonArray<Anchor> anchorsInDeletedRangeToShift, boolean isFirstLine) {
AnchorList anchors = getAnchorsOrNull(line);
if (anchors == null) {
return;
}
boolean entireLineDeleted = line.getText().length() == deleteCountForLine;
assert !entireLineDeleted || column == 0;
if (entireLineDeleted && !isFirstLine) {
// If entire line is deleted, shift/remove line anchors too
for (int i = 0, n = anchors.size(); i < n && anchors.get(i).isLineAnchor(); i++) {
categorizeAccordingToRemovalStrategy(anchors.get(i), anchorsInDeletedRangeToRemove,
anchorsInDeletedRangeToShift);
}
}
/*
* To support the cursor at the end of a line (without a newline), we must
* extend past the last column of the line
*/
int lastColumnToDelete =
entireLineDeleted ? Integer.MAX_VALUE : column + deleteCountForLine - 1;
for (int i = anchors.findInsertionIndex(column, Anchor.ID_FIRST_IN_COLUMN), n = anchors.size();
i < n && anchors.get(i).getColumn() <= lastColumnToDelete; i++) {
categorizeAccordingToRemovalStrategy(anchors.get(i), anchorsInDeletedRangeToRemove,
anchorsInDeletedRangeToShift);
}
}
// TODO: not public
public void handleTextDeletionLastLineLeftover(JsonArray<Anchor> anchorsLeftoverFromLastLine,
Line firstLine, Line lastLine, int lastLineFirstUntouchedColumn) {
AnchorList anchors = getAnchorsOrNull(lastLine);
if (anchors == null) {
return;
}
if (firstLine != lastLine) {
for (int i = 0, n = anchors.size(); i < n && anchors.get(i).isLineAnchor(); i++) {
anchorsLeftoverFromLastLine.add(anchors.get(i));
}
}
for (int i =
anchors.findInsertionIndex(lastLineFirstUntouchedColumn, Anchor.ID_FIRST_IN_COLUMN), n =
anchors.size(); i < n; i++) {
anchorsLeftoverFromLastLine.add(anchors.get(i));
}
}
// TODO: not public
/**
* @param lastLineFirstUntouchedColumn the left-most column that was not part
* of the deletion. If all of the characters on the last line were
* deleted, this will be the length of the text on the line
*/
public void handleTextDeletionFinished(JsonArray<Anchor> anchorsInDeletedRangeToRemove,
JsonArray<Anchor> anchorsInDeletionRangeToShift, JsonArray<Anchor> anchorsLeftoverOnLastLine,
Line firstLine, int firstLineNumber, int firstLineColumn, int numberOfLinesDeleted,
int lastLineFirstUntouchedColumn) {
AnchorDeferredDispatcher dispatcher = new AnchorDeferredDispatcher();
// Remove anchors that did not want to be shifted
for (int i = 0, n = anchorsInDeletedRangeToRemove.size(); i < n; i++) {
removeAnchorDeferDispatch(anchorsInDeletedRangeToRemove.get(i), dispatcher);
}
// Shift anchors that were part of the deletion range and want to be shifted
for (int i = 0, n = anchorsInDeletionRangeToShift.size(); i < n; i++) {
Anchor anchor = anchorsInDeletionRangeToShift.get(i);
updateAnchorPositionObeyingExistingIgnoresWithoutDispatch(anchor,
firstLine, firstLineNumber, firstLineColumn);
dispatcher.deferDispatchShifted(anchor);
}
/*
* Shift anchors that were on the leftover text on the last line (now their
* text lives on the first line)
*/
for (int i = 0, n = anchorsLeftoverOnLastLine.size(); i < n; i++) {
Anchor anchor = anchorsLeftoverOnLastLine.get(i);
int anchorFirstLineColumn =
anchor.getColumn() - lastLineFirstUntouchedColumn + firstLineColumn;
updateAnchorPositionObeyingExistingIgnoresWithoutDispatch(anchor, firstLine, firstLineNumber,
anchorFirstLineColumn);
dispatcher.deferDispatchShifted(anchor);
}
if (numberOfLinesDeleted > 0) {
/*
* Shift the line numbers of anchors past the deleted range (note that the
* anchors still have their old line numbers, hence the
* "+ numberOfLinesDeleted")
*/
shiftLineNumbersDeferDispatch(firstLineNumber + numberOfLinesDeleted + 1,
-numberOfLinesDeleted, dispatcher);
}
dispatcher.dispatch();
}
private void categorizeAccordingToRemovalStrategy(Anchor anchor,
JsonArray<Anchor> anchorsToRemove, JsonArray<Anchor> anchorsToShift) {
switch (anchor.getRemovalStrategy()) {
case SHIFT:
anchorsToShift.add(anchor);
break;
case REMOVE:
anchorsToRemove.add(anchor);
break;
}
}
// TODO: not public
public void handleMultilineTextInsertion(Line oldLine, int oldLineNumber, int oldColumn,
Line newLine, int newLineNumber, int newColumn) {
AnchorDeferredDispatcher dispatcher = new AnchorDeferredDispatcher();
/*
* Shift all of the following line anchors (remember that the anchor data
* structures do not know about the newly inserted lines yet, so
* oldLineNumber + 1 is the first line after the insertion point.
*/
shiftLineNumbersDeferDispatch(oldLineNumber + 1, newLineNumber - oldLineNumber,
dispatcher);
/*
* Now update the anchors on the line receiving the multiline text
* insertion
*/
AnchorList anchors = getAnchorsOrNull(oldLine);
if (anchors != null) {
// Shift *line* anchors (those without columns) if their strategies allow
for (int i = 0; i < anchors.size() && anchors.get(i).isLineAnchor();) {
Anchor anchor = anchors.get(i);
if (isInsertionPlacementStrategyLater(anchor, oldLine, oldColumn)) {
updateAnchorPositionWithoutDispatch(anchor, newLine, newLineNumber,
AnchorManager.IGNORE_COLUMN);
dispatcher.deferDispatchShifted(anchor);
} else {
i++;
}
}
/*
* Consider moving the anchors that are positioned greater than or equal
* to the column receiving the newline
*/
for (int i = anchors.findInsertionIndex(oldColumn, Anchor.ID_FIRST_IN_COLUMN); i < anchors
.size();) {
Anchor anchor = anchors.get(i);
if (anchor.getColumn() == oldColumn
&& !isInsertionPlacementStrategyLater(anchor, oldLine, oldColumn)) {
/*
* This anchor is on the same column as the split but does not want to
* be moved
*/
i++;
continue;
}
int newAnchorColumn = anchor.getColumn() - oldColumn + newColumn;
updateAnchorPositionObeyingExistingIgnoresWithoutDispatch(anchor, newLine, newLineNumber,
newAnchorColumn);
dispatcher.deferDispatchShifted(anchor);
// No need to touch i since the size of anchors is one smaller now
}
}
dispatcher.dispatch();
}
private boolean isInsertionPlacementStrategyLater(Anchor anchor, Line line, int column) {
InsertionPlacementStrategy.Placement placement =
anchor.getInsertionPlacementStrategy().determineForInsertion(anchor, line, column);
return placement == Placement.LATER;
}
// TODO: not public
public void handleSingleLineTextInsertion(Line line, int column, int length) {
shiftColumnAnchors(line, column, length, true);
}
/**
* Moves the anchor to a new position.
*/
public void moveAnchor(final Anchor anchor, Line line, int lineNumber, int column) {
updateAnchorPositionWithoutDispatch(anchor, line, lineNumber, column);
anchor.dispatchMoved();
}
private void updateAnchorPositionObeyingExistingIgnoresWithoutDispatch(Anchor anchor,
Line newLine, int newLineNumber, int newColumn) {
int anchorsNewColumn = anchor.getColumn() == IGNORE_COLUMN ? IGNORE_COLUMN : newColumn;
int anchorsNewLineNumber =
anchor.getLineNumber() == IGNORE_LINE_NUMBER ? IGNORE_LINE_NUMBER : newLineNumber;
updateAnchorPositionWithoutDispatch(anchor, newLine, anchorsNewLineNumber, anchorsNewColumn);
}
/**
* Moves the anchor without dispatching. This will update the anchor lists.
*/
private void updateAnchorPositionWithoutDispatch(final Anchor anchor, Line line, int lineNumber,
int column) {
Preconditions.checkState(anchor.isAttached(), "Cannot move detached anchor");
// Ensure it's different
if (anchor.getLine() == line && anchor.getLineNumber() == lineNumber
&& anchor.getColumn() == column) {
return;
}
// Remove the anchor
Line oldLine = anchor.getLine();
AnchorList oldAnchors = getAnchorsOrNull(oldLine);
if (oldAnchors == null) {
throw new IllegalStateException("List of line's anchors should not be null\nLine anchors:\n"
+ dumpAnchors(lineAnchors));
}
boolean removed = oldAnchors.remove(anchor);
if (!removed) {
throw new IllegalStateException(
"Could not find anchor in list of line's anchors\nAnchors on line:\n"
+ dumpAnchors(oldAnchors) + "\nLine anchors:\n" + dumpAnchors(lineAnchors));
}
if (anchor.hasLineNumber()) {
removed = lineAnchors.remove(anchor);
if (!removed) {
throw new IllegalStateException(
"Could not find anchor in list of anchors that care about line numbers\nLine anchors:\n"
+ dumpAnchors(lineAnchors) + "\nAnchors on line:\n" + dumpAnchors(oldAnchors));
}
}
// Update its position
anchor.setLineWithoutDispatch(line, lineNumber);
anchor.setColumnWithoutDispatch(column);
// Add it again so its in the list reflects its new position
AnchorList anchors = line.equals(oldLine) ? oldAnchors : getAnchors(line);
anchors.add(anchor);
if (lineNumber != IGNORE_LINE_NUMBER) {
lineAnchors.add(anchor);
}
}
public void removeAnchor(Anchor anchor) {
// Do not add any extra logic here
AnchorDeferredDispatcher dispatcher = new AnchorDeferredDispatcher();
removeAnchorDeferDispatch(anchor, dispatcher);
dispatcher.dispatch();
}
/**
* Clears the line anchors list. This is not public API.
*/
public void clearLineAnchors() {
lineAnchors.clear();
}
private void removeAnchorDeferDispatch(Anchor anchor, AnchorDeferredDispatcher dispatcher) {
if (anchor.hasLineNumber()) {
lineAnchors.remove(anchor);
}
AnchorList anchors = getAnchorsOrNull(anchor.getLine());
if (anchors != null) {
anchors.remove(anchor);
}
anchor.detach();
dispatcher.deferDispatchRemoved(anchor);
}
/**
* Shifts the column anchors anchored to the column or later by the given
* {@code shiftAmount}.
*
* @param consultPlacementStrategy true to consult and obey the placement
* strategies of anchors that lie exactly on {@code column}
*/
private void shiftColumnAnchors(Line line, int column, int shiftAmount,
boolean consultPlacementStrategy) {
final AnchorList anchors = getAnchorsOrNull(line);
if (anchors == null) {
return;
}
AnchorDeferredDispatcher dispatcher = new AnchorDeferredDispatcher();
int insertionIndex = anchors.findInsertionIndex(column, Anchor.ID_FIRST_IN_COLUMN);
for (int i = insertionIndex; i < anchors.size();) {
Anchor anchor = anchors.get(i);
boolean repositionAnchor = true;
if (consultPlacementStrategy && anchor.getColumn() == column) {
repositionAnchor = isInsertionPlacementStrategyLater(anchor, line, column);
}
if (repositionAnchor) {
anchors.remove(anchor);
anchor.setColumnWithoutDispatch(anchor.getColumn() + shiftAmount);
dispatcher.deferDispatchShifted(anchor);
// No need to increase i since we removed above
} else {
i++;
}
}
// Re-adding in the loop above can cause problems if shiftAmount > 0
JsonArray<Anchor> shiftedAnchors = dispatcher.getShiftedAnchors();
if (shiftedAnchors != null) {
for (int i = 0, n = shiftedAnchors.size(); i < n; i++) {
anchors.add(shiftedAnchors.get(i));
}
}
// Dispatch after all anchors are in their final, consistent state
dispatcher.dispatch();
}
/**
* Takes care of shifting the line numbers of interested anchors.
*
* @param lineNumber inclusive
*/
private void shiftLineNumbersDeferDispatch(final int lineNumber, int shiftAmount,
AnchorDeferredDispatcher dispatcher) {
int insertionIndex = lineAnchors.findInsertionIndex(lineNumber);
for (int i = insertionIndex, n = lineAnchors.size(); i < n; i++) {
Anchor anchor = lineAnchors.get(i);
anchor.setLineWithoutDispatch(anchor.getLine(), anchor.getLineNumber() + shiftAmount);
dispatcher.deferDispatchShifted(anchor);
}
}
private static String dumpAnchors(SortedList<Anchor> anchorList) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = anchorList.size(); i < n; i++) {
sb.append(anchorList.get(i).toString()).append("\n");
}
return sb.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/AnchorType.java | shared/src/main/java/com/google/collide/shared/document/anchor/AnchorType.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
/**
* A type identifier for anchors.
*/
public class AnchorType {
public static AnchorType create(Class<?> clientClazz, String name) {
return new AnchorType(clientClazz.getName() + "_" + name);
}
private final String type;
AnchorType(String type) {
this.type = type;
}
@Override
public String toString() {
return type;
}
@Override
public boolean equals(Object o) {
if (o instanceof AnchorType) {
return type.equals(((AnchorType) o).type);
}
return false;
}
@Override
public int hashCode() {
return type.hashCode();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/Anchor.java | shared/src/main/java/com/google/collide/shared/document/anchor/Anchor.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerManager.Dispatcher;
import com.google.collide.shared.util.ListenerRegistrar;
// TODO: resolve the looseness in type safety
/*
* There is loosened type safety in this class for the ListenerManagers to allow
* for both the read-only interface (ReadOnlyAnchor) and this class to share the
* same underlying ListenerManager for each event.
*/
/**
* Model for an anchor in the document that maintains its up-to-date positioning
* in the document as text changes occur.
*
* An anchor should pass {@link AnchorManager#IGNORE_LINE_NUMBER} if its line
* number will not be used.
*
* Similarly, an anchor should pass {@link AnchorManager#IGNORE_COLUMN} if its
* column will not be used. Anchors with this flag will be called
* "line anchors".
*
* One caveat with line anchors that have the {@link RemovalStrategy#REMOVE}
* removal strategy is they will be removed when the line's preceding newline
* character is removed. For example, if the cursor is at (line 2, column 0) and
* the user presses backspace, line 2's contents will be appended to line 1. In
* this case, any line anchors on line 2 will be removed. One example where this
* might be confusing is if the user selects from (line 1, column 0) to (line 2,
* column 0) and presses delete. This would delete the line anchors on line 2
* with the {@link RemovalStrategy#REMOVE} strategy even though the user has
* logically deleted the text on line 1. There used to be a partial exception to
* this rule to account for this confusin case, but that led to subtle bugs.
*
* Anchors can be positioned through the {@link AnchorManager}.
*
*/
@SuppressWarnings("rawtypes")
public class Anchor implements ReadOnlyAnchor {
/**
* Listener that is notified when an anchor is shifted as a result of a text
* change that affects the line number or column of the anchor. If the anchor
* ignores the column, it will never receive a callback as a result of a
* column shift. The same is true for line numbers.
*
* <p>
* If the anchor moves because of
* {@link AnchorManager#moveAnchor(Anchor, Line, int, int)}, this will not be
* called (see {@link MoveListener}).
*/
public interface ShiftListener extends ShiftListenerImpl<Anchor> {
}
interface ShiftListenerImpl<A extends ReadOnlyAnchor> {
void onAnchorShifted(A anchor);
}
/**
* Listener that is notified when an anchor is moved via
* {@link AnchorManager#moveAnchor(Anchor, Line, int, int)}.
*
* <p>
* If the anchor shifts because of text changes in the document, this will not
* be called (see {@link ShiftListener}.
*/
public interface MoveListener extends MoveListenerImpl<Anchor> {
}
interface MoveListenerImpl<A extends ReadOnlyAnchor> {
void onAnchorMoved(A anchor);
}
/**
* Listener that is notified when an anchor is removed.
*/
public interface RemoveListener extends RemoveListenerImpl<Anchor> {
}
interface RemoveListenerImpl<A> {
void onAnchorRemoved(A anchor);
}
/**
* Defines the behavior for this anchor if the text where it is anchored gets
* deleted.
*/
public enum RemovalStrategy {
/**
* Removes the anchor if the text is deleted. Read the {@link Anchor}
* javadoc for caveats with line anchors.
*/
REMOVE,
/** Shifts the anchor's position if the text is deleted */
SHIFT
}
/**
* This id is guaranteed to have a lower insertion index than any other id
* in the same column.
*/
public static final int ID_FIRST_IN_COLUMN = -1;
/**
* Counter for {@link #id} generation.
*
* <p>
* <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsCompatibility.html">
* Actually</a> it is not a 32-bit integer value, but 64-bit double value.
* So it <a href="http://ecma262-5.com/ELS5_HTML.htm#Section_8.5">can</a>
* address 2^53 positive integer values.
*/
private static int nextId = 0;
private boolean attached = true;
private int column;
private InsertionPlacementStrategy insertionPlacementStrategy =
InsertionPlacementStrategy.DEFAULT;
/**
* The type of this anchor.
*/
private final AnchorType type;
private final int id;
/**
* The client may optionally stuff an opaque, dynamic value into the anchor
*/
private Object value;
private Line line;
private int lineNumber;
private ListenerManager<ShiftListenerImpl<? extends ReadOnlyAnchor>> shiftListenerManager;
private ListenerManager<MoveListenerImpl<? extends ReadOnlyAnchor>> moveListenerManager;
private ListenerManager<RemoveListenerImpl<? extends ReadOnlyAnchor>> removeListenerManager;
private RemovalStrategy removalStrategy = RemovalStrategy.REMOVE;
Anchor(AnchorType type, Line line, int lineNumber, int column) {
this.type = type;
this.id = nextId++;
this.line = line;
this.lineNumber = lineNumber;
this.column = column;
}
@Override
public int getColumn() {
return column;
}
/**
* @return a unique id that can serve as a stable identifier for this anchor.
*/
@Override
public int getId() {
return id;
}
@Override
public AnchorType getType() {
return type;
}
/**
* Update the value stored in this anchor
*
* @param value the opaque value to store
*/
public void setValue(Object value) {
this.value = value;
}
/**
* @param <T>
* @return the value stored in this anchor. Note that type safety is the
* responsibility of the caller.
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getValue() {
return (T) value;
}
@Override
public Line getLine() {
return line;
}
public LineInfo getLineInfo() {
return new LineInfo(line, lineNumber);
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public boolean isLineAnchor() {
return column == AnchorManager.IGNORE_COLUMN;
}
@Override
public RemovalStrategy getRemovalStrategy() {
return removalStrategy;
}
@Override
public boolean hasLineNumber() {
return lineNumber != AnchorManager.IGNORE_LINE_NUMBER;
}
@Override
public boolean isAttached() {
return attached;
}
@Override
public InsertionPlacementStrategy getInsertionPlacementStrategy() {
return insertionPlacementStrategy;
}
public void setInsertionPlacementStrategy(InsertionPlacementStrategy insertionPlacementStrategy) {
this.insertionPlacementStrategy = insertionPlacementStrategy;
}
@SuppressWarnings("unchecked")
@Override
public ListenerRegistrar<ReadOnlyAnchor.ShiftListener> getReadOnlyShiftListenerRegistrar() {
return (ListenerRegistrar) getShiftListenerRegistrar();
}
@SuppressWarnings("unchecked")
public ListenerRegistrar<ShiftListener> getShiftListenerRegistrar() {
if (shiftListenerManager == null) {
shiftListenerManager = ListenerManager.create();
}
return (ListenerRegistrar) shiftListenerManager;
}
@SuppressWarnings("unchecked")
@Override
public ListenerRegistrar<ReadOnlyAnchor.MoveListener> getReadOnlyMoveListenerRegistrar() {
return (ListenerRegistrar) getMoveListenerRegistrar();
}
@SuppressWarnings("unchecked")
public ListenerRegistrar<MoveListener> getMoveListenerRegistrar() {
if (moveListenerManager == null) {
moveListenerManager = ListenerManager.create();
}
return (ListenerRegistrar) moveListenerManager;
}
@SuppressWarnings("unchecked")
@Override
public ListenerRegistrar<ReadOnlyAnchor.RemoveListener> getReadOnlyRemoveListenerRegistrar() {
return (ListenerRegistrar) getRemoveListenerRegistrar();
}
@SuppressWarnings("unchecked")
public ListenerRegistrar<RemoveListener> getRemoveListenerRegistrar() {
if (removeListenerManager == null) {
removeListenerManager = ListenerManager.create();
}
return (ListenerRegistrar) removeListenerManager;
}
public void setRemovalStrategy(RemovalStrategy removalStrategy) {
this.removalStrategy = removalStrategy;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getType().toString());
sb.append(":").append(getId());
sb.append(" (").append(lineNumber).append(',').append(column).append(")");
sb.append("[").append(value).append("]");
sb.append(": ");
String lineStr = line.toString();
if (column <= lineStr.length()) {
int split = Math.max(0, Math.min(column, lineStr.length()));
sb.append(lineStr.subSequence(0, split));
sb.append("^");
sb.append(lineStr.substring(split));
} else {
sb.append(lineStr);
for (int i = 0, n = column - lineStr.length(); i < n; i++) {
sb.append(" ");
}
sb.append("^ (WARNING: the anchor is out-of-bounds)");
}
return sb.toString();
}
void dispatchShifted() {
if (shiftListenerManager != null) {
shiftListenerManager
.dispatch(new Dispatcher<Anchor.ShiftListenerImpl<? extends ReadOnlyAnchor>>() {
@SuppressWarnings("unchecked")
@Override
public void dispatch(ShiftListenerImpl listener) {
listener.onAnchorShifted(Anchor.this);
}
});
}
}
public void dispatchMoved() {
if (moveListenerManager != null) {
moveListenerManager
.dispatch(new Dispatcher<Anchor.MoveListenerImpl<? extends ReadOnlyAnchor>>() {
@SuppressWarnings("unchecked")
@Override
public void dispatch(MoveListenerImpl listener) {
listener.onAnchorMoved(Anchor.this);
}
});
}
}
void detach() {
this.attached = false;
}
void dispatchRemoved() {
if (removeListenerManager != null) {
removeListenerManager
.dispatch(new Dispatcher<Anchor.RemoveListenerImpl<? extends ReadOnlyAnchor>>() {
@SuppressWarnings("unchecked")
@Override
public void dispatch(RemoveListenerImpl listener) {
listener.onAnchorRemoved(Anchor.this);
}
});
}
}
/**
* Make sure all calls to this method are surrounded with removal and
* re-addition to the list(s) it belongs in!
*/
void setColumnWithoutDispatch(int column) {
this.column = column;
}
void setLineWithoutDispatch(Line line, int lineNumber) {
checkArgument(hasLineNumber() == (lineNumber != AnchorManager.IGNORE_LINE_NUMBER));
this.line = line;
this.lineNumber = lineNumber;
}
@Override
public boolean hasColumn() {
return column != AnchorManager.IGNORE_COLUMN;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/InsertionPlacementStrategy.java | shared/src/main/java/com/google/collide/shared/document/anchor/InsertionPlacementStrategy.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.shared.document.Line;
/**
* A strategy that determines where an anchor will be placed after a text
* insertion at the anchor's position.
*
* For line anchors, this strategy is consulted when a newline is inserted
* anywhere on the anchor's line. For column anchors, this strategy is consulted
* when a character is inserted at the anchor's column.
*
*/
public interface InsertionPlacementStrategy {
/**
* Constants for the two positions that are possible placement targets.
*/
public enum Placement {
EARLIER, LATER
}
/**
* Always stays at the earlier position.
*/
public static final InsertionPlacementStrategy EARLIER =
new InsertionPlacementStrategy() {
@Override
public Placement determineForInsertion(Anchor anchor, Line line, int column) {
return Placement.EARLIER;
}
};
/**
* Always moves to the later position.
*/
public static final InsertionPlacementStrategy LATER =
new InsertionPlacementStrategy() {
@Override
public Placement determineForInsertion(Anchor anchor, Line line, int column) {
return Placement.LATER;
}
};
/**
* The default behavior for line anchors is to stay on the line,
* and the default behavior for normal anchors is to move with
* the insertion.
*/
public static final InsertionPlacementStrategy DEFAULT =
new InsertionPlacementStrategy() {
@Override
public Placement determineForInsertion(Anchor anchor, Line line, int column) {
InsertionPlacementStrategy currentStrategy =
anchor.isLineAnchor() ? EARLIER : LATER;
return currentStrategy.determineForInsertion(anchor, line, column);
}
};
Placement determineForInsertion(Anchor anchor, Line line, int column);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/AnchorDeferredDispatcher.java | shared/src/main/java/com/google/collide/shared/document/anchor/AnchorDeferredDispatcher.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
/**
* Helper class to defer the dispatching of anchor callbacks until state has
* stabilized.
*/
class AnchorDeferredDispatcher {
private JsonArray<Anchor> shiftedAnchors;
private JsonArray<Anchor> removedAnchors;
void deferDispatchShifted(Anchor anchor) {
if (removedAnchors != null && removedAnchors.contains(anchor)) {
// Anchor has been removed, don't dispatch shift
return;
}
if (shiftedAnchors == null) {
shiftedAnchors = JsonCollections.createArray();
}
shiftedAnchors.add(anchor);
}
void deferDispatchRemoved(Anchor anchor) {
if (removedAnchors == null) {
removedAnchors = JsonCollections.createArray();
}
removedAnchors.add(anchor);
// Anchor has been removed, don't dispatch these
if (shiftedAnchors != null) {
shiftedAnchors.remove(anchor);
}
}
JsonArray<Anchor> getShiftedAnchors() {
return shiftedAnchors;
}
void dispatch() {
if (shiftedAnchors != null) {
for (int i = 0, n = shiftedAnchors.size(); i < n; i++) {
shiftedAnchors.get(i).dispatchShifted();
}
}
if (removedAnchors != null) {
for (int i = 0, n = removedAnchors.size(); i < n; i++) {
removedAnchors.get(i).dispatchRemoved();
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/AnchorList.java | shared/src/main/java/com/google/collide/shared/document/anchor/AnchorList.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.shared.util.SortedList;
import com.google.common.annotations.VisibleForTesting;
/**
* List with anchor-specific optimizations. This class assumes all the anchors
* in the list will be on the same line.
*/
@VisibleForTesting
public class AnchorList extends SortedList<Anchor> {
private static class Comparator implements SortedList.Comparator<Anchor> {
@Override
public int compare(Anchor a, Anchor b) {
int comparison = a.getColumn() - b.getColumn();
if (comparison == 0) {
comparison = (a.getId() > b.getId()) ? 1 : (a.getId() < b.getId()) ? -1 : 0;
}
return comparison;
}
}
private static class OneWayComparator implements SortedList.OneWayComparator<Anchor> {
private int column;
private int id;
@Override
public int compareTo(Anchor o) {
int comparison = column - o.getColumn();
if (comparison == 0) {
comparison = (id > o.getId()) ? 1 : (id < o.getId()) ? -1 : 0;
}
return comparison;
}
}
private static final Comparator COMPARATOR = new Comparator();
private final OneWayComparator oneWayComparator = new OneWayComparator();
public AnchorList() {
super(COMPARATOR);
}
// TODO: second parameter is always -1. Remove?
public int findInsertionIndex(int columnNumber, int id) {
oneWayComparator.column = columnNumber;
oneWayComparator.id = id;
return findInsertionIndex(oneWayComparator);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(get(i).toString());
sb.append("\n");
}
return sb.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/AnchorUtils.java | shared/src/main/java/com/google/collide/shared/document/anchor/AnchorUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.shared.document.DocumentMutator;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.document.util.LineUtils;
import com.google.collide.shared.document.util.PositionUtils;
import com.google.common.base.Preconditions;
/**
* Utility methods relating to anchors.
*/
public final class AnchorUtils {
/**
* Returns a negative number if {@code a} is earlier than {@code b}, a
* positive number if the inverse, and zero if they are positioned the same.
*
* Comparing an anchor that ignores either a line number or column to another
* anchor that does not ignore that same property is invalid and will have
* strange results.
*
* @param a an anchor with both a line number and a column
* @param b an anchor with both a line number and a column
*/
public static int compare(Anchor a, Anchor b) {
assert (a.hasLineNumber() == b.hasLineNumber());
assert ((a.getColumn() == AnchorManager.IGNORE_COLUMN) == (b.getColumn() ==
AnchorManager.IGNORE_COLUMN));
return LineUtils.comparePositions(a.getLineNumber(), a.getColumn(), b.getLineNumber(),
b.getColumn());
}
/**
* @param a an anchor with both a line number and a column
* @see #compare(Anchor, Anchor)
*/
public static int compare(Anchor a, int bLineNumber, int bColumn) {
assert a.hasLineNumber();
assert (a.getColumn() != AnchorManager.IGNORE_COLUMN);
return LineUtils.comparePositions(a.getLineNumber(), a.getColumn(), bLineNumber, bColumn);
}
/**
* Replace all text between line anchors {@code begin} and {@code end}
* with {@code text}.
*/
public static void setTextBetweenAnchors(String text, Anchor begin, Anchor end,
DocumentMutator documentMutator) {
Preconditions.checkArgument(begin.isAttached(), "begin must be attached");
Preconditions.checkArgument(begin.isLineAnchor(), "begin must be line anchor");
Preconditions.checkArgument(end.isLineAnchor(), "end must be line anchor");
Preconditions.checkArgument(end.isAttached(), "end must be attached");
Preconditions.checkArgument(
begin.getLineNumber() <= end.getLineNumber(), "begin line below end line");
// TODO: Fix same-line text replacement.
LineInfo topLineInfo = begin.getLineInfo();
Line topLine = topLineInfo.line();
Line bottomLine = end.getLine();
/*
* At the very end of the document, the text being inserted will have a
* trailing "\n" that needs to be deleted to avoid an empty line at the
* end.
*/
boolean deleteEndingNewline = !bottomLine.getText().endsWith("\n");
if (!text.endsWith("\n")) {
text = text + "\n";
}
// Delete all of the existing text, minus the last newline.
int deleteCount =
LineUtils.getTextCount(topLine, 0, bottomLine, bottomLine.getText().length() -
(deleteEndingNewline ? 0 : 1));
documentMutator.insertText(topLine, topLineInfo.number(), 0, text, false);
Position endOfInsertion =
PositionUtils.getPosition(topLine, topLineInfo.number(), 0, text.length() - 1);
documentMutator.deleteText(endOfInsertion.getLine(), endOfInsertion.getColumn(), deleteCount);
}
private AnchorUtils() {
}
public static void visitAnchorsOnLine(Line line, AnchorManager.AnchorVisitor visitor) {
AnchorList anchors = AnchorManager.getAnchorsOrNull(line);
if (anchors == null) {
return;
}
for (int i = 0; i < anchors.size(); i++) {
visitor.visitAnchor(anchors.get(i));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/ReadOnlyAnchor.java | shared/src/main/java/com/google/collide/shared/document/anchor/ReadOnlyAnchor.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy;
import com.google.collide.shared.util.ListenerRegistrar;
/**
* A read-only interface to {@link Anchor}.
*/
public interface ReadOnlyAnchor {
/**
* @see Anchor.ShiftListener
*/
public interface ShiftListener extends Anchor.ShiftListenerImpl<ReadOnlyAnchor> {
}
/**
* @see Anchor.MoveListener
*/
public interface MoveListener extends Anchor.MoveListenerImpl<ReadOnlyAnchor> {
}
/**
* @see Anchor.RemoveListener
*/
public interface RemoveListener extends Anchor.RemoveListenerImpl<ReadOnlyAnchor> {
}
int getColumn();
int getId();
<T> T getValue();
AnchorType getType();
Line getLine();
int getLineNumber();
boolean isLineAnchor();
RemovalStrategy getRemovalStrategy();
boolean hasLineNumber();
boolean isAttached();
InsertionPlacementStrategy getInsertionPlacementStrategy();
ListenerRegistrar<ShiftListener> getReadOnlyShiftListenerRegistrar();
ListenerRegistrar<MoveListener> getReadOnlyMoveListenerRegistrar();
ListenerRegistrar<RemoveListener> getReadOnlyRemoveListenerRegistrar();
boolean hasColumn();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/document/anchor/LineAnchorList.java | shared/src/main/java/com/google/collide/shared/document/anchor/LineAnchorList.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.document.anchor;
import com.google.collide.shared.util.SortedList;
/**
* List for line anchors with specific optimizations for line anchors.
*/
public class LineAnchorList extends SortedList<Anchor> {
private static class Comparator implements SortedList.Comparator<Anchor> {
@Override
public int compare(Anchor a, Anchor b) {
return a.getLineNumber() - b.getLineNumber();
}
}
private static class OneWayComparator implements SortedList.OneWayComparator<Anchor> {
private int lineNumber;
@Override
public int compareTo(Anchor o) {
return lineNumber - o.getLineNumber();
}
}
private static final Comparator COMPARATOR = new Comparator();
private final OneWayComparator oneWayComparator = new OneWayComparator();
public LineAnchorList() {
super(COMPARATOR);
}
public int findInsertionIndex(int lineNumber) {
oneWayComparator.lineNumber = lineNumber;
return findInsertionIndex(oneWayComparator);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/Inverter.java | shared/src/main/java/com/google/collide/shared/ot/Inverter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.shared.JsonArray;
/**
* Inverts document operations such that A composed with the inverse of A is an
* identity document operation.
*
*/
public class Inverter {
/**
* Inverts the given document operation.
*/
public static DocOp invert(DocOpFactory factory, DocOp docOp) {
DocOp invertedDocOp = factory.createDocOp();
JsonArray<DocOpComponent> invertedDocOpComponents = invertedDocOp.getComponents();
JsonArray<DocOpComponent> components = docOp.getComponents();
for (int i = 0, n = components.size(); i < n; i++) {
invertedDocOpComponents.add(invertComponent(factory, components.get(i)));
}
return invertedDocOp;
}
private static DocOpComponent invertComponent(DocOpFactory factory, DocOpComponent component) {
switch (component.getType()) {
case DocOpComponent.Type.INSERT:
return factory.createDelete(((Insert) component).getText());
case DocOpComponent.Type.DELETE:
return factory.createInsert(((Insert) component).getText());
default:
return component;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/PositionTransformer.java | shared/src/main/java/com/google/collide/shared/ot/PositionTransformer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
/**
* A class to transform a document position with a document operation so that
* the the relative position is maintained even after the document operation is
* applied.
*/
public class PositionTransformer {
private class Transformer implements DocOpCursor {
private int docOpColumn;
private int docOpLineNumber;
@Override
public void delete(String text) {
if (lineNumber == docOpLineNumber) {
if (column >= docOpColumn) {
// We need to update the position because the deletion is before it
int columnOfLastDeletedChar = docOpColumn + text.length() - 1;
if (column <= columnOfLastDeletedChar) {
/*
* The position is inside the deleted region, but we want to keep it
* alive, so it's final position is the column where the delete
* collapses to
*/
column = docOpColumn;
} else {
/*
* The position is after the deletion region, offset the position to
* account for the delete
*/
column -= text.length();
}
}
} else if (text.endsWith("\n") && lineNumber == docOpLineNumber + 1) {
/*
* This line and the next are being joined and our position is on the
* next line. Bring the position onto this line.
*/
lineNumber = docOpLineNumber;
column += docOpColumn;
} else if (text.endsWith("\n") && lineNumber > docOpLineNumber) {
lineNumber--;
}
}
@Override
public void insert(String text) {
if (lineNumber == docOpLineNumber) {
if (column >= docOpColumn) {
if (text.endsWith("\n")) {
// Splitting the lines
lineNumber++;
column = column - docOpColumn;
} else {
column += text.length();
}
}
} else if (lineNumber > docOpLineNumber && text.endsWith("\n")) {
lineNumber++;
}
if (text.endsWith("\n")) {
skipDocOpLines(1);
} else {
docOpColumn += text.length();
}
}
@Override
public void retain(int count, boolean hasTrailingNewline) {
if (hasTrailingNewline) {
skipDocOpLines(1);
} else {
docOpColumn += count;
}
}
@Override
public void retainLine(int lineCount) {
skipDocOpLines(lineCount);
}
private void skipDocOpLines(int lineCount) {
docOpLineNumber += lineCount;
docOpColumn = 0;
}
}
private int column;
private int lineNumber;
public PositionTransformer(int lineNumber, int column) {
this.column = column;
this.lineNumber = lineNumber;
}
public void transform(DocOp op) {
Transformer transformer = new Transformer();
DocOpUtils.accept(op, transformer);
}
public int getColumn() {
return column;
}
public int getLineNumber() {
return lineNumber;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/OperationPair.java | shared/src/main/java/com/google/collide/shared/ot/OperationPair.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
/**
* A pair of document operations.
*/
public final class OperationPair {
private final DocOp clientOp;
private final DocOp serverOp;
/**
* Constructs an OperationPair from a client operation and a server operation.
*
* @param clientOp The client's operation.
* @param serverOp The server's operation.
*/
public OperationPair(DocOp clientOp, DocOp serverOp) {
this.clientOp = clientOp;
this.serverOp = serverOp;
}
/**
* @return The client's operation.
*/
public DocOp clientOp() {
return clientOp;
}
/**
* @return The server's operation.
*/
public DocOp serverOp() {
return serverOp;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/DocOpBuilder.java | shared/src/main/java/com/google/collide/shared/ot/DocOpBuilder.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.shared.DocOpFactory;
/**
* Helper to create document operations via a builder pattern.
*
*/
public class DocOpBuilder {
private DocOpCapturer capturer;
private final Runnable createCapturer;
public DocOpBuilder(final DocOpFactory factory, final boolean shouldCompact) {
createCapturer = new Runnable() {
@Override
public void run() {
capturer = new DocOpCapturer(factory, shouldCompact);
}
};
createCapturer.run();
}
/**
* Builds and returns the document operation, and prepares the builder for
* another building sequence.
*/
public DocOp build() {
DocOp op = capturer.getDocOp();
createCapturer.run();
return op;
}
/**
* Adds a delete component for the given {@code text} to the document
* operation being built.
*/
public DocOpBuilder delete(String text) {
capturer.delete(text);
return this;
}
/**
* Adds an insert component for the given {@code text} to the document
* operation being built.
*/
public DocOpBuilder insert(String text) {
capturer.insert(text);
return this;
}
/**
* Adds a retain component for the given number of characters to the document
* operation being built.
*/
public DocOpBuilder retain(int count, boolean hasTrailingNewline) {
capturer.retain(count, hasTrailingNewline);
return this;
}
/**
* Adds a retain line component for the given number of lines to the document
* operation being built.
*/
public DocOpBuilder retainLine(int lineCount) {
capturer.retainLine(lineCount);
return this;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/Transformer.java | shared/src/main/java/com/google/collide/shared/ot/Transformer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.shared.JsonArray;
import com.google.common.base.Preconditions;
/*
* Influenced by Wave's Transformer and Composer classes. Generally, we can't
* use Wave's because we introduce the RetainLine doc op component, and don't
* support a few extra components that Wave has. We didn't fork Wave's
* Transformer because its design wasn't amenable to the changes required by
* RetainLine. Instead, we wrote this from scratch to be able to handle that
* component easily.
*
* The operations being transformed are A and B. Both are intended to be applied
* to the same document. The output of the transformation will be A' and B'. For
* example, A' will be A transformed so it can be cleanly applied after B has
* been applied.
*
* The Processor class maintains the state for a document operation component.
* Each method in the Processor handles a component from the other document
* operation. As each method is executed, it outputs to its output document
* operation and to the other processor's output document operation. It also
* marks the general state into the ProcessorResult.
*/
/**
* Transforms document operations for the code editor.
*
*/
public class Transformer {
/**
* Exception that is thrown when there is a problem transforming two document
* operations.
*/
public static class TransformException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 5029139051395933161L;
public TransformException(String message, Throwable cause) {
super(message, cause);
}
}
private static class DeleteProcessor extends Processor {
static String performDelete(DocOpCapturer output, String text, int deleteLength,
ProcessorResult result) {
output.delete(text.substring(0, deleteLength));
if (text.length() == deleteLength) {
result.markMyStateFinished();
}
return text.substring(deleteLength);
}
private String text;
DeleteProcessor(DocOpCapturer output, String text) {
super(output);
this.text = text;
}
@Override
void handleOtherDelete(DeleteProcessor other, ProcessorResult result) {
/*
* The transformed op shouldn't know about the deletes, so don't output
* anything
*/
if (text.length() == other.text.length()) {
result.markMyStateFinished();
result.markOtherStateFinished();
} else if (text.length() < other.text.length()) {
other.text = other.text.substring(text.length());
result.markMyStateFinished();
} else {
text = text.substring(other.text.length());
result.markOtherStateFinished();
}
}
@Override
void handleOtherFinished(Processor other, ProcessorResult result) {
throw new IllegalStateException("Cannot delete if the other side is finished");
}
@Override
void handleOtherInsert(InsertProcessor other, ProcessorResult result) {
/*
* Look at comments in InsertProcessor on why it needs to always handle
* these components
*/
result.flip();
other.handleOtherDelete(this, result);
}
@Override
void handleOtherRetain(RetainProcessor other, ProcessorResult result) {
/*
* The other transformed op won't have anything to retain, so output
* nothing for it. Our transformed op needs to delete though, since the
* other original op is just retaining.
*/
int minCount = Math.min(text.length(), other.count);
other.count -= minCount;
text = performDelete(output, text, minCount, result);
if (other.count == 0) {
result.markOtherStateFinished();
}
}
@Override
void handleOtherRetainLine(RetainLineProcessor other, ProcessorResult result) {
// Let RetainLineProcessor handle this
result.flip();
other.handleOtherDelete(this, result);
}
}
private static class FinishedProcessor extends Processor {
FinishedProcessor(DocOpCapturer output) {
super(output);
}
@Override
void handleOtherDelete(DeleteProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherFinished(this, result);
}
@Override
void handleOtherFinished(Processor other, ProcessorResult result) {
throw new IllegalStateException("Both should not be finished");
}
@Override
void handleOtherInsert(InsertProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherFinished(this, result);
}
@Override
void handleOtherRetain(RetainProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherFinished(this, result);
}
@Override
void handleOtherRetainLine(RetainLineProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherFinished(this, result);
}
}
private static class InsertProcessor extends Processor {
private static void performInsert(DocOpCapturer output, DocOpCapturer otherOutput,
String text, ProcessorResult result) {
output.insert(text);
boolean endsWithNewline = text.endsWith(NEWLINE);
otherOutput.retain(text.length(), endsWithNewline);
if (endsWithNewline) {
result.markMyCurrentComponentInsertOfNewline();
}
result.markMyStateFinished();
}
private String text;
InsertProcessor(DocOpCapturer output, String text) {
super(output);
this.text = text;
}
@Override
void handleOtherDelete(DeleteProcessor other, ProcessorResult result) {
// Handle insertion
performInsert(output, other.output, text, result);
// The delete will be handled by the successor for this processor
}
@Override
void handleOtherFinished(Processor other, ProcessorResult result) {
performInsert(output, other.output, text, result);
}
@Override
void handleOtherInsert(InsertProcessor other, ProcessorResult result) {
/*
* Instead of inserting both, we only insert one so contiguous insertions
* by one side will end up being contiguous in the transformed op.
* (Otherwise, you get interleaved I, RL, I, RL, ...)
*/
performInsert(output, other.output, text, result);
}
@Override
void handleOtherRetain(RetainProcessor other, ProcessorResult result) {
performInsert(output, other.output, text, result);
// The retain will be handled by the successor for this processor
}
@Override
void handleOtherRetainLine(RetainLineProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherInsert(this, result);
}
}
private abstract static class Processor {
final DocOpCapturer output;
Processor(DocOpCapturer output) {
this.output = output;
}
abstract void handleOtherDelete(DeleteProcessor other, ProcessorResult result);
abstract void handleOtherFinished(Processor other, ProcessorResult result);
abstract void handleOtherInsert(InsertProcessor other, ProcessorResult result);
abstract void handleOtherRetain(RetainProcessor other, ProcessorResult result);
abstract void handleOtherRetainLine(RetainLineProcessor other, ProcessorResult result);
}
private static class ProcessorFactory implements DocOpCursor {
private DocOpCapturer curOutput;
private Processor returnProcessor;
@Override
public void delete(String text) {
returnProcessor = new DeleteProcessor(curOutput, text);
}
@Override
public void insert(String text) {
returnProcessor = new InsertProcessor(curOutput, text);
}
@Override
public void retain(int count, boolean hasTrailingNewline) {
returnProcessor = new RetainProcessor(curOutput, count, hasTrailingNewline);
}
@Override
public void retainLine(int lineCount) {
returnProcessor = new RetainLineProcessor(curOutput, lineCount);
}
Processor create(DocOpCapturer output, DocOpComponent component) {
curOutput = output;
DocOpUtils.acceptComponent(component, this);
return returnProcessor;
}
}
private static class ProcessorResult {
private boolean isMyStateFinished;
private boolean isOtherStateFinished;
/*
* We need to know the value of the previous component, but if we only tracked that then reset
* would clear it.
*/
private boolean isMyCurrentComponentInsertOfNewline;
private boolean isOtherCurrentComponentInsertOfNewline;
private boolean isMyPreviousComponentInsertOfNewline;
private boolean isOtherPreviousComponentInsertOfNewline;
private boolean isFlipped;
private ProcessorResult() {
}
/**
* Flips the "my" and "other" states. This should be called before one
* processor is handing over execution to the other processor, including
* passing this instance to the other processor.
*/
void flip() {
boolean origMyStateFinished = isMyStateFinished;
isMyStateFinished = isOtherStateFinished;
isOtherStateFinished = origMyStateFinished;
boolean origMyPreviousComponentInsertOfNewline = isMyPreviousComponentInsertOfNewline;
isMyPreviousComponentInsertOfNewline = isOtherPreviousComponentInsertOfNewline;
isOtherPreviousComponentInsertOfNewline = origMyPreviousComponentInsertOfNewline;
boolean origMyCurrentComponentInsertOfNewline = isMyCurrentComponentInsertOfNewline;
isMyCurrentComponentInsertOfNewline = isOtherCurrentComponentInsertOfNewline;
isOtherCurrentComponentInsertOfNewline = origMyCurrentComponentInsertOfNewline;
isFlipped = !isFlipped;
}
void markMyStateFinished() {
if (!isFlipped) {
isMyStateFinished = true;
} else {
isOtherStateFinished = true;
}
}
void markOtherStateFinished() {
if (!isFlipped) {
isOtherStateFinished = true;
} else {
isMyStateFinished = true;
}
}
void markMyCurrentComponentInsertOfNewline() {
if (!isFlipped) {
isMyCurrentComponentInsertOfNewline = true;
} else {
isOtherCurrentComponentInsertOfNewline = true;
}
}
void markOtherCurrentComponentInsertOfNewline() {
if (!isFlipped) {
isOtherCurrentComponentInsertOfNewline = true;
} else {
isMyCurrentComponentInsertOfNewline = true;
}
}
void reset() {
isMyPreviousComponentInsertOfNewline = isMyCurrentComponentInsertOfNewline;
isOtherPreviousComponentInsertOfNewline = isOtherCurrentComponentInsertOfNewline;
isFlipped = isMyStateFinished = isOtherStateFinished =
isMyCurrentComponentInsertOfNewline = isOtherCurrentComponentInsertOfNewline = false;
}
}
private static class RetainLineProcessor extends Processor {
private int lineCount;
/**
* In the event that we need to expand the retain line, we need to know
* exactly how many retains it should be expanded to. This tracks that
* number.
*/
private int substituteRetainCount;
RetainLineProcessor(DocOpCapturer output, int lineCount) {
super(output);
this.lineCount = lineCount;
}
@Override
void handleOtherDelete(DeleteProcessor other, ProcessorResult result) {
other.output.delete(other.text);
if (other.text.endsWith(NEWLINE)) {
handleOtherLineEnd(false, result);
} else {
// My transformed op won't see the delete, so do nothing
}
result.markOtherStateFinished();
}
@Override
void handleOtherFinished(Processor other, ProcessorResult result) {
Preconditions.checkState(
lineCount == 1, "Cannot retain more than one line if other side is finished");
if (result.isMyPreviousComponentInsertOfNewline) {
other.output.retainLine(1);
}
lineCount = 0;
output.retainLine(1);
result.markMyStateFinished();
}
@Override
void handleOtherInsert(InsertProcessor other, ProcessorResult result) {
other.output.insert(other.text);
if (other.text.endsWith(NEWLINE)) {
// Retain the line just inserted by other
lineCount++;
handleOtherLineEnd(true, result);
result.markOtherCurrentComponentInsertOfNewline();
} else {
substituteRetainCount += other.text.length();
}
result.markOtherStateFinished();
}
void handleOtherLineEnd(boolean canUseRetainLine, ProcessorResult result) {
if (canUseRetainLine) {
output.retainLine(1);
} else {
if (substituteRetainCount > 0) {
output.retain(substituteRetainCount, false);
}
}
lineCount--;
substituteRetainCount = 0;
if (lineCount == 0) {
result.markMyStateFinished();
}
}
@Override
void handleOtherRetain(RetainProcessor other, ProcessorResult result) {
other.output.retain(other.count, other.hasTrailingNewline);
substituteRetainCount += other.count;
if (other.hasTrailingNewline) {
handleOtherLineEnd(true, result);
}
result.markOtherStateFinished();
}
@Override
void handleOtherRetainLine(RetainLineProcessor other, ProcessorResult result) {
int minLineCount = Math.min(lineCount, other.lineCount);
output.retainLine(minLineCount);
lineCount -= minLineCount;
other.output.retainLine(minLineCount);
other.lineCount -= minLineCount;
if (lineCount == 0) {
result.markMyStateFinished();
}
if (other.lineCount == 0) {
result.markOtherStateFinished();
}
}
}
private static class RetainProcessor extends Processor {
static int performRetain(DocOpCapturer output, int fullCount, int retainCount,
boolean hasTrailingNewline, ProcessorResult result, boolean useOtherInResult) {
output.retain(retainCount, fullCount == retainCount ? hasTrailingNewline : false);
if (retainCount == fullCount) {
if (useOtherInResult) {
result.markOtherStateFinished();
} else {
result.markMyStateFinished();
}
}
return fullCount - retainCount;
}
private int count;
private final boolean hasTrailingNewline;
RetainProcessor(DocOpCapturer output, int count, boolean hasTrailingNewline) {
super(output);
this.count = count;
this.hasTrailingNewline = hasTrailingNewline;
}
@Override
void handleOtherDelete(DeleteProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherRetain(this, result);
}
@Override
void handleOtherFinished(Processor other, ProcessorResult result) {
throw new IllegalStateException("Cannot retain if other side is finished");
}
@Override
void handleOtherInsert(InsertProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherRetain(this, result);
}
@Override
void handleOtherRetain(RetainProcessor other, ProcessorResult result) {
int minCount = Math.min(count, other.count);
count = performRetain(output, count, minCount, hasTrailingNewline, result, false);
other.count =
performRetain(other.output, other.count, minCount, other.hasTrailingNewline, result,
true);
}
@Override
void handleOtherRetainLine(RetainLineProcessor other, ProcessorResult result) {
result.flip();
other.handleOtherRetain(this, result);
}
}
private static final String NEWLINE = "\n";
private static final ProcessorFactory PROCESSOR_FACTORY = new ProcessorFactory();
public static OperationPair transform(DocOpFactory factory, DocOp clientOp, DocOp serverOp)
throws TransformException {
try {
return new Transformer(factory).transformImpl(clientOp, serverOp);
} catch (Throwable t) {
throw new TransformException("Could not transform doc ops:\nClient: "
+ DocOpUtils.toString(clientOp, false) + "\nServer: "
+ DocOpUtils.toString(serverOp, false) + "\n", t);
}
}
private static void dispatchProcessor(Processor a, Processor b, ProcessorResult result) {
if (b instanceof DeleteProcessor) {
a.handleOtherDelete((DeleteProcessor) b, result);
} else if (b instanceof InsertProcessor) {
a.handleOtherInsert((InsertProcessor) b, result);
} else if (b instanceof RetainProcessor) {
a.handleOtherRetain((RetainProcessor) b, result);
} else if (b instanceof RetainLineProcessor) {
a.handleOtherRetainLine((RetainLineProcessor) b, result);
} else if (b instanceof FinishedProcessor) {
a.handleOtherFinished(b, result);
}
}
private final DocOpFactory factory;
private Transformer(DocOpFactory factory) {
this.factory = factory;
}
private OperationPair transformImpl(DocOp clientOp, DocOp serverOp) {
/*
* These capturers will create the respective side's doc op which will be
* transformed from the respective side's original doc op to apply to the
* document *after* the other side's original doc op.
*/
DocOpCapturer clientOutput = new DocOpCapturer(factory, true);
DocOpCapturer serverOutput = new DocOpCapturer(factory, true);
JsonArray<DocOpComponent> clientComponents = clientOp.getComponents();
JsonArray<DocOpComponent> serverComponents = serverOp.getComponents();
int clientIndex = 0;
int serverIndex = 0;
boolean clientComponentsFinished = false;
boolean serverComponentsFinished = false;
Processor client = null;
Processor server = null;
ProcessorResult result = new ProcessorResult();
while (!clientComponentsFinished || !serverComponentsFinished) {
if (client == null) {
if (clientIndex < clientComponents.size()) {
client = PROCESSOR_FACTORY.create(clientOutput, clientComponents.get(clientIndex++));
} else {
client = new FinishedProcessor(clientOutput);
clientComponentsFinished = true;
}
}
if (server == null) {
if (serverIndex < serverComponents.size()) {
server = PROCESSOR_FACTORY.create(serverOutput, serverComponents.get(serverIndex++));
} else {
server = new FinishedProcessor(serverOutput);
serverComponentsFinished = true;
}
}
if (!clientComponentsFinished || !serverComponentsFinished) {
dispatchProcessor(client, server, result);
}
if (result.isMyStateFinished) {
client = null;
}
if (result.isOtherStateFinished) {
server = null;
}
result.reset();
}
return new OperationPair(clientOutput.getDocOp(), serverOutput.getDocOp());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/DocOpSink.java | shared/src/main/java/com/google/collide/shared/ot/DocOpSink.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
/**
* Consumer for document operations.
*/
public interface DocOpSink {
void consume(DocOp docOp);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/Composer.java | shared/src/main/java/com/google/collide/shared/ot/Composer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import java.util.Iterator;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.shared.JsonArray;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/*
* Derived from Wave's Composer class. We forked it because we have new doc op
* components, and removed some of Wave's that aren't applicable.
*
* The operations being composed are A and B. A occurs before B, so B must
* account for A's changes.
*
* Each of the State subclasses model a possible state during the composing of
* the two doc ops. This structure assumes that one of the doc op's current
* components is longer lived (for example, spans more characters) than the
* other doc op's current component. Given this, each State subclass is just
* modeling all the possible combinations. For example, the subclass
* ProcessingAForBRetain's responsibility is to keep the current state of the
* retain component from the B doc op, and process components from A. As soon as
* all of the characters being retained by the componenet from B is finished,
* the state will likely flip-flop to ProcessingBForAXxx.
*/
/**
* Composes document operations for the code editor.
*/
public class Composer {
/**
* Exception thrown when a composition fails.
*/
public static class ComposeException extends Exception {
/**
*
*/
private static final long serialVersionUID = 5790109173803687121L;
private ComposeException(String message, Exception e) {
super(message, e);
}
}
/**
* Runtime exception used internally by this class. The processing states
* implement {@link DocOpCursor} which does not throw these exceptions, so we
* model them as runtime exceptions and have an outer catch around the entire
* transformation that converts these to the public exception.
*/
private static class InternalComposeException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -8754601577190652698L;
private InternalComposeException(String message) {
super(message);
}
private InternalComposeException(String message, Throwable t) {
super(message, t);
}
}
/**
* Base class for any state that is processing A's components.
*/
private abstract class ProcessingA extends State {
/**
* Since A occurs before B, B won't have any components that align with A's
* delete (B doesn't even know about the text that A deleted.) So, we pass
* through the delete without ever touching any of B's components.
*/
@Override
public void delete(String aDeleteText) {
output.delete(aDeleteText);
}
@Override
boolean isProcessingB() {
return false;
}
}
/**
* State that models an outstanding delete component from B.
*/
private class ProcessingAForBDelete extends ProcessingA {
private String bDeleteText;
ProcessingAForBDelete(String bDeleteText) {
this.bDeleteText = bDeleteText;
}
@Override
public void insert(String aInsertText) {
if (aInsertText.length() <= bDeleteText.length()) {
cancel(aInsertText.length());
} else {
curState = new ProcessingBForAInsert(aInsertText.substring(bDeleteText.length()));
}
}
@Override
public void retain(int aRetainCount, boolean aRetainHasTrailingNewline) {
if (aRetainCount <= bDeleteText.length()) {
output.delete(bDeleteText.substring(0, aRetainCount));
cancel(aRetainCount);
} else {
output.delete(bDeleteText);
curState =
new ProcessingBForARetain(aRetainCount - bDeleteText.length(),
aRetainHasTrailingNewline);
}
}
@Override
public void retainLine(int aRetainLineCount) {
// B is modifying a previously retained line
output.delete(bDeleteText);
if (bDeleteText.endsWith("\n") || isLastComponentOfB) {
// B's deletion finishes a line, so A's retain line is affected
if (aRetainLineCount == 1) {
curState = defaultState;
} else {
curState = new ProcessingBForARetainLine(aRetainLineCount - 1);
}
} else {
/*
* B's deletion is part of a line without finishing it, so A's retain
* line is unaffected, we just have to set the state to processing A's
* retain line (and so will iterate through B's components)
*/
curState = new ProcessingBForARetainLine(aRetainLineCount);
}
}
private void cancel(int count) {
Preconditions.checkArgument(count <= bDeleteText.length(),
"Cannot cancel if A's component is longer than B's");
if (count < bDeleteText.length()) {
bDeleteText = bDeleteText.substring(count);
} else {
curState = defaultState;
}
}
}
private class ProcessingAForBRetain extends ProcessingA {
private int bRetainCount;
private final boolean bRetainHasTrailingNewline;
ProcessingAForBRetain(int bRetainCount, boolean bRetainHasTrailingNewline) {
this.bRetainCount = bRetainCount;
this.bRetainHasTrailingNewline = bRetainHasTrailingNewline;
}
@Override
public void insert(String aInsertText) {
if (aInsertText.length() <= bRetainCount) {
output.insert(aInsertText);
cancel(aInsertText.length());
} else {
output.insert(aInsertText.substring(0, bRetainCount));
curState = new ProcessingBForAInsert(aInsertText.substring(bRetainCount));
}
}
@Override
public void retain(int aRetainCount, boolean aRetainHasTrailingNewline) {
if (aRetainCount <= bRetainCount) {
output.retain(aRetainCount, aRetainHasTrailingNewline);
cancel(aRetainCount);
} else {
output.retain(bRetainCount, bRetainHasTrailingNewline);
curState =
new ProcessingBForARetain(aRetainCount - bRetainCount, aRetainHasTrailingNewline);
}
}
@Override
public void retainLine(int aRetainLineCount) {
// B is modifying a previously retained line
output.retain(bRetainCount, bRetainHasTrailingNewline);
if (bRetainHasTrailingNewline || isLastComponentOfB) {
if (aRetainLineCount == 1) {
curState = defaultState;
} else {
curState = new ProcessingBForARetainLine(aRetainLineCount - 1);
}
} else {
curState = new ProcessingBForARetainLine(aRetainLineCount);
}
}
private void cancel(int count) {
Preconditions.checkArgument(count <= bRetainCount,
"Cannot cancel if A's component is longer than B's");
if (count < bRetainCount) {
bRetainCount -= count;
} else {
curState = defaultState;
}
}
}
private class ProcessingAForBRetainLine extends ProcessingA {
private int bRetainLineCount;
ProcessingAForBRetainLine(int bRetainLineCount) {
this.bRetainLineCount = bRetainLineCount;
}
@Override
public void insert(String aInsertText) {
// B is retaining the line that A modified
output.insert(aInsertText);
boolean aInsertTextHasNewline = aInsertText.endsWith("\n");
if (aInsertTextHasNewline || isLastComponentOfA) {
cancelLines(1, aInsertTextHasNewline);
}
}
@Override
public void retain(int aRetainCount, boolean aRetainHasTrailingNewline) {
// B is retaining the line that A modified
output.retain(aRetainCount, aRetainHasTrailingNewline);
if (aRetainHasTrailingNewline || isLastComponentOfA) {
cancelLines(1, aRetainHasTrailingNewline);
}
}
@Override
public void retainLine(int aRetainLineCount) {
// A and B are retaining some lines
int minRetainLineCount = Math.min(aRetainLineCount, bRetainLineCount);
output.retainLine(minRetainLineCount);
if (aRetainLineCount == bRetainLineCount) {
curState = defaultState;
} else if (aRetainLineCount == minRetainLineCount) {
cancelLines(minRetainLineCount, true);
} else if (bRetainLineCount == minRetainLineCount) {
curState = new ProcessingBForARetainLine(aRetainLineCount - minRetainLineCount);
}
}
private void cancelLines(int cancelLineCount, boolean hasNewline) {
if (hasNewline) {
bRetainLineCount -= cancelLineCount;
}
if (isLastComponentOfA) {
transitionForLastComponentOfAAndBRetainLine(bRetainLineCount);
} else if (bRetainLineCount == 0) {
curState = defaultState;
}
}
}
private abstract class ProcessingB extends State {
@Override
public void insert(String text) {
output.insert(text);
}
@Override
boolean isProcessingB() {
return true;
}
}
private class ProcessingBForAFinished extends ProcessingB {
/**
* Tracks whether B has used a retain line component to match any
* potentially leftover (unmatched) text on the last line of A.
*
* A few examples:
* <ul>
* <li>A is R(2, true), R(5) and B is RL(1), D(2), RL(1). The use of B's
* second RL(1) to match the last three characters in A's R(5) would lead to
* this variable being set to true.</li>
* <li>There is also a potential for this to be true when B's RL is matching
* empty text from A. For example, the document text is "Z\n",
* A is R(2, true) and B is RL(2). A does not have a component for the
* empty-texted last line, but B does (the second line of the RL(2)).</li>
* </ul>
*/
private boolean hasBUsedRlToMatchLeftoverTextOnLastLineOfA;
ProcessingBForAFinished(boolean hasBUsedRlToMatchLeftoverTextOnLastLineOfA) {
this.hasBUsedRlToMatchLeftoverTextOnLastLineOfA = hasBUsedRlToMatchLeftoverTextOnLastLineOfA;
}
@Override
public void delete(String text) {
throw new InternalComposeException("A finished, B cannot have a delete");
}
@Override
public void retain(int count, boolean hasTrailingNewline) {
throw new InternalComposeException("A finished, B cannot have a retain");
}
@Override
public void retainLine(int lineCount) {
if (lineCount == 1 && !hasBUsedRlToMatchLeftoverTextOnLastLineOfA) {
output.retainLine(1);
hasBUsedRlToMatchLeftoverTextOnLastLineOfA = true;
} else {
throw new InternalComposeException("A finished, B cannot have a retain line");
}
}
}
private class ProcessingBForAInsert extends ProcessingB {
private String aInsertText;
ProcessingBForAInsert(String aInsertText) {
this.aInsertText = aInsertText;
}
@Override
public void delete(String bDeleteText) {
if (bDeleteText.length() <= aInsertText.length()) {
cancel(bDeleteText.length());
} else {
curState = new ProcessingAForBDelete(bDeleteText.substring(aInsertText.length()));
}
}
@Override
public void retain(int bRetainCount, boolean bRetainHasTrailingNewline) {
if (bRetainCount <= aInsertText.length()) {
output.insert(aInsertText.substring(0, bRetainCount));
cancel(bRetainCount);
} else {
output.insert(aInsertText);
curState =
new ProcessingAForBRetain(bRetainCount - aInsertText.length(),
bRetainHasTrailingNewline);
}
}
@Override
public void retainLine(int bRetainLineCount) {
assert bRetainLineCount > 0;
// B is retaining the line where A modified
output.insert(aInsertText);
if (aInsertText.endsWith("\n")) {
bRetainLineCount--;
}
transitionForAInsertOrRetainAndBRetainLine(bRetainLineCount);
}
private void cancel(int bCount) {
if (bCount < aInsertText.length()) {
aInsertText = aInsertText.substring(bCount);
} else {
curState = defaultState;
}
}
}
private class ProcessingBForARetain extends ProcessingB {
private int aRetainCount;
private final boolean aRetainHasTrailingNewline;
ProcessingBForARetain(int aRetainCount, boolean aRetainHasTrailingNewline) {
this.aRetainCount = aRetainCount;
this.aRetainHasTrailingNewline = aRetainHasTrailingNewline;
}
@Override
public void delete(String bDeleteText) {
if (bDeleteText.length() <= aRetainCount) {
output.delete(bDeleteText);
cancel(bDeleteText.length());
} else {
output.delete(bDeleteText.substring(0, aRetainCount));
curState = new ProcessingAForBDelete(bDeleteText.substring(aRetainCount));
}
}
@Override
public void retain(int bRetainCount, boolean bRetainHasTrailingNewline) {
if (bRetainCount <= this.aRetainCount) {
output.retain(bRetainCount, bRetainHasTrailingNewline);
cancel(bRetainCount);
} else {
output.retain(aRetainCount, aRetainHasTrailingNewline);
curState =
new ProcessingAForBRetain(bRetainCount - aRetainCount, bRetainHasTrailingNewline);
}
}
@Override
public void retainLine(int bRetainLineCount) {
Preconditions.checkArgument(bRetainLineCount > 0, "Must retain more than one line");
output.retain(aRetainCount, aRetainHasTrailingNewline);
if (aRetainHasTrailingNewline) {
bRetainLineCount--;
}
transitionForAInsertOrRetainAndBRetainLine(bRetainLineCount);
}
private void cancel(int count) {
if (count < aRetainCount) {
aRetainCount -= count;
} else {
curState = defaultState;
}
}
}
private class ProcessingBForARetainLine extends ProcessingB {
private int aRetainLineCount;
ProcessingBForARetainLine(int aRetainLineCount) {
this.aRetainLineCount = aRetainLineCount;
}
@Override
public void insert(String bInsertText) {
super.insert(bInsertText);
if (isLastComponentOfB) {
cancelLines(1);
}
}
@Override
public void delete(String bDeleteText) {
// A is retaining the line that B modified
output.delete(bDeleteText);
if (bDeleteText.endsWith("\n") || isLastComponentOfB) {
cancelLines(1);
}
}
@Override
public void retain(int bRetainCount, boolean bRetainHasTrailingNewline) {
// A is retaining the line that B modified
output.retain(bRetainCount, bRetainHasTrailingNewline);
if (bRetainHasTrailingNewline || isLastComponentOfB) {
cancelLines(1);
}
}
@Override
public void retainLine(int bRetainLineCount) {
// A and B are retaining some lines
int minRetainLineCount = Math.min(aRetainLineCount, bRetainLineCount);
output.retainLine(minRetainLineCount);
if (aRetainLineCount == bRetainLineCount) {
curState = defaultState;
} else if (bRetainLineCount == minRetainLineCount) {
cancelLines(minRetainLineCount);
} else if (aRetainLineCount == minRetainLineCount) {
curState = new ProcessingAForBRetainLine(bRetainLineCount - minRetainLineCount);
}
}
private void cancelLines(int cancelLineCount) {
aRetainLineCount -= cancelLineCount;
if (aRetainLineCount == 0) {
curState = defaultState;
}
}
}
private static abstract class State implements DocOpCursor {
abstract boolean isProcessingB();
}
public static DocOp compose(DocOpFactory factory, DocOp a, DocOp b)
throws ComposeException {
try {
return new Composer(factory, a, b).composeImpl(false);
} catch (InternalComposeException e) {
throw new ComposeException("Could not compose operations:\na: "
+ DocOpUtils.toString(a, true) + "\nb: " + DocOpUtils.toString(b, true) + "\n", e);
}
}
@VisibleForTesting
public static DocOp composeWithStartState(DocOpFactory factory, DocOp a, DocOp b,
boolean startWithSpecificProcessingAState) throws ComposeException {
try {
return new Composer(factory, a, b).composeImpl(startWithSpecificProcessingAState);
} catch (InternalComposeException e) {
throw new ComposeException("Could not compose operations:\na: "
+ DocOpUtils.toString(a, true) + "\nb: " + DocOpUtils.toString(b, true) + "\n", e);
}
}
public static DocOp compose(DocOpFactory factory, Iterable<DocOp> docOps)
throws ComposeException {
Iterator<DocOp> iterator = docOps.iterator();
DocOp prevDocOp = iterator.next();
while (iterator.hasNext()) {
prevDocOp = compose(factory, prevDocOp, iterator.next());
}
return prevDocOp;
}
private final DocOp a;
private final DocOp b;
private final DocOpCapturer output;
private final ProcessingA defaultState = new ProcessingA() {
@Override
public void insert(String aInsertText) {
curState = new ProcessingBForAInsert(aInsertText);
}
@Override
public void retain(int aRetainCount, boolean aRetainHasTrailingNewline) {
curState = new ProcessingBForARetain(aRetainCount, aRetainHasTrailingNewline);
}
@Override
public void retainLine(int aRetainLineCount) {
if (isLastComponentOfB && aRetainLineCount == 1 && isLastComponentOfA) {
// This catches the RL(1) that matches nothing
// Essentially curState = defaultState;
} else {
curState = new ProcessingBForARetainLine(aRetainLineCount);
}
}
};
private State curState = defaultState;
/**
* State for use by processors that is true if A is on its last component. The
* last component of A can cancel B's retain line even if A's last component
* does not end with a newline or is not a retain line.
*/
private boolean isLastComponentOfA;
/** Similar to {@link #isLastComponentOfA} but for B */
private boolean isLastComponentOfB;
private Composer(DocOpFactory factory, DocOp a, DocOp b) {
this.a = a;
this.b = b;
output = new DocOpCapturer(factory, true);
}
/**
* @param startWithSpecificProcessingAState the allows the caller to begin the
* compose with an alternate start state. Normally, the first state is
* a trivial ProcessingA that just creates a ProcessingBForAXxx.
* However, we could also start the compose with a ProcessingAForBXxx.
* If true, we will attempt to do the latter. The two paths should
* eventually lead to the same solution.
*/
private DocOp composeImpl(boolean startWithSpecificProcessingAState) {
int aIndex = 0;
JsonArray<DocOpComponent> aComponents = a.getComponents();
int bIndex = 0;
JsonArray<DocOpComponent> bComponents = b.getComponents();
/*
* Note the "!= INSERT": There isn't a ProcessingAForBInsert. What that
* implementation would like is emit B's insertion, and then flip to
* ProcessingBForAXxx, which is what the defaultState will do.
*/
if (!bComponents.isEmpty() && startWithSpecificProcessingAState
&& bComponents.get(0).getType() != DocOpComponent.Type.INSERT) {
curState = createSpecificProcessingAState(aComponents.get(0), bComponents.get(0));
bIndex++;
} else {
curState = defaultState;
}
isLastComponentOfB = bIndex == bComponents.size();
while (aIndex < aComponents.size()) {
/*
* The state from the previous iteration could be a "processing B for A
* finished" which is of type "processing B", but in that case, we would
* not have continued to this iteration since the invariant above would
* not have passed.
*/
assert !curState.isProcessingB();
isLastComponentOfA = aIndex == aComponents.size() - 1;
DocOpUtils.acceptComponent(aComponents.get(aIndex++), curState);
// Notice the different invariant compared to the outer while-loop
while (curState.isProcessingB() && !isProcessingBForAFinished()) {
if (bIndex >= bComponents.size()) {
throw new InternalComposeException("Mismatch in doc ops");
}
isLastComponentOfB = bIndex == bComponents.size() - 1;
DocOpUtils.acceptComponent(bComponents.get(bIndex++), curState);
}
/*
* At this point, curState must either be processing A, or processing B
* after A is finished
*/
}
if (curState != defaultState && !isProcessingBForAFinished() && !isBRetainingRestOfLastLine()) {
throw new InternalComposeException("Invalid state");
}
if (bIndex < bComponents.size()) {
if (curState == defaultState) {
curState = new ProcessingBForAFinished(false);
}
while (bIndex < bComponents.size()) {
isLastComponentOfB = bIndex == bComponents.size() - 1;
DocOpUtils.acceptComponent(bComponents.get(bIndex++), curState);
}
}
return output.getDocOp();
}
private ProcessingA createSpecificProcessingAState(DocOpComponent a, DocOpComponent b) {
switch (b.getType()) {
case DocOpComponent.Type.DELETE:
return new ProcessingAForBDelete(((DocOpComponent.Delete) b).getText());
case DocOpComponent.Type.INSERT:
throw new IllegalArgumentException(
"Cannot create a specific ProcessingA state for B insertion");
case DocOpComponent.Type.RETAIN:
return new ProcessingAForBRetain(((DocOpComponent.Retain) b).getCount(),
((DocOpComponent.Retain) b).hasTrailingNewline());
case DocOpComponent.Type.RETAIN_LINE:
return new ProcessingAForBRetainLine(((DocOpComponent.RetainLine) b).getLineCount());
default:
throw new IllegalArgumentException("Unknown component type with ordinal: " + b.getType());
}
}
/**
* Trivial method for cleaner syntax at the call sites (no instanceof there)
*/
private boolean isProcessingBForAFinished() {
return curState instanceof ProcessingBForAFinished;
}
/**
* Trivial method for clear syntax at the call sites.
*/
private boolean isBRetainingRestOfLastLine() {
return curState instanceof ProcessingAForBRetainLine && isLastComponentOfA && isLastComponentOfB
&& ((ProcessingAForBRetainLine) curState).bRetainLineCount == 1;
}
private void transitionForAInsertOrRetainAndBRetainLine(int remainingBRetainLineCount) {
if (isLastComponentOfA) {
transitionForLastComponentOfAAndBRetainLine(remainingBRetainLineCount);
} else {
if (remainingBRetainLineCount == 0) {
curState = defaultState;
} else {
curState = new ProcessingAForBRetainLine(remainingBRetainLineCount);
}
}
}
/**
* @param remainingBRetainLineCount the remaining retain line count of B
* (after any newline that may exist in A)
*/
private void transitionForLastComponentOfAAndBRetainLine(int remainingBRetainLineCount) {
switch (remainingBRetainLineCount) {
case 0:
curState = new ProcessingBForAFinished(false);
break;
case 1:
curState = new ProcessingBForAFinished(true);
break;
default:
// This is an invalid state
curState = new ProcessingAForBRetainLine(remainingBRetainLineCount);
break;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/DocOpUtils.java | shared/src/main/java/com/google/collide/shared/ot/DocOpUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import static com.google.collide.dto.DocOpComponent.Type.DELETE;
import static com.google.collide.dto.DocOpComponent.Type.INSERT;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN_LINE;
import java.util.List;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.DocOpComponent.Delete;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.DocOpComponent.Retain;
import com.google.collide.dto.DocOpComponent.RetainLine;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.document.util.LineUtils;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Preconditions;
/**
* Utility methods for document operation manipulation.
*
*/
public final class DocOpUtils {
public static void accept(DocOp docOp, DocOpCursor visitor) {
JsonArray<DocOpComponent> components = docOp.getComponents();
for (int i = 0, n = components.size(); i < n; i++) {
acceptComponent(components.get(i), visitor);
}
}
public static void acceptComponent(DocOpComponent component, DocOpCursor visitor) {
switch (component.getType()) {
case DELETE:
visitor.delete(((Delete) component).getText());
break;
case INSERT:
visitor.insert(((Insert) component).getText());
break;
case RETAIN:
Retain retain = (Retain) component;
visitor.retain(retain.getCount(), retain.hasTrailingNewline());
break;
case RETAIN_LINE:
visitor.retainLine(((RetainLine) component).getLineCount());
break;
default:
throw new IllegalArgumentException(
"Unknown doc op component with ordinal " + component.getType());
}
}
public static DocOp createFromTextChange(DocOpFactory factory, TextChange textChange) {
DocOp docOp = factory.createDocOp();
JsonArray<DocOpComponent> components = docOp.getComponents();
int lineNumber = textChange.getLineNumber();
if (lineNumber > 0) {
components.add(factory.createRetainLine(lineNumber));
}
int column = textChange.getColumn();
if (column > 0) {
components.add(factory.createRetain(column, false));
}
String text = textChange.getText();
/*
* Split the potentially multiline text into a component per line
*/
JsonArray<String> lineTexts = StringUtils.split(text, "\n");
// Create components for all but the last line
int nMinusOne = lineTexts.size() - 1;
for (int i = 0; i < nMinusOne; i++) {
components.add(createComponentFromTextChange(factory, textChange, lineTexts.get(i) + "\n"));
}
String lastLineText = lineTexts.get(nMinusOne);
if (!lastLineText.isEmpty()) {
// Create a component for the last line
components.add(createComponentFromTextChange(factory, textChange, lastLineText));
}
// Create a retain, if required
int remainingRetainCount;
int numNewlines = lineTexts.size() - 1;
if (textChange.getType() == TextChange.Type.INSERT) {
Line lastModifiedLine = LineUtils.getLine(textChange.getLine(), numNewlines);
remainingRetainCount = lastModifiedLine.getText().length() - lastLineText.length();
if (numNewlines == 0) {
remainingRetainCount -= column;
}
} else { // DELETE
remainingRetainCount = textChange.getLine().getText().length() - column;
}
// Create a retain line, if required
int docLineCount = textChange.getLine().getDocument().getLineCount();
int numNewlinesFromTextChangeInCurDoc =
textChange.getType() == TextChange.Type.DELETE ? 0 : numNewlines;
int remainingLineCount = docLineCount - (lineNumber + numNewlinesFromTextChangeInCurDoc + 1);
// Add the retain and retain line components
if (remainingRetainCount > 0) {
// This retain has a trailing new line if it is NOT on the last line
components.add(factory.createRetain(remainingRetainCount, remainingLineCount > 0));
}
if (remainingLineCount > 0) {
components.add(factory.createRetainLine(remainingLineCount));
} else {
Preconditions.checkState(remainingLineCount == 0, "How is it negative?");
/*
* If the retainingLineCount calculation resulted in 0, there's still a
* chance that there is a empty last line that needs to be retained. Our
* contract says if the resulting document (that is, the document in its
* state right now) has an empty last line, we should have a RetainLine
* that accounts for it. In addition if the document contained an empty
* last line before the delete we should also emit a retain line.
*
* Since we didn't emit the RetainLine above (since remainingLineCount ==
* 0), we can check and emit one here.
*/
// to check if the document ended in a new line before the change, we check if the change
// endsWith \n and remainingRetainCount = 0;
boolean didDocumentEndInEmptyLineBeforeDelete = textChange.getType() == TextChange.Type.DELETE
&& remainingRetainCount == 0 && text.endsWith("\n");
boolean isLastLineEmptyAfterTextChange =
textChange.getLine().getDocument().getLastLine().getText().length() == 0;
if (isLastLineEmptyAfterTextChange || didDocumentEndInEmptyLineBeforeDelete) {
components.add(factory.createRetainLine(1));
}
}
return docOp;
}
/**
* Creates a single doc op composed of docops converted from a collection
* of text changes. For a single text change use
* {@link #createFromTextChange(DocOpFactory, TextChange)}.
*
* @param factory doc ops factory
* @param textChanges list of changes to convert to doc op
* @return composed doc op, or {@code null} if text changes array is empty
* @throws Composer.ComposeException if error happens during composal
*/
public static DocOp createFromTextChanges(DocOpFactory factory,
JsonArray<TextChange> textChanges) throws Composer.ComposeException {
DocOp result = null;
for (int i = 0, n = textChanges.size(); i < n; i++) {
TextChange textChange = textChanges.get(i);
DocOp curOp = DocOpUtils.createFromTextChange(factory, textChange);
result = result != null ? Composer.compose(factory, result, curOp) : curOp;
}
return result;
}
public static boolean containsMutation(Iterable<DocOp> docOps) {
for (DocOp docOp : docOps) {
if (containsMutation(docOp)) {
return true;
}
}
return false;
}
public static boolean containsMutation(DocOp docOp) {
for (int i = 0; i < docOp.getComponents().size(); i++) {
DocOpComponent component = docOp.getComponents().get(i);
switch (component.getType()) {
case DocOpComponent.Type.DELETE:
case DocOpComponent.Type.INSERT:
return true;
case DocOpComponent.Type.RETAIN:
case DocOpComponent.Type.RETAIN_LINE:
// Retains do not dirty the contents of a file
break;
default:
throw new IllegalArgumentException("Got an unknown doc op type " + component.getType());
}
}
return false;
}
public static String toString(DocOp docOp, boolean verbose) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = docOp.getComponents().size(); i < n; i++) {
sb.append(toString(docOp.getComponents().get(i), verbose));
}
return sb.toString();
}
public static String toString(DocOpComponent component, boolean verbose) {
switch (component.getType()) {
case DELETE:
String deleteText = ((Delete) component).getText();
return "D(" + toStringForComponentText(deleteText, verbose) + ")";
case INSERT:
String insertText = ((Insert) component).getText();
return "I(" + toStringForComponentText(insertText, verbose) + ")";
case RETAIN:
Retain retain = (Retain) component;
return "R(" + (retain.hasTrailingNewline() ? (retain.getCount() - 1) + "\\n" : ""
+ retain.getCount()) + ")";
case RETAIN_LINE:
return "RL(" + ((RetainLine) component).getLineCount() + ")";
default:
return "?(???)";
}
}
public static String toString(
List<? extends DocOp> docOps, int firstIndex, int lastIndex, boolean verbose) {
StringBuilder sb = new StringBuilder("[");
for (int i = firstIndex; i <= lastIndex; i++) {
DocOp docOp = docOps.get(i);
if (docOp == null) {
sb.append("<null doc op>,");
} else {
sb.append(toString(docOp, verbose)).append(',');
}
}
sb.setLength(sb.length() - 1);
sb.append(']');
return sb.toString();
}
private static DocOpComponent createComponentFromTextChange(
DocOpFactory factory, TextChange textChange, String text) {
switch (textChange.getType()) {
case INSERT:
return factory.createInsert(text);
case DELETE:
return factory.createDelete(text);
default:
throw new IllegalArgumentException(
"Unknown text change type with ordinal " + textChange.getType().ordinal());
}
}
private static String toStringForComponentText(String componentText, boolean verbose) {
if (verbose) {
return componentText.endsWith("\n") ? componentText.substring(0, componentText.length() - 1)
+ "\\n" : componentText;
} else {
return componentText.endsWith("\n") ? (componentText.length() - 1) + "\\n" : ""
+ componentText.length();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/DocOpApplier.java | shared/src/main/java/com/google/collide/shared/ot/DocOpApplier.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.DocOpComponent.Delete;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.DocOpComponent.Retain;
import com.google.collide.dto.DocOpComponent.RetainLine;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.DocumentMutator;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
/**
*/
public class DocOpApplier {
public static JsonArray<TextChange> apply(DocOp docOp, Document document) {
return apply(docOp, document, document);
}
public static JsonArray<TextChange> apply(DocOp docOp, Document document,
DocumentMutator documentMutator) {
DocOpApplier docOpApplier = new DocOpApplier(docOp, document, documentMutator);
docOpApplier.apply();
return docOpApplier.textChanges;
}
private int column;
private final JsonArray<DocOpComponent> components;
private int componentIndex;
private final Document document;
private DocumentMutator documentMutator;
/**
* If true, we are definitely finished and cannot accepts any more doc op
* components.
*/
private boolean isFinished;
private LineInfo lineInfo;
private final JsonArray<TextChange> textChanges = JsonCollections.createArray();
private DocOpApplier(DocOp docOp, Document document, DocumentMutator documentMutator) {
this.components = docOp.getComponents();
this.document = document;
this.documentMutator = documentMutator;
lineInfo = new LineInfo(document.getFirstLine(), 0);
}
public void apply() {
for (; componentIndex < components.size(); componentIndex++) {
DocOpComponent component = components.get(componentIndex);
switch (component.getType()) {
case DocOpComponent.Type.INSERT:
handleInsert((Insert) component);
break;
case DocOpComponent.Type.DELETE:
handleDelete((Delete) component);
break;
case DocOpComponent.Type.RETAIN:
handleRetain((Retain) component);
break;
case DocOpComponent.Type.RETAIN_LINE:
handleRetainLine((RetainLine) component);
break;
}
}
}
private void handleDelete(Delete deleteOp) {
Preconditions.checkArgument(!isFinished, "Unexpected finished while handling delete");
Preconditions.checkArgument(lineInfo.line().getText().substring(column).startsWith(
deleteOp.getText()), "To-be-deleted text isn't actually at location");
StringBuilder text = new StringBuilder(deleteOp.getText());
while (componentIndex + 1 < components.size()
&& components.get(componentIndex + 1).getType() == DocOpComponent.Type.DELETE) {
componentIndex++;
text.append(((Delete) components.get(componentIndex)).getText());
}
addTextChange(documentMutator.deleteText(lineInfo.line(), lineInfo.number(), column,
text.length()));
}
private void handleInsert(Insert insertOp) {
Preconditions.checkArgument(!isFinished, "Unexpected finished while handling insert");
StringBuilder text = new StringBuilder();
int newLineDelta = 0;
int newColumn = column;
// Offset the componentIndex for the first iteration
componentIndex--;
do {
componentIndex++;
String insertOpText = ((Insert) components.get(componentIndex)).getText();
text.append(insertOpText);
if (insertOpText.endsWith("\n")) {
newLineDelta++;
newColumn = 0;
} else {
newColumn += insertOpText.length();
}
} while (componentIndex + 1 < components.size()
&& components.get(componentIndex + 1).getType() == DocOpComponent.Type.INSERT);
addTextChange(documentMutator.insertText(lineInfo.line(), lineInfo.number(), column,
text.toString()));
for (; newLineDelta > 0; newLineDelta--) {
moveToNextLine();
}
column = newColumn;
}
private void addTextChange(TextChange textChange) {
if (textChange != null) {
textChanges.add(textChange);
}
}
private void handleRetain(Retain retainOp) {
Preconditions.checkArgument(!isFinished, "Unexpected finished while handling retain");
if (retainOp.hasTrailingNewline()) {
moveToNextLine();
} else {
column += retainOp.getCount();
}
}
private void handleRetainLine(RetainLine retainLineOp) {
Preconditions.checkArgument(!isFinished, "Unexpected finished while handling retain line");
int lineCount = retainLineOp.getLineCount();
int newLineNumber = lineInfo.number() + lineCount;
if (newLineNumber < document.getLineCount()) {
lineInfo = document.getLineFinder().findLine(lineInfo.number() + lineCount);
column = 0;
} else {
// We have spanned the entire document
isFinished = true;
}
}
private void moveToNextLine() {
boolean didMove = lineInfo.moveToNext();
Preconditions.checkArgument(didMove, "Did not actually move to next line");
column = 0;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/DocOpCapturer.java | shared/src/main/java/com/google/collide/shared/ot/DocOpCapturer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import static com.google.collide.dto.DocOpComponent.Type.DELETE;
import static com.google.collide.dto.DocOpComponent.Type.INSERT;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN_LINE;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.shared.JsonArray;
/**
* Helper to create document operations via a method call for each component.
*
*/
public class DocOpCapturer implements DocOpCursor {
private final JsonArray<DocOpComponent> components;
private final DocOpFactory factory;
private final DocOp op;
private int curComponentType = -1;
/** Only valid if the current component is delete or insert */
private String curText = "";
/** Only valid if the current component is retain or retain line */
private int curCount;
/** Only valid if the current component is retain */
private boolean curHasTrailingNewline;
private boolean curLineHasNonRetainComponents = false;
private final boolean shouldCompact;
/**
* @param shouldCompact whether similar adjacent components should be
* compacted into a single component
*/
public DocOpCapturer(DocOpFactory factory, boolean shouldCompact) {
this.factory = factory;
this.shouldCompact = shouldCompact;
op = factory.createDocOp();
components = op.getComponents();
}
@Override
public void delete(String text) {
checkAndCommitIfRequired(DELETE);
curComponentType = DELETE;
curText += text;
// Reset the variable if starting a new line
curLineHasNonRetainComponents = !text.endsWith("\n");
}
public DocOp getDocOp() {
commitCurrentComponent();
return op;
}
@Override
public void insert(String text) {
checkAndCommitIfRequired(INSERT);
curComponentType = INSERT;
curText += text;
// Reset the variable if starting a new line
curLineHasNonRetainComponents = !text.endsWith("\n");
}
@Override
public void retain(int count, boolean hasTrailingNewline) {
if (shouldCompact && !curLineHasNonRetainComponents && hasTrailingNewline) {
/*
* Since this line only had retain(s), we can convert it to the more terse
* retain line
*/
/*
* curXxx refers to the state prior to the retain we're handling right
* now. If the ongoing component was a retain, throw it away.
*/
if (curComponentType == RETAIN && !curHasTrailingNewline) {
discardCurrentComponent();
}
retainLine(1);
return;
}
checkAndCommitIfRequired(RETAIN);
curComponentType = RETAIN;
curCount += count;
curHasTrailingNewline = hasTrailingNewline;
if (curHasTrailingNewline) {
curLineHasNonRetainComponents = false;
}
}
@Override
public void retainLine(int lineCount) {
checkAndCommitIfRequired(RETAIN_LINE);
curComponentType = RETAIN_LINE;
curCount += lineCount;
curLineHasNonRetainComponents = false;
}
private void checkAndCommitIfRequired(int newType) {
/*-
* Rules for committing:
* - This instance does NOT compact components of the same type
* into a single component, or
* - The component about to be captured is a different type from the
* currently compacting component type, or
* - The new and current component type is the same and not RETAIN_LINE,
* and it ends with a newline
*/
if (!shouldCompact || curComponentType != newType
|| (curComponentType == RETAIN && curHasTrailingNewline)
|| (curComponentType == DELETE && curText.endsWith("\n"))
|| (curComponentType == INSERT && curText.endsWith("\n"))) {
commitCurrentComponent();
}
}
private void commitCurrentComponent() {
if (curComponentType == -1) {
return;
}
switch (curComponentType) {
case INSERT:
components.add(factory.createInsert(curText));
break;
case DELETE:
components.add(factory.createDelete(curText));
break;
case RETAIN:
components.add(factory.createRetain(curCount, curHasTrailingNewline));
break;
case RETAIN_LINE:
components.add(factory.createRetainLine(curCount));
break;
default:
throw new IllegalStateException("Cannot handle component type with ordinal "
+ curComponentType);
}
discardCurrentComponent();
}
private void discardCurrentComponent() {
curComponentType = -1;
curHasTrailingNewline = false;
curText = "";
curCount = 0;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/DocOpCursor.java | shared/src/main/java/com/google/collide/shared/ot/DocOpCursor.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
/**
* Callback used to iterate through a document operation.
*/
public interface DocOpCursor {
void delete(String text);
void insert(String text);
void retain(int count, boolean hasTrailingNewline);
void retainLine(int lineCount);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/ot/PositionMigrator.java | shared/src/main/java/com/google/collide/shared/ot/PositionMigrator.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.ot;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Document.TextListener;
import com.google.collide.shared.document.LineNumberAndColumn;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar;
/**
* A mechanism that translates file positions to/from file position at
* earlier point in time when this position migrator was created or reset.
* The scope of PositionMigrator object is currently opened document.
* On "start" position migrator starts tracking text changes.
* Calling "reset" clears tracked docops and moves tracking start to current
* moment.
*
*/
public class PositionMigrator {
private final TextListener textListener = new TextListener() {
@Override
public void onTextChange(Document document, JsonArray<TextChange> textChanges) {
PositionMigrator.this.onTextChange(textChanges);
}
};
private final DocOpFactory docOpFactory;
private final JsonArray<DocOp> appliedDocOps = JsonCollections.createArray();
private ListenerRegistrar.Remover textListenerRemover;
public PositionMigrator(DocOpFactory docOpFactory) {
this.docOpFactory = docOpFactory;
}
/**
* Converts given position as it was at the time when tracking started,
* to current position.
*
* @param lineNumber old position line number
* @param column old position column
* @return current position line number and column
*/
public LineNumberAndColumn migrateToNow(int lineNumber, int column) {
// TODO: Cache the result.
DocOp docOp = composeCurrentDocOps();
if (docOp == null) {
return LineNumberAndColumn.from(lineNumber, column);
}
PositionTransformer positionTransformer =
new PositionTransformer(lineNumber, column);
positionTransformer.transform(docOp);
return LineNumberAndColumn.from(positionTransformer.getLineNumber(),
positionTransformer.getColumn());
}
public boolean haveChanges() {
return composeCurrentDocOps() != null;
}
/**
* Converts given position at current time to position as it was at the time
* when tracking started.
*
* @param lineNumber current position line number
* @param column current position column
* @return old position line number and column
*/
public LineNumberAndColumn migrateFromNow(int lineNumber, int column) {
// TODO: Cache the result.
DocOp docOp = composeCurrentDocOps();
if (docOp == null) {
return LineNumberAndColumn.from(lineNumber, column);
}
PositionTransformer positionTransformer =
new PositionTransformer(lineNumber, column);
positionTransformer.transform(Inverter.invert(docOpFactory, docOp));
return LineNumberAndColumn.from(positionTransformer.getLineNumber(),
positionTransformer.getColumn());
}
/**
* Forgets about all currently recorded text changes and continues tracking
* if started.
*/
public void reset() {
appliedDocOps.clear();
}
/**
* Starts tracking text changes. Text changes collected so far are discarded.
*
* @param textListenerRegistrar listener registrar to use for listening text
* changes
*/
public void start(ListenerRegistrar<TextListener> textListenerRegistrar) {
reset();
stop();
this.textListenerRemover = textListenerRegistrar.add(textListener);
}
/**
* Stops tracking text changes, keeping currently recorded text changes.
*/
public void stop() {
if (textListenerRemover != null) {
textListenerRemover.remove();
textListenerRemover = null;
}
}
private void onTextChange(JsonArray<TextChange> textChanges) {
try {
appliedDocOps.add(DocOpUtils.createFromTextChanges(docOpFactory, textChanges));
} catch (Composer.ComposeException e) {
throw new RuntimeException(e);
}
}
/**
* Composes currently collected doc ops into a single doc op and returns it.
*
* @return composed doc op or {@code null} if no doc ops were collected so far
*/
private DocOp composeCurrentDocOps() {
if (appliedDocOps.size() < 2) {
return appliedDocOps.size() > 0 ? appliedDocOps.get(0) : null;
}
try {
DocOp docOp = Composer.compose(docOpFactory, appliedDocOps.asIterable());
appliedDocOps.clear();
appliedDocOps.add(docOp);
return docOp;
} catch (Composer.ComposeException e) {
throw new RuntimeException(e);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/grok/PositionTranslator.java | shared/src/main/java/com/google/collide/shared/grok/PositionTranslator.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.grok;
import java.util.Collections;
import java.util.List;
import com.google.collide.shared.document.LineNumberAndColumn;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
/**
* A class to translate between position representations, such as (line number,
* column) and text offset.
*
*/
@GwtCompatible
public class PositionTranslator {
private static List<Integer> calculateNewlineOffsets(String fileContents) {
Preconditions.checkNotNull(fileContents);
List<Integer> newlineOffsets = Lists.newArrayList();
for (int i = -1; (i = fileContents.indexOf('\n', i + 1)) >= 0;) {
newlineOffsets.add(i);
}
return newlineOffsets;
}
/**
* Stores the offset for the newline character on line i, where i is the index
*/
private final List<Integer> newlineOffsets;
public PositionTranslator(String fileContents) {
this.newlineOffsets = calculateNewlineOffsets(fileContents);
}
public LineNumberAndColumn getLineNumberAndColumn(int offset) {
int binarySearchResult = Collections.binarySearch(newlineOffsets, offset);
int lineNumber = binarySearchResult >= 0 ? binarySearchResult : -(binarySearchResult + 1);
int offsetOfFirstCharacterOnLine = getOffsetOfPreviousNewline(lineNumber) + 1;
return new LineNumberAndColumn(lineNumber, offset - offsetOfFirstCharacterOnLine);
}
public int getOffset(int lineNumber, int column) {
int offsetOfPreviousNewline = getOffsetOfPreviousNewline(lineNumber);
return offsetOfPreviousNewline + 1 + column;
}
/**
* Returns -1 if this is the first line.
*/
private int getOffsetOfPreviousNewline(int lineNumber) {
return lineNumber > 0 ? newlineOffsets.get(lineNumber - 1) : -1;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/shared/src/main/java/com/google/collide/shared/grok/GrokUtils.java | shared/src/main/java/com/google/collide/shared/grok/GrokUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.shared.grok;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.CodeGraph;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.StringUtils;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
/**
* Shared utilities for working with grok-related data structures.
*/
@GwtCompatible
public class GrokUtils {
private static final String QNAME_DELIMITER = ".";
/**
* A pair of (container, missing child name)
*/
public static class MissingChildCodeBlock {
public final CodeBlock container;
public final String childName;
private MissingChildCodeBlock(CodeBlock container, String name) {
this.container = container;
this.childName = name;
}
}
public static final Function<MissingChildCodeBlock, CodeBlock> NO_MISSING_CHILD =
new Function<MissingChildCodeBlock, CodeBlock>() {
@Override
public CodeBlock apply(MissingChildCodeBlock input) {
return null;
}
};
/**
* Finds code block by its qualified name relative to the {@code root} code
* block.
*
* @param root code block to search from
* @param qname dot-separated qualified name
* @return code block accessible by {@code qname} from {@code root} or {@code
* null}
*/
public static CodeBlock findCodeBlockByQname(CodeBlock root, String qname) {
return getOrCreateCodeBlock(root, StringUtils.split(qname, QNAME_DELIMITER), NO_MISSING_CHILD);
}
/**
* Finds code block by its qualified name relative to the {@code root} code
* block and creates missing blocks if necessary using a factory function. If
* factory function returns {@code null} at some point, this function also
* returns {@code null}, otherwise it inserts code blocks created by a factory
* function into the tree (like mkdir -p does for directories).
*
* @param root code block to search from
* @param qname dot-separated qualified name
* @param createCodeBlock factory function
* @return code block accessible by {@code qname} from {@code root} or {@code
* null} if the path was missing in the original tree and factory
* function refused to create some part of it
*/
public static CodeBlock getOrCreateCodeBlock(CodeBlock root, JsonArray<String> qname,
Function<MissingChildCodeBlock, CodeBlock> createCodeBlock) {
for (int nameIdx = 0, end = qname.size(); nameIdx < end; nameIdx++) {
CodeBlock newRoot = null;
for (int i = 0; i < root.getChildren().size(); i++) {
if (root.getChildren().get(i).getName().equals(qname.get(nameIdx))) {
newRoot = root.getChildren().get(i);
break;
}
}
if (newRoot == null) {
newRoot = createCodeBlock.apply(new MissingChildCodeBlock(root, qname.get(nameIdx)));
if (newRoot == null) {
return null;
}
root.getChildren().add(newRoot);
}
root = newRoot;
}
return root;
}
/**
* Search in graph blocks map for block with specific file path.
*
* @return {@code null} if filePath or graph is {@code null}, or there is
* no code block with specified path
*/
public static CodeBlock findFileCodeBlock(CodeGraph graph, String filePath) {
if (filePath == null) {
return null;
}
if (graph == null) {
return null;
}
JsonStringMap<CodeBlock> blockMap = graph.getCodeBlockMap();
if (blockMap == null) {
return null;
}
JsonArray<String> keys = blockMap.getKeys();
final int l = keys.size();
for (int i = 0; i < l; i++) {
String key = keys.get(i);
CodeBlock codeBlock = blockMap.get(key);
if (CodeBlock.Type.VALUE_FILE == codeBlock.getBlockType()) {
if (filePath.equals(codeBlock.getName())) {
return codeBlock;
}
}
}
return null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/settings/LookAndFeelSetting.java | src/main/java/io/github/struppigel/settings/LookAndFeelSetting.java | /**
* *****************************************************************************
* Copyright 2023 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.settings;
/**
* Available GUI themes
*/
public enum LookAndFeelSetting {
PORTEX,
SYSTEM;
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/settings/PortexSettings.java | src/main/java/io/github/struppigel/settings/PortexSettings.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.settings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import static io.github.struppigel.settings.PortexSettingsKey.*;
public class PortexSettings extends HashMap<PortexSettingsKey, String> {
private static final Logger LOGGER = LogManager.getLogger();
private final URL appPath = this.getClass().getProtectionDomain().getCodeSource().getLocation();
private static final String SETTINGS_FILE_NAME = "settings.ini";
private static final String SETTINGS_DELIMITER = ":::";
private File settingsFile;
public PortexSettings() {
try {
File app = new File(appPath.toURI());
File folder = app.getAbsoluteFile();
if(!folder.isDirectory()) { // different behaviour Win vs Linux here
folder = folder.getParentFile();
}
settingsFile = Paths.get(folder.getAbsolutePath(), SETTINGS_FILE_NAME).toFile();
loadSettings();
} catch (URISyntaxException e) {
LOGGER.fatal(e); // must never happen
throw new RuntimeException(e);
}
}
private void loadSettings() {
this.clear();
try {
if (settingsFile.exists() && settingsFile.isFile()) {
try (BufferedReader reader = new BufferedReader(new FileReader(settingsFile))) {
String line;
while ((line = reader.readLine()) != null) {
String[] pair = line.split(SETTINGS_DELIMITER);
if (pair.length >= 2) {
try {
PortexSettingsKey key = PortexSettingsKey.valueOf(pair[0].trim());
String value = pair[1];
this.put(key, value);
} catch (IllegalArgumentException e) {
LOGGER.warn("Non-existing settings key read! Will be ignored " + e);
e.printStackTrace();
}
}
}
}
LOGGER.info("Settings read successfully from " + settingsFile.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(e);
}
applyDefaults();
}
private void applyDefaults() {
// apply defaults
applySettingIfNotSet(DISABLE_YARA_WARNINGS, "0");
applySettingIfNotSet(DISABLE_UPDATE, "0");
applySettingIfNotSet(LOOK_AND_FEEL, LookAndFeelSetting.PORTEX.toString());
applySettingIfNotSet(VALUES_AS_HEX, "1");
applySettingIfNotSet(CONTENT_PREVIEW, "1");
}
private void applySettingIfNotSet(PortexSettingsKey key, String value) {
if(!this.containsKey(key)) {
this.put(key, value);
}
}
public boolean valueEquals(PortexSettingsKey key, String value) {
return this.containsKey(key) && this.get(key).equals(value);
}
public void writeSettings() throws IOException {
HashMap<PortexSettingsKey, String> map = new HashMap<>(this); // shallow copy
new SettingsWriter(settingsFile, map).execute();
}
private static class SettingsWriter extends SwingWorker<Void, Void> {
private final File settingsFile;
private final HashMap<PortexSettingsKey, String> map;
public SettingsWriter(File settingsFile, HashMap<PortexSettingsKey, String> map) {
this.settingsFile = settingsFile;
this.map = map;
}
@Override
protected Void doInBackground() throws Exception {
try {
settingsFile.delete();
settingsFile.createNewFile();
try (PrintStream out = new PrintStream(new FileOutputStream(settingsFile))) {
for (Map.Entry<PortexSettingsKey, String> entry : map.entrySet()) {
out.println(entry.getKey() + SETTINGS_DELIMITER + entry.getValue().trim());
}
LOGGER.info("Settings written to " + settingsFile.getAbsolutePath());
}
} catch (IOException e) {
LOGGER.error("problem with writing " + settingsFile);
throw e;
}
return null;
}
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/settings/PortexSettingsKey.java | src/main/java/io/github/struppigel/settings/PortexSettingsKey.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.settings;
public enum PortexSettingsKey {
YARA_PATH,
YARA_SIGNATURE_PATH,
DISABLE_UPDATE,
DISABLE_YARA_WARNINGS,
// possible values are in LookAndFeelSetting
LOOK_AND_FEEL,
VALUES_AS_HEX,
CONTENT_PREVIEW;
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/PEComponentTree.java | src/main/java/io/github/struppigel/gui/PEComponentTree.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import io.github.struppigel.gui.pedetails.PEDetailsPanel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* The tree on the left side
*/
public class PEComponentTree extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private static final String DOS_STUB_TEXT = "MS DOS Stub";
private static final String COFF_FILE_HEADER_TEXT = "COFF File Header";
private static final String OPTIONAL_HEADER_TEXT = "Optional Header";
private static final String STANDARD_FIELDS_TEXT = "Standard Fields";
private static final String WINDOWS_FIELDS_TEXT = "Windows Fields";
private static final String DATA_DIRECTORY_TEXT = "Data Directory";
private static final String SECTION_TABLE_TEXT = "Section Table";
private static final String PE_HEADERS_TEXT = "PE Headers";
private static final String OVERLAY_TEXT = "Overlay";
private static final String RICH_TEXT = "Rich Header";
private static final String MANIFEST_TEXT = "Manifests";
private static final String RESOURCES_TEXT = "Resources";
private static final String RT_STRING_TEXT = "String Table";
private static final String VERSION_INFO_TEXT = "Version Info";
private static final String IMPORTS_TEXT = "Imports";
private static final String DELAY_LOAD_IMPORTS_TEXT = "Delay Load Imports";
private static final String BOUND_IMPORTS_TEXT = "Bound Imports";
private static final String EXPORTS_TEXT = "Exports";
private static final String DEBUG_TEXT = "Debug";
private static final String ANOMALY_TEXT = "Anomalies";
private static final String HASHES_TEXT = "Hashes";
private static final String VISUALIZATION_TEXT = "Visualization";
private static final String PE_FORMAT_TEXT = "PE Format";
private static final String ICONS_TEXT = "Icons";
private static final String SIGNATURES_TEXT = "Signatures";
private static final String DOT_NET_TEXT = ".NET Headers";
private static final String DOT_NET_METADATA_ROOT_TEXT = "Metadata Root";
private static final String DOT_NET_STREAM_HEADERS_TEXT = "Stream Headers";
private static final String DOT_NET_OPTIMIZED_STREAM_TEXT = "#~";
private List<String> clrTableNames = new ArrayList<>();
private final PEDetailsPanel peDetailsPanel;
private FullPEData peData = null;
private JTree peTree;
public PEComponentTree(PEDetailsPanel peDetailsPanel) {
this.peDetailsPanel = peDetailsPanel;
initTree();
}
public void setPeData(FullPEData peData) {
this.peData = peData;
updateTree();
}
private void updateTree() {
LOGGER.debug("Updating tree");
DefaultMutableTreeNode root = (DefaultMutableTreeNode) peTree.getModel().getRoot();
root.removeAllChildren();
// create the child nodes
// PE related
// DOS/PE Headers
DefaultMutableTreeNode pe = new DefaultMutableTreeNode(PE_FORMAT_TEXT);
DefaultMutableTreeNode dosStub = new DefaultMutableTreeNode(DOS_STUB_TEXT);
DefaultMutableTreeNode rich = new DefaultMutableTreeNode(RICH_TEXT);
DefaultMutableTreeNode coff = new DefaultMutableTreeNode(COFF_FILE_HEADER_TEXT);
DefaultMutableTreeNode optional = new DefaultMutableTreeNode(OPTIONAL_HEADER_TEXT);
DefaultMutableTreeNode sections = new DefaultMutableTreeNode(SECTION_TABLE_TEXT);
DefaultMutableTreeNode overlay = new DefaultMutableTreeNode(OVERLAY_TEXT);
// OptionalHeader
DefaultMutableTreeNode standard = new DefaultMutableTreeNode(STANDARD_FIELDS_TEXT);
DefaultMutableTreeNode windows = new DefaultMutableTreeNode(WINDOWS_FIELDS_TEXT);
DefaultMutableTreeNode datadir = new DefaultMutableTreeNode(DATA_DIRECTORY_TEXT);
// Resources
DefaultMutableTreeNode resources = new DefaultMutableTreeNode(RESOURCES_TEXT);
DefaultMutableTreeNode manifest = new DefaultMutableTreeNode(MANIFEST_TEXT);
DefaultMutableTreeNode version = new DefaultMutableTreeNode(VERSION_INFO_TEXT);
DefaultMutableTreeNode icons = new DefaultMutableTreeNode(ICONS_TEXT);
DefaultMutableTreeNode rtstrings = new DefaultMutableTreeNode(RT_STRING_TEXT);
// Data directories
DefaultMutableTreeNode imports = new DefaultMutableTreeNode(IMPORTS_TEXT);
DefaultMutableTreeNode delayLoad = new DefaultMutableTreeNode(DELAY_LOAD_IMPORTS_TEXT);
DefaultMutableTreeNode bound = new DefaultMutableTreeNode(BOUND_IMPORTS_TEXT);
DefaultMutableTreeNode exports = new DefaultMutableTreeNode(EXPORTS_TEXT);
DefaultMutableTreeNode debug = new DefaultMutableTreeNode(DEBUG_TEXT);
// .NET related
DefaultMutableTreeNode dotNet = new DefaultMutableTreeNode(DOT_NET_TEXT);
DefaultMutableTreeNode dotNetRoot = new DefaultMutableTreeNode(DOT_NET_METADATA_ROOT_TEXT);
DefaultMutableTreeNode dotNetStreams = new DefaultMutableTreeNode(DOT_NET_STREAM_HEADERS_TEXT);
DefaultMutableTreeNode dotNetOptStream = new DefaultMutableTreeNode(DOT_NET_OPTIMIZED_STREAM_TEXT);
// Non-PE
DefaultMutableTreeNode anomaly = new DefaultMutableTreeNode(ANOMALY_TEXT);
DefaultMutableTreeNode hashes = new DefaultMutableTreeNode(HASHES_TEXT);
DefaultMutableTreeNode vis = new DefaultMutableTreeNode(VISUALIZATION_TEXT);
DefaultMutableTreeNode signatures = new DefaultMutableTreeNode(SIGNATURES_TEXT);
// adding the sub nodes for optional header
optional.add(standard);
optional.add(windows);
optional.add(datadir);
// add the child nodes to the root node
root.add(pe);
pe.add(dosStub);
if (peData.getPeData().maybeGetRichHeader().isPresent()) {
pe.add(rich);
}
pe.add(coff);
pe.add(optional);
pe.add(sections);
if (peData.hasResources()) {
pe.add(resources);
if (peData.hasManifest()) {
resources.add(manifest);
}
if(peData.hasVersionInfo()) {
resources.add(version);
}
if(peData.hasIcons()){
resources.add(icons);
}
if(peData.hasRTStrings()) {
resources.add(rtstrings);
}
}
if(peData.hasImports()){
pe.add(imports);
}
if(peData.hasDelayLoadImports()){
pe.add(delayLoad);
}
if(peData.hasBoundImportEntries()) {
pe.add(bound);
}
if(peData.hasExports()){
pe.add(exports);
}
if(peData.hasDebugInfo()) {
pe.add(debug);
}
if (peData.overlayExists()) {
pe.add(overlay);
LOGGER.debug("Overlay added to root node of tree");
}
if(peData.isDotNet()) {
root.add(dotNet);
dotNet.add(dotNetRoot);
dotNet.add(dotNetStreams);
if(peData.hasOptimizedStream()) {
dotNetStreams.add(dotNetOptStream);
this.clrTableNames = peData.getClrTables().keySet().stream().sorted().collect(Collectors.toList());
for (String name : clrTableNames) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
dotNetOptStream.add(node);
}
}
}
root.add(anomaly);
root.add(hashes);
root.add(vis);
root.add(signatures);
// no root
peTree.setRootVisible(false);
// reload the tree model to actually show the update
DefaultTreeModel model = (DefaultTreeModel) peTree.getModel();
model.reload();
// expand the tree per default except for .NET CLR tables
setTreeExpandedState(peTree, true);
setNodeExpandedState(peTree, dotNetOptStream, false);
}
// this method is from https://www.logicbig.com/tutorials/java-swing/jtree-expand-collapse-all-nodes.html
private static void setTreeExpandedState(JTree tree, boolean expanded) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getModel().getRoot();
setNodeExpandedState(tree, node, expanded);
}
// this method is from https://www.logicbig.com/tutorials/java-swing/jtree-expand-collapse-all-nodes.html
private static void setNodeExpandedState(JTree tree, DefaultMutableTreeNode node, boolean expanded) {
List<DefaultMutableTreeNode> list = Collections.list(node.children());
for (DefaultMutableTreeNode treeNode : list) {
setNodeExpandedState(tree, treeNode, expanded);
}
if (!expanded && node.isRoot()) {
return;
}
TreePath path = new TreePath(node.getPath());
if (expanded) {
tree.expandPath(path);
} else {
tree.collapsePath(path);
}
}
public void setSelectionRow(int i) {
peTree.setSelectionRow(i);
}
private void initTree() {
//create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("PE Format");
//create the tree by passing in the root node
this.peTree = new JTree(root);
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) peTree.getCellRenderer();
Icon leafIcon = new ImageIcon(getClass().getResource("/document-red-icon.png"));
Icon openIcon = new ImageIcon(getClass().getResource("/Places-folder-red-icon.png"));
Icon closeIcon = new ImageIcon(getClass().getResource("/folder-red-icon.png"));
renderer.setLeafIcon(leafIcon);
renderer.setOpenIcon(openIcon);
renderer.setOpenIcon(closeIcon);
// set scrollbar
JScrollPane scrollPane = new JScrollPane(peTree);
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
peTree.setRootVisible(false);
peTree.addTreeSelectionListener(e -> selectionChanged(e.getNewLeadSelectionPath()));
this.setVisible(true);
}
private void selectionChanged(TreePath path) {
if (path == null)
return; // this happens when a selected node was removed, e.g., new file with no overlay loaded
String node = path.getLastPathComponent().toString();
LOGGER.debug("Tree selection changed to " + node);
switch (node) {
case DOS_STUB_TEXT:
peDetailsPanel.showDosStub();
return;
case RICH_TEXT:
peDetailsPanel.showRichHeader();
return;
case COFF_FILE_HEADER_TEXT:
peDetailsPanel.showCoffFileHeader();
return;
case OPTIONAL_HEADER_TEXT:
peDetailsPanel.showOptionalHeader();
return;
case STANDARD_FIELDS_TEXT:
peDetailsPanel.showStandardFieldsTable();
return;
case WINDOWS_FIELDS_TEXT:
peDetailsPanel.showWindowsFieldsTable();
return;
case DATA_DIRECTORY_TEXT:
peDetailsPanel.showDataDirectoryTable();
return;
case SECTION_TABLE_TEXT:
peDetailsPanel.showSectionTable();
return;
case PE_HEADERS_TEXT:
peDetailsPanel.showPEHeaders();
return;
case OVERLAY_TEXT:
peDetailsPanel.showOverlay();
return;
case MANIFEST_TEXT:
peDetailsPanel.showManifests();
return;
case RESOURCES_TEXT:
peDetailsPanel.showResources();
return;
case VERSION_INFO_TEXT:
peDetailsPanel.showVersionInfo();
return;
case IMPORTS_TEXT:
peDetailsPanel.showImports();
return;
case DELAY_LOAD_IMPORTS_TEXT:
peDetailsPanel.showDelayLoadImports();
return;
case BOUND_IMPORTS_TEXT:
peDetailsPanel.showBoundImports();
return;
case EXPORTS_TEXT:
peDetailsPanel.showExports();
return;
case DEBUG_TEXT:
peDetailsPanel.showDebugInfo();
return;
case ANOMALY_TEXT:
peDetailsPanel.showAnomalies();
return;
case HASHES_TEXT:
peDetailsPanel.showHashes();
return;
case VISUALIZATION_TEXT:
peDetailsPanel.showVisualization();
return;
case PE_FORMAT_TEXT:
peDetailsPanel.showPEFormat();
return;
case ICONS_TEXT:
peDetailsPanel.showIcons();
return;
case SIGNATURES_TEXT:
peDetailsPanel.showSignatures();
return;
case RT_STRING_TEXT:
peDetailsPanel.showRTStrings();
return;
case DOT_NET_METADATA_ROOT_TEXT:
peDetailsPanel.showDotNetMetadataRoot();
return;
case DOT_NET_STREAM_HEADERS_TEXT:
peDetailsPanel.showDotNetStreamHeaders();
return;
case DOT_NET_OPTIMIZED_STREAM_TEXT:
peDetailsPanel.showOptimizedStream();
return;
}
for(String name : clrTableNames){
if(node.equals(name)) {
peDetailsPanel.showClrTable(name);
return;
}
}
}
public void refreshSelection() {
TreePath[] paths = peTree.getSelectionModel().getSelectionPaths();
if(paths.length > 0) {
// trigger selection change on same element to refresh the view
selectionChanged(paths[0]);
}
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/PEFieldsTable.java | src/main/java/io/github/struppigel/gui/PEFieldsTable.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import io.github.struppigel.gui.pedetails.FileContentPreviewPanel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.Vector;
public class PEFieldsTable extends JTable {
private static final Logger LOGGER = LogManager.getLogger();
private final boolean enableHex;
private int previewOffsetColumn;
public PEFieldsTable(boolean enableHex) {
this.enableHex = enableHex;
initTable();
}
public void setPreviewOffsetColumn(int column, FileContentPreviewPanel previewPanel) {
this.previewOffsetColumn = column;
initOffsetListener(this, previewPanel);
}
private void initTable() {
// set PETableModel for proper sorting of integers and longs
DefaultTableModel model = new PETableModel();
setModel(model);
// show long and int as hexadecimal string
setDefaultRenderer(Long.class, new HexValueRenderer(enableHex));
setDefaultRenderer(Integer.class, new HexValueRenderer(enableHex));
setPreferredScrollableViewportSize(new Dimension(500, 70));
setFillsViewportHeight(true);
setAutoCreateRowSorter(true);
setDefaultEditor(Object.class, null); // make not editable
}
private void initOffsetListener(JTable table, FileContentPreviewPanel previewPanel) {
ListSelectionModel model = table.getSelectionModel();
model.addListSelectionListener(e -> {
Long offset = getOffsetForSelectedRow(table);
if(offset == null) return;
LOGGER.info(offset + " offset selected");
previewPanel.showContentAtOffset(offset);
});
}
private Long getOffsetForSelectedRow(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int row = getSelectedRow(table);
if (row == -1) return null;
Vector vRow = (Vector) model.getDataVector().elementAt(row);
Object offset = vRow.elementAt(previewOffsetColumn);
return (Long) offset;
}
/**
* Return a vector of the data in the currently selected row. Returns null if no row selected
*
* @param table
* @return vector of the data in the currently selected row or null if nothing selected
*/
private int getSelectedRow(JTable table) {
int rowIndex = table.getSelectedRow();
if (rowIndex >= 0) {
return table.convertRowIndexToModel(rowIndex);
}
return -1;
}
public static class PETableModel extends DefaultTableModel {
@Override
public Class<?> getColumnClass(int columnIndex) {
if (this.getColumnCount() < columnIndex || this.getRowCount() == 0) {
return Object.class;
}
Class clazz = getValueAt(0, columnIndex).getClass();
return clazz;
}
}
public static class HexValueRenderer extends DefaultTableCellRenderer {
private boolean enableHex;
public HexValueRenderer(boolean enableHex){
this.enableHex = enableHex;
}
@Override
public void setValue(Object value){
if(value == null) {
return;
}
if(value.getClass() == Long.class) {
Long lvalue = (Long) value;
if(enableHex) {
setText(toHex(lvalue));
} else {
setText(lvalue.toString());
}
}
if(value.getClass() == Integer.class) {
Integer ivalue = (Integer) value;
if(enableHex) {
setText(toHex(ivalue));
} else {
setText(ivalue.toString());
}
}
}
}
private static String toHex(Long num) {
return "0x" + Long.toHexString(num);
}
private static String toHex(Integer num) {
return "0x" + Integer.toHexString(num);
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/Starter.java | src/main/java/io/github/struppigel/gui/Starter.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import io.github.struppigel.settings.LookAndFeelSetting;
import io.github.struppigel.settings.PortexSettings;
import io.github.struppigel.settings.PortexSettingsKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
/**
* Sets the look and feel and starts the GUI
*/
public class Starter {
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
LOGGER.debug("starting program");
PortexSettings s = new PortexSettings();
if(s.valueEquals(PortexSettingsKey.LOOK_AND_FEEL, LookAndFeelSetting.PORTEX.toString())) {
setPortexLookAndFeel();
} else {
setSystemLookAndFeel();
}
initMainFrame(s);
}
private static void initMainFrame(PortexSettings s) {
SwingUtilities.invokeLater(() -> new MainFrame(s));
}
private static void setSystemLookAndFeel() {
try {
// Set System L&F
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
UIManager.put("Table.alternateRowColor", new Color(240,240,240));
}
catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e) {
LOGGER.error(e.getMessage());
}
}
private static void setPortexLookAndFeel() {
UIManager.put("nimbusBase", new Color(15, 0, 0));
UIManager.put("nimbusBlueGrey", new Color(170, 0, 0));
UIManager.put("control", Color.black);
// UIManager.put("ToggleButton.disabled", Color.yellow);
//UIManager.put("ToggleButton.foreground", Color.yellow);
//UIManager.put("ToolBar.opaque", true);
//UIManager.put("ToolBar.background", new Color(100, 0, 0));
//UIManager.put("ToolBar.disabled", Color.green);
//UIManager.put("ToolBar.foreground", Color.red);
UIManager.put("text", Color.white);
UIManager.put("nimbusSelectionBackground", Color.gray);
UIManager.put("nimbusSelectedText", Color.white);
UIManager.put("textHighlight", Color.lightGray);
UIManager.put("nimbusFocus", new Color(0xBA3A1E));
UIManager.put("nimbusSelection", new Color(170, 0, 0));
UIManager.put("textBackground", Color.darkGray);
UIManager.put("nimbusLightBackground", Color.black);
UIManager.put("Table.alternateRowColor", new Color(20,20,20));
/*
UIManager.put("ToolBar.background", Color.blue);
UIManager.put("ToolBar.foreground", Color.blue);
UIManager.put("ToolBar.disabled", Color.blue);
UIManager.put("ToolBar.opaque", false);
*/
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e) {
LOGGER.error(e.getMessage());
}
break;
}
}
}
} | java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/MainFrame.java | src/main/java/io/github/struppigel/gui/MainFrame.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import io.github.struppigel.gui.pedetails.FileContentPreviewPanel;
import io.github.struppigel.gui.pedetails.PEDetailsPanel;
import io.github.struppigel.gui.utils.PELoadWorker;
import io.github.struppigel.gui.utils.PortexSwingUtils;
import io.github.struppigel.gui.utils.WorkerKiller;
import io.github.struppigel.gui.utils.WriteSettingsWorker;
import io.github.struppigel.settings.LookAndFeelSetting;
import io.github.struppigel.settings.PortexSettings;
import io.github.struppigel.settings.PortexSettingsKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ItemEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import static javax.swing.SwingUtilities.invokeLater;
import static javax.swing.SwingWorker.StateValue.DONE;
/**
* The main frame that sets everything in place and holds the main menu.
*/
public class MainFrame extends JFrame {
private static final Logger LOGGER = LogManager.getLogger();
private final JLabel filePathLabel = new JLabel();
private final VisualizerPanel visualizerPanel = new VisualizerPanel();;
private final PEDetailsPanel peDetailsPanel;
private final PortexSettings settings;
private FullPEData pedata = null;
private PEComponentTree peComponentTree;
;
private JFrame progressBarFrame;
private JProgressBar progressBar;
private final static String versionURL = "https://github.com/struppigel/PortexAnalyzerGUI/raw/main/resources/upd_version.txt";
private final static String currVersion = "/upd_version.txt";
private final static String releasePage = "https://github.com/struppigel/PortexAnalyzerGUI/releases";
private final JLabel progressText = new JLabel("Loading ...");
private final JPanel cardPanel = new JPanel(new CardLayout());
private FileContentPreviewPanel fileContent = new FileContentPreviewPanel();
public MainFrame(PortexSettings settings) {
super("Portex Analyzer v. " + AboutFrame.version);
this.settings = settings;
peDetailsPanel = new PEDetailsPanel(cardPanel, this, settings, fileContent);
peComponentTree = new PEComponentTree(peDetailsPanel);
initGUI();
initDropTargets();
checkForUpdate();
setToHex(settings.valueEquals(PortexSettingsKey.VALUES_AS_HEX, "1"));
}
private void checkForUpdate() {
// only update if setting does not prevent it
if(settings.valueEquals(PortexSettingsKey.DISABLE_UPDATE,"1")) {
return;
}
UpdateWorker updater = new UpdateWorker();
updater.execute();
}
public void refreshSelection() {
peComponentTree.refreshSelection();
}
private static class UpdateWorker extends SwingWorker<Boolean, Void> {
@Override
protected Boolean doInBackground() {
try {
URL githubURL = new URL(versionURL);
try (InputStreamReader is = new InputStreamReader(getClass().getResourceAsStream(currVersion), StandardCharsets.UTF_8);
BufferedReader versionIn = new BufferedReader(is);
Scanner s = new Scanner(githubURL.openStream())) {
int versionHere = Integer.parseInt(versionIn.readLine().trim());
int githubVersion = s.nextInt();
if (versionHere < githubVersion) {
return true;
}
}
} catch (UnknownHostException e) {
LOGGER.info("unknown host or no internet connection: " + e.getMessage());
} catch (IOException | NumberFormatException e) {
LOGGER.error(e);
e.printStackTrace();
}
return false;
}
protected void done() {
try {
if (get()) {
LOGGER.debug("update requested");
String message = "A new version is available. Do you want to download it?";
int response = JOptionPane.showConfirmDialog(null,
message,
"Update available",
JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION) {
openWebpage(new URL(releasePage));
}
} else {
LOGGER.debug("no update necessary");
}
} catch (InterruptedException | ExecutionException | MalformedURLException e) {
LOGGER.error(e);
}
}
}
private static boolean openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
return true;
} catch (IOException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
return false;
}
private static boolean openWebpage(URL url) {
try {
return openWebpage(url.toURI());
} catch (URISyntaxException e) {
LOGGER.error(e);
e.printStackTrace();
}
return false;
}
private void initDropTargets() {
// file drag and drop support
this.setDropTarget(new FileDropper());
peDetailsPanel.setDropTarget(new FileDropper());
visualizerPanel.setDropTarget(new FileDropper());
filePathLabel.setDropTarget(new FileDropper());
}
private void loadFile(File file) {
PELoadWorker worker = new PELoadWorker(file, this, progressText);
worker.addPropertyChangeListener(evt -> {
String name = evt.getPropertyName();
if (name.equals("progress")) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
progressBar.setString(progress + " %");
progressBarFrame.toFront();
progressBarFrame.setAlwaysOnTop(true);
} else if (name.equals("state")) {
SwingWorker.StateValue state = (SwingWorker.StateValue) evt
.getNewValue();
if (state == DONE) {
progressBarFrame.setVisible(false);
}
}
});
progressBarFrame.setVisible(true);
WorkerKiller.getInstance().cancelAndDeleteWorkers();
WorkerKiller.getInstance().addWorker(worker); // need to add this in case a user loads another PE during load process
worker.execute();
}
public void setPeData(FullPEData data) {
try {
this.pedata = data;
visualizerPanel.visualizePE(pedata.getFile());
peDetailsPanel.setPeData(pedata);
peComponentTree.setPeData(pedata);
peComponentTree.setSelectionRow(0);
fileContent.setPeData(pedata);
} catch (IOException e) {
String message = "Could not load PE file! Reason: " + e.getMessage();
LOGGER.error(message);
e.printStackTrace();
JOptionPane.showMessageDialog(this,
message,
"Unable to load",
JOptionPane.ERROR_MESSAGE);
}
}
private void initGUI() {
// Main frame settings
setSize(1280, 768);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Init main panel that holds everything
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// init Card Panel on the right
this.cardPanel.add(visualizerPanel, "VISUALIZER");
this.cardPanel.add(fileContent, "FILE_CONTENT");
if(settings.valueEquals(PortexSettingsKey.CONTENT_PREVIEW, "1")) {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "FILE_CONTENT");
} else {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "VISUALIZER");
}
// Add all other components
panel.add(peDetailsPanel, BorderLayout.CENTER);
panel.add(peComponentTree, BorderLayout.LINE_START);
panel.add(cardPanel, BorderLayout.LINE_END);
this.add(panel, BorderLayout.CENTER);
initToolbar();
initMenu();
initProgressBar();
}
private void initToolbar() {
JToolBar toolBar = new JToolBar();
ImageIcon ico = new ImageIcon(getClass().getResource("/icons8-hexadecimal-24.png"));
JToggleButton hexButton = new JToggleButton(ico);
hexButton.setSelected(settings.valueEquals(PortexSettingsKey.VALUES_AS_HEX, "1"));
hexButton.addItemListener(e -> {
int state = e.getStateChange();
if (state == ItemEvent.SELECTED) {
setToHex(true);
settings.put(PortexSettingsKey.VALUES_AS_HEX, "1");
} else if (state == ItemEvent.DESELECTED) {
setToHex(false);
settings.put(PortexSettingsKey.VALUES_AS_HEX, "0");
}
new WriteSettingsWorker(settings).execute();
});
ImageIcon imgIco = new ImageIcon(getClass().getResource("/icons8-image-24.png"));
JToggleButton imgButton = new JToggleButton(imgIco);
imgButton.setSelected(settings.valueEquals(PortexSettingsKey.CONTENT_PREVIEW, "0"));
imgButton.addItemListener(e -> {
int state = e.getStateChange();
if(state == ItemEvent.SELECTED){
((CardLayout) cardPanel.getLayout()).show(cardPanel, "VISUALIZER");
settings.put(PortexSettingsKey.CONTENT_PREVIEW, "0");
} else {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "FILE_CONTENT");
settings.put(PortexSettingsKey.CONTENT_PREVIEW, "1");
}
cardPanel.repaint();
fileContent.repaint();
new WriteSettingsWorker(settings).execute();
});
toolBar.add(hexButton);
toolBar.add(imgButton);
toolBar.add(Box.createHorizontalGlue());
toolBar.add(filePathLabel);
toolBar.add(Box.createHorizontalGlue());
toolBar.setOpaque(true);
add(toolBar, BorderLayout.PAGE_START);
toolBar.repaint();
}
private void setToHex(boolean hexEnabled) {
peDetailsPanel.setHexEnabled(hexEnabled);
}
private void initProgressBar() {
this.progressBarFrame = new JFrame("Loading PE file");
JPanel panel = new JPanel();
this.progressBar = new JProgressBar();
progressBar.setPreferredSize(new Dimension(250, 25));
progressBar.setIndeterminate(false);
progressBar.setStringPainted(true);
progressBar.setMaximum(100);
panel.setLayout(new GridLayout(0, 1));
panel.add(progressBar);
// this panel makes sure the text is in the middle
JPanel middleText = new JPanel();
middleText.add(progressText);
panel.add(middleText);
progressBarFrame.add(panel);
progressBarFrame.pack();
progressBarFrame.setSize(400, 100);
progressBarFrame.setLocationRelativeTo(null);
progressBarFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = createFileMenu();
JMenu help = createHelpMenu();
JMenu settingsMenu = createSettingsMenu();
menuBar.add(fileMenu);
menuBar.add(settingsMenu);
menuBar.add(help);
this.setJMenuBar(menuBar);
}
private JMenu createSettingsMenu() {
JMenu settingsMenu = new JMenu("Settings");
JCheckBoxMenuItem disableYaraWarn = new JCheckBoxMenuItem("Disable Yara warnings");
JCheckBoxMenuItem disableUpdateCheck = new JCheckBoxMenuItem("Disable update check");
JCheckBoxMenuItem systemTheme = new JCheckBoxMenuItem("Use system theme");
disableUpdateCheck.setState(settings.valueEquals(PortexSettingsKey.DISABLE_UPDATE, "1"));
disableYaraWarn.setState(settings.valueEquals(PortexSettingsKey.DISABLE_YARA_WARNINGS, "1"));
systemTheme.setState(settings.valueEquals(PortexSettingsKey.LOOK_AND_FEEL, LookAndFeelSetting.SYSTEM.toString()));
settingsMenu.add(disableYaraWarn);
settingsMenu.add(disableUpdateCheck);
settingsMenu.add(systemTheme);
disableYaraWarn.addActionListener(e -> {
if(disableYaraWarn.getState()) {
settings.put(PortexSettingsKey.DISABLE_YARA_WARNINGS, "1");
} else {
settings.put(PortexSettingsKey.DISABLE_YARA_WARNINGS, "0");
}
try {
settings.writeSettings();
} catch (IOException ex) {
LOGGER.error(e);
}
});
disableUpdateCheck.addActionListener(e -> {
if(disableUpdateCheck.getState()) {
settings.put(PortexSettingsKey.DISABLE_UPDATE, "1");
} else {
settings.put(PortexSettingsKey.DISABLE_UPDATE, "0");
}
try {
settings.writeSettings();
} catch (IOException ex) {
LOGGER.error(e);
}
});
systemTheme.addActionListener(e -> {
JOptionPane.showMessageDialog(this,
"Please restart PortexAnalyzerGUI for the new theme!",
"Theme changed",
JOptionPane.INFORMATION_MESSAGE);
if(systemTheme.getState()) {
settings.put(PortexSettingsKey.LOOK_AND_FEEL, LookAndFeelSetting.SYSTEM.toString());
} else {
settings.put(PortexSettingsKey.LOOK_AND_FEEL, LookAndFeelSetting.PORTEX.toString());
}
try {
settings.writeSettings();
} catch (IOException ex) {
LOGGER.error(e);
}
});
return settingsMenu;
}
private JMenu createHelpMenu() {
JMenu help = new JMenu("Help");
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(arg0 -> invokeLater(() -> {
AboutFrame aFrame = new AboutFrame();
aFrame.setVisible(true);
}));
return help;
}
private JMenu createFileMenu() {
// open file
JMenu fileMenu = new JMenu("File");
JMenuItem open = new JMenuItem("Open...", new ImageIcon(getClass().getResource("/laptop-bug-icon.png")));
fileMenu.add(open);
open.addActionListener(arg0 -> {
String path = PortexSwingUtils.getOpenFileNameFromUser(this);
if (path != null) {
filePathLabel.setText(path);
loadFile(new File(path));
}
});
// close application
JMenuItem exit = new JMenuItem("Exit", new ImageIcon(getClass().getResource("/moon-icon.png")));
fileMenu.add(exit);
exit.addActionListener(arg0 -> dispose());
return fileMenu;
}
private class FileDropper extends DropTarget {
public synchronized void drop(DropTargetDropEvent evt) {
try {
evt.acceptDrop(DnDConstants.ACTION_COPY);
List<File> droppedFiles = (List<File>)
evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
if (droppedFiles.size() > 0) {
File file = droppedFiles.get(0);
filePathLabel.setText(file.getAbsolutePath());
loadFile(file);
}
} catch (IOException | UnsupportedFlavorException ex) {
String message = "Could not load PE file from dropper! Reason: " + ex.getMessage();
LOGGER.error(message);
ex.printStackTrace();
JOptionPane.showMessageDialog(null,
message,
"Unable to load",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/VisualizerPanel.java | src/main/java/io/github/struppigel/gui/VisualizerPanel.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import io.github.struppigel.tools.visualizer.ColorableItem;
import io.github.struppigel.tools.visualizer.ImageUtil;
import io.github.struppigel.tools.visualizer.Visualizer;
import io.github.struppigel.tools.visualizer.VisualizerBuilder;
import io.github.struppigel.gui.utils.WorkerKiller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
/**
* Panel with byteplot, entropy and PE structure image
*/
public class VisualizerPanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private javax.swing.Timer waitingTimer;
private final JLabel visLabel = new JLabel();
private File pefile;
private final static int RESIZE_DELAY = 1000;
private JProgressBar scanRunningBar = new JProgressBar();
private boolean enableLegend = false;
private boolean enableByteplot = true;
private boolean enableEntropy = true;
private int imageWidth = 50;
private BufferedImage image;
public VisualizerPanel() {
super();
initPanel();
}
public VisualizerPanel(boolean enableLegend, boolean enableByteplot, boolean enableEntropy, int imageWidth) {
super();
this.enableByteplot = enableByteplot;
this.enableEntropy = enableEntropy;
this.enableLegend = enableLegend;
this.imageWidth = imageWidth;
initPanel();
}
private void initPanel(){
this.removeAll();
setLayout(new BorderLayout());
add(visLabel, BorderLayout.CENTER);
addComponentListener(new ResizeListener());
/*JToolBar toolBar = new JToolBar();
ImageIcon ico = new ImageIcon(getClass().getResource("/science-icon.png"));
toolBar.add(new JToggleButton(ico));
add(toolBar, BorderLayout.PAGE_START);*/
}
public void visualizePE(File pefile) throws IOException {
this.pefile = pefile;
SwingWorker worker = new VisualizerWorker(getHeight(), imageWidth, pefile, enableEntropy, enableByteplot, enableLegend);
WorkerKiller.getInstance().addWorker(worker);
worker.execute();
initProgressBar();
}
private void initProgressBar() {
this.removeAll();
this.add(scanRunningBar);
this.setLayout(new FlowLayout());
scanRunningBar.setIndeterminate(true);
scanRunningBar.setVisible(true);
this.repaint();
}
public BufferedImage getImage() {
return image;
}
private class VisualizerWorker extends SwingWorker<BufferedImage, Void> {
private final int maxHeight;
private final File file;
private final boolean showEntropy;
private final boolean showByteplot;
private final boolean showLegend;
private final int width;
private int pixelSize = 4;
public VisualizerWorker(int height, int width, File file, boolean showEntropy, boolean showByteplot, boolean showLegend) {
this.maxHeight = height;
this.width = width;
this.file = file;
this.showEntropy = showEntropy;
this.showByteplot = showByteplot;
this.showLegend = showLegend;
}
private int height(int nrBytes) {
double nrOfPixels = file.length() / (double) nrBytes;
double pixelsPerRow = width / (double) pixelSize;
double pixelsPerCol = nrOfPixels / pixelsPerRow;
return (int) Math.ceil(pixelsPerCol * pixelSize);
}
@Override
protected BufferedImage doInBackground() throws Exception {
if(pefile == null) return null;
// bps
int res = 1;
while(height(res) > maxHeight) res *= 2;
int bytesPerPixel = res;
Visualizer visualizer = new VisualizerBuilder()
.setFileWidth(width)
.setPixelSize(pixelSize)
.setBytesPerPixel(bytesPerPixel, file.length())
.setColor(ColorableItem.ENTROPY, Color.cyan)
.build();
BufferedImage peImage = visualizer.createImage(file);
if(showEntropy){
BufferedImage entropyImg = visualizer.createEntropyImage(file);
peImage = ImageUtil.appendImages(entropyImg, peImage);
}
if(showByteplot) {
int bytePlotPixelSize = (width * height(bytesPerPixel) > file.length()) ? pixelSize : 1;
Visualizer vi2 = new VisualizerBuilder() // more fine grained bytePlot, hence new visualizer
.setPixelSize(bytePlotPixelSize)
.setFileWidth(width)
.setHeight(height(bytesPerPixel))
.build();
BufferedImage bytePlot = vi2.createBytePlot(file);
peImage = ImageUtil.appendImages(bytePlot, peImage);
}
if(showLegend) {
BufferedImage legendImage = visualizer.createLegendImage(showByteplot, showEntropy, true);
peImage = ImageUtil.appendImages(peImage, legendImage);
}
return peImage;
}
@Override
protected void done() {
if(isCancelled()){return;}
try {
image = get();
if(image == null) return;
initPanel();
visLabel.setIcon(new ImageIcon(image));
visLabel.repaint();
} catch (InterruptedException e) {
String message = "Problem with visualizer! Reason: " + e.getMessage();
LOGGER.error(message);
e.printStackTrace(); // no dialog necessary
} catch (ExecutionException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
}
private class ResizeListener extends ComponentAdapter implements ActionListener {
public void componentResized(ComponentEvent e) {
if(waitingTimer == null) {
try {
waitingTimer = new Timer(RESIZE_DELAY, this);
waitingTimer.start();
} catch (Exception ex) {
LOGGER.error("Visualization update failed " + ex.getMessage());
throw new RuntimeException(ex);
}
} else {
waitingTimer.restart();
}
}
public void actionPerformed(ActionEvent ae)
{
/* Timer finished? */
if (ae.getSource()==waitingTimer)
{
/* Stop timer */
waitingTimer.stop();
waitingTimer = null;
/* Resize */
applyResize();
}
}
private void applyResize() {
SwingWorker worker = new VisualizerWorker(getHeight(), imageWidth, pefile, enableEntropy, enableByteplot, enableLegend);
WorkerKiller.getInstance().addWorker(worker);
worker.execute();
}
}
public void setEnableLegend(boolean enableLegend) {
this.enableLegend = enableLegend;
}
public void setEnableByteplot(boolean enableByteplot) {
this.enableByteplot = enableByteplot;
}
public void setEnableEntropy(boolean enableEntropy) {
this.enableEntropy = enableEntropy;
}
public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/AboutFrame.java | src/main/java/io/github/struppigel/gui/AboutFrame.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import javax.swing.*;
/**
* Small window showing the stuff in the About section
*/
public class AboutFrame extends JFrame {
private static final long serialVersionUID = 1L;
public static String version = "0.13.2";
private static final String text = "Portex Analyzer GUI" + "\n\n" + "Version: " + version
+ "\nAuthor: Karsten Hahn"
+ "\nLast update: 18. July 2024"
+ "\n\nI develop this software as a hobby in my free time."
+ "\n\nIf you like it, please consider buying me a coffee: https://ko-fi.com/struppigel"
+ "\n\nThe repository is available at https://github.com/struppigel/PortexAnalyzerGUI";
public AboutFrame() {
super("About PortexAnalyzer GUI");
initGUI();
}
private void initGUI() {
this.setSize(350, 320);
this.setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTextArea area = new JTextArea();
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setText(text);
area.setEditable(false);
this.add(area);
}
} | java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/FullPEData.java | src/main/java/io/github/struppigel/gui/FullPEData.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui;
import io.github.struppigel.parser.PEData;
import io.github.struppigel.parser.StandardField;
import io.github.struppigel.parser.sections.clr.CLRSection;
import io.github.struppigel.parser.sections.clr.CLRTable;
import io.github.struppigel.parser.sections.clr.OptimizedStream;
import io.github.struppigel.parser.sections.edata.ExportEntry;
import io.github.struppigel.parser.sections.idata.ImportDLL;
import io.github.struppigel.parser.sections.rsrc.Resource;
import io.github.struppigel.parser.sections.rsrc.icon.IconParser;
import io.github.struppigel.tools.Overlay;
import io.github.struppigel.gui.utils.TableContent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Wrapper for the PE data. Contains all data that must be parsed from file and converted by a worker.
* This class makes sure to save all the data that we do not want to compute several times and
* definitely do not want to compute in the event dispatch thread.
* It stores that data in a form that is easily digestible by the GUI and does not need intensive transformations.
*/
public class FullPEData {
private static final Logger LOGGER = LogManager.getLogger();
private final PEData pedata;
private final Overlay overlay;
private final double overlayEntropy;
private final List<String> overlaySignatures;
private final double[] sectionEntropies;
private final List<ImportDLL> imports;
private final List<Object[]> importTableEntries;
private final List<Object[]> delayLoadEntries;
private final List<Object[]> boundImportEntries;
private final List<Object[]> resourceTableEntries;
private final List<Resource> resources;
private final List<ExportEntry> exports;
private final String hashes;
private final List<Object[]> anomaliesTable;
private final List<TableContent> debugTableEntries;
private final List<Object[]> vsInfoTable;
private final List<String> manifests;
private final List<Object[]> exportTableEntries;
private final List<Object[]> sectionHashTableEntries;
private final String rehintsReport;
private final List<Object[]> stringTableEntries;
private final List<StandardField> dotNetMetadataRootTableEntries;
private final java.util.Optional<CLRSection> maybeCLR;
private final List<Object[]> dotNetStreamHeaders;
private final List<StandardField> optimizedStreamEntries;
private final Map<String, List<List<Object>>> clrTables;
private final Map<String, List<String>> clrTableHeaders;
private final long OFFSET_DEFAULT = 0L;
public FullPEData(PEData data, Overlay overlay, double overlayEntropy, List<String> overlaySignatures,
double[] sectionEntropies, List<ImportDLL> imports, List<Object[]> importTableEntries, List<Object[]> delayLoadEntries,
List<Object[]> boundImportEntries,
List<Object[]> resourceTableEntries, List<Resource> resources, List<String> manifests,
List<Object[]> exportTableEntries, List<ExportEntry> exports,
String hashes, List<Object[]> sectionHashTableEntries,
List<Object[]> anomaliesTable, List<TableContent> debugTableEntries, List<Object[]> vsInfoTable,
String rehintsReport, List<Object[]> stringTableEntries, List<StandardField> dotNetMetadataRootTableEntries,
java.util.Optional<CLRSection> maybeCLR, List<Object[]> dotNetStreamHeaders, List<StandardField> optimizedStreamEntries,
Map<String, List<List<Object>>> clrTables, Map<String, List<String>> clrTableHeaders) {
this.pedata = data;
this.overlay = overlay;
this.overlayEntropy = overlayEntropy;
this.overlaySignatures = overlaySignatures;
this.sectionEntropies = sectionEntropies;
this.imports = imports;
this.importTableEntries = importTableEntries;
this.delayLoadEntries = delayLoadEntries;
this.boundImportEntries = boundImportEntries;
this.resourceTableEntries = resourceTableEntries;
this.resources = resources;
this.manifests = manifests;
this.exportTableEntries = exportTableEntries;
this.exports = exports;
this.hashes = hashes;
this.sectionHashTableEntries = sectionHashTableEntries;
this.anomaliesTable = anomaliesTable;
this.debugTableEntries = debugTableEntries;
this.vsInfoTable = vsInfoTable;
this.rehintsReport = rehintsReport;
this.stringTableEntries = stringTableEntries;
this.dotNetMetadataRootTableEntries = dotNetMetadataRootTableEntries;
this.maybeCLR = maybeCLR;
this.dotNetStreamHeaders = dotNetStreamHeaders;
this.optimizedStreamEntries = optimizedStreamEntries;
this.clrTables = clrTables;
this.clrTableHeaders = clrTableHeaders;
}
public Map<String, List<String>> getClrTableHeaders() { return clrTableHeaders; }
public Map<String, List<List<Object>>> getClrTables() { return clrTables; }
public PEData getPeData() {
return pedata;
}
public Overlay getOverlay() {
return overlay;
}
public double getOverlayEntropy() {
return overlayEntropy;
}
public List<String> getOverlaySignatures() {
return overlaySignatures;
}
public File getFile() {
return pedata.getFile();
}
public List<Object[]> getImportTableEntries() {
return importTableEntries;
}
public List<Object[]> getDelayLoadEntries() {return delayLoadEntries;}
public List<Object[]> getBoundImportEntries() {return boundImportEntries;}
public boolean hasBoundImportEntries() {return !boundImportEntries.isEmpty();}
public boolean hasManifest() {
return getManifests().size() > 0;
}
/**
* Obtain manifest as string. Returns empty string if no manifest exists, could not be read or is too large.
* @return UTF-8 string of manifest, or empty string if not exists
*/
public List<String> getManifests() {
return manifests;
}
/**
* Check for presence of resources,
* @return true of at least one resource exists, false if not there or if exceptions occur
*/
public boolean hasResources() {
return resources.size() > 0;
}
/**
* Check overlay presence without dealing with exceptions from reading. Returns false if exception occurs.
* @return true if overlay exists, false otherwise or if exception occurs while reading
*/
public boolean overlayExists() {
try {
if (new Overlay(pedata).exists()) {
return true;
}
} catch (IOException e) {
LOGGER.error(e);
e.printStackTrace();
}
return false;
}
public boolean hasVersionInfo() {
return resources.stream().anyMatch(r -> r.getType().equals("RT_VERSION"));
}
public double getEntropyForSection(int secNumber) {
return sectionEntropies[secNumber-1] * 8;
}
public boolean hasImports() {
return imports.size() > 0;
}
public boolean hasDelayLoadImports() {
return delayLoadEntries.size() > 0;
}
public List<Object[]> getResourceTableEntries() {
return resourceTableEntries;
}
public List<Resource> getResources() {
return resources;
}
public boolean hasExports() {
return exports.size() > 0;
}
public List<Object[]> getExportTableEntries() {
return this.exportTableEntries;
}
public boolean hasDebugInfo() {
return debugTableEntries.size() > 0;
}
public String getHashesReport() {
return this.hashes;
}
public List<Object[]> getSectionHashTableEntries() {
return this.sectionHashTableEntries;
}
public List<Object[]> getAnomaliesTable() {
return anomaliesTable;
}
public List<TableContent> getDebugTableEntries() {
return debugTableEntries;
}
public List<Object[]> getVersionInfoTable() {
return vsInfoTable;
}
public boolean hasIcons() {
return resources.stream().anyMatch(r -> IconParser.isGroupIcon(r));
}
public String getReHintsReport() {
return this.rehintsReport;
}
public boolean hasRTStrings() {
return !stringTableEntries.isEmpty();
}
public List<Object[]> getRTStringTableEntries() {
return this.stringTableEntries;
}
public boolean isDotNet() { return !dotNetMetadataRootTableEntries.isEmpty(); }
public boolean hasOptimizedStream() { return !optimizedStreamEntries.isEmpty(); }
public List<StandardField> getDotNetMetadataRootEntries() {
return dotNetMetadataRootTableEntries;
}
public long getDotNetMetadataRootOffset(){
if(maybeCLR.isPresent() && !maybeCLR.get().isEmpty()) {
return maybeCLR.get().getMetadataRoot().getOffset();
} else {
return OFFSET_DEFAULT;
}
}
public String getDotNetMetadataVersionString(){
if(maybeCLR.isPresent() && !maybeCLR.get().isEmpty()) {
return maybeCLR.get().getMetadataRoot().getVersionString();
} else {
return "<no metadata root version string>";
}
}
public java.util.Optional<CLRTable> getClrTableForName(String name) {
Optional<CLRSection> clr = getPeData().loadClrSection();
if(clr.isPresent()) {
Optional<OptimizedStream> optStream = clr.get().getMetadataRoot().maybeGetOptimizedStream();
if (optStream.isPresent()) {
java.util.Optional<CLRTable> clrTable = optStream.get().getCLRTables().stream().filter(t -> name.contains(t.getTableName())).findFirst();
return clrTable;
}
}
return Optional.empty();
}
public long getClrTableOffset(String tableName) {
java.util.Optional<CLRTable> clrTable = getClrTableForName(tableName);
if(clrTable.isPresent()) {
return clrTable.get().getRawOffset();
}
return OFFSET_DEFAULT;
}
public List<Object[]> getDotNetStreamHeaderEntries() {
return this.dotNetStreamHeaders;
}
public List<StandardField> getOptimizedStreamEntries() {
return this.optimizedStreamEntries;
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/SectionsTabbedPanel.java | src/main/java/io/github/struppigel/gui/pedetails/SectionsTabbedPanel.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui.pedetails;
import io.github.struppigel.parser.sections.*;
import io.github.struppigel.gui.FullPEData;
import io.github.struppigel.gui.PEFieldsTable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static io.github.struppigel.parser.sections.SectionHeaderKey.*;
import static java.lang.Math.min;
/**
* There can be many sections, so this panel adds tabs at the top.
*/
public class SectionsTabbedPanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private FullPEData peData;
private final List<JTable> tables = new ArrayList<>();
private final JTabbedPane tabbedPane = new JTabbedPane();
private static final int SECTIONS_PER_TABLE = 4;
private static final int TABLES_PER_TAB = 2;
private static final int SECTION_NR_MAX = 200;
private boolean hexEnabled = true;
public SectionsTabbedPanel() {
this.setLayout(new GridLayout(0,1));
add(tabbedPane);
}
private void cleanUpTabsAndTables() {
tabbedPane.removeAll();
tables.clear();
//tabs.clear(); // this will make everything non-working, but why?
LOGGER.debug("Tabs and tables cleared");
}
public void setPeData(FullPEData peData){
LOGGER.debug("PEData for tabbed Pane changed");
this.peData = peData;
initializeContent();
}
public void initializeContent() {
LOGGER.debug("Init tabs for section tables");
cleanUpTabsAndTables();
SectionTable sectionTable = peData.getPeData().getSectionTable();
List<SectionHeader> sections = sectionTable.getSectionHeaders();
List<JPanel> tabs = initTabs(sections);
if (peData == null) {
LOGGER.error("PE Data is null!");
return;
}
initTables(tabs, sections);
LOGGER.debug("Section table shown");
refreshPanel(tabs);
}
private void initTables(List<JPanel> tabs, List<SectionHeader> sections) {
// we need that to calculate how many tabs and tables
// init counters
int tableCount = 0;
int tabIndex = 0;
// get first tab
JPanel currTab = tabs.get(tabIndex);
// a section group will contain SECTIONS_PER_TABLE sections max
List<SectionHeader> sectionGroup = new ArrayList<>();
// we want to add every section
for (SectionHeader currSec : sections) {
// obtain current section header and add to section group
sectionGroup.add(currSec);
// check if enough sections to create a table
if (sectionGroup.size() == SECTIONS_PER_TABLE) {
// create table with the sections and add table to current tab
addSingleTableForSections(sectionGroup, currTab);
// increment table counter
tableCount++;
// we added the sections to a table, so empty the list
sectionGroup.clear();
// check if we need to grab the next tab for the next table
if (tableCount % TABLES_PER_TAB == 0) {
// increment tab index (which is equal to tab count - 1)
tabIndex++;
// bounds check, in case we are already done with everything the index will be out of bounds
if (tabIndex < tabs.size()) {
currTab = tabs.get(tabIndex);
}
}
}
}
// add remaining tables
if(sectionGroup.size() > 0) {
addSingleTableForSections(sectionGroup, currTab);
tableCount++;
}
LOGGER.debug("Added " + tableCount + " tables and " + tabIndex + " tabs");
}
private List<JPanel> initTabs(List<SectionHeader> sections) {
int secNr = min(sections.size(), SECTION_NR_MAX);
int nrOfTabs = new Double(Math.ceil(secNr/(double)(TABLES_PER_TAB * SECTIONS_PER_TABLE))).intValue();
LOGGER.debug("Number of tabs to create: " + nrOfTabs);
if(nrOfTabs == 0){ nrOfTabs = 1;}
List<JPanel> tabs = new ArrayList<>();
for (int i = 0; i < nrOfTabs; i++) {
JPanel tab = new JPanel();
tab.setLayout(new GridLayout(0, 1));
tabbedPane.addTab((i + 1) + "", tab);
tabs.add(tab);
}
return tabs;
}
private void refreshPanel(List<JPanel> tabs) {
LOGGER.debug("Refreshing tabs");
for(JTable tbl : tables) {
tbl.revalidate();
tbl.repaint();
}
for(JPanel tab : tabs) {
tab.revalidate();
tab.repaint();
}
revalidate();
repaint();
tabbedPane.revalidate();
tabbedPane.repaint();
}
private void addSingleTableForSections(List<SectionHeader> sections, JPanel tab) {
LOGGER.info("Setting hex enabled to " + hexEnabled);
JTable table = new PEFieldsTable(hexEnabled);
DefaultTableModel model = new PEFieldsTable.PETableModel();
createTableHeaderForSections(sections, model);
createRowsForSections(sections, model);
table.setModel(model);
addTable(table, tab);
}
private void addTable(JTable table, JPanel tab) {
tables.add(table);
JScrollPane sPane = new JScrollPane(table);
tab.add(sPane);
}
private void createRowsForSections(List<SectionHeader> sections, DefaultTableModel model) {
// Section tables should only use string based sorting because there are mixed data types --> keep String[] type for rows
List<String[]> rows = new ArrayList<>();
SectionLoader loader = new SectionLoader(peData.getPeData());
boolean lowAlign = peData.getPeData().getOptionalHeader().isLowAlignmentMode();
// collect entropy
Stream<String> entropyRow = sections.stream().map(s -> String.format("%1.2f", peData.getEntropyForSection(s.getNumber())));
addStreamToRow(entropyRow, rows, "Entropy");
// collect Pointer To Raw Data
Stream<String> ptrToRawRow = sections.stream().map(s -> toHexIfEnabled(s.get(SectionHeaderKey.POINTER_TO_RAW_DATA)));
addStreamToRow(ptrToRawRow, rows, "Pointer To Raw Data");
// collect aligned Pointer To Raw Data
Stream<String> alignedPtrRaw = sections.stream().map(s -> toHexIfEnabled(s.getAlignedPointerToRaw(lowAlign)));
addStreamToRow(alignedPtrRaw, rows, "-> Aligned (act. start)");
// collect Size of Raw Data
Stream<String> sizeRawRow = sections.stream().map(s -> toHexIfEnabled(s.get(SIZE_OF_RAW_DATA)));
addStreamToRow(sizeRawRow, rows, "Size Of Raw Data");
// collect actual read size
Stream<String> readSizeRow = sections.stream().map(s -> s.get(SIZE_OF_RAW_DATA) != loader.getReadSize(s) ? toHexIfEnabled(loader.getReadSize(s)) : "");
addStreamToRow(readSizeRow, rows, "-> Actual Read Size");
// collect Physical End
Stream<String> endRow = sections.stream().map(s -> toHexIfEnabled(loader.getReadSize(s) + s.getAlignedPointerToRaw(lowAlign)));
addStreamToRow(endRow, rows, "-> Physical End");
// collect VA
Stream<String> vaRow = sections.stream().map(s -> toHexIfEnabled(s.get(VIRTUAL_ADDRESS)));
addStreamToRow(vaRow, rows, "Virtual Address");
// collect alligned VA
Stream<String> vaAlignedRow = sections.stream().map(s -> s.get(VIRTUAL_ADDRESS) != s.getAlignedVirtualAddress(lowAlign) ? toHexIfEnabled(s.getAlignedVirtualAddress(lowAlign)) : "");
addStreamToRow(vaAlignedRow, rows, "-> Aligned");
// collect Virtual Size
Stream<String> vSizeRow = sections.stream().map(s -> toHexIfEnabled(s.get(VIRTUAL_SIZE)));
addStreamToRow(vSizeRow, rows, "Virtual Size");
// collect Actual Virtual Size
Stream<String> actSizeRow = sections.stream().map(s -> s.get(VIRTUAL_SIZE) != loader.getActualVirtSize(s) ? toHexIfEnabled(loader.getActualVirtSize(s)) : "");
addStreamToRow(actSizeRow, rows, "-> Actual Virtual Size");
// collect Virtual End
Stream<String> veRow = sections.stream().map(s -> toHexIfEnabled(s.getAlignedVirtualAddress(lowAlign) + loader.getActualVirtSize(s)));
addStreamToRow(veRow, rows, "-> Virtual End");
// collect Pointer To Relocations
Stream<String> relocRow = sections.stream().map(s -> toHexIfEnabled(s.get(POINTER_TO_RELOCATIONS)));
addStreamToRow(relocRow, rows, "Pointer To Relocations");
// collect Number Of Relocations
Stream<String> numreRow = sections.stream().map(s -> toHexIfEnabled(s.get(NUMBER_OF_RELOCATIONS)));
addStreamToRow(numreRow, rows, "Number Of Relocations");
// collect Pointer To Line Numbers
Stream<String> linRow = sections.stream().map(s -> toHexIfEnabled(s.get(POINTER_TO_LINE_NUMBERS)));
addStreamToRow(linRow, rows, "Pointer To Line Numbers");
// collect Number Of Line Numbers
Stream<String> numLinRow = sections.stream().map(s -> toHexIfEnabled(s.get(NUMBER_OF_LINE_NUMBERS)));
addStreamToRow(numLinRow, rows, "Number Of Line Numbers");
for(SectionCharacteristic ch : SectionCharacteristic.values()) {
Stream<String> secCharRow = sections.stream().map(s -> s.getCharacteristics().contains(ch) ? "x" : "");
addStreamToRow(secCharRow, rows, ch.shortName());
}
// add all rows to model
for(String[] row : rows) {
model.addRow(row);
}
}
private void addStreamToRow(Stream<String> aStream, List<String[]> rows, String title) {
List<String> list = aStream.collect(Collectors.toList());
boolean hasContent = false;
for(String l : list) {
if (!l.equals("")) {
hasContent = true;
break;
}
}
if(hasContent) {
list.add(0, title);
rows.add(list.toArray(new String[0]));
}
}
private String toHexIfEnabled(Long num) {
if(hexEnabled) {
return "0x" + Long.toHexString(num);
}
return num.toString();
}
private void createTableHeaderForSections(List<SectionHeader> sections, DefaultTableModel model) {
List<String> names = sections.stream().map(h -> h.getNumber() + ". " + h.getName()).collect(Collectors.toList());
names.add(0,"");
String[] tableHeader = names.toArray(new String[0]);
model.setColumnIdentifiers(tableHeader);
}
public void setHexEnabled(boolean hexEnabled) {
this.hexEnabled = hexEnabled;
if(peData == null) {return;}
initializeContent();
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/PEDetailsPanel.java | src/main/java/io/github/struppigel/gui/pedetails/PEDetailsPanel.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui.pedetails;
import io.github.struppigel.parser.RichHeader;
import io.github.struppigel.parser.StandardField;
import io.github.struppigel.parser.coffheader.COFFFileHeader;
import io.github.struppigel.parser.msdos.MSDOSHeader;
import io.github.struppigel.parser.optheader.DataDirEntry;
import io.github.struppigel.parser.optheader.DataDirectoryKey;
import io.github.struppigel.parser.optheader.OptionalHeader;
import io.github.struppigel.parser.sections.SectionHeader;
import io.github.struppigel.parser.sections.SectionLoader;
import io.github.struppigel.parser.sections.SectionTable;
import io.github.struppigel.gui.FullPEData;
import io.github.struppigel.gui.MainFrame;
import io.github.struppigel.gui.PEFieldsTable;
import io.github.struppigel.gui.VisualizerPanel;
import io.github.struppigel.gui.pedetails.signatures.SignaturesPanel;
import io.github.struppigel.gui.utils.PortexSwingUtils;
import io.github.struppigel.gui.utils.TableContent;
import io.github.struppigel.parser.sections.debug.ExtendedDLLCharacteristics;
import io.github.struppigel.settings.PortexSettings;
import com.google.common.base.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.dnd.DropTarget;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static io.github.struppigel.parser.optheader.StandardFieldEntryKey.ADDR_OF_ENTRY_POINT;
/**
* Displays the data in the middle.
*/
public class PEDetailsPanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private static final String DEFAULT_SAVE_FILENAME = "portex_visualization.png";
private final String NL = System.getProperty("line.separator");
private final JPanel rightPanel;
private final MainFrame parent;
private final PortexSettings settings;
private FullPEData peData;
/**
* Part of table panel
*/
private final List<JTable> tables = new ArrayList<>();
private final JTextArea descriptionWithButtonArea = new JTextArea();
private final JTextArea descriptionField = new JTextArea();
/**
* Contains the tablePanel, tabbedPanel and descriptionField
*/
private final JPanel cardPanel = new JPanel(new CardLayout());
/**
* Contains the tables
*/
private final JPanel tablePanel = new JPanel();
private SectionsTabbedPanel sectionsPanel;
private VisualizerPanel visPanel = new VisualizerPanel(true, true, true, 180);
private IconPanel iconPanel = new IconPanel();
private final SignaturesPanel signaturesPanel;
private boolean isHexEnabled = true;
private FileContentPreviewPanel previewPanel;
private TabbedPanel tabbedPanel;
public PEDetailsPanel(JPanel rightPanel, MainFrame mainFrame, PortexSettings settings, FileContentPreviewPanel previewPanel) {
super(new GridLayout(1, 0));
this.rightPanel = rightPanel;
this.parent = mainFrame;
this.settings = settings;
this.previewPanel = previewPanel;
signaturesPanel = new SignaturesPanel(settings, previewPanel);
initDetails();
}
private void initDetails() {
// only description
descriptionField.setText("Drop file here");
descriptionField.setEditable(false);
descriptionField.setDropTarget(this.getDropTarget());
descriptionField.setDragEnabled(true);
descriptionField.setLineWrap(true);
JScrollPane scrollPaneDescription = new JScrollPane(descriptionField);
// visualizer page + button
JPanel bigVisuals = new JPanel();
bigVisuals.setLayout(new BorderLayout());
bigVisuals.add(visPanel, BorderLayout.CENTER);
JPanel visButtonPanel = initSaveVisualsButtonPanel();
bigVisuals.add(visButtonPanel, BorderLayout.PAGE_END);
// icons page + button
JPanel iconWrapperPanel = new JPanel();
JPanel icoButtonPanel = initSaveIconsButtonPanel();
iconWrapperPanel.setLayout(new BorderLayout());
iconWrapperPanel.add(new JScrollPane(iconPanel), BorderLayout.CENTER);
iconWrapperPanel.add(icoButtonPanel, BorderLayout.PAGE_END);
// description + dump button
descriptionWithButtonArea.setText("");
descriptionWithButtonArea.setEditable(false);
descriptionWithButtonArea.setDragEnabled(true);
descriptionWithButtonArea.setDropTarget(this.getDropTarget());
descriptionWithButtonArea.setLineWrap(true);
JPanel descriptionAndButtonWrapperPanel = new JPanel();
JPanel dumpButtonPanel = initDumpButtonPanel();
descriptionAndButtonWrapperPanel.setLayout(new BorderLayout());
descriptionAndButtonWrapperPanel.add(new JScrollPane(descriptionWithButtonArea), BorderLayout.CENTER);
descriptionAndButtonWrapperPanel.add(dumpButtonPanel, BorderLayout.PAGE_END);
sectionsPanel = new SectionsTabbedPanel();
tabbedPanel = new TabbedPanel(previewPanel);
tablePanel.setLayout(new GridLayout(0, 1));
cardPanel.add(tablePanel, "TABLE");
cardPanel.add(scrollPaneDescription, "DESCRIPTION");
cardPanel.add(descriptionAndButtonWrapperPanel, "DESCBUTTON");
cardPanel.add(tabbedPanel, "TABBED");
cardPanel.add(sectionsPanel, "SECTIONS");
cardPanel.add(bigVisuals, "VISUALIZATION");
cardPanel.add(iconWrapperPanel, "ICONS");
cardPanel.add(signaturesPanel, "SIGNATURES");
//add the table to the frame
setLayout(new BorderLayout());
add(cardPanel, BorderLayout.CENTER);
showDescriptionPanel();
}
private JPanel initSaveIconsButtonPanel() {
JPanel buttonPanel = new JPanel();
JButton saveImgButton = new JButton("Save all");
saveImgButton.addActionListener(e -> {
String path = PortexSwingUtils.getSaveFolderNameFromUser(this);
new SaveIconsWorker(path, iconPanel.getIcons()).execute();
});
buttonPanel.add(saveImgButton);
return buttonPanel;
}
private JPanel initDumpButtonPanel() {
JPanel buttonPanel = new JPanel();
JButton saveButton = new JButton("Dump overlay");
saveButton.addActionListener(e -> {
String defaultFileName = peData.getFile().getAbsolutePath() + ".overlay";
String path = PortexSwingUtils.getSaveFileNameFromUser(this, defaultFileName);
if(PortexSwingUtils.checkIfFileExistsAndAskIfOverwrite(this, new File(path))) {
new DumpOverlayWorker(path).execute();
}
});
JButton removeButton = new JButton("Remove overlay");
removeButton.addActionListener(e -> {
String defaultFileName = peData.getFile().getAbsolutePath() + ".truncated";
String path = PortexSwingUtils.getSaveFileNameFromUser(this, defaultFileName);
if(PortexSwingUtils.checkIfFileExistsAndAskIfOverwrite(this, new File(path))) {
new RemoveOverlayWorker(path).execute();
}
});
buttonPanel.add(saveButton);
buttonPanel.add(removeButton);
return buttonPanel;
}
private class SaveIconsWorker extends SwingWorker<Boolean, Void> {
private final List<BufferedImage> icons;
private final String folder;
public SaveIconsWorker(String folder, List<BufferedImage> icons) {
this.folder = folder;
this.icons = icons;
}
@Override
protected Boolean doInBackground() {
int counter = 0;
boolean successFlag = true;
for (BufferedImage icon : icons) {
File file;
// find next file path that does not exist
do {
file = Paths.get(folder, counter + ".png").toFile();
counter++;
} while (file.exists());
try {
ImageIO.write(icon, "png", file);
} catch (IOException e) {
LOGGER.error(e);
successFlag = false;
}
}
return successFlag;
}
@Override
protected void done() {
try {
Boolean success = get();
if (success) {
JOptionPane.showMessageDialog(null,
"Icons successfully saved",
"Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,
"Unable to save some icons :(",
"Something went wrong",
JOptionPane.ERROR_MESSAGE);
}
} catch (ExecutionException | InterruptedException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
}
private class RemoveOverlayWorker extends SwingWorker<String, Void> {
private final String outFile;
public RemoveOverlayWorker(String outFile) {
this.outFile = outFile;
}
@Override
protected String doInBackground() {
String resultMessage = "something unknown went wrong";
File file = new File(outFile);
if(!file.isDirectory()) {
try (RandomAccessFile raf = new RandomAccessFile(peData.getFile(), "r");
FileOutputStream out = new FileOutputStream(outFile)) {
long endOffset = peData.getOverlay().getOffset();
raf.seek(0);
byte[] buffer = new byte[2048];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = raf.read(buffer)) != -1) {
// end was reached, we calculate the rest of the buffer
if (totalBytesRead + bytesRead > endOffset) {
int bytesToWrite = (int) (endOffset - totalBytesRead);
out.write(buffer, 0, bytesToWrite);
break;
}
out.write(buffer, 0, bytesRead);
}
resultMessage = "success";
} catch (IOException e) {
e.printStackTrace();
resultMessage = e.getMessage();
}
} else {
resultMessage = "given output file is a directory";
}
return resultMessage;
}
@Override
protected void done() {
try {
String msg = get();
if (msg.equals("success")) {
JOptionPane.showMessageDialog(null,
"File successfully saved to " + outFile,
"Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,
"Unable to save file :(. " + msg,
"Something went wrong",
JOptionPane.ERROR_MESSAGE);
}
} catch (ExecutionException | InterruptedException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
}
private class DumpOverlayWorker extends SwingWorker<String, Void> {
private final String outFile;
public DumpOverlayWorker(String outFile) {
this.outFile = outFile;
}
@Override
protected String doInBackground() {
String resultMessage = "something unknown went wrong";
File file = new File(outFile);
if(!file.isDirectory()) {
try (RandomAccessFile raf = new RandomAccessFile(peData.getFile(), "r");
FileOutputStream out = new FileOutputStream(outFile)) {
long offset = peData.getOverlay().getOffset();
raf.seek(offset);
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = raf.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
resultMessage = "success";
} catch (IOException e) {
e.printStackTrace();
resultMessage = e.getMessage();
}
} else {
resultMessage = "given output file is a directory";
}
return resultMessage;
}
@Override
protected void done() {
try {
String msg = get();
if (msg.equals("success")) {
JOptionPane.showMessageDialog(null,
"File successfully saved to " + outFile,
"Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,
"Unable to save file :(. " + msg,
"Something went wrong",
JOptionPane.ERROR_MESSAGE);
}
} catch (ExecutionException | InterruptedException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
}
private JPanel initSaveVisualsButtonPanel() {
JPanel buttonPanel = new JPanel();
JButton saveImgButton = new JButton("Save to file");
saveImgButton.addActionListener(e -> {
String path = PortexSwingUtils.getSaveFileNameFromUser(this, DEFAULT_SAVE_FILENAME);
if(path != null) {
if (!path.toLowerCase().endsWith(".png")) {
path += ".png";
}
Boolean canWrite = PortexSwingUtils.checkIfFileExistsAndAskIfOverwrite(this, new File(path));
if(canWrite){
new SaveImageFileWorker(path).execute();
}
}
});
buttonPanel.add(saveImgButton);
return buttonPanel;
}
private class SaveImageFileWorker extends SwingWorker<Boolean, Void> {
private String path;
public SaveImageFileWorker(String path) {
this.path = path;
}
@Override
protected Boolean doInBackground() {
try {
ImageIO.write(visPanel.getImage(), "png", new File(path));
} catch (IOException ex) {
LOGGER.error(ex);
ex.printStackTrace();
return false;
}
return true;
}
@Override
protected void done() {
try {
Boolean success = get();
if (success) {
JOptionPane.showMessageDialog(PEDetailsPanel.this,
"File successfully saved under " + path,
"Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,
"Unable to save file " + path,
"Something went wrong :(",
JOptionPane.ERROR_MESSAGE);
}
} catch (ExecutionException | InterruptedException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
}
public void setPeData(FullPEData peData) {
this.peData = peData;
sectionsPanel.setPeData(peData);
iconPanel.setPeData(peData);
signaturesPanel.setPeData(peData);
try {
visPanel.visualizePE(peData.getFile());
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(e);
}
}
public void setHexEnabled(boolean hexEnabled) {
this.isHexEnabled = hexEnabled;
previewPanel.setHexEnabled(hexEnabled);
sectionsPanel.setHexEnabled(hexEnabled);
signaturesPanel.setHexEnabled(hexEnabled);
tabbedPanel.setHexEnabled(hexEnabled);
parent.refreshSelection();
}
public void showDosStub() {
if (peData != null) {
MSDOSHeader header = peData.getPeData().getMSDOSHeader();
List<StandardField> entries = header.getHeaderEntries();
showFieldEntries(entries);
LOGGER.debug("MS DOS Stub shown");
showTablePanel();
previewPanel.showContentAtOffset(0);
} else {
LOGGER.warn("PE Data is null!");
}
}
public void showCoffFileHeader() {
if (peData == null) return;
COFFFileHeader header = peData.getPeData().getCOFFFileHeader();
List<StandardField> entries = header.getHeaderEntries();
String date = peData.getPeData().isReproBuild() ? "invalid - reproducibility build" : header.getTimeDate().toString();
String text = "Time date stamp : " + date + NL;
text += "Machine type: " + header.getMachineType().getDescription() + NL;
text += "Characteristics: " + NL;
text += header.getCharacteristics().stream().map(ch -> "\t* " + ch.getDescription()).collect(Collectors.joining(NL));
if (header.getCharacteristics().size() == 0) {
text += "no characteristics set";
}
String[] tableHeader = {"Description", "Value", "File offset"};
showFieldEntriesAndDescription(entries, tableHeader, text, 2);
LOGGER.debug("COFF File header shown");
showTablePanel();
previewPanel.showContentAtOffset(header.getOffset());
}
public void showOptionalHeader() {
showEmpty();
previewPanel.showContentAtOffset(peData.getPeData().getOptionalHeader().getOffset());
}
private void showEmpty() {
if (peData != null) {
descriptionField.setText("");
descriptionField.repaint();
showDescriptionPanel();
} else {
LOGGER.warn("PE Data is null!");
}
}
public void showStandardFieldsTable() {
if (peData == null) return;
OptionalHeader header = peData.getPeData().getOptionalHeader();
List<StandardField> entries = new ArrayList<>(header.getStandardFields().values());
String[] tableHeader = {"Description", "Value", "File offset"};
String text = "Linker version: " + header.getLinkerVersionDescription() + NL;
text += "Magic Number: " + header.getMagicNumber().getDescription() + NL;
showFieldEntriesAndDescription(entries, tableHeader, text, 2);
LOGGER.debug("Standard Fields shown");
showTablePanel();
previewPanel.showContentAtOffset(header.getOffset());
}
public void showRTStrings() {
if (peData == null) return;
List<Object[]> entries = peData.getRTStringTableEntries();
String[] tableHeader = {"ID", "String"};
showTextEntries(entries, tableHeader, -1); //TODO add offsets for RT_TABLE entries
LOGGER.debug("RT_STRINGS shown");
showTablePanel();
// find offset for first RT_STRING table
Long offset = getMinOffsetForResourceTypeOrZero("RT_STRING");
previewPanel.showContentAtOffset(offset);
}
public void showDotNetMetadataRoot() {
if (peData == null) return;
List<StandardField> entries = peData.getDotNetMetadataRootEntries();
String[] tableHeader = {"Key", "Value", "Offset"};
int offsetColumn = 2;
long startOffset = peData.getDotNetMetadataRootOffset();
String description = "MetadataRoot version string: " + peData.getDotNetMetadataVersionString();
showFieldEntriesAndDescription(entries, tableHeader, description, offsetColumn);
LOGGER.debug(".NET MetadataRoot shown");
showTablePanel();
previewPanel.showContentAtOffset(startOffset);
}
public void showDotNetStreamHeaders() {
if (peData == null) return;
List<Object[]> entries = peData.getDotNetStreamHeaderEntries();
String[] tableHeader = {"Stream name", "Size", "BSJB offset", "File offset"};
showTextEntries(entries, tableHeader, 3);
LOGGER.debug(".NET Stream Headers shown");
showTablePanel();
previewPanel.showContentAtOffset(peData.getDotNetMetadataRootOffset());
}
public void showOptimizedStream() {
if (peData == null) return;
List<StandardField> entries = peData.getOptimizedStreamEntries();
showFieldEntries(entries);
LOGGER.debug("#~ shown");
showTablePanel();
Long offset = Collections.min(
peData.getOptimizedStreamEntries()
.stream()
.map(e -> e.getOffset())
.collect(Collectors.toList()));
previewPanel.showContentAtOffset(offset);
}
public void showWindowsFieldsTable() {
if (peData == null) return;
OptionalHeader header = peData.getPeData().getOptionalHeader();
List<StandardField> entries = new ArrayList<>(header.getWindowsSpecificFields().values());
String[] tableHeader = {"Description", "Value", "File offset"};
String text = "Subsystem: " + header.getSubsystem().getDescription() + NL;
long entryPoint = header.get(ADDR_OF_ENTRY_POINT);
Optional<SectionHeader> maybeHeader = new SectionLoader(peData.getPeData()).maybeGetSectionHeaderByRVA(entryPoint);
if (maybeHeader.isPresent()) {
text += "Entry point is in section " + maybeHeader.get().getNumber() + " with name " + maybeHeader.get().getName() + NL;
} else {
text += "Entry point is not in a section" + NL;
}
text += NL + "DLL Characteristics:" + NL;
text += header.getDllCharacteristics().stream().map(ch -> "\t* " + ch.getDescription()).collect(Collectors.joining(NL)) + NL;
java.util.Optional<ExtendedDLLCharacteristics> exDll = peData.getPeData().loadExtendedDllCharacteristics();
if(exDll.isPresent() && (exDll.get().getCETCompat() || exDll.get().getForwardCFICompat())) {
text += NL + "Extended DLL Characteristics:" + NL;
if ( exDll.get().getCETCompat() ) {
text += "\t* CET Compat" + NL;
}
if ( exDll.get().getForwardCFICompat() ) {
text += "\t* Foward CFI Compat" + NL;
}
}
showFieldEntriesAndDescription(entries, tableHeader, text, 2);
LOGGER.debug("Windows Fields shown");
showTablePanel();
previewPanel.showContentAtOffset(header.getOffset());
}
public void showDataDirectoryTable() {
if (peData == null) return;
OptionalHeader header = peData.getPeData().getOptionalHeader();
SectionTable secTable = peData.getPeData().getSectionTable();
List<Object[]> dirEntries = new ArrayList<>();
long startOffset = 0L;
for (DataDirEntry de : header.getDataDirectory().values()) {
Long offset = de.getFileOffset(secTable);
if(startOffset == 0 || offset < startOffset) {
startOffset = offset;
}
Long size = de.getDirectorySize();
Long va = de.getVirtualAddress();
Optional<SectionHeader> hOpt = de.maybeGetSectionTableEntry(secTable);
String section = hOpt.isPresent() ? hOpt.get().getNumber() + ". " + hOpt.get().getName() : "NaN";
Long valueOffset = de.getTableEntryOffset();
Object[] row = {de.getKey(), va, offset, size, section, valueOffset};
dirEntries.add(row);
}
String[] tableHeader = {"Data directory", "RVA", "-> Offset", "Size", "In section", "Value offset"};
showTextEntries(dirEntries, tableHeader, 2);
LOGGER.debug("Windows Fields shown");
showTablePanel();
previewPanel.showContentAtOffset(startOffset);
}
@Override
public synchronized void setDropTarget(DropTarget dt) {
descriptionWithButtonArea.setDropTarget(dt);
tablePanel.setDropTarget(dt);
sectionsPanel.setDropTarget(dt);
iconPanel.setDropTarget(dt);
signaturesPanel.setDropTarget(dt);
}
private void showDescriptionPanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "DESCRIPTION");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to DESCRIPTION");
}
private void showDescriptionButtonPanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "DESCBUTTON");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to DESCBUTTON");
}
private void showTablePanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "TABLE");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to TABLE");
}
private void showSectionPanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "SECTIONS");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to SECTION");
}
private void showIconPanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "ICONS");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to ICONS");
}
private void showTabbedPanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "TABBED");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to TABBED");
}
private void showSignaturesPanel() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "SIGNATURES");
rightPanel.setVisible(true);
LOGGER.debug("Card panel set to SIGNATURES");
}
public void showVisualization() {
((CardLayout) cardPanel.getLayout()).show(cardPanel, "VISUALIZATION");
rightPanel.setVisible(false);
LOGGER.debug("Card panel set to VISUALIZATION");
}
public void showSectionTable() {
showSectionPanel();
Long offset = peData.getPeData().getSectionTable().getOffset();
previewPanel.showContentAtOffset(offset);
}
private void addTable(JTable table) {
tables.add(table);
JScrollPane sPane = new JScrollPane(table);
tablePanel.add(sPane);
}
private void cleanUpTablePanel() {
tables.clear();
tablePanel.removeAll();
}
private void showUpdatesInTablePanel() {
for (JTable tbl : tables) {
tbl.revalidate();
tbl.repaint();
}
tablePanel.revalidate();
tablePanel.repaint();
}
private void showFieldEntries(List<StandardField> entries) {
String[] tableHeader = {"Description", "Value", "File offset"};
cleanUpTablePanel();
PEFieldsTable table = new PEFieldsTable(isHexEnabled);
DefaultTableModel model = new PEFieldsTable.PETableModel();
model.setColumnIdentifiers(tableHeader);
for (StandardField field : entries) {
Object[] row = {field.getDescription(), field.getValue(), field.getOffset()};
model.addRow(row);
}
table.setPreviewOffsetColumn(2, previewPanel);
table.setModel(model);
addTable(table);
showUpdatesInTablePanel();
}
private void showFieldEntriesAndDescription(List<StandardField> entries, String[] tableHeader, String text, int offsetColumn) {
cleanUpTablePanel();
tablePanel.add(new JScrollPane(new JTextArea(text)));
PEFieldsTable table = new PEFieldsTable(isHexEnabled);
DefaultTableModel model = new PEFieldsTable.PETableModel();
model.setColumnIdentifiers(tableHeader);
for (StandardField field : entries) {
Object[] row = {field.getDescription(), field.getValue(), field.getOffset()};
model.addRow(row);
}
if(offsetColumn >= 0) {
table.setPreviewOffsetColumn(offsetColumn, previewPanel);
}
table.setModel(model);
addTable(table);
showUpdatesInTablePanel();
}
private PEFieldsTable showTextEntries(List<Object[]> entries, String[] tableHeader, int offsetColumn) {
cleanUpTablePanel();
PEFieldsTable table = new PEFieldsTable(isHexEnabled);
DefaultTableModel model = new PEFieldsTable.PETableModel();
model.setColumnIdentifiers(tableHeader);
model.setColumnIdentifiers(tableHeader);
for (Object[] row : entries) {
model.addRow(row);
}
if(offsetColumn >= 0) {
table.setPreviewOffsetColumn(offsetColumn, previewPanel);
}
table.setModel(model);
addTable(table);
showUpdatesInTablePanel();
return table;
}
private PEFieldsTable showTextEntriesAndDescription(List<Object[]> entries, String[] tableHeader, String text, int offsetColumn) {
cleanUpTablePanel();
JTextArea t = new JTextArea(text); // if you end up using this again, create a class instead
t.setEditable(false);
t.setDragEnabled(true);
t.setLineWrap(true);
tablePanel.add(new JScrollPane(t));
PEFieldsTable table = new PEFieldsTable(isHexEnabled);
DefaultTableModel model = new PEFieldsTable.PETableModel();
model.setColumnIdentifiers(tableHeader);
model.setColumnIdentifiers(tableHeader);
for (Object[] row : entries) {
model.addRow(row);
}
if(offsetColumn >= 0) {
table.setPreviewOffsetColumn(offsetColumn, previewPanel);
}
table.setModel(model);
addTable(table);
showUpdatesInTablePanel();
return table;
}
public void showPEHeaders() {
descriptionField.setText("");
showDescriptionPanel();
previewPanel.showContentAtOffset(peData.getPeData().getPESignature().getOffset());
}
private String toHexIfEnabled(Long num) {
if (isHexEnabled) {
return "0x" + Long.toHexString(num);
}
return num.toString();
}
public void showOverlay() {
if (peData == null) return;
try {
long offset = peData.getOverlay().getOffset();
long size = peData.getOverlay().getSize();
double entropy = peData.getOverlayEntropy() * 8;
List<String> sigs = peData.getOverlaySignatures();
String text = "Offset: " + toHexIfEnabled(offset) + NL + "Size: " + toHexIfEnabled(size) + NL;
String packed = entropy >= 7.0 ? " (packed)" : "";
text += "Entropy: " + String.format("%1.2f", entropy) + packed + NL + NL;
text += "Signatures: " + NL;
for (String s : sigs) {
text += s + NL;
}
if (sigs.size() == 0) {
text += "no matches";
}
descriptionWithButtonArea.setText(text);
showDescriptionButtonPanel();
previewPanel.showContentAtOffset(offset);
} catch (IOException e) {
String message = "Could not read Overlay! Reason: " + e.getMessage();
LOGGER.error(message);
e.printStackTrace();
}
}
public void showClrTable(String name) {
if (peData == null || !peData.isDotNet()) return;
if(!peData.getClrTables().containsKey(name) || !peData.getClrTableHeaders().containsKey(name)) return;
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | true |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/IconPanel.java | src/main/java/io/github/struppigel/gui/pedetails/IconPanel.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui.pedetails;
import io.github.struppigel.parser.PEData;
import io.github.struppigel.parser.sections.rsrc.icon.IcoFile;
import io.github.struppigel.parser.sections.rsrc.icon.IconParser;
import io.github.struppigel.gui.FullPEData;
import io.github.struppigel.gui.utils.WorkerKiller;
import net.ifok.image.image4j.codec.ico.ICODecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class IconPanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private FullPEData peData;
private List<BufferedImage> icons;
public void setPeData(FullPEData peData) {
this.peData = peData;
SwingWorker worker = new IconUpdateWorker(peData.getPeData());
WorkerKiller.getInstance().addWorker(worker);
worker.execute();
}
public List<BufferedImage> getIcons() {
return icons;
}
private class IconUpdateWorker extends SwingWorker<List<BufferedImage>, Void> {
private final PEData data;
public IconUpdateWorker(PEData data) {
this.data = data;
}
@Override
protected List<BufferedImage> doInBackground() throws IOException {
List<IcoFile> icons = IconParser.extractIcons(data);
List<BufferedImage> images = new ArrayList<>();
for (IcoFile icon : icons) {
try {
List<BufferedImage> result = ICODecoder.read(icon.getInputStream());
images.addAll(result);
} catch (IOException e) {
LOGGER.error(e);
}
}
return images;
}
@Override
protected void done() {
if (isCancelled()) {
return;
}
try {
// get images
icons = get();
// init Swing components in the icon panel
GridLayout grid = new GridLayout(0, 2);
JPanel gridPanel = new JPanel(grid);
//gridPanel.setPreferredSize(new Dimension(getWidth(), getHeight()));
IconPanel.this.removeAll();
IconPanel.this.add(gridPanel);
// add all icons to the grid
for (BufferedImage image : icons) {
JLabel iconLabel = new JLabel(new ImageIcon(image));
gridPanel.add(iconLabel);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
LOGGER.error(e);
}
}
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/FileContentPreviewPanel.java | src/main/java/io/github/struppigel/gui/pedetails/FileContentPreviewPanel.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui.pedetails;
import io.github.struppigel.parser.IOUtil;
import io.github.struppigel.gui.FullPEData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.ExecutionException;
public class FileContentPreviewPanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private static final int PREVIEW_SIZE = 0x2000;
private JTextArea contentDisplay = new JTextArea("Offset: 0");
private FullPEData pedata;
private boolean isHexEnabled = true;
public FileContentPreviewPanel() {
contentDisplay.setLineWrap(true);
this.setLayout(new BorderLayout());
this.add(contentDisplay, BorderLayout.CENTER);
Font font = new Font("Courier New", Font.PLAIN, 12);
contentDisplay.setFont(font);
}
public void setPeData(FullPEData data) {
this.pedata = data;
showContentAtOffset(0);
}
public void showContentAtOffset(long offset) {
if (pedata == null) {return;}
(new SwingWorker<String, Void>() {
@Override
protected String doInBackground() {
byte[] content = prepareContentString(readContentAtOffset(offset));
String contentStr = new String(content);
return contentStr;
}
protected void done() {
try {
String contentStr = get();
String offsetStr = isHexEnabled ? "Offset: 0x" + Long.toHexString(offset) : "Offset: " + offset;
contentDisplay.setText(offsetStr + "\n" + contentStr);
contentDisplay.repaint();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(e);
}
}
}).execute();
}
private byte[] prepareContentString(byte[] arr) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] < 32 || arr[i] == 127) {
arr[i] = 0x2e; // '.'
}
}
return arr;
}
private byte[] readContentAtOffset(long offset) {
try (RandomAccessFile raf = new RandomAccessFile(pedata.getFile(), "r")) {
return IOUtil.loadBytesSafely(offset, PREVIEW_SIZE, raf);
} catch (IOException e) {
LOGGER.error(e);
}
return new byte[0];
}
public void setHexEnabled(boolean hexEnabled) {
this.isHexEnabled = hexEnabled;
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/TabbedPanel.java | src/main/java/io/github/struppigel/gui/pedetails/TabbedPanel.java | /**
* *****************************************************************************
* Copyright 2023 Karsten Hahn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui.pedetails;
import io.github.struppigel.parser.StandardField;
import io.github.struppigel.gui.PEFieldsTable;
import io.github.struppigel.gui.utils.TableContent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TabbedPanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger();
private final List<JTable> tables = new ArrayList<>();
private final JTabbedPane tabbedPane = new JTabbedPane();
private final FileContentPreviewPanel previewPanel;
private List<String> tableHeader = new ArrayList<>();
private List<TableContent> contents = new ArrayList<>();
private boolean hexEnabled = true;
public TabbedPanel(FileContentPreviewPanel previewPanel) {
LOGGER.debug("Tabbed Panel constructor");
this.previewPanel = previewPanel;
this.setLayout(new GridLayout(0,1));
add(tabbedPane);
}
public void setContent(List<TableContent> contents, String[] tableHeader) {
this.contents = contents;
this.tableHeader = Arrays.asList(tableHeader);
initializeContent();
}
private void cleanUpTabsAndTables() {
tabbedPane.removeAll();
tables.clear();
LOGGER.debug("Tabs and tables cleared");
}
public void initializeContent() {
LOGGER.debug("Init tabs for tables");
cleanUpTabsAndTables();
List<JPanel> tabs = initTabsAndTables();
refreshPanel(tabs);
}
private void refreshPanel(List<JPanel> tabs) {
LOGGER.debug("Refreshing tabs");
for(JTable tbl : tables) {
tbl.revalidate();
tbl.repaint();
}
for(JPanel tab : tabs) {
tab.revalidate();
tab.repaint();
}
revalidate();
repaint();
tabbedPane.revalidate();
tabbedPane.repaint();
}
private String toHexIfEnabled(Long num) {
if(hexEnabled) {
return "0x" + Long.toHexString(num);
}
return num.toString();
}
public void setHexEnabled(boolean hexEnabled) {
this.hexEnabled = hexEnabled;
initializeContent();
}
private List<JPanel> initTabsAndTables() {
List<JPanel> tabs = new ArrayList<>();
for(TableContent content : contents) {
String title = content.getTitle();
JPanel tab = createTabWithTitle(title);
tabs.add(tab);
addSingleTableForContent(content, tab);
}
return tabs;
}
private JPanel createTabWithTitle(String title) {
JPanel tab = new JPanel();
tab.setLayout(new GridLayout(0, 1));
tabbedPane.addTab(title, tab);
return tab;
}
private void addSingleTableForContent(TableContent content, JPanel tab) {
LOGGER.info("Setting hex enabled to " + hexEnabled);
PEFieldsTable table = new PEFieldsTable(hexEnabled);
DefaultTableModel model = new PEFieldsTable.PETableModel();
table.setPreviewOffsetColumn(2, previewPanel);
// add table header
String[] header = tableHeader.toArray(new String[0]);
model.setColumnIdentifiers(header);
createRows(content, model);
table.setModel(model);
addTableAndDescription(table, tab, content.getDescription());
}
private void createRows(TableContent content, DefaultTableModel model) {
for(StandardField field : content) {
Object[] row = {field.getDescription(), field.getValue(), field.getOffset()};
model.addRow(row);
}
}
private void addTableAndDescription(JTable table, JPanel tab, String description) {
tables.add(table);
if(description.length() > 0) {
tab.add(new JScrollPane(new JTextArea(description)));
}
JScrollPane sPane = new JScrollPane(table);
tab.add(sPane);
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/PEidScanner.java | src/main/java/io/github/struppigel/gui/pedetails/signatures/PEidScanner.java | package io.github.struppigel.gui.pedetails.signatures;
import io.github.struppigel.tools.Overlay;
import io.github.struppigel.tools.sigscanner.MatchedSignature;
import io.github.struppigel.tools.sigscanner.SignatureScanner;
import io.github.struppigel.gui.FullPEData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class PEidScanner extends SwingWorker<List<PEidRuleMatch>, Void> {
private static final Logger LOGGER = LogManager.getLogger();
private final SignaturesPanel signaturesPanel;
private final FullPEData pedata;
public PEidScanner(SignaturesPanel signaturesPanel, FullPEData data) {
this.signaturesPanel = signaturesPanel;
this.pedata = data;
}
@Override
protected List<PEidRuleMatch> doInBackground() {
List<PEidRuleMatch> result = entryPointScan(); // epOnly
result.addAll(overlayScan()); // Overlay
result.addAll(resourceScan()); // Resource
return result;
}
private List<PEidRuleMatch> entryPointScan() {
List<PEidRuleMatch> result;
List<PatternMatch> matches = SignatureScanner.newInstance().scanAll(pedata.getFile(), true)
.stream()
.map(this::toPatternMatch)
.collect(Collectors.toList());
result = toPeidRuleMatches(matches, "Entry Point", "PEiD");
return result;
}
private List<PEidRuleMatch> overlayScan() {
Overlay overlay = pedata.getOverlay();
List<PEidRuleMatch> result = new ArrayList<>();
try {
long offset = overlay.getOffset();
List<PatternMatch> overlayMatches = pedata.getPeData().getOverlaySignatures()
.stream()
.map(this::toPatternMatch)
.collect(Collectors.toList());
List<PEidRuleMatch> oMatch = toPeidRuleMatches(overlayMatches, "Overlay", "Filetype");
result.addAll(oMatch);
} catch (IOException e) {
LOGGER.error("something went wrong while scanning the overlay " + e);
}
return result;
}
private List<PEidRuleMatch> resourceScan() {
List<PatternMatch> resSigs = pedata.getPeData().getResourceSignatures().stream().map(this::toPatternMatch).collect(Collectors.toList());
return toPeidRuleMatches(resSigs, "Resource", "Filetype");
}
private PatternMatch toPatternMatch(MatchedSignature m) {
String rulename = m.getName();
if (rulename.startsWith("[")) {
rulename = rulename.substring(1, rulename.length() - 1);
}
String pattern = m.getPattern();
long offset = m.getAddress();
return new PatternMatch(offset, rulename, pattern);
}
private PatternMatch toPatternMatch(SignatureScanner.SignatureMatch m) {
String rulename = m.signature().name();
if (rulename.startsWith("[")) {
rulename = rulename.substring(1, rulename.length() - 1);
}
String pattern = m.signature().signatureString();
long offset = m.address();
return new PatternMatch(offset, rulename, pattern);
}
private List<PEidRuleMatch> toPeidRuleMatches(List<PatternMatch> patterns, String scanMode, String scannerName) {
List<PEidRuleMatch> result = new ArrayList<>();
// create unique list of all rule names
Set<String> uniqueRulenames = new HashSet<>();
for(PatternMatch pattern : patterns) {
uniqueRulenames.add(pattern.patternName);
}
// for every unique rule name get all patterns
for(String rule : uniqueRulenames) {
List<PatternMatch> rulePatterns = patterns.stream().filter(p -> p.patternName.equals(rule)).collect(Collectors.toList());
// make pattern name empty string because it looks weird to see the same value for rule name and pattern name
rulePatterns = rulePatterns.stream().map(p -> new PatternMatch(p.offset, "", p.patternContent)).collect(Collectors.toList());
// create a PEiD rule match out of these patterns
result.add(new PEidRuleMatch(rule, scanMode, rulePatterns, scannerName));
}
return result;
}
@Override
protected void done() {
if(isCancelled()){return;}
try {
List<PEidRuleMatch> matches = get();
signaturesPanel.buildPEiDTables(get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
LOGGER.error(e);
}
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/RuleMatch.java | src/main/java/io/github/struppigel/gui/pedetails/signatures/RuleMatch.java | package io.github.struppigel.gui.pedetails.signatures;
import java.util.List;
public interface RuleMatch {
public Object[] toSummaryRow();
public List<Object[]> toPatternRows();
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/PEidRuleMatch.java | src/main/java/io/github/struppigel/gui/pedetails/signatures/PEidRuleMatch.java | package io.github.struppigel.gui.pedetails.signatures;
import java.util.List;
import java.util.stream.Collectors;
public class PEidRuleMatch implements RuleMatch {
final String ruleName;
private final List<PatternMatch> patterns;
private final String scanMode;
private final String scannerName;
public PEidRuleMatch(String ruleName, String scanMode, List<PatternMatch> patterns, String scannerName) {
this.ruleName = ruleName;
this.patterns = patterns;
this.scanMode = scanMode;
this.scannerName = scannerName;
}
// {"Source", "Match name", "Scan mode"};
public Object[] toSummaryRow() {
Object[] row = {scannerName, ruleName, scanMode};
return row;
}
// {"Rule name", "Pattern", "Content", "Offset"}
public List<Object[]> toPatternRows() {
return patterns.stream().map(p -> p.toPatternRow(ruleName)).collect(Collectors.toList());
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/EmptyRuleMatch.java | src/main/java/io/github/struppigel/gui/pedetails/signatures/EmptyRuleMatch.java | package io.github.struppigel.gui.pedetails.signatures;
import java.util.ArrayList;
import java.util.List;
public class EmptyRuleMatch implements RuleMatch {
private static final String message = "no matches found";
@Override
public Object[] toSummaryRow() {
Object[] row = {message,"",""};
return row;
}
// {"Rule name" , "Pattern name", "Pattern content", "Offset", "Location"};
@Override
public List<Object[]> toPatternRows() {
List<Object[]> row = new ArrayList<>();
Object[] obj = {message, "","","",""};
row.add(obj);
return row;
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
struppigel/PortexAnalyzerGUI | https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/YaraScanner.java | src/main/java/io/github/struppigel/gui/pedetails/signatures/YaraScanner.java | /**
* *****************************************************************************
* Copyright 2022 Karsten Hahn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package io.github.struppigel.gui.pedetails.signatures;
import io.github.struppigel.gui.FullPEData;
import io.github.struppigel.settings.PortexSettings;
import io.github.struppigel.settings.PortexSettingsKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static io.github.struppigel.settings.PortexSettingsKey.DISABLE_YARA_WARNINGS;
class YaraScanner extends SwingWorker<List<YaraRuleMatch>, Void> {
private static final Logger LOGGER = LogManager.getLogger();
private final SignaturesPanel signaturesPanel;
private final FullPEData pedata;
private final String yaraPath;
private final String rulePath;
private PortexSettings settings;
public YaraScanner(SignaturesPanel signaturesPanel, FullPEData data, String yaraPath, String rulePath, PortexSettings settings) {
this.signaturesPanel = signaturesPanel;
this.pedata = data;
this.yaraPath = yaraPath;
this.rulePath = rulePath;
this.settings = settings;
}
@Override
protected List<YaraRuleMatch> doInBackground() throws IOException {
ProcessBuilder pbuilder = new ProcessBuilder(yaraPath, "-s", rulePath, pedata.getFile().getAbsolutePath());
Process process = null;
List<YaraRuleMatch> matches = new ArrayList<>();
try {
process = pbuilder.start();
stdInHandling(process, matches);
stdErrHandling(process);
} finally {
if (process != null) {
process.destroy();
}
}
return matches;
}
private void stdErrHandling(Process process) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("warning:")) {
LOGGER.warn("Warning while parsing yara rules: " + line);
if (settings.containsKey(DISABLE_YARA_WARNINGS) && settings.get(DISABLE_YARA_WARNINGS).equals("1")) {
return;
}
JOptionPane.showMessageDialog(signaturesPanel,
line,
"Rule parsing warning",
JOptionPane.WARNING_MESSAGE);
} else {
LOGGER.error("Error while parsing yara rules: " + line);
JOptionPane.showMessageDialog(signaturesPanel,
line,
"Rule parsing error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void stdInHandling(Process process, List<YaraRuleMatch> matches) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
List<PatternMatch> patterns = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
patterns = scanLine(matches, patterns, line);
}
}
}
private List<PatternMatch> scanLine(List<YaraRuleMatch> matches, List<PatternMatch> patterns, String line) {
if (isRuleName(line)) {
String rulename = parseRulename(line);
patterns = new ArrayList<>(); // fresh patterns
matches.add(new YaraRuleMatch(rulename, patterns, new ArrayList<>()));
} else if (isPattern(line)) {
PatternMatch pattern = parsePattern(line);
patterns.add(pattern);
}
return patterns;
}
private PatternMatch parsePattern(String line) {
assert isPattern(line); // make sure the pattern is 0xcafebabe:...:...
String[] split = line.split(":");
String longStr = split[0].substring(2);// remove '0x'
long offset = Long.parseLong(longStr, 16); // convert from hex
String name = split[1];
String content = String.join(":", Arrays.copyOfRange(split, 2, split.length));
return new PatternMatch(offset, name, content);
}
private boolean isPattern(String line) {
return line.startsWith("0x") && line.contains(":$") &&
line.split(":").length >= 3 && isLongHex(line.split(":\\$")[0]);
}
private boolean isLongHex(String s) {
if (s.startsWith("0x")) {
return isLongHex(s.substring(2));
}
try {
Long.parseLong(s, 16);
return true;
} catch (NumberFormatException e) {
LOGGER.warn("This is not a long " + s);
return false;
}
}
private String parseRulename(String line) {
assert isRuleName(line);
return line.split(" ")[0];
}
private boolean isRuleName(String line) {
return !isPattern(line) && line.split(" ").length >= 2;
}
@Override
protected void done() {
if (isCancelled()) {
return;
}
try {
signaturesPanel.buildYaraTables(get());
} catch (ExecutionException e) {
// most commonly when user did not choose valid yara path or signature path
// so we request them again
signaturesPanel.requestPaths();
JOptionPane.showMessageDialog(signaturesPanel,
e.getMessage(),
"IO Error",
JOptionPane.ERROR_MESSAGE);
LOGGER.error(e);
} catch (InterruptedException e) {
e.printStackTrace();
LOGGER.error(e);
}
}
}
| java | Apache-2.0 | 88091e58891354ddefd35db0d79bc3e0c8e3e57a | 2026-01-05T02:37:12.650809Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.