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/client/src/main/java/com/google/collide/client/editor/search/SearchTask.java | client/src/main/java/com/google/collide/client/editor/search/SearchTask.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.client.editor.search;
import com.google.collide.client.editor.ViewportModel;
import com.google.collide.client.editor.search.SearchModel.SearchProgressListener;
import com.google.collide.client.util.IncrementalScheduler;
import com.google.collide.client.util.IncrementalScheduler.Task;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.common.base.Preconditions;
/**
* A class which can be used to iterate through the lines of a document. It will
* synchronously callback for each line in the viewport then asynchronously
* callback for the remaining lines in the document. The direction and start
* line within the viewport are configurable.
*/
public class SearchTask {
public interface SearchTaskExecutor {
/**
* Called for each line in the document as it is searched.
*
* @param line the current line
* @param number the current line number
* @param shouldRenderLine if this line is in the viewport and a render must
* be performed if any visible changes are made.
* @return false to stop the search.
*/
public boolean onSearchLine(Line line, int number, boolean shouldRenderLine);
}
/**
* The direction of the document search.
*/
public enum SearchDirection {
UP, DOWN
}
/**
* An object which simplifies searches by hiding the logic which depends on
* the search direction.
*/
private static class SearchDirectionHelper {
private final ViewportModel viewport;
private final Document document;
private SearchDirection direction;
public SearchDirectionHelper(ViewportModel viewport, Document document) {
this.viewport = viewport;
this.document = document;
}
/**
* Sets the direction of the search so the helper can return valid line
* information.
*/
public void setDirection(SearchDirection direction) {
this.direction = direction;
}
/**
* Gets the starting line of the viewport, bottom if
* {@link SearchDirection#DOWN}, top if {@link SearchDirection#UP}.
*/
public Line getViewportEndLine() {
return isGoingDown() ? viewport.getBottomLine() : viewport.getTopLine();
}
/**
* Gets the starting line of the viewport, bottom if
* {@link SearchDirection#DOWN}, top if {@link SearchDirection#UP}.
*/
public LineInfo getViewportEndLineInfo() {
return isGoingDown() ? viewport.getBottomLineInfo() : viewport.getTopLineInfo();
}
/**
* Gets the starting line of the viewport, top if
* {@link SearchDirection#DOWN}, bottom if {@link SearchDirection#UP}.
*/
public LineInfo getViewportStartLineInfo() {
return isGoingDown() ? viewport.getTopLineInfo() : viewport.getBottomLineInfo();
}
/**
* Returns the line necessary to wrap around the document. i.e. if you are
* searching down it will return the top, if you are searching up it will
* return the bottom.
*/
public LineInfo getWrapDocumentLine() {
return isGoingDown() ? document.getFirstLineInfo() : document.getLastLineInfo();
}
/**
* Returns if the search is going down.
*/
public boolean isGoingDown() {
return direction == SearchDirection.DOWN;
}
/**
* Returns true if the line to be wrapped to is not at the corresponding
* edge of the document. i.e. Don't wrap to the top of the document if the
* viewport is at the top already (which we've already scanned).
*/
public boolean canWrapDocument() {
boolean atEdge = isGoingDown() ? viewport.getTopLine() == document.getFirstLine() :
viewport.getBottomLine() == document.getLastLine();
return !atEdge;
}
}
/**
* Indicates that the search task should start a search starting at either the
* top or bottom of the viewport depending on the selected direction.
*/
public static final LineInfo DEFAULT_START_LINE = new LineInfo(null, -1);
private static final AnchorType SEARCH_TASK_ANCHOR =
AnchorType.create(SearchTask.class, "SearchAnchor");
private final ViewportModel viewport;
private final IncrementalScheduler scheduler;
private final Document document;
private final Task asyncSearchTask;
private final SearchDirectionHelper searchDirectionHelper;
private Anchor stopLineAnchor;
private Anchor searchTaskAnchor;
private SearchProgressListener progressListener;
private SearchTaskExecutor executor;
private boolean shouldWrapDocument = true;
public SearchTask(Document document, ViewportModel viewport, IncrementalScheduler scheduler) {
this.document = document;
this.viewport = viewport;
this.scheduler = scheduler;
this.searchDirectionHelper = new SearchDirectionHelper(viewport, document);
asyncSearchTask = new AsyncSearchTask();
}
public void teardown() {
scheduler.teardown();
removeSearchTaskAnchors();
}
/**
* Starts searching the document in the down direction starting at the
* default line.
*/
public void searchDocument(
SearchTaskExecutor executor, SearchProgressListener progressListener) {
searchDocumentStartingAtLine(
executor, progressListener, SearchDirection.DOWN, DEFAULT_START_LINE);
}
/**
* Starts searching the document in the down direction starting at the given
* line.
*/
public void searchDocument(
SearchTaskExecutor executor, SearchProgressListener progressListener, LineInfo startLine) {
searchDocumentStartingAtLine(
executor, progressListener, SearchDirection.DOWN, startLine);
}
/**
* Starts searching the document in the given direction starting at the
* default start line.
*/
public void searchDocument(SearchTaskExecutor executor, SearchProgressListener progressListener,
SearchDirection direction) {
searchDocumentStartingAtLine(executor, progressListener, direction, DEFAULT_START_LINE);
}
/**
* Starts searching the document at the given line in the viewport and in the
* specified direction. If the startLine is not within the viewport then
* behavior is undefined and terrible things will likely happen.
*/
public void searchDocumentStartingAtLine(SearchTaskExecutor executor,
SearchProgressListener progressListener, SearchDirection direction, LineInfo startLine) {
scheduler.cancel();
this.progressListener = progressListener;
this.executor = executor;
searchDirectionHelper.setDirection(direction);
if (startLine == DEFAULT_START_LINE) {
startLine = searchDirectionHelper.getViewportStartLineInfo();
}
dispatchSearchBegin();
boolean doAsyncSearch = true;
if (startLine.number() >= viewport.getTopLineNumber() &&
startLine.number() <= viewport.getBottomLineNumber()) {
doAsyncSearch = scanViewportStartingAtLine(startLine);
}
if (doAsyncSearch) {
setupSearchTaskAnchors(startLine);
scheduler.schedule(asyncSearchTask);
} else {
dispatchSearchDone();
}
}
/**
* Returns if the search will wrap around the document when it gets to the
* bottom or top.
*/
public boolean isShouldWrapDocument() {
return shouldWrapDocument;
}
/**
* Determines if the search should wrap around the document either from the
* top to the bottom or vice versa.
*/
public void setShouldWrapDocument(boolean shouldWrapDocument) {
this.shouldWrapDocument = shouldWrapDocument;
}
/**
* Cancels any currently running search task.
*/
public void cancelTask() {
scheduler.cancel();
}
/**
* Starts a scan of the viewport at the given line. If the given lineInfo is
* not a line within the viewport then behavior is undefined (and likely not
* going to end well).
*/
private boolean scanViewportStartingAtLine(LineInfo startLineInfo) {
Preconditions.checkArgument(
startLineInfo.number() >= viewport.getTopLineNumber() &&
startLineInfo.number() <= viewport.getBottomLineNumber(),
"Editor: Search start line number not within viewport.");
LineInfo lineInfo = startLineInfo.copy();
do {
if (!executor.onSearchLine(lineInfo.line(), lineInfo.number(), true)) {
return false;
}
} while (lineInfo.line() != searchDirectionHelper.getViewportEndLine()
&& lineInfo.moveTo(searchDirectionHelper.isGoingDown()));
/*
* If we stopped because lineInfo == endline then we need to continue async
* scanning, otherwise this moveTo call will fail and we won't bother. We
* also have to check for the case where the viewport was already scrolled
* to the very bottom or top of the document.
*/
return lineInfo.moveTo(searchDirectionHelper.isGoingDown())
|| (searchDirectionHelper.canWrapDocument() && shouldWrapDocument);
}
/**
* Removes the search task anchors after the task has completed.
*/
private void removeSearchTaskAnchors() {
if (stopLineAnchor != null) {
document.getAnchorManager().removeAnchor(stopLineAnchor);
stopLineAnchor = null;
}
if (searchTaskAnchor != null) {
document.getAnchorManager().removeAnchor(searchTaskAnchor);
searchTaskAnchor = null;
}
}
/**
* Sets an anchor at the top of the current viewport and one line below the
* end of the viewport so we can scan the rest of the document.
*/
private void setupSearchTaskAnchors(LineInfo stopLine) {
if (stopLineAnchor == null) {
stopLineAnchor = document.getAnchorManager().createAnchor(
SEARCH_TASK_ANCHOR, stopLine.line(), stopLine.number(), AnchorManager.IGNORE_COLUMN);
stopLineAnchor.setRemovalStrategy(RemovalStrategy.SHIFT);
} else {
document.getAnchorManager().moveAnchor(
stopLineAnchor, stopLine.line(), stopLine.number(), AnchorManager.IGNORE_COLUMN);
}
// Try to set the line at the top or bottom of viewport (depending on
// direction), if we fail then wrap around the document. We don't have to
// check shoudl wrap here since the viewport scan would have returned false.
LineInfo startAnchorLine = searchDirectionHelper.getViewportEndLineInfo();
if (!startAnchorLine.moveTo(searchDirectionHelper.isGoingDown())) {
startAnchorLine = searchDirectionHelper.getWrapDocumentLine();
}
if (searchTaskAnchor == null) {
searchTaskAnchor =
document.getAnchorManager().createAnchor(SEARCH_TASK_ANCHOR, startAnchorLine.line(),
startAnchorLine.number(), AnchorManager.IGNORE_COLUMN);
searchTaskAnchor.setRemovalStrategy(RemovalStrategy.SHIFT);
} else {
document.getAnchorManager().moveAnchor(searchTaskAnchor, startAnchorLine.line(),
startAnchorLine.number(), AnchorManager.IGNORE_COLUMN);
}
}
private void dispatchSearchBegin() {
if (progressListener != null) {
progressListener.onSearchBegin();
}
}
private void dispatchSearchProgress() {
if (progressListener != null) {
progressListener.onSearchProgress();
}
}
private void dispatchSearchDone() {
removeSearchTaskAnchors();
if (progressListener != null) {
progressListener.onSearchDone();
}
}
private class AsyncSearchTask implements IncrementalScheduler.Task {
@Override
public boolean run(int workAmount) {
LineInfo lineInfo = searchTaskAnchor.getLineInfo();
for (; lineInfo.line() != stopLineAnchor.getLine() && workAmount > 0; workAmount--) {
if (!executor.onSearchLine(lineInfo.line(), lineInfo.number(), false)) {
dispatchSearchDone();
return false;
}
if (!lineInfo.moveTo(searchDirectionHelper.isGoingDown())) {
if (shouldWrapDocument) {
lineInfo = searchDirectionHelper.getWrapDocumentLine();
} else {
dispatchSearchDone();
return false;
}
}
}
if (lineInfo.line() == stopLineAnchor.getLine()) {
dispatchSearchDone();
return false;
}
document.getAnchorManager().moveAnchor(
searchTaskAnchor, lineInfo.line(), lineInfo.number(), AnchorManager.IGNORE_COLUMN);
dispatchSearchProgress();
return true;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/search/SearchMatchManager.java | client/src/main/java/com/google/collide/client/editor/search/SearchMatchManager.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.client.editor.search;
import com.google.collide.client.editor.search.SearchModel.MatchCountListener;
import com.google.collide.client.editor.search.SearchTask.SearchTaskExecutor;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.shared.document.Document;
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.util.ListenerManager;
import com.google.collide.shared.util.ListenerManager.Dispatcher;
import com.google.collide.shared.util.ListenerRegistrar;
import com.google.collide.shared.util.RegExpUtils;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
/**
* Manages search matches and can be queried to determine the current match and
* select a new match.
*/
/*
* TODO: Consider making searching for matches asynchrounous if it
* proves to be a bottleneck. Particularly revisit code that touches
* totalMatches since it will no longer be valid and could lead to races.
*/
public class SearchMatchManager {
private final Document document;
private RegExp searchPattern;
int totalMatches;
private final SelectionModel selection;
private final DocumentMutator editorDocumentMutator;
private final SearchTask searchTask;
private final ListenerManager<MatchCountListener> totalMatchesListenerManager =
ListenerManager.create();
public SearchMatchManager(Document document, SelectionModel selection,
DocumentMutator editorDocumentMutator, SearchTask searchTask) {
this.document = document;
this.selection = selection;
this.editorDocumentMutator = editorDocumentMutator;
this.searchTask = searchTask;
}
/**
* Moves to the next match starting from the current cursor position.
*
* @returns Position of match or null if no matches are found.
*/
public Position selectNextMatch() {
Position[] position = selection.getSelectionRange(false);
return selectNextMatchFromPosition(position[1].getLineInfo(), position[1].getColumn());
}
/**
* Moves to the next match after the given position (inclusive).
*
* @returns Position of match or null if no matches are found.
*/
public Position selectNextMatchFromPosition(LineInfo lineInfo, int startColumn) {
if (totalMatches == 0 || searchPattern == null || lineInfo == null) {
return null;
}
/*
* Basic Strategy: loop through lines until we find another match, if we hit
* the end start at the top. Until we hit our own line then just select the
* first match from index 0 (shouldn't be us).
*/
Line beginLine = lineInfo.line();
int column = startColumn;
do {
if (selectNextMatchOnLine(lineInfo, column, lineInfo.line().length())) {
return new Position(lineInfo, selection.getCursorColumn());
}
if (!lineInfo.moveToNext()) {
lineInfo = document.getFirstLineInfo();
}
// after first attempt, we always look at start of line
column = 0;
} while (lineInfo.line() != beginLine);
// We check to ensure there wasn't another match to wrap to on our own line
if (selectNextMatchOnLine(lineInfo, 0, startColumn)) {
return new Position(lineInfo, selection.getCursorColumn());
}
return null;
}
/**
* Moves to the previous match starting at the current cursor position.
*
* @returns Position of match or null if no matches are found.
*/
public Position selectPreviousMatch() {
Position[] position = selection.getSelectionRange(false);
return selectPreviousMatchFromPosition(position[0].getLineInfo(), position[0].getColumn());
}
/**
* Moves to the previous match from the given position (inclusive).
*
* @returns Position of match or null if no matches are found.
*/
public Position selectPreviousMatchFromPosition(LineInfo lineInfo, int startColumn) {
if (totalMatches == 0 || searchPattern == null || lineInfo == null) {
return null;
}
/*
* Basic Strategy: loop through lines going up, we have to go right to left
* though so we use the line keys to determine how many matches should be in
* a line and back out from that.
*/
Line beginLine = lineInfo.line();
int column = startColumn;
do {
if (selectPreviousMatchOnLine(lineInfo, 0, column)) {
return new Position(lineInfo, selection.getCursorColumn());
}
if (!lineInfo.moveToPrevious()) {
lineInfo = document.getLastLineInfo();
}
// after first attempt we want the last match in a line always
column = lineInfo.line().getText().length();
} while (lineInfo.line() != beginLine);
// We check to ensure there wasn't another match to wrap to on our own line
if (selectPreviousMatchOnLine(lineInfo, startColumn, beginLine.length())) {
return new Position(lineInfo, selection.getCursorColumn());
}
return null;
}
/**
* Increments the current total. If no match is currently selected this will
* select the first match that is added automatically.
*/
public void addMatches(LineInfo lineInfo, int matches) {
assert searchPattern != null;
if (totalMatches == 0 && matches > 0) {
selectNextMatchOnLine(lineInfo, 0, lineInfo.line().length());
}
totalMatches += matches;
dispatchTotalMatchesChanged();
}
public int getTotalMatches() {
return totalMatches;
}
ListenerRegistrar<MatchCountListener> getMatchCountChangedListenerRegistrar() {
return totalMatchesListenerManager;
}
public void clearMatches() {
totalMatches = 0;
dispatchTotalMatchesChanged();
}
/**
* @return true if current selection is a match to the searchPattern.
*/
private boolean isSelectionRangeAMatch() {
Position[] selectionRange = selection.getSelectionRange(false);
if (searchPattern != null && totalMatches > 0
&& selectionRange[0].getLine() == selectionRange[1].getLine()) {
String text =
document.getText(selectionRange[0].getLine(), selectionRange[0].getColumn(),
selectionRange[1].getColumn() - selectionRange[0].getColumn());
return !text.isEmpty() && RegExpUtils.resetAndTest(searchPattern, text);
}
return false;
}
/**
* Sets the search pattern used when finding matches. Also clears any existing
* match count.
*/
public void setSearchPattern(RegExp searchPattern) {
clearMatches();
this.searchPattern = searchPattern;
}
private void dispatchTotalMatchesChanged() {
totalMatchesListenerManager.dispatch(new Dispatcher<MatchCountListener>() {
@Override
public void dispatch(MatchCountListener listener) {
listener.onMatchCountChanged(totalMatches);
}
});
}
/**
* Selects the next match using the search pattern given line and startIndex.
*
* @param startIndex The boundary to find the next match after.
* @param endIndex The boundary to find the next match before.
*
* @returns true if match is found
*/
private boolean selectNextMatchOnLine(LineInfo line, int startIndex, int endIndex) {
searchPattern.setLastIndex(startIndex);
MatchResult result = searchPattern.exec(line.line().getText());
if (result == null || result.getIndex() >= endIndex) {
return false;
}
moveAndSelectMatch(line, result.getIndex(), result.getGroup(0).length());
return true;
}
/**
* Selects the previous match using the search pattern given line and
* startIndex.
*
* @param startIndex The boundary to find a previous match after.
* @param endIndex The boundary to find a previous match before.
*
* @returns true if a match is found
*/
private boolean selectPreviousMatchOnLine(LineInfo line, int startIndex, int endIndex) {
searchPattern.setLastIndex(0);
// Find the last match without going over our startIndex
MatchResult lastMatch = null;
for (MatchResult result = searchPattern.exec(line.line().getText());
result != null && result.getIndex() < endIndex && result.getIndex() >= startIndex;
result = searchPattern.exec(line.line().getText())) {
lastMatch = result;
}
if (lastMatch == null) {
return false;
}
moveAndSelectMatch(line, lastMatch.getIndex(), lastMatch.getGroup(0).length());
return true;
}
/**
* Moves the editor selection to the specified line and column and selects
* length characters.
*/
private void moveAndSelectMatch(LineInfo line, int column, int length) {
selection.setSelection(line, column + length, line, column);
}
public void replaceAllMatches(final String replacement) {
// TODO: There's an issue relying on the same SearchTask as
// SearchModel, since they share the same scheduler the searchModel can
// preempt a replaceAll before it is finish!
searchTask.searchDocument(new SearchTaskExecutor() {
@Override
public boolean onSearchLine(Line line, int number, boolean shouldRenderLine) {
searchPattern.setLastIndex(0);
for (MatchResult result = searchPattern.exec(line.getText());
result != null && result.getGroup(0).length() != 0;
result = searchPattern.exec(line.getText())) {
int start = searchPattern.getLastIndex() - result.getGroup(0).length();
editorDocumentMutator.deleteText(line, number, start, result.getGroup(0).length());
editorDocumentMutator.insertText(line, number, start, replacement);
int newIndex = result.getIndex() + replacement.length();
searchPattern.setLastIndex(newIndex);
}
return true;
}
}, null);
}
public boolean replaceMatch(String replacement) {
if (!isSelectionRangeAMatch() && selectNextMatch() == null) {
return false;
}
editorDocumentMutator.insertText(selection.getCursorLine(), selection.getCursorLineNumber(),
selection.getCursorColumn(), replacement, true);
selectNextMatch();
return true;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/filehistory/FileHistory.java | client/src/main/java/com/google/collide/client/filehistory/FileHistory.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.client.filehistory;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.FileContent;
import com.google.collide.client.code.FileSelectedPlace;
import com.google.collide.client.history.Place;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
/**
* The File History diff and bar view, which uses a Javascript timeline widget
* to compare past revisions. Also allows for reverting back to previous
* revisions.
*
*/
public class FileHistory extends UiComponent<FileHistory.View> implements FileContent {
/**
* Static factory method for obtaining an instance of FileHistory.
*/
public static FileHistory create(
Place currentPlace, AppContext appContext, FileHistory.View view) {
return new FileHistory(view, currentPlace, appContext);
}
public interface Css extends CssResource {
String base();
String diff();
String timelineBar();
String timelineWrapper();
String timelineTitle();
String filters();
String filter();
String currentFilter();
String closeButton();
String closeIcon();
String button();
String disabledButton();
String title();
String rightRevisionTitle();
String leftRevisionTitle();
String titleBar();
}
public interface Resources extends Timeline.Resources {
@Source("close.png")
ImageResource closeIcon();
@Source("FileHistory.css")
Css fileHistoryCss();
}
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("FileHistory.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, View> {
}
static MyBinder binder = GWT.create(MyBinder.class);
@UiField
DivElement diff;
@UiField
DivElement timelineBar;
@UiField
DivElement timelineWrapper;
@UiField
DivElement timelineTitle;
Element leftRevisionTitle;
Element rightRevisionTitle;
Element titleBar;
Element closeButton;
Element closeIcon;
Timeline.View timelineView;
@UiField(provided = true)
final Resources res;
@UiField(provided = true)
final Css css;
View(Resources res) {
this.res = res;
this.css = res.fileHistoryCss();
this.timelineView = new Timeline.View(res);
setElement(Elements.asJsElement(binder.createAndBindUi(this)));
Elements.asJsElement(timelineWrapper).appendChild(timelineView.getElement());
createDom();
attachEventHandlers();
}
protected void attachEventHandlers() {
closeButton.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
ViewEvents delegate = getDelegate();
if (delegate == null) {
return;
}
delegate.onCloseButtonClicked();
}
});
}
/**
* Initialize diff revision titles on the toolbar (default to base version
* and current version.
*/
private void createDom() {
closeButton = Elements.createDivElement(css.closeButton());
closeIcon = Elements.createDivElement(css.closeIcon());
closeButton.appendChild(closeIcon);
titleBar = Elements.createDivElement(css.titleBar());
leftRevisionTitle = Elements.createDivElement(css.leftRevisionTitle());
rightRevisionTitle = Elements.createDivElement(css.rightRevisionTitle());
leftRevisionTitle.addClassName(css.title());
rightRevisionTitle.addClassName(css.title());
titleBar.appendChild(leftRevisionTitle);
titleBar.appendChild(rightRevisionTitle);
}
}
/**
* Events reported by the FileHistory's View.
*/
private interface ViewEvents {
void onCloseButtonClicked();
}
/**
* The delegate implementation for handling events reported by the View.
*/
private class ViewEventsImpl implements ViewEvents {
@Override
public void onCloseButtonClicked() {
// Clear editor content
api.clearDiffEditors();
// unfortunately this must be hard coded since we can be either a child of
// the file selected place or the workspace place.
WorkspacePlace.PLACE.fireChildPlaceNavigation(
FileSelectedPlace.PLACE.createNavigationEvent(path));
}
}
private final AppContext appContext;
private final Place currentPlace;
private PathUtil path;
private FileHistoryApi api;
@VisibleForTesting
protected FileHistory(View view, Place currentPlace, AppContext appContext) {
super(view);
this.currentPlace = currentPlace;
this.appContext = appContext;
this.path = PathUtil.WORKSPACE_ROOT;
view.setDelegate(new ViewEventsImpl());
}
@Override
public PathUtil filePath() {
return path;
}
public void setPath(PathUtil path) {
this.path = path;
}
public void setApi(FileHistoryApi api) {
this.api = api;
}
@Override
public Element getContentElement() {
return getView().getElement();
}
@Override
public void onContentDisplayed() {
}
@Override
public void onContentDestroyed() {
}
/* Setup/teardown for the FileHistory place */
public void setup(Element contentHeader) {
contentHeader.appendChild(getView().closeButton);
contentHeader.appendChild(getView().titleBar);
changeLeftRevisionTitle("Workspace Branched");
changeRightRevisionTitle("Current Version");
}
public void teardown() {
getView().closeButton.removeFromParent();
getView().titleBar.removeFromParent();
}
/* Change revision titles */
public void changeLeftRevisionTitle(String title) {
getView().leftRevisionTitle.setTextContent(title);
}
public void changeRightRevisionTitle(String title) {
getView().rightRevisionTitle.setTextContent(title);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/filehistory/FileHistoryNavigationHandler.java | client/src/main/java/com/google/collide/client/filehistory/FileHistoryNavigationHandler.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.client.filehistory;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.diff.EditorDiffContainer;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.util.PathUtil;
/**
* Navigation handler for the FileHistoryPlace.
*
*
*/
public class FileHistoryNavigationHandler
extends PlaceNavigationHandler<FileHistoryPlace.NavigationEvent> {
private final EditorDiffContainer editorDiffContainer;
private final Timeline timeline;
private final FileHistory fileHistory;
private final MultiPanel<?,?> contentArea;
private final FileHistoryApi api;
private final AppContext appContext;
private PanelContent oldContent;
public FileHistoryNavigationHandler(Place currentPlace,
AppContext appContext,
MultiPanel<?,?> contentArea,
DocumentManager documentManager) {
this.appContext = appContext;
this.contentArea = contentArea;
this.editorDiffContainer = EditorDiffContainer.create(appContext);
this.fileHistory = FileHistory.create(
currentPlace, appContext, new FileHistory.View(appContext.getResources()));
this.timeline = Timeline.create(fileHistory, appContext);
this.api =
new FileHistoryApi(appContext,editorDiffContainer, timeline, documentManager);
this.fileHistory.setApi(api);
this.timeline.setApi(api);
}
@Override
public void cleanup() {
fileHistory.teardown();
contentArea.getToolBar().show();
if (oldContent != null) {
contentArea.setContent(oldContent);
}
}
@Override
protected void enterPlace(FileHistoryPlace.NavigationEvent navigationEvent) {
Elements.asJsElement(fileHistory.getView().diff)
.appendChild(editorDiffContainer.getView().getElement());
oldContent = contentArea.getCurrentContent();
contentArea.setContent(fileHistory);
contentArea.setHeaderVisibility(false);
fileHistory.setup(contentArea.getView().getHeaderElement());
contentArea.getToolBar().hide();
/* Get file contents and diff */
PathUtil filePath = navigationEvent.getPath();
fileHistory.setPath(filePath);
timeline.setPath(filePath);
timeline.setLoading();
api.getFileRevisions(filePath, navigationEvent.getRootId());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/filehistory/FileHistoryApi.java | client/src/main/java/com/google/collide/client/filehistory/FileHistoryApi.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.client.filehistory;
import com.google.collide.client.AppContext;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.diff.EditorDiffContainer;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.logging.Log;
import com.google.collide.clientlibs.model.Workspace;
import com.google.collide.dto.DiffChunkResponse;
import com.google.collide.dto.DiffChunkResponse.DiffType;
import com.google.collide.dto.FileContents;
import com.google.collide.dto.GetFileRevisions;
import com.google.collide.dto.GetFileRevisionsResponse;
import com.google.collide.dto.Revision;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.DiffChunkResponseImpl;
import com.google.collide.dto.client.DtoClientImpls.GetFileRevisionsImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.common.base.Preconditions;
/**
* Handles queries from the file history classes for getting revisions and diffs
* of those revisions
*/
class FileHistoryApi {
private final AppContext appContext;
private final EditorDiffContainer editorDiffContainer;
private final Timeline timeline;
private final DocumentManager documentManager;
private Workspace workspace;
FileHistoryApi(AppContext appContext, EditorDiffContainer editorDiffContainer,
Timeline timeline, DocumentManager documentManager) {
this.appContext = appContext;
this.editorDiffContainer = editorDiffContainer;
this.timeline = timeline;
this.documentManager = documentManager;
}
void setWorkspace(Workspace workspace) {
// Save workspace info. Time line asks server for revisions and workspace info. When revision
// info comes after workspace info, the saved workspace info is used to properly set revision
// tooltips.
this.workspace = workspace;
this.timeline.updateNodeTooltips();
}
Workspace getWorkspace() {
return workspace;
}
void getFileRevisions(PathUtil path, String pathRootId) {
Preconditions.checkNotNull(pathRootId);
GetFileRevisionsImpl message = GetFileRevisionsImpl.make()
.setClientId(BootstrapSession.getBootstrapSession().getActiveClientId())
.setPathRootId(pathRootId)
.setPath(path.getPathString())
.setNumOfRevisions(timeline.maxNumberOfNodes())
.setFiltering(true)
.setIncludeBranchRevision(true)
.setIncludeMostRecentRevision(true);
getFileRevisions(message);
}
void clearDiffEditors() {
editorDiffContainer.clearDiffEditors();
}
/**
* Fetch a list of revisions for the given file, and call Timeline's drawNodes
*/
private void getFileRevisions(final GetFileRevisions message) {
// appContext.getStatusManager(). ("Getting file revisions");
appContext.getFrontendApi().GET_FILE_REVISIONS
.send(message,
new FrontendApi.ApiCallback<GetFileRevisionsResponse>() {
@Override
public void onFail(FailureReason reason) {
Log.warn(getClass(), "Call to get revisions for file failed.");
}
@Override
public void onMessageReceived(GetFileRevisionsResponse message) {
// Render timeline with newly fetched revisions
timeline.drawNodes((JsoArray<Revision>) message.getRevisions());
}
});
}
/**
* Fetch the diff of the files for the given revisions and set
* editorDiffContainer split-pane contents to be the current file before and
* after snapshots
*/
void setFile(final PathUtil path, final Revision beforeRevision, final Revision afterRevision) {
if (beforeRevision == null) {
throw new IllegalArgumentException("before revision can not be null");
}
if (editorDiffContainer.hasRevisions(beforeRevision, afterRevision)) {
// We already had the diff.
return;
}
editorDiffContainer.setExpectedRevisions(beforeRevision, afterRevision);
final int scrollTop = editorDiffContainer.getScrollTop();
// TODO: This use to call out to an API to receive the file diff,
// we can revist this stuff later, it just called set diff chunks
}
/**
* Gets the file from document manager and sets the left and right panels to the same file.
*/
void setUnchangedFile(final PathUtil path) {
timeline.setDiffFilePaths(path.getPathString(), path.getPathString());
editorDiffContainer.setExpectedRevisions(
EditorDiffContainer.UNKNOWN_REVISION, EditorDiffContainer.UNKNOWN_REVISION);
documentManager.getDocument(path, new DocumentManager.GetDocumentCallback() {
@Override
public void onUneditableFileContentsReceived(FileContents contents) {
// TODO handle images here.
}
@Override
public void onFileNotFoundReceived() {
Log.warn(getClass(), "Call to get file " + path.getPathString() + " failed.");
}
@Override
public void onDocumentReceived(Document document) {
// editable file. construct unchanged diff chunk here.
String text = document.asText();
DiffChunkResponseImpl unchangedDiffChunk = DiffChunkResponseImpl.make()
.setBeforeData(text).setAfterData(text).setDiffType(DiffType.UNCHANGED);
JsonArray<DiffChunkResponse> diffChunks = JsoArray.create();
diffChunks.add(unchangedDiffChunk);
editorDiffContainer.setDiffChunks(path, diffChunks, EditorDiffContainer.UNKNOWN_REVISION,
EditorDiffContainer.UNKNOWN_REVISION);
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/filehistory/FileHistoryPlace.java | client/src/main/java/com/google/collide/client/filehistory/FileHistoryPlace.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.client.filehistory;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceConstants;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.WorkspacePlaceNavigationHandler;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
/**
* A Place representing the file history view in the workspace.
*
*
*/
public class FileHistoryPlace extends Place {
/**
* The event that gets dispatched in order to arrive at the Workspace.
*
* @See {@link WorkspacePlaceNavigationHandler}.
*/
public class NavigationEvent extends PlaceNavigationEvent<FileHistoryPlace> {
private static final String PATH_KEY = "path";
private static final String ROOT_ID_KEY = "revision";
private final PathUtil path;
private final String rootId;
private NavigationEvent(PathUtil path, String rootId) {
super(FileHistoryPlace.this);
this.path = path;
this.rootId = rootId;
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> state = JsoStringMap.create();
state.put(PATH_KEY, path.getPathString());
if (rootId != null) {
state.put(ROOT_ID_KEY, rootId);
}
return state;
}
public PathUtil getPath() {
return path;
}
public String getRootId() {
return rootId;
}
}
public static final FileHistoryPlace PLACE = new FileHistoryPlace();
FileHistoryPlace() {
super(PlaceConstants.FILEHISTORY_PLACE_NAME);
}
@Override
public PlaceNavigationEvent<FileHistoryPlace> createNavigationEvent(
JsonStringMap<String> decodedState) {
return createNavigationEvent(new PathUtil(decodedState.get(NavigationEvent.PATH_KEY)),
decodedState.get(NavigationEvent.ROOT_ID_KEY));
}
public PlaceNavigationEvent<FileHistoryPlace> createNavigationEvent(
PathUtil path, String rootId) {
// TODO: considering adding rootId to PathUtil so that the client
// can somewhat sensibly talk about paths to objects in both space and time.
return new NavigationEvent(path, rootId);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/filehistory/TimelineNode.java | client/src/main/java/com/google/collide/client/filehistory/TimelineNode.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.client.filehistory;
import java.util.Date;
import java.util.List;
import collide.client.util.Elements;
import com.google.collide.client.ClientConfig;
import com.google.collide.client.ui.menu.PositionController.HorizontalAlign;
import com.google.collide.client.ui.menu.PositionController.Position;
import com.google.collide.client.ui.menu.PositionController.Positioner;
import com.google.collide.client.ui.menu.PositionController.VerticalAlign;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.client.util.dom.MouseMovePauseDetector;
import com.google.collide.client.util.dom.eventcapture.MouseCaptureListener;
import com.google.collide.clientlibs.model.Workspace;
import com.google.collide.dto.Revision;
import com.google.collide.dto.Revision.RevisionType;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.common.collect.Lists;
import com.google.gwt.i18n.shared.DateTimeFormat;
import com.google.gwt.i18n.shared.DateTimeFormat.PredefinedFormat;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import elemental.css.CSSStyleDeclaration;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.MouseEvent;
import elemental.html.DivElement;
/**
* Representation of a timeline node ("dot") on the timeline widget, and its
* tooltip with node information
*/
public class TimelineNode extends UiComponent<TimelineNode.View> {
/**
* Static factory method for obtaining an instance of the TimelineNode.
*/
public static TimelineNode create(
TimelineNode.View view, int index, Revision revision, Timeline timeline) {
return new TimelineNode(view, index, revision, timeline);
}
/**
* Style names used by the TimelineNode.
*/
public interface Css extends CssResource {
String base();
String currentLeft();
String currentRight();
String nodeWrapper();
String largeNodeWrapper();
String node();
String nodeRange();
String nodeBranch();
String nodeBranchRange();
String nodeSync();
String nodeSyncRange();
String nodeIndicator();
String conflictIcon();
String conflictResolvedIcon();
// TODO: add deleted icon.
String label();
}
/**
* CSS and images used by the TimelineNode.
*/
public interface Resources extends Tooltip.Resources {
// Regular Node
@Source("node.png")
ImageResource node();
@Source("conflictIcon.png")
ImageResource conflictIcon();
@Source("conflictResolvedIcon.png")
ImageResource conflictResolvedIcon();
@Source("nodeHover.png")
ImageResource nodeHover();
@Source("nodeRange.png")
ImageResource nodeRange();
// Branch Node
@Source("nodeBranch.png")
ImageResource nodeBranch();
@Source("nodeBranchHover.png")
ImageResource nodeBranchHover();
@Source("nodeBranchRange.png")
ImageResource nodeBranchRange();
// Sync Node
@Source("nodeSync.png")
ImageResource nodeSync();
@Source("nodeSyncHover.png")
ImageResource nodeSyncHover();
@Source("nodeSyncRange.png")
ImageResource nodeSyncRange();
// Current Node
@Source("nodeCurrent.png")
ImageResource nodeCurrent();
@Source("clear.png")
ImageResource clear();
@Source("TimelineNode.css")
Css timelineNodeCss();
}
/**
* The View for the TimelineNode.
*/
public static class View extends CompositeView<ViewEvents> {
private final Resources res;
private final Css css;
private DivElement nodeIndicator;
private DivElement node;
private DivElement nodeWrapper;
private DivElement label;
View(TimelineNode.Resources res) {
super(Elements.createDivElement(res.timelineNodeCss().base()));
this.res = res;
this.css = res.timelineNodeCss();
createDom();
attachHandlers();
}
protected void createDom() {
getElement().setAttribute("draggable", "true");
node = Elements.createDivElement(css.node());
nodeIndicator = Elements.createDivElement(css.nodeIndicator());
nodeWrapper = Elements.createDivElement(css.nodeWrapper());
label = Elements.createDivElement(css.label());
nodeWrapper.appendChild(node);
nodeWrapper.appendChild(nodeIndicator);
getElement().appendChild(nodeWrapper);
}
protected void attachHandlers() {
nodeWrapper.setOndblclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
ViewEvents delegate = getDelegate();
if (delegate == null) {
return;
}
delegate.onNodeDblClick();
}
});
nodeWrapper.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
ViewEvents delegate = getDelegate();
if (delegate == null) {
return;
}
delegate.onNodeClick(((MouseEvent) evt).isCtrlKey());
}
});
}
public void attachDragHandler(MouseCaptureListener mouseCaptureListener) {
nodeWrapper.addEventListener(Event.MOUSEDOWN, mouseCaptureListener, false);
}
public void setNodeType(NodeType nodeType) {
node.addClassName(nodeType.getBaseClassName());
nodeIndicator.addClassName(nodeType.getIndicatorClassName());
nodeWrapper.addClassName(nodeType.getWrapperClassName());
}
public void addRangeStyles(NodeType nodeType, boolean left) {
node.addClassName(nodeType.getRangeClassName());
if (left) {
getElement().addClassName(css.currentLeft());
} else {
getElement().addClassName(css.currentRight());
}
}
public void clearRangeStyles(NodeType nodeType) {
node.removeClassName(nodeType.getRangeClassName());
getElement().removeClassName(css.currentLeft());
getElement().removeClassName(css.currentRight());
}
public void setAsCurrentNode() {
node.setAttribute("current", "true");
nodeWrapper.removeClassName(css.largeNodeWrapper());
}
}
/**
* Events reported by the TimelineNode's View.
*/
private interface ViewEvents {
void onNodeDblClick();
void onNodeClick(boolean isCtrlKey);
}
/**
* The delegate implementation for handling events reported by the View.
*/
private class ViewEventsImpl implements ViewEvents {
/**
* On node double click, the range should adjust to be this node -> last
* node
*/
@Override
public void onNodeDblClick() {
setTempLeftRange(true);
timeline.nodes.get(timeline.nodes.size() - 1).setTempRightRange(true);
// Update current range = temp range
timeline.resetLeftRange();
timeline.resetRightRange();
timeline.adjustRangeLine();
}
/**
* On node click, the range should shorten appropriately
*/
@Override
public void onNodeClick(boolean isCtrlKey) {
// Check if dot inside the range line or not
if (index > timeline.currentLeftRange.index && index < timeline.currentRightRange.index) {
// If clicked inside the range line,
if (isCtrlKey) {
// act as dragging the right side
setTempRightRange(true);
} else {
// act as dragging the left side
setTempLeftRange(true);
}
} else {
// If clicked outside the range line, find which side it is closest
// to and update the range line
if (index < timeline.currentLeftRange.index) {
setTempLeftRange(true);
} else if (index > timeline.currentRightRange.index) {
setTempRightRange(true);
}
}
// Update current range = temp range
timeline.resetLeftRange();
timeline.resetRightRange();
timeline.adjustRangeLine();
}
}
private final MouseCaptureListener mouseCaptureListener = new MouseCaptureListener() {
@Override
protected void onMouseMove(MouseEvent evt) {
mouseMovePauseDetector.handleMouseMove(evt);
if (!dragging) {
onNodeDragStart();
dragging = true;
}
onNodeDragMove(getDeltaX());
}
@Override
protected void onMouseUp(MouseEvent evt) {
onNodeDragEnd();
dragging = false;
}
};
private final MouseMovePauseDetector mouseMovePauseDetector =
new MouseMovePauseDetector(new MouseMovePauseDetector.Callback() {
@Override
public void onMouseMovePaused() {
if (timeline.closeEnoughToDot()) {
timeline.adjustRangeLine();
timeline.setDiffForRevisions();
}
}
});
private boolean dragging = false;
private void onNodeDragStart() {
// Record original x-coordinate
timeline.setCurrentDragX(0);
// Can only drag edge nodes
TimelineNode that = getNode();
if (that == timeline.currentLeftRange) {
timeline.setDrag(true);
timeline.forceCursor("col-resize");
} else if (that == timeline.currentRightRange) {
timeline.setDrag(true);
timeline.forceCursor("col-resize");
}
mouseMovePauseDetector.start();
}
private void onNodeDragMove(int delta) {
if (timeline.getDrag()) {
timeline.moveRangeEdge(getNode(), delta);
}
}
public void onNodeDragEnd() {
mouseMovePauseDetector.stop();
timeline.setDrag(false);
timeline.removeCursor();
timeline.resetCatchUp();
// Update current range = temp range
timeline.resetLeftRange();
timeline.resetRightRange();
timeline.adjustRangeLine();
timeline.setDiffForRevisions();
}
// Timeline Node types (sync, branch)
static class NodeType {
/**
* Static factory method for a NodeType.
*/
public static NodeType create(Revision revision, Css css) {
String indicatorClassName = css.nodeIndicator();
switch (revision.getRevisionType()) {
case AUTO_SAVE:
if (revision.getHasUnresolvedConflicts()) {
indicatorClassName = css.conflictIcon();
} else if (revision.getIsFinalResolution()) {
indicatorClassName = css.conflictResolvedIcon();
}
return new NodeType(revision.getRevisionType(), css.node(), css.nodeRange(),
css.nodeWrapper(), indicatorClassName);
case SYNC_SOURCE:
case SYNC_MERGED:
if (revision.getHasUnresolvedConflicts()) {
indicatorClassName = css.conflictIcon();
}
// not possible to be a final conflict resolution node.
return new NodeType(revision.getRevisionType(), css.nodeSync(), css.nodeSyncRange(),
css.largeNodeWrapper(), indicatorClassName);
case BRANCH:
return new NodeType(revision.getRevisionType(), css.nodeBranch(), css.nodeBranchRange(),
css.largeNodeWrapper(), indicatorClassName);
case DELETE:
// TODO need a DELETE node type or indicator.
return new NodeType(revision.getRevisionType(), css.node(), css.nodeRange(),
css.nodeWrapper(), indicatorClassName);
case MOVE:
// TODO need a MOVE node type or indicator.
return new NodeType(revision.getRevisionType(), css.node(), css.nodeRange(),
css.nodeWrapper(), indicatorClassName);
case COPY:
// TODO need a COPY node type or indicator.
return new NodeType(revision.getRevisionType(), css.node(), css.nodeRange(),
css.nodeWrapper(), indicatorClassName);
default:
throw new IllegalArgumentException("Attempted to create a non-existent NodeType!");
}
}
private final RevisionType type;
private final String baseClassName;
private final String rangeClassName;
private final String wrapperClassName;
private final String indicatorClassName; //displayed at top-right to indicate node states.
NodeType(
RevisionType type, String baseClassName, String rangeClassName, String wrapperClassName,
String indicatorClassName) {
this.type = type;
this.baseClassName = baseClassName;
this.rangeClassName = rangeClassName;
this.wrapperClassName = wrapperClassName;
this.indicatorClassName = indicatorClassName;
}
RevisionType getType(){
return type;
}
String getBaseClassName() {
return baseClassName;
}
String getRangeClassName() {
return rangeClassName;
}
String getWrapperClassName() {
return wrapperClassName;
}
String getIndicatorClassName(){
return indicatorClassName;
}
}
private final Tooltip tooltip;
private final Timeline timeline;
private final Revision revision;
// file path is discovered during file diff.
private String filePath = "";
public final int index;
public final NodeType nodeType;
public boolean currentNode;
protected TimelineNode(View view, int index, Revision revision, Timeline timeline) {
super(view);
this.timeline = timeline;
this.revision = revision;
this.index = index;
this.nodeType = NodeType.create(revision, getView().css);
setLabelText();
setNodeOffset();
setNodeType();
Positioner positioner = new Tooltip.TooltipPositionerBuilder().setVerticalAlign(
VerticalAlign.TOP).setHorizontalAlign(HorizontalAlign.MIDDLE).setPosition(Position.OVERLAP)
.buildAnchorPositioner(getView().nodeWrapper);
tooltip = new Tooltip.Builder(getView().res, getView().nodeWrapper, positioner).setTooltipText(
"").build();
tooltip.setTitle(getTooltipTitle());
view.setDelegate(new ViewEventsImpl());
view.attachDragHandler(mouseCaptureListener);
}
private TimelineNode getNode() {
return this;
}
public Revision getRevision() {
return revision;
}
void setFilePath(String filePath) {
this.filePath = filePath;
}
String getFilePath() {
return filePath;
}
public String getRevisionTitle() {
return filePath + " @ " + getFormattedFullDate();
}
void updateTooltipTitle() {
tooltip.setTitle(getTooltipTitle());
}
private String getTooltipTitle() {
String type = revision.getRevisionType().name();
if (revision.getRevisionType() == RevisionType.AUTO_SAVE) {
type = "EDIT";
}
Workspace workspaceInfo = timeline.getFileHistoryApi().getWorkspace();
if (workspaceInfo != null /*&& workspaceInfo.getWorkspaceType() == WorkspaceType.TRUNK*/) {
type = "SUBMITTED_" + type;
}
return type + " " + getFormattedFullDate();
}
private String[] getTooltipText() {
List<String> text = Lists.newArrayList();
if (revision.getHasUnresolvedConflicts()) {
text.add("Has conflicts.");
} else if (revision.getIsFinalResolution()) {
text.add("Conflicts resolved.");
}
if (ClientConfig.isDebugBuild()) {
if (revision.getPreviousNodesSkipped() != 0) {
text.add("Hide " + (revision.getPreviousNodesSkipped() == -1
? " unkown # of" : revision.getPreviousNodesSkipped()) + " previous nodes.");
}
text.add("Root ID: " + revision.getRootId());
text.add("ID:" + revision.getNodeId());
}
return text.toArray(new String[0]);
}
private String getFormattedDate() {
// If today, only put the time. Else, only put the date.
// TODO: Figure out what's the best way to display dates like this
PredefinedFormat format;
if (dateIsToday(new Date(Long.valueOf(revision.getTimestamp())))) {
format = PredefinedFormat.TIME_SHORT;
} else {
format = PredefinedFormat.DATE_SHORT;
}
return getFormattedDate(format);
}
private String getFormattedFullDate() {
return getFormattedDate(PredefinedFormat.DATE_TIME_SHORT);
}
private boolean dateIsToday(Date date) {
Date today = new Date();
return today.getYear() == date.getYear() && today.getDate() == date.getDate();
}
private String getFormattedDate(PredefinedFormat format) {
String timestamp = revision.getTimestamp();
Date date = new Date(Long.valueOf(revision.getTimestamp()));
return DateTimeFormat.getFormat(format).format(date);
}
protected void setLabelText() {
getView().label.setTextContent(getFormattedDate());
}
protected void setNodeOffset() {
getView().getElement().getStyle().setLeft(getNodeOffset(), CSSStyleDeclaration.Unit.PCT);
}
public double getNodeOffset() {
return (index * 100.0 / (timeline.numNodes - 1));
}
public void setNodeType() {
getView().setNodeType(nodeType);
}
public void setAsCurrentNode() {
currentNode = true;
getView().setAsCurrentNode();
}
/*
* Methods to set current and temp ranges. Temp ranges needed to preserve
* original (before dragging) range as the "current"
*/
/**
* Set the current node to be the new temporary left edge node of the range
* line, and adjusts range styles. The temporary node becomes the current node
* upon calling resetLeftRange();
*/
public void setTempLeftRange(boolean updateDiff) {
TimelineNode old = timeline.tempLeftRange;
if (old != null) {
old.getView().clearRangeStyles(old.nodeType);
}
timeline.tempLeftRange = this;
getView().addRangeStyles(nodeType, true);
if (updateDiff) {
timeline.setDiffForRevisions();
}
}
/**
* Set the current node to be the new temporary right edge node of the range
* line, and adjusts range styles. The temporary node becomes the current node
* upon calling resetRightRange();
*/
public void setTempRightRange(boolean updateDiff) {
TimelineNode old = timeline.tempRightRange;
// Clear range styles from the old node
if (old != null) {
old.getView().clearRangeStyles(old.nodeType);
}
timeline.tempRightRange = this;
getView().addRangeStyles(nodeType, false);
if (updateDiff) {
timeline.setDiffForRevisions();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/filehistory/Timeline.java | client/src/main/java/com/google/collide/client/filehistory/Timeline.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.client.filehistory;
import collide.client.common.CommonResources;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.dom.MouseMovePauseDetector;
import com.google.collide.client.util.dom.eventcapture.MouseCaptureListener;
import com.google.collide.dto.Revision;
import com.google.collide.dto.Revision.RevisionType;
import com.google.collide.json.client.JsoArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import elemental.css.CSSStyleDeclaration;
import elemental.events.Event;
import elemental.events.MouseEvent;
import elemental.html.DivElement;
import elemental.html.StyleElement;
/**
* Representation for the FileHistory timeline widget
*
*/
public class Timeline extends UiComponent<Timeline.View> {
/**
* Static factory method for obtaining an instance of the Timeline.
*/
public static Timeline create(FileHistory fileHistory, AppContext context) {
return new Timeline(fileHistory, fileHistory.getView().timelineView, context);
}
/**
* Style names used by the Timeline.
*/
public interface Css extends CssResource {
String base();
String rangeLine();
String rangeLineWrapper();
String baseLine();
String nodeContainer();
String notice();
}
/**
* CSS and images used by the Timeline.
*/
public interface Resources extends CommonResources.BaseResources {
@Source("Timeline.css")
Css timelineCss();
@Source("rangeLeft.png")
ImageResource rangeLeft();
@Source("rangeRight.png")
ImageResource rangeRight();
}
/**
* The View for the Timeline.
*/
public static class View extends CompositeView<Void> {
private final Resources res;
private final Css css;
private DivElement baseLine;
private DivElement rangeLine;
private DivElement rangeLineWrapper;
private DivElement nodeContainer;
// Keep range line width and left because in CSS they're stored as Strings
// with unit PCT
private double rangeLineWidth = 100.0;
private double rangeLineLeft = 0.0;
// Base line width for maxNode calculations
private int baseLineWidth = 0;
View(Timeline.Resources res) {
super(Elements.createDivElement(res.timelineCss().base()));
this.res = res;
this.css = res.timelineCss();
// Create DOM and initialize View.
createDom();
}
/**
* Get revision history and create the DOM for the timeline widget.
*/
private void createDom() {
// Instantiate DOM elems.
baseLine = Elements.createDivElement(css.baseLine());
rangeLine = Elements.createDivElement(css.rangeLine());
rangeLineWrapper = Elements.createDivElement(css.rangeLineWrapper());
nodeContainer = Elements.createDivElement(css.nodeContainer());
rangeLineWrapper.appendChild(rangeLine);
getElement().appendChild(baseLine);
getElement().appendChild(rangeLineWrapper);
getElement().appendChild(nodeContainer);
}
/**
* Empty the node container of any previous nodes before we create
* fresh nodes from the getRevisions call
*/
public void emptyNodeContainer() {
nodeContainer.setInnerHTML("");
}
public void setLoading() {
emptyNodeContainer();
toggleTimeline(true);
// Capture length of baseLine for later use before hiding
baseLineWidth = baseLine.getOffsetWidth();
toggleTimeline(false);
}
public void setNotice(String text) {
DivElement notice = Elements.createDivElement(css.notice());
notice.setTextContent(text);
nodeContainer.appendChild(notice);
}
public int getBaseLineWidth() {
return baseLineWidth;
}
public void toggleTimeline(boolean visible) {
CssUtils.setDisplayVisibility(rangeLineWrapper, visible);
CssUtils.setDisplayVisibility(baseLine, visible);
}
/**
* Adjust range line to be between the currentLeftRange and
* currentRightRange. Used for snapping between a specific range of nodes.
*
* @param leftIndex index of the left edge node
* @param rightIndex index of the right edge node
* @param numNodes total number of nodes, used for percentage width calculations
*/
public void adjustRangeLine(int leftIndex, int rightIndex, int numNodes) {
rangeLineWidth = ((rightIndex - leftIndex) * 100.0) / (numNodes - 1);
rangeLineLeft = (leftIndex * 100.0 / (numNodes - 1));
rangeLineWrapper.getStyle().setWidth(rangeLineWidth, CSSStyleDeclaration.Unit.PCT);
rangeLineWrapper.getStyle().setLeft(rangeLineLeft, CSSStyleDeclaration.Unit.PCT);
}
/**
* Adjust the range line during the middle of a drag (NOT strictly between
* two different nodes)
*
* @param widthDelta increase in range line width, in percentage
* @param leftDelta increase in range line left offset, in percentage
*/
public void adjustRangeLineBetween(double widthDelta, double leftDelta) {
rangeLineWidth += widthDelta;
rangeLineLeft += leftDelta;
rangeLineWrapper.getStyle().setWidth(rangeLineWidth, CSSStyleDeclaration.Unit.PCT);
rangeLineWrapper.getStyle().setLeft(rangeLineLeft, CSSStyleDeclaration.Unit.PCT);
}
public void attachDragHandler(MouseCaptureListener mouseCaptureListener) {
rangeLineWrapper.addEventListener(Event.MOUSEDOWN, mouseCaptureListener, false);
}
}
/* Mouse dragging event listener for range Line */
private final MouseCaptureListener mouseCaptureListener = new MouseCaptureListener() {
@Override
protected void onMouseMove(MouseEvent evt) {
mouseMovePauseDetector.handleMouseMove(evt);
if (!dragging) {
onNodeDragStart();
dragging = true;
}
onNodeDragMove(getDeltaX());
}
@Override
protected void onMouseUp(MouseEvent evt) {
onNodeDragEnd();
dragging = false;
}
};
private final MouseMovePauseDetector mouseMovePauseDetector =
new MouseMovePauseDetector(new MouseMovePauseDetector.Callback() {
@Override
public void onMouseMovePaused() {
if (closeEnoughToDot()) {
adjustRangeLine();
setDiffForRevisions();
}
}
});
private boolean dragging = false;
private void onNodeDragStart() {
// Record original x-coordinate
setCurrentDragX(0);
forceCursor("-webkit-grabbing");
setDrag(true);
mouseMovePauseDetector.start();
}
private void onNodeDragMove(int delta) {
if (getDrag()) {
moveRange(delta);
}
}
public void onNodeDragEnd() {
mouseMovePauseDetector.stop();
setDrag(false);
removeCursor();
resetCatchUp();
// Update current range = temp range
resetLeftRange();
resetRightRange();
adjustRangeLine();
setDiffForRevisions();
}
final AppContext context;
FileHistoryApi api;
final FileHistory fileHistory;
PathUtil path;
JsoArray<TimelineNode> nodes;
int numNodes;
// Minimum interval between (used to calculate max number of nodes) in pixels
private final int MIN_NODE_INTERNAL = 70;
// Nodes representing the current left and right sides of the rangeLine
TimelineNode currentLeftRange;
TimelineNode currentRightRange;
// Temporary nodes representing the current left and right sides of the
// range line during the current action (ex. during a drag). These values
// are converted into the currentLeftRange and currentRightRange at the
// end of the drag (see resetLeftRange() and resetRightRange()). We need
// these because the drag offset is calculated from the original rangeLine
// position before a drag.
TimelineNode tempLeftRange;
TimelineNode tempRightRange;
// Current dx dragged so far, needed for snapping calculations
private int currentDragX;
// Amount the mouse needs to catch up to the range line due to snapping
private int catchUp;
private boolean catchUpLeft;
// Whether the current node is draggable (must be an edge node)
private boolean drag;
// Snap-to constants
private static final double SNAP_THRESHOLD = 2.0/3.0;
// Cursor style to force when doing a drag action
private final StyleElement forceDragCursor;
protected Timeline(FileHistory fileHistory, View view, AppContext context) {
super(view);
this.context = context;
this.fileHistory = fileHistory;
this.forceDragCursor = Elements.getDocument().createStyleElement();
this.nodes = JsoArray.create();
view.attachDragHandler(mouseCaptureListener);
}
public void setApi(FileHistoryApi api) {
this.api = api;
}
public void setPath(PathUtil path) {
this.path = path;
}
public void setLoading() {
// Set loading state for timeline
getView().setLoading();
}
void updateNodeTooltips() {
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).updateTooltipTitle();
}
}
/**
* Return the number of nodes allowed with a minimum node spacing
*/
public int maxNumberOfNodes() {
return (getView().getBaseLineWidth() / MIN_NODE_INTERNAL) + 1;
}
private JsoArray<Revision> removeSyncSource(JsoArray<Revision> revisions) {
JsoArray<Revision> result = JsoArray.create();
for (int i = 0; i < revisions.size(); i++) {
if (revisions.get(i).getRevisionType() != RevisionType.SYNC_SOURCE) {
// For now, we hide SYNC_SOURCE.
result.add(revisions.get(i));
}
}
return result;
}
public void drawNodes(JsoArray<Revision> revisions) {
// Remove any existing nodes
getView().emptyNodeContainer();
nodes.clear();
if (revisions.size() > 1) {
getView().toggleTimeline(true);
// Make file history view default the left side of the diff to the last
// sync point if any.
int leftNodeIndex = -1;
// Draw nodes based on data
numNodes = revisions.size();
for (int i = 0; i < revisions.size(); i++) {
TimelineNode currNode = new TimelineNode(
new TimelineNode.View(context.getResources()), i, revisions.get(i), this);
nodes.add(currNode);
getView().nodeContainer.appendChild(currNode.getView().getElement());
if (revisions.get(i).getRevisionType() == RevisionType.SYNC_SOURCE) {
leftNodeIndex = i;
}
}
// By default, the range goes from the first to last node
TimelineNode leftNode;
if (leftNodeIndex < 0) {
leftNode = nodes.get(0);
} else if (leftNodeIndex == nodes.size() - 1) {
// When leftNode is the same as the right node, move leftNode left.
// This can happen when users sync and this file has NO conflict.
// We have a SYNC_SOURCE and SYNC_MERGED; leftNodeIndex is at
// SYNC_MERGED, which is the last node.
// Since revisions.size() > 1, nodes.size() - 2 is valid.
// To avoid to have left and right diff points to the same revision.
leftNode = nodes.get(nodes.size() - 2);
} else {
leftNode = nodes.get(leftNodeIndex);
}
setActiveRange(leftNode, nodes.get(nodes.size() - 1));
adjustRangeLine();
} else {
api.setUnchangedFile(path);
getView().setNotice("File unchanged.");
}
}
/* Set cursor style */
public void forceCursor(String type) {
forceDragCursor.setTextContent("* { cursor: " + type + " !important; }");
Elements.getBody().appendChild(forceDragCursor);
}
public void removeCursor() {
forceDragCursor.removeFromParent();
}
/* Getter and setter methods for private Timeline fields */
public void setCurrentDragX(int previousDragX) {
this.currentDragX = previousDragX;
}
public int getCurrentDragX() {
return currentDragX;
}
public void setDrag(boolean drag) {
this.drag = drag;
}
public boolean getDrag() {
return drag;
}
public void resetCatchUp() {
catchUp = 0;
}
/**
* If not valid move for left or right, add distance mouse moved to
* catchup to close the gap
* @param dx
*/
public void incrementCatchUp(int dx) {
catchUp += dx;
catchUpLeft = dx < 0;
}
/**
* Update the current drag and catchUp variables to reflect the post autosnap
* state
* @param snap snap threshold in pixels
* @param offset distance we auto-snapped over, need compensate in mouse movements
*/
public void updateSnapVariables(int snap, int offset) {
// Subtract the distance we just "snapped" to
currentDragX += ((currentDragX > 0) ? -snap : snap);
catchUp += ((currentDragX > 0) ? -offset : offset);
// Save which direction you're currently going in. Let changing directions
// be OK.
catchUpLeft = currentDragX > 0;
}
/* Utility methods for snap-to/dragging calculations */
/**
* Return the distance (in pixels) of the distance between two nodes on
* the timeline.
*/
public int intervalInPx() {
return getView().baseLine.getOffsetWidth() / (numNodes - 1);
}
/**
* Return the horizontal delta dragged, as a percent of the length
* of the timeline (because the width of the timeline is recorded
* as a percentage).
*
* @param dx
* @return
*/
public double percentageMoved(int dx) {
return (dx * 100.0) / getView().baseLine.getOffsetWidth();
}
/*
* Reset range methods - encompasses resetting nodes, code, and labels
*/
public void resetLeftRange() {
currentLeftRange = tempLeftRange;
}
public void resetRightRange() {
currentRightRange = tempRightRange;
}
/**
* Adjust rangeline to be between the temp left and right edge nodes.
*/
public void adjustRangeLine() {
getView().adjustRangeLine(tempLeftRange.index, tempRightRange.index, numNodes);
}
// TODO: If moving back and forth really fast, mouse gets out of
// sync with the range line (there's a gap). Maybe this is due to arithmetic
// rounding errors? Investigate and fix.
/**
* Controls the edge of the range line currently being dragged. If it is a
* valid drag, calculates how the rangeline should be moved in terms of width
* changed (percentage) and left offset. Includes auto-snap while dragging if
* dragged more than 2/3 the way to the next node. Also, "catchup" is allocated
* to compensate for the gap between the mouse and the range line after auto-snapping
*
* @param currentNode the node currently being dragged
* @param dx the current drag dx recorded (+ is to the right, - is to the left)
*/
public void moveRangeEdge(TimelineNode currentNode, int dx) {
// Continue recording and calculating snapping as usual if the mouse
// doesn't need to catch up
if (!catchUp(dx)) {
double percentMoved = percentageMoved(dx);
currentDragX += dx;
// Check if dragging left or right edge node
if (currentNode == currentLeftRange && validLeftEdgeMove(percentMoved < 0)) {
// Left: need to set new left and extend width
// Add to left and subtract from width
getView().adjustRangeLineBetween(-percentMoved, percentMoved);
} else if (currentNode == currentRightRange && validRightEdgeMove(percentMoved < 0)) {
// Right: only need to extend width
// Add to width
getView().adjustRangeLineBetween(percentMoved, 0);
} else {
currentDragX -= dx;
incrementCatchUp(dx);
}
int snap = (int) (SNAP_THRESHOLD * intervalInPx());
int offset = (int) ((1 - SNAP_THRESHOLD) * intervalInPx());
// If > snapThreshold away, snapTo the next one
if (currentDragX > snap || -currentDragX > snap) {
snapToDot(currentNode);
adjustRangeLine();
updateSnapVariables(snap, offset);
}
}
}
public void moveRange(int dx) {
if(!catchUp(dx)) {
double percentMoved = percentageMoved(dx);
boolean left = percentMoved < 0;
currentDragX += dx;
if ((left && validLeftMove()) || (!left && validRightMove())) {
// Add percent moved to the left offset, width stays the same
getView().adjustRangeLineBetween(0, percentMoved);
} else {
currentDragX -= dx;
incrementCatchUp(dx);
}
int snap = (int) (SNAP_THRESHOLD * intervalInPx());
int offset = (int) ((1 - SNAP_THRESHOLD) * intervalInPx());
// If > snapThreshold away, snapTo the next one
if (currentDragX > snap || -currentDragX > snap) {
snapToRange();
adjustRangeLine();
updateSnapVariables(snap, offset);
}
}
}
boolean closeEnoughToDot() {
return Math.abs(currentDragX) < Math.min(30, (1 - SNAP_THRESHOLD) * intervalInPx());
}
/**
* Because of auto-snapping, there's an awkward gap between the mouse and
* the edge of the range line. Let the mouse catch up to the next node before
* moving the range line with mouse movements again.
*
* @param dx number of pixels dragged
* @return if the mouse needs to catch up
*/
public boolean catchUp(int dx) {
int error = 1;
boolean goingLeft = dx > 0;
if ((goingLeft && catchUp < -error) || (!goingLeft && catchUp > error)) {
// Reset catchup if decide to move mouse in the opposite direction before
// reaching the next node
if (goingLeft == catchUpLeft) {
catchUp += dx;
} else {
resetCatchUp();
}
// Skip moving the range line, let the mouse catch up to the snapping
return true;
}
return false;
}
/*
* Snap-to methods for dragging the rangeLine
*/
/**
* Snap dragging to the next left or right (depending on which direction you
* are currently dragging) node, if it is a valid drag direction.
*
* @param currentNode node currently being dragged
*/
public void snapToDot(TimelineNode currentNode) {
boolean left = currentDragX < 0;
int passed = !left ? 1 : -1;
// Check if dragging the left or right edge node
if (currentNode == currentLeftRange && validLeftEdgeMove(left)) {
// Set the node we "snapped to" by dragging as the new left
nodes.get(tempLeftRange.index + passed).setTempLeftRange(false);
} else if (currentNode == currentRightRange && validRightEdgeMove(left)) {
// Set the node we "snapped to" by dragging as the new right
nodes.get(tempRightRange.index + passed).setTempRightRange(false);
}
}
public void snapToRange() {
boolean left = currentDragX < 0;
int passed = !left ? 1 : -1;
// Check that dragging is valid depending on the drag direction
if ((left && validLeftMove()) || (!left && validRightMove())) {
// Set new rangeline range
setTempRange(nodes.get(tempLeftRange.index + passed),
nodes.get(tempRightRange.index + passed), false);
}
}
/**
* Set the temporary range left and right edges at the same time. Used
* in snapToRange().
*
* @param nextLeft the next left edge to be set
* @param nextRight the next right edge to be set
*/
private void setTempRange(TimelineNode nextLeft, TimelineNode nextRight, boolean updateDiff) {
TimelineNode oldLeft = tempLeftRange;
TimelineNode oldRight = tempRightRange;
if (oldRight != null && oldLeft != null) {
oldLeft.getView().clearRangeStyles(oldLeft.nodeType);
oldRight.getView().clearRangeStyles(oldRight.nodeType);
}
tempLeftRange = nextLeft;
tempRightRange = nextRight;
nextLeft.getView().addRangeStyles(nextLeft.nodeType, true);
nextRight.getView().addRangeStyles(nextRight.nodeType, false);
if (updateDiff) {
setDiffForRevisions();
}
}
public void setActiveRange(TimelineNode nextLeft, TimelineNode nextRight) {
setTempRange(nextLeft, nextRight, true);
currentLeftRange = nextLeft;
currentRightRange = nextRight;
}
public void setDiffForRevisions() {
fileHistory.changeLeftRevisionTitle(tempLeftRange.getRevisionTitle());
fileHistory.changeRightRevisionTitle(tempRightRange.getRevisionTitle());
api.setFile(path, tempLeftRange.getRevision(), tempRightRange.getRevision());
}
void setDiffFilePaths(String leftFilePath, String rightFilePath) {
if (tempLeftRange != null) {
tempLeftRange.setFilePath(leftFilePath);
fileHistory.changeLeftRevisionTitle(tempLeftRange.getRevisionTitle());
} else {
fileHistory.changeLeftRevisionTitle(leftFilePath);
}
if (tempRightRange != null) {
tempRightRange.setFilePath(rightFilePath);
fileHistory.changeRightRevisionTitle(tempRightRange.getRevisionTitle());
} else {
fileHistory.changeRightRevisionTitle(rightFilePath);
}
}
/**
* Don't allow dragging to the left past the first node
*
* @return if dragging to the left is valid
*/
public boolean validLeftMove() {
return !(currentDragX < 0 && tempLeftRange.index == 0);
}
/**
* Don't allow dragging to the right past the last node
*
* @return if dragging to the right is valid
*/
public boolean validRightMove() {
return !(currentDragX > 0 && tempRightRange.index == numNodes - 1);
}
/**
* Don't allow dragging the left edge right past the first node or
* dragging the left edge to the right if length = 1
*
* @param dragLeft drag direction (true for left, false for right)
* @return if the current direction is a valid direction for the left edge node
*/
public boolean validLeftEdgeMove(boolean dragLeft) {
return (!dragLeft || validLeftMove())
&& !(!dragLeft && currentDragX > 0 && tempRightRange.index - tempLeftRange.index == 1);
}
/**
* Don't allow dragging the right edge right past the last node or
* dragging the right edge to the left if length = 1
*
* @param dragLeft drag direction (true for left, false for right)
* @return if the current direction is a valid direction for the right edge node
*/
public boolean validRightEdgeMove(boolean dragLeft) {
return (dragLeft || validRightMove())
&& !(dragLeft && currentDragX < 0 && tempRightRange.index - tempLeftRange.index == 1);
}
FileHistoryApi getFileHistoryApi() {
return api;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/syntaxhighlighter/SyntaxHighlighterRenderer.java | client/src/main/java/com/google/collide/client/syntaxhighlighter/SyntaxHighlighterRenderer.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.client.syntaxhighlighter;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.Editor.Css;
import com.google.collide.client.editor.renderer.LineRenderer;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Line;
import com.google.common.base.Preconditions;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
/**
* A {@link LineRenderer} to render the syntax highlighting.
*
*/
public class SyntaxHighlighterRenderer implements LineRenderer {
/**
* ClientBundle for the syntax highlighter renderer.
*/
public interface Resources extends ClientBundle {
@Source("SyntaxHighlighterRenderer.css")
CssResource syntaxHighlighterRendererCss();
}
private final SelectionModel selection;
private final SyntaxHighlighter syntaxHighlighter;
private JsonArray<Token> tokens;
private int tokenPos;
private final Css editorCss;
SyntaxHighlighterRenderer(
SyntaxHighlighter syntaxHighlighter, SelectionModel selection, Editor.Css editorCss) {
this.syntaxHighlighter = syntaxHighlighter;
this.selection = selection;
this.editorCss = editorCss;
}
@Override
public void renderNextChunk(Target target) {
Token token = tokens.get(tokenPos++);
Preconditions.checkNotNull(token, "Token was null");
String tokenValue = token.getValue();
String style = "";
switch (token.getType()) {
case NEWLINE:
// we special case the NEWLINE token and do not append the default style.
style = null;
break;
case ERROR:
style = editorCss.lineRendererError() + " ";
// Fall through to add the external stable class name too (unofficial color API)
default:
style += token.getStyle();
}
target.render(tokenValue.length(), style);
}
@Override
public boolean resetToBeginningOfLine(Line line, int lineNumber) {
tokens = syntaxHighlighter.getTokens(line);
tokenPos = 0;
// If we failed to get any tokens, don't try to render this line
return tokens != null;
}
@Override
public boolean shouldLastChunkFillToRight() {
return false;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/syntaxhighlighter/SyntaxHighlighter.java | client/src/main/java/com/google/collide/client/syntaxhighlighter/SyntaxHighlighter.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.client.syntaxhighlighter;
import javax.annotation.Nonnull;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.ViewportModel;
import com.google.collide.client.editor.renderer.LineRenderer;
import com.google.collide.client.editor.renderer.Renderer;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar;
/**
* Syntax highlighter for the Collide editor.
*
*/
public class SyntaxHighlighter implements DocumentParser.Listener, Renderer.CompletionListener {
/**
* Key for {@link Line#getTag} that stores the parsed tokens for that line. We
* must cache these because of the asynchronous nature of rendering. Once the
* rendering pass is complete, we clear this cache. So, this cache gets cleared
* before the browser event loop is run.
*/
private static final String LINE_TAG_CACHED_TOKENS = "SyntaxHighlighter.cachedTokens";
public static SyntaxHighlighter create(Document document, Renderer renderer,
ViewportModel viewport, SelectionModel selection, DocumentParser documentParser,
Editor.Css editorCss) {
ListenerRegistrar.RemoverManager removerManager = new ListenerRegistrar.RemoverManager();
SyntaxHighlighter syntaxHighlighter = new SyntaxHighlighter(document,
renderer,
viewport,
selection,
documentParser,
removerManager,
editorCss);
removerManager.track(documentParser.getListenerRegistrar().add(syntaxHighlighter));
removerManager.track(renderer.getCompletionListenerRegistrar().add(syntaxHighlighter));
return syntaxHighlighter;
}
private final Renderer editorRenderer;
private final SyntaxHighlighterRenderer lineRenderer;
private final ViewportModel viewport;
private final JsonArray<Line> linesWithCachedTokens;
private final DocumentParser documentParser;
private final ListenerRegistrar.RemoverManager removerManager;
private SyntaxHighlighter(Document document,
Renderer editorRenderer,
ViewportModel viewport,
SelectionModel selection,
DocumentParser documentParser,
ListenerRegistrar.RemoverManager removerManager,
Editor.Css editorCss) {
this.editorRenderer = editorRenderer;
this.viewport = viewport;
this.documentParser = documentParser;
this.removerManager = removerManager;
this.linesWithCachedTokens = JsonCollections.createArray();
this.lineRenderer = new SyntaxHighlighterRenderer(this, selection, editorCss);
}
public LineRenderer getRenderer() {
return lineRenderer;
}
@Override
public void onIterationStart(int lineNumber) {
// do nothing
}
@Override
public void onIterationFinish() {
// do nothing
}
@Override
public void onDocumentLineParsed(Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) {
if (!viewport.isLineInViewport(line)) {
return;
}
// Save the cached tokens so the async render will have them accessible
line.putTag(LINE_TAG_CACHED_TOKENS, tokens);
linesWithCachedTokens.add(line);
editorRenderer.requestRenderLine(line);
}
@Override
public void onRenderCompleted() {
// Wipe the cached tokens
for (int i = 0, n = linesWithCachedTokens.size(); i < n; i++) {
linesWithCachedTokens.get(i).putTag(LINE_TAG_CACHED_TOKENS, null);
}
linesWithCachedTokens.clear();
}
public void teardown() {
removerManager.remove();
}
/**
* Returns the tokens for the given line, or null if the tokens could not be
* retrieved synchronously
*/
JsonArray<Token> getTokens(Line line) {
JsonArray<Token> tokens = line.getTag(LINE_TAG_CACHED_TOKENS);
/*
* If we haven't gotten a callback from the parser (hence no cached tokens),
* try to synchronously parse the line
*/
return tokens != null ? tokens : documentParser.parseLineSync(line);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/history/RootPlace.java | client/src/main/java/com/google/collide/client/history/RootPlace.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.client.history;
import com.google.collide.client.util.logging.Log;
import com.google.collide.clientlibs.navigation.NavigationToken;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
/**
* The Root {@link Place}. We are in the Root place implicitly via onModuleLoad.
* Thus the RootPlace has no associated {@link PlaceNavigationHandler} or
* {@link PlaceNavigationEvent}.
*/
public class RootPlace extends Place {
class NullEvent extends PlaceNavigationEvent<RootPlace> {
protected NullEvent() {
super(RootPlace.this);
}
@Override
public JsonStringMap<String> getBookmarkableState() {
Log.error(getClass(), "The ROOT place should never need bookmarkable state!");
return null;
}
}
/**
* The Root Place is implicit. We get here from onModuleLoad.
*/
static class NullHandler extends PlaceNavigationHandler<NullEvent> {
@Override
protected void enterPlace(NullEvent navigationEvent) {
Log.error(getClass(), "The Navigation handler for the ROOT Place should never fire!");
}
}
public static final RootPlace PLACE = new RootPlace();
public static final String ROOT_NAME = "Root";
/**
* This is an optional default for navigations on the Root that fail. note
* that this place MUST be able to handle a navigation with an empty key/value
* state map.
*/
private Place defaultPlace;
private RootPlace() {
super(ROOT_NAME);
// The Root is always active.
setIsActive(true, null);
}
@Override
public NullEvent createNavigationEvent(JsonStringMap<String> decodedState) {
Log.error(getClass(), "The ROOT Place should never need to create a Navigation Event!");
return null;
}
@Override
public void dispatchHistory(JsonArray<NavigationToken> historyPieces) {
if (historyPieces.isEmpty()
|| (getRegisteredChild(historyPieces.get(0).getPlaceName()) == null)) {
// If the history string is empty, or if the first navigation is bogus,
// then we go to the default child Place if any.
if (defaultPlace != null) {
fireChildPlaceNavigation(defaultPlace.createNavigationEvent(JsoStringMap.<String>create()));
}
return;
}
super.dispatchHistory(historyPieces);
}
/**
* Same as {@link Place#registerChildHandler(Place, PlaceNavigationHandler)}, except this takes an
* additional parameter to specify whether or not we should treat this child {@link Place} as a
* default fallback for bogus navigations.
*/
public <E extends PlaceNavigationEvent<C>, N extends PlaceNavigationHandler<E>,
C extends Place> void registerChildHandler(C childPlace, N handler, boolean isDefault) {
if (isDefault) {
this.defaultPlace = childPlace;
}
super.registerChildHandler(childPlace, handler);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/history/Place.java | client/src/main/java/com/google/collide/client/history/Place.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.client.history;
import javax.annotation.Nonnull;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.logging.Log;
import com.google.collide.clientlibs.navigation.NavigationToken;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
import com.google.common.base.Preconditions;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.SimpleEventBus;
/**
* A tier in Hierarchical History.
*
* We use Places to control application level navigations. Each time you
* navigate to a Place, a history token is created.
*
* Note to self. Holy crazy generics batman!
*/
public abstract class Place {
private class Scope {
private PlaceNavigationEvent<?> currentChildPlaceNavigation = null;
private final SimpleEventBus eventBus = new SimpleEventBus();
private final JsoStringMap<
JsoArray<PlaceNavigationHandler<PlaceNavigationEvent<Place>>>> handlers =
JsoStringMap.create();
private final JsoStringMap<Place> knownChildPlaces = JsoStringMap.create();
}
/**
* Used to iterate over the state key/value map present in a child
* {@link PlaceNavigationEvent} to ensure that everything lines up with the
* specified history token.
*/
private static class StateMatcher implements IterationCallback<String> {
JsonStringMap<String> historyState;
boolean matches;
StateMatcher(JsonStringMap<String> historyState) {
this.matches = true;
this.historyState = historyState;
}
@Override
public void onIteration(String key, String value) {
matches = matches && (historyState.get(key) != null) && historyState.get(key).equals(value);
}
}
/**
* If we detect more than 20 {@link Place}s when walking the active set, then
* we can assume we have a cycle somewhere. This acts as a bound.
*/
private static final int PLACE_LIMIT = 20;
private static void cleanupChild(Place parent, Place child) {
JsoArray<PlaceNavigationHandler<PlaceNavigationEvent<Place>>> handlers =
parent.scope.handlers.get(child.getName().toLowerCase());
assert (handlers != null && handlers.size() > 0) : "Child handle disappeared from parent.";
for (int j = 0, n = handlers.size(); j < n; j++) {
PlaceNavigationHandler<PlaceNavigationEvent<Place>> handler = handlers.get(j);
handler.cleanup();
}
child.setIsActive(false, null);
}
private boolean createHistoryToken = true;
private Place currentParentPlace;
private boolean isActive = false;
private boolean isStrict = true;
private final String name;
private Scope scope = new Scope();
protected Place(String placeName) {
this.name = placeName;
}
/**
* @return The Place that is the parent of this Place (earlier on the active
* Place stack). Will return {@code null} if this Place is not active.
*/
public Place getParentPlace() {
return currentParentPlace;
}
/**
* @return The current {@link PlaceNavigationEvent} that is the direct child
* of this Place.
*/
public PlaceNavigationEvent<?> getCurrentChildPlaceNavigation() {
return scope.currentChildPlaceNavigation;
}
/**
* Walks the active {@link Place}s and returns a snapshot of the current state
* of the application, which can be used to create an entry in History.
*/
public JsoArray<PlaceNavigationEvent<?>> collectHistorySnapshot() {
return collectActiveChildPlaceNavigationEvents();
}
JsoArray<PlaceNavigationEvent<?>> collectActiveChildPlaceNavigationEvents() {
JsoArray<PlaceNavigationEvent<?>> snapshot = JsoArray.create();
PlaceNavigationEvent<?> child = getCurrentChildPlaceNavigation();
int placeCount = 0;
while (child != null) {
// Detect a cycle and shiny.
if (placeCount > PLACE_LIMIT) {
Log.error(getClass(), "We probably have a cycle in our Place chain!");
throw new RuntimeException("Cycle detected in Place chain!");
}
if (child.getPlace().isActive()) {
snapshot.add(child);
placeCount++;
}
child = child.getPlace().getCurrentChildPlaceNavigation();
}
return snapshot;
}
public PlaceNavigationEvent<? extends Place> createNavigationEvent() {
return createNavigationEvent(JsoStringMap.<String>create());
}
/**
* Should create the associated {@link PlaceNavigationEvent} for the concrete
* Place implementation. We pass along key/value pairs that were decoded from
* the History Token, if there were any. This will be an empty, non-null map
* if there were no such key/values passed in.
*
* Implementors are responsible for interpreting the <String,String> map and
* initializing the {@link PlaceNavigationEvent} appropriately.
*
* @param decodedState key/value pairs encoded in the {@link HistoryPiece}
* associated with this Place.
* @return the {@link PlaceNavigationEvent} associated with this Place
*/
public abstract PlaceNavigationEvent<? extends Place> createNavigationEvent(
JsonStringMap<String> decodedState);
/**
* This creates a child {@link PlaceNavigationEvent}s based on a
* {@link HistoryPiece}.
*
* If there is no such child Place registered to us, then we return {@code
* null}.
*
* @return the {@link PlaceNavigationEvent} for the child Place that is keyed
* by the name present in the inputed {@link HistoryPiece}, or {@code
* null} if there is no such child Place directly reachable from this
* Place.
*/
private PlaceNavigationEvent<?> decodeChildNavigationEvent(NavigationToken childHistoryPiece) {
Place childPlace = getRegisteredChild(childHistoryPiece.getPlaceName());
if (childPlace == null) {
Log.warn(getClass(),
"Attempting to decode a Child navigation event for a Place that was not registered to"
+ " us.",
"Parent: ",
getName(),
" Potential Child: ",
childHistoryPiece.getPlaceName(),
" State: ",childHistoryPiece.getBookmarkableState());
return null;
}
return childPlace.createNavigationEvent(childHistoryPiece.getBookmarkableState());
}
/**
* Dispatch cleanup to current place and all its subchildren
*
* @param includeCurrentChildPlace whether to clean up everything or just the
* subplaces
*/
private void dispatchCleanup(boolean includeCurrentChildPlace) {
if (getCurrentChildPlaceNavigation() != null) {
JsoArray<PlaceNavigationEvent<?>> activeChildren = collectActiveChildPlaceNavigationEvents();
// Decide if want to cleanup everything, or only subplaces
int cleanLimit = includeCurrentChildPlace ? 0 : 1;
// Walk the active subtree going bottom up, firing their cleanup handlers,
// and letting them know they are inactive.
for (int i = activeChildren.size() - 1; i >= cleanLimit; i--) {
Place childPlace = activeChildren.get(i).getPlace();
Place place = (i > 0) ? activeChildren.get(i - 1).getPlace() : this;
cleanupChild(place, childPlace);
}
}
}
/**
* Takes in an array of {@link HistoryPiece}s representing Place navigations
* rooted at this Place, and dispatches them in order.
*
* This method is intelligent, in that it will not re-dispatch Place
* navigations that are already active. The last piece of the incoming history
* pieces is always dispatched though.
*
* This method will walk the common links until it encounters one of the
* following scenarios:
*
* 1. Our current active Place chain ran out, and we have 1 or more pieces of
* history to turn into events and dispatch.
*
* 2. The history pieces are shorter than active Place chain (like when you
* click back), in which case we simple dispatch the last item in the history
* pieces, on the appropriate parent Place's scope.
*
* NOTE: If you call this method without first calling
* {@link #disableHistorySnapshotting()}, then each tier of the history
* dispatch will result in a history token. If you do disable snapshotting,
* please be nice and re-enable it when you are done by calling
* {@link #enableHistorySnapshotting()}.
*
*/
public void dispatchHistory(JsonArray<NavigationToken> historyPieces) {
// Terminate if there are no more pieces to dispatch.
if (historyPieces.isEmpty()) {
return;
}
NavigationToken piece = historyPieces.get(0);
PlaceNavigationEvent<?> child = getCurrentChildPlaceNavigation();
// The active Place chain ran out, go ahead and dispatch for real.
if (child == null || !isActive()) {
dispatchHistoryNow(historyPieces);
return;
}
// Compare child to see if it is the same.
if (historyPieceMatchesPlaceEvent(child, piece)) {
// We dispatch if this is the last history piece.
if (historyPieces.size() == 1) {
dispatchHistoryNow(historyPieces);
} else {
// Recurse downwards passing the remainder of the history array.
child.getPlace().dispatchHistory(historyPieces.slice(1, historyPieces.size()));
}
return;
}
// If we get here, then we know that we have reached the end of the common
// overlap with the active Places and the history pieces.
dispatchHistoryNow(historyPieces);
}
void dispatchHistoryNow(JsonArray<NavigationToken> historyPieces) {
// Terminate if there are no more pieces to dispatch.
if (historyPieces.isEmpty()) {
return;
}
PlaceNavigationEvent<?> childNavEvent = decodeChildNavigationEvent(historyPieces.get(0));
if (childNavEvent == null) {
Log.warn(getClass(), "Attempted to dispatch a line of history rooted at: ", getName(),
" but we had no such children.", historyPieces);
return;
}
// Navigate to the child. This should invoke the PlaceNavigationHandler and
// register any subsequent child Places.
fireChildPlaceNavigation(childNavEvent);
// Recurse downwards passing the remainder of the history array.
childNavEvent.getPlace().dispatchHistoryNow(historyPieces.slice(1, historyPieces.size()));
}
public void disableHistorySnapshotting() {
this.createHistoryToken = false;
}
public void enableHistorySnapshotting() {
this.createHistoryToken = true;
}
/**
* Dispatches a navigation event to the scope of this Place.
*/
public void fireChildPlaceNavigation(@Nonnull PlaceNavigationEvent<? extends Place> event) {
@SuppressWarnings("unchecked")
PlaceNavigationEvent<Place> navigationEvent = (PlaceNavigationEvent<Place>) event;
Log.info(getClass(), "Firing nav event "+event);
// Make sure that we contain such a child registered to our scope.
if (navigationEvent == null
|| getRegisteredChild(navigationEvent.getPlace().getName()) == null) {
Log.warn(getClass(), "Attempted to navigate to a child place that was not registered to us.",
navigationEvent, navigationEvent.getBookmarkableState());
return;
}
// If we are not currently active, then we are not allowed to fire child
// place navigations.
if (!isActive && isStrict()) {
Log.warn(getClass(), "Attempted to navigate to a child place when we were not active",
navigationEvent, RootPlace.PLACE.collectHistorySnapshot().join(PathUtil.SEP));
return;
}
// Whether or not the Place we are navigating to is the same type as the
// Place we are currently in.
boolean isReEntrantDispatch = false;
// Inform the previous active child (and all active sub Places in that
// chain) that he is no longer active.
if (scope.currentChildPlaceNavigation != null
&& scope.currentChildPlaceNavigation.getPlace().isActive()) {
isReEntrantDispatch =
scope.currentChildPlaceNavigation.getPlace() == navigationEvent.getPlace();
// Cleanup the old Place stack rooted at our current child place. If this
// is a re-entrant dispatch, then we want to skip cleaning up ourselves.
dispatchCleanup(!isReEntrantDispatch);
}
// Only reset the scope if we are navigating to a totally new Place.
if (!isReEntrantDispatch) {
// This ensures that when the child handler runs, it gets a clean scope
// and therefore can't leak references to handler code.
navigationEvent.getPlace().resetScope();
}
JsoArray<PlaceNavigationHandler<PlaceNavigationEvent<Place>>> handlers =
scope.handlers.get(navigationEvent.getPlace().getName().toLowerCase());
if (handlers == null || handlers.isEmpty()) {
Log.warn(getClass(), "Firing navigation event with no registered handlers", navigationEvent);
}
for (int i = 0, n = handlers.size(); i < n; i++) {
PlaceNavigationHandler<PlaceNavigationEvent<Place>> handler = handlers.get(i);
if (isReEntrantDispatch) {
handler.reEnterPlace(
navigationEvent, !placesMatch(scope.currentChildPlaceNavigation, navigationEvent));
} else {
handler.enterPlace(navigationEvent);
}
}
// Tell the new one that he is active AFTER invoking place navigation
// handlers.
navigationEvent.getPlace().setIsActive(true, this);
scope.currentChildPlaceNavigation = navigationEvent;
// This should default to true. It gets set to false if we are replaying a
// line of history, in which case it really doesn't make sense to snapshot
// each tier of the replay.
if (createHistoryToken) {
// Snapshot the active history by asking the RootPlace for all active
// Places.
JsoArray<PlaceNavigationEvent<?>> historySnapshot = RootPlace.PLACE.collectHistorySnapshot();
// Set the History string now.
HistoryUtils.createHistoryEntry(historySnapshot);
}
}
/**
* Dispatches a sequence of navigation events to the scope of this Place.
*
* The navigationEvents must be non-null.
*
* NOTE: If you call this method without first calling
* {@link #disableHistorySnapshotting()}, then each tier of the history
* dispatch will result in a history token. If you do disable snapshotting,
* please be nice and re-enable it when you are done by calling
* {@link #enableHistorySnapshotting()}.
*/
public void fireChildPlaceNavigations(JsoArray<PlaceNavigationEvent<?>> navigationEvents) {
// Terminate if there are no more pieces to dispatch.
if (navigationEvents.isEmpty()) {
return;
}
Place place = this;
for (int i = 0, n = navigationEvents.size(); i < n; i++) {
PlaceNavigationEvent<?> childNavEvent = navigationEvents.get(i);
// Navigate to the child. This should invoke the PlaceNavigationHandler
// and register any subsequent child Places.
place.fireChildPlaceNavigation(childNavEvent);
place = childNavEvent.getPlace();
}
}
/**
* Dispatches an event on our Place's Scope and all currently active child
* Places.
*/
public void fireEvent(GwtEvent<?> event) {
Place currPlace = this;
while (currPlace != null && currPlace.isActive()) {
fireEventInScope(currPlace, event);
PlaceNavigationEvent<?> activeChildNavigation = currPlace.getCurrentChildPlaceNavigation();
currPlace = (activeChildNavigation == null) ? null : activeChildNavigation.getPlace();
}
}
/**
* Dispatches an event on the specified Place's Scope {@link SimpleEventBus}.
*/
private void fireEventInScope(Place place, GwtEvent<?> event) {
// If we are not currently active, then we are not allowed to fire anything.
if (!isActive) {
Log.warn(getClass(), "Attempted to fire a simple event when we were not active", event);
return;
}
place.scope.eventBus.fireEvent(event);
}
public String getName() {
return name;
}
protected Place getRegisteredChild(String childName) {
return scope.knownChildPlaces.get(childName.toLowerCase());
}
private boolean historyPieceMatchesPlaceEvent(
PlaceNavigationEvent<?> event, NavigationToken historyPiece) {
// First match the name. We use toLowerCase() to make it resilient to users
// typing in URLs and mixing up cases.
final boolean namesMatch =
event.getPlace().getName().toLowerCase().equals(historyPiece.getPlaceName().toLowerCase());
// We also want to make sure the state that was passed in the parsed history
// match our live state.
StateMatcher matcher = new StateMatcher(historyPiece.getBookmarkableState());
// Now we match all state key/values.
JsonStringMap<String> state = event.getBookmarkableState();
state.iterate(matcher);
return namesMatch && matcher.matches;
}
/**
* Compare two Places (including parameters) to see if they match
*
* We say a place matches if all the state in the Place we are navigating to
* is already contained in the current Place.
*/
protected boolean placesMatch(PlaceNavigationEvent<?> current, PlaceNavigationEvent<?> next) {
if (current == null) {
return false;
}
StateMatcher matcher = new StateMatcher(current.getBookmarkableState());
JsonStringMap<String> state = next.getBookmarkableState();
state.iterate(matcher);
return matcher.matches;
}
public boolean isActive() {
return isActive;
}
public boolean isLeaf() {
PlaceNavigationEvent<?> activeChildPlaceNavigation = getCurrentChildPlaceNavigation();
return activeChildPlaceNavigation == null || !activeChildPlaceNavigation.getPlace().isActive();
}
/**
* @return true if this navigation event is active and is the leaf of the
* place chain.
*/
public boolean isActiveLeaf() {
return isLeaf() && isActive();
}
protected boolean isStrict() {
return isStrict;
}
/**
* Registers a {@link PlaceNavigationHandler} to deal with navigations to a
* particular child Place.
*
* <p>Subclasses are encouraged to restrict the types of children Places that
* can be registered in their public API. But this API is still visible and
* doesn't restrict the type of Place that can be added as a child.
*
* @param <C> subclass of {@link Place} that is the child place we are
* registering. <C> must a Place that is initialized by handler
* of appropriate type
*/
public <C extends Place> void registerChildHandler(
C childPlace, PlaceNavigationHandler<? extends PlaceNavigationEvent<C>> handler) {
String placeName = childPlace.getName().toLowerCase();
JsoArray<PlaceNavigationHandler<PlaceNavigationEvent<Place>>> placeHandlers =
scope.handlers.get(placeName);
if (placeHandlers == null) {
placeHandlers = JsoArray.create();
}
@SuppressWarnings("unchecked") // We promise this cast is okay...
PlaceNavigationHandler<PlaceNavigationEvent<Place>> placeNavigationHandler =
(PlaceNavigationHandler<PlaceNavigationEvent<Place>>) ((Object) handler);
placeHandlers.add(placeNavigationHandler);
scope.handlers.put(placeName, placeHandlers);
scope.knownChildPlaces.put(placeName, childPlace);
}
/**
* Registers an {@link EventHandler} on our Scope's {@link SimpleEventBus}.
* Dispatches on
*
* @param <T> the type of the {@link EventHandler}
*/
public <T extends EventHandler> void registerSimpleEventHandler(
GwtEvent.Type<T> eventType, T handler) {
scope.eventBus.addHandler(eventType, handler);
}
void resetScope() {
scope = new Scope();
}
/**
* Sets whether or not this Place is currently active. A Place is not allowed
* to dispatch to its scope if it is not active.
*
* Note that this method is protected and not private simply because the
* {@link RootPlace} needs to be able to set this.
*/
protected void setIsActive(boolean isActive, Place currentParentPlace) {
this.isActive = isActive;
this.currentParentPlace = currentParentPlace;
}
/**
* Determines whether or not the place should throw exceptions if it is not active.
* @param isStrict
* @return
*/
public void setIsStrict(boolean isStrict) {
this.isStrict = isStrict;
}
/**
* Leaves the current place, re-entering its parent
*/
public void leave() {
/*
* This precondition is somewhat arbitrary, as long as a place is active and
* not RootPlace then it should be fine to leave it. For now it's nice since
* it restricts the scope of this method.
*/
Preconditions.checkState(isActiveLeaf(), "Place must be the active leaf to be left");
/*
* TODO: This implementation means you can't leave an immediate
* child of the RootPlace, which seems okay for now. When we rewrite the
* place framework we'll make this more general.
*/
Place parent = getParentPlace();
Preconditions.checkNotNull(parent, "Parent cannot be null");
Place grandParent = parent.getParentPlace();
Preconditions.checkNotNull(grandParent, "Grandparent cannot be null");
grandParent.fireChildPlaceNavigation(parent.getCurrentChildPlaceNavigation());
}
@Override
public String toString() {
return "Place{name=" + name + ", isActive=" + isActive + "}";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/history/HistoryUtils.java | client/src/main/java/com/google/collide/client/history/HistoryUtils.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.client.history;
import com.google.collide.clientlibs.navigation.NavigationToken;
import com.google.collide.clientlibs.navigation.UrlSerializationController;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.common.annotations.VisibleForTesting;
import elemental.client.Browser;
import elemental.events.Event;
import elemental.events.EventListener;
/*
* TODO: The prefixing of paths with "/h/" is to allow us to use HTML5
* pushState(). We currently still use the hash fragment because our testing
* infrastructure doesn't work with FF4, or Chrome. Rage. But we are setup to
* easily switch to using it once the testing infrastructure gets with the
* times.
*/
/**
* Utility class for extracting String encodings of {@link Place}s from the
* history string, and for creating entries in History based on
* {@link PlaceNavigationEvent}s.
*
* Note that because we are using HTML5 pushState() and popState(), that we are
* not using a hash fragment to encode the history string. We use a simple URL
* scheme where the path of the URL is the History String.
*
* In order to not collide with some of the reserved URL mappings exposed by
* the Frontend, we prefix paths used as history with "/h/", since the FE treats
* "/h/*" URLs like a request for the root servlet.
*
*/
public class HistoryUtils {
/**
* Callback for entities that are interested when HistoryUtils API changes the
* URL.
*/
public interface SetHistoryListener {
void onHistorySet(String historyString);
}
/**
* This gets called back when the user navigates history via back/forward
* button presses. This does NOT get dispatched when we set the history token
* ourselves.
*/
public interface ValueChangeListener {
void onValueChanged(String historyString);
}
private static String lastSetHistoryString = "";
private static final JsoArray<SetHistoryListener> setHistoryListeners = JsoArray.create();
private static final JsoArray<ValueChangeListener> valueChangeListeners = JsoArray.create();
private static final UrlSerializationController urlSerializationController =
new UrlSerializationController();
// We want to trap changes to the hash fragment.
static {
Browser.getWindow().addEventListener("hashchange", new EventListener() {
@Override
public void handleEvent(Event evt) {
String currentHistoryString = getHistoryString();
// We dispatch only if the current history string is different from one
// that we set.
if (!lastSetHistoryString.equals(currentHistoryString)) {
for (int i = 0, n = valueChangeListeners.size(); i < n; i++) {
valueChangeListeners.get(i).onValueChanged(currentHistoryString);
}
}
lastSetHistoryString = currentHistoryString;
}
}, false);
}
/**
* Adds a listener that will be called whenever the URL changes. This gets
* called each time we set a history token. It will also be called immediately
* from this registration.
*/
public static void addSetHistoryListener(SetHistoryListener listener) {
setHistoryListeners.add(listener);
listener.onHistorySet(getHistoryString());
}
/**
* Adds a listener that will be called whenever the user presses back and
* forward. This will NOT get called when we set the history string.
*/
public static void addValueChangeListener(ValueChangeListener listener) {
valueChangeListeners.add(listener);
}
/**
* Takes in a snapshot of the active Places, and creates a History entry for
* it.
*/
public static void createHistoryEntry(JsoArray<? extends NavigationToken> historySnapshot) {
String historyString = createHistoryString(historySnapshot);
// This will update the URL without refreshing the browser.
setHistoryString(historyString);
// Now inform interested parties of the new URL.
for (int i = 0, n = setHistoryListeners.size(); i < n; i++) {
setHistoryListeners.get(i).onHistorySet(historyString);
}
}
public static String createHistoryString(JsonArray<? extends NavigationToken> historySnapshot) {
return urlSerializationController.serializeToUrl(historySnapshot);
}
/**
* @return the currently set, entire History String.
*/
public static String getHistoryString() {
// TODO: We're currently using hash when we refactor the place
// framework we will move to pushstate.
String hashFragment = Browser.getWindow().getLocation().getHash();
// Remove the hash/
if (hashFragment.length() > 0) {
hashFragment = hashFragment.substring(1);
}
return Browser.decodeURI(hashFragment);
}
/**
* See: {@link #parseHistoryString(String historyString)}.
*/
public static JsonArray<NavigationToken> parseHistoryString() {
return parseHistoryString(getHistoryString());
}
/**
* Parses the history string and returns an array of {@link HistoryPiece}s.
* These can be used to construct an array of {@link PlaceNavigationEvent}s
* that can be fired on the {@link RootPlace}.
*
* @param historyString the String corresponding to the entire History Token.
* @return the parsed history String as an array of history pieces, or an
* empty {@link JsoArray} if the History String is malformed or not
* present.
*/
public static JsonArray<NavigationToken> parseHistoryString(String historyString) {
return urlSerializationController.deserializeFromUrl(historyString);
}
@VisibleForTesting
static void setHistoryString(String historyString) {
lastSetHistoryString = historyString;
// TODO: When we move to FF4, we can use the pushState() API.
// Until then, we are stuck with the hash fragment.
// history.pushState(null, null, historyString);
Browser.getWindow().getLocation().setHash(Browser.encodeURI(historyString));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/history/PlaceConstants.java | client/src/main/java/com/google/collide/client/history/PlaceConstants.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.client.history;
/**
* Constants used in the places package.
*/
public class PlaceConstants {
public static final String LANDING_PAGE_PLACE_NAME = "landing";
public static final String WORKSPACE_PLACE_NAME = "ws";
public static final String CODE_PERSPECTIVE_PLACE_NAME = "code";
public static final String FILE_SELECTED_PLACE_NAME = "file";
public static final String TREE_CONFLICT_PLACE_NAME = "conflict";
public static final String REVIEW_PERSPECTIVE_PLACE_NAME = "review";
public static final String DIFF_PLACE_NAME = "diff";
public static final String WORKSPACE_SEARCH_PLACE_NAME = "search";
public static final String FILEHISTORY_PLACE_NAME = "history";
public static final String DEBUG_PLACE_NAME = "debug";
public static final String HOME_PLACE_NAME = "home";
public static final String GWT_PLACE_NAME = "gwt";
public static final String XAPI_PLACE_NAME = "xapi";
public static final String INSPECTOR_PLACE_NAME = "open";
public static final String TERMINAL_PLACE_NAME = "sh";
public static final String ANT_PLACE_NAME = "ant";
public static final String MAVEN_PLACE_NAME = "mvn";
// public static final String STANDALONE_PLACE_NAME = "util";
private PlaceConstants() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/history/PlaceNavigationHandler.java | client/src/main/java/com/google/collide/client/history/PlaceNavigationHandler.java | package com.google.collide.client.history;
import com.google.gwt.event.shared.EventHandler;
/**
* Handles navigating to a {@link Place}.
*
* Child {@link Place}s should be wired up when this handler is invoked.
*/
public abstract class PlaceNavigationHandler<E extends PlaceNavigationEvent<?>>
implements EventHandler {
/**
* Invoked when we navigate away from a particular Place. Logically equivalent
* to popping a Place off the Place stack.
*
* Subclasses should implement cleanup if any state leaks outside of the
* {@link Place}'s scope.
*/
protected void cleanup() {
// Empty default implementation.
}
/**
* Invoked when we navigate to a particular place that ALREADY IS ACTIVE on
* the Place stack. For example, if the current Place stack is "A/B/C" and we
* dispatch "B" on Place "A" then this method will be called. It is subtly
* different from {@link #enterPlace(PlaceNavigationEvent)} in that we have an
* opportunity to skip heavy weight setup code here that was run when
* {@link #enterPlace(PlaceNavigationEvent)} first navigated us to this place.
*
* <p>Note that the associated Place's scope is NOT RESET before invoking
* reEnterPlace by the Place framework.
*
* <p>reEnterPlace can be called any number of times and is NOT matched by calls
* to {@link #cleanup()} in the framework.
*
* <p>The Default implementation simply simulates a regular non-re-entrant
* dispatch. That is, a cleanup/enter pair with a call to reset the scope in
* between them. Concrete implementations have the opportunity to override
* this if they choose to short circuit expensive work done in
* {@link #enterPlace(PlaceNavigationEvent)}.
*
* @param navigationEvent the PlaceNavigationEvent associated with the
* navigation to the new {@link Place}.
* @param hasNewState whether or not the navigationEvent has new bookmarkable
* state.
*/
protected void reEnterPlace(E navigationEvent, boolean hasNewState) {
cleanup();
navigationEvent.getPlace().resetScope();
enterPlace(navigationEvent);
}
/**
* Invoked when we navigate to a particular place. Logically equivalent to
* pushing onto the Place stack. Code that runs within this method receives a
* {@link PlaceNavigationEvent} whose associated {@link Place} has a clean
* scope.
*
* All calls to enterPlace are matched by a call to {@link #cleanup()} before
* subsequent invocations if enterPlace.
*
* @param navigationEvent the PlaceNavigationEvent associated with the
* navigation to the new {@link Place}.
*/
protected abstract void enterPlace(E navigationEvent);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/history/PlaceNavigationEvent.java | client/src/main/java/com/google/collide/client/history/PlaceNavigationEvent.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.client.history;
import com.google.collide.clientlibs.navigation.NavigationToken;
/**
* Event fired to signal a transition to a particular {@link Place}.
*
* These events are cheap to instantiate, and should be used as vehicles for
* delivering any state needed by the {@link PlaceNavigationHandler} to perform
* the transition.
*/
public abstract class PlaceNavigationEvent<P extends Place> implements NavigationToken {
private final P associatedPlace;
protected PlaceNavigationEvent(P associatedPlace) {
this.associatedPlace = associatedPlace;
}
public P getPlace() {
return associatedPlace;
}
/**
* @return true if this navigation event is active and is the leaf of the
* place chain.
*/
public boolean isActiveLeaf() {
return getPlace().isActiveLeaf();
}
@Override
public String getPlaceName() {
return associatedPlace.getName();
}
@Override
public String toString() {
return "PlaceNavigationEvent{" + "associatedPlace=" + associatedPlace.toString() + ", isLeaf="
+ getPlace().isLeaf() + "}";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/diff/EditorDiffContainer.java | client/src/main/java/com/google/collide/client/diff/EditorDiffContainer.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.client.diff;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.FileContent;
import com.google.collide.client.editor.Buffer;
import com.google.collide.client.editor.Buffer.ScrollListener;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.DiffChunkResponse;
import com.google.collide.dto.Revision;
import com.google.collide.dto.client.DtoClientImpls.RevisionImpl;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.collide.shared.document.Document;
import com.google.common.base.Preconditions;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
import elemental.html.DivElement;
/**
* Container for the diff editor which contains an editor for the before
* document (on the left) and the after document (on the right).
*
* TODO: In the future, we will support diffing across workspaces.
* When we do so, we need to revisit this class and consider making its
* terminology more general than "before" and "after".
*
*/
public class EditorDiffContainer extends UiComponent<EditorDiffContainer.View>
implements FileContent {
/**
* Static factory method for obtaining an instance of the EditorDiffContainer.
*/
public static EditorDiffContainer create(AppContext appContext) {
EditorDiffBundle editorBefore = new EditorDiffBundle(appContext);
editorBefore.getEditor().setReadOnly(true);
EditorDiffBundle editorAfter = new EditorDiffBundle(appContext);
editorAfter.getEditor().setReadOnly(true);
View view =
new View(editorBefore.getEditor(), editorAfter.getEditor(), appContext.getResources());
return new EditorDiffContainer(view, appContext, editorBefore, editorAfter);
}
public interface Css extends CssResource {
String root();
String diffColumn();
String editorLeftContainer();
String editorRightContainer();
}
public interface Resources extends DiffRenderer.Resources {
@Source("EditorDiffContainer.css")
Css editorDiffContainerCss();
}
/**
* The view for the container for two editors.
*/
public static class View extends CompositeView<Void> {
DivElement editorLeftContainer;
DivElement editorRightContainer;
DivElement diffLeft;
DivElement diffRight;
DivElement root;
public View(final Editor editorLeft, final Editor editorRight,
EditorDiffContainer.Resources resources) {
Css css = resources.editorDiffContainerCss();
editorLeftContainer = Elements.createDivElement(css.editorLeftContainer());
editorLeftContainer.appendChild(editorLeft.getElement());
diffLeft = Elements.createDivElement(css.diffColumn());
diffLeft.appendChild(editorLeftContainer);
editorRightContainer = Elements.createDivElement(css.editorRightContainer());
editorRightContainer.appendChild(editorRight.getElement());
diffRight = Elements.createDivElement(css.diffColumn());
diffRight.appendChild(editorRightContainer);
root = Elements.createDivElement(css.root());
root.appendChild(diffLeft);
root.appendChild(diffRight);
setElement(root);
}
}
private final EditorDiffBundle editorBefore;
private final EditorDiffBundle editorAfter;
private final AppContext appContext;
private PathUtil path;
public static final Revision UNKNOWN_REVISION = RevisionImpl.make().setRootId("").setNodeId("");
private Revision revisionBefore = UNKNOWN_REVISION;
private Revision revisionAfter = UNKNOWN_REVISION;
private Revision expectedRevisionBefore = UNKNOWN_REVISION;
private Revision expectedRevisionAfter = UNKNOWN_REVISION;
private EditorDiffContainer(View view, AppContext appContext, final EditorDiffBundle editorBefore,
final EditorDiffBundle editorAfter) {
super(view);
this.appContext = appContext;
this.editorBefore = editorBefore;
this.editorAfter = editorAfter;
this.editorBefore.getEditor().getBuffer().setVerticalScrollbarVisibility(false);
editorBefore.getEditor().getBuffer().getScrollListenerRegistrar().add(new ScrollListener() {
@Override
public void onScroll(Buffer buffer, int scrollTop) {
editorAfter.getEditor().getBuffer().setScrollTop(scrollTop);
}
});
editorAfter.getEditor().getBuffer().getScrollListenerRegistrar().add(new ScrollListener() {
@Override
public void onScroll(Buffer buffer, int scrollTop) {
editorBefore.getEditor().getBuffer().setScrollTop(scrollTop);
}
});
}
private static boolean isSameRevision(Revision revision, Revision expectedRevision) {
return revision.getRootId().equals(expectedRevision.getRootId())
&& revision.getNodeId().equals(expectedRevision.getNodeId());
}
private boolean areRevisionsExpected(Revision revisionBefore, Revision revisionAfter) {
return isSameRevision(revisionBefore, expectedRevisionBefore)
&& isSameRevision(revisionAfter, expectedRevisionAfter);
}
@Override
public PathUtil filePath() {
return path;
}
public void setExpectedRevisions(Revision revisionBefore, Revision revisionAfter) {
expectedRevisionBefore = Preconditions.checkNotNull(revisionBefore);
expectedRevisionAfter = Preconditions.checkNotNull(revisionAfter);
}
public boolean hasRevisions(Revision revisionBefore, Revision revisionAfter) {
Preconditions.checkNotNull(revisionBefore);
Preconditions.checkNotNull(revisionAfter);
if (this.revisionBefore == UNKNOWN_REVISION || this.revisionAfter == UNKNOWN_REVISION) {
return false;
}
return isSameRevision(revisionBefore, this.revisionBefore)
&& isSameRevision(revisionAfter, this.revisionAfter);
}
/**
* Replace the before and after documents with the new documents formed by the
* given diffChunks.
*
* TODO: Handle line numbers properly.
*
* TODO: Make the before editor read-only.
*
* TODO: collaboration. Because we don't currently have an origin ID,
* the diff editors will not be set up for collaboration, but this will only
* be meaningful once we do diff merging, so we will implement it then.
*/
public void setDiffChunks(PathUtil path, JsonArray<DiffChunkResponse> diffChunks,
Revision revisionBefore, Revision revisionAfter) {
if (!areRevisionsExpected(
Preconditions.checkNotNull(revisionBefore), Preconditions.checkNotNull(revisionAfter))) {
return;
}
this.revisionBefore = revisionBefore;
this.revisionAfter = revisionAfter;
this.path = path;
Document beforeDoc = Document.createEmpty();
Document afterDoc = Document.createEmpty();
DiffRenderer beforeRenderer = new DiffRenderer(beforeDoc, appContext.getResources(), true);
DiffRenderer afterRenderer = new DiffRenderer(afterDoc, appContext.getResources(), false);
for (int i = 0, n = diffChunks.size(); i < n; i++) {
DiffChunkResponse diffChunk = diffChunks.get(i);
String beforeText = diffChunk.getBeforeData();
String afterText = diffChunk.getAfterData();
beforeRenderer.addDiffChunk(diffChunk.getDiffType(), beforeText);
afterRenderer.addDiffChunk(diffChunk.getDiffType(), afterText);
}
// TODO: This setup is a bit awkward so that we can defer setting
// the editor's document in order to workaround some editor bugs. Clean this
// up once those bugs are resolved.
editorBefore.setDocument(beforeDoc, path, beforeRenderer);
editorAfter.setDocument(afterDoc, path, afterRenderer);
}
public int getScrollTop() {
return editorBefore.getEditor().getBuffer().getScrollTop();
}
public void setScrollTop(int scrollTop) {
editorBefore.getEditor().getBuffer().setScrollTop(scrollTop);
editorAfter.getEditor().getBuffer().setScrollTop(scrollTop);
}
public void clearDiffEditors() {
// TODO: update when setDocument(null) works
editorBefore.getEditor().setDocument(Document.createEmpty());
editorAfter.getEditor().setDocument(Document.createEmpty());
revisionAfter = UNKNOWN_REVISION;
revisionBefore = UNKNOWN_REVISION;
}
public PathUtil getPath() {
return path;
}
@Override
public Element getContentElement() {
return getView().getElement();
}
@Override
public void onContentDisplayed() {
}
@Override
public void onContentDestroyed() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/diff/DeltaInfoBar.java | client/src/main/java/com/google/collide/client/diff/DeltaInfoBar.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.client.diff;
import collide.client.util.Elements;
import com.google.collide.client.ui.menu.PositionController.HorizontalAlign;
import com.google.collide.client.ui.menu.PositionController.VerticalAlign;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.dto.DiffStatsDto;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
import elemental.html.DivElement;
/**
* Presenter for the graphical delta statistics of a change. This presenter
* shows a set of bars that depict the change in percentage of
* added/deleted/changed/unmodified lines.
*
*/
public class DeltaInfoBar extends UiComponent<DeltaInfoBar.View> {
/**
* Static factory method for obtaining an instance of the DeltaInfoBar.
*/
public static DeltaInfoBar create(Resources resources, DiffStatsDto diffStats,
boolean includeTooltip) {
View view = new View(resources);
DeltaInfoBar deltaInfoBar = new DeltaInfoBar(resources, view, includeTooltip);
deltaInfoBar.setStats(diffStats);
return deltaInfoBar;
}
public interface Css extends CssResource {
String added();
String bar();
String count();
String inline();
String modified();
String deleted();
String unmodified();
}
public interface Resources extends Tooltip.Resources {
@Source("DeltaInfoBar.css")
Css deltaInfoBarCss();
}
public static class View extends CompositeView<Void> {
@VisibleForTesting
DivElement barsDiv;
private DivElement container;
private DivElement countDiv;
private final Resources res;
private final Css css;
private View(Resources res) {
this.res = res;
this.css = res.deltaInfoBarCss();
setElement(createDom());
}
/**
* Create several bars of the given style and append them to the element.
*/
private void createBars(Element element, int bars, String style) {
for (int i = 0; i < bars; i++) {
DivElement bar = Elements.createDivElement(css.bar());
bar.addClassName(style);
element.appendChild(bar);
}
}
private Element createDom() {
container = Elements.createDivElement(css.inline());
barsDiv = Elements.createDivElement(css.inline());
countDiv = Elements.createDivElement(css.inline(), css.count());
container.appendChild(barsDiv);
container.appendChild(countDiv);
return container;
}
}
@VisibleForTesting
static final int BAR_COUNT = 12;
/**
* The maximum number of affected lines to display. If the maximum number of
* affected lines exceeds this value, we display >##### instead of the full
* number. Used to improve formatting.
*/
private static final int MAX_AFFECTED = 10000;
/**
* For a given component, calculate the number of bars to display relative to
* the total. For a non-zero component, at least one bar will always be shown.
* Bar counts are always rounded down.
*/
@VisibleForTesting
static int calculateBars(int component, int total) {
if (total == 0) {
// Prevent divide-by-zero.
return 0;
}
double bars = (((double) component / (double) total) * BAR_COUNT);
// Force at least one bar if we have any of that type
if (component > 0 && bars < 1) {
bars = 1;
}
return (int) bars;
}
private final Css css;
private Tooltip tooltip;
private final boolean includeTooltip;
private DeltaInfoBar(Resources resources, View view, boolean includeTooltip) {
super(view);
css = resources.deltaInfoBarCss();
this.includeTooltip = includeTooltip;
}
/**
* Cleans up the tooltip used by this info bar.
*/
public void destroy() {
if (tooltip != null) {
tooltip.destroy();
tooltip = null;
}
}
/**
* Calculates and display the components for the given {@link DiffStatsDto}.
*/
public void setStats(DiffStatsDto diffStats) {
// Cleanup any old state.
destroy();
DivElement barsDiv = getView().barsDiv;
barsDiv.setInnerHTML("");
int total = getTotal(diffStats);
int addedBars = calculateBars(diffStats.getAdded(), total);
int deletedBars = calculateBars(diffStats.getDeleted(), total);
int modifiedBars = calculateBars(diffStats.getChanged(), total);
int unmodifiedBars = Math.max(0, BAR_COUNT - (addedBars + deletedBars + modifiedBars));
getView().createBars(barsDiv, addedBars, css.added());
getView().createBars(barsDiv, deletedBars, css.deleted());
getView().createBars(barsDiv, modifiedBars, css.modified());
getView().createBars(barsDiv, unmodifiedBars, css.unmodified());
int affected = getAffected(diffStats);
if (affected > MAX_AFFECTED) {
getView().countDiv.setTextContent(">" + String.valueOf(MAX_AFFECTED));
} else {
getView().countDiv.setTextContent(String.valueOf(affected));
}
// Create a tooltip for the bar.
if (includeTooltip) {
tooltip = Tooltip.create(getView().res, getView().container, VerticalAlign.MIDDLE,
HorizontalAlign.RIGHT, getDescription(diffStats));
}
}
/**
* Get the total number of lines affected by the change.
*/
private static int getAffected(DiffStatsDto diffStats) {
return diffStats.getAdded() + diffStats.getChanged() + diffStats.getDeleted();
}
/**
* Get the textual description of this line count suitable for the UI.
*/
private static String getDescription(DiffStatsDto diffStats) {
return "" + diffStats.getAdded() + " added, " + diffStats.getDeleted() + " deleted, "
+ diffStats.getChanged() + " changed (" + diffStats.getUnchanged() + " unchanged)";
}
/**
* Get the total count for each component of the change.
*/
private static int getTotal(DiffStatsDto diffStats) {
return getAffected(diffStats) + diffStats.getUnchanged();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/diff/EditorDiffBundle.java | client/src/main/java/com/google/collide/client/diff/EditorDiffBundle.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.client.diff;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.EditorBundle;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.syntaxhighlighter.SyntaxHighlighter;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.UserActivityManager;
import com.google.collide.codemirror2.CodeMirror2;
import com.google.collide.codemirror2.Parser;
import com.google.collide.shared.document.Document;
import com.google.common.base.Preconditions;
/**
* Like the {@link EditorBundle} this class groups together the various editor
* components.
*
*/
public class EditorDiffBundle {
private final Editor editor;
private DocumentParser parser;
private SyntaxHighlighter syntaxHighlighter;
private DiffRenderer diffRenderer;
private final UserActivityManager userActivityManager;
private final Editor.Css editorCss;
public EditorDiffBundle(AppContext appContext) {
this.editor = Editor.create(appContext);
this.userActivityManager = appContext.getUserActivityManager();
this.editorCss = appContext.getResources().workspaceEditorCss();
this.editor.setLeftGutterVisible(false);
this.editor.getBuffer().setColumnMarkerVisibility(false);
}
public DiffRenderer getDiffRenderer() {
return diffRenderer;
}
public Editor getEditor() {
return editor;
}
public SyntaxHighlighter getSyntaxHighlighter() {
return syntaxHighlighter;
}
/**
* Replaces the document for the editor and related components.
*/
public void setDocument(Document document, PathUtil path, DiffRenderer diffRenderer) {
this.diffRenderer = diffRenderer;
if (syntaxHighlighter != null) {
editor.removeLineRenderer(syntaxHighlighter.getRenderer());
syntaxHighlighter.teardown();
syntaxHighlighter = null;
parser.teardown();
parser = null;
}
Parser codeMirrorParser = CodeMirror2.getParser(path);
parser = DocumentParser.create(document, codeMirrorParser, userActivityManager);
Preconditions.checkNotNull(parser);
editor.setDocument(document);
editor.addLineRenderer(diffRenderer);
syntaxHighlighter =
SyntaxHighlighter.create(document, editor.getRenderer(), editor.getViewport(),
editor.getSelection(), parser, editorCss);
editor.addLineRenderer(syntaxHighlighter.getRenderer());
parser.begin();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/diff/DiffCommon.java | client/src/main/java/com/google/collide/client/diff/DiffCommon.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.client.diff;
import collide.client.common.CommonResources;
import collide.client.util.Elements;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.NodeConflictDto;
import com.google.collide.dto.NodeMutationDto;
import com.google.collide.dto.NodeMutationDto.MutationType;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import elemental.html.DivElement;
/**
* Common, static functionality shared by the various diff-related presenters.
*
*/
public class DiffCommon {
public interface Css extends CssResource {
String addedIcon();
String conflictIcon();
String deltaIcon();
String iconLabel();
String removedIcon();
String resolvedIcon();
String commonIcon();
}
public interface Resources extends CommonResources.BaseResources {
@Source("added.png")
ImageResource addedIcon();
@Source("delta.png")
ImageResource deltaIcon();
@Source("DiffCommon.css")
DiffCommon.Css diffCommonCss();
@Source("removed.png")
ImageResource removedIcon();
@Source("resolved.png")
ImageResource resolvedIcon();
}
/**
* Sets the appropriate icon based on the type of changed file.
*
* @param changedNode
*/
public static DivElement makeConflictIconDiv(Css css, NodeConflictDto changedNode) {
DivElement icon = Elements.createDivElement();
if (changedNode.getSimplifiedConflictType() !=
NodeConflictDto.SimplifiedConflictType.RESOLVED) {
icon.setClassName(css.conflictIcon());
} else {
icon.setClassName(css.resolvedIcon());
}
icon.addClassName(css.commonIcon());
return icon;
}
/**
* Sets the appropriate icon based on the type of changed file.
*/
public static DivElement makeModifiedIconDiv(Css css, NodeMutationDto changedNode) {
return makeModifiedIconDiv(css, changedNode.getMutationType());
}
/**
* Sets the appropriate icon based on the type of changed file.
*/
public static DivElement makeModifiedIconDiv(Css css, MutationType mutationType) {
DivElement icon = Elements.createDivElement();
switch (mutationType) {
case ADDED:
case COPIED:
case COPIED_AND_EDITED:
icon.setClassName(css.addedIcon());
break;
case DELETED:
icon.setClassName(css.removedIcon());
break;
case EDITED:
case MOVED:
case MOVED_AND_EDITED:
icon.setClassName(css.deltaIcon());
break;
default:
Log.error(DiffCommon.class, "Unknown modification type " + mutationType);
icon.setClassName(css.deltaIcon());
}
icon.addClassName(css.commonIcon());
return icon;
}
private DiffCommon() {
// Disallow instantiation.
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/diff/DiffRenderer.java | client/src/main/java/com/google/collide/client/diff/DiffRenderer.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.client.diff;
import com.google.collide.client.editor.renderer.PreviousAnchorRenderer;
import com.google.collide.dto.DiffChunkResponse;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
/**
* A @{link {@link PreviousAnchorRenderer} for diff chunks
*/
public class DiffRenderer extends PreviousAnchorRenderer {
private static final AnchorType DIFF_CHUNK_ANCHOR_TYPE =
AnchorType.create(DiffRenderer.class, "chunk");
private final String diffBlockStyle;
private final JsonStringMap<String> chunkStyles;
private boolean isBeforeFile;
public DiffRenderer(Document document, Resources resources, boolean isBeforeFile) {
super(document, DIFF_CHUNK_ANCHOR_TYPE, PreviousAnchorRenderer.ANCHOR_VALUE_IS_STYLE);
chunkStyles = JsonCollections.createMap();
Css css = resources.diffRendererCss();
chunkStyles.put(DiffChunkResponse.DiffType.ADDED_LINE.toString(), css.addedLine());
chunkStyles.put(DiffChunkResponse.DiffType.REMOVED_LINE.toString(), css.removedLine());
chunkStyles.put(DiffChunkResponse.DiffType.CHANGED_LINE.toString(), css.changedLine());
chunkStyles.put(DiffChunkResponse.DiffType.ADDED.toString(), css.added());
chunkStyles.put(DiffChunkResponse.DiffType.CHANGED.toString(), css.changed());
chunkStyles.put(DiffChunkResponse.DiffType.REMOVED.toString(), css.removed());
chunkStyles.put(DiffChunkResponse.DiffType.UNCHANGED.toString(), css.unchanged());
diffBlockStyle = css.diffBlock();
this.isBeforeFile = isBeforeFile;
}
public interface Css extends CssResource {
String addedLine();
String removedLine();
String changedLine();
String added();
String changed();
String removed();
String unchanged();
String diffBlock();
}
public interface Resources extends ClientBundle {
@Source("DiffRenderer.css")
Css diffRendererCss();
}
/**
* Append a diff chunk to the document.
*
* @param chunkType the type of the diff chunk
* @param chunkText the contents of the diff chunk
*/
void addDiffChunk(DiffChunkResponse.DiffType chunkType, String chunkText) {
if (!chunkText.isEmpty()) {
Line lastLine = document.getLastLine();
int lastColumn = lastLine.getText().length();
document.insertText(lastLine, document.getLastLineNumber(), lastColumn, chunkText);
Anchor anchor = document.getAnchorManager().createAnchor(
DIFF_CHUNK_ANCHOR_TYPE, lastLine, AnchorManager.IGNORE_LINE_NUMBER, lastColumn);
anchor.setValue(chunkStyles.get(chunkType.toString()));
// TODO Below is temp fix to ensure
// "Left should never have Green. Right should never have Red"
if (isBeforeFile) {
if (chunkType == DiffChunkResponse.DiffType.ADDED_LINE
|| chunkType == DiffChunkResponse.DiffType.ADDED) {
anchor.setValue(diffBlockStyle);
} else if (chunkType == DiffChunkResponse.DiffType.CHANGED) {
anchor.setValue(chunkStyles.get(DiffChunkResponse.DiffType.REMOVED.toString()));
} else if (chunkType == DiffChunkResponse.DiffType.CHANGED_LINE) {
anchor.setValue(chunkStyles.get(DiffChunkResponse.DiffType.REMOVED_LINE.toString()));
}
} else {
if (chunkType == DiffChunkResponse.DiffType.REMOVED
|| chunkType == DiffChunkResponse.DiffType.REMOVED_LINE) {
anchor.setValue(diffBlockStyle);
} else if (chunkType == DiffChunkResponse.DiffType.CHANGED) {
anchor.setValue(chunkStyles.get(DiffChunkResponse.DiffType.ADDED.toString()));
} else if (chunkType == DiffChunkResponse.DiffType.CHANGED_LINE) {
anchor.setValue(chunkStyles.get(DiffChunkResponse.DiffType.ADDED_LINE.toString()));
}
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/xhrmonitor/XhrWarden.java | client/src/main/java/com/google/collide/client/xhrmonitor/XhrWarden.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.client.xhrmonitor;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.core.client.JavaScriptObject;
import elemental.xml.XMLHttpRequest;
/**
* The warden watches XMLHttpRequests so we can monitor how many are going out
* and in and log it when it passes some threshold. The request kill feature
* should not be used in production as it could degrade the user experience.
*/
public class XhrWarden {
/**
* If more than {@code WARDEN_WARNING_THRESHOLD} xhr requests are opened the
* warden will trigger a warning to the warden listener.
*/
public static final int WARDEN_WARNING_THRESHOLD = 7;
/**
* If {@code WARDEN_REQUEST_LIMIT} xhr's are already opened the oldest one
* gets logged and is killed automatically.
*/
/*
* After switching to SPDY, we don't have a hard-limit on simultaneous XHRs so
* there's no need to kill. Leaving this in just in-case anyone needs to use it
* for debug purposes.
*/
public static final int WARDEN_REQUEST_LIMIT = Integer.MAX_VALUE;
/**
* The underlying singleton used by the warden implementation.
*/
private static WardenImpl wardenManager;
/**
* Initializes the warden.
*/
public static WardenRequestManager watch() {
if (wardenManager == null) {
wardenManager = new WardenImpl(WARDEN_WARNING_THRESHOLD, WARDEN_REQUEST_LIMIT);
createWarden(wardenManager);
}
return wardenManager;
}
/**
* Listener for warden events
*/
public interface WardenListener {
/**
* Called when the warning threshold of XHR requests is reached.
*/
public void onWarning(WardenRequestManager manager);
/**
* Called when the hard request limit is reached and the oldest XHR request has been killed.
*
* @param request The request that was killed.
*/
public void onEmergency(WardenRequestManager manager, WardenXhrRequest request);
}
/**
* Defines public facing methods of a warden request manager.
*/
public interface WardenRequestManager {
public int getRequestCount();
/**
* Dumps all requests to the console.
*/
void dumpRequestsToConsole();
/**
* Iterates over all open requests objects.
*/
public void iterate(IterationCallback<WardenXhrRequest> callback);
/**
* Adds a custom header to the list of headers to be added by the XhrWarden.
* This is meant for debugging purposes since this will get added to every
* XHR request made by the client.
*/
public void addCustomHeader(String header, String value);
}
interface WardenReadyStateHandler {
public void onRequestOpen(WardenXhrRequest request);
public void onRequestDone(WardenXhrRequest request);
public void onRequestOpening(WardenXhrRequest request);
public void doListRequests();
}
/**
* Receives javascript events from the warden and decides which XHR requests
* may need to die. Also deals with logging to counselor if things start going
* awry.
*/
static class WardenImpl implements WardenReadyStateHandler, WardenRequestManager {
private final JsonStringMap<WardenXhrRequest> openXhrRequests;
private final JsonStringMap<String> customHeaders;
private boolean alreadyLoggedError;
private final WardenListener eventListener;
private final int requestWarningLimit;
private final int requestErrorLimit;
/**
* The default event handler for warden events.
*/
private static class WardenEventHandler implements WardenListener {
@Override
public void onEmergency(WardenRequestManager manager, WardenXhrRequest request) {
String message =
"The Warden killed an xhr request due to capacity issues: " + request.getUrl();
Log.info(XhrWarden.class, message);
}
@Override
public void onWarning(WardenRequestManager manager) {
Log.info(XhrWarden.class, "Warden Warning -- Too Many Open Requests.");
manager.dumpRequestsToConsole();
}
}
public WardenImpl(int requestWarningLimit, int requestErrorLimit) {
this(requestWarningLimit, requestErrorLimit, new WardenEventHandler());
}
public WardenImpl(int requestWarningLimit, int requestErrorLimit, WardenListener listener) {
this.requestWarningLimit = requestWarningLimit;
this.requestErrorLimit = requestErrorLimit;
openXhrRequests = JsonCollections.createMap();
customHeaders = JsonCollections.createMap();
alreadyLoggedError = false;
eventListener = listener;
}
@Override
public int getRequestCount() {
return openXhrRequests.getKeys().size();
}
@Override
public void iterate(IterationCallback<WardenXhrRequest> callback) {
openXhrRequests.iterate(callback);
}
public WardenXhrRequest getLongestIdleRequest() {
WardenXhrRequest oldest = null;
for (int i = 0; i < openXhrRequests.getKeys().size(); i++) {
WardenXhrRequest wrapper = openXhrRequests.get(openXhrRequests.getKeys().get(i));
if (oldest == null || oldest.getTime() > wrapper.getTime()) {
oldest = wrapper;
}
}
return oldest;
}
@Override
public void dumpRequestsToConsole() {
final StringBuilder builder = new StringBuilder();
builder.append("\n -- ");
builder.append(getRequestCount());
builder.append(" Open XHR Request(s) --\n");
iterate(new IterationCallback<WardenXhrRequest>() {
@Override
public void onIteration(String key, WardenXhrRequest value) {
builder.append('(');
builder.append(key);
builder.append(") ");
builder.append(value.getUrl());
builder.append(" -- last activity on ");
builder.append(value.getDateString());
builder.append('\n');
}
});
Log.info(getClass(), builder.toString());
}
@Override
public void onRequestOpen(WardenXhrRequest request) {
if (openXhrRequests.get(request.getId()) != null) {
// strange state to be in
return;
}
openXhrRequests.put(request.getId(), request);
/*
* If we haven't notified the server of our state we will let them know
* now. In an effort to not flood ourselves we will only re-notify them
* once we go back below the warning threshold.
*/
if (getRequestCount() >= requestWarningLimit && !alreadyLoggedError) {
eventListener.onWarning(this);
alreadyLoggedError = true;
}
final XMLHttpRequest xhr = request.getRequest();
customHeaders.iterate(new IterationCallback<String>() {
@Override
public void onIteration(String header, String value) {
xhr.setRequestHeader(header, value);
}
});
}
@Override
public void onRequestOpening(WardenXhrRequest request) {
/*
* We are trying to open up a new xhr request but are at the limit we will
* kill the oldest inactive request so that we can make room
*/
if (openXhrRequests.get(request.getId()) == null && getRequestCount() >= requestErrorLimit) {
WardenXhrRequest oldest = getLongestIdleRequest();
oldest.kill();
openXhrRequests.remove(oldest.getId());
eventListener.onEmergency(this, oldest);
}
}
@Override
public void onRequestDone(WardenXhrRequest request) {
if (openXhrRequests.get(request.getId()) != null) {
openXhrRequests.remove(request.getId());
}
if (getRequestCount() < requestWarningLimit) {
alreadyLoggedError = false;
}
}
@Override
public void doListRequests() {
dumpRequestsToConsole();
}
@Override
public void addCustomHeader(String header, String value) {
customHeaders.put(header, value);
}
}
/**
* Models a warden HTTP request which effectively wraps a XMLHttpRequest
*/
public interface WardenXhrRequest {
/**
* Kills the request immediately.
*/
public void kill();
/**
* Retrieves the time of the last activity for this request.
*/
public double getTime();
/**
* Returns the date and time of this requests last activity as a String.
*/
public String getDateString();
/**
* Gets the id for this request that was assigned by the warden.
*/
public String getId();
/**
* Gets the URL this request tried to open.
*/
public String getUrl();
/**
* Retrieves the underlying XMLHttpRequest.
*/
public XMLHttpRequest getRequest();
}
/**
* Wraps a warden jso which is essentially an XMLHttpRequest plus a few
* special properties.
*
*/
static class WardenXhrRequestImpl extends JavaScriptObject implements WardenXhrRequest {
protected WardenXhrRequestImpl() {
}
public final native void kill() /*-{
this.abort();
}-*/;
public final native double getTime() /*-{
return this.wardenTime;
}-*/;
public final native String getDateString() /*-{
return new Date(this.wardenTime).toString();
}-*/;
public final native String getId() /*-{
return "" + this.wardenId;
}-*/;
public final native String getUrl() /*-{
// Devmode optimization (Browser Channel Weirdness)
if (typeof this.wardenUrl != "string") {
return "Browser Channel";
}
return this.wardenUrl;
}-*/;
@Override
public final native XMLHttpRequest getRequest() /*-{
return this;
}-*/;
}
static WardenRequestManager getInstance() {
return wardenManager;
}
static void setInstance(WardenImpl manager) {
wardenManager = manager;
}
/**
* If the warden is currently enabled, it will disable the warden; otherwise,
* this is a no-op.
*/
public static void stopWatching() {
wardenManager = null;
removeWarden();
}
/**
* Dumps a list of open requests to the console.
*/
public static void dumpRequestsToConsole() {
if (getInstance() != null) {
getInstance().dumpRequestsToConsole();
}
}
/**
* Creates the warden and substitutes it for the XMLHttpRequest object.
* Basically creates an XMLHttpRequest factory with an automatic event
* listener for onreadystatechange and an overridden open function. This
* proved one of the few fully working ways to override the native object.
*/
private static native void createWarden(WardenReadyStateHandler handler) /*-{
$wnd.XMLHttpRequest = (function(handler) {
var requestid = 0;
var xmlhttp = $wnd.xmlhttp = $wnd.XMLHttpRequest;
return function() {
var request = new xmlhttp();
request.wardenId = requestid++;
request.addEventListener("readystatechange", function() {
// On Open
if (this.readyState == 1) {
handler.
@com.google.collide.client.xhrmonitor.XhrWarden.WardenReadyStateHandler::onRequestOpen(Lcom/google/collide/client/xhrmonitor/XhrWarden$WardenXhrRequest;)
(this);
} else if (this.readyState == 3) {
// this indicates progress so a send or a receive
this.wardenTime = (new Date()).getTime();
} else if (this.readyState == 4) {
// indicates we ended due to failure or otherwise
handler.
@com.google.collide.client.xhrmonitor.XhrWarden.WardenReadyStateHandler::onRequestDone(Lcom/google/collide/client/xhrmonitor/XhrWarden$WardenXhrRequest;)
(this);
}
}, true);
// Override the xml http request open command
request.xhrOpen = request.open;
request.open = function(method, url) {
this.wardenUrl = url;
this.wardenTime = (new Date()).getTime();
handler.
@com.google.collide.client.xhrmonitor.XhrWarden.WardenReadyStateHandler::onRequestOpening(Lcom/google/collide/client/xhrmonitor/XhrWarden$WardenXhrRequest;)
(this);
this.xhrOpen.apply(this,arguments);
};
return request;
}
})(handler);
// Calls the warden to list any open xhr requests
$wnd.XMLHttpRequest.list = function() {
handler.
@com.google.collide.client.xhrmonitor.XhrWarden.WardenReadyStateHandler::doListRequests()();
};
if ($wnd.console && $wnd.console.info) {
$wnd.console.info("The warden is watching.");
}
}-*/;
private static native void removeWarden() /*-{
$wnd.XMLHttpRequest = $wnd.xmlhttp || $wnd.XMLHttpRequest;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/terminal/TerminalPlace.java | client/src/main/java/com/google/collide/client/terminal/TerminalPlace.java | package com.google.collide.client.terminal;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
public class TerminalPlace extends Place{
public class NavigationEvent extends PlaceNavigationEvent<TerminalPlace> {
public static final String QUERY_KEY = "q";
public static final String PAGE_KEY = "p";
private final String query;
private final int page;
private NavigationEvent(String query) {
super(TerminalPlace.this);
this.query = query;
this.page = 1;
}
private NavigationEvent(String query, int page) {
super(TerminalPlace.this);
this.query = query;
this.page = page;
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> map = JsoStringMap.create();
map.put(QUERY_KEY, query);
map.put(PAGE_KEY, Integer.toString(page));
return map;
}
public String getQuery() {
return query;
}
public int getPage() {
return page;
}
}
protected TerminalPlace(String placeName) {
super(placeName);
}
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(
JsonStringMap<String> decodedState) {
return null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/DocOpRecoveryInitiator.java | client/src/main/java/com/google/collide/client/collaboration/DocOpRecoveryInitiator.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.client.collaboration;
/**
* A class that can initiate doc op recovery.
*/
public interface DocOpRecoveryInitiator {
void recover();
void teardown();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/IncomingDocOpDemultiplexer.java | client/src/main/java/com/google/collide/client/collaboration/IncomingDocOpDemultiplexer.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.client.collaboration;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerToClientDocOp;
import com.google.collide.dto.client.DtoClientImpls.ServerToClientDocOpImpl;
import com.google.collide.dto.client.DtoClientImpls.ServerToClientDocOpsImpl;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
/**
* Receives {@link ServerToClientDocOp} from the {@link MessageFilter} and
* forwards them.
*/
public class IncomingDocOpDemultiplexer {
public static IncomingDocOpDemultiplexer create(MessageFilter messageFilter) {
IncomingDocOpDemultiplexer receiver = new IncomingDocOpDemultiplexer(messageFilter);
messageFilter.registerMessageRecipient(RoutingTypes.SERVERTOCLIENTDOCOP,
receiver.messageReceiver);
messageFilter.registerMessageRecipient(RoutingTypes.SERVERTOCLIENTDOCOPS,
receiver.bulkMessageReceiver);
return receiver;
}
public interface Receiver {
/*
* TODO: if a client wants to have in-order doc ops, we should
* really be passing each DocOpReceiver the list of BulkReceivers so it can
* callback the same time it would normally call into the OT stack (this
* ensures ordering and even recovered doc ops).
*/
/**
* Called when a doc op is received from the server. These may be
* out-of-order and during doc op recovery, this will NOT be called.
*/
void onDocOpReceived(ServerToClientDocOpImpl docOpDto, DocOp docOp);
}
private final MessageFilter.MessageRecipient<ServerToClientDocOpImpl> messageReceiver =
new MessageRecipient<ServerToClientDocOpImpl>() {
@Override
public void onMessageReceived(ServerToClientDocOpImpl message) {
handleServerToClientDocOpMsg(message);
}
};
private final MessageFilter.MessageRecipient<ServerToClientDocOpsImpl> bulkMessageReceiver =
new MessageRecipient<ServerToClientDocOpsImpl>() {
@Override
public void onMessageReceived(ServerToClientDocOpsImpl message) {
for (int i = 0, n = message.getDocOps().size(); i < n; i++) {
handleServerToClientDocOpMsg((ServerToClientDocOpImpl) message.getDocOps().get(i));
}
}
};
/** Map from file edit session key to receiver */
private final JsonStringMap<Receiver> receivers = JsonCollections.createMap();
private final JsonArray<Receiver> bulkReceivers = JsonCollections.createArray();
private final MessageFilter messageFilter;
private IncomingDocOpDemultiplexer(MessageFilter messageFilter) {
this.messageFilter = messageFilter;
}
public void teardown() {
messageFilter.removeMessageRecipient(RoutingTypes.SERVERTOCLIENTDOCOP);
}
/**
* Adds a {@link Receiver} that will receive all DocOp messages.
*/
public void addBulkReceiver(Receiver receiver) {
bulkReceivers.add(receiver);
}
public void removeBulkReceiver(Receiver receiver) {
bulkReceivers.remove(receiver);
}
public void setReceiver(String fileEditSessionKey, Receiver receiver) {
receivers.put(fileEditSessionKey, receiver);
}
public void handleServerToClientDocOpMsg(ServerToClientDocOpImpl message) {
// Early exit if nobody is listening.
Receiver receiver = receivers.get(message.getFileEditSessionKey());
if (receiver == null && bulkReceivers.size() == 0) {
return;
}
DocOp docOp = message.getDocOp2();
// Send to the registered receiver for the file edit session.
if (receiver != null) {
receiver.onDocOpReceived(message, docOp);
}
// Send to bulk receivers.
for (int i = 0; i < bulkReceivers.size(); i++) {
bulkReceivers.get(i).onDocOpReceived(message, docOp);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/DocOpSender.java | client/src/main/java/com/google/collide/client/collaboration/DocOpSender.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.client.collaboration;
import java.util.List;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.collaboration.FileConcurrencyController.DocOpListener;
import com.google.collide.client.collaboration.cc.GenericOperationChannel.SendOpService;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.ServerToClientDocOps;
import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl;
import com.google.collide.dto.client.DtoClientImpls.DocOpImpl;
import com.google.collide.dto.client.DtoClientImpls.ServerToClientDocOpImpl;
import com.google.collide.json.client.Jso;
import com.google.collide.json.client.JsoArray;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerManager.Dispatcher;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
/**
* Helper to take outgoing doc ops from the local concurrency control library
* and send them to the server.
*
*/
class DocOpSender implements SendOpService<DocOp>, LastClientToServerDocOpProvider {
private final ListenerManager<DocOpListener> docOpListenerManager;
private final int documentId;
private final String fileEditSessionKey;
private final FrontendApi frontendApi;
private final IncomingDocOpDemultiplexer docOpDemux;
private ClientToServerDocOpCreationParticipant clientToServerDocOpCreationParticipant;
private ClientToServerDocOpImpl lastClientToServerDocOpMsg;
private final DocOpRecoveryInitiator docOpRecoveryInitiator;
public DocOpSender(FrontendApi frontendApi,
IncomingDocOpDemultiplexer docOpDemux,
String fileEditSessionKey,
int documentId,
ListenerManager<DocOpListener> docOpListenerManager,
DocOpRecoveryInitiator docOpRecoveryInitiator) {
this.frontendApi = frontendApi;
this.docOpDemux = docOpDemux;
this.fileEditSessionKey = fileEditSessionKey;
this.documentId = documentId;
this.docOpListenerManager = docOpListenerManager;
this.docOpRecoveryInitiator = docOpRecoveryInitiator;
}
@Override
public void callbackNotNeeded(SendOpService.Callback callback) {
}
@Override
public void requestRevision(SendOpService.Callback callback) {
/*
* TODO: get revision from server, but for now this is never
* called since we are not handling connection errors fully
*/
assert false;
}
@Override
public void submitOperations(
int revision, final List<DocOp> operations, final SendOpService.Callback callback) {
try {
/*
* Copy the operations into the list.
* TODO: Consider making the client code maintain this list as a native collection.
*/
JsoArray<String> docOps = JsoArray.create();
for (int i = 0, n = operations.size(); i < n; i++) {
docOps.add(Jso.serialize((DocOpImpl) operations.get(i)));
}
ClientToServerDocOpImpl message = ClientToServerDocOpImpl
.make()
.setFileEditSessionKey(fileEditSessionKey)
.setCcRevision(revision)
.setClientId(BootstrapSession.getBootstrapSession().getActiveClientId())
.setDocOps2(docOps);
if (clientToServerDocOpCreationParticipant != null) {
clientToServerDocOpCreationParticipant.onCreateClientToServerDocOp(message);
}
frontendApi.MUTATE_FILE.send(message, new ApiCallback<ServerToClientDocOps>() {
@Override
public void onFail(FailureReason reason) {
if (reason == FailureReason.MISSING_WORKSPACE_SESSION) {
docOpRecoveryInitiator.teardown();
} else {
docOpRecoveryInitiator.recover();
}
}
@Override
public void onMessageReceived(ServerToClientDocOps message) {
for (int i = 0; i < message.getDocOps().size(); i++) {
docOpDemux.handleServerToClientDocOpMsg(
(ServerToClientDocOpImpl) message.getDocOps().get(i));
}
}
});
lastClientToServerDocOpMsg = message;
docOpListenerManager.dispatch(new Dispatcher<DocOpListener>() {
@Override
public void dispatch(DocOpListener listener) {
listener.onDocOpSent(documentId, operations);
}
});
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
/*
* Need to defer this since the client is not expecting a success
* reply from within the same call stack
*/
/*
* TODO: Need the applied revision. We can't easily get
* it since unlike HTTP, our push channel does not have a mechanism
* for an inline response (could create a separate response message,
* which is this TODO). We'll be okay for now without it because the
* cc lib uses it for recovery, but we never report failures so it
* doesn't have exercise the recovery logic right now. It also uses
* this for optimizations if the given applied revision matches what
* it expects, but since we give an unexpected value, it does nothing
* with it.
*/
callback.onSuccess(Integer.MIN_VALUE);
}
});
} catch (Throwable t) {
callback.onFatalError(t);
}
}
void setDocOpCreationParticipant(ClientToServerDocOpCreationParticipant participant) {
clientToServerDocOpCreationParticipant = participant;
}
@Override
public ClientToServerDocOpImpl getLastClientToServerDocOpMsg() {
return lastClientToServerDocOpMsg;
}
/**
* Clears the message that would be returned by
* {@link #getLastClientToServerDocOpMsg()}.
*
* @param clientToServerDocOpMsgToDelete if provided, the current message must
* match the given message for it to be cleared
*/
@Override
public void clearLastClientToServerDocOpMsg(
ClientToServerDocOpImpl clientToServerDocOpMsgToDelete) {
if (clientToServerDocOpMsgToDelete == null
|| clientToServerDocOpMsgToDelete == lastClientToServerDocOpMsg) {
lastClientToServerDocOpMsg = null;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/CollaborationManager.java | client/src/main/java/com/google/collide/client/collaboration/CollaborationManager.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.client.collaboration;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.ParticipantModel;
import com.google.collide.client.communication.PushChannel;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.document.DocumentManager.LifecycleListener;
import com.google.collide.client.document.DocumentMetadata;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.util.JsIntegerMap;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.FileContents;
import com.google.collide.json.client.Jso;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
/**
* A manager for real-time collaboration.
*
* This class listens for document lifecycle changes and creates or tears down individual
* {@link DocumentCollaborationController}s.
*/
public class CollaborationManager {
public static CollaborationManager create(AppContext appContext, DocumentManager documentManager,
ParticipantModel participantModel, IncomingDocOpDemultiplexer docOpRecipient) {
/*
* Ideally this whole stack wouldn't be stuck on passing around a workspace id but it is too
* much work right now to refactor it out so here it stays.
*/
return new CollaborationManager(appContext, documentManager,
participantModel, docOpRecipient);
}
private final LifecycleListener lifecycleListener = new LifecycleListener() {
@Override
public void onDocumentCreated(Document document) {}
@Override
public void onDocumentGarbageCollected(Document document) {}
@Override
public void onDocumentOpened(Document document, Editor editor) {
handleDocumentOpened(document, editor);
}
@Override
public void onDocumentClosed(Document document, Editor editor) {
handleDocumentClosed(document, editor);
}
@Override
public void onDocumentLinkedToFile(Document document, FileContents fileContents) {
JsonArray<DocumentSelection> selections = JsonCollections.createArray();
JsonArray<String> serializedSelections = fileContents.getSelections();
for (int i = 0, n = serializedSelections.size(); i < n; i++) {
selections.add((DocumentSelection) Jso.deserialize(serializedSelections.get(i)));
}
handleDocumentLinkedToFile(document, selections);
}
@Override
public void onDocumentUnlinkingFromFile(Document document) {
handleDocumentUnlinkingFromFile(document);
}
};
private final PushChannel.Listener pushChannelListener = new PushChannel.Listener() {
@Override
public void onReconnectedSuccessfully() {
docCollabControllersByDocumentId.iterate(
new JsonIntegerMap.IterationCallback<DocumentCollaborationController>() {
@Override
public void onIteration(
int documentId, DocumentCollaborationController collabController) {
collabController.handleTransportReconnectedSuccessfully();
}
});
}
};
private final AppContext appContext;
private final ParticipantModel participantModel;
private final RemoverManager removerManager = new RemoverManager();
private final JsIntegerMap<DocumentCollaborationController> docCollabControllersByDocumentId =
JsIntegerMap.create();
private final IncomingDocOpDemultiplexer docOpRecipient;
private CollaborationManager(AppContext appContext, DocumentManager documentManager,
ParticipantModel participantModel, IncomingDocOpDemultiplexer docOpRecipient) {
this.appContext = appContext;
this.participantModel = participantModel;
this.docOpRecipient = docOpRecipient;
removerManager.track(documentManager.getLifecycleListenerRegistrar().add(lifecycleListener));
removerManager.track(
appContext.getPushChannel().getListenerRegistrar().add(pushChannelListener));
}
public void cleanup() {
docOpRecipient.teardown();
removerManager.remove();
}
DocumentCollaborationController getDocumentCollaborationController(int documentId) {
return docCollabControllersByDocumentId.get(documentId);
}
private void handleDocumentLinkedToFile(
Document document, JsonArray<DocumentSelection> selections) {
DocumentCollaborationController docCollabController = new DocumentCollaborationController(
appContext, participantModel, docOpRecipient, document, selections);
docCollabController.initialize(DocumentMetadata.getFileEditSessionKey(document),
DocumentMetadata.getBeginCcRevision(document));
docCollabControllersByDocumentId.put(document.getId(), docCollabController);
}
private void handleDocumentUnlinkingFromFile(Document document) {
DocumentCollaborationController docCollabController =
docCollabControllersByDocumentId.remove(document.getId());
if (docCollabController != null) {
docCollabController.teardown();
}
}
private void handleDocumentOpened(Document document, Editor editor) {
DocumentCollaborationController docCollabController =
docCollabControllersByDocumentId.get(document.getId());
if (docCollabController != null) {
docCollabController.attachToEditor(editor);
}
}
private void handleDocumentClosed(Document document, Editor editor) {
DocumentCollaborationController docCollabController =
docCollabControllersByDocumentId.get(document.getId());
if (docCollabController != null) {
docCollabController.detachFromEditor();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/FileConcurrencyController.java | client/src/main/java/com/google/collide/client/collaboration/FileConcurrencyController.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.client.collaboration;
import java.util.List;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import com.google.collide.client.AppContext;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.collaboration.cc.GenericOperationChannel;
import com.google.collide.client.collaboration.cc.TransformQueue;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.ClientToServerDocOp;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.client.ClientDocOpFactory;
import com.google.collide.dto.client.DtoClientImpls.DocumentSelectionImpl;
import com.google.collide.dto.client.DtoClientImpls.FilePositionImpl;
import com.google.collide.shared.ot.OperationPair;
import com.google.collide.shared.ot.PositionTransformer;
import com.google.collide.shared.ot.Transformer;
import com.google.collide.shared.util.ErrorCallback;
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.Reorderer.TimeoutCallback;
/**
* Controller that handles the real-time collaboration and concurrency control
* for a file. An instance is per file, and is meant to be replaced by a new
* instance when switching files.
*
*/
class FileConcurrencyController {
private static final int OUT_OF_ORDER_DOC_OP_TIMEOUT_MS = 5000;
interface CollaboratorDocOpSink {
/**
* @param selection as described in
* {@link ClientToServerDocOp#getSelection()}, with the exception
* that this has been transformed with outstanding client ops so that
* it is ready to be applied to the local document
*/
void consume(DocOp docOp, String clientId, DocumentSelection selection);
}
interface DocOpListener {
void onDocOpAckReceived(int documentId, DocOp serverHistoryDocOp, boolean clean);
void onDocOpSent(int documentId, List<DocOp> docOps);
}
private static class ChannelListener implements GenericOperationChannel.Listener<DocOp> {
private FileConcurrencyController controller;
private final DocOpSender sender;
private final ListenerManager<DocOpListener> docOpListenerManager;
private ChannelListener(
ListenerManager<DocOpListener> docOpListenerManager, DocOpSender sender) {
this.docOpListenerManager = docOpListenerManager;
this.sender = sender;
}
@Override
public void onAck(final DocOp serverHistoryOp, final boolean clean) {
sender.clearLastClientToServerDocOpMsg(null);
docOpListenerManager.dispatch(new Dispatcher<DocOpListener>() {
@Override
public void dispatch(DocOpListener listener) {
listener.onDocOpAckReceived(controller.getDocumentId(), serverHistoryOp, clean);
}
});
}
@Override
public void onError(Throwable e) {
Log.error(getClass(), "Error from concurrency control", e);
}
@Override
public void onRemoteOp(DocOp serverHistoryOp, List<DocOp> pretransformedUnackedClientOps,
List<DocOp> pretransformedQueuedClientOps) {
/*
* Do not pass the given server history doc op because it hasn't been
* transformed for local consumption. Instead, the client calls
* GenericOperationChannel.receive().
*/
controller.onRemoteOp(pretransformedUnackedClientOps, pretransformedQueuedClientOps);
}
}
private static class OutOfOrderDocOpTimeoutRecoveringCallback implements TimeoutCallback {
private final StatusManager statusManager;
private DocOpRecoverer recoverer;
private final ErrorCallback errorCallback = new ErrorCallback() {
@Override
public void onError() {
StatusMessage fatal = new StatusMessage(statusManager, MessageType.FATAL,
"There was a problem syncing with the server.");
fatal.addAction(StatusMessage.RELOAD_ACTION);
fatal.setDismissable(false);
fatal.fire();
}
};
OutOfOrderDocOpTimeoutRecoveringCallback(StatusManager statusManager) {
this.statusManager = statusManager;
}
@Override
public void onTimeout(int lastVersionDispatched) {
recoverer.recover(errorCallback);
}
}
private static final TransformQueue.Transformer<DocOp> transformer =
new TransformQueue.Transformer<DocOp>() {
@Override
public List<DocOp> compact(List<DocOp> clientOps) {
// TODO: implement for efficiency
return clientOps;
}
@Override
public org.waveprotocol.wave.model.operation.OperationPair<DocOp> transform(DocOp clientOp,
DocOp serverOp) {
try {
OperationPair operationPair =
Transformer.transform(ClientDocOpFactory.INSTANCE, clientOp, serverOp);
return new org.waveprotocol.wave.model.operation.OperationPair<DocOp>(
operationPair.clientOp(), operationPair.serverOp());
} catch (Exception e) {
// TODO: stop using RuntimeException and make a custom
// exception type
Log.error(getClass(), "Error from DocOp transformer", e);
throw new RuntimeException(e);
}
}
};
public static FileConcurrencyController create(AppContext appContext,
String fileEditSessionKey,
int documentId,
IncomingDocOpDemultiplexer docOpDemux,
CollaboratorDocOpSink remoteOpSink,
DocOpListener docOpListener,
DocOpRecoveryInitiator docOpRecoveryInitiator) {
ListenerManager<DocOpListener> docOpListenerManager = ListenerManager.create();
docOpListenerManager.add(docOpListener);
OutOfOrderDocOpTimeoutRecoveringCallback timeoutCallback =
new OutOfOrderDocOpTimeoutRecoveringCallback(appContext.getStatusManager());
DocOpReceiver receiver = new DocOpReceiver(
docOpDemux, fileEditSessionKey, timeoutCallback, OUT_OF_ORDER_DOC_OP_TIMEOUT_MS);
DocOpSender sender = new DocOpSender(appContext.getFrontendApi(),
docOpDemux,
fileEditSessionKey,
documentId,
docOpListenerManager,
docOpRecoveryInitiator);
ChannelListener listener = new ChannelListener(docOpListenerManager, sender);
// TODO: implement the Logger interface using our logging utils
GenericOperationChannel<DocOp> channel = new GenericOperationChannel<DocOp>(
SchedulerInstance.getMediumPriorityTimer(), transformer, receiver, sender, listener);
receiver.setRevisionProvider(channel);
DocOpRecoverer recoverer = new DocOpRecoverer(fileEditSessionKey,
appContext.getFrontendApi().RECOVER_FROM_MISSED_DOC_OPS,
receiver,
sender,
channel);
timeoutCallback.recoverer = recoverer;
FileConcurrencyController fileConcurrencyController = new FileConcurrencyController(channel,
receiver,
sender,
remoteOpSink,
recoverer,
docOpListenerManager,
documentId);
listener.controller = fileConcurrencyController;
return fileConcurrencyController;
}
private final GenericOperationChannel<DocOp> ccChannel;
private final DocOpReceiver receiver;
private final CollaboratorDocOpSink sink;
private final DocOpSender sender;
private final DocOpRecoverer recoverer;
private final ListenerManager<DocOpListener> docOpListenerManager;
private final int documentId;
private FileConcurrencyController(GenericOperationChannel<DocOp> ccChannel,
DocOpReceiver receiver,
DocOpSender sender,
CollaboratorDocOpSink sink,
DocOpRecoverer recoverer,
ListenerManager<DocOpListener> docOpListenerManager,
int documentId) {
this.ccChannel = ccChannel;
this.receiver = receiver;
this.sender = sender;
this.sink = sink;
this.recoverer = recoverer;
this.docOpListenerManager = docOpListenerManager;
this.documentId = documentId;
}
int getDocumentId() {
return documentId;
}
void consumeLocalDocOp(DocOp docOp) {
ccChannel.send(docOp);
}
ListenerRegistrar<DocOpListener> getDocOpListenerRegistrar() {
return docOpListenerManager;
}
int getQueuedClientOpCount() {
return ccChannel.getQueuedClientOpCount();
}
int getUnackedClientOpCount() {
return ccChannel.getUnacknowledgedClientOpCount();
}
void start(int ccRevision) {
ccChannel.connect(ccRevision, BootstrapSession.getBootstrapSession().getActiveClientId());
}
void stop() {
ccChannel.disconnect();
}
void setDocOpCreationParticipant(ClientToServerDocOpCreationParticipant participant) {
sender.setDocOpCreationParticipant(participant);
}
void recover(ErrorCallback errorCallback) {
recoverer.recover(errorCallback);
}
private void onRemoteOp(List<DocOp> pretransformedUnackedClientOps,
List<DocOp> pretransformedQueuedClientOps) {
DocumentSelection selection = receiver.getSelection();
if (selection != null) {
// Transform the remote position with our unacked and queued doc ops
selection =
transformSelection(selection, pretransformedUnackedClientOps,
pretransformedQueuedClientOps);
}
sink.consume(ccChannel.receive(), receiver.getClientId(), selection);
}
private DocumentSelection transformSelection(DocumentSelection selection,
List<DocOp> pretransformedUnackedClientOps,
List<DocOp> pretransformedQueuedClientOps) {
PositionTransformer basePositionTransformer =
new PositionTransformer(selection.getBasePosition().getLineNumber(), selection
.getBasePosition().getColumn());
PositionTransformer cursorPositionTransformer =
new PositionTransformer(selection.getCursorPosition().getLineNumber(), selection
.getCursorPosition().getColumn());
for (DocOp op : pretransformedUnackedClientOps) {
basePositionTransformer.transform(op);
cursorPositionTransformer.transform(op);
}
for (DocOp op : pretransformedQueuedClientOps) {
basePositionTransformer.transform(op);
cursorPositionTransformer.transform(op);
}
return DocumentSelectionImpl.make().setBasePosition(makeFilePosition(basePositionTransformer))
.setCursorPosition(makeFilePosition(cursorPositionTransformer))
.setUserId(selection.getUserId());
}
private FilePositionImpl makeFilePosition(PositionTransformer transformer) {
return
FilePositionImpl.make().setLineNumber(transformer.getLineNumber())
.setColumn(transformer.getColumn());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/CollaboratorCursorController.java | client/src/main/java/com/google/collide/client/collaboration/CollaboratorCursorController.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.client.collaboration;
import javax.annotation.Nullable;
import com.google.collide.client.AppContext;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.code.Participant;
import com.google.collide.client.code.ParticipantModel;
import com.google.collide.client.editor.Buffer;
import com.google.collide.client.editor.selection.CursorView;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.client.DtoClientImpls.DocumentSelectionImpl;
import com.google.collide.dto.client.DtoClientImpls.FilePositionImpl;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.collide.shared.util.JsonCollections;
import elemental.util.Timer;
/**
* A controller for the collaborators' cursors.
*/
class CollaboratorCursorController {
private class CollaboratorState {
private Anchor anchor;
private CursorView cursorView;
private Timer inactiveTimer = new Timer() {
@Override
public void run() {
cursorView.setVisibility(false);
}
};
CollaboratorState(Anchor anchor, CursorView cursorView) {
this.anchor = anchor;
this.cursorView = cursorView;
}
void markAsActive() {
inactiveTimer.schedule(INACTIVE_DELAY_MS);
if (!cursorView.isVisible()) {
cursorView.setVisibility(true);
}
}
}
private static final AnchorType COLLABORATOR_CURSOR_ANCHOR_TYPE = AnchorType.create(
CollaboratorCursorController.class, "collaboratorCursor");
private static final int INACTIVE_DELAY_MS = 10 * 1000;
private final AppContext appContext;
private final Buffer buffer;
private final JsonStringMap<CollaboratorState> collaboratorStates = JsonCollections.createMap();
private final Document document;
private final ParticipantModel participantModel;
private final ParticipantModel.Listener participantModelListener =
new ParticipantModel.Listener() {
@Override
public void participantRemoved(Participant participant) {
CollaboratorState collaboratorState = collaboratorStates.get(participant.getUserId());
if (collaboratorState == null) {
return;
}
document.getAnchorManager().removeAnchor(collaboratorState.anchor);
}
@Override
public void participantAdded(Participant participant) {
CollaboratorState collaboratorState = collaboratorStates.get(participant.getUserId());
if (collaboratorState == null) {
return;
}
collaboratorState.cursorView.setColor(participant.getColor());
}
};
CollaboratorCursorController(AppContext appContext, Document document, Buffer buffer,
ParticipantModel participantModel, JsonStringMap<DocumentSelection> collaboratorSelections) {
this.appContext = appContext;
this.buffer = buffer;
this.document = document;
this.participantModel = participantModel;
participantModel.addListener(participantModelListener);
collaboratorSelections.iterate(new IterationCallback<DocumentSelection>() {
@Override
public void onIteration(String userId, DocumentSelection selection) {
try {
handleSelectionChangeWithUserId(userId, selection);
} catch (Throwable t) {
/*
* TODO: There's a known bug that if a document is not open in the editor,
* our cached collaborator selections won't get transformed with incoming doc ops. This
* means that it's possible the selection is out of the actual document's range (either
* line number or column is too big.)
*/
}
}
});
}
void handleSelectionChange(String clientId, @Nullable DocumentSelection selection) {
handleSelectionChangeWithUserId(participantModel.getUserId(clientId), selection);
}
private void handleSelectionChangeWithUserId(String userId,
@Nullable DocumentSelection selection) {
if (BootstrapSession.getBootstrapSession().getUserId().equals(userId)) {
// Do not draw a collaborator cursor for our user
return;
}
// If a user is typing, a selection will likely be null (since it isn't an explicit move)
if (selection != null) {
LineInfo lineInfo =
document.getLineFinder().findLine(selection.getCursorPosition().getLineNumber());
int cursorColumn = selection.getCursorPosition().getColumn();
if (!collaboratorStates.containsKey(selection.getUserId())) {
createCursor(selection.getUserId(), lineInfo.line(), lineInfo.number(), cursorColumn);
} else {
document.getAnchorManager().moveAnchor(collaboratorStates.get(selection.getUserId()).anchor,
lineInfo.line(), lineInfo.number(), cursorColumn);
}
}
if (collaboratorStates.containsKey(userId)) {
collaboratorStates.get(userId).markAsActive();
}
}
void teardown() {
participantModel.removeListener(participantModelListener);
collaboratorStates.iterate(new IterationCallback<CollaboratorState>() {
@Override
public void onIteration(String key, CollaboratorState collaboratorState) {
document.getAnchorManager().removeAnchor(collaboratorState.anchor);
}
});
}
private void createCursor(final String userId, Line line, int lineNumber, int column) {
final CursorView cursorView = CursorView.create(appContext.getResources(), false);
cursorView.setVisibility(true);
Participant participant = participantModel.getParticipantByUserId(userId);
if (participant != null) {
/*
* If the participant exists already, set his color (otherwise the
* participant model listener will set the color)
*/
cursorView.setColor(participant.getColor());
}
Anchor anchor =
document.getAnchorManager().createAnchor(COLLABORATOR_CURSOR_ANCHOR_TYPE, line, lineNumber,
column);
anchor.setRemovalStrategy(RemovalStrategy.SHIFT);
buffer.addAnchoredElement(anchor, cursorView.getElement());
collaboratorStates.put(userId, new CollaboratorState(anchor, cursorView));
}
public JsonStringMap<DocumentSelection> getSelectionsMap() {
final JsonStringMap<DocumentSelection> map = JsonCollections.createMap();
collaboratorStates.iterate(
new IterationCallback<CollaboratorCursorController.CollaboratorState>() {
@Override
public void onIteration(String userId, CollaboratorState state) {
FilePositionImpl basePosition = FilePositionImpl.make().setColumn(
state.anchor.getColumn()).setLineNumber(state.anchor.getLineNumber());
FilePositionImpl cursorPosition = FilePositionImpl.make().setColumn(
state.anchor.getColumn()).setLineNumber(state.anchor.getLineNumber());
DocumentSelectionImpl selection = DocumentSelectionImpl.make()
.setBasePosition(basePosition).setCursorPosition(cursorPosition).setUserId(userId);
map.put(userId, selection);
}
});
return map;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/DocOpsSavedNotifier.java | client/src/main/java/com/google/collide/client/collaboration/DocOpsSavedNotifier.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.client.collaboration;
import java.util.List;
import com.google.collide.client.collaboration.FileConcurrencyController.DocOpListener;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.document.DocumentMetadata;
import com.google.collide.dto.DocOp;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
import com.google.common.base.Preconditions;
/**
* A utility class to register for callbacks when all of the doc ops in a particular scope are
* saved (the server has successfully received and applied them to the document.)
*/
public class DocOpsSavedNotifier {
public abstract static class Callback {
private final DocOpListener docOpListener = new DocOpListener() {
@Override
public void onDocOpAckReceived(int documentId, DocOp serverHistoryDocOp, boolean clean) {
Integer remainingAcks = remainingAcksByDocumentId.get(documentId);
if (remainingAcks == null) {
// We have already reached our ack count for this document ID
return;
}
remainingAcks--;
if (remainingAcks == 0) {
remainingAcksByDocumentId.erase(documentId);
tryCallback();
} else {
remainingAcksByDocumentId.put(documentId, remainingAcks);
}
}
@Override
public void onDocOpSent(int documentId, List<DocOp> docOps) {
}
};
private RemoverManager remover;
private JsonIntegerMap<Integer> remainingAcksByDocumentId;
public abstract void onAllDocOpsSaved();
private void initialize(
RemoverManager remover, JsonIntegerMap<Integer> remainingAcksByDocumentId) {
this.remover = remover;
this.remainingAcksByDocumentId = remainingAcksByDocumentId;
}
/**
* Stops listening for the doc ops to be saved.
*/
protected void cancel() {
remover.remove();
remover = null;
remainingAcksByDocumentId = null;
}
private void tryCallback() {
if (!isWaiting()) {
// Only callback after all documents' doc ops have been acked
cancel();
onAllDocOpsSaved();
}
}
boolean isWaiting() {
return remainingAcksByDocumentId != null && !remainingAcksByDocumentId.isEmpty();
}
}
private final DocumentManager documentManager;
private final CollaborationManager collaborationManager;
public DocOpsSavedNotifier(
DocumentManager documentManager, CollaborationManager collaborationManager) {
this.documentManager = documentManager;
this.collaborationManager = collaborationManager;
}
/**
* @see #notifyForFiles(Callback, String...)
*/
public boolean notifyForWorkspace(Callback callback) {
JsonArray<Document> documents = documentManager.getDocuments();
int[] documentIds = new int[documents.size()];
for (int i = 0; i < documentIds.length; i++) {
documentIds[i] = documents.get(i).getId();
}
return notifyForDocuments(callback, documentIds);
}
/**
* @see #notifyForDocuments(Callback, int...)
*/
public boolean notifyForFiles(Callback callback, String... fileEditSessionKeys) {
int[] documentIds = new int[fileEditSessionKeys.length];
for (int i = 0; i < documentIds.length; i++) {
Document document = documentManager.getDocumentByFileEditSessionKey(fileEditSessionKeys[i]);
Preconditions.checkNotNull(document,
"Document for given fileEditSessionKey [" + fileEditSessionKeys[i] + "] does not exist");
documentIds[i] = document.getId();
}
return notifyForDocuments(callback, documentIds);
}
/**
* @return whether we are waiting for unacked or queued doc ops
*/
public boolean notifyForDocuments(Callback callback, int... documentIds) {
RemoverManager remover = new RemoverManager();
JsonIntegerMap<Integer> remainingAcksByDocumentId = JsonCollections.createIntegerMap();
for (int i = 0; i < documentIds.length; i++) {
int documentId = documentIds[i];
if (!DocumentMetadata.isLinkedToFile(documentManager.getDocumentById(documentId))) {
// Ignore unlinked files
continue;
}
DocumentCollaborationController documentCollaborationController =
collaborationManager.getDocumentCollaborationController(documentId);
Preconditions.checkNotNull(documentCollaborationController,
"Could not find collaboration controller document ID [" + documentId + "]");
FileConcurrencyController fileConcurrencyController =
documentCollaborationController.getFileConcurrencyController();
int remainingAcks = computeRemainingAcks(fileConcurrencyController);
if (remainingAcks > 0) {
remainingAcksByDocumentId.put(documentId, remainingAcks);
remover.track(
fileConcurrencyController.getDocOpListenerRegistrar().add(callback.docOpListener));
}
}
callback.initialize(remover, remainingAcksByDocumentId);
// If there aren't any unacked or queued doc ops, this will callback immediately
callback.tryCallback();
return callback.isWaiting();
}
private static int computeRemainingAcks(FileConcurrencyController fileConcurrencyController) {
return fileConcurrencyController.getUnackedClientOpCount()
+ fileConcurrencyController.getQueuedClientOpCount();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/AckWatchdog.java | client/src/main/java/com/google/collide/client/collaboration/AckWatchdog.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.client.collaboration;
import java.util.List;
import com.google.collide.client.collaboration.FileConcurrencyController.DocOpListener;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.util.WindowUnloadingController;
import com.google.collide.client.util.WindowUnloadingController.Message;
import com.google.collide.client.xhrmonitor.XhrWarden;
import com.google.collide.dto.DocOp;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.ot.DocOpUtils;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.user.client.Timer;
/**
* A service that warns the user if a sent document operation does not receive
* an acknowledgment in a short amount of itme.
*
*/
class AckWatchdog implements DocOpListener {
private static final int ACK_WARNING_TIMEOUT_MS = 10000;
private static final int ACK_ERROR_TIMEOUT_MS = 60000;
/*
* TODO: editor read-only state can be touched by multiple
* clients. Imagine two that each want to set the editor read-only for 5
* seconds, (A) sets read-only, a few seconds elapse, (B) sets read-only, (A)
* wants to set back to write (but B still wants read-only), then (B) wants to
* set to write. This doesn't handle that well; the editor needs to expose
* better API for this (give each caller a separate boolean and only set back
* to write when all callers have readonly=false. Perhaps API will be
* editor.setReadOnly(getClass(), true) or some string ID instead of class).
*/
private boolean hasSetEditorReadOnly;
private boolean isEditorReadOnlyByOthers;
private Editor editor;
private final JsonArray<DocOp> unackedDocOps = JsonCollections.createArray();
private final DocOpRecoveryInitiator docOpRecoveryInitiator;
private final StatusManager statusManager;
private StatusMessage warningMessage;
private StatusMessage errorMessage;
private final WindowUnloadingController windowUnloadingController;
private final WindowUnloadingController.Message windowUnloadingMessage;
private final Timer warningTimer = new Timer() {
@Override
public void run() {
showErrorOrWarningMessage(false);
}
};
private final Timer errorTimer = new Timer() {
@Override
public void run() {
showErrorOrWarningMessage(true);
}
};
AckWatchdog(StatusManager statusManager, WindowUnloadingController windowClosingController,
DocOpRecoveryInitiator docOpRecoveryInitiator) {
this.statusManager = statusManager;
this.windowUnloadingController = windowClosingController;
this.docOpRecoveryInitiator = docOpRecoveryInitiator;
// Add a window closing listener to wait for client ops to complete.
windowUnloadingMessage = new Message() {
@Override
public String getMessage() {
if (unackedDocOps.size() > 0) {
return
"You have changes that are still saving and will be lost if you leave this page now.";
} else {
return null;
}
}
};
windowClosingController.addMessage(windowUnloadingMessage);
}
void teardown() {
warningTimer.cancel();
errorTimer.cancel();
windowUnloadingController.removeMessage(windowUnloadingMessage);
}
public void setEditor(Editor editor) {
/*
* TODO: minimizing change in this CL, but a future CL could
* introudce a document tag for the read-only state
*/
Editor oldEditor = this.editor;
if (oldEditor != null && hasSetEditorReadOnly && !isEditorReadOnlyByOthers) {
// Undo our changes
oldEditor.setReadOnly(false);
}
hasSetEditorReadOnly = false;
this.editor = editor;
}
@Override
public void onDocOpAckReceived(int documentId, DocOp serverHistoryDocOp, boolean clean) {
unackedDocOps.remove(0);
if (unackedDocOps.size() == 0) {
warningTimer.cancel();
errorTimer.cancel();
hideErrorAndWarningMessages();
}
}
@Override
public void onDocOpSent(int documentId, List<DocOp> docOps) {
/*
* Our OT model only allows for one set of outstanding doc ops, so this will
* not be called again until we have received acks for all of the individual
* doc ops.
*/
for (int i = 0, n = docOps.size(); i < n; i++) {
unackedDocOps.add(docOps.get(i));
}
warningTimer.schedule(ACK_WARNING_TIMEOUT_MS);
errorTimer.schedule(ACK_ERROR_TIMEOUT_MS);
}
/**
* @param error true for error, false for warning
*/
private void showErrorOrWarningMessage(boolean error) {
if (error && editor != null) {
isEditorReadOnlyByOthers = editor.isReadOnly();
hasSetEditorReadOnly = true;
editor.setReadOnly(true);
}
if (error && errorMessage == null) {
errorMessage = createErrorMessage();
errorMessage.fire();
} else if (!error && warningMessage == null) {
warningMessage = createWarningMessage();
warningMessage.fire();
}
docOpRecoveryInitiator.recover();
}
private void hideErrorAndWarningMessages() {
if (hasSetEditorReadOnly && !isEditorReadOnlyByOthers && editor != null) {
editor.setReadOnly(false);
hasSetEditorReadOnly = false;
}
boolean hadErrorOrWarningMessage = errorMessage != null || warningMessage != null;
if (errorMessage != null) {
errorMessage.cancel();
errorMessage = null;
}
if (warningMessage != null) {
warningMessage.cancel();
warningMessage = null;
}
if (hadErrorOrWarningMessage) {
createReceivedAckMessage().fire();
}
}
private StatusMessage createWarningMessage() {
StatusMessage msg =
new StatusMessage(statusManager, MessageType.LOADING,
"Still saving your latest changes...");
msg.setDismissable(true);
XhrWarden.dumpRequestsToConsole();
return msg;
}
private StatusMessage createErrorMessage() {
StatusMessage msg =
new StatusMessage(statusManager, MessageType.ERROR,
"Your latest changes timed out while saving.");
msg.addAction(StatusMessage.RELOAD_ACTION);
msg.setDismissable(false);
XhrWarden.dumpRequestsToConsole();
return msg;
}
private StatusMessage createReceivedAckMessage() {
StatusMessage msg =
new StatusMessage(statusManager, MessageType.CONFIRMATION,
"Saved successfully.");
msg.setDismissable(true);
msg.expire(1500);
return msg;
}
private String getUnackedDocOpsString() {
StringBuilder str = new StringBuilder();
for (int i = 0, n = unackedDocOps.size(); i < n; i++) {
str.append(DocOpUtils.toString(unackedDocOps.get(i), true)).append("\n");
}
return str.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/LocalCursorTracker.java | client/src/main/java/com/google/collide/client/collaboration/LocalCursorTracker.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.client.collaboration;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl;
import com.google.collide.dto.client.DtoClientImpls.DocumentSelectionImpl;
import com.google.collide.dto.client.DtoClientImpls.FilePositionImpl;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
/**
* A class that tracks local cursor changes and eventually will aid in
* broadcasting them to the collaborators.
*
*/
class LocalCursorTracker
implements SelectionModel.CursorListener, ClientToServerDocOpCreationParticipant {
private final DocumentCollaborationController collaborationController;
private boolean hasExplicitCursorChange;
private final SelectionModel selectionModel;
private final Remover cursorListenerRemover;
LocalCursorTracker(
DocumentCollaborationController collaborationController, SelectionModel selectionModel) {
this.collaborationController = collaborationController;
this.selectionModel = selectionModel;
cursorListenerRemover = selectionModel.getCursorListenerRegistrar().add(this);
}
@Override
public void onCreateClientToServerDocOp(ClientToServerDocOpImpl message) {
if (!hasExplicitCursorChange) {
return;
}
FilePositionImpl basePosition =
FilePositionImpl.make().setColumn(selectionModel.getBaseColumn()).setLineNumber(
selectionModel.getBaseLineNumber());
FilePositionImpl cursorPosition =
FilePositionImpl.make().setColumn(selectionModel.getCursorColumn()).setLineNumber(
selectionModel.getCursorLineNumber());
DocumentSelectionImpl selection =
DocumentSelectionImpl.make().setBasePosition(basePosition).setCursorPosition(
cursorPosition).setUserId(BootstrapSession.getBootstrapSession().getUserId());
message.setSelection(selection);
// Reset
hasExplicitCursorChange = false;
}
@Override
public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) {
if (isExplicitChange) {
hasExplicitCursorChange = true;
collaborationController.ensureQueuedDocOp();
}
}
/**
* Forces the next client to server doc op to have our selection included.
*/
void forceSendingSelection() {
hasExplicitCursorChange = true;
}
void teardown() {
cursorListenerRemover.remove();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/DocOpRecoverer.java | client/src/main/java/com/google/collide/client/collaboration/DocOpRecoverer.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.client.collaboration;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.collaboration.cc.RevisionProvider;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.FrontendApi.RequestResponseApi;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.RecoverFromMissedDocOps;
import com.google.collide.dto.RecoverFromMissedDocOpsResponse;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.ServerToClientDocOp;
import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl;
import com.google.collide.dto.client.DtoClientImpls.RecoverFromMissedDocOpsImpl;
import com.google.collide.dto.client.DtoClientImpls.ServerToClientDocOpImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.ErrorCallback;
import elemental.util.Timer;
/**
* A class that performs the XHR to recover missed doc ops and funnels the results into the right
* components.
*/
class DocOpRecoverer {
private static final int RECOVERY_MAX_RETRIES = 5;
private static final int RECOVERY_RETRY_DELAY_MS = 5000;
private final String fileEditSessionKey;
private final RequestResponseApi<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse>
recoverFrontendApi;
private final DocOpReceiver docOpReceiver;
private final LastClientToServerDocOpProvider lastSentDocOpProvider;
private final RevisionProvider revisionProvider;
private boolean isRecovering;
DocOpRecoverer(String fileEditSessionKey, RequestResponseApi<
RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse> recoverFrontendApi,
DocOpReceiver docOpReceiver, LastClientToServerDocOpProvider lastSentDocOpProvider,
RevisionProvider revisionProvider) {
this.fileEditSessionKey = fileEditSessionKey;
this.recoverFrontendApi = recoverFrontendApi;
this.docOpReceiver = docOpReceiver;
this.lastSentDocOpProvider = lastSentDocOpProvider;
this.revisionProvider = revisionProvider;
}
/**
* Attempts to recover after missed doc ops.
*/
void recover(ErrorCallback errorCallback) {
recover(errorCallback, 0);
}
private void recover(final ErrorCallback errorCallback, final int retryCount) {
if (isRecovering) {
return;
}
isRecovering = true;
Log.info(getClass(), "Recovering from disconnection");
// 1) Gather potentially unacked doc ops
final ClientToServerDocOpImpl lastSentMsg =
lastSentDocOpProvider.getLastClientToServerDocOpMsg();
/*
* 2) Pause processing of incoming doc ops and queue them instead. This allows us, in the
* future, to apply the queued doc ops after recovery (the recovery response may not have
* contained some of the queued doc ops depending on the order the XHR and doc ops being
* processed by the server.)
*/
docOpReceiver.pause();
// 3) Perform recovery XHR
/*
* If we had unacked doc ops, we must use their intended version since that
* is the version of the document to which the unacked doc ops apply
* cleanly. If there aren't any unacked doc ops, we can use the latest
* version of the document that we have. (These can differ if we received
* doc ops while still waiting for our ack.)
*
* The unacked doc ops' intended version will always be less than or equal
* to the latest version we have received. When applying the returned doc
* ops from the document history, we will skip those that have already been
* applied.
*/
int revision = lastSentMsg != null ? lastSentMsg.getCcRevision() : revisionProvider.revision();
RecoverFromMissedDocOpsImpl recoveryDto =
RecoverFromMissedDocOpsImpl.make()
.setClientId(BootstrapSession.getBootstrapSession().getActiveClientId())
.setCurrentCcRevision(revision)
.setFileEditSessionKey(fileEditSessionKey);
if (lastSentMsg != null) {
recoveryDto.setDocOps2((JsoArray<String>) lastSentMsg.getDocOps2());
}
recoverFrontendApi.send(recoveryDto,
new ApiCallback<RecoverFromMissedDocOpsResponse>() {
@Override
public void onMessageReceived(RecoverFromMissedDocOpsResponse message) {
// 4) Process the doc ops while I was disconnected (which will include our ack)
JsonArray<ServerToClientDocOp> recoveredServerDocOps = message.getDocOps();
for (int i = 0; i < recoveredServerDocOps.size(); i++) {
ServerToClientDocOp serverDocOp = recoveredServerDocOps.get(i);
if (serverDocOp.getAppliedCcRevision() > revisionProvider.revision()) {
docOpReceiver.simulateOrderedDocOpReceived((ServerToClientDocOpImpl) serverDocOp,
true);
}
}
// 5) Process queued doc ops while I was recovering
JsonArray<ServerToClientDocOp> queuedServerDocOps =
docOpReceiver.getOrderedQueuedServerToClientDocOps();
for (int i = 0; i < queuedServerDocOps.size(); i++) {
ServerToClientDocOp serverDocOp = queuedServerDocOps.get(i);
if (serverDocOp.getAppliedCcRevision() > revisionProvider.revision()) {
docOpReceiver.simulateOrderedDocOpReceived((ServerToClientDocOpImpl) serverDocOp,
true);
}
}
/*
* 6) Back to normal! At this point, any unacked doc ops will have
* been acked. Any queued doc ops are scheduled to be sent. We clear
* the last client-to-server-doc-op. We can also resume the doc op
* receiver now since our document is at the version that they will
* be targetting.
*/
lastSentDocOpProvider.clearLastClientToServerDocOpMsg(lastSentMsg);
docOpReceiver.resume(revisionProvider.revision() + 1);
Log.info(getClass(), "Recovered successfully");
handleRecoverFinished();
}
@Override
public void onFail(FailureReason reason) {
if (retryCount < RECOVERY_MAX_RETRIES) {
new Timer() {
@Override
public void run() {
recover(errorCallback, retryCount + 1);
}
}.schedule(RECOVERY_RETRY_DELAY_MS);
} else {
Log.info(getClass(), "Could not recover");
errorCallback.onError();
handleRecoverFinished();
}
}
});
}
private void handleRecoverFinished() {
isRecovering = false;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/DocumentCollaborationController.java | client/src/main/java/com/google/collide/client/collaboration/DocumentCollaborationController.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.client.collaboration;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.ParticipantModel;
import com.google.collide.client.collaboration.FileConcurrencyController.CollaboratorDocOpSink;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.client.ClientDocOpFactory;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Document.TextListener;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.ot.Composer;
import com.google.collide.shared.ot.Composer.ComposeException;
import com.google.collide.shared.ot.DocOpApplier;
import com.google.collide.shared.ot.DocOpBuilder;
import com.google.collide.shared.ot.DocOpUtils;
import com.google.collide.shared.util.ErrorCallback;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
/**
* Controller that adds real-time collaboration at the document level.
*
* This controller attaches to the document to broadcast any local changes to other collaborators.
* Conversely, it receives other collaborators' changes and applies them to the local document.
*
* Clients must call {@link #initialize}.
*/
public class DocumentCollaborationController implements DocOpRecoveryInitiator {
private final AppContext appContext;
private final ParticipantModel participantModel;
private final Document document;
private final RemoverManager removerManager = new RemoverManager();
private AckWatchdog ackWatchdog;
private FileConcurrencyController fileConcurrencyController;
private Editor editor;
private LocalCursorTracker localCursorTracker;
/** Saves the collaborators' selections to display when we attach to an editor */
private JsonStringMap<DocumentSelection> collaboratorSelections = JsonCollections.createMap();
private CollaboratorCursorController collaboratorCursorController;
private final IncomingDocOpDemultiplexer docOpDemux;
/**
* Used to prevent remote doc ops from being considered as local user edits inside the document
* callback
*/
private boolean isConsumingRemoteDocOp;
private final CollaboratorDocOpSink remoteOpSink = new CollaboratorDocOpSink() {
@Override
public void consume(DocOp docOp, String clientId, DocumentSelection selection) {
isConsumingRemoteDocOp = true;
try {
DocOpApplier.apply(docOp, document);
if (editor == null) {
if (selection != null) {
collaboratorSelections.put(selection.getUserId(), selection);
}
} else {
collaboratorCursorController.handleSelectionChange(clientId, selection);
}
} finally {
isConsumingRemoteDocOp = false;
}
}
};
private final Document.TextListener localTextListener = new TextListener() {
@Override
public void onTextChange(Document document, JsonArray<TextChange> textChanges) {
if (isConsumingRemoteDocOp) {
/*
* These text changes are being caused by the consumption of the remote doc ops. We don't
* want to rebroadcast these.
*/
return;
}
DocOp op = null;
for (int i = 0, n = textChanges.size(); i < n; i++) {
TextChange textChange = textChanges.get(i);
DocOp curOp = DocOpUtils.createFromTextChange(ClientDocOpFactory.INSTANCE, textChange);
try {
op = op != null ? Composer.compose(ClientDocOpFactory.INSTANCE, op, curOp) : curOp;
} catch (ComposeException e) {
if (editor != null) {
editor.setReadOnly(true);
}
new StatusMessage(appContext.getStatusManager(), MessageType.FATAL,
"Problem processing the text changes, please reload.").fire();
return;
}
}
fileConcurrencyController.consumeLocalDocOp(op);
}
};
/**
* Creates an instance of the {@link DocumentCollaborationController}.
*/
public DocumentCollaborationController(AppContext appContext, ParticipantModel participantModel,
IncomingDocOpDemultiplexer docOpDemux, Document document,
JsonArray<DocumentSelection> selections) {
this.appContext = appContext;
this.participantModel = participantModel;
this.docOpDemux = docOpDemux;
this.document = document;
for (int i = 0, n = selections.size(); i < n; i++) {
DocumentSelection selection = selections.get(i);
collaboratorSelections.put(selection.getUserId(), selection);
}
}
public void initialize(String fileEditSessionKey, int ccRevision) {
ackWatchdog = new AckWatchdog(
appContext.getStatusManager(), appContext.getWindowUnloadingController(), this);
fileConcurrencyController = FileConcurrencyController.create(appContext,
fileEditSessionKey,
document.getId(),
docOpDemux,
remoteOpSink,
ackWatchdog,
this);
fileConcurrencyController.start(ccRevision);
removerManager.track(document.getTextListenerRegistrar().add(localTextListener));
}
@Override
public void teardown() {
detachFromEditor();
removerManager.remove();
/*
* Replace the concurrency controller instance to ensure there isn't any internal state leftover
* from the previous file. (At the time of this writing, the concurrency control library has
* internal state that cannot be reset completely via its public API.)
*/
fileConcurrencyController.stop();
fileConcurrencyController = null;
ackWatchdog.teardown();
ackWatchdog = null;
}
public void attachToEditor(Editor editor) {
this.editor = editor;
ackWatchdog.setEditor(editor);
/*
* TODO: when supporting multiple editors, we'll need to encapsulate these in a
* POJO keyed off editor ID. For now, assume only a single editor.
*/
localCursorTracker = new LocalCursorTracker(this, editor.getSelection());
localCursorTracker.forceSendingSelection();
collaboratorCursorController = new CollaboratorCursorController(
appContext, document, editor.getBuffer(), participantModel, collaboratorSelections);
fileConcurrencyController.setDocOpCreationParticipant(localCursorTracker);
// Send our document selection
ensureQueuedDocOp();
}
public void detachFromEditor() {
/*
* The "!= null" checks are for when detachFromEditor is called from teardown because we can be
* torndown before the document is detached from the editor.
*/
fileConcurrencyController.setDocOpCreationParticipant(null);
if (collaboratorCursorController != null) {
collaboratorSelections = collaboratorCursorController.getSelectionsMap();
collaboratorCursorController.teardown();
collaboratorCursorController = null;
}
if (localCursorTracker != null) {
localCursorTracker.teardown();
localCursorTracker = null;
}
ackWatchdog.setEditor(null);
this.editor = null;
}
FileConcurrencyController getFileConcurrencyController() {
return fileConcurrencyController;
}
void ensureQueuedDocOp() {
if (fileConcurrencyController.getQueuedClientOpCount() == 0) {
// There aren't any queued doc ops, create and send a noop doc op
DocOp noopDocOp = new DocOpBuilder(ClientDocOpFactory.INSTANCE, false).retainLine(
document.getLineCount()).build();
fileConcurrencyController.consumeLocalDocOp(noopDocOp);
}
}
@Override
public void recover() {
fileConcurrencyController.recover(new ErrorCallback() {
@Override
public void onError() {
StatusMessage fatal = new StatusMessage(appContext.getStatusManager(), MessageType.FATAL,
"There was a problem synchronizing with the server.");
fatal.addAction(StatusMessage.RELOAD_ACTION);
fatal.setDismissable(false);
fatal.fire();
}
});
}
void handleTransportReconnectedSuccessfully() {
recover();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/DocOpReceiver.java | client/src/main/java/com/google/collide/client/collaboration/DocOpReceiver.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.client.collaboration;
import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer.Receiver;
import com.google.collide.client.collaboration.cc.GenericOperationChannel.ReceiveOpChannel;
import com.google.collide.client.collaboration.cc.RevisionProvider;
import com.google.collide.client.util.ClientTimer;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.ServerToClientDocOp;
import com.google.collide.dto.client.DtoClientImpls.ServerToClientDocOpImpl;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.Pair;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.Reorderer;
import com.google.collide.shared.util.Reorderer.ItemSink;
import com.google.collide.shared.util.Reorderer.TimeoutCallback;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* Helper to receive messages from the transport and pass it onto the local
* concurrency control library.
*
*/
class DocOpReceiver implements ReceiveOpChannel<DocOp> {
private ReceiveOpChannel.Listener<DocOp> listener;
@VisibleForTesting
final Receiver unorderedDocOpReceiver = new Receiver() {
@Override
public void onDocOpReceived(ServerToClientDocOpImpl message, DocOp docOp) {
// We just received this doc op from the wire, pass it to the reorderer
docOpReorderer.acceptItem(Pair.of(message, docOp), message.getAppliedCcRevision());
}
};
private final ItemSink<Pair<ServerToClientDocOpImpl, DocOp>> orderedDocOpSink =
new ItemSink<Pair<ServerToClientDocOpImpl, DocOp>>() {
@Override
public void onItem(Pair<ServerToClientDocOpImpl, DocOp> docOpPair, int version) {
onReceivedOrderedDocOp(docOpPair.first, docOpPair.second, false);
}
};
private Reorderer<Pair<ServerToClientDocOpImpl, DocOp>> docOpReorderer;
private final TimeoutCallback outOfOrderTimeoutCallback;
private final int outOfOrderTimeoutMs;
private final String fileEditSessionKey;
/** Valid only for a partial scope of messageReceiver */
private String currentMessageClientId;
/** Valid only for a partial scope of messageReceiver */
private DocumentSelection currentMessageSelection;
private final IncomingDocOpDemultiplexer docOpDemux;
private boolean isPaused;
private final JsonArray<ServerToClientDocOp> queuedOrderedServerToClientDocOps = JsonCollections
.createArray();
private RevisionProvider revisionProvider;
DocOpReceiver(IncomingDocOpDemultiplexer docOpDemux, String fileEditSessionKey,
Reorderer.TimeoutCallback outOfOrderTimeoutCallback, int outOfOrderTimeoutMs) {
this.docOpDemux = docOpDemux;
this.fileEditSessionKey = fileEditSessionKey;
this.outOfOrderTimeoutCallback = outOfOrderTimeoutCallback;
this.outOfOrderTimeoutMs = outOfOrderTimeoutMs;
}
void setRevisionProvider(RevisionProvider revisionProvider) {
this.revisionProvider = revisionProvider;
}
@Override
public void connect(int revision, ReceiveOpChannel.Listener<DocOp> listener) {
Preconditions.checkState(revisionProvider != null, "Must have set revisionProvider by now");
this.listener = listener;
int nextExpectedVersion = revision + 1;
this.docOpReorderer = Reorderer.create(
nextExpectedVersion, orderedDocOpSink, outOfOrderTimeoutMs, outOfOrderTimeoutCallback,
ClientTimer.FACTORY);
docOpDemux.setReceiver(fileEditSessionKey, unorderedDocOpReceiver);
}
@Override
public void disconnect() {
docOpDemux.setReceiver(fileEditSessionKey, null);
}
/**
* Pauses the processing (calling back to listener) of received doc ops. While paused, any
* received doc ops will be stored in a queue which can be retrieved via
* {@link #getOrderedQueuedServerToClientDocOps()}. This queue will only contain doc ops from this
* point forward.
*
* <p>
* This method can be called multiple times without calling {@link #resume(int)}.
*/
void pause() {
if (isPaused) {
return;
}
isPaused = true;
docOpReorderer.setTimeoutEnabled(false);
// Clear queue so it will contain only doc ops after this pause
queuedOrderedServerToClientDocOps.clear();
}
JsonArray<ServerToClientDocOp> getOrderedQueuedServerToClientDocOps() {
return queuedOrderedServerToClientDocOps;
}
/**
* Resumes the processing of received doc ops.
*
* <p>
* While this was paused, doc ops were accumulated in the queue
* {@link #getOrderedQueuedServerToClientDocOps()}. Those will not be processed
* automatically.
*
* <p>
* This method cannot be called when already resumed.
*/
void resume(int nextExpectedVersion) {
Preconditions.checkState(isPaused, "Cannot resume if already resumed");
isPaused = false;
docOpReorderer.setTimeoutEnabled(true);
docOpReorderer.skipToVersion(nextExpectedVersion);
}
String getClientId() {
return currentMessageClientId;
}
DocumentSelection getSelection() {
return currentMessageSelection;
}
/**
* @param bypassPaused whether to process the doc op immediately even if
* {@link #pause()} has been called
*/
void simulateOrderedDocOpReceived(ServerToClientDocOpImpl message, boolean bypassPaused) {
DocOp docOp = message.getDocOp2();
onReceivedOrderedDocOp(message, docOp, bypassPaused);
}
private void onReceivedOrderedDocOp(
ServerToClientDocOpImpl message, DocOp docOp, boolean bypassPaused) {
if (isPaused && !bypassPaused) {
// Just queue the doc op messages instead
queuedOrderedServerToClientDocOps.add(message);
return;
}
if (revisionProvider.revision() >= message.getAppliedCcRevision()) {
// Already seen this
return;
}
/*
* Later in the stack, we need this valuable information for rendering the
* collaborator's cursor. But, since we funnel through the concurrency
* control library, this information is lost. The workaround is to stash
* the data here. We will fetch this from the callback given by the
* concurrency control library.
*
* TODO: This is really a workaround until I have time to
* think about a clean API for sending/receiving positions like the
* collaborative selection/cursor stuff requires. Once I do that, I'll
* also remove this workaround and make position transformation a
* first-class feature inside the forked CC library.
*/
currentMessageClientId = message.getClientId();
currentMessageSelection = message.getSelection();
try {
listener.onMessage(message.getAppliedCcRevision(), message.getClientId(), docOp);
} catch (Throwable t) {
Log.error(getClass(), "Could not handle received doc op", t);
}
currentMessageClientId = null;
currentMessageSelection = null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/LastClientToServerDocOpProvider.java | client/src/main/java/com/google/collide/client/collaboration/LastClientToServerDocOpProvider.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.client.collaboration;
import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl;
/**
* Interface for providing the most recently sent {@link ClientToServerDocOpImpl}.
*/
public interface LastClientToServerDocOpProvider {
ClientToServerDocOpImpl getLastClientToServerDocOpMsg();
/**
* Clears the message that would be returned by
* {@link #getLastClientToServerDocOpMsg()}.
*
* @param clientToServerDocOpMsgToDelete if provided, the current message must
* match the given message for it to be cleared
*/
void clearLastClientToServerDocOpMsg(ClientToServerDocOpImpl clientToServerDocOpMsgToDelete);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/ClientToServerDocOpCreationParticipant.java | client/src/main/java/com/google/collide/client/collaboration/ClientToServerDocOpCreationParticipant.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.client.collaboration;
import com.google.collide.dto.ClientToServerDocOp;
import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl;
/**
* An interface that is called when a {@link ClientToServerDocOp} is being
* created.
*/
public interface ClientToServerDocOpCreationParticipant {
void onCreateClientToServerDocOp(ClientToServerDocOpImpl message);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/cc/RevisionProvider.java | client/src/main/java/com/google/collide/client/collaboration/cc/RevisionProvider.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.client.collaboration.cc;
/**
* A provider for the latest revision received.
*/
public interface RevisionProvider {
int revision();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/cc/GenericOperationChannel.java | client/src/main/java/com/google/collide/client/collaboration/cc/GenericOperationChannel.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.client.collaboration.cc;
import java.util.EnumSet;
import java.util.List;
import org.waveprotocol.wave.client.scheduler.Scheduler;
import org.waveprotocol.wave.client.scheduler.TimerService;
import org.waveprotocol.wave.model.util.FuzzingBackOffGenerator;
import com.google.collide.client.collaboration.cc.TransformQueue.Transformer;
import com.google.collide.client.util.logging.Log;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/*
* Forked from Wave. Currently, the only changes are exposing some otherwise
* internal state (such as queuedClientOps).
*
* TODO: Make it fit in with Collide: no JRE collections, reduce Wave
* dependencies
*/
/**
* Service that handles transportation and transforming of client and server
* operations.
*
* Design document:
* http://goto.google.com/generic-operation-channel/
*
*
* @param <M> Mutation type.
*/
public class GenericOperationChannel<M> implements RevisionProvider {
/** Whether debug/info logging is enabled */
private static final boolean LOG_ENABLED = false;
/**
* Provides a channel for incoming operations.
*/
public interface ReceiveOpChannel<M> {
public interface Listener<M> {
void onMessage(int resultingRevision, String sid, M mutation);
void onError(Throwable e);
}
void connect(int revision, Listener<M> listener);
void disconnect();
}
/**
* Provides a service to send outgoing operations and synchronize the
* concurrent object with the server.
*/
public interface SendOpService<M> {
public interface Callback {
void onSuccess(int appliedRevision);
void onConnectionError(Throwable e);
void onFatalError(Throwable e);
}
/**
* Submit operations at the given revision.
*
* <p>Will be called back with the revision at which the ops were applied.
*/
void submitOperations(int revision, List<M> operations, Callback callback);
/**
* Lightweight request to get the current revision of the object without
* submitting operations (somewhat equivalent to applying no operations).
*
* <p>Useful for synchronizing with the channel for retrying/reconnection.
*/
void requestRevision(Callback callback);
/**
* Called to indicate that the channel is no longer interested in being
* notified via the given callback object, so implementations may optionally
* discard the associated request state and callback. It is safe to do
* nothing with this method.
*
* @param callback
*/
void callbackNotNeeded(Callback callback);
}
/**
* Notifies when operations and acknowledgments come in. The values passed to
* the methods can be used to reconstruct the exact server history.
*
* <p>WARNING: The server history ops cannot be applied to local client
* state, because they have not been transformed properly. Server history
* ops are for other uses. To get the server ops to apply locally, use
* {@link GenericOperationChannel#receive()}
*/
public interface Listener<M> {
/**
* A remote op has been received. Do not use the parameter to apply to local
* state, instead use {@link GenericOperationChannel#receive()}.
*
* @param serverHistoryOp the operation as it appears in the server history
* (do not apply this to local state).
* @param pretransformedQueuedClientOps
* @param pretransformedUnackedClientOps
*/
void onRemoteOp(M serverHistoryOp, List<M> pretransformedUnackedClientOps,
List<M> pretransformedQueuedClientOps);
/**
* A local op is acknowledged as applied at this point in the server history
* op stream.
*
* @param serverHistoryOp the operation as it appears in the server history,
* not necessarily as it was when passed into the channel.
* @param clean true if the channel is now clean.
*/
void onAck(M serverHistoryOp, boolean clean);
/**
* Called when some unrecoverable problem occurs.
*/
void onError(Throwable e);
}
private final Scheduler.Task maybeSendTask = new Scheduler.Task() {
@Override public void execute() {
maybeSend();
}
};
private final Scheduler.Task delayedResyncTask = new Scheduler.Task() {
@Override public void execute() {
doResync();
}
};
private final ReceiveOpChannel.Listener<M> receiveListener = new ReceiveOpChannel.Listener<M>() {
@Override public void onMessage(int resultingRevision, String sid, M operation) {
if (!isConnected()) {
return;
}
if (LOG_ENABLED) {
Log.debug(getClass(), "my sid=", sessionId, ", incoming sid=", sid);
}
if (sessionId.equals(sid)) {
onAckOwnOperation(resultingRevision, operation);
} else {
onIncomingOperation(resultingRevision, operation);
}
maybeSynced();
}
@Override public void onError(Throwable e) {
if (!isConnected()) {
return;
}
listener.onError(e);
}
};
/**
* To reduce the risk of the channel behaving unpredictably due to poor
* external implementations, we handle discarding callbacks internally and
* merely hint to the service that it may be discarded.
*/
abstract class DiscardableCallback implements SendOpService.Callback {
private boolean discarded = false;
void discard() {
if (discarded) {
return;
}
discarded = true;
submitService.callbackNotNeeded(this);
}
@Override
public void onConnectionError(Throwable e) {
if (!isConnected()) {
return;
}
if (discarded) {
Log.warn(getClass(), "Ignoring failure, ", e);
return;
}
discarded = true;
Log.warn(getClass(), "Retryable failure, will resync.", e);
delayResync();
}
@Override
public void onSuccess(int appliedRevision) {
if (!isConnected()) {
return;
}
if (discarded) {
if (LOG_ENABLED) {
Log.info(getClass(), "Ignoring success @", appliedRevision);
}
return;
}
discarded = true;
success(appliedRevision);
}
@Override
public final void onFatalError(Throwable e) {
fail(e);
}
abstract void success(int appliedRevision);
}
enum State {
/**
* Cannot send ops in this state. All states can transition here if either
* explicitly requested, or if there is a permanent failure.
*/
UNINITIALISED,
/**
* No unacked ops. There may be queued ops though.
*/
ALL_ACKED,
/**
* Waiting for an ack for sent ops. Will transition back to ALL_ACKED if
* successful, or to DELAY_RESYNC if there is a retryable failure.
*/
WAITING_ACK,
/**
* Waiting to attempt a resync/reconnect (delay can be large due to
* exponential backoff). Will transition to WAITING_SYNC when the delay is
* up and we send off the version request, or to ALL_ACKED if all ops get
* acked while waiting.
*/
DELAY_RESYNC,
/**
* Waiting for our version sync. If it turns out that all ops get acked down
* the channel in the meantime, we can return to ALL_ACKED. Otherwise, we
* can resend and go to WAITING_ACK. If there is a retryable failure, we
* will go to DELAY_RESYNC
*/
WAITING_SYNC;
private EnumSet<State> to;
static {
UNINITIALISED.transitionsTo(ALL_ACKED);
ALL_ACKED.transitionsTo(WAITING_ACK);
WAITING_ACK.transitionsTo(ALL_ACKED, DELAY_RESYNC);
DELAY_RESYNC.transitionsTo(ALL_ACKED, WAITING_SYNC);
WAITING_SYNC.transitionsTo(ALL_ACKED, WAITING_ACK, DELAY_RESYNC);
}
private void transitionsTo(State... validTransitionStates) {
// Also, everything may transition to UNINITIALISED
to = EnumSet.of(UNINITIALISED, validTransitionStates);
}
}
private final FuzzingBackOffGenerator backoffGenerator;
private final TimerService scheduler;
private final ReceiveOpChannel<M> channel;
private final SendOpService<M> submitService;
private final Listener<M> listener;
// State variables
private State state = State.UNINITIALISED;
private final TransformQueue<M> queue;
private String sessionId;
private int retryVersion = -1;
private DiscardableCallback submitCallback; // mutable to discard out of date ones
private DiscardableCallback versionCallback;
public GenericOperationChannel(TimerService scheduler, Transformer<M> transformer,
ReceiveOpChannel<M> channel, SendOpService<M> submitService,
Listener<M> listener) {
this(new FuzzingBackOffGenerator(1500, 1800 * 1000, 0.5),
scheduler, transformer, channel, submitService, listener);
}
public GenericOperationChannel(FuzzingBackOffGenerator generator, TimerService scheduler,
Transformer<M> transformer, ReceiveOpChannel<M> channel, SendOpService<M> submitService,
Listener<M> listener) {
this.backoffGenerator = generator;
this.scheduler = scheduler;
this.queue = new TransformQueue<M>(transformer);
this.channel = channel;
this.submitService = submitService;
this.listener = listener;
}
public boolean isConnected() {
// UNINITIALISED implies sessionId == null.
assert state != State.UNINITIALISED || sessionId == null;
return sessionId != null;
}
@Override
public int revision() {
checkConnected();
return queue.revision();
}
public void connect(int revision, String sessionId) {
Preconditions.checkState(!isConnected(), "Already connected");
Preconditions.checkNotNull(sessionId, "Null sessionId");
Preconditions.checkArgument(revision >= 0, "Invalid revision, %s", revision);
this.sessionId = sessionId;
channel.connect(revision, receiveListener);
queue.init(revision);
setState(State.ALL_ACKED);
}
public void disconnect() {
checkConnected();
channel.disconnect();
sessionId = null;
scheduler.cancel(maybeSendTask);
setState(State.UNINITIALISED);
}
/**
* @return true if there are no queued or unacknowledged ops
*/
public boolean isClean() {
checkConnected();
boolean ret = !queue.hasQueuedClientOps() && !queue.hasUnacknowledgedClientOps();
// isClean() implies ALL_ACKED
assert !ret || state == State.ALL_ACKED;
return ret;
}
public void send(M operation) {
checkConnected();
queue.clientOp(operation);
// Defer the send to allow multiple ops to batch up, and
// to avoid waiting for the browser's network stack in case
// we are in a time critical piece of code. Note, we could even
// go further and avoid doing the transform inside the queue.
if (!queue.hasUnacknowledgedClientOps()) {
assert state == State.ALL_ACKED;
scheduler.schedule(maybeSendTask);
}
}
public M peek() {
checkConnected();
return queue.hasServerOp() ? queue.peekServerOp() : null;
}
public M receive() {
checkConnected();
return queue.hasServerOp() ? queue.removeServerOp() : null;
}
public int getQueuedClientOpCount() {
return queue.getQueuedClientOpCount();
}
public int getUnacknowledgedClientOpCount() {
return queue.getUnacknowledgedClientOpCount();
}
/**
* Brings the state variable to the given value.
*
* <p>Verifies that other member variables are are in the correct state.
*/
private void setState(State newState) {
// Check transitioning from valid old state
State oldState = state;
assert oldState.to.contains(newState)
: "Invalid state transition " + oldState + " -> " + newState;
// Check consistency of variables with new state
checkState(newState);
state = newState;
}
private void checkState(State newState) {
switch (newState) {
case UNINITIALISED:
assert sessionId == null;
break;
case ALL_ACKED:
assert sessionId != null;
assert queue.revision() >= 0;
assert isDiscarded(submitCallback);
assert isDiscarded(versionCallback);
assert retryVersion == -1;
assert !queue.hasUnacknowledgedClientOps();
assert !scheduler.isScheduled(delayedResyncTask);
break;
case WAITING_ACK:
assert !isDiscarded(submitCallback);
assert isDiscarded(versionCallback);
assert retryVersion == -1;
assert !scheduler.isScheduled(maybeSendTask);
assert !scheduler.isScheduled(delayedResyncTask);
break;
case DELAY_RESYNC:
assert isDiscarded(submitCallback);
assert isDiscarded(versionCallback);
assert retryVersion == -1;
assert !scheduler.isScheduled(maybeSendTask);
assert scheduler.isScheduled(delayedResyncTask);
break;
case WAITING_SYNC:
assert isDiscarded(submitCallback);
assert !isDiscarded(versionCallback);
assert !scheduler.isScheduled(maybeSendTask);
assert !scheduler.isScheduled(delayedResyncTask);
break;
default:
throw new AssertionError("State " + state + " not implemented");
}
}
private void delayResync() {
scheduler.scheduleDelayed(delayedResyncTask, backoffGenerator.next().targetDelay);
setState(State.DELAY_RESYNC);
}
private void doResync() {
versionCallback = new DiscardableCallback() {
@Override public void success(int appliedRevision) {
if (LOG_ENABLED) {
Log.info(getClass(), "version callback returned @", appliedRevision);
}
retryVersion = appliedRevision;
maybeSynced();
}
};
submitService.requestRevision(versionCallback);
setState(State.WAITING_SYNC);
}
private void maybeSend() {
if (queue.hasUnacknowledgedClientOps()) {
if (LOG_ENABLED) {
Log.info(getClass(), state, ", Has ", queue.unackedClientOps.size(), " unacked...");
}
return;
}
queue.pushQueuedOpsToUnacked();
sendUnackedOps();
}
/**
* Sends unacknowledged ops and transitions to the WAITING_ACK state
*/
private void sendUnackedOps() {
List<M> ops = queue.unackedClientOps();
assert ops.size() > 0;
if (LOG_ENABLED) {
Log.info(getClass(), "Sending ", ops.size(), " ops @", queue.revision());
}
submitCallback = new DiscardableCallback() {
@Override void success(int appliedRevision) {
maybeEagerlyHandleAck(appliedRevision);
}
};
submitService.submitOperations(queue.revision(), ops, submitCallback);
setState(State.WAITING_ACK);
}
private void onIncomingOperation(int revision, M operation) {
if (LOG_ENABLED) {
Log.info(getClass(), "Incoming ", revision, " ", state);
}
List<M> pretransformedUnackedClientOps = queue.unackedClientOps();
List<M> pretransformedQueuedClientOps = queue.queuedClientOps();
queue.serverOp(revision, operation);
listener.onRemoteOp(operation, pretransformedUnackedClientOps, pretransformedQueuedClientOps);
}
private void onAckOwnOperation(int resultingRevision, M ackedOp) {
boolean alreadyAckedByXhr = queue.expectedAck(resultingRevision);
if (alreadyAckedByXhr) {
// Nothing to do, just receiving expected operations that we've
// already handled by the optimization in maybeEagerlyHandleAck()
return;
}
boolean allAcked = queue.ackClientOp(resultingRevision);
if (LOG_ENABLED) {
Log.info(getClass(), "Ack @", resultingRevision, ", ",
queue.unackedClientOps.size(), " ops remaining");
}
// If we have more ops to send and no unacknowledged ops,
// then schedule a send.
if (allAcked) {
allAcked();
}
listener.onAck(ackedOp, isClean());
}
private void maybeEagerlyHandleAck(int appliedRevision) {
List<M> ownOps = queue.ackOpsIfVersionMatches(appliedRevision);
if (ownOps == null) {
return;
}
if (LOG_ENABLED) {
Log.info(getClass(), "Eagerly acked @", appliedRevision);
}
// Special optimization: there were no concurrent ops on the server,
// so we don't need to wait for them or even our own ops on the channel.
// We just throw back our own ops to our listeners as if we had
// received them from the server (we expect they should exactly
// match the server history we will shortly receive on the channel).
assert !queue.hasUnacknowledgedClientOps();
allAcked();
boolean isClean = isClean();
for (int i = 0; i < ownOps.size(); i++) {
boolean isLast = i == ownOps.size() - 1;
listener.onAck(ownOps.get(i), isClean && isLast);
}
}
private void allAcked() {
// This also counts as an early sync
synced();
// No point waiting for the XHR to come back, we're already acked.
submitCallback.discard();
setState(State.ALL_ACKED);
if (queue.hasQueuedClientOps()) {
scheduler.schedule(maybeSendTask);
}
}
private void maybeSynced() {
if (state == State.WAITING_SYNC && retryVersion != -1 && queue.revision() >= retryVersion) {
// Our ping has returned.
synced();
if (queue.hasUnacknowledgedClientOps()) {
// We've synced and didn't see our unacked ops, so they never made it (we
// are not handling the case of ops that hang around on the network and
// make it after a very long time, i.e. after a sync round trip. This
// scenario most likely extremely rare).
// Send the unacked ops again.
sendUnackedOps();
}
}
}
/**
* We have reached a state where we are confident we know whether any unacked
* ops made it to the server.
*/
private void synced() {
if (LOG_ENABLED) {
Log.info(getClass(), "synced @", queue.revision());
}
retryVersion = -1;
scheduler.cancel(delayedResyncTask);
backoffGenerator.reset();
if (versionCallback != null) {
versionCallback.discard();
}
}
private void checkConnected() {
Preconditions.checkState(isConnected(), "Not connected");
}
private boolean isDiscarded(DiscardableCallback c) {
return c == null || c.discarded;
}
private void fail(Throwable e) {
Log.warn(getClass(), "channel.fail()");
if (!isConnected()) {
Log.warn(getClass(), "not connected");
return;
}
Log.warn(getClass(), "Permanent failure");
disconnect();
listener.onError(e);
}
@VisibleForTesting State getState() {
return state;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/collaboration/cc/TransformQueue.java | client/src/main/java/com/google/collide/client/collaboration/cc/TransformQueue.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.client.collaboration.cc;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.waveprotocol.wave.model.operation.OperationPair;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/*
* Forked from Wave. Currently, the only changes are exposing some otherwise
* internal state (such as queuedClientOps).
*/
/**
* Simple implementation of main concurrency control logic, independent of
* transport concerns.
*
* <p>
* For efficiency, client ops are also compacted before transforming and before
* sending.
*/
public class TransformQueue<M> {
public interface Transformer<M> {
OperationPair<M> transform(M clientOp, M serverOp);
List<M> compact(List<M> clientOps);
}
private final Transformer<M> transformer;
private int revision = -1;
@VisibleForTesting int expectedAckedClientOps = 0;
@VisibleForTesting List<M> serverOps = new LinkedList<M>();
@VisibleForTesting List<M> unackedClientOps = Collections.emptyList();
@VisibleForTesting List<M> queuedClientOps = new LinkedList<M>();
boolean newClientOpSinceTransform = false;
public TransformQueue(Transformer<M> transformer) {
this.transformer = transformer;
}
public void init(int revision) {
Preconditions.checkState(this.revision == -1, "Already at a revision (%s), can't init at %s)",
this.revision, revision);
Preconditions.checkArgument(revision >= 0, "Initial revision must be >= 0, not %s", revision);
this.revision = revision;
}
public void serverOp(int resultingRevision, M serverOp) {
checkRevision(resultingRevision);
Preconditions.checkState(expectedAckedClientOps == 0,
"server op arrived @%s while expecting %s client ops",
resultingRevision, expectedAckedClientOps);
this.revision = resultingRevision;
if (!unackedClientOps.isEmpty()) {
List<M> newUnackedClientOps = new LinkedList<M>();
for (M clientOp : unackedClientOps) {
OperationPair<M> pair = transformer.transform(clientOp, serverOp);
newUnackedClientOps.add(pair.clientOp());
serverOp = pair.serverOp();
}
unackedClientOps = newUnackedClientOps;
}
if (!queuedClientOps.isEmpty()) {
if (newClientOpSinceTransform) {
queuedClientOps = transformer.compact(queuedClientOps);
}
newClientOpSinceTransform = false;
List<M> newQueuedClientOps = new LinkedList<M>();
for (M clientOp : queuedClientOps) {
OperationPair<M> pair = transformer.transform(clientOp, serverOp);
newQueuedClientOps.add(pair.clientOp());
serverOp = pair.serverOp();
}
queuedClientOps = newQueuedClientOps;
}
serverOps.add(serverOp);
}
public void clientOp(M clientOp) {
if (!serverOps.isEmpty()) {
List<M> newServerOps = new LinkedList<M>();
for (M serverOp : serverOps) {
OperationPair<M> pair = transformer.transform(clientOp, serverOp);
newServerOps.add(pair.serverOp());
clientOp = pair.clientOp();
}
serverOps = newServerOps;
}
queuedClientOps.add(clientOp);
newClientOpSinceTransform = true;
}
public boolean expectedAck(int resultingRevision) {
if (expectedAckedClientOps == 0) {
return false;
}
Preconditions.checkArgument(resultingRevision == revision - expectedAckedClientOps + 1,
"bad rev %s, current rev %s, expected remaining %s",
resultingRevision, revision, expectedAckedClientOps);
expectedAckedClientOps--;
return true;
}
/**
* @param resultingRevision
* @return true if all unacked ops are now acked
*/
public boolean ackClientOp(int resultingRevision) {
checkRevision(resultingRevision);
Preconditions.checkState(expectedAckedClientOps == 0,
"must call expectedAck, there are %s expectedAckedClientOps", expectedAckedClientOps);
Preconditions.checkState(!unackedClientOps.isEmpty(), "unackedClientOps is empty");
this.revision = resultingRevision;
unackedClientOps.remove(0);
return unackedClientOps.isEmpty();
}
/**
* Pushes the queued client ops into the unacked ops, clearing the queued ops.
* @return see {@link #unackedClientOps()}
*/
public List<M> pushQueuedOpsToUnacked() {
Preconditions.checkState(unackedClientOps.isEmpty(),
"Queue contains unacknowledged operations: %s", unackedClientOps);
unackedClientOps = new LinkedList<M>(transformer.compact(queuedClientOps));
queuedClientOps = new LinkedList<M>();
return unackedClientOps();
}
public boolean hasServerOp() {
return !serverOps.isEmpty();
}
public boolean hasUnacknowledgedClientOps() {
return !unackedClientOps.isEmpty();
}
public int getUnacknowledgedClientOpCount() {
return unackedClientOps.size();
}
public boolean hasQueuedClientOps() {
return !queuedClientOps.isEmpty();
}
public int getQueuedClientOpCount() {
return queuedClientOps.size();
}
public M peekServerOp() {
Preconditions.checkState(hasServerOp(), "No server ops");
return serverOps.get(0);
}
public M removeServerOp() {
Preconditions.checkState(hasServerOp(), "No server ops");
return serverOps.remove(0);
}
public int revision() {
return revision;
}
private void checkRevision(int resultingRevision) {
Preconditions.checkArgument(resultingRevision >= 1, "New revision %s must be >= 1",
resultingRevision);
Preconditions.checkState(this.revision == resultingRevision - 1,
"Revision mismatch: at %s, received %s", this.revision, resultingRevision);
}
@Override
public String toString() {
return "TQ{ " + revision + "\n s:" + serverOps +
"\n exp: " + expectedAckedClientOps +
"\n u:" + unackedClientOps + "\n q:" + queuedClientOps + "\n}";
}
/**
* @return the current queued client ops. Note: the behavior of this list
* after calling mutating methods on the transform queue is undefined.
* This method should be called each time immediately before use.
*/
List<M> queuedClientOps() {
return Collections.unmodifiableList(queuedClientOps);
}
public List<M> ackOpsIfVersionMatches(int newRevision) {
if (newRevision == revision + unackedClientOps.size()) {
List<M> expectedAckingClientOps = unackedClientOps;
expectedAckedClientOps += expectedAckingClientOps.size();
unackedClientOps = new LinkedList<M>();
revision = newRevision;
return expectedAckingClientOps;
}
return null;
}
/**
* @return the current unacked client ops. Note: the behavior of this list
* after calling mutating methods on the transform queue is undefined.
* This method should be called each time immediately before use.
*/
List<M> unackedClientOps() {
return Collections.unmodifiableList(unackedClientOps);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/autoindenter/Autoindenter.java | client/src/main/java/com/google/collide/client/autoindenter/Autoindenter.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.client.autoindenter;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.EditorDocumentMutator;
import com.google.collide.codemirror2.SyntaxType;
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.ListenerRegistrar.Remover;
import com.google.collide.shared.util.StringUtils;
import com.google.collide.shared.util.TextUtils;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.regexp.shared.RegExp;
/**
* A class responsible for automatically adding indentation when appropriate.
*/
public class Autoindenter {
private static final RegExp WHITESPACES = RegExp.compile("^\\s*$");
private interface IndentationStrategy {
Runnable handleTextChange(TextChange textChange, EditorDocumentMutator editorDocumentMutator);
}
private static class PreviousLineMatchingIndentationStrategy implements IndentationStrategy {
@Override
public Runnable handleTextChange(
TextChange textChange, final EditorDocumentMutator editorDocumentMutator) {
String text = textChange.getText();
if (!"\n".equals(text)) {
return null;
}
final int toInsert = TextUtils.countWhitespacesAtTheBeginningOfLine(
textChange.getLine().getText());
if (toInsert == 0) {
return null;
}
final Line line = LineUtils.getLine(textChange.getLine(), 1);
final int lineNumber = textChange.getLineNumber() + 1;
return new Runnable() {
@Override
public void run() {
String addend = StringUtils.getSpaces(toInsert);
editorDocumentMutator.insertText(line, lineNumber, 0, addend);
}
};
}
}
private static class CodeMirrorIndentationStrategy implements IndentationStrategy {
private final DocumentParser documentParser;
CodeMirrorIndentationStrategy(DocumentParser parser) {
documentParser = parser;
}
@Override
public Runnable handleTextChange(
TextChange textChange, final EditorDocumentMutator editorDocumentMutator) {
String text = textChange.getText();
if (!"\n".equals(text)) {
// TODO: We should incrementally apply autoindention to
// multiline pastes.
// TODO: Take electric characters into account:
// documentParser.getElectricCharacters.
return null;
}
// TODO: Ask parser to reparse changed line.
final Line line = LineUtils.getLine(textChange.getLine(), 1);
// Special case: pressing ENTER in the middle of whitespaces line should
// not fix indentation (use case: press ENTER on empty line).
Line prevLine = textChange.getLine();
if (WHITESPACES.test(prevLine.getText()) && WHITESPACES.test(line.getText())) {
return null;
}
final int lineNumber = textChange.getLineNumber() + 1;
final int indentation = documentParser.getIndentation(line);
if (indentation < 0) {
return null;
}
final int oldIndentation = TextUtils.countWhitespacesAtTheBeginningOfLine(line.getText());
if (indentation == oldIndentation) {
return null;
}
return new Runnable() {
@Override
public void run() {
if (indentation < oldIndentation) {
editorDocumentMutator.deleteText(line, lineNumber, 0, oldIndentation - indentation);
} else {
String addend = StringUtils.getSpaces(indentation - oldIndentation);
editorDocumentMutator.insertText(line, lineNumber, 0, addend);
}
}
};
}
}
/**
* Creates an instance of {@link Autoindenter} that is configured to take on
* the appropriate indentation strategy depending on the document parser.
*/
public static Autoindenter create(DocumentParser documentParser, Editor editor) {
if (documentParser.getSyntaxType() != SyntaxType.NONE && documentParser.hasSmartIndent()) {
return new Autoindenter(new CodeMirrorIndentationStrategy(documentParser), editor);
}
return new Autoindenter(new PreviousLineMatchingIndentationStrategy(), editor);
}
private final Editor editor;
private final IndentationStrategy indentationStrategy;
private boolean isMutatingDocument;
private final Editor.TextListener textListener = new Editor.TextListener() {
@Override
public void onTextChange(TextChange textChange) {
handleTextChange(textChange);
}
};
private final Remover textListenerRemover;
private Autoindenter(IndentationStrategy indentationStrategy, Editor editor) {
this.indentationStrategy = indentationStrategy;
this.editor = editor;
textListenerRemover = editor.getTextListenerRegistrar().add(textListener);
}
public void teardown() {
textListenerRemover.remove();
}
private void handleTextChange(TextChange textChange) {
if (isMutatingDocument || editor.isMutatingDocumentFromUndoOrRedo()
|| textChange.getType() != TextChange.Type.INSERT) {
return;
}
final Runnable mutator = indentationStrategy.handleTextChange(
textChange, editor.getEditorDocumentMutator());
if (mutator == null) {
return;
}
// We shouldn't be touching the document in this callback, so defer.
Scheduler.get().scheduleFinally(new ScheduledCommand() {
@Override
public void execute() {
isMutatingDocument = true;
try {
mutator.run();
} finally {
isMutatingDocument = false;
}
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/testing/DebugAttributeSetter.java | client/src/main/java/com/google/collide/client/testing/DebugAttributeSetter.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.client.testing;
import com.google.collide.client.ClientConfig;
import elemental.dom.Element;
import elemental.js.dom.JsElement;
import java.util.HashMap;
import java.util.Map;
/**
* Setter for setting debug ID and/or attributes.
* <p>
* Examples:
* <p>
* <code>new DebugAttributeSetter().add("wsId";, "2323").on(element); </code>
* <p>
* <code>new DebugAttributeSetter()
* .setId(DebugId.CONTEXT_MENU)
* .add("wsId", "2323")
* .add("owner", "b")
* .on(element);</code>
*/
public class DebugAttributeSetter {
private Map<String, String> keyValues;
private DebugId debugId;
public DebugAttributeSetter() {
if (ClientConfig.isDebugBuild()) {
keyValues = new HashMap<String, String>();
}
}
/**
* Sets debug ID to {@code debugId} if this is debug build. In release mode,
* this method will be dead code eliminated at compile time
*/
public DebugAttributeSetter setId(DebugId debugId) {
if (ClientConfig.isDebugBuild()) {
if (this.debugId != null) {
throw new IllegalArgumentException("DebugId was already set to " + this.debugId.name());
}
this.debugId = debugId;
}
return this;
}
/**
* Adds an attribute specified by {key, value} if this is debug build. In
* release mode, this method will be dead code eliminated at compile time
*
* Note that "collideid_" is added to {@code key} as prefix.
*/
public DebugAttributeSetter add(String key, String value) {
if (ClientConfig.isDebugBuild()) {
if (key == null) {
throw new IllegalArgumentException("null key");
}
if (value == null) {
throw new IllegalArgumentException("null value");
}
keyValues.put(key, value);
}
return this;
}
/**
* Applies debug ID and attributes to {@code element}.
*/
public void on(Element element) {
if (ClientConfig.isDebugBuild()) {
if (element == null) {
throw new IllegalArgumentException("null element");
}
if (debugId != null) {
element.setAttribute(DebugId.getIdKey(), debugId.name());
}
for (Map.Entry<String, String> entry : keyValues.entrySet()) {
element.setAttribute(DebugId.getAttributeKey(entry.getKey()), entry.getValue());
}
}
}
/**
* See {@code #on(Element)}
*/
public void on(com.google.gwt.dom.client.Element element) {
on(element.<JsElement>cast());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/testing/DebugId.java | client/src/main/java/com/google/collide/client/testing/DebugId.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.client.testing;
/**
* Element debug IDs used by integration test to locate elements.
*/
public enum DebugId {
// Debug
DEBUG_BREAKPOINT_SLIDER,
// DeployPopup
DEPLOY_POPUP_BASE,
DEPLOY_POPUP_DEPLOY_BUTTON,
DEPLOY_POPUP_DONE_BUTTON,
DEPLOY_POPUP_EDIT_BUTTON,
DEPLOY_POPUP_APP_IDS_DROPDOWN,
// ManageMembership
MANAGE_MEMBERSHIP_PENDING_REQUESTS_TITLE,
MANAGE_MEMBERSHIP_DONE_BUTTON,
MANAGE_MEMBERSHIP_ADD_MEMBERS_INPUT,
MANAGE_MEMBERSHIP_ADD_MEMBERS_BUTTON,
MANAGE_MEMBERSHIP_ADD_MEMBERS_CANCEL_BUTTON,
MANAGE_MEMBERSHIP_ADD_MEMBERS_ROLE_BUTTON,
MANAGE_MEMBERSHIP_ADD_MEMBERS_SEND_EMAIL_CHECKBOX,
MANAGE_MEMBERSHIP_ADD_MEMBERS_SEND_EMAIL_LABEL,
MANAGE_MEMBERSHIP_ADD_MEMBERS_COPY_SELF_CHECKBOX,
MANAGE_MEMBERSHIP_ADD_MEMBERS_COPY_SELF_LABEL,
MANAGE_MEMBERSHIP_ADD_MEMBERS_TOGGLE_MESSAGE_BUTTON,
MANAGE_MEMBERSHIP_ADD_MEMBERS_PRIVATE_MESSAGE_INPUT,
MANAGE_MEMBERSHIP_ROW,
MANAGE_MEMBERSHIP_ROW_ADD_MEMBER_ROLE_BUTTON,
MANAGE_MEMBERSHIP_ROW_CHANGE_MEMBER_ROLE_BUTTON,
MANAGE_MEMBERSHIP_ROW_IGNORE_BUTTON,
MANAGE_MEMBERSHIP_ROW_IGNORED_CONTENT,
MANAGE_MEMBERSHIP_ROW_UNDO_IGNORE_BUTTON,
MANAGE_MEMBERSHIP_ROW_UNDO_REVOKE_BUTTON,
MANAGE_MEMBERSHIP_ROW_BLOCK_BUTTON,
MANAGE_MEMBERSHIP_ROW_UNBLOCK_BUTTON,
// ProjectNavigation
PROJECT_NAVIGATION_PROJECT_LINK,
// ProjectMenu
PROJECT_MENU_REQUEST_MEMBERSHIP,
PROJECT_MENU_PENDING_REQUEST_LABEL,
PROJECT_MENU_PENDING_MANAGE_MEMBERS_BUTTON,
// MemberRoleDropdown
MEMBER_ROLE_DROPDOWN_ROW,
// RequestMembership
REQUEST_MEMBERSHIP_BASE,
REQUEST_MEMBERSHIP_CANCEL_BUTTON,
REQUEST_MEMBERSHIP_SEND_BUTTON,
// StatusPresenter
STATUS_PRESENTER,
// WorkspaceHeader
WORKSPACE_HEADER_SHARE_BUTTON,
// WorkspaceListing
WORKSPACE_LISTING_ROW;
/**
* Gets key for setting debug attribute.
* <p>
* The method is also used by JS test code to ensure consistent key value.
*/
public static String getAttributeKey(String key) {
return getIdKey() + "_" + key;
}
/**
* Gets key for setting debug ID.
* <p>
* The method is also used by JS test code to ensure consistent key value.
*/
public static String getIdKey() {
return "collideid";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/TreeWalkFileNameSearchImpl.java | client/src/main/java/com/google/collide/client/search/TreeWalkFileNameSearchImpl.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.client.search;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeNode;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.regexp.shared.RegExp;
/**
* Implements filename search by walking the file tree until enough results are
* found.
*
*
*/
public class TreeWalkFileNameSearchImpl implements FileNameSearch {
public static TreeWalkFileNameSearchImpl create() {
return new TreeWalkFileNameSearchImpl();
}
private FileTreeModel treeModel;
protected TreeWalkFileNameSearchImpl() {
treeModel = null; // must set this externally
}
/**
* Sets the file tree model to search
*/
@Override
public void setFileTreeModel(FileTreeModel model) {
treeModel = model;
}
@Override
public JsonArray<PathUtil> getMatches(RegExp query, int maxResults) {
return getMatchesRelativeToPath(PathUtil.WORKSPACE_ROOT, query, maxResults);
}
@Override
public JsonArray<PathUtil> getMatchesRelativeToPath(
PathUtil searchPath, RegExp query, int maxResults) {
JsonArray<PathUtil> results = JsonCollections.createArray();
if (treeModel == null || maxResults < 0) {
return results;
}
FileTreeNode root = treeModel.getWorkspaceRoot();
if (root == null) {
return results;
}
recurseTree(searchPath, root, query, maxResults, results);
return results;
}
/**
* Recurse a file tree node to find any matching children
*
* @param searchPath A relative path to restrict the search to
* @param node parent tree node
* @param query search query
* @param maxResults max results
* @param results the current results set
*/
protected void recurseTree(PathUtil searchPath, FileTreeNode node, RegExp query, int maxResults,
JsonArray<PathUtil> results) {
boolean isChildOfSearchPath = searchPath.containsPath(node.getNodePath());
JsonArray<FileTreeNode> children = node.getUnifiedChildren();
for (int i = 0;
i < children.size() && (results.size() < maxResults || maxResults == RETURN_ALL_RESULTS);
i++) {
if (children.get(i).isDirectory()) {
recurseTree(searchPath, children.get(i), query, maxResults, results);
// early-out, if finished recursing the search directory
if (searchPath.equals(children.get(i).getNodePath())) {
return;
}
} else if (isChildOfSearchPath && query.test(children.get(i).getName())) {
results.add(children.get(i).getNodePath());
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/SearchContainer.java | client/src/main/java/com/google/collide/client/search/SearchContainer.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.client.search;
import collide.client.util.Elements;
import com.google.collide.client.code.FileContent;
import com.google.collide.client.code.FileSelectedPlace;
import com.google.collide.client.history.Place;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.SearchResponse;
import com.google.collide.dto.SearchResult;
import com.google.collide.dto.Snippet;
import com.google.collide.json.client.JsoArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.AnchorElement;
import elemental.html.DivElement;
import elemental.html.SpanElement;
/**
* Container for search results, at least for those searches that have a results
* page. (Local search and search-and-replace do not...)
*
*/
public class SearchContainer extends UiComponent<SearchContainer.View> implements FileContent {
public interface Css extends CssResource {
String container();
String next();
String otherpage();
String pager();
String previous();
String second();
String snippet();
String thispage();
String title();
}
public interface Resources extends ClientBundle {
@Source("next_page.png")
ImageResource nextPage();
@Source("previous_page.png")
ImageResource prevPage();
@Source("SearchContainer.css")
Css searchContainerCss();
}
public static class View extends CompositeView<Void> {
Css css;
DivElement pager;
DivElement results;
public View(Css css) {
super(Elements.createDivElement(css.container()));
this.css = css;
createDom();
}
private void createDom() {
Element top = getElement();
results = Elements.createDivElement();
top.appendChild(results);
pager = Elements.createDivElement(css.pager());
top.appendChild(pager);
}
public void clear() {
results.removeFromParent();
pager.removeFromParent();
createDom();
}
}
private final String query;
private final Place currentPlace;
public SearchContainer(Place currentPlace, View view, final String query) {
super(view);
this.currentPlace = currentPlace;
this.query = query;
}
/**
* Updates with new results.
*
* @param message the message containing the new results.
*/
public void showResults(SearchResponse message) {
getView().clear();
showResultsImpl(
message.getPage(), message.getPageCount(), (JsoArray<SearchResult>) message.getResults());
}
@Override
public PathUtil filePath() {
return null;
}
@Override
public Element getContentElement() {
return getView().getElement();
}
@Override
public void onContentDisplayed() {
}
// TODO: Clean up the code below. It does not properly follow the
// View/Presenter contracts used by other UiComponents. It also makes many
// static references to Places on dispatch.
/**
* Updates the view to displays results and appropriate pager widgetry.
*
* @param page the page of "this" result page, one-based
* @param pageCount the total number of pages
* @param items the {@link SearchResult} items on this page.
*/
private void showResultsImpl(final int page, int pageCount, JsoArray<SearchResult> items) {
Css css = getView().css;
buildPager(page, pageCount, css);
for (int i = 0; i < items.size(); i++) {
SearchResult item = items.get(i);
DivElement outer = Elements.createDivElement();
if (i > 0) {
outer.setClassName(css.second());
}
final PathUtil path = new PathUtil(item.getTitle());
AnchorElement title = Elements.createAnchorElement(css.title());
title.setTextContent(item.getTitle());
if (item.getUrl() != null) {
// this is unusual, but allows search results to point outside of this
// workspace, e.g. to language API docs.
title.setHref(item.getUrl());
} else {
// this is the common case; the title will be a path in this workspace
// and clicking on the link should take us to its editor.
title.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
currentPlace.fireChildPlaceNavigation(
FileSelectedPlace.PLACE.createNavigationEvent(path));
}
});
}
outer.appendChild(title);
JsoArray<Snippet> snippets = (JsoArray<Snippet>) item.getSnippets();
for (int j = 0; j < snippets.size(); j++) {
DivElement snippetDiv = Elements.createDivElement(css.snippet());
final int lineNo = snippets.get(j).getLineNumber();
snippetDiv.setTextContent(lineNo + ": " + snippets.get(j).getSnippetText());
snippetDiv.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
// lineNo is 1-based, whereas the editor expects 0-based
int documentLineNo = lineNo - 1;
currentPlace.fireChildPlaceNavigation(
FileSelectedPlace.PLACE.createNavigationEvent(path, documentLineNo));
}
});
outer.appendChild(snippetDiv);
}
getView().results.appendChild(outer);
}
}
private void buildPager(final int page, final int pageCount, Css css) {
if (pageCount > 1) {
if (page > 1) {
DivElement previous = Elements.createDivElement(css.previous());
getView().pager.appendChild(previous);
previous.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
currentPlace.fireChildPlaceNavigation(
SearchPlace.PLACE.createNavigationEvent(query, page - 1));
}
});
}
if (page > 7) {
SpanElement elipsis = Elements.createSpanElement(css.thispage());
elipsis.setTextContent("...");
getView().pager.appendChild(elipsis);
}
// page numbers are one-based (i.e. human-oriented)
for (int i = page > 6 ? page - 6 : 1; i < pageCount + 1 && i < page + 6; i++) {
SpanElement counter =
Elements.createSpanElement(i == page ? css.thispage() : css.otherpage());
counter.setTextContent(Integer.toString(i));
getView().pager.appendChild(counter);
final int pageNumber = i;
counter.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
currentPlace.fireChildPlaceNavigation(
SearchPlace.PLACE.createNavigationEvent(query, pageNumber));
}
});
if (page + 7 < pageCount + 1) {
SpanElement elipsis = Elements.createSpanElement(css.thispage());
elipsis.setTextContent("...");
getView().pager.appendChild(elipsis);
}
}
if (page < pageCount) {
DivElement next = Elements.createDivElement(css.next());
getView().pager.appendChild(next);
next.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
currentPlace.fireChildPlaceNavigation(
SearchPlace.PLACE.createNavigationEvent(query, page + 1));
}
});
}
}
}
@Override
public void onContentDestroyed() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/SearchPlaceNavigationHandler.java | client/src/main/java/com/google/collide/client/search/SearchPlaceNavigationHandler.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.client.search;
import collide.client.filetree.FileTreeUiController;
import com.google.collide.client.AppContext;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.dto.SearchResponse;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.SearchImpl;
/**
* Navigation handler for the {@link SearchPlace}.
*
*/
public class SearchPlaceNavigationHandler extends PlaceNavigationHandler<
SearchPlace.NavigationEvent> {
private final AppContext context;
private final MultiPanel<?,?> contentArea;
private final FileTreeUiController fileTreeUiController;
private final Place currentPlace;
private SearchContainer searchContainer;
public SearchPlaceNavigationHandler(AppContext context,
MultiPanel<?,?> contentArea, FileTreeUiController fileTreeUiController,
Place currentPlace) {
this.context = context;
this.contentArea = contentArea;
this.fileTreeUiController = fileTreeUiController;
this.currentPlace = currentPlace;
searchContainer = null;
}
@Override
public void cleanup() {
contentArea.getToolBar().show();
}
@Override
protected void enterPlace(SearchPlace.NavigationEvent navigationEvent) {
fileTreeUiController.clearSelectedNodes();
if (searchContainer == null) {
// first entrance (later queries already from a search place don't go
// here)
searchContainer =
new SearchContainer(currentPlace,
new SearchContainer.View(context.getResources().searchContainerCss()),
navigationEvent.getQuery());
}
contentArea.setContent(searchContainer);
contentArea.getToolBar().hide();
StatusMessage message = new StatusMessage(
context.getStatusManager(), StatusMessage.MessageType.LOADING, "Searching...");
message.fireDelayed(200);
context.getFrontendApi().SEARCH.send(SearchImpl
.make()
.setQuery(navigationEvent.getQuery())
.setPage(navigationEvent.getPage()),
new ApiCallback<SearchResponse>() {
@Override
public void onFail(FailureReason reason) {
new StatusMessage(context.getStatusManager(), StatusMessage.MessageType.ERROR,
"Search failed in 3 attempts. Try again later.").fire();
}
@Override
public void onMessageReceived(SearchResponse message) {
searchContainer.showResults(message);
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/FileNameSearch.java | client/src/main/java/com/google/collide/client/search/FileNameSearch.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.client.search;
import collide.client.filetree.FileTreeModel;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonArray;
import com.google.gwt.regexp.shared.RegExp;
/**
* Listens to the file model changes and handles building and searching the file
* index
*
*
*/
public interface FileNameSearch {
/**
* When passed in for maxResults this will return all results in the tree.
*/
public static final int RETURN_ALL_RESULTS = 0;
/**
* Retrieves matches from the index given a query
*
* @param query The user query
* @param maxResults The maximum number of results to return
*
* @return An array of file paths which match the query
*/
JsonArray<PathUtil> getMatches(RegExp query, int maxResults);
/**
* Retrieves matches from the index that are at or below the supplied path
*
* @param searchPath The path to restrict the search to
*
* @return An array of file paths which match the query
*/
JsonArray<PathUtil> getMatchesRelativeToPath(PathUtil searchPath, RegExp query, int maxResults);
/**
* Sets the file tree model to search
*/
void setFileTreeModel(FileTreeModel model);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/SearchPlace.java | client/src/main/java/com/google/collide/client/search/SearchPlace.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.client.search;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceConstants;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
/**
* @{link Place} for the Workspace search results page.
*/
public class SearchPlace extends Place {
public class NavigationEvent extends PlaceNavigationEvent<SearchPlace> {
public static final String QUERY_KEY = "q";
public static final String PAGE_KEY = "p";
private final String query;
private final int page;
private NavigationEvent(String query) {
super(SearchPlace.this);
this.query = query;
this.page = 1;
}
private NavigationEvent(String query, int page) {
super(SearchPlace.this);
this.query = query;
this.page = page;
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> map = JsoStringMap.create();
map.put(QUERY_KEY, query);
map.put(PAGE_KEY, Integer.toString(page));
return map;
}
public String getQuery() {
return query;
}
public int getPage() {
return page;
}
}
public static final SearchPlace PLACE = new SearchPlace();
private SearchPlace() {
super(PlaceConstants.WORKSPACE_SEARCH_PLACE_NAME);
}
@Override
public PlaceNavigationEvent<SearchPlace> createNavigationEvent(
JsonStringMap<String> decodedState) {
int page = 1;
String pageString = decodedState.get(NavigationEvent.PAGE_KEY);
if (pageString != null) {
page = Integer.parseInt(pageString);
}
return new NavigationEvent(decodedState.get(NavigationEvent.QUERY_KEY), page);
}
/**
* @param query the query expression to search on
* @return a new navigation event
*/
public PlaceNavigationEvent<SearchPlace> createNavigationEvent(String query) {
return new NavigationEvent(query);
}
/**
* @param query the query expression to search on
* @return a new navigation event
*/
public PlaceNavigationEvent<SearchPlace> createNavigationEvent(String query, int page) {
return new NavigationEvent(query, page);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/AbstractActionSection.java | client/src/main/java/com/google/collide/client/search/awesomebox/AbstractActionSection.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.client.search.awesomebox;
import collide.client.util.CssUtils;
import com.google.collide.client.search.awesomebox.AwesomeBox.Resources;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.StringUtils;
/**
* Renders actions which are filtered via query. Meant to allow easy
* implementation of a large list of actions which can quickly be filtered.
*
* NOTE: This section adds all items to the DOM and hides/shows them, it will
* not handle dynamic lists nor is it particularly DOM efficient.
*
*/
public abstract class AbstractActionSection<T extends AbstractActionSection.FilteredActionItem>
extends AbstractAwesomeBoxSection<T> {
protected final int maxResults;
private final JsonArray<T> allActions;
public static abstract class FilteredActionItem extends ActionItem {
private final String text;
public FilteredActionItem(Resources res, String text) {
super(res, text);
this.text = text.toLowerCase();
}
public FilteredActionItem(Resources res, String text, int modifiers, String shortcutKey) {
super(res, text);
this.text = text.toLowerCase();
getElement().insertBefore(AwesomeBoxUtils.createSectionShortcut(res, modifiers, shortcutKey),
getElement().getFirstChild());
}
/**
* @return true to show as soon as the AwesomeBox is focused.
*/
public abstract boolean onShowing();
/**
* Return true for this item to be visible.
*/
public boolean onQueryChanged(String query) {
return !StringUtils.isNullOrWhitespace(query) && text.contains(query.toLowerCase());
}
}
public AbstractActionSection(AwesomeBox.Resources res, int maxResults) {
super(res);
this.maxResults = maxResults;
sectionElement = AwesomeBoxUtils.createSectionContainer(res);
allActions = getAllActions();
initializeDom();
}
/**
* Returns the header title for this section.
*/
protected abstract String getTitle();
/**
* Creates all DOM for all items in getAllActions hiding them by default.
*/
protected void initializeDom() {
for (int i = 0; i < allActions.size(); i++) {
CssUtils.setDisplayVisibility2(allActions.get(i).getElement(), false);
sectionElement.appendChild(allActions.get(i).getElement());
}
}
@Override
public boolean onQueryChanged(final String query) {
listItems.clear();
updateItemVisibility(new ItemConditionCallback<T>() {
@Override
public boolean isCondition(T item) {
return item.onQueryChanged(query);
}
});
return listItems.size() > 0;
}
@Override
public boolean onShowing(AwesomeBox awesomeBox) {
listItems.clear();
updateItemVisibility(new ItemConditionCallback<T>() {
@Override
public boolean isCondition(T item) {
return item.onShowing();
}
});
return listItems.size() > 0;
}
/**
* Override to provide a list of actions to be added to the DOM. This will be
* cached at construction time within the AbstractActionSection.
*/
protected abstract JsonArray<T> getAllActions();
private interface ItemConditionCallback<T extends FilteredActionItem> {
public boolean isCondition(T item);
}
private void updateItemVisibility(ItemConditionCallback<T> callback) {
for (int i = 0, r = 0; i < allActions.size(); i++) {
if (r < maxResults && callback.isCondition(allActions.get(i))) {
CssUtils.setDisplayVisibility2(allActions.get(i).getElement(), true);
listItems.add(allActions.get(i));
r++;
} else {
CssUtils.setDisplayVisibility2(allActions.get(i).getElement(), false);
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBox.java | client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBox.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.client.search.awesomebox;
import collide.client.common.CommonResources;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.search.awesomebox.AwesomeBoxModel.ContextChangeListener;
import com.google.collide.client.search.awesomebox.host.AbstractAwesomeBoxComponent;
import com.google.collide.client.search.awesomebox.host.ComponentHost;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.client.util.UserActivityManager;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.HasView;
import com.google.collide.shared.util.StringUtils;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Timer;
import elemental.dom.Node;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.KeyboardEvent;
import elemental.events.KeyboardEvent.KeyCode;
import elemental.events.MouseEvent;
import elemental.html.HTMLCollection;
/**
* The main controller and view for the awesome box
*
*/
/*
* The autohide component was not used since this component does not strictly
* utilize a full auto-hide type functionality. The input box is still part of
* the control (for styling and ui reasons) but does not hide.
*/
// TODO: In the future lets add some sort of query ranking/processor.
public class AwesomeBox extends AbstractAwesomeBoxComponent implements HasView<AwesomeBox.View> {
/**
* Creates a new AwesomeBox component and returns it. Though the class
* instance will be unique, the underlying model will remain consistent among
* all AwesomeBox's. This allows the AwesomeBox to be added at different
* places but rely on only one underlying set of data for a consistent
* experience.
*/
public static AwesomeBox create(AppContext context) {
return new AwesomeBox(new AwesomeBox.View(context.getResources()), context.getAwesomeBoxModel(),
context.getUserActivityManager());
}
public interface Css extends CssResource {
/* Generic Awesome Box and Container Styles */
String awesomeContainer();
String dropdownContainer();
String closeButton();
String awesomeBox();
/* Generic Section Styles */
String section();
String selected();
String sectionItem();
String shortcut();
}
public interface SectionCss extends CssResource {
/* Goto File Actions */
String fileItem();
String folder();
/* Goto Branch Actions */
String branchIcon();
/* Find Actions */
String searchIcon();
}
public interface Resources extends CommonResources.BaseResources, Tooltip.Resources {
@Source({"AwesomeBox.css", "collide/client/common/constants.css"})
public Css awesomeBoxCss();
@Source("AwesomeBoxSection.css")
public SectionCss awesomeBoxSectionCss();
}
/**
* Defines an AwesomeBox section which is hidden until the AwesomeBox is
* focused.
*
*/
public interface AwesomeBoxSection {
/**
* Actions that can be taken when a section item is selected.
*/
public enum ActionResult {
/**
* An action was performed and the AwesomeBox should be closed.
*/
CLOSE,
/**
* An item was selected and the section should receive selection.
*/
SELECT_ITEM,
/**
* Do nothing.
*/
DO_NOTHING
}
/**
* Called when the section has been added to a context. Any context related
* setup should be performed here.
*/
public void onAddedToContext(AwesomeBoxContext context);
/**
* Called when the query in the AwesomeBox is modified and the section may
* need to be filtered.
*
* If the section currently has a selection it should be removed upon query
* change.
*
* @return true if the section has results and should be visible.
*/
public boolean onQueryChanged(String query);
/**
* Called when the global context has been changed to a context containing
* this section and any previous state should most likely be removed.
*/
public void onContextChanged(AwesomeBoxContext context);
/**
* Called when the AwesomeBox is focused and in a context that this section
* is a member of. The section should prepare itself for the AwesomeBox to
* be empty.
*
* @return true if section should be immediately visible in the dropdown.
*/
public boolean onShowing(AwesomeBox awesomeBox);
/**
* Called when the AwesomeBox panel is hidden due to loss of focus or
* external click.
*/
public void onHiding(AwesomeBox awesomeBox);
/**
* Called to move the selection down or up. The contract for this method
* specifies that the section will return false if it is at a boundary and
* unable to move the selection or does not accept selection. When unable to
* move selection it should not assume it has lost selection until
* onClearSelection is called.
*
* @param moveDown true if the selection is moving down, false if up. If the
* section currently has no selection it should select it's first
* item when moveDown is true and it's last item if moveDown is
* false.
*
* @return true if the selection was moved successfully
*/
/*
* This method off-loads selection onto the sections with little expectation
* set forth by the AwesomeBox. This allows for sections which are
* non-standard and can be selected in different ways (or not at all).
*/
public boolean onMoveSelection(boolean moveDown);
/**
* The selection has been reset. If the section has any item selected it
* should clear the selection.
*/
public void onClearSelection();
/**
* The enter key has been pressed and the target is the current selection in
* this section. The necessary action should be performed.
*
* @return Appropriate action to take after action has been performed
*/
public ActionResult onActionRequested();
/**
* Called when the tab completion key is pressed in the AwesomeBox and the
* section currently has selection.
*
* @return A string representing the item currently selected. Null or empty
* will cancel the completion.
*/
public String onCompleteSelection();
/**
* Called when a click event is received where the target is a child of this
* section. Typically a section should call mouseEvent.preventDefault() to
* prevent native selection and focus from being transferred.
*
* @param mouseEvent The location of the click.
*
* @return The appropriate action for the AwesomeBox to take.
*/
public ActionResult onSectionClicked(MouseEvent mouseEvent);
/**
* Returns the div element which wraps this section's contents.
*/
public elemental.html.DivElement getElement();
}
/**
* Callback used when iterating through sections.
*/
public interface SectionIterationCallback {
public boolean onIteration(AwesomeBoxSection section);
}
private static final String NO_QUERY = "";
private final AwesomeBoxModel model;
private final UserActivityManager userActivityManager;
private final View view;
/** A hacky means to ensure our keyup handler ignores enter after show */
private boolean ignoreEnterKeyUp = false;
/**
* Tracks the last query we have dispatched to ensure that we don't duplicate
* query changed events.
*/
private String lastDispatchedQuery = NO_QUERY;
protected AwesomeBox(View view, AwesomeBoxModel model, UserActivityManager userActivityManager) {
super(HideMode.AUTOHIDE, HiddenBehavior.STAY_ACTIVE, "Type to find files and features");
this.view = view;
this.model = model;
this.userActivityManager = userActivityManager;
view.setDelegate(new ViewEventsImpl());
model.getContextChangeListener().add(new ContextChangeListener() {
@Override
public void onContextChanged(boolean contextAlreadyActive) {
if (contextAlreadyActive) {
selectQuery();
} else {
refreshView();
}
}
});
}
/**
* Returns the view for this component.
*/
@Override
public View getView() {
return view;
}
/**
* Refreshes the view by reloading all the section DOM and clearing selection.
*/
private void refreshView() {
getView().clearSections();
getView().awesomeBoxInput.setAttribute(
"placeholder", getModel().getContext().getPlaceholderText());
getView().setInputEmptyStyle(getModel().getContext().getAlwaysShowCloseButton());
JsonArray<AwesomeBoxSection> sections = getModel().getCurrentSections();
for (int i = 0; i < sections.size(); i++) {
AwesomeBoxSection section = sections.get(i);
if (isActive()) {
boolean showInitial = section.onShowing(this);
CssUtils.setDisplayVisibility2(section.getElement(),
StringUtils.isNullOrEmpty(getQuery()) ? showInitial : section.onQueryChanged(
getQuery()));
}
getView().getElement().appendChild(section.getElement());
}
// If the view is expanded, try to get back to a default state of some kind.
if (isActive()) {
getModel().selectFirstItem();
getView().awesomeBoxInput.focus();
}
}
@Override
public elemental.dom.Element getElement() {
return getView().getElement();
}
@Override
public String getTooltipText() {
return "Press Alt+Enter to quickly access the AwesomeBox";
}
AwesomeBoxModel getModel() {
return model;
}
/**
* Retrieves the current query of the AwesomeBox.
*/
public String getQuery() {
return getView().awesomeBoxInput.getValue();
}
/**
* Sets the query of the AwesomeBox, this will not trigger a query changed
* event.
*/
public void setQuery(String query) {
getView().awesomeBoxInput.setValue(query);
getView().setInputEmptyStyle(getModel().getContext().getAlwaysShowCloseButton());
}
/**
* Selects whatever text is in the Awesomebox input.
*/
public void selectQuery() {
getView().awesomeBoxInput.select();
}
@Override
public void onShow(ComponentHost host, ShowReason reason) {
super.onShow(host, reason);
// We assume the alt+enter shortcut focused us (and its a keydown listener).
ignoreEnterKeyUp = reason == ShowReason.OTHER;
JsonArray<AwesomeBoxSection> sections = getModel().getCurrentSections();
for (int i = 0; i < sections.size(); i++) {
AwesomeBoxSection section = sections.get(i);
CssUtils.setDisplayVisibility2(section.getElement(), section.onShowing(AwesomeBox.this));
getView().getElement().appendChild(section.getElement());
}
getModel().selectFirstItem();
// Show the panel
getView().setInputEmptyStyle(getModel().getContext().getAlwaysShowCloseButton());
}
@Override
public void onHide() {
super.onHide();
getModel().clearSelection();
JsonArray<AwesomeBoxSection> sections = getModel().getCurrentSections();
for (int i = 0; i < sections.size(); i++) {
AwesomeBoxSection section = sections.get(i);
section.onHiding(AwesomeBox.this);
CssUtils.setDisplayVisibility2(section.getElement(), false);
}
lastDispatchedQuery = NO_QUERY;
getView().awesomeBoxInput.setValue("");
getView().setInputEmptyStyle(false);
}
/**
* Focuses the AwesomeBox view.
*/
@Override
public void focus() {
getView().awesomeBoxInput.focus();
}
private interface ViewEvents {
public void onCloseClicked();
/**
* The AwesomeBox input has lost focus.
*/
public void onBlur();
/**
* Called when the AwesomeBox panel is clicked.
*/
public void onClick(MouseEvent mouseEvent);
/**
* Fired when a key down event occurs on the AwesomeBox input.
*/
public void onInputKeyDown(KeyboardEvent keyEvent);
public void onKeyUp(KeyboardEvent keyEvent);
}
private class ViewEventsImpl implements ViewEvents {
@Override
public void onBlur() {
hide();
}
@Override
public void onClick(MouseEvent mouseEvent) {
mouseEvent.stopPropagation();
boolean isInInput = getView().mainInput.isOrHasChild((Element) mouseEvent.getTarget());
boolean isInDropDown = getView().getElement().contains((Node) mouseEvent.getTarget());
if (mouseEvent.getButton() == MouseEvent.Button.PRIMARY && isInDropDown) {
sectionClicked(mouseEvent);
} else if (!isInInput) {
mouseEvent.preventDefault();
}
}
@SuppressWarnings("incomplete-switch")
private void sectionClicked(MouseEvent mouseEvent) {
JsonArray<AwesomeBoxSection> sections = getModel().getCurrentSections();
for (int i = 0; i < sections.size(); i++) {
AwesomeBoxSection section = sections.get(i);
if (section.getElement().contains((Node) mouseEvent.getTarget())) {
switch (section.onSectionClicked(mouseEvent)) {
case CLOSE:
hide();
break;
case SELECT_ITEM:
/**
* We assume the section has internally handled selection, set
* selection only clears selection if it was on another section
* previously.
*/
getModel().setSelection(section);
break;
}
return;
}
}
}
@Override
public void onKeyUp(KeyboardEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyCode.ENTER) {
if (ignoreEnterKeyUp) {
ignoreEnterKeyUp = false;
return;
}
AwesomeBoxSection section =
getModel().getSelection(AwesomeBoxModel.SelectMode.TRY_AUTOSELECT_FIRST_ITEM);
if (section != null
&& section.onActionRequested() == AwesomeBoxSection.ActionResult.CLOSE) {
hide();
}
} else if (!lastDispatchedQuery.equals(getQuery())) {
lastDispatchedQuery = getQuery();
// TODO: allow context to choose rather query change is batched.
deferQueryChangeTimer.cancel();
deferQueryChangeTimer.schedule(30);
}
}
/**
* Timer which defers query change until 50ms after the user has stopped
* typing. This prevents spamming the event if the user is typing in a large
* amount of text quickly.
*/
private final Timer deferQueryChangeTimer = new Timer() {
@Override
public void run() {
dispatchQueryChangeEvent();
}
};
private void dispatchQueryChangeEvent() {
// force selection to be cleared before a query change
getModel().clearSelection();
JsonArray<AwesomeBoxSection> sections = getModel().getCurrentSections();
for (int i = 0; i < sections.size(); i++) {
AwesomeBoxSection section = sections.get(i);
CssUtils.setDisplayVisibility2(
section.getElement(), section.onQueryChanged(getView().awesomeBoxInput.getValue()));
}
// Select the first item in our list
getModel().selectFirstItem();
}
private void changeSelection(final boolean moveDown) {
AwesomeBoxSection section = getModel().getSelection(AwesomeBoxModel.SelectMode.DEFAULT);
if (section == null) {
// if null then we should reset selection to the top or the bottom
getModel().selectFirstItem();
} else if (!section.onMoveSelection(moveDown)) {
getModel().iterateFrom(section, moveDown, new SectionIterationCallback() {
@Override
public boolean onIteration(AwesomeBoxSection curSection) {
return !getModel().trySetSelection(curSection, moveDown);
}
});
// if nothing is selected on iteration then the selection doesn't change
}
}
@Override
public void onInputKeyDown(KeyboardEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyCode.UP) {
changeSelection(false);
} else if (keyEvent.getKeyCode() == KeyCode.DOWN) {
changeSelection(true);
} else if (keyEvent.getKeyCode() == KeyCode.TAB) {
handleTabComplete();
if (getModel().getContext().getPreventTab()) {
keyEvent.preventDefault();
}
}
dispatchEmptyAwesomeBoxCheck();
userActivityManager.markUserActive();
// For a few keys the default is always prevented.
if (keyEvent.getKeyCode() == KeyCode.UP || keyEvent.getKeyCode() == KeyCode.DOWN) {
keyEvent.preventDefault();
} else {
getModel().getContext().getShortcutManager().onKeyDown(keyEvent);
}
}
/**
* Handles tab based query completion.
*/
private void handleTabComplete() {
AwesomeBoxSection section = getModel().getSelection(AwesomeBoxModel.SelectMode.DEFAULT);
if (section != null) {
String completion = section.onCompleteSelection();
if (completion != null) {
// TODO: Potentially highlight completed part of the query
getView().awesomeBoxInput.setValue(completion);
}
}
}
private void dispatchEmptyAwesomeBoxCheck() {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
getView().setInputEmptyStyle(getModel().getContext().getAlwaysShowCloseButton());
}
});
}
@Override
public void onCloseClicked() {
hide();
}
}
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("AwesomeBox.ui.xml")
interface AwesomeBoxUiBinder extends UiBinder<Element, View> {
}
private static AwesomeBoxUiBinder uiBinder = GWT.create(AwesomeBoxUiBinder.class);
@UiField(provided = true)
final Resources res;
@UiField
InputElement awesomeBoxInput;
@UiField
DivElement closeButton;
@UiField
DivElement mainInput;
public View(Resources res) {
this.res = res;
setElement(Elements.asJsElement(uiBinder.createAndBindUi(this)));
attachHandlers();
}
/**
* Attaches several handlers to the awesome box input and the container.
*/
private void attachHandlers() {
Elements.asJsElement(awesomeBoxInput).setOnblur(new EventListener() {
@Override
public void handleEvent(Event event) {
// blur removes the focus then we hide the actual panel
if (getDelegate() != null) {
getDelegate().onBlur();
}
}
});
Elements.asJsElement(awesomeBoxInput).setOnkeydown(new EventListener() {
@Override
public void handleEvent(Event event) {
KeyboardEvent keyEvent = (KeyboardEvent) event;
if (getDelegate() != null) {
getDelegate().onInputKeyDown(keyEvent);
}
}
});
Elements.asJsElement(closeButton).setOnclick(new EventListener() {
@Override
public void handleEvent(Event arg0) {
getDelegate().onCloseClicked();
}
});
getElement().setOnkeyup(new EventListener() {
@Override
public void handleEvent(Event event) {
KeyboardEvent keyEvent = (KeyboardEvent) event;
if (getDelegate() != null) {
getDelegate().onKeyUp(keyEvent);
}
}
});
getElement().setOnmousedown(new EventListener() {
@Override
public void handleEvent(Event event) {
MouseEvent mouseEvent = (MouseEvent) event;
if (getDelegate() != null) {
getDelegate().onClick(mouseEvent);
}
}
});
}
/**
* Removes all sections DOM from the AwesomeBox.
*/
private void clearSections() {
HTMLCollection elements = getElement().getChildren();
for (int l = elements.getLength() - 1; l >= 0; l--) {
if (elements.item(l) != mainInput) {
elements.item(l).removeFromParent();
}
}
}
/**
* Sets the empty or non-empty styles of the AwesomeBox.
*/
private void setInputEmptyStyle(boolean alwaysShowClose) {
boolean isEmpty = StringUtils.isNullOrEmpty(awesomeBoxInput.getValue());
// Intentional use of setDisplayVisibility
CssUtils.setDisplayVisibility(Elements.asJsElement(closeButton), !isEmpty || alwaysShowClose);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBoxModel.java | client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBoxModel.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.client.search.awesomebox;
import com.google.collide.client.search.awesomebox.AwesomeBox.AwesomeBoxSection;
import com.google.collide.client.search.awesomebox.AwesomeBox.SectionIterationCallback;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerManager.Dispatcher;
/**
* The underlying AwesomeBox model used accross all AwesomeBox instances.
*/
// TODO: Provide push/pop context functionality so its much easier to go
// into a temporarily restricted context with limited actions.
public class AwesomeBoxModel {
/**
* Called when the context has been updated in the AwesomeBox model.
*/
public interface ContextChangeListener {
/**
* @param contextAlreadyActive true if
* {@link AwesomeBoxModel#changeContext(AwesomeBoxContext)} was
* called with a context which is already active. This case is just
* for informational purposes and no changes are actually performed.
*/
public void onContextChanged(boolean contextAlreadyActive);
}
/**
* Modes which change the behavior of getSelection.
*/
public enum SelectMode {
/**
* Returns null if there is no selection.
*/
DEFAULT,
/**
* Will attempt to select the first selectable item in the drop-down if
* there isn't currently a selection.
*/
TRY_AUTOSELECT_FIRST_ITEM
}
/**
* Modes which change the hide behavior of the dialog.
*/
public enum HideMode {
/**
* The component will autohide when the user clicks outside of the
* AwesomeBox container or the actual input loses focus.
*/
AUTOHIDE,
/**
* The component will autohide only if user clicks outside of the AwesomeBox
* container. This allows the AwesomeBox input to be hidden but the popup to
* stay visible.
*/
DONT_HIDE_ON_INPUT_LOSE_FOCUS,
/**
* The component must be manually closed or programatically closed.
*/
NO_AUTOHIDE,
}
private AwesomeBoxContext currentContext;
private AwesomeBoxSection selectedSection;
private final ListenerManager<ContextChangeListener> listener;
public AwesomeBoxModel() {
currentContext = AwesomeBoxContext.DEFAULT;
listener = ListenerManager.create();
}
/**
* Retrieves the current AwesomeBox autohide behavior.
*/
public HideMode getHideMode() {
return currentContext.getHideMode();
}
/**
* Attempts to change the selection to the new section, if the section refuses
* it will return false. If the section accepts selection any old selection
* will be cleared. In the special case where the section is already selected
* it will clear the selection and select the first or last item depending on
* selectFirstItem.
*
* @param selectFirstItem True to select the first item, false to select the
* last.
*
* @return true if the selection is set to the new section.
*/
boolean trySetSelection(AwesomeBoxSection section, boolean selectFirstItem) {
if (selectedSection == section) {
selectedSection.onClearSelection();
selectedSection.onMoveSelection(selectFirstItem);
} else if (section.onMoveSelection(selectFirstItem)) {
if (selectedSection != null) {
selectedSection.onClearSelection();
}
selectedSection = section;
} else {
return false;
}
return true;
}
/**
* Retrieves the currently selected section.
*
* @return null if there is no selection.
*/
AwesomeBoxSection getSelection(SelectMode mode) {
if (selectedSection == null && mode == SelectMode.TRY_AUTOSELECT_FIRST_ITEM) {
selectFirstItem();
}
return selectedSection;
}
/**
* Updates the model selection. Without checking if the section will accept
* selection. TrySetSelection should be preferred if you can't be sure the
* section will accept selection.
*/
void setSelection(AwesomeBoxSection section) {
if (selectedSection != section && selectedSection != null) {
selectedSection.onClearSelection();
}
selectedSection = section;
}
void clearSelection() {
if (selectedSection != null) {
selectedSection.onClearSelection();
}
selectedSection = null;
}
/**
* Will iterate through the sections until it finds the first section which
* will accept selection and returns it.
*
* @return null if there are no no sections or no section accepts selection.
*/
AwesomeBoxSection selectFirstItem() {
if (selectedSection != null) {
selectedSection.onClearSelection();
}
JsonArray<AwesomeBoxSection> sections = currentContext.getSections();
for (int i = 0; i < sections.size(); i++) {
if (sections.get(i).onMoveSelection(true)) {
selectedSection = sections.get(i);
return sections.get(i);
}
}
return null;
}
public ListenerManager<ContextChangeListener> getContextChangeListener() {
return listener;
}
/**
* @return the current context of the AwesomeBox.
*/
public AwesomeBoxContext getContext() {
return currentContext;
}
/**
* Changes to the specified context.
*/
public void changeContext(AwesomeBoxContext context) {
if (currentContext == context) {
listener.dispatch(new Dispatcher<ContextChangeListener>() {
@Override
public void dispatch(ContextChangeListener listener) {
listener.onContextChanged(true);
}
});
return;
}
clearSelection();
currentContext = context;
// Notify contexts of change event
JsonArray<AwesomeBoxSection> sections = context.getSections();
for (int i = 0; i < sections.size(); i++) {
sections.get(i).onContextChanged(currentContext);
}
// Dispatch the onContextChanged event
listener.dispatch(new Dispatcher<ContextChangeListener>() {
@Override
public void dispatch(ContextChangeListener listener) {
listener.onContextChanged(false);
}
});
}
/**
* @return The sections in the current context.
*/
public JsonArray<AwesomeBoxSection> getCurrentSections() {
return currentContext.getSections();
}
/**
* Iterates through the section list starting at the specified section
* (exclusive). This is a helper function that simplifies finding the next or
* previous section.
*
* @param startSection Section to start iterating from (exclusive).
* @param forward Direction to iterate.
* @param sectionIterationCallback Callback to call for each iteration.
*/
void iterateFrom(AwesomeBoxSection startSection, boolean forward,
SectionIterationCallback sectionIterationCallback) {
JsonArray<AwesomeBoxSection> sections = currentContext.getSections();
for (int i = 0; i < sections.size(); i++) {
if (startSection == sections.get(i)) {
if (forward) {
iterateForward(i + 1, sectionIterationCallback);
} else {
iterateBackwards(i - 1, sectionIterationCallback);
}
return;
}
}
}
/**
* Iterates the section list starting at the given index moving backwards to
* the beginning.
*/
private void iterateBackwards(int index, SectionIterationCallback sectionIterationCallback) {
JsonArray<AwesomeBoxSection> sections = currentContext.getSections();
for (int i = index; i >= 0; i--) {
if (!sectionIterationCallback.onIteration(sections.get(i))) {
return;
}
}
}
/**
* Iterates the section list starting at the given index and moving forward to
* the end.
*/
private void iterateForward(int index, SectionIterationCallback sectionIterationCallback) {
JsonArray<AwesomeBoxSection> sections = currentContext.getSections();
for (int i = index; i < sections.size(); i++) {
if (!sectionIterationCallback.onIteration(sections.get(i))) {
return;
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/OutlineViewAwesomeBoxSection.java | client/src/main/java/com/google/collide/client/search/awesomebox/OutlineViewAwesomeBoxSection.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.client.search.awesomebox;
import collide.client.util.Elements;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.search.awesomebox.AwesomeBox.Resources;
import com.google.collide.client.util.ViewListController;
import com.google.collide.client.workspace.outline.OutlineModel;
import com.google.collide.client.workspace.outline.OutlineNode;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.HasView;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Preconditions;
import elemental.dom.Element;
import elemental.html.SpanElement;
/**
* An awesome box section which displays the classes/functions/variables in your file.
*
*/
public class OutlineViewAwesomeBoxSection
extends AbstractAwesomeBoxSection<OutlineViewAwesomeBoxSection.OutlineItem> {
/**
* An item in the awesomebox which displays an OutlineNode.
*/
public static class OutlineItem extends AbstractAwesomeBoxSection.ActionItem
implements HasView<OutlineItem.View> {
/** A handler called when a node is selected */
public interface SelectedHandler {
void onSelected(OutlineNode node);
}
/** A factory which can create an {@link OutlineItem} */
public static class OutlineItemFactory implements ViewListController.Factory<OutlineItem> {
private final Resources res;
private final SelectedHandler handler;
public OutlineItemFactory(Resources res, SelectedHandler handler) {
this.res = res;
this.handler = handler;
}
@Override
public OutlineItem create(Element container) {
View v = new View(res);
container.appendChild(v.getElement());
return new OutlineItem(res, v, handler);
}
}
public static class View extends CompositeView<Void> {
private final SpanElement name;
private final SpanElement type;
public View(Resources res) {
super(AwesomeBoxUtils.createSectionItem(res));
name = Elements.createSpanElement();
type = Elements.createSpanElement();
type.getStyle().setColor("#AAA");
getElement().appendChild(name);
getElement().appendChild(type);
}
}
private final View view;
private final SelectedHandler handler;
private OutlineNode node;
private OutlineItem(Resources res, View view, SelectedHandler handler) {
super(res, view.getElement());
Preconditions.checkNotNull(handler, "Handle for outline element cannot be null");
this.view = view;
this.handler = handler;
}
public void setOutlineNode(OutlineNode node) {
this.node = node;
view.name.setTextContent(node.getName());
view.type.setTextContent(" - " + node.getType().toString().toLowerCase());
}
@Override
public String completeQuery() {
return node.getName();
}
@Override
public ActionResult doAction(ActionSource source) {
handler.onSelected(node);
return ActionResult.CLOSE;
}
@Override
public View getView() {
return view;
}
}
/** The maximum number of results to display */
private static final int MAX_RESULTS = 6;
/** A prefix which can be used to force the awesomebox to show only outline results */
private static final String QUERY_PREFIX = "@";
private final ViewListController<OutlineItem> listController;
private OutlineModel model;
private Editor editor;
public OutlineViewAwesomeBoxSection(Resources res) {
super(res);
sectionElement = AwesomeBoxUtils.createSectionContainer(res);
this.listController = new ViewListController<OutlineItem>(
sectionElement, listItems.asJsonArray(),
new OutlineItem.OutlineItemFactory(res, new OutlineItem.SelectedHandler() {
@Override
public void onSelected(OutlineNode node) {
if (editor != null) {
editor.scrollTo(node.getLineNumber(), node.getColumn());
editor.getFocusManager().focus();
}
}
}));
}
@Override
public boolean onQueryChanged(String query) {
listController.reset();
if (!StringUtils.isNullOrWhitespace(query) && !query.equals(QUERY_PREFIX) && model != null) {
traverseNode(model.getRoot(), query.startsWith(QUERY_PREFIX) ? query.substring(1) : query);
}
listController.prune();
return listController.size() > 0;
}
@Override
public boolean onShowing(AwesomeBox awesomeBox) {
return false;
}
public void setOutlineModelAndEditor(OutlineModel model, Editor editor) {
this.model = model;
this.editor = editor;
}
private void traverseNode(OutlineNode parent, String query) {
if (listController.size() >= MAX_RESULTS || parent == null) {
return;
}
JsonArray<OutlineNode> children = parent.getChildren();
for (int i = 0; listController.size() < MAX_RESULTS && i < children.size(); i++) {
OutlineNode node = children.get(i);
if (node.getName().contains(query)) {
OutlineItem item = listController.next();
item.setOutlineNode(node);
}
traverseNode(children.get(i), query);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBoxUtils.java | client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBoxUtils.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.client.search.awesomebox;
import collide.client.util.Elements;
import com.google.collide.client.ClientOs;
import com.google.collide.client.search.awesomebox.AwesomeBox.Resources;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.gwt.core.client.GWT;
/**
* Static Utility Methods for AwesomeBox Sections
*/
public class AwesomeBoxUtils {
/* Section Helper Functions */
public static elemental.html.DivElement createSectionContainer(Resources res) {
return Elements.createDivElement(res.awesomeBoxCss().section());
}
public static elemental.html.DivElement createSectionItem(Resources res) {
return Elements.createDivElement(res.awesomeBoxCss().sectionItem());
}
/**
* Creates a element with the OS appropriate text for the shortcut consisting
* of the specified modifier keys and character.
*
* @param modifiers A binarySuffix OR of the appropriate ModifierKeys constants
* @return a div containing the shortcut text
*/
public static elemental.html.DivElement createSectionShortcut(
Resources res, int modifiers, String shortcutKey) {
elemental.html.DivElement element = Elements.createDivElement(res.awesomeBoxCss().shortcut());
// Builds a shortcut key string based on the modifiers given
element.setTextContent(formatShortcutAsString(modifiers, shortcutKey));
return element;
}
private static ClientOs clientOs = GWT.create(ClientOs.class);
/**
* Converts a shortcut based on ModifierKeys constants and a character to it's
* string abbreviation. This is OS specific.
*/
public static String formatShortcutAsString(int modifiers, String shortcutKey) {
StringBuilder builder = new StringBuilder();
if ((modifiers & ModifierKeys.ACTION) == ModifierKeys.ACTION) {
builder.append(clientOs.actionKeyLabel());
} else if ((modifiers & ModifierKeys.CTRL) == ModifierKeys.CTRL) {
/*
* This is an "else" on "ACTION" since if the platform treats CTRL as
* ACTION, we don't want to print this
*/
builder.append(clientOs.ctrlKeyLabel());
}
if ((modifiers & ModifierKeys.ALT) == ModifierKeys.ALT) {
builder.append(clientOs.altKeyLabel());
}
if ((modifiers & ModifierKeys.SHIFT) == ModifierKeys.SHIFT) {
builder.append(clientOs.shiftKeyLabel());
}
builder.append(shortcutKey);
return builder.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/PrimaryWorkspaceActionSection.java | client/src/main/java/com/google/collide/client/search/awesomebox/PrimaryWorkspaceActionSection.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.client.search.awesomebox;
import com.google.collide.client.code.FileSelectionController.FileOpenedEvent;
import com.google.collide.client.history.Place;
import com.google.collide.client.search.awesomebox.components.FindReplaceComponent.FindMode;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerManager.Dispatcher;
/**
* Contains the primary actions for a workspace that are always shown and quickly accesible by a
* user.
*
*/
public class PrimaryWorkspaceActionSection
extends AbstractActionSection<AbstractActionSection.FilteredActionItem> {
/**
* The abstract action section usually filters actions so it expects a maximum number of actions
* to display.
*/
public static final int NUMBER_OF_ACTIONS = 2;
public interface FindActionSelectedCallback {
public void onSelected(FindMode mode);
}
private final ListenerManager<FindActionSelectedCallback> listenerManager;
private boolean showFindAndReplace = false;
private Place currentPlace;
public PrimaryWorkspaceActionSection(AwesomeBox.Resources res) {
super(res, NUMBER_OF_ACTIONS);
this.listenerManager = ListenerManager.create();
}
public void registerOnFileOpenedHandler(Place currentPlace) {
this.currentPlace = currentPlace;
currentPlace.registerSimpleEventHandler(FileOpenedEvent.TYPE, new FileOpenedEvent.Handler() {
@Override
public void onFileOpened(boolean isEditable, PathUtil filePath) {
// If the file is editable then we can find/replace through it
showFindAndReplace = isEditable;
}
});
}
public ListenerManager<FindActionSelectedCallback> getFindActionSelectionListener() {
return listenerManager;
}
@Override
protected JsonArray<AbstractActionSection.FilteredActionItem> getAllActions() {
JsonArray<AbstractActionSection.FilteredActionItem> allActions = JsonCollections.createArray();
allActions.add(new FilteredActionItem(res, "Find in this file...", ModifierKeys.ACTION, "F") {
@Override
public void initialize() {
getElement().addClassName(res.awesomeBoxSectionCss().searchIcon());
}
@Override
public boolean onQueryChanged(String query) {
return showFindAndReplace;
}
@Override
public boolean onShowing() {
return showFindAndReplace;
}
@Override
public ActionResult doAction(ActionSource source) {
listenerManager.dispatch(new Dispatcher<FindActionSelectedCallback>() {
@Override
public void dispatch(FindActionSelectedCallback listener) {
listener.onSelected(FindMode.FIND);
}
});
return ActionResult.DO_NOTHING;
}
});
allActions.add(new FilteredActionItem(res, "Replace in this file...", ModifierKeys.ACTION
| ModifierKeys.SHIFT, "F") {
@Override
public boolean onQueryChanged(String query) {
return showFindAndReplace;
}
@Override
public boolean onShowing() {
return showFindAndReplace;
}
@Override
public ActionResult doAction(ActionSource source) {
listenerManager.dispatch(new Dispatcher<FindActionSelectedCallback>() {
@Override
public void dispatch(FindActionSelectedCallback listener) {
listener.onSelected(FindMode.REPLACE);
}
});
return ActionResult.DO_NOTHING;
}
});
/**
* This assert is just here as a handy reminder to update assumptions if the situation changes
* and to prevent someone from pulling their hair out.
*/
assert allActions.size() == NUMBER_OF_ACTIONS;
return allActions;
}
@Override
protected String getTitle() {
return "Actions";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/AbstractAwesomeBoxSection.java | client/src/main/java/com/google/collide/client/search/awesomebox/AbstractAwesomeBoxSection.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.client.search.awesomebox;
import collide.client.util.CssUtils;
import com.google.collide.client.search.awesomebox.AbstractAwesomeBoxSection.ActionItem;
import com.google.collide.client.search.awesomebox.AwesomeBox.Resources;
import com.google.collide.client.search.awesomebox.ManagedSelectionList.SelectableElement;
import elemental.dom.Element;
import elemental.dom.Node;
import elemental.events.MouseEvent;
import elemental.html.DivElement;
/**
* Represents a generic AwesomeBoxSection which contains a selectable item list.
*/
public abstract class AbstractAwesomeBoxSection<T extends ActionItem>
implements AwesomeBox.AwesomeBoxSection {
/**
* Generic wrapper around an element so it can be selected in our selection
* list.
*/
public static abstract class ActionItem implements SelectableElement {
public enum ActionSource {
CLICK, SELECTION
}
protected final Element element;
protected final Resources res;
protected ActionItem(Resources res, Element element) {
this.element = element;
this.res = res;
initialize();
}
public ActionItem(Resources res, String text) {
this(res, AwesomeBoxUtils.createSectionItem(res));
element.setTextContent(text);
}
/**
* Initialize's the element after element creation.
*/
public void initialize() {
}
/**
* Perform this elements action.
*/
public abstract ActionResult doAction(ActionSource source);
public void remove() {
getElement().removeFromParent();
}
/**
* Called to complete a query using tab completion. By default null is
* returned indicating this item does not support completion.
*/
public String completeQuery() {
return null;
}
@Override
public Element getElement() {
return element;
}
@Override
public boolean onSelected() {
element.addClassName(res.awesomeBoxCss().selected());
return true;
}
@Override
public void onSelectionCleared() {
element.removeClassName(res.awesomeBoxCss().selected());
}
}
protected final Resources res;
protected final ManagedSelectionList<T> listItems;
protected DivElement sectionElement;
protected AbstractAwesomeBoxSection(Resources res) {
this.res = res;
listItems = ManagedSelectionList.create();
}
@Override
public DivElement getElement() {
return sectionElement;
}
@Override
public ActionResult onActionRequested() {
if (listItems.hasSelection()) {
return listItems.getSelectedElement().doAction(ActionItem.ActionSource.SELECTION);
}
return ActionResult.DO_NOTHING;
}
@Override
public void onClearSelection() {
listItems.clearSelection();
}
@Override
public String onCompleteSelection() {
return listItems.hasSelection() ? listItems.getSelectedElement().completeQuery() : null;
}
@Override
public void onAddedToContext(AwesomeBoxContext context) {
// no-op by default
}
@Override
public void onContextChanged(AwesomeBoxContext context) {
// no-op by default
}
@Override
public void onHiding(AwesomeBox awesomeBox) {
// no-op by default
}
@Override
public boolean onMoveSelection(boolean moveDown) {
if (!CssUtils.isVisible(getElement())) {
return false;
}
return listItems.moveSelection(moveDown);
}
@Override
public ActionResult onSectionClicked(MouseEvent mouseEvent) {
mouseEvent.preventDefault();
for (int i = 0; i < listItems.size(); i++) {
if (listItems.get(i).getElement().contains((Node) mouseEvent.getTarget())) {
return listItems.get(i).doAction(ActionItem.ActionSource.CLICK);
}
}
return ActionResult.DO_NOTHING;
}
/**
* Shows the section by default.
*/
@Override
public boolean onShowing(AwesomeBox awesomeBox) {
return true;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBoxContext.java | client/src/main/java/com/google/collide/client/search/awesomebox/AwesomeBoxContext.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.client.search.awesomebox;
import com.google.collide.client.search.awesomebox.AwesomeBox.AwesomeBoxSection;
import com.google.collide.client.search.awesomebox.AwesomeBoxModel.HideMode;
import com.google.collide.client.search.awesomebox.shared.MappedShortcutManager;
import com.google.collide.client.search.awesomebox.shared.ShortcutManager;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
/**
* Context class which manages sections.
*/
public class AwesomeBoxContext {
/**
* Builds an AwesomeBox Context
*/
public static class Builder {
private HideMode hideMode = HideMode.AUTOHIDE;
private String headerText = "";
private boolean preventTab = true;
private String watermarkText = "";
private String placeholderText = "";
private boolean alwaysShowClose = false;
private AwesomeBoxContext fallbackContext = null;
public Builder setHideMode(HideMode hideMode) {
this.hideMode = hideMode;
return this;
}
public Builder setPlaceholderText(String placeholderText) {
this.placeholderText = placeholderText;
return this;
}
public Builder setHeaderText(String headerText) {
this.headerText = headerText;
return this;
}
public Builder setPreventTab(boolean preventTab) {
this.preventTab = preventTab;
return this;
}
public Builder setWaterMarkText(String watermarkText) {
this.watermarkText = watermarkText;
return this;
}
public Builder setAlwaysShowCloseButton(boolean alwaysShow) {
this.alwaysShowClose = alwaysShow;
return this;
}
/**
* If a fallback context is set, then this context can only be visible for
* one showing of the AwesomeBox. As soon as the AwesomeBox is closed, the
* context will automatically change to this fallback context.
*/
public Builder setFallbackContext(AwesomeBoxContext context) {
this.fallbackContext = context;
return this;
}
}
/**
* The default context of the AwesomeBox, most likely this is empty.
*/
public static final AwesomeBoxContext DEFAULT = new AwesomeBoxContext(new Builder());
private final JsonArray<AwesomeBoxSection> sections;
private final ShortcutManager shortcutManager;
private final HideMode hideMode;
private final String headerText;
private final boolean preventTab;
private final String watermarkText;
private final String placeholderText;
private final boolean alwaysShowClose;
private final AwesomeBoxContext fallbackContext;
public AwesomeBoxContext(Builder builder) {
sections = JsonCollections.createArray();
shortcutManager = new MappedShortcutManager();
hideMode = builder.hideMode;
headerText = builder.headerText;
preventTab = builder.preventTab;
watermarkText = builder.watermarkText;
placeholderText = builder.placeholderText;
alwaysShowClose = builder.alwaysShowClose;
fallbackContext = builder.fallbackContext;
}
public void addSection(AwesomeBoxSection section) {
sections.add(section);
section.onAddedToContext(this);
}
public void addAllSections(JsonArray<? extends AwesomeBoxSection> sections) {
this.sections.addAll(sections);
}
public JsonArray<AwesomeBoxSection> getSections() {
return sections;
}
public ShortcutManager getShortcutManager() {
return shortcutManager;
}
public HideMode getHideMode() {
return hideMode;
}
public String getHeaderText() {
return headerText;
}
public String getWaterMarkText() {
return watermarkText;
}
public boolean getPreventTab() {
return preventTab;
}
public String getPlaceholderText() {
return placeholderText;
}
public boolean getAlwaysShowCloseButton() {
return alwaysShowClose;
}
public AwesomeBoxContext getFallbackContext() {
return fallbackContext;
}
/**
* @return The number of sections in the context.
*/
public int size() {
return sections.size();
}
/**
* Removes all sections from the internal list for this context.
*/
public void clearSections() {
sections.clear();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/ManagedSelectionList.java | client/src/main/java/com/google/collide/client/search/awesomebox/ManagedSelectionList.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.client.search.awesomebox;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import elemental.dom.Element;
/**
* Manages a list of elements which can have selection. Note no guarantees are
* made when a JsonArray operation which affects the underlying list is
* performed. If you do something rash, clearSelection or selectFirst or
* selectLast, to reset into a known state.
*/
public class ManagedSelectionList<T extends ManagedSelectionList.SelectableElement> {
public static <T extends ManagedSelectionList.SelectableElement> ManagedSelectionList<
T> create() {
return new ManagedSelectionList<T>();
}
public interface SelectableElement {
Element getElement();
/**
* @return false if the item doesn't want selection.
*/
boolean onSelected();
void onSelectionCleared();
}
private static final int NO_SELECTION = -1;
private int selectedIndex = NO_SELECTION;
private JsonArray<T> elements;
public ManagedSelectionList() {
elements = JsonCollections.createArray();
}
public T getSelectedElement() {
return hasSelection() ? elements.get(selectedIndex) : null;
}
public boolean selectNext() {
for (int i = selectedIndex + 1; i < elements.size(); i++) {
if (elements.get(i).onSelected()) {
clearSelection();
selectedIndex = i;
return true;
}
}
return false;
}
public boolean selectPrevious() {
for (int i = selectedIndex - 1; i >= 0; i--) {
if (elements.get(i).onSelected()) {
clearSelection();
selectedIndex = i;
return true;
}
}
return false;
}
/**
* @param index of item to select
*/
public void selectIndex(int index) {
clearSelection();
if (index < 0 || index >= elements.size()) {
throw new IndexOutOfBoundsException();
}
selectedIndex = index;
getSelectedElement().onSelected();
}
/**
* Moves the selection either next or previous based on a boolean
*/
public boolean moveSelection(boolean next) {
if (!hasSelection()) {
return next ? selectFirst() : selectLast();
} else {
return next ? selectNext() : selectPrevious();
}
}
public boolean selectFirst() {
selectedIndex = -1;
if (!selectNext()) {
selectedIndex = NO_SELECTION;
}
return selectedIndex != NO_SELECTION;
}
public boolean selectLast() {
selectedIndex = elements.size();
if (!selectPrevious()) {
selectedIndex = NO_SELECTION;
}
return selectedIndex != NO_SELECTION;
}
public void clearSelection() {
if (hasSelection()) {
getSelectedElement().onSelectionCleared();
}
selectedIndex = NO_SELECTION;
}
public boolean hasSelection() {
return selectedIndex >= 0 && selectedIndex < elements.size();
}
public JsonArray<T> asJsonArray() {
return elements;
}
public void add(T value) {
elements.add(value);
}
public T get(int index) {
return elements.get(index);
}
public int size() {
return elements.size();
}
public T remove(int index) {
return elements.remove(index);
}
public void clear() {
elements.clear();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/GotoActionSection.java | client/src/main/java/com/google/collide/client/search/awesomebox/GotoActionSection.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.client.search.awesomebox;
import com.google.collide.client.code.FileSelectionController.FileOpenedEvent;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.history.Place;
import com.google.collide.client.search.awesomebox.AbstractActionSection.FilteredActionItem;
import com.google.collide.client.search.awesomebox.AwesomeBox.Resources;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
/**
* An AwesomeBox section which is responsible for presenting the user with
* possible actions which affect the current editor document.
*/
public class GotoActionSection extends AbstractActionSection<FilteredActionItem> {
/**
* The maximum number of results to display when filtering.
*/
public static final int MAX_RESULTS = 3;
private Editor editor;
private boolean isEditableFileOpened = false;
/**
* Instantiates a new EditorActionSection
*/
public GotoActionSection(Resources res) {
super(res, MAX_RESULTS);
}
/**
* Attach the editor to this awesome box section.
*
* @param editor The Collide editor .
*/
public void attachEditorAndPlace(Place place, Editor editor) {
this.editor = editor;
place.registerSimpleEventHandler(FileOpenedEvent.TYPE, new FileOpenedEvent.Handler() {
@Override
public void onFileOpened(boolean isEditable, PathUtil filePath) {
isEditableFileOpened = isEditable;
}
});
}
@Override
public boolean onQueryChanged(String query) {
if (!isEditableFileOpened) {
return false;
}
return super.onQueryChanged(query);
}
@Override
public boolean onShowing(AwesomeBox awesomebox) {
// no reason to call up to our parent, we don't show.
return false;
}
@Override
protected JsonArray<FilteredActionItem> getAllActions() {
JsonArray<FilteredActionItem> actions = JsonCollections.createArray();
actions.add(new FilteredActionItem(res, "goto line #", ModifierKeys.ACTION, "g") {
private RegExp numbers = RegExp.compile("(\\d+)");
private String lastQuery;
@Override
public boolean onQueryChanged(String query) {
if (numbers.test(query)) {
String number = numbers.exec(query).getGroup(1);
getElement().setTextContent("goto line " + number);
lastQuery = query;
// TODO: An actual disabled style
getElement().getStyle().setColor("black");
return true;
}
// we defer to testing our goto line label
getElement().setTextContent("goto line #");
lastQuery = "";
getElement().getStyle().setColor("gray");
return super.onQueryChanged(query);
}
@Override
public boolean onShowing() {
return false;
}
@Override
public ActionResult doAction(ActionSource source) {
Preconditions.checkNotNull(editor, "Editor cannot be null");
MatchResult match = numbers.exec(lastQuery);
// if the user clicks us without specifying a line
if (match == null) {
return ActionResult.DO_NOTHING;
}
int line = Integer.parseInt(match.getGroup(1));
int realLine = Math.min(editor.getDocument().getLineCount() - 1, Math.max(line - 1, 0));
editor.scrollTo(realLine, 0);
editor.getFocusManager().focus();
return ActionResult.CLOSE;
}
});
actions.add(new FilteredActionItem(res, "goto top") {
@Override
public ActionResult doAction(ActionSource source) {
Preconditions.checkNotNull(editor, "Editor cannot be null");
editor.scrollTo(0, 0);
editor.getFocusManager().focus();
return ActionResult.CLOSE;
}
@Override
public boolean onShowing() {
return false;
}
});
actions.add(new FilteredActionItem(res, "goto end") {
@Override
public ActionResult doAction(ActionSource source) {
Preconditions.checkNotNull(editor, "Editor cannot be null");
editor.scrollTo(editor.getDocument().getLineCount() - 1, 0);
editor.getFocusManager().focus();
return ActionResult.CLOSE;
}
@Override
public boolean onShowing() {
return false;
}
});
return actions;
}
@Override
protected String getTitle() {
return "Goto";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/FileNameNavigationSection.java | client/src/main/java/com/google/collide/client/search/awesomebox/FileNameNavigationSection.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.client.search.awesomebox;
import collide.client.util.Elements;
import com.google.collide.client.code.FileSelectedPlace;
import com.google.collide.client.code.FileSelectionController.FileOpenedEvent;
import com.google.collide.client.history.Place;
import com.google.collide.client.search.FileNameSearch;
import com.google.collide.client.search.awesomebox.AwesomeBox.Resources;
import com.google.collide.client.search.awesomebox.FileNameNavigationSection.FileNavItem;
import com.google.collide.client.util.ClientStringUtils;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.RegExpUtils;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Preconditions;
import com.google.gwt.regexp.shared.RegExp;
import elemental.html.SpanElement;
/**
* Section that performs navigation via file names in the AwesomeBox
*/
public class FileNameNavigationSection extends AbstractAwesomeBoxSection<FileNavItem> {
/*
* Maximum number of recently opened files to display in the dropdown list.
* The list contains at most MAX_RECENT_FILES+1 since the most recent file
* will be the currently opened file and thus not displayed.
*/
private static final int MAX_RECENT_FILES = 3;
private final FileNameSearch searchIndex;
private final JsonArray<PathUtil> recentFiles;
// TODO: When code place is gone look into compile time injection.
private Place currentPlace;
public FileNameNavigationSection(AwesomeBox.Resources res, FileNameSearch searchIndex) {
super(res);
this.searchIndex = searchIndex;
recentFiles = JsonCollections.createArray();
createDom();
}
public void registerOnFileOpenedHandler(Place currentPlace) {
this.currentPlace = currentPlace;
// Subscribe to file notifications for our recent file list
currentPlace.registerSimpleEventHandler(FileOpenedEvent.TYPE, new FileOpenedEvent.Handler() {
@Override
public void onFileOpened(boolean isEditable, PathUtil filePath) {
// in case it is already there, remove it.
recentFiles.remove(filePath);
// check to ensure we aren't over our file limit and then insert
if (recentFiles.size() > MAX_RECENT_FILES) {
recentFiles.pop();
}
recentFiles.splice(0, 0, filePath);
}
});
}
/**
* Encapsulates a file path that is displayed in the awesome box.
*
*/
static class FileNavItem extends AbstractAwesomeBoxSection.ActionItem {
private final SpanElement fileNameElement;
private final SpanElement folderNameElement;
private PathUtil filePath;
private final Place place;
public FileNavItem(Resources res, Place place) {
super(res, AwesomeBoxUtils.createSectionItem(res));
Preconditions.checkNotNull(place, "Place cannot be null");
this.place = place;
element.addClassName(res.awesomeBoxSectionCss().fileItem());
fileNameElement = Elements.createSpanElement();
folderNameElement = Elements.createSpanElement(res.awesomeBoxSectionCss().folder());
element.appendChild(fileNameElement);
element.appendChild(folderNameElement);
}
public void setPath(PathUtil path) {
int size = path.getPathComponentsCount();
if (size == 1) {
fileNameElement.setTextContent(path.getPathComponent(0));
folderNameElement.setTextContent("");
} else {
fileNameElement.setTextContent(path.getPathComponent(size - 1));
folderNameElement.setTextContent(" - " + path.getPathComponent(size - 2));
}
filePath = path;
}
/**
* Navigates to this file.
*/
@Override
public ActionResult doAction(ActionSource source) {
place.fireChildPlaceNavigation(FileSelectedPlace.PLACE.createNavigationEvent(filePath));
return ActionResult.CLOSE;
}
/**
* @return The filename portion of the path
*/
@Override
public String completeQuery() {
return filePath.getBaseName();
}
}
/**
* Creates the basic DOM for this section
*/
private void createDom() {
sectionElement = AwesomeBoxUtils.createSectionContainer(res);
}
@Override
public boolean onQueryChanged(String query) {
// the most recent file in our list is the current opened one, don't show it
JsonArray<PathUtil> files = recentFiles.slice(1, MAX_RECENT_FILES+1);
if (searchIndex != null && !StringUtils.isNullOrEmpty(query)) {
// TODO: Results come back in the order they appear in the tree
// there needs to be some sort of twiddler that re-ranks the results so
// that filenames that are better matches appear higher.
RegExp reQuery = RegExpUtils.createRegExpForWildcardPattern(
query, ClientStringUtils.containsUppercase(query) ? "" : "i");
files = searchIndex.getMatches(reQuery, 5);
}
// we don't have anything to display
if (files.size() == 0) {
return false;
}
showFiles(files);
return true;
}
private void showFiles(JsonArray<PathUtil> files) {
// Reuse any fileNavItems that are currently out there, don't worry about
// selection, clearSelection will be called by the AwesomeBox after this
int i = reuseAnyExistingElements(files);
for (; i < files.size(); i++) {
FileNavItem item = new FileNavItem(res, currentPlace);
item.setPath(files.get(i));
listItems.add(item);
sectionElement.appendChild(item.getElement());
}
}
/**
* Reuses any existing FileNavItem elements in the dropdown section for speed.
* If the number of existing elements is greater than the number of new
* elements then the remaining items are removed from the dropdown and our
* array.
*
* @param newItems
*/
private int reuseAnyExistingElements(JsonArray<PathUtil> newItems) {
int i = 0;
for (; i < newItems.size() && i < listItems.size(); i++) {
listItems.get(i).setPath(newItems.get(i));
}
JsonArray<FileNavItem> removed = listItems.asJsonArray().splice(i, listItems.size() - i);
for (int r = 0; r < removed.size(); r++) {
removed.get(r).remove();
}
return i;
}
/**
* The file name navigation section is never shown initially.
*/
@Override
public boolean onShowing(AwesomeBox awesomeBox) {
// Never show the first file in the list, since it's the current file.
if (recentFiles.size() > 1) {
showFiles(recentFiles.slice(1, MAX_RECENT_FILES+1));
return true;
}
return false;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/components/FindReplaceComponent.java | client/src/main/java/com/google/collide/client/search/awesomebox/components/FindReplaceComponent.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.client.search.awesomebox.components;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.Editor.KeyListener;
import com.google.collide.client.editor.FocusManager;
import com.google.collide.client.editor.search.SearchModel;
import com.google.collide.client.editor.search.SearchModel.MatchCountListener;
import com.google.collide.client.search.awesomebox.host.AbstractAwesomeBoxComponent;
import com.google.collide.client.search.awesomebox.host.ComponentHost;
import com.google.collide.client.search.awesomebox.shared.AwesomeBoxResources;
import com.google.collide.client.search.awesomebox.shared.AwesomeBoxResources.ComponentCss;
import com.google.collide.client.search.awesomebox.shared.MappedShortcutManager;
import com.google.collide.client.search.awesomebox.shared.ShortcutManager;
import com.google.collide.client.search.awesomebox.shared.ShortcutManager.ShortcutPressedCallback;
import com.google.collide.client.ui.menu.PositionController.HorizontalAlign;
import com.google.collide.client.ui.menu.PositionController.VerticalAlign;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.HasView;
import com.google.collide.shared.util.ListenerRegistrar;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.KeyboardEvent;
import elemental.events.KeyboardEvent.KeyCode;
import elemental.events.MouseEvent;
/**
* Section that displays find and replace controls. This section is meant to be
* the first item in it's context since it piggy backs off the AwesomeBox input.
*/
public class FindReplaceComponent extends AbstractAwesomeBoxComponent implements HasView<
FindReplaceComponent.View> {
public interface ViewEvents {
public void onFindQueryChanged();
public void onKeydown(KeyboardEvent event);
public void onNextClicked();
public void onPreviousClicked();
public void onReplaceClicked();
public void onReplaceAllClicked();
public void onCloseClicked();
}
public enum FindMode {
FIND, REPLACE
}
private final View view;
private final ShortcutManager shortcutManager = new MappedShortcutManager();
private SearchModel searchModel;
private String lastQuery = "";
private FocusManager focusManager;
// Editor Listener For Esc
// TODO: Long term this should be a global clear event that bubbles
private ListenerRegistrar<KeyListener> editorKeyListenerRegistrar;
private RemoverManager removerManager = new RemoverManager();
// TODO: Handle changes to total matches via document mutations
private final MatchCountListener totalMatchesListener = new MatchCountListener() {
@Override
public void onMatchCountChanged(int total) {
getView().numMatches.setInnerText(String.valueOf(total));
}
};
public FindReplaceComponent(View view) {
super(HideMode.NO_AUTOHIDE, HiddenBehavior.REVERT_TO_DEFAULT, "Find in this file");
this.view = view;
view.setDelegate(new ViewEventsImpl());
}
public void setFindMode(FindMode mode) {
CssUtils.setDisplayVisibility2(
Elements.asJsElement(getView().totalMatchesContainer), mode == FindMode.FIND);
CssUtils.setDisplayVisibility2(
Elements.asJsElement(getView().replaceActions), mode == FindMode.REPLACE);
CssUtils.setDisplayVisibility2(
Elements.asJsElement(getView().replaceRow), mode == FindMode.REPLACE);
}
/**
* Attaches to the editor's search model for querying.
*/
public void attachEditor(Editor editor) {
this.searchModel = editor.getSearchModel();
this.focusManager = editor.getFocusManager();
this.editorKeyListenerRegistrar = editor.getKeyListenerRegistrar();
searchModel.getMatchCountChangedListenerRegistrar().add(totalMatchesListener);
setupShortcuts();
}
@Override
public View getView() {
return view;
}
@Override
public elemental.dom.Element getElement() {
return getView().getElement();
}
/**
* Sets the query of the find replace component.
*/
public void setQuery(String query) {
getView().setQuery(query);
if (isActive()) {
Preconditions.checkNotNull(searchModel, "Search model is required to set the query");
getView().selectQuery();
searchModel.setQuery(query);
}
}
@Override
public String getTooltipText() {
return "Press Ctrl+F to quickly find text in the current file";
}
/**
* Initializes the shortcut manager with our shortcuts of interest. The
* {@link ComponentHost} will handle actually notifying us of shortcuts being
* used.
*/
private void setupShortcuts() {
shortcutManager.addShortcut(0, KeyCode.ENTER, new ShortcutPressedCallback() {
@Override
public void onShortcutPressed(KeyboardEvent event) {
event.preventDefault();
if (searchModel != null) {
searchModel.getMatchManager().selectNextMatch();
}
}
});
shortcutManager.addShortcut(ModifierKeys.SHIFT, KeyCode.ENTER, new ShortcutPressedCallback() {
@Override
public void onShortcutPressed(KeyboardEvent event) {
event.preventDefault();
if (searchModel != null) {
searchModel.getMatchManager().selectPreviousMatch();
}
}
});
shortcutManager.addShortcut(ModifierKeys.ACTION, KeyCode.G, new ShortcutPressedCallback() {
@Override
public void onShortcutPressed(KeyboardEvent event) {
event.preventDefault();
if (focusManager != null) {
focusManager.focus();
}
}
});
shortcutManager.addShortcut(
ModifierKeys.ACTION | ModifierKeys.SHIFT, KeyCode.G, new ShortcutPressedCallback() {
@Override
public void onShortcutPressed(KeyboardEvent event) {
event.preventDefault();
searchModel.getMatchManager().selectPreviousMatch();
if (focusManager != null) {
focusManager.focus();
}
}
});
}
@Override
public void onShow(ComponentHost host, ShowReason reason) {
super.onShow(host, reason);
String query = getView().getQuery();
if (StringUtils.isNullOrEmpty(query)) {
getView().setQuery(lastQuery);
searchModel.setQuery(lastQuery);
} else if (!searchModel.getQuery().equals(query)) {
searchModel.setQuery(query);
}
// Listen for esc in the editor while we're showing
// TODO: Use some sort of event system long term
removerManager.track(editorKeyListenerRegistrar.add(new KeyListener() {
@Override
public boolean onKeyPress(SignalEvent event) {
if (event.getKeyCode() == KeyCode.ESC) {
hide();
}
return false;
}
}));
}
@Override
public void focus() {
getView().selectQuery();
getView().focus();
}
@Override
public void onHide() {
lastQuery = getView().getQuery();
if (searchModel != null) {
searchModel.setQuery("");
}
removerManager.remove();
getView().numMatches.setInnerText("0");
}
public class ViewEventsImpl implements ViewEvents {
@Override
public void onFindQueryChanged() {
Preconditions.checkNotNull(searchModel, "Search model must be set for find/replace to work");
String query = getView().getQuery();
searchModel.setQuery(query);
}
@Override
public void onKeydown(KeyboardEvent event) {
shortcutManager.onKeyDown(event);
}
@Override
public void onNextClicked() {
if (searchModel != null && !StringUtils.isNullOrEmpty(searchModel.getQuery())) {
searchModel.getMatchManager().selectNextMatch();
}
}
@Override
public void onPreviousClicked() {
if (searchModel != null && !StringUtils.isNullOrEmpty(searchModel.getQuery())) {
searchModel.getMatchManager().selectPreviousMatch();
}
}
@Override
public void onReplaceAllClicked() {
searchModel.getMatchManager().replaceAllMatches(getView().replaceInput.getValue());
getView().selectQuery();
getView().focus();
}
@Override
public void onReplaceClicked() {
searchModel.getMatchManager().replaceMatch(getView().replaceInput.getValue());
}
@Override
public void onCloseClicked() {
hide();
}
}
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("FindReplaceComponent.ui.xml")
interface FindReplaceUiBinder extends UiBinder<Element, View> {
}
private static FindReplaceUiBinder uiBinder = GWT.create(FindReplaceUiBinder.class);
@UiField(provided = true)
final ComponentCss css;
@UiField(provided = true)
final AwesomeBoxResources res;
@UiField
InputElement findInput;
@UiField
DivElement closeButton;
@UiField
DivElement replaceRow;
@UiField
InputElement replaceInput;
@UiField
AnchorElement prevButton;
@UiField
AnchorElement nextButton;
@UiField
DivElement replaceActions;
@UiField
AnchorElement replaceButton;
@UiField
AnchorElement replaceAllButton;
@UiField
SpanElement numMatches;
@UiField
DivElement totalMatchesContainer;
public View(AwesomeBoxResources res) {
this.res = res;
this.css = res.awesomeBoxComponentCss();
setElement(Elements.asJsElement(uiBinder.createAndBindUi(this)));
createTooltips(res);
handleEvents();
}
public String getQuery() {
return findInput.getValue();
}
public void setQuery(String query) {
findInput.setValue(query);
}
public void selectQuery() {
findInput.select();
}
public void focus() {
findInput.focus();
}
private void createTooltips(AwesomeBoxResources res) {
Tooltip.create(res, Elements.asJsElement(nextButton), VerticalAlign.BOTTOM,
HorizontalAlign.MIDDLE, "Next match");
Tooltip.create(res, Elements.asJsElement(prevButton), VerticalAlign.BOTTOM,
HorizontalAlign.MIDDLE, "Previous match");
Tooltip.create(res, Elements.asJsElement(replaceButton), VerticalAlign.BOTTOM,
HorizontalAlign.MIDDLE, "Replace current match");
Tooltip.create(res, Elements.asJsElement(replaceAllButton), VerticalAlign.BOTTOM,
HorizontalAlign.MIDDLE, "Replace all matches");
}
private void handleEvents() {
Elements.asJsElement(findInput).addEventListener(Event.INPUT, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (getDelegate() != null) {
getDelegate().onFindQueryChanged();
}
}
}, false);
getElement().addEventListener(Event.KEYDOWN, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (getDelegate() != null) {
getDelegate().onKeydown((KeyboardEvent) evt);
}
}
}, false);
getElement().addEventListener(Event.CLICK, new EventListener() {
@Override
public void handleEvent(Event arg0) {
if (getDelegate() == null) {
return;
}
MouseEvent mouseEvent = (MouseEvent) arg0;
if (prevButton.isOrHasChild((Node) mouseEvent.getTarget())) {
getDelegate().onPreviousClicked();
} else if (nextButton.isOrHasChild((Node) mouseEvent.getTarget())) {
getDelegate().onNextClicked();
} else if (replaceButton.isOrHasChild((Node) mouseEvent.getTarget())) {
getDelegate().onReplaceClicked();
} else if (replaceAllButton.isOrHasChild((Node) mouseEvent.getTarget())) {
getDelegate().onReplaceAllClicked();
} else if (closeButton.isOrHasChild((Node) mouseEvent.getTarget())) {
getDelegate().onCloseClicked();
}
}
}, false);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/host/AwesomeBoxComponent.java | client/src/main/java/com/google/collide/client/search/awesomebox/host/AwesomeBoxComponent.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.client.search.awesomebox.host;
import elemental.dom.Element;
/**
* Defines the minimum interface exposed by an {@link AwesomeBoxComponentHost}
* component. A component is one which is hosted within the AwesomeBox UI.
* Examples include find/replace, the awesomebox itself, and the checkpoint ui.
*/
public interface AwesomeBoxComponent {
/**
* Defines how the component host hides this component.
*/
public enum HideMode {
/**
* The component will autohide when the user clicks outside of the
* {@link AwesomeBoxComponentHost} or the actual input loses focus.
*/
AUTOHIDE,
/** The component must be manually closed or programatically closed. */
NO_AUTOHIDE,
}
public enum HiddenBehavior {
/** The component will stay active when hidden. */
STAY_ACTIVE,
/**
* When hidden, this current component hosted by the
* {@link AwesomeBoxComponentHost} will revert to the default component.
*/
REVERT_TO_DEFAULT
}
public enum ShowReason {
/** Indicates the component is being shown due to a click event */
CLICK,
/** Indicates the component is being shown programatically */
OTHER
}
HideMode getHideMode();
HiddenBehavior getHiddenBehavior();
String getPlaceHolderText();
String getTooltipText();
Element getElement();
/**
* Called when the component should steal focus, guaranteed to be called
* immediately after onShow.
*/
void focus();
void onShow(ComponentHost host, ShowReason reason);
void onHide();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/host/AbstractAwesomeBoxComponent.java | client/src/main/java/com/google/collide/client/search/awesomebox/host/AbstractAwesomeBoxComponent.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.client.search.awesomebox.host;
/**
* Defines a component which is hosted by the {@link AwesomeBoxComponentHost}.
*
*/
public abstract class AbstractAwesomeBoxComponent implements AwesomeBoxComponent {
private final HideMode hideMode;
private final String placeHolderText;
private final HiddenBehavior hiddenBehavior;
private ComponentHost host;
/**
* Creates a new {@link AbstractAwesomeBoxComponent} with
* {@link AwesomeBoxComponent.HideMode#AUTOHIDE},
* {@link AwesomeBoxComponent.HiddenBehavior#STAY_ACTIVE} and a default
* placeholder text of 'Actions...'.
*/
public AbstractAwesomeBoxComponent() {
this(HideMode.AUTOHIDE, HiddenBehavior.REVERT_TO_DEFAULT, "Actions...");
}
public AbstractAwesomeBoxComponent(
HideMode hideMode, HiddenBehavior hideBehavior, String placeHolderText) {
this.hideMode = hideMode;
this.hiddenBehavior = hideBehavior;
this.placeHolderText = placeHolderText;
}
@Override
public HideMode getHideMode() {
return hideMode;
}
@Override
public HiddenBehavior getHiddenBehavior() {
return hiddenBehavior;
}
@Override
public String getPlaceHolderText() {
return placeHolderText;
}
@Override
public String getTooltipText() {
// no tooltip by default
return null;
}
public void hide() {
// Component is already hidden
if (host == null) {
return;
}
// request that our host hide us
host.requestHide();
host = null;
}
/**
* @return true if this component is active.
*/
public boolean isActive() {
return host != null;
}
/**
* Notifies the component that the component has been hidden and its base
* element has been removed from the DOM.
*/
@Override
public void onHide() {
host = null;
}
/**
* Notifies the component that it has been added to the DOM and is visible.
*/
@Override
public void onShow(ComponentHost host, ShowReason reason) {
this.host = host;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/host/ComponentHost.java | client/src/main/java/com/google/collide/client/search/awesomebox/host/ComponentHost.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.client.search.awesomebox.host;
/**
* An interface defining the methods a {@link ComponentHost} will expose to a
* component.
*/
public interface ComponentHost {
void requestHide();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/host/AwesomeBoxComponentHost.java | client/src/main/java/com/google/collide/client/search/awesomebox/host/AwesomeBoxComponentHost.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.client.search.awesomebox.host;
import collide.client.util.Elements;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponent.HiddenBehavior;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponent.HideMode;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponent.ShowReason;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
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.common.base.Preconditions;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
import elemental.dom.Node;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.EventRemover;
import elemental.events.KeyboardEvent;
import elemental.events.KeyboardEvent.KeyCode;
import elemental.html.DivElement;
/**
* The host control of the {@link AwesomeBoxComponent}s and related components.
* It performs very little other than management of {@link AwesomeBoxComponent}s
* and focus/cancel actions.
*
*/
public class AwesomeBoxComponentHost extends UiComponent<AwesomeBoxComponentHost.View> {
public interface Css extends CssResource {
String container();
String base();
}
/**
* A small class which wraps the currently visible
* {@link AwesomeBoxComponent}.
*/
public class HostedComponent implements ComponentHost {
public final AwesomeBoxComponent component;
public HostedComponent(AwesomeBoxComponent component) {
this.component = component;
}
@Override
public void requestHide() {
if (current != this) {
// This is stale, the component is already hidden.
return;
}
hideImpl(AwesomeBoxComponentHiddenListener.Reason.OTHER);
}
}
/**
* Allows an object that is not a section to listen in when the AwesomeBox is
* hiding/showing.
*/
public interface AwesomeBoxComponentHiddenListener {
public enum Reason {
/**
* An event occurred which canceled the user's interaction with the
* AwesomeBox such as pressing the ESC button.
*/
CANCEL_EVENT,
/**
* An external click occurred triggering an autohide.
*/
EXTERNAL_CLICK,
/**
* The component was hidden programatically, or by the component.
*/
OTHER
}
public void onHidden(Reason reason);
}
public interface ViewEvents {
public void onExternalClick();
public void onClick();
public void onEscapePressed();
}
public static class View extends CompositeView<ViewEvents> {
private final EventListener bodyListener = new EventListener() {
@Override
public void handleEvent(Event evt) {
if (getDelegate() != null && !getElement().contains((Node) evt.getTarget())) {
getDelegate().onExternalClick();
}
}
};
private final DivElement baseElement;
private EventRemover bodyRemover;
public View(Element container, Css css) {
super(container);
container.addClassName(css.container());
baseElement = Elements.createDivElement(css.base());
baseElement.setTextContent("Actions");
container.appendChild(baseElement);
attachEvents();
}
void attachEvents() {
baseElement.addEventListener(Event.CLICK, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (getDelegate() != null) {
getDelegate().onClick();
}
}
}, false);
getElement().addEventListener(Event.KEYUP, new EventListener() {
@Override
public void handleEvent(Event evt) {
KeyboardEvent event = (KeyboardEvent) evt;
if (event.getKeyCode() == KeyCode.ESC && getDelegate() != null) {
getDelegate().onEscapePressed();
}
}
}, false);
}
public void setBaseActive(boolean active) {
Preconditions.checkState(!isBaseActive() == active, "Invalid base element state!");
if (!active) {
baseElement.removeFromParent();
} else {
getElement().appendChild(baseElement);
}
}
public boolean isBaseActive() {
return baseElement.getParentElement() != null;
}
public void attachComponentElement(Element component) {
Preconditions.checkState(!isBaseActive(), "Base cannot be attached");
getElement().appendChild(component);
}
public void setBodyListenerAttached(boolean shouldAttach) {
boolean isListenerAttached = bodyRemover != null;
Preconditions.checkState(
isListenerAttached != shouldAttach, "Invalid listener attachment state");
if (shouldAttach) {
bodyRemover = Elements.getBody().addEventListener(Event.MOUSEDOWN, bodyListener, false);
} else {
bodyRemover.remove();
bodyRemover = null;
}
}
}
public class ViewEventsImpl implements ViewEvents {
@Override
public void onClick() {
// only do a show if we're not showing anything already
if (getView().isBaseActive()) {
showImpl(ShowReason.CLICK);
}
}
@Override
public void onExternalClick() {
if (model.getActiveComponent().getHideMode() == HideMode.AUTOHIDE) {
hideImpl(AwesomeBoxComponentHiddenListener.Reason.EXTERNAL_CLICK);
}
}
@Override
public void onEscapePressed() {
hideImpl(AwesomeBoxComponentHiddenListener.Reason.CANCEL_EVENT);
}
}
private final HostedComponent NONE_SHOWING = new HostedComponent(null);
private final ListenerManager<AwesomeBoxComponentHiddenListener> componentHiddenListener =
ListenerManager.create();
private final AwesomeBoxComponentHostModel model;
private HostedComponent current = NONE_SHOWING;
public AwesomeBoxComponentHost(View view, AwesomeBoxComponentHostModel model) {
super(view);
this.model = model;
view.setDelegate(new ViewEventsImpl());
}
/**
* Returns a {@link ListenerRegistrar} which can be used to listen for the
* active component being hidden.
*/
public ListenerRegistrar<AwesomeBoxComponentHiddenListener> getComponentHiddenListener() {
return componentHiddenListener;
}
/**
* Hides the currently active component.
*/
public void hide() {
if (isComponentActive()) {
hideImpl(AwesomeBoxComponentHiddenListener.Reason.OTHER);
}
}
/**
* Displays the current component set in the
* {@link AwesomeBoxComponentHostModel}. Any currently displayed component
* will be removed from the DOM.
*/
public void show() {
showImpl(ShowReason.OTHER);
}
private void showImpl(ShowReason reason) {
if (current.component == model.getActiveComponent()) {
current.component.focus();
return;
} else if (isComponentActive()) {
hide();
}
current = new HostedComponent(model.getActiveComponent());
Preconditions.checkState(current.component != null, "There is no active component to host");
getView().setBaseActive(false);
getView().setBodyListenerAttached(true);
getView().attachComponentElement(current.component.getElement());
current.component.onShow(current, reason);
current.component.focus();
}
/**
* @return true if a component is currently active.
*/
public boolean isComponentActive() {
return current != NONE_SHOWING;
}
private void hideImpl(AwesomeBoxComponentHiddenListener.Reason reason) {
Preconditions.checkNotNull(
current != NONE_SHOWING, "There must be an active component to hide.");
// Extract the current component and mark us as none showing
AwesomeBoxComponent component = current.component;
current = NONE_SHOWING;
// remove the current component and reattach our base
/*
* NOTE: Removing parent seems to cause any queued DOM events for this
* element to freak out, make sure current is already NONE_SHOWING to block
* other hide attempts. If you don't you'll probably see things like
* NOT_FOUND_ERR. This is especially true of the blur event used by the
* AwesomeBox to hide.
*/
component.getElement().removeFromParent();
getView().setBaseActive(true);
getView().setBodyListenerAttached(false);
// Hide component, potentially revert, then dispatch the hidden listener
component.onHide();
maybeRevertToDefaultComponent(component);
dispatchHiddenListener(reason);
}
private void dispatchHiddenListener(final AwesomeBoxComponentHiddenListener.Reason reason) {
componentHiddenListener.dispatch(new Dispatcher<AwesomeBoxComponentHiddenListener>() {
@Override
public void dispatch(AwesomeBoxComponentHiddenListener listener) {
listener.onHidden(reason);
}
});
}
private void maybeRevertToDefaultComponent(AwesomeBoxComponent component) {
boolean isComponentTheModelsActiveComponent = component == model.getActiveComponent();
boolean isHiddenBehaviorRevert =
component.getHiddenBehavior() == HiddenBehavior.REVERT_TO_DEFAULT;
if (isComponentTheModelsActiveComponent && isHiddenBehaviorRevert) {
model.revertToDefaultComponent();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/host/AwesomeBoxComponentHostModel.java | client/src/main/java/com/google/collide/client/search/awesomebox/host/AwesomeBoxComponentHostModel.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.client.search.awesomebox.host;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerRegistrar;
/**
* The model for the {@link AwesomeBoxComponentHost}.
*
*/
public class AwesomeBoxComponentHostModel {
interface ComponentStatusChangedListener {
public void onComponentChanged();
}
private final ListenerManager<ComponentStatusChangedListener>
componentStatusChangedListenerManager = ListenerManager.create();
private AwesomeBoxComponent defaultComponent;
private AwesomeBoxComponent currentComponent;
/**
* Returns the registration interface for clients to listen to be notified
* when the active component is changed.
*/
public ListenerRegistrar<ComponentStatusChangedListener> getComponentChangedListenerRegistrar() {
return componentStatusChangedListenerManager;
}
public void setDefaultComponent(AwesomeBoxComponent defaultComponent) {
this.defaultComponent = defaultComponent;
if (currentComponent == null) {
currentComponent = defaultComponent;
}
}
public void setActiveComponent(AwesomeBoxComponent component) {
currentComponent = component;
}
public AwesomeBoxComponent getActiveComponent() {
return currentComponent;
}
public void revertToDefaultComponent() {
currentComponent = defaultComponent;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/shared/AwesomeBoxResources.java | client/src/main/java/com/google/collide/client/search/awesomebox/shared/AwesomeBoxResources.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.client.search.awesomebox.shared;
import collide.client.common.CommonResources;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponent;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponentHost;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.gwt.resources.client.CssResource;
/**
* The resources shared by the awesomebox related objects.
*/
public interface AwesomeBoxResources extends CommonResources.BaseResources, Tooltip.Resources {
/**
* Shared CSS styles by all {@link AwesomeBoxComponent} objects.
*/
public interface ComponentCss extends CssResource {
// Generic Component Styles
String closeButton();
// Snapshot Styles
String snapshot();
String snapshotComponent();
String snapshotMessageInput();
String snapshotTextAreaContainer();
String snapshotLabelContainer();
String snapshotLabel();
// Find/Replace Styles
String findComponent();
String findContainer();
String findInput();
String findRowLabel();
String replaceInput();
String findRow();
String findActions();
String navActions();
String actionGroup();
String replaceActions();
String totalMatchesContainer();
String numMatches();
}
@Source({"AwesomeBoxComponentHost.css", "collide/client/common/constants.css"})
public AwesomeBoxComponentHost.Css awesomeBoxHostCss();
@Source({"AwesomeBoxComponent.css", "collide/client/common/constants.css"})
public ComponentCss awesomeBoxComponentCss();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/shared/MappedShortcutManager.java | client/src/main/java/com/google/collide/client/search/awesomebox/shared/MappedShortcutManager.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.client.search.awesomebox.shared;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
import elemental.events.KeyboardEvent;
/**
* The simplest shortcut manager I could conceive.
*/
// TODO: HA this will need rewriting
public class MappedShortcutManager implements ShortcutManager {
public JsonStringMap<ShortcutPressedCallback> shortcutMap;
public MappedShortcutManager() {
shortcutMap = JsonCollections.createMap();
}
@Override
public void addShortcut(int modifiers, int keyCode, ShortcutPressedCallback callback) {
shortcutMap.put(getKeyForShortcut(modifiers, keyCode), callback);
}
/**
* Returns the string key in the map for the given modifier keys and key code.
*/
private String getKeyForShortcut(int modifiers, int keyCode) {
return String.valueOf(modifiers) + "-" + String.valueOf(keyCode);
}
@Override
public void onKeyDown(KeyboardEvent event) {
int modifiers = ModifierKeys.computeExactModifiers(event);
ShortcutPressedCallback callback =
shortcutMap.get(getKeyForShortcut(modifiers, event.getKeyCode()));
if (callback != null) {
callback.onShortcutPressed(event);
}
}
@Override
public void clearShortcuts() {
// TODO: Better way to clear this
shortcutMap = JsonCollections.createMap();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/search/awesomebox/shared/ShortcutManager.java | client/src/main/java/com/google/collide/client/search/awesomebox/shared/ShortcutManager.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.client.search.awesomebox.shared;
import elemental.events.KeyboardEvent;
// TODO: Refactor when we figure out some sort of reusable shortcut
// component that is a permenant solution.
public interface ShortcutManager {
public interface ShortcutPressedCallback {
public void onShortcutPressed(KeyboardEvent event);
}
/**
* Adds a shortcut to the shortcut manager. If the shortcut already exists it
* will be overwritten.
*
* @param modifiers Logical OR of modifier keys
* @param keycode KeyCode
*/
public void addShortcut(int modifiers, int keycode, ShortcutPressedCallback callback);
/**
* Clears all shortcuts in the manager.
*/
public void clearShortcuts();
/**
* On key down we check for shortcuts.
*/
public void onKeyDown(KeyboardEvent event);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/status/StatusHandler.java | client/src/main/java/com/google/collide/client/status/StatusHandler.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.client.status;
/**
* Client code wishing to react to status events must implement this interface.
*/
public interface StatusHandler {
void clear();
void onStatusMessage(StatusMessage msg);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/status/StatusPresenter.java | client/src/main/java/com/google/collide/client/status/StatusPresenter.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.client.status;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.testing.DebugAttributeSetter;
import com.google.collide.client.testing.DebugId;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.client.JsoArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import elemental.css.CSSStyleDeclaration;
import elemental.css.CSSStyleDeclaration.Display;
import elemental.css.CSSStyleDeclaration.Visibility;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.DivElement;
import elemental.html.PreElement;
import elemental.html.SpanElement;
/**
* The StatusPresenter handles status events and renders them into the UI. This
* presenter is meant to be injected into some already constructed DOM space
* since it does not define its own dimensions.
*
*/
public class StatusPresenter extends UiComponent<StatusPresenter.View>
implements StatusHandler {
public interface Css extends CssResource {
String actionsContainer();
String action();
String expandedFatal();
String expandedRegular();
String fatal();
String fatalImage();
String inline();
String longText();
String more();
String statusArea();
String statusConfirmation();
String statusDismiss();
String statusError();
String statusLoading();
String statusText();
}
public interface Resources extends ClientBundle {
@Source("close.png")
ImageResource close();
@Source("fatal_border.png")
ImageResource fatalBorder();
@Source({"collide/client/common/constants.css", "StatusPresenter.css"})
Css statusPresenterCss();
}
public static class View extends CompositeView<StatusPresenter.ViewEvents> {
private static final int PADDING_WIDTH = 60;
private DivElement actionsContainer;
private final Css css;
private DivElement fatalImage;
private PreElement longText;
private SpanElement more;
private DivElement statusDismiss;
private StatusMessage statusMessage;
private DivElement statusText;
public View(Resources resources) {
this.css = resources.statusPresenterCss();
setElement(createDom());
}
public void clear() {
getElement().getStyle().setVisibility(Visibility.HIDDEN);
statusDismiss.getStyle().setVisibility(Visibility.HIDDEN);
longText.getStyle().setDisplay(Display.NONE);
}
public void renderStatus(StatusMessage message) {
this.statusMessage = message;
getElement().getStyle().setVisibility(Visibility.VISIBLE);
longText.getStyle().setDisplay(CSSStyleDeclaration.Display.NONE);
final JsoArray<StatusAction> statusActions = message.getActions();
actionsContainer.getStyle().setDisplay(
statusActions.size() > 0 ? Display.BLOCK : Display.NONE);
actionsContainer.setInnerHTML("");
for (int i = 0, n = statusActions.size(); i < n; i++) {
final StatusAction statusAction = statusActions.get(i);
SpanElement action = Elements.createSpanElement(css.action());
statusAction.renderAction(action);
action.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
statusAction.onAction();
}
});
actionsContainer.appendChild(action);
}
statusText.setTextContent(message.getText());
// Render a countdown if the message is going to expire.
if (message.getTimeToExpiry() > 0) {
final StatusMessage msg = message;
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
@Override
public boolean execute() {
if (msg == StatusPresenter.View.this.statusMessage) {
int seconds = msg.getTimeToExpiry() / 1000;
statusText.setTextContent(msg.getText() + " ..." + seconds);
return seconds > 0;
} else {
return false;
}
}
}, 1000);
}
if (!message.getLongText().isEmpty()) {
longText.setTextContent(message.getLongText());
more.getStyle().setDisplay(Display.INLINE_BLOCK);
} else {
more.getStyle().setDisplay(Display.NONE);
}
if (message.isDismissable()) {
statusDismiss.getStyle().setVisibility(Visibility.VISIBLE);
} else {
statusDismiss.getStyle().setVisibility(Visibility.HIDDEN);
}
if (message.getType() != MessageType.FATAL) {
// Size and center the message
dynamicallyPositionMessage();
} else {
// Fatal messages are 100% width.
getElement().getStyle().setWidth(100, CSSStyleDeclaration.Unit.PCT);
getElement().getStyle().setMarginLeft(0, CSSStyleDeclaration.Unit.PX);
}
// Render the particular message type's style
DebugAttributeSetter debugSetter = new DebugAttributeSetter();
switch (message.getType()) {
case LOADING:
debugSetter.add("status", "loading");
getElement().setClassName(css.statusLoading());
break;
case CONFIRMATION:
debugSetter.add("status", "confirmation");
getElement().setClassName(css.statusConfirmation());
break;
case ERROR:
debugSetter.add("status", "error");
getElement().setClassName(css.statusError());
break;
case FATAL:
debugSetter.add("status", "fatal");
getElement().setClassName(css.fatal());
getDelegate().onStatusExpanded();
break;
default:
debugSetter.add("status", "unknown");
Log.error(getClass(), "Got a status message of unknown type " + message.getType());
}
debugSetter.on(getElement());
}
private Element createDom() {
DivElement root = Elements.createDivElement(css.statusArea());
statusText = Elements.createDivElement(css.statusText());
statusDismiss = Elements.createDivElement(css.statusDismiss());
statusDismiss.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onStatusDismissed();
}
});
new DebugAttributeSetter().setId(DebugId.STATUS_PRESENTER).on(root);
longText = Elements.createPreElement();
longText.setClassName(css.longText());
longText.getStyle().setDisplay(CSSStyleDeclaration.Display.NONE);
more = Elements.createSpanElement();
more.setClassName(css.more());
more.setTextContent("show more details...");
more.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onStatusExpanded();
}
});
actionsContainer = Elements.createDivElement();
actionsContainer.setClassName(css.actionsContainer());
fatalImage = Elements.createDivElement(css.fatalImage());
root.appendChild(fatalImage);
root.appendChild(statusText);
root.appendChild(more);
root.appendChild(actionsContainer);
root.appendChild(statusDismiss);
root.appendChild(longText);
return root;
}
/**
* Size the message dynamically to scale with the text but not taking up
* more than 50% of the screen width.
*/
private void dynamicallyPositionMessage() {
int messageWidth =
statusText.getScrollWidth() + actionsContainer.getScrollWidth() + more.getScrollWidth()
+ statusDismiss.getScrollWidth() + PADDING_WIDTH;
int maxWidth = Elements.getBody().getClientWidth() / 2;
int width = CssUtils.isVisible(longText) ? maxWidth : Math.min(messageWidth, maxWidth);
getElement().getStyle().setWidth(width, CSSStyleDeclaration.Unit.PX);
getElement().getStyle().setMarginLeft(width / -2, CSSStyleDeclaration.Unit.PX);
}
}
public interface ViewEvents {
void onStatusDismissed();
void onStatusExpanded();
}
public static StatusPresenter create(Resources resources) {
View view = new View(resources);
return new StatusPresenter(view);
}
private StatusMessage statusMessage;
protected StatusPresenter(View view) {
super(view);
handleViewEvents();
}
@Override
public void clear() {
getView().clear();
statusMessage = null;
}
@Override
public void onStatusMessage(StatusMessage msg) {
statusMessage = msg;
getView().renderStatus(msg);
}
private void handleViewEvents() {
getView().setDelegate(new ViewEvents() {
@Override
public void onStatusDismissed() {
if (statusMessage != null) {
statusMessage.cancel();
}
}
@Override
public void onStatusExpanded() {
getView().more.getStyle().setDisplay(CSSStyleDeclaration.Display.NONE);
getView().longText.getStyle().setDisplay(CSSStyleDeclaration.Display.BLOCK);
if (statusMessage.getType() != MessageType.FATAL) {
getView().getElement().addClassName(getView().css.expandedRegular());
getView().dynamicallyPositionMessage();
} else {
getView().getElement().addClassName(getView().css.expandedFatal());
}
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/status/StatusManager.java | client/src/main/java/com/google/collide/client/status/StatusManager.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.client.status;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.client.JsoArray;
/**
* The Status Manager is responsible for maintaining all status state. It
* coordinates priorities between different types of messages and allows the
* status view to be stateless.
*
* There can be many outstanding messages at any given time, but only one
* message is active. When a message becomes active, the {@link StatusHandler}
* is notified of this change.
*
* A fatal message is unrecoverable and cannot be dismissed or canceled once
* fired.
*/
public class StatusManager {
/**
* The currently active message, or null if there are none
*/
private StatusMessage activeMessage = null;
// TODO: Too bad we don't have real lightweight collections. Might be
// worth making an Ordered Set implementation for wider client use, but for
// now these collections are always very small.
/**
* The set of outstanding confirmation messages.
*/
private final JsoArray<StatusMessage> confirmationMessages = JsoArray.create();
/**
* The set of outstanding error messages.
*/
private final JsoArray<StatusMessage> errorMessages = JsoArray.create();
/**
* If a fatal message fires, it is recorded here.
*/
private StatusMessage firedFatal = null;
/**
* The set of outstanding loading messages.
*/
private final JsoArray<StatusMessage> loadingMessages = JsoArray.create();
/**
* The handler responsible for updating the view when there is a new active
* message.
*/
private StatusHandler statusHandler;
public StatusManager() {
/*
* Create a dummy statusHandler to safely handle events that occur before
* the UI handler is hooked up.
*/
this.statusHandler = new StatusHandler() {
@Override
public void clear() {
}
@Override
public void onStatusMessage(StatusMessage msg) {
}
};
}
StatusManager(StatusHandler statusHandler) {
this.statusHandler = statusHandler;
}
/**
* Cancel a message. Once a message is canceled, all subsequent fires are
* no-ops.
*
* @param msg the message to cancel
*/
void cancel(StatusMessage msg) {
switch (msg.getType()) {
case LOADING:
loadingMessages.remove(msg);
break;
case CONFIRMATION:
confirmationMessages.remove(msg);
break;
case ERROR:
errorMessages.remove(msg);
break;
case FATAL:
// cannot cancel a fatal;
return;
default:
Log.error(getClass(), "Got a status message of unknown type " + msg.getType());
return;
}
possiblyFireHandler();
}
/**
* Clear all outstanding and active messages.
*/
public void clear() {
activeMessage = null;
loadingMessages.clear();
errorMessages.clear();
statusHandler.clear();
}
/**
* A message firing to the StatusManager puts it on the queue of pending
* messages. If this message is the active message, then it fires to the
* handler as well.
*
* @param msg
*/
void fire(StatusMessage msg) {
if ((msg.getType() == MessageType.FATAL) && (firedFatal == null)) {
statusHandler.onStatusMessage(msg);
firedFatal = msg;
} else {
possiblyAddMessage(msg);
possiblyFireHandler();
}
}
/**
* Convenience method for giving the message lists ordered-set like semantics
* where an update will not add another element but will re-fire the handler
* if the given message is the active message.
*
* @param msg
*/
private void possiblyAddMessage(StatusMessage msg) {
JsoArray<StatusMessage> list = null;
switch (msg.getType()) {
case LOADING:
list = loadingMessages;
break;
case CONFIRMATION:
list = confirmationMessages;
break;
case ERROR:
list = errorMessages;
break;
case FATAL:
return;
default:
Log.error(getClass(), "Got a status message of unknown type " + msg.getType());
return;
}
boolean found = false;
for (int i = 0; !found && i < list.size(); i++) {
if (list.get(i) == msg) {
found = true;
}
}
if (found && (msg == activeMessage)) {
// Trigger a re-fire to the handler if the active message fires again.
activeMessage = null;
} else if (!found) {
list.add(msg);
}
}
/**
* If the top message has changed, then notify the handler.
*/
private void possiblyFireHandler() {
if (firedFatal != null) {
// Drop all other messages ones a fatal message has fired.
return;
}
// Normal message handling.
StatusMessage top = null;
if (!errorMessages.isEmpty()) {
top = errorMessages.peek();
} else if (!confirmationMessages.isEmpty()) {
top = confirmationMessages.peek();
} else if (!loadingMessages.isEmpty()) {
top = loadingMessages.peek();
}
if (top == null) {
statusHandler.clear();
} else if (top != activeMessage) {
statusHandler.onStatusMessage(top);
}
activeMessage = top;
}
/**
* Set a new status handler. This will clear the view of the old handler and
* immediately fire the top status message to the new handler.
*
* @param statusHandler the new status handler.
*/
public void setHandler(StatusHandler statusHandler) {
this.statusHandler.clear();
this.statusHandler = statusHandler;
if (firedFatal != null) {
// On a handoff, persist the fatal message
statusHandler.onStatusMessage(firedFatal);
} else if (activeMessage != null) {
activeMessage = null;
possiblyFireHandler();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/status/StatusMessage.java | client/src/main/java/com/google/collide/client/status/StatusMessage.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.client.status;
import collide.client.util.Elements;
import com.google.collide.json.client.JsoArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import elemental.client.Browser;
import elemental.html.AnchorElement;
import elemental.html.SpanElement;
/**
* This is the base of all message types.
*
* All common message properties are set through this base class. Message
* events are routed through double-dispatch in the protected do*() methods
* while their public facing counterparts ensure that the base message state is
* consistent (e.g. setting canceled).
*/
public class StatusMessage {
/**
* A loading message indicates that the application is waiting for a slow
* operation.
*
* A confirmation message is an informational message to the user.
*
* An error message indicates that there has been a recoverable or transient
* error.
*
* A fatal message indicates that the application has entered into an
* unrecoverable state (for example, an uncaught exception). Once a fatal
* message fires, no other subsequent status messages will fire.
*
* NOTE: These message types are in order of priority.
*/
public enum MessageType {
LOADING, //
CONFIRMATION, //
ERROR, //
FATAL
}
// The default delay to use for avoiding message flicker.
public static final int DEFAULT_DELAY = 200;
public static final StatusAction RELOAD_ACTION = new StatusAction() {
@Override
public void renderAction(SpanElement actionContainer) {
actionContainer.setTextContent("Reload Collide");
}
@Override
public void onAction() {
Browser.getWindow().getLocation().reload();
}
};
public static final StatusAction FEEDBACK_ACTION = new StatusAction() {
@Override
public void renderAction(SpanElement actionContainer) {
AnchorElement a = Elements.createAnchorElement();
a.setHref(
"https://groups.google.com/forum/?domain=google.com#!newtopic/collide-discussions");
a.setTarget("_blank");
a.setTextContent("Tell us what happened!");
a.getStyle().setColor("yellow");
actionContainer.appendChild(a);
}
@Override
public void onAction() {
// Nothing. Let the native anchor do its thing.
}
};
private final JsoArray<StatusAction> actions = JsoArray.create();
private boolean canceled = false;
private boolean dismissable = false;
private long expiryTime = 0;
private String longText;
private final StatusManager statusManager;
private String text;
private final MessageType type;
public StatusMessage(StatusManager statusManager, MessageType type, String text) {
this.statusManager = statusManager;
this.type = type;
this.text = text;
}
/**
* Cancel a message. Once a message is canceled, all subsequent fires are
* no-ops.
*/
public final void cancel() {
canceled = true;
statusManager.cancel(this);
}
/**
* Cancel an event in the future.
*
* @param milliseconds time to expiry.
*/
public final void expire(int milliseconds) {
expiryTime = System.currentTimeMillis() + milliseconds;
Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
@Override
public boolean execute() {
cancel();
return false;
}
}, milliseconds);
}
/**
* Fires a message to the status manager. If the message has been canceled,
* this is a no-op. If the message has already been fired, then update that
* message.
*/
public final void fire() {
if (!canceled) {
statusManager.fire(this);
}
}
/**
* Fire a message with a delay. If the message is canceled before the delay,
* this is a no-op.
*
* @param milliseconds time to delay firing this message.
*/
public final void fireDelayed(int milliseconds) {
Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
@Override
public boolean execute() {
fire();
return false;
}
}, milliseconds);
}
/**
* @return the actions associated with this message or null
*/
public JsoArray<StatusAction> getActions() {
return actions;
}
public String getLongText() {
return longText == null ? "" : longText;
}
/**
* Concrete implementations can reference the {@link StatusManager} through
* this getter.
*
* @return the @{link StatusManager} for this message.
*/
protected final StatusManager getStatusManager() {
return statusManager;
}
public String getText() {
return text == null ? "" : text;
}
public void setText(String text) {
this.text = text;
}
/**
* @return return the time in milliseconds left until expiration or 0 if there
* is no pending expiration.
*/
public int getTimeToExpiry() {
return (int) (expiryTime == 0 ? 0 : Math.max(0, expiryTime - System.currentTimeMillis()));
}
public MessageType getType() {
return type;
}
/**
* @return Can the user manually dismiss this message?
*/
public boolean isDismissable() {
return dismissable;
}
public void addAction(StatusAction action) {
this.actions.add(action);
}
/**
* @param dismissable whether or not this message can be dismissed by the
* user.
*/
public void setDismissable(boolean dismissable) {
this.dismissable = dismissable;
}
/**
* The status message must fit on one line, but the message can be expanded to
* show more detailed information like a stack trace using long text.
*
* @param longText
*/
public void setLongText(String longText) {
this.longText = longText;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/status/StatusAction.java | client/src/main/java/com/google/collide/client/status/StatusAction.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.client.status;
import elemental.html.SpanElement;
/**
* An action can be used to make a message interactive.
*/
public interface StatusAction {
/**
* Called when the user initiates the action.
*/
void onAction();
/**
* Render the DOM for the action.
*/
void renderAction(SpanElement actionContainer);
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/DocumentManagerFileTreeModelListener.java | client/src/main/java/com/google/collide/client/document/DocumentManagerFileTreeModelListener.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.client.document;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeNode;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.history.RootPlace;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.Pair;
import com.google.collide.shared.document.Document;
/**
* Listener for relevant file tree model events (such as a node being removed) and updates the
* document manager accordingly.
*
*/
class DocumentManagerFileTreeModelListener implements FileTreeModel.TreeModelChangeListener {
private final DocumentManager documentManager;
private final FileTreeModel fileTreeModel;
DocumentManagerFileTreeModelListener(
DocumentManager documentManager, FileTreeModel fileTreeModel) {
this.documentManager = documentManager;
this.fileTreeModel = fileTreeModel;
attachListeners();
}
private void attachListeners() {
fileTreeModel.addModelChangeListener(this);
}
void teardown() {
fileTreeModel.removeModelChangeListener(this);
}
@Override
public void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode) {}
@Override
public void onNodeMoved(
PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode) {
// Update the document path if the document exists.
String fileEditSessionKey = (node == null) ? null : node.getFileEditSessionKey();
if (fileEditSessionKey != null) {
Document document = documentManager.getDocumentByFileEditSessionKey(fileEditSessionKey);
if (document != null) {
DocumentMetadata.putPath(document, newPath);
return;
}
}
}
@Override
public void onNodesRemoved(JsonArray<FileTreeNode> oldNodes) {
JsonArray<Document> documents = documentManager.getDocuments();
JsonArray<Pair<Document, Editor>> openDocuments = documentManager.getOpenDocuments();
for (int k = 0; k < oldNodes.size(); k++) {
// Note that this can be a parent directory
PathUtil removedPath = oldNodes.get(k).getNodePath();
for (int i = 0, n = documents.size(); i < n; i++) {
Document document = documents.get(i);
if (DocumentMetadata.isLinkedToFile(document)) {
PathUtil path = DocumentMetadata.getPath(document);
if (path == null || !removedPath.containsPath(path)) {
continue;
}
updateEditorsForFileInvalidated(document, openDocuments, false);
}
}
}
}
private void updateEditorsForFileInvalidated(Document document,
JsonArray<Pair<Document, Editor>> openDocuments, boolean switchToReadOnly) {
boolean isDocumentOpen = false;
for (int j = 0; j < openDocuments.size(); j++) {
Pair<Document, Editor> documentAndEditor = openDocuments.get(j);
if (documentAndEditor.first == document) {
if (!switchToReadOnly) {
/*
* TODO: in future CL, update UI to handle tabs, currently we display a
* NoFileSelected place holder page in editor
*/
RootPlace.PLACE.fireChildPlaceNavigation(WorkspacePlace.PLACE.createNavigationEvent());
} else {
documentAndEditor.second.setReadOnly(true);
}
documentManager.unlinkFromFile(document);
isDocumentOpen = true;
}
}
if (!isDocumentOpen) {
documentManager.garbageCollectDocument(document);
}
}
@Override
public void onNodeReplaced(FileTreeNode oldNode, FileTreeNode newNode) {
JsonArray<Document> documents = documentManager.getDocuments();
JsonArray<Pair<Document, Editor>> openDocuments = documentManager.getOpenDocuments();
PathUtil nodePath = newNode.getNodePath();
for (int i = 0, n = documents.size(); i < n; i++) {
Document document = documents.get(i);
if (DocumentMetadata.isLinkedToFile(document) && nodePath.containsPath(
DocumentMetadata.getPath(document))) {
updateEditorsForFileInvalidated(document, openDocuments, true);
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/DocumentMetadata.java | client/src/main/java/com/google/collide/client/document/DocumentMetadata.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.client.document;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.ConflictChunk;
import com.google.collide.dto.NodeConflictDto.ConflictHandle;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
/**
* Utility methods for retrieving metadata associated with a document.
*/
public final class DocumentMetadata {
private static final String TAG_LINKED_TO_FILE = DocumentManager.class.getName()
+ ":LinkedToFile";
private static final String TAG_FILE_EDIT_SESSION_KEY = DocumentManager.class.getName()
+ ":FileEditSessionKey";
private static final String TAG_BEGIN_CC_REVISION = DocumentManager.class.getName()
+ ":BeginCcRevision";
private static final String TAG_PATH = DocumentManager.class.getName() + ":Path";
// TODO: move conflicts and conflict handle out of metadata.
private static final String TAG_CONFLICTS = DocumentManager.class.getName() + ":Conflicts";
private static final String TAG_CONFLICT_HANDLE =
DocumentManager.class.getName() + ":ConflictHandle";
/**
* Returns whether the document is linked to a file.
*
* If a document is not linked to a file, it is a client-only document.
* Metadata such as {@link #getFileEditSessionKey(Document)},
* {@link #getBeginCcRevision(Document)}, {@link #getConflicts(Document)},
* {@link #getPath(Document)} will be invalid.
*/
public static boolean isLinkedToFile(Document document) {
return ((Boolean) document.getTag(TAG_LINKED_TO_FILE)).booleanValue();
}
static void putLinkedToFile(Document document, boolean isLinkedToFile) {
document.putTag(TAG_LINKED_TO_FILE, isLinkedToFile);
}
/**
* Only valid if {@link #isLinkedToFile(Document)} is true.
*/
public static String getFileEditSessionKey(Document document) {
ensureLinkedToFile(document);
return document.getTag(TAG_FILE_EDIT_SESSION_KEY);
}
static void putFileEditSessionKey(Document document, String fileEditSessionKey) {
document.putTag(TAG_FILE_EDIT_SESSION_KEY, fileEditSessionKey);
}
/**
* Only valid if {@link #isLinkedToFile(Document)} is true.
*/
public static int getBeginCcRevision(Document document) {
ensureLinkedToFile(document);
return ((Integer) document.getTag(TAG_BEGIN_CC_REVISION)).intValue();
}
static void putBeginCcRevision(Document document, int beginCcRevision) {
document.putTag(TAG_BEGIN_CC_REVISION, beginCcRevision);
}
/**
* Only valid if {@link #isLinkedToFile(Document)} is true.
*/
public static PathUtil getPath(Document document) {
ensureLinkedToFile(document);
return document.getTag(TAG_PATH);
}
static void putPath(Document document, PathUtil path) {
document.putTag(TAG_PATH, path);
}
/**
* Only valid if {@link #isLinkedToFile(Document)} is true.
*/
public static JsonArray<ConflictChunk> getConflicts(Document document) {
ensureLinkedToFile(document);
return document.getTag(TAG_CONFLICTS);
}
static void putConflicts(Document document, JsonArray<ConflictChunk> conflicts) {
document.putTag(TAG_CONFLICTS, conflicts);
}
/**
* Only valid if {@link #isLinkedToFile(Document)} is true.
*/
public static ConflictHandle getConflictHandle(Document document) {
ensureLinkedToFile(document);
return document.getTag(TAG_CONFLICT_HANDLE);
}
static void putConflictHandle(Document document, ConflictHandle conflictHandle) {
document.putTag(TAG_CONFLICT_HANDLE, conflictHandle);
}
private static void ensureLinkedToFile(Document document) {
if (!isLinkedToFile(document)) {
throw new IllegalStateException("Document must be linked to file");
}
}
public static void clearConflicts(Document document) {
document.putTag(TAG_CONFLICT_HANDLE, null);
document.putTag(TAG_CONFLICTS, null);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/DocumentManager.java | client/src/main/java/com/google/collide/client/document/DocumentManager.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.client.document;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeNode;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.ConflictChunk;
import com.google.collide.dto.FileContents;
import com.google.collide.dto.NodeConflictDto.ConflictHandle;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.Pair;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
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;
/**
* Manager for documents and editors.
*
* Note that a document can be unlinked from a file <em>while</em> it is open
* in an editor!
*
*/
public class DocumentManager {
public static DocumentManager create(FileTreeModel fileTreeModel, FileTreeController<?> fileTreeController) {
return new DocumentManager(fileTreeModel, fileTreeController);
}
/**
* Listener for changes to the lifecycle of individual documents.
*/
public interface LifecycleListener {
/**
* Called after the document is created.
*/
void onDocumentCreated(Document document);
/**
* Called after the document is linked to a file.
*/
void onDocumentLinkedToFile(Document document, FileContents fileContents);
/**
* Called after the document is opened in an editor.
*/
void onDocumentOpened(Document document, Editor editor);
/**
* Called after the document is no longer open in an editor.
*/
void onDocumentClosed(Document document, Editor editor);
/**
* Called <em>before</em> the document is unlinked to its file (calling the
* {@link DocumentMetadata} getters for file-related metadata is okay.)
*/
void onDocumentUnlinkingFromFile(Document document);
/**
* Called after the document has been garbage collected.
*/
void onDocumentGarbageCollected(Document document);
}
/**
* Listener for the loading of a document.
*/
public interface GetDocumentCallback {
void onDocumentReceived(Document document);
void onUneditableFileContentsReceived(FileContents contents);
void onFileNotFoundReceived();
}
private static final int MAX_CACHED_DOCUMENTS = 4;
private final FileTreeModel fileTreeModel;
private final DocumentManagerNetworkController networkController;
private final DocumentManagerFileTreeModelListener fileTreeModelListener;
/**
* All of the documents, ordered by least-recently used documents (index 0 is
* the least recently used).
*/
private final JsonArray<Document> documents = JsonCollections.createArray();
private final JsonStringMap<Document> documentsByFileEditSessionKey = JsonCollections.createMap();
private final ListenerManager<LifecycleListener> lifecycleListenerManager =
ListenerManager.create();
/*
* TODO: this will need to become a Document -> Editors map
* eventually
*/
private Editor editor;
private DocumentManager(FileTreeModel fileTreeModel, FileTreeController<?> fileTreeController) {
this.fileTreeModel = fileTreeModel;
networkController = new DocumentManagerNetworkController(this, fileTreeController);
fileTreeModelListener = new DocumentManagerFileTreeModelListener(this, fileTreeModel);
}
public void cleanup() {
fileTreeModelListener.teardown();
networkController.teardown();
while (documents.size() > 0) {
garbageCollectDocument(documents.get(0));
}
}
public ListenerRegistrar<LifecycleListener> getLifecycleListenerRegistrar() {
return lifecycleListenerManager;
}
/**
* Returns a copy of the list of documents managed by this class.
*/
public JsonArray<Document> getDocuments() {
return documents.copy();
}
public Document getDocumentByFileEditSessionKey(String fileEditSessionKey) {
return documentsByFileEditSessionKey.get(fileEditSessionKey);
}
public void attachToEditor(final Document document, final Editor editor) {
final Document oldDocument = editor.getDocument();
if (oldDocument != null) {
detachFromEditor(editor, oldDocument);
}
this.editor = editor;
markAsActive(document);
editor.setDocument(document);
lifecycleListenerManager.dispatch(new Dispatcher<LifecycleListener>() {
@Override
public void dispatch(LifecycleListener listener) {
listener.onDocumentOpened(document, editor);
}
});
}
private void detachFromEditor(final Editor editor, final Document document) {
lifecycleListenerManager.dispatch(new Dispatcher<LifecycleListener>() {
@Override
public void dispatch(LifecycleListener listener) {
listener.onDocumentClosed(document, editor);
}
});
clearDocumentState(document);
}
/*
* TODO: in the future, different features will remove
* non-persistent stuff themselves. For now, clear everything.
*/
private void clearDocumentState(final Document document) {
for (Line line = document.getFirstLine(); line != null; line = line.getNextLine()) {
line.clearTags();
}
// Column anchors exist on the line via a tag, so those get cleared above
document.getAnchorManager().clearLineAnchors();
}
public void getDocument(PathUtil path, GetDocumentCallback callback) {
if (fileTreeModel.getWorkspaceRoot() != null) {
// FileTreeModel is populated so get the file edit session key for this path
FileTreeNode node = fileTreeModel.getWorkspaceRoot().findChildNode(path);
if (node != null && node.getFileEditSessionKey() != null) {
String fileEditSessionKey = node.getFileEditSessionKey();
Document document = documentsByFileEditSessionKey.get(fileEditSessionKey);
if (document != null) {
callback.onDocumentReceived(document);
return;
}
}
}
networkController.load(path, callback);
// handleEditableFileReceived will be called async
}
void handleEditableFileReceived(
FileContents fileContents, JsonArray<GetDocumentCallback> callbacks) {
/*
* One last check to make sure we don't already have a Document for this
* file
*/
Document document = documentsByFileEditSessionKey.get(fileContents.getFileEditSessionKey());
if (document == null) {
document = createDocument(fileContents.getContents(), new PathUtil(fileContents.getPath()),
fileContents.getFileEditSessionKey(), fileContents.getCcRevision(),
fileContents.getConflicts(), fileContents.getConflictHandle(), fileContents);
tryGarbageCollect();
} else {
/*
* Ensure we have the latest path stashed in the metadata. One case where
* this matters is if a file is renamed, we will have had the old path --
* this logic will update its path.
*/
DocumentMetadata.putPath(document, new PathUtil(fileContents.getPath()));
}
for (int i = 0, n = callbacks.size(); i < n; i++) {
callbacks.get(i).onDocumentReceived(document);
}
}
/**
* @param conflicts only required for documents that are in a conflicted state
* @param conflictHandle only required for documents that are in a conflicted state
*/
private Document createDocument(String contents, PathUtil path, String fileEditSessionKey,
int ccRevision, JsonArray<ConflictChunk> conflicts, ConflictHandle conflictHandle,
final FileContents fileContents) {
final Document document = Document.createFromString(contents);
documents.add(document);
boolean isLinkedToFile = fileEditSessionKey != null;
if (isLinkedToFile) {
documentsByFileEditSessionKey.put(fileEditSessionKey, document);
}
DocumentMetadata.putLinkedToFile(document, isLinkedToFile);
DocumentMetadata.putPath(document, path);
DocumentMetadata.putFileEditSessionKey(document, fileEditSessionKey);
DocumentMetadata.putBeginCcRevision(document, ccRevision);
DocumentMetadata.putConflicts(document, conflicts);
DocumentMetadata.putConflictHandle(document, conflictHandle);
lifecycleListenerManager.dispatch(new Dispatcher<LifecycleListener>() {
@Override
public void dispatch(LifecycleListener listener) {
listener.onDocumentCreated(document);
}
});
if (isLinkedToFile) {
lifecycleListenerManager.dispatch(new Dispatcher<LifecycleListener>() {
@Override
public void dispatch(LifecycleListener listener) {
listener.onDocumentLinkedToFile(document, fileContents);
}
});
}
// Save the fileEditSessionKey into the tree node.
if (fileTreeModel.getWorkspaceRoot() != null) {
FileTreeNode node = fileTreeModel.getWorkspaceRoot().findChildNode(path);
if (node != null) {
node.setFileEditSessionKey(fileEditSessionKey);
}
}
return document;
}
private void markAsActive(Document document) {
if (documents.peek() != document) {
// Ensure it is at the top
documents.remove(document);
documents.add(document);
}
}
private void tryGarbageCollect() {
int removeCount = documents.size() - MAX_CACHED_DOCUMENTS;
for (int i = 0; i < documents.size() && removeCount > 0;) {
Document document = documents.get(i);
boolean documentIsOpen = editor != null && editor.getDocument() == document;
if (documentIsOpen) {
i++;
continue;
}
garbageCollectDocument(document);
removeCount--;
}
}
void garbageCollectDocument(final Document document) {
if (DocumentMetadata.isLinkedToFile(document)) {
unlinkFromFile(document);
}
documents.remove(document);
lifecycleListenerManager.dispatch(new Dispatcher<LifecycleListener>() {
@Override
public void dispatch(LifecycleListener listener) {
listener.onDocumentGarbageCollected(document);
}
});
}
public void unlinkFromFile(final Document document) {
lifecycleListenerManager.dispatch(new Dispatcher<DocumentManager.LifecycleListener>() {
@Override
public void dispatch(LifecycleListener listener) {
listener.onDocumentUnlinkingFromFile(document);
}
});
documentsByFileEditSessionKey.remove(DocumentMetadata.getFileEditSessionKey(document));
DocumentMetadata.putLinkedToFile(document, false);
}
Document getMostRecentlyActiveDocument() {
return documents.peek();
}
/**
* Returns a potentially empty list of pairs of a document and an editor.
*/
JsonArray<Pair<Document, Editor>> getOpenDocuments() {
JsonArray<Pair<Document, Editor>> result = JsonCollections.createArray();
if (editor == null || editor.getDocument() == null) {
return result;
}
/*
* TODO: When there are more than one editor, this will not be
* trivial
*/
result.add(Pair.of(editor.getDocument(), editor));
return result;
}
public Document getDocumentById(int documentId) {
for (int i = 0, n = documents.size(); i < n; i++) {
if (documents.get(i).getId() == documentId) {
return documents.get(i);
}
}
return null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/DocumentManagerNetworkController.java | client/src/main/java/com/google/collide/client/document/DocumentManagerNetworkController.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.client.document;
import collide.client.filetree.FileTreeController;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.document.DocumentManager.GetDocumentCallback;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.FileContents.ContentType;
import com.google.collide.dto.GetFileContentsResponse;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.GetFileContentsImpl;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
import xapi.log.X_Log;
/**
* Controller responsible for loading documents (and uneditable files) from the
* server.
*
* This class accepts multiple calls to
* {@link #load(PathUtil, GetDocumentCallback)} for the same path and intelligently
* batches together the callbacks so only one network request will occur.
*/
class DocumentManagerNetworkController {
private final DocumentManager documentManager;
private final FileTreeController<?> fileTreeController;
/** Path to a list of {@link GetDocumentCallback} */
JsonStringMap<JsonArray<GetDocumentCallback>> outstandingCallbacks = JsonCollections.createMap();
private StatusMessage loadingMessage;
DocumentManagerNetworkController(DocumentManager documentManager, FileTreeController<?> fileTreeController) {
this.documentManager = documentManager;
this.fileTreeController = fileTreeController;
}
public void teardown() {
if (loadingMessage != null) {
cancelLoadingMessage();
}
fileTreeController.getMessageFilter().removeMessageRecipient(RoutingTypes.GETFILECONTENTSRESPONSE);
}
void load(PathUtil path, GetDocumentCallback callback) {
boolean shouldRequestFile = addCallback(path, callback);
if (shouldRequestFile) {
requestFile(path);
}
}
private boolean addCallback(PathUtil path, GetDocumentCallback callback) {
JsonArray<GetDocumentCallback> callbacks = outstandingCallbacks.get(path.getPathString());
if (callbacks == null) {
callbacks = JsonCollections.createArray(callback);
outstandingCallbacks.put(path.getPathString(), callbacks);
return true;
} else {
callbacks.add(callback);
return false;
}
}
private void requestFile(final PathUtil path) {
delayLoadingMessage(path);
// Fetch the file's contents
GetFileContentsImpl getFileContents = GetFileContentsImpl.make().setPath(path.getPathString());
fileTreeController.getFileContents(getFileContents,
new ApiCallback<GetFileContentsResponse>() {
@Override
public void onMessageReceived(GetFileContentsResponse response) {
if (!handleFileReceived(response)) {
X_Log.warn(DocumentManagerNetworkController.class,
"Tried to load a missing file", path, "\nresulted in:", response);
}
}
@Override
public void onFail(FailureReason reason) {
Log.error(getClass(), "Failed to retrieve file contents for path " + path);
}
});
}
/**
* Called when the file contents are received from the network. Routes to the appropriate content
* handling mechanism depending on whether or not the file content type is text, an image, or some
* other binarySuffix file.
*/
private boolean handleFileReceived(GetFileContentsResponse response) {
if (response.getFileContents() == null) {
// Woops! Asked to load a missing file...
return false;
}
boolean isUneditable =
(response.getFileContents().getContentType() == ContentType.UNKNOWN_BINARY)
|| (response.getFileContents().getContentType() == ContentType.IMAGE);
PathUtil path = new PathUtil(response.getFileContents().getPath());
cancelLoadingMessage();
JsonArray<GetDocumentCallback> callbacks = outstandingCallbacks.remove(path.getPathString());
Preconditions.checkNotNull(callbacks);
if (!response.getFileExists()) {
// Dispatch to callbacks directly
for (int i = 0, n = callbacks.size(); i < n; i++) {
callbacks.get(i).onFileNotFoundReceived();
}
} else if (isUneditable) {
// Dispatch to callbacks directly
for (int i = 0, n = callbacks.size(); i < n; i++) {
callbacks.get(i).onUneditableFileContentsReceived(response.getFileContents());
}
} else {
documentManager.handleEditableFileReceived(response.getFileContents(), callbacks);
}
return true;
}
private void delayLoadingMessage(PathUtil path) {
cancelLoadingMessage();
loadingMessage =
new StatusMessage(fileTreeController.getStatusManager(), MessageType.LOADING, "Loading "
+ path.getBaseName() + "...");
loadingMessage.fireDelayed(StatusMessage.DEFAULT_DELAY);
}
private void cancelLoadingMessage() {
if (loadingMessage != null) {
loadingMessage.cancel();
loadingMessage = null;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/linedimensions/ColumnOffsetCache.java | client/src/main/java/com/google/collide/client/document/linedimensions/ColumnOffsetCache.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.client.document.linedimensions;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.collide.shared.Pair;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.util.SortedList;
/**
* A cache object that is attached to each line which caches its offsets.
*
*/
class ColumnOffsetCache {
/**
* An object which caches a map of a line column to its left edge pixel
* position. This allows efficient lookup of column positions when variable
* width characters are used.
*/
public static class ColumnOffset {
/**
* Orders a list of ColumnOffsetCache by their column order.
*/
private static final SortedList.Comparator<ColumnOffset> COLUMN_COMPARATOR =
new SortedList.Comparator<ColumnOffset>() {
@Override
public int compare(ColumnOffset a, ColumnOffset b) {
return a.column - b.column;
}
};
/**
* Finds an object in the column offset list by its X value.
*/
private static final SortedList.OneWayDoubleComparator<ColumnOffset> X_ONE_WAY_COMPARATOR =
new SortedList.OneWayDoubleComparator<ColumnOffset>() {
@Override
public int compareTo(ColumnOffset o) {
return (int) (value - o.x);
}
};
/**
* Finds an object in the column offset list by its Column value.
*/
private static final SortedList.OneWayIntComparator<ColumnOffset> COLUMN_ONE_WAY_COMPARATOR =
new SortedList.OneWayIntComparator<ColumnOffset>() {
@Override
public int compareTo(ColumnOffset o) {
return value - o.column;
}
};
public final int column;
public final double x;
/** Width of previous column's character */
public final double previousColumnWidth;
public ColumnOffset(int column, double x, double previousColumnWidth) {
this.column = column;
this.x = x;
this.previousColumnWidth = previousColumnWidth;
}
public boolean isZeroWidth() {
return previousColumnWidth == 0;
}
}
/**
* Gets the {@link ColumnOffsetCache} stored on the given line. If it does not
* already exist it will be created. If it already exists but with a different
* zoomId, it will be cleared, removed and a new one created.
*
* @param line The line for this ColumnOffsetCache
* @param zoomId A unique parameter which identifies the current page zoom
* level. This id is checked before the cache is returned. If it does
* not match the parameter stored inside the cache being retrieved then
* the cache is considered out of date and a new one constructed.
*/
public static ColumnOffsetCache getOrCreate(Line line, double zoomId) {
ColumnOffsetCache offsetCache = getUnsafe(line);
if (offsetCache == null || offsetCache.zoomId != zoomId) {
offsetCache = createCache(line, zoomId);
}
return offsetCache;
}
/**
* Returns a column offset cache without checking its zoom level first.
*
* <p>If the zoom level has changed the data in this cache will be stale and
* need to be rebuilt. Use this only if you aren't going to read it for
* position data. If you can you should use {@link #getOrCreate}.
*
* @return {@code null} if cache doesn't exist
*/
@Nullable
public static ColumnOffsetCache getUnsafe(@Nonnull Line line) {
return line.getTag(LINE_TAG_COLUMN_OFFSET_CACHE);
}
/**
* The internal key used to tag a line with its cache.
*/
private static final String LINE_TAG_COLUMN_OFFSET_CACHE =
ColumnOffsetCache.class.getName() + "COLUMN_OFFSET_CACHE";
/**
* An object which serves as a flag to indicate that the entire string has
* been measured. This prevents us from duplicating measurements when the user
* clicks past the end of a line.
*/
static final ColumnOffset FULLY_MEASURED =
new ColumnOffset(Integer.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE);
/**
* A column offset which is used to early out when the user is requesting
* column 0 or pixel 0.
*/
public static final ColumnOffset ZERO_OFFSET = new ColumnOffset(0, 0, 0);
private final double zoomId;
private SortedList<ColumnOffset> columnOffsets;
ColumnOffset measuredOffset = ZERO_OFFSET;
public ColumnOffsetCache(double zoomId) {
this.zoomId = zoomId;
}
private SortedList<ColumnOffset> getCache() {
if (columnOffsets == null) {
columnOffsets = new SortedList<ColumnOffset>(ColumnOffset.COLUMN_COMPARATOR);
}
return columnOffsets;
}
/**
* Returns the exact {@link ColumnOffset} or the nearest {@link ColumnOffset}
* less than the requested column. Clients should check if measurements are
* needed first by calling {@link #isColumnMeasurementNeeded(int)}.
*/
public ColumnOffset getColumnOffsetForColumn(int column) {
assert !isColumnMeasurementNeeded(column) : "Measurement of Column was needed";
if (column == 0 || columnOffsets == null || columnOffsets.size() == 0) {
return ZERO_OFFSET;
}
ColumnOffset.COLUMN_ONE_WAY_COMPARATOR.setValue(column);
return getColumnOffset(ColumnOffset.COLUMN_ONE_WAY_COMPARATOR);
}
/**
* Returns the exact {@link ColumnOffset} or the nearest {@link ColumnOffset}
* less than the requested X. Clients should check if measurements are needed
* first by calling {@link #isXMeasurementNeeded(double)}.
*
* @param defaultCharacterWidth The width that will be returned if the
* character is not a special width.
* @param x The x pixel value
*
* @return This function will return the offset which corresponds either to
* the base character, or to the last zero-width mark following a base
* character. It will also return the width of the current column
* character so fractional columns can be determined.
*/
public Pair<ColumnOffset, Double> getColumnOffsetForX(double x, double defaultCharacterWidth) {
assert !isXMeasurementNeeded(x) : "Measurement of X was needed";
if (x == 0 || columnOffsets == null || columnOffsets.size() == 0) {
return Pair.of(ZERO_OFFSET, defaultCharacterWidth);
}
ColumnOffset.X_ONE_WAY_COMPARATOR.setValue(x);
int index = getColumnOffsetIndex(ColumnOffset.X_ONE_WAY_COMPARATOR, true);
if (index + 1 >= getCache().size()) {
return Pair.of(getCache().get(index), defaultCharacterWidth);
}
ColumnOffset offset = index < 0 ? ZERO_OFFSET : getCache().get(index);
ColumnOffset nextOffset = getCache().get(index < 0 ? 0 : index + 1);
/*
* So this is confusing but since a column offset always represents the
* character before its column, we look to the next one to see if it is one
* column more than us, if it is then we can grab the width of this
* character from it since its special; otherwise, it's normal.
*/
return Pair.of(offset, nextOffset.column == offset.column + 1
? nextOffset.previousColumnWidth : defaultCharacterWidth);
}
/**
* Returns the last entry in the cache. If no entries are in the cache it will
* return {@link #ZERO_OFFSET}.
*/
public ColumnOffset getLastColumnOffsetInCache() {
if (columnOffsets == null || columnOffsets.size() == 0) {
return ZERO_OFFSET;
}
return columnOffsets.get(columnOffsets.size() - 1);
}
/**
* Returns a {@link ColumnOffset} using the logic in {@link
* #getColumnOffset(com.google.collide.shared.util.SortedList.OneWayComparator)}
*
* @return {@link #ZERO_OFFSET} if there are no items in the cache, otherwise
* either the matched {@link ColumnOffset} or one with less than the
* requested value.
*/
private ColumnOffset getColumnOffset(SortedList.OneWayComparator<ColumnOffset> comparator) {
int index = getColumnOffsetIndex(comparator, false);
return index < 0 ? ZERO_OFFSET : getCache().get(index);
}
/**
* Gets the index of the column offset based on the given comparator.
*
* @param comparator The comparator to use for ordering.
* @param findLastOffsetIfZeroWidth if true then
* {@link #findLastCombiningMarkIfItExistsFromCache(int)} will be
* called so that we try to return a {@link ColumnOffset} which is the
* last zero-width in a string of zero-width marks. -1 will be returned
* if no applicable ColumnOffset is in the cache.
*/
private int getColumnOffsetIndex(
SortedList.OneWayComparator<ColumnOffset> comparator, boolean findLastOffsetIfZeroWidth) {
SortedList<ColumnOffset> cache = getCache();
int index = cache.findInsertionIndex(comparator, false);
if (findLastOffsetIfZeroWidth) {
index = findLastCombiningMarkIfItExistsFromCache(index);
}
if (index == 0) {
ColumnOffset value = cache.get(index);
/*
* guards against a condition where the returned offset can be greater
* than the requested value if there are only greater offsets in the cache
* than what was requested.
*/
return comparator.compareTo(value) < 0 ? -1 : 0;
}
return index;
}
/**
* Appends an {@link ColumnOffset} with the specified column, x, and
* previousColumnWidth parameters. Also updates the internal values to note
* how far we have measured.
*
* <p>
* Note: We expect x to correspond to the left edge of column.
* </p>
*/
public void appendOffset(int column, double x, double previousColumnWidth) {
assert getLastColumnOffsetInCache().x <= x;
assert getLastColumnOffsetInCache().column < column;
SortedList<ColumnOffset> cache = getCache();
ColumnOffset cacheOffset = new ColumnOffset(column, x, previousColumnWidth);
cache.add(cacheOffset);
measuredOffset = cacheOffset;
}
/**
* Marks a line's cache dirty starting at the specified column. A column of 0
* will completely clear the cache.
*/
public void markDirty(int column) {
if (column <= 0 || columnOffsets == null || columnOffsets.size() == 0) {
if (columnOffsets != null) {
columnOffsets.clear();
}
measuredOffset = ZERO_OFFSET;
} else {
ColumnOffset.COLUMN_ONE_WAY_COMPARATOR.setValue(column);
int index = columnOffsets.findInsertionIndex(ColumnOffset.COLUMN_ONE_WAY_COMPARATOR, true);
assert index != -1 && index <= columnOffsets.size();
/*
* we can be in a state where index == size() since the column we want to
* mark dirty is past the last entry in the cache. If thats the case we
* only need to update our measuredOffset.
*/
if (index < columnOffsets.size()) {
index = findBaseNonCombiningMarkIfItExistsFromCache(index);
columnOffsets.removeThisAndFollowing(index);
}
measuredOffset = index == 0 ? ZERO_OFFSET : columnOffsets.get(index - 1);
}
}
/**
* Given an index in cache, walks backwards checking the
* {@link ColumnOffset#isZeroWidth} to find the closest non-zero-width
* character entry in the cache. If one does not exist (i.e. a` has only one
* entry for the `) it will walk backwards to the offset entry of the first
* combining mark (i.e. something like a````, it will return the entry of the
* first `).
*/
/*
* This makes it so when someone deletes a combining mark we find the closest
* character to its left which is not a combining mark to it (unless its not a
* special width in which case we return the combining mark offset) and delete
* the appropriate cache entries from there forward.
*/
private int findBaseNonCombiningMarkIfItExistsFromCache(int index) {
for (; index > 0; index--) {
ColumnOffset currentOffset = columnOffsets.get(index);
ColumnOffset previousOffset = columnOffsets.get(index - 1);
/*
* if I'm not zero width return me, otherwise if the offset before me in
* cache is not the previous column then we may be something like a grave
* accent.
*/
if (!currentOffset.isZeroWidth() || currentOffset.column - 1 != previousOffset.column) {
return index;
}
}
return index;
}
/**
* Given an index walks forward checking {@link ColumnOffset#isZeroWidth()} to
* find the last contiguous, zero-width character in the cache. If one does
* not exist it will return index.
*/
private int findLastCombiningMarkIfItExistsFromCache(int index) {
for (; index >= 0 && index < columnOffsets.size() - 1; index++) {
ColumnOffset currentOffset = columnOffsets.get(index);
ColumnOffset nextOffset = columnOffsets.get(index + 1);
// if the next character is not zero-width return me, otherwise march on.
if (!nextOffset.isZeroWidth() || currentOffset.column + 1 != nextOffset.column) {
return index;
}
}
return index;
}
/**
* Checks if the column needs measurement before it can be retrieved by the
* cache.
*/
public boolean isColumnMeasurementNeeded(int column) {
return measuredOffset != FULLY_MEASURED && column > measuredOffset.column;
}
/**
* Checks if the x pixel needs measurement before it can be retrieved by the
* cache.
*/
public boolean isXMeasurementNeeded(double x) {
return measuredOffset != FULLY_MEASURED && x >= measuredOffset.x;
}
/**
* Removes the cache stored on a line, if any.
*/
public static void removeFrom(Line line) {
line.removeTag(LINE_TAG_COLUMN_OFFSET_CACHE);
}
private static ColumnOffsetCache createCache(Line line, double zoomId) {
ColumnOffsetCache offsetCache = new ColumnOffsetCache(zoomId);
line.putTag(LINE_TAG_COLUMN_OFFSET_CACHE, offsetCache);
return offsetCache;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/linedimensions/MeasurementProvider.java | client/src/main/java/com/google/collide/client/document/linedimensions/MeasurementProvider.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.client.document.linedimensions;
/**
* An object which exposes methods which can be used to obtain the width of a
* string.
*
*/
interface MeasurementProvider {
/**
* Measures a string of text and returns its rendered width in pixels.
*/
public double measureStringWidth(String text);
/**
* Returns the width in pixels of a single-standard latin character.
*/
public double getCharacterWidth();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/linedimensions/BrowserMeasurementProvider.java | client/src/main/java/com/google/collide/client/document/linedimensions/BrowserMeasurementProvider.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.client.document.linedimensions;
import collide.client.util.Elements;
import com.google.collide.client.util.dom.FontDimensionsCalculator;
import com.google.collide.client.util.dom.FontDimensionsCalculator.FontDimensions;
import com.google.collide.shared.util.StringUtils;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
/**
* A {@link MeasurementProvider} which utilizes the DOM to measure a string.
*/
class BrowserMeasurementProvider implements MeasurementProvider {
/**
* The minimum number of characters we require to measure.
* #getRenderedStringWidth(String) will use this to duplicate the string when
* measuring short strings.
*/
/*
* this is not completely arbitrary, too low of a number and WebKit
* mis-calculates the width due to rounding errors and minor variations in
* zoom level character widths. As a reference, 10.0 was too small.
*/
private static final double MINIMUM_TEXT_LENGTH = 30.0;
private final FontDimensions fontDimensions;
private final Element element;
public BrowserMeasurementProvider(FontDimensionsCalculator calculator) {
fontDimensions = calculator.getFontDimensions();
element = Elements.createSpanElement(calculator.getFontClassName());
element.getStyle().setVisibility(CSSStyleDeclaration.Visibility.HIDDEN);
element.getStyle().setPosition(CSSStyleDeclaration.Position.ABSOLUTE);
Elements.getBody().appendChild(element);
}
@Override
public double getCharacterWidth() {
return fontDimensions.getCharacterWidth();
}
@Override
public double measureStringWidth(String text) {
LineDimensionsUtils.markTimeline(getClass(), "Starting measurement of text");
int instances = (int) Math.ceil(MINIMUM_TEXT_LENGTH / text.length());
/*
* We add a hardspace since this prevents bi-directional combining marks
* from screwing with our measurement (these spaces must be removed from our
* result at the end).
*/
element.setTextContent(StringUtils.repeatString(text + "\u00A0", instances));
double width = (element.getBoundingClientRect().getWidth() - (getCharacterWidth() * instances))
/ instances;
LineDimensionsUtils.markTimeline(getClass(), "End measurement of text");
return width;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/linedimensions/CanvasMeasurementProvider.java | client/src/main/java/com/google/collide/client/document/linedimensions/CanvasMeasurementProvider.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.client.document.linedimensions;
import collide.client.util.Elements;
import com.google.collide.client.util.dom.FontDimensionsCalculator;
import elemental.html.CanvasElement;
import elemental.html.CanvasRenderingContext2D;
import elemental.html.TextMetrics;
/**
* A measurement provider which utilizes an in-memory canvas to measure text.
*
*/
/*
* TODO: This is currently unused though it would be preferred. There is
* a rounding bug in webkit which causes zoom levels to minutely change the
* width of text. So even though 6px text should always be 6px it is in fact off
* thanks to webkit. The canvas doesn't have this bug and will always correctly
* report the width of text correctly. So until a big webkit patch lands fixing
* rounding bugs we can't switch to this significantly faster provider.
*
* BUG: https://bugs.webkit.org/show_bug.cgi?id=60318
*
* More Specifically: https://bugs.webkit.org/show_bug.cgi?id=71143
*/
public class CanvasMeasurementProvider implements MeasurementProvider {
private final FontDimensionsCalculator calculator;
private final CanvasElement canvas;
public CanvasMeasurementProvider(FontDimensionsCalculator calculator) {
this.calculator = calculator;
canvas = Elements.createCanvas();
}
@Override
public double getCharacterWidth() {
return calculator.getFontDimensions().getCharacterWidth();
}
@Override
public double measureStringWidth(String text) {
CanvasRenderingContext2D context = (CanvasRenderingContext2D) canvas.getContext("2d");
context.setFont(calculator.getFont());
TextMetrics metrics = context.measureText(text);
return metrics.getWidth();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/linedimensions/LineDimensionsCalculator.java | client/src/main/java/com/google/collide/client/document/linedimensions/LineDimensionsCalculator.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.client.document.linedimensions;
import com.google.collide.client.document.linedimensions.ColumnOffsetCache.ColumnOffset;
import com.google.collide.client.util.dom.FontDimensionsCalculator;
import com.google.collide.client.util.dom.FontDimensionsCalculator.FontDimensions;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.Pair;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Document.PreTextListener;
import com.google.collide.shared.document.Document.TextListener;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.document.TextChange.Type;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
import com.google.collide.shared.util.StringUtils;
import com.google.collide.shared.util.UnicodeUtils;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import elemental.client.Browser;
/**
* An object which can accurately measure a {@link Line} and map X coordinates
* to columns and vice versa.
*/
/*
* TL;DR;
*
* We have a fast regex to tell whether a line can use the naive calculations
* for column/x. If it doesn't we have to put it in a span and measure special
* characters then store how much they effect the width of our columns. Tabs
* which are prefixing indentation and suffix carraige returns are special cased
* and don't require measurements.
*/
/*
* Implementation Details
*
* There are three states a line can be in:
*
* 1. Unknown, this is represented by the lack of a NEEDS_OFFSET tag on the
* Line. This is the default line state and means that a user (or this class)
* has yet to visit this line in the document.
*
* 2. No offset needed (false NEEDS_OFFSET value), this state indicates that
* we've visited the line and decided it has no characters which warrant special
* attention. Prefix tabs and suffix carriage returns are included in this state
* since they are a common case. If they exist they will be handled in some very
* simple offset code.
*
* 3. Offset needed (true NEEDS_OFFSET value), this state indicates that there
* are special characters within this line. This includes tabs which appear in
* the middle of a line or carriage-returns which aren't at the end followed by
* a \n. In this state a ColumnOffsetCache is built and put onto the line. It is
* lazily constructed as columns are requested.
*
* ColumnOffsetCache internals:
*
* Once built and attached to a line, the column offset cache maintains a cache
* entry for each special character on a line. The entry will be made for the
* column immediately following the special character and the x value of that
* entry will represent the left edge of that column (the right edge of the
* column with the special character).
*
* All examples assume double-wide characters are 10px and normal characters are
* 5px wide, combining marks are 0px.
*
* For example, if the line is "烏烏龍茶\n" the cache will contain:
*
* [{column: 1, x: 10px }, {column: 2, x: 20px }, {column: 3, x: 30px },
* {column: 4, x: 40px }]
*
* Note that this last entry exists regardless of the \n existing. So the last
* entry may be a column which does not exist in the string.
*
* Using the example, when column 2's x is requested (that is the third
* character in the string), entry [1] will be pulled from the cache and the
* returned left edge will be 20px.
*
* A cache entry is only created for special width characters, any interesting
* character that turns out to be our same width is ignored as well.
*
* For example in the case of "烏aaa烏" the cache will contain:
*
* [{column: 1, x: 10px }, {column: 5, x: 25px }]
*
* In this example if we were interested in column 2 (that is the 3rd character
* in the string or 2nd 'a' character), entry [1] will be pulled from cache,
* then 10px + 5px will be added together and a left edge of 15px will be
* returned.
*
* An important note on combining marks:
*
* Combining marks and some similar characters, show up in the cache as 0 width
* characters. That is when they are measured they add no additional width to
* the string and function as a zero width column. They will still contain an
* entry in cache but it will be marked as isZeroWidth and the x value will
* correspond to the same x value of the previous column.
*
* For example, if the line is "à=à" (note the first a has a combining mark so
* the string is really more like "a`=à" the cache will contain:
*
* [{column: 2, x: 5px, isZeroWidth: true }]
*
* That means if we look up say character 4 (the last à). We will take 5px and
* add 5px to get 10px which would put us to the right of the '=' when rendered.
*
* How the cache is built:
*
* We scan the string for any characters of interest (we vaguely define that as
* any character not part of the original latin alphabet so character code >
* 255). We then measure the entire string up to and including that character.
* If the string matches the length we'd expect, then we cache that the
* character is normal but do not create an offset cache entry. Otherwise we
* store the width of the character so we don't have to measure for it again,
* then create an offset cache entry to denote that this character affects
* columns past it since it has an odd width.
*
* Current Limitations:
*
* Some combining marks combine in both directions (this is mostly script type
* languages). This means they can affect the width of columns before themselves
* (aka make the character the combine width smaller). We have a hack to
* mitigate this but really there's only so much we can do.
*
* Measuring can be expensive in long strings containing a large number of
* different special characters. So if you paste a 500 character string of
* Katakana, then click at the very end, prepare for a small wait while we catch
* up. The good news is that will be mitigated the second time since each of
* those character's width is cached and we won't have to layout again.
*
* Zoom makes us wipe the entire cache (sucks), Unfortunately this can't be
* avoided as different character's scale at different factors (double sucks).
* So we just clear our cache and go about rebuilding.
*
* Further comments:
*
* I'm not sure how docs does it but they seem pretty quick, they bite it hard
* on combining marks (the cursor just moves over the letter), but they do
* handle wider characters fine. The one thing they do have is Arabic makes the
* cursor go right-to-left but still combining mark's don't quite work and in
* fact some don't render correctly at all (which do otherwise).
*/
public class LineDimensionsCalculator {
/**
* Creates a new {@link LineDimensionsCalculator} from a
* {@link FontDimensionsCalculator}.
*/
public static LineDimensionsCalculator create(FontDimensionsCalculator fontCalculator) {
final LineDimensionsCalculator calculator =
new LineDimensionsCalculator(new BrowserMeasurementProvider(fontCalculator));
// add a listener so that we can clear our cache if the dimensions change.
fontCalculator.addCallback(new FontDimensionsCalculator.Callback() {
@Override
public void onFontDimensionsChanged(FontDimensions fontDimensions) {
LineDimensionsCalculator.clearCharacterCacheDueToZoomChange();
}
});
return calculator;
}
/**
* Creates a new {@link LineDimensionsCalculator} with a custom
* {@link MeasurementProvider}.
*/
static LineDimensionsCalculator createWithCustomProvider(MeasurementProvider provider) {
return new LineDimensionsCalculator(provider);
}
/**
* Specifies how a X-to-column conversion determines the column if the X isn't on the exact column
* boundary.
*/
public enum RoundingStrategy {
ROUND, FLOOR, CEIL;
public int apply(double value) {
switch (this) {
case ROUND:
return (int) Math.round(value);
case FLOOR:
return (int) Math.floor(value);
case CEIL:
return (int) Math.ceil(value);
default:
throw new IllegalStateException("Unexpected value for RoundingStrategy");
}
}
}
/**
* A cache used to cache the width of special characters. Would be final
* except there isn't a fast way to clear a map.
*/
private static JsonStringMap<Double> characterWidthCache = JsonCollections.createMap();
/**
* A listener which notifies us of dirty lines. We only have to handle the
* case where the endLine != startLine since the startLine is handled in the
* preTextListener.
*/
private static TextListener textListener = new TextListener() {
@Override
public void onTextChange(com.google.collide.shared.document.Document document,
JsonArray<TextChange> textChanges) {
for (int i = 0; i < textChanges.size(); i++) {
TextChange change = textChanges.get(i);
if (change.getEndLine() != change.getLine()) {
LineDimensionsUtils.isOffsetNeededAndCache(
change.getEndLine(), change.getEndColumn(), change.getType());
}
}
}
};
/**
* A listener which allows us to mark the cache dirty before a text change
* actually takes place.
*/
private static PreTextListener preTextListener = new PreTextListener() {
@Override
public void onPreTextChange(Document document,
Type type,
Line line,
int lineNumber,
int column,
String text) {
/*
* In the case where text is deleted, we only need to mark ourselves dirty
* if there is already an OffsetCache. The insert case though requires
* looking at the newly typed text for special characters.
*/
LineDimensionsUtils.preTextIsOffsetNeededAndCache(line, column, type, text);
}
};
private final RemoverManager listenerManager = new RemoverManager();
private final MeasurementProvider measurementProvider;
private LineDimensionsCalculator(MeasurementProvider measurementProvider) {
this.measurementProvider = measurementProvider;
}
/**
* Sets the currently opened document so we can listen for mutations.
*/
public void handleDocumentChange(Document newDocument) {
// Remove old document listener
listenerManager.remove();
// add the new ones
listenerManager.track(newDocument.getPreTextListenerRegistrar().add(preTextListener));
listenerManager.track(newDocument.getTextListenerRegistrar().add(textListener));
}
/**
* Converts a column to its x coordinate.
*/
public double convertColumnToX(Line line, int column) {
// Simple case we early out
if (column == 0) {
return 0;
}
if (!LineDimensionsUtils.needsOffset(line)) {
return simpleConvertColumnToX(line, column);
}
return convertColumnToXMeasuringIfNeeded(line, column);
}
/**
* Converts an x coordinate to the Editor column.
*/
public int convertXToColumn(Line line, double x, RoundingStrategy roundingStrategy) {
// Easy out (< can happen when selection dragging).
x = x + Browser.getWindow().getScrollX();
if (x <= 0) {
return 0;
}
if (!LineDimensionsUtils.needsOffset(line)) {
return simpleConvertXToColumn(line, x, roundingStrategy);
}
return roundingStrategy.apply(convertXToColumnMeasuringIfNeeded(line, x));
}
/**
* Converts column to x using the {@link ColumnOffsetCache} stored on the
* line, measuring if required.
*/
private double convertColumnToXMeasuringIfNeeded(Line line, int column) {
LineDimensionsUtils.markTimeline(getClass(), "Begin converting Column To X via offset cache.");
ColumnOffsetCache cache = ColumnOffsetCache.getOrCreate(line, getColumnWidth());
checkColumnInCacheAndMeasureIfNeeded(cache, line, column);
ColumnOffset offset = cache.getColumnOffsetForColumn(column);
LineDimensionsUtils.markTimeline(getClass(), "End converting Column To X via offset cache.");
return smartColumnToX(offset, column);
}
/**
* Converts x to a column using the {@link ColumnOffsetCache} stored on the
* line, measuring if needed.
*/
private double convertXToColumnMeasuringIfNeeded(Line line, double x) {
LineDimensionsUtils.markTimeline(getClass(), "Begin converting X To column via offset cache.");
ColumnOffsetCache cache = ColumnOffsetCache.getOrCreate(line, getColumnWidth());
checkXInCacheAndMeasureIfNeeded(cache, line, x);
Pair<ColumnOffset, Double> offsetAndWidth = cache.getColumnOffsetForX(x, getColumnWidth());
LineDimensionsUtils.markTimeline(getClass(), "End converting X To column via offset cache.");
return smartXToColumn(offsetAndWidth.first, offsetAndWidth.second, x);
}
/**
* Smart column to x conversion which converts a column to an x position based
* on a {@link ColumnOffset}.
*/
private double smartColumnToX(ColumnOffset offset, int column) {
if (offset.column == column) {
return offset.x;
}
return offset.x + naiveColumnToX(column - offset.column);
}
/**
* Smart x to column conversion which an x pixel position to a column based on
* a {@link ColumnOffset}.
*/
private double smartXToColumn(ColumnOffset offset, double width, double x) {
double column = offset.column;
if (x == offset.x) {
return column;
} else if (x < offset.x + width) {
/*
* We are converting this exact column so lets taken into account this
* columns length which may be special.
*/
column += (x - offset.x) / width;
} else {
// Figure out the offset in pixels and subtract then convert.
column += naiveXToColumn(x - offset.x);
}
return column;
}
/**
* Naively converts a column to its expected x value not taking into account
* any special characters.
*/
private double naiveColumnToX(double column) {
return column * getColumnWidth();
}
/**
* Naively converts a x pixel value to its expected column not taking into
* account any special characters.
*/
private double naiveXToColumn(double x) {
return x / getColumnWidth();
}
/**
* Finds the adjusted column number due to tab indentation and carriage
* returns. This is used in the simple case to handle prefixing tabs and the
* '\r\n' windows line format. Complex cases are handled in the
* {@link ColumnOffsetCache}.
*/
private double simpleConvertColumnToX(Line line, int column) {
// early out when we are at the start of the line
if (column == 0) {
return 0;
}
LineDimensionsUtils.markTimeline(getClass(), "Calculating simple offset");
// get any indentation tabs that are affecting us
int offsetTabColumns = LineDimensionsUtils.getLastIndentationTabCount(line.getText(), column)
* (LineDimensionsUtils.getTabWidth() - 1);
int offsetCarriageReturn = 0;
if (isColumnAffectedByCarriageReturn(line, column)) {
offsetCarriageReturn = -1;
}
LineDimensionsUtils.markTimeline(getClass(), "End calculating simple offset");
return naiveColumnToX(offsetTabColumns + offsetCarriageReturn + column);
}
private int simpleConvertXToColumn(Line line, double x, RoundingStrategy roundingStrategy) {
if (x == 0) {
return 0;
}
LineDimensionsUtils.markTimeline(getClass(), "Calculating simple offset from x");
/*
* we just have to be conscious here of prefix tabs which may be a different
* width and suffix \r which is 0 width. We deal accordingly.
*/
/*
* we divide x by the width of a tab in pixels to overshoot the number of
* indentation tabs
*/
int columnIfAllTabs = (int) Math.floor(x / naiveColumnToX(LineDimensionsUtils.getTabWidth()));
int offsetTabColumns =
LineDimensionsUtils.getLastIndentationTabCount(line.getText(), columnIfAllTabs);
assert columnIfAllTabs >= offsetTabColumns : "You appear to be less tabs then you say you are";
double lineWidthPxWithoutTabs =
x - (offsetTabColumns * LineDimensionsUtils.getTabWidth() * getColumnWidth());
int column =
roundingStrategy.apply(naiveXToColumn(lineWidthPxWithoutTabs) + offsetTabColumns);
// if we landed on the carriage return column++
if (column < line.length() && line.getText().charAt(column) == '\r') {
column++;
}
LineDimensionsUtils.markTimeline(getClass(), "End calculating simple offset from x");
return column;
}
/**
* @return true if a measurement was performed.
*/
private boolean checkColumnInCacheAndMeasureIfNeeded(
ColumnOffsetCache cache, Line line, int column) {
if (cache.isColumnMeasurementNeeded(column)) {
measureLineStoppingAtColumn(cache, line, column);
return true;
}
return false;
}
/**
* @return true if a measurement was performed.
*/
private boolean checkXInCacheAndMeasureIfNeeded(ColumnOffsetCache cache, Line line, double x) {
if (cache.isXMeasurementNeeded(x)) {
measureLineStoppingAtX(cache, line, x);
return true;
}
return false;
}
/**
* Builds the cache for a line up to or beyond the given endColumn value.
*
* @see #measureLine(ColumnOffsetCache, Line, int, double)
*/
private void measureLineStoppingAtColumn(ColumnOffsetCache cache, Line line, int endColumn) {
measureLine(cache, line, endColumn, Double.MAX_VALUE);
}
/**
* Builds the cache for a line up to or beyond the given endX value.
*
* @see #measureLine(ColumnOffsetCache, Line, int, double)
*/
private void measureLineStoppingAtX(ColumnOffsetCache cache, Line line, double endX) {
measureLine(cache, line, Integer.MAX_VALUE, endX);
}
/**
* Builds the cache for a line up to a particular column. Should not be called
* if the line has already been {@link ColumnOffsetCache#FULLY_MEASURED}.
*
* <p>
* You should only rely on either endColumn or endX, one or the other should
* be the max value for its data type.
*
* @see #measureLineStoppingAtColumn(ColumnOffsetCache, Line, int)
* @see #measureLineStoppingAtX(ColumnOffsetCache, Line, double)
*
* @param endColumn inclusive end column (we will end on or after end)
* @param endX inclusive end x pixel width (we will end on or after endX)
*/
private void measureLine(ColumnOffsetCache cache, Line line, int endColumn, double endX) {
/*
* Starting at cache.measuredColumn we will use the regex to scan forward to
* see if we hit an interesting character other than prefixed tab. if we do
* we'll measure that to that point and append a {@link ColumnOffset} if it
* is a special size. Rinse and repeat.
*/
LineDimensionsUtils.markTimeline(getClass(), "Beginning measure line");
RegExp regexp = UnicodeUtils.regexpNonAsciiTabOrCarriageReturn;
regexp.setLastIndex(cache.measuredOffset.column);
MatchResult result = regexp.exec(line.getText());
if (result != null) {
double x = 0;
do {
// Calculate any x offset up to this point in the line
ColumnOffset offset = cache.getLastColumnOffsetInCache();
double baseXOffset = smartColumnToX(offset, result.getIndex());
/*
* TODO: we can be smarter here, if i > 1, then this character
* is a mark. We could separate out the RegExp into non-spacing,
* enclosing-marks v. spacing-marks and already know which are supposed
* to be zero-width based on which groups are null.
*/
String match = result.getGroup(0);
for (int i = 0; i < match.length(); i++) {
x = addOffsetForResult(cache, match.charAt(i), result.getIndex() + i, line, baseXOffset);
baseXOffset = x;
}
result = regexp.exec(line.getText());
// we have to ensure we measure through the last zero-width character.
} while (result != null && result.getIndex() < endColumn && x < endX);
}
if (result == null) {
cache.measuredOffset = ColumnOffsetCache.FULLY_MEASURED;
return;
}
LineDimensionsUtils.markTimeline(getClass(), "Ending measure line");
}
private double addOffsetForResult(
ColumnOffsetCache cache, char matchedCharacter, int index, Line line, double baseXOffset) {
/*
* Get the string up to the current character, special casing tabs since
* they must render as the correct number of spaces (we replace them when
* the appropriate number of hard-spaces so the browser doesn't trim them).
*/
String partialLineText = line.getText().substring(0, index + 1).replace(
"\t", StringUtils.repeatString("\u00A0", LineDimensionsUtils.getTabWidth()));
/*
* Get the width of the string including our special character and if needed
* append an offset to the cache.
*/
double expectedWidth = baseXOffset + getColumnWidth();
double stringWidth = getStringWidth(matchedCharacter, baseXOffset, partialLineText);
if (stringWidth < baseXOffset) {
/*
* This is a annoying condition where certain combining characters can
* actually change how the previous character is rendered. In some cases
* actually making it smaller than before. This is fairly annoying. It
* only happens when some scripts and languages like Arabic with heavy
* combining marks. This is also possible due to measurement
* inconsistencies when measuring combining characters.
*
* Honestly there's not much we can do, but we make our best attempt to at
* least provide a consistent cursor experience even if it isn't
* navigating the characters correctly (not that I would even know,
* considering I can't speak/read Arabic).
*/
stringWidth = baseXOffset;
}
if (stringWidth != expectedWidth) {
cache.appendOffset(index + 1, stringWidth, stringWidth - baseXOffset);
}
return stringWidth;
}
/**
* Returns the width of a column within the current zoom level.
*/
private double getColumnWidth() {
return measurementProvider.getCharacterWidth();
}
/**
* Determines the width of a string using either the cached width of a
* character of interest or by measuring it using a
* {@link MeasurementProvider}
*
* @param characterOfInterest The character we are interested in which should
* also be the last character of the textToMeasure string.
* @param baseXOffset The base x offset of the column before the character of
* interest. The returned result will be this offset + the width of the
* characterOfInterest.
* @param textToMeasureIncludingCharacterOfInterest The string of text to
* measure including the character of interest.
*
* @return The width of the string which is baseXOffset +
* characterOfInterestWidth
*/
private double getStringWidth(char characterOfInterest, double baseXOffset,
String textToMeasureIncludingCharacterOfInterest) {
switch (characterOfInterest) {
case '\t':
// base + columnWidth * tab_size_in_columns
return baseXOffset + LineDimensionsUtils.getTabWidth() * getColumnWidth();
case '\r':
// zero-width just return the baseXOffset
return baseXOffset;
default:
Double characterWidth = characterWidthCache.get(String.valueOf(characterOfInterest));
// if we know the width already return it
if (characterWidth != null) {
return baseXOffset + characterWidth;
}
// Measure and store the width of the character
double expectedWidth = baseXOffset + getColumnWidth();
double width =
measurementProvider.measureStringWidth(textToMeasureIncludingCharacterOfInterest);
// cache the width of this character
characterWidthCache.put(String.valueOf(characterOfInterest), width - baseXOffset);
return width;
}
}
/**
* Returns true if the column is past a carriage return at the end of a line.
*/
private static boolean isColumnAffectedByCarriageReturn(Line line, int column) {
return line.length() >= 2 && column > line.length() - 2
&& line.getText().charAt(line.length() - 2) == '\r';
}
/**
* Due to differences in how characters measure at different zoom levels (it's
* not a constant factor for all character types!!!), we just clear the world
* and rebuild.
*/
private static void clearCharacterCacheDueToZoomChange() {
LineDimensionsUtils.markTimeline(LineDimensionsCalculator.class, "Cleared cache due to zoom");
characterWidthCache = JsonCollections.createMap();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/document/linedimensions/LineDimensionsUtils.java | client/src/main/java/com/google/collide/client/document/linedimensions/LineDimensionsUtils.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.client.document.linedimensions;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.util.RegExpUtils;
import com.google.collide.shared.util.SharedLogUtils;
import com.google.collide.shared.util.StringUtils;
import com.google.collide.shared.util.UnicodeUtils;
/**
* Various utility functions used by the {@link LineDimensionsCalculator}.
*
*/
public class LineDimensionsUtils {
/**
* Tag to identify if a line has an offset cache.
*/
final static String NEEDS_OFFSET_LINE_TAG =
LineDimensionsCalculator.class.getName() + "NEEDS_OFFSET";
/**
* The number of spaces a tab is treated as.
*/
// TODO: Delegate to EditorSettings once it is available.
private static int tabSpaceEquivalence = 2;
/**
* Enables or disables timeline marking.
*/
private static boolean enableLogging = false;
/**
* Checks if the line needs any offset other than indentation tabs and
* line-ending carriage-return.
*/
static boolean needsOffset(Line line) {
Boolean needsOffset = line.getTag(NEEDS_OFFSET_LINE_TAG);
// lets do a quick test if we haven't visited this line before
if (needsOffset == null) {
return forceUpdateNeedsOffset(line);
}
return needsOffset;
}
static boolean forceUpdateNeedsOffset(Line line) {
boolean needsOffset = hasSpecialCharactersWithExclusions(line);
line.putTag(NEEDS_OFFSET_LINE_TAG, needsOffset);
return needsOffset;
}
/**
* Uses the special character regex to determine if the line will need to be
* fully scanned.
*/
static boolean hasSpecialCharactersWithExclusions(Line line) {
return hasSpecialCharactersMaybeWithExclusions(line.getText(), true);
}
static boolean hasSpecialCharactersMaybeWithExclusions(String lineText, boolean stripTab) {
int length = lineText.length();
int index = stripTab ? getLastIndentationTabCount(lineText, length) : 0;
int endIndex = lineText.endsWith("\r\n") ? length - 2 : length;
return RegExpUtils.resetAndTest(
UnicodeUtils.regexpNonAsciiTabOrCarriageReturn, lineText.substring(index, endIndex));
}
/**
* Marks the lines internal cache of offset information dirty starting at the
* specified column. A column of 0 will clear the cache completely marking the
* line for re-measuring as needed.
*/
public static void isOffsetNeededAndCache(Line line, int column, TextChange.Type type) {
// TODO: Inspect the text instead of re-inspecting the entire line
markTimeline(LineDimensionsCalculator.class, "Begin maybe mark cache dirty");
Boolean hadNeedsOffset = line.getTag(NEEDS_OFFSET_LINE_TAG);
/*
* if you backspace the first character in a line, the line will be the
* previous line and type will be TextChange.Type.DELETE but that line could
* not have been visited yet. So we force a needOffset update in that case.
*/
if (hadNeedsOffset == null || (!hadNeedsOffset && type == TextChange.Type.INSERT)) {
forceUpdateNeedsOffset(line);
} else if (hadNeedsOffset) {
/*
* we don't know the zoom level here and am only going to mark the cache
* dirty so we can safely use getUnsafe.
*/
ColumnOffsetCache cache = ColumnOffsetCache.getUnsafe(line);
if (cache != null) {
// if the text was deleted, perhaps we removed the special characters?
if (type == TextChange.Type.DELETE && !forceUpdateNeedsOffset(line)) {
ColumnOffsetCache.removeFrom(line);
} else {
// if not we should mark our cache dirty
cache.markDirty(column);
}
}
}
markTimeline(LineDimensionsCalculator.class, "End maybe mark cache dirty");
}
public static void preTextIsOffsetNeededAndCache(
Line line, int column, TextChange.Type type, String text) {
// For delete we delegate through since the behavior is the same.
if (type == TextChange.Type.DELETE) {
isOffsetNeededAndCache(line, column, type);
} else {
Boolean hadNeedsOffset = line.getTag(NEEDS_OFFSET_LINE_TAG);
// If we are non-special case, scan the new text to determine if that's
// still the case.
if (hadNeedsOffset == null || !hadNeedsOffset) {
int newlineIndex = text.indexOf('\n');
String newText;
String oldText = line.getText();
if (newlineIndex == -1) {
// Inline insert.
newText = oldText.substring(0, column) + text + oldText.substring(column);
} else {
// Multi-line insert. We do not care about the following lines,
// as they will be processed later.
newText = oldText.substring(0, column) + text.substring(0, newlineIndex);
}
line.putTag(
NEEDS_OFFSET_LINE_TAG, hasSpecialCharactersMaybeWithExclusions(newText, true));
} else {
// We don't know the zoom level here and am only going to mark the cache
// dirty so we can safely use getUnsafe.
ColumnOffsetCache cache = ColumnOffsetCache.getUnsafe(line);
if (cache != null) {
cache.markDirty(column);
}
}
}
}
/**
* Returns the index of the last indentation tab before endColumn.
*/
public static int getLastIndentationTabCount(String lineText, int endColumn) {
int tabs = 0;
int length = lineText.length();
for (; tabs < length && lineText.charAt(tabs) == '\t' && tabs < endColumn; tabs++) {
// we do it all in the for loop :o
}
return tabs;
}
/**
* Sets the number of spaces a tab is rendered as.
*/
public static void setTabSpaceEquivalence(int spaces) {
tabSpaceEquivalence = spaces;
}
/**
* Retrieves the number of spaces a tab is rendered as.
*/
public static int getTabWidth() {
return tabSpaceEquivalence;
}
/**
* Returns a tab represented as a space.
*/
public static String getTabAsSpaces() {
return StringUtils.repeatString(" ", tabSpaceEquivalence);
}
/**
* Emits a markTimeline message if logging is enabled via
* {@link #enableLogging}.
*/
public static void markTimeline(Class<?> c, String message) {
if (enableLogging) {
SharedLogUtils.markTimeline(c, message);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/GrowableTextArea.java | client/src/main/java/com/google/collide/client/ui/GrowableTextArea.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.client.ui;
import collide.client.util.Elements;
import com.google.common.base.Preconditions;
import elemental.css.CSSStyleDeclaration;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.TextAreaElement;
/**
* Creates a GrowableTextArea, it isn't perfect but it does a fairly decent job
* of growing as the user types in new text.
*
*/
/*
* How it works:
*
* This class creates two text areas, one which is returned to the user and a
* second which is hidden and placed off-screen. As users type into the main
* text area, the text is also put into the hidden text area which has an
* explicit row height of 1. We use the scrollHeight of the hidden text area to
* determine the number of row necessary to display the text in the main area
* without scrolling. It is off a little bit due to the scrollbar width changing
* the width of the hidden text area a little bit, but generally it is good
* enough.
*/
public class GrowableTextArea {
public static GrowableTextArea create(String className) {
return createWithMinimumRows(className, 1);
}
/**
* @param minRows The minimum number of rows for this {@link GrowableTextArea}
* to be.
*/
public static GrowableTextArea createWithMinimumRows(String className, int minRows) {
Preconditions.checkArgument(minRows >= 1, "Minimum rows must be >= 1");
// Create the base text element and pass it in
TextAreaElement element = Elements.createTextAreaElement();
element.setClassName(className);
element.setRows(minRows);
element.getStyle().setOverflowY(CSSStyleDeclaration.OverflowY.HIDDEN);
return new GrowableTextArea(element, minRows);
}
private final TextAreaElement element;
private final TextAreaElement clone;
private final int minimumRows;
public GrowableTextArea(TextAreaElement element, int minimumRows) {
this.element = element;
this.minimumRows = minimumRows;
this.clone = Elements.createTextAreaElement();
setupClone();
attachEvents();
}
private void setupClone() {
clone.setClassName(element.getClassName());
CSSStyleDeclaration style = clone.getStyle();
style.setVisibility(CSSStyleDeclaration.Visibility.HIDDEN);
style.setPosition(CSSStyleDeclaration.Position.ABSOLUTE);
style.setOverflow(CSSStyleDeclaration.Overflow.AUTO);
style.setLeft("-5000px");
style.setTop("-5000px");
clone.setRows(1);
}
private void attachEvents() {
element.addEventListener(Event.INPUT, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (clone.getParentElement() == null) {
element.getParentElement().appendChild(clone);
}
clone.setValue(element.getValue());
int requiredRows =
(int) Math.ceil((double) clone.getScrollHeight() / (double) clone.getClientHeight());
int rows = Math.max(requiredRows, minimumRows);
element.setRows(rows);
}
}, false);
}
public TextAreaElement asTextArea() {
return element;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/TabController.java | client/src/main/java/com/google/collide/client/ui/TabController.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.client.ui;
import collide.client.common.CommonResources.BaseResources;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.json.shared.JsonArray;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.MouseEvent;
import elemental.html.HTMLCollection;
import elemental.js.dom.JsElement;
/**
* An object which manages a list of elements and treats them as tabs.
*/
public class TabController<T> {
/**
* Creates a TabController for a list of elements.
*/
public static <T> TabController<T> create(BaseResources res, TabClickedListener<T> listener,
Element tabContainer, JsonArray<TabElement<T>> headers) {
TabController<T> controller = new TabController<T>(res, listener, tabContainer);
// Create the tab headers
for (int i = 0; i < headers.size(); i++) {
TabElement<T> element = headers.get(i);
if (controller.activeTab == null) {
controller.setActiveTab(element);
}
tabContainer.appendChild(element);
}
return controller;
}
public interface TabClickedListener<T> {
public void onTabClicked(TabElement<T> element);
}
/**
* An javascript overlay which encapsulates the tab identifier associated with
* each tab header.
*/
public static class TabElement<T> extends JsElement {
/**
* Creates a tab element from an element and data.
*/
public static <T> TabElement<T> create(BaseResources res, String label, T data) {
@SuppressWarnings("unchecked")
TabElement<T> element = (TabElement<T>) Elements.createDivElement(res.baseCss().tab());
element.setTextContent(label);
element.setTabData(data);
return element;
}
protected TabElement() {
// javascript overlay
}
public final native void setTabData(T data) /*-{
this.__tabData = data;
}-*/;
public final native T getTabData() /*-{
return this.__tabData;
}-*/;
}
private final BaseResources res;
private final TabClickedListener<T> listener;
private final Element container;
private TabElement<T> activeTab;
private TabController(BaseResources res, TabClickedListener<T> listener, Element container) {
this.container = container;
this.res = res;
this.listener = listener;
attachHandlers();
}
private void attachHandlers() {
container.addEventListener(Event.CLICK, new EventListener() {
@Override
public void handleEvent(Event evt) {
MouseEvent event = (MouseEvent) evt;
// we could really just use the event target but this is for future
// expandability I guess.
Element element = CssUtils.getAncestorOrSelfWithClassName(
(Element) event.getTarget(), res.baseCss().tab());
if (element != null) {
@SuppressWarnings("unchecked")
TabElement<T> tabElement = (TabElement<T>) element;
selectTab(tabElement);
}
}
}, false);
}
/**
* Selects the supplied tab dispatching the listeners clicked event.
*/
public void selectTab(TabElement<T> element) {
if (activeTab == element) {
return;
}
setActiveTab(element);
listener.onTabClicked(element);
}
public T getActiveTab() {
return activeTab.getTabData();
}
/**
* Sets the active tab based on the provided tab data without dispatching the
* listeners clicked event.
*/
public boolean setActiveTab(T tab) {
if (getActiveTab() == tab) {
return true;
}
HTMLCollection nodes = container.getChildren();
for (int i = 0; i < nodes.getLength(); i++) {
@SuppressWarnings("unchecked")
TabElement<T> element = (TabElement<T>) nodes.item(i);
if (element.getTabData().equals(tab)) {
setActiveTab(element);
return true;
}
}
return false;
}
/**
* Sets the active tab without triggering the {@link TabClickedListener}
* callback.
*/
private void setActiveTab(TabElement<T> element) {
if (activeTab != null) {
activeTab.removeClassName(res.baseCss().activeTab());
}
element.addClassName(res.baseCss().activeTab());
activeTab = element;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/ElementView.java | client/src/main/java/com/google/collide/client/ui/ElementView.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.client.ui;
import com.google.collide.mvp.UiComponent;
import com.google.collide.mvp.View;
import elemental.dom.Element;
import elemental.js.dom.JsElement;
/**
* A single DOM Element.
*
* This is a View (V) in our use of MVP.
*
* Use this when you want to give some brains to a single DOM element by making this the View for
* some {@link UiComponent} that will contain business logic.
*
*/
// TODO: move this to mvp package when ray fixes the
// JsoRestrictionChecker bug in the gwt compiler.
public class ElementView<D> extends JsElement implements View<D> {
protected ElementView() {
}
@Override
public final native D getDelegate() /*-{
return this["delegate"];
}-*/;
@Override
public final native void setDelegate(D delegate) /*-{
this["delegate"] = delegate;
}-*/;
@Override
public final native Element getElement() /*-{
return this;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/slider/Slider.java | client/src/main/java/com/google/collide/client/ui/slider/Slider.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.client.ui.slider;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.testing.DebugAttributeSetter;
import com.google.collide.client.util.AnimationUtils;
import com.google.collide.client.util.ResizeController;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
/**
* Slider UI component.
*/
public class Slider extends UiComponent<Slider.View> {
private static final String SLIDER_MODE = "slidermode";
/**
* BaseCss selectors applied to DOM elements in the slider.
*/
public interface Css extends CssResource {
String sliderRoot();
String sliderLeft();
String sliderSplitter();
String sliderRight();
String sliderFlex();
String paddingForBorderRadius();
}
/**
* BaseResources used by the Slider.
*
* In order to theme the Slider, you extend this interface and override
* {@link Slider.Resources#sliderCss()}.
*/
public interface Resources extends ClientBundle, ResizeController.Resources {
// Default Stylesheet.
@Source("Slider.css")
Css sliderCss();
}
/**
* Listener interface for being notified about slider events.
*/
public interface Listener {
public void onStateChanged(boolean active);
}
/**
* The view for a Slider.
*/
public static class View extends CompositeView<ViewEvents> {
private static final double DURATION = AnimationUtils.SHORT_TRANSITION_DURATION;
private final Resources resources;
private final Css css;
private final Element sliderLeft;
private final Element sliderSplitter;
private final Element sliderRight;
private final int paddingForBorderRadius;
private boolean animating;
private final EventListener toggleSliderListener = new EventListener() {
@Override
public void handleEvent(Event evt) {
if (!animating) {
animateSlider();
}
}
};
private class SplitterController extends ResizeController {
private boolean active;
private int value;
private int lastDelta;
private SplitterController() {
super(resources, sliderSplitter, new ElementInfo(sliderLeft, ResizeProperty.RIGHT),
new ElementInfo(sliderSplitter, ResizeProperty.RIGHT),
new ElementInfo(sliderRight, ResizeProperty.RIGHT));
setNegativeDeltaW(true);
showResizingCursor(false);
}
@Override
protected boolean canStartResizing() {
return !animating;
}
@Override
protected void resizeStarted() {
animating = true;
active = CssUtils.isVisible(sliderLeft);
value = prepareForAnimation(active);
showResizingCursor(true);
setRestrictions();
super.resizeStarted();
}
@Override
protected void resizeEnded() {
super.resizeEnded();
if (lastDelta > 0) {
active = true;
} else if (lastDelta < 0) {
active = false;
}
runPreparedAnimation(active, value);
showResizingCursor(false);
lastDelta = 0;
}
@Override
protected void applyDelta(int deltaW, int deltaH) {
if (deltaW != 0) {
lastDelta = deltaW;
}
super.applyDelta(deltaW, deltaH);
}
private void setRestrictions() {
for (ElementInfo elementInfo : getElementInfos()) {
elementInfo.setPropertyMinValue(0);
elementInfo.setPropertyMaxValue(value - paddingForBorderRadius);
}
}
private void showResizingCursor(boolean show) {
CssUtils.setClassNameEnabled(sliderSplitter, getCss().hSplitter(), show);
}
}
public View(Resources resources) {
this.resources = resources;
css = resources.sliderCss();
sliderLeft = Elements.createDivElement(css.sliderLeft());
sliderSplitter = Elements.createDivElement(css.sliderSplitter());
sliderRight = Elements.createDivElement(css.sliderRight());
paddingForBorderRadius = CssUtils.parsePixels(css.paddingForBorderRadius());
Element rootElement = Elements.createDivElement(css.sliderRoot());
rootElement.appendChild(sliderLeft);
rootElement.appendChild(sliderSplitter);
rootElement.appendChild(sliderRight);
setElement(rootElement);
rootElement.addEventListener(Event.CLICK, toggleSliderListener, false);
new SplitterController().start();
}
private void setActive(boolean active) {
CssUtils.setDisplayVisibility(sliderLeft, active);
CssUtils.setDisplayVisibility(sliderRight, !active);
sliderLeft.getStyle().removeProperty("width");
sliderRight.getStyle().removeProperty("width");
sliderLeft.getStyle().removeProperty("right");
sliderSplitter.getStyle().removeProperty("right");
sliderRight.getStyle().removeProperty("right");
CssUtils.setClassNameEnabled(sliderLeft, css.sliderFlex(), active);
CssUtils.setClassNameEnabled(sliderRight, css.sliderFlex(), !active);
new DebugAttributeSetter().add(SLIDER_MODE, String.valueOf(active)).on(getElement());
}
private void animateSlider() {
final boolean active = CssUtils.isVisible(sliderLeft);
final int value = prepareForAnimation(active);
// Need to defer the animation, until both elements are visible.
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
runPreparedAnimation(active, value);
}
});
animating = true;
}
private int prepareForAnimation(boolean active) {
Element visibleButton = active ? sliderLeft : sliderRight;
int value = visibleButton.getOffsetWidth();
String rightStart = (active ? 0 : value - paddingForBorderRadius)
+ CSSStyleDeclaration.Unit.PX;
sliderLeft.getStyle().setWidth(value + CSSStyleDeclaration.Unit.PX);
sliderRight.getStyle().setWidth(value + CSSStyleDeclaration.Unit.PX);
sliderLeft.removeClassName(css.sliderFlex());
sliderRight.removeClassName(css.sliderFlex());
CssUtils.setDisplayVisibility(sliderLeft, true);
CssUtils.setDisplayVisibility(sliderRight, true);
sliderLeft.getStyle().setRight(rightStart);
sliderSplitter.getStyle().setRight(rightStart);
sliderRight.getStyle().setRight(rightStart);
return value;
}
private void runPreparedAnimation(final boolean active, int value) {
String rightEnd = (active ? value - paddingForBorderRadius : 0) + CSSStyleDeclaration.Unit.PX;
if (value <= 0 || rightEnd.equals(sliderRight.getStyle().getRight())) {
setActive(!active);
getDelegate().onStateChanged(!active);
// We should be "animating" until the event queue is processed, so that,
// for example, a mouse CLICK event should be skipped after a resizing.
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
animating = false;
}
});
return;
}
AnimationUtils.animatePropertySet(sliderLeft, "right", rightEnd, DURATION);
AnimationUtils.animatePropertySet(sliderSplitter, "right", rightEnd, DURATION);
AnimationUtils.animatePropertySet(sliderRight, "right", rightEnd, DURATION,
new EventListener() {
@Override
public void handleEvent(Event evt) {
setActive(!active);
getDelegate().onStateChanged(!active);
animating = false;
}
});
// In case the previous commands call an old event listener that would
// set the animating flag to false.
animating = true;
}
private void setSliderStrings(String activatedSlider, String deactivatedSlider) {
sliderLeft.setTextContent(activatedSlider);
sliderRight.setTextContent(deactivatedSlider);
}
}
private interface ViewEvents {
void onStateChanged(boolean active);
}
/**
* Creates an instance of the Slider with its default View.
*
* @return a {@link Slider} instance with default View
*/
public static Slider create(View view) {
return new Slider(view);
}
private Listener listener;
private Slider(View view) {
super(view);
getView().setDelegate(new ViewEvents() {
@Override
public void onStateChanged(boolean active) {
if (Slider.this.listener != null) {
Slider.this.listener.onStateChanged(active);
}
}
});
setActive(true);
}
public void setListener(Listener listener) {
this.listener = listener;
}
public void setActive(boolean active) {
getView().setActive(active);
}
/**
* Sets UI strings to display on the slider when it is activated and
* deactivated correspondingly.
*/
public void setSliderStrings(String activatedSlider, String deactivatedSlider) {
getView().setSliderStrings(activatedSlider, deactivatedSlider);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/tooltip/Tooltip.java | client/src/main/java/com/google/collide/client/ui/tooltip/Tooltip.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.client.ui.tooltip;
import collide.client.common.Constants;
import collide.client.util.Elements;
import com.google.collide.client.ui.menu.AutoHideComponent;
import com.google.collide.client.ui.menu.AutoHideView;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.ui.menu.PositionController.HorizontalAlign;
import com.google.collide.client.ui.menu.PositionController.Position;
import com.google.collide.client.ui.menu.PositionController.Positioner;
import com.google.collide.client.ui.menu.PositionController.PositionerBuilder;
import com.google.collide.client.ui.menu.PositionController.VerticalAlign;
import com.google.collide.client.util.AnimationController;
import com.google.collide.client.util.HoverController.HoverListener;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
import elemental.dom.Node;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.EventRemover;
import elemental.events.EventTarget;
import elemental.events.MouseEvent;
import elemental.util.Timer;
/**
* Represents a single tooltip instance attached to any element, activated by
* hovering.
*/
/*
* TODO: oh, my god this thing has become a monster. Might be nice to
* get a list of requirements and start from the top... especially if we need
* some coach marks as well for the landing page.
*/
public class Tooltip extends AutoHideComponent<AutoHideView<Void>,
AutoHideComponent.AutoHideModel> {
/**
* A builder used to construct a new Tooltip.
*/
public static class Builder {
private final Resources res;
private final JsonArray<Element> targetElements;
private final Positioner positioner;
private boolean shouldShowOnHover = true;
private TooltipRenderer renderer;
/**
* @see TooltipPositionerBuilder
*/
public Builder(Resources res, Element targetElement, Positioner positioner) {
this.res = res;
this.positioner = positioner;
this.targetElements = JsonCollections.createArray(targetElement);
}
/**
* Adds additional target elements. If the user hovers over any of the target elements, the
* tooltip will appear.
*/
public Builder addTargetElements(Element... additionalTargets) {
for (int i = 0; i < additionalTargets.length; i++) {
targetElements.add(additionalTargets[i]);
}
return this;
}
/**
* Sets the tooltip text. Each item in the array appears on a new line. This
* method overwrites the tooltip renderer.
*/
public Builder setTooltipText(String... tooltipText) {
return setTooltipRenderer(new SimpleStringRenderer(tooltipText));
}
public Builder setTooltipRenderer(TooltipRenderer renderer) {
this.renderer = renderer;
return this;
}
/**
* If false, will prevent the tooltip from automatically showing on hover.
*/
public Builder setShouldListenToHover(boolean shouldShowOnHover) {
this.shouldShowOnHover = shouldShowOnHover;
return this;
}
public Tooltip build() {
return new Tooltip(getViewInstance(res.tooltipCss()),
res,
targetElements,
positioner,
renderer,
shouldShowOnHover);
}
}
/**
* A {@link PositionerBuilder} which uses some more convenient defaults for tooltips. This builder
* defaults to {@link VerticalAlign#BOTTOM} {@link HorizontalAlign#MIDDLE} and
* {@link Position#NO_OVERLAP}.
*/
public static class TooltipPositionerBuilder extends PositionerBuilder {
public TooltipPositionerBuilder() {
setVerticalAlign(PositionController.VerticalAlign.BOTTOM);
setHorizontalAlign(PositionController.HorizontalAlign.MIDDLE);
setPosition(PositionController.Position.NO_OVERLAP);
}
}
/**
* Static factory method for creating a simple tooltip.
*/
public static Tooltip create(Resources res, Element targetElement, VerticalAlign vAlign,
HorizontalAlign hAlign, String... tooltipText) {
return new Builder(res, targetElement, new TooltipPositionerBuilder().setVerticalAlign(vAlign)
.setHorizontalAlign(hAlign).buildAnchorPositioner(targetElement)).setTooltipRenderer(
new SimpleStringRenderer(tooltipText)).build();
}
/**
* Interface for specifying an arbitrary renderer for tooltips.
*/
public interface TooltipRenderer {
Element renderDom();
}
/**
* Default renderer that simply renders the tooltip text with no other DOM.
*/
private static class SimpleStringRenderer implements TooltipRenderer {
private final String[] tooltipText;
SimpleStringRenderer(String... tooltipText) {
this.tooltipText = tooltipText;
}
@Override
public Element renderDom() {
Element content = Elements.createDivElement();
int i = 0;
for (String p : tooltipText) {
content.appendChild(Elements.createTextNode(p));
if (i < tooltipText.length - 1) {
content.appendChild(Elements.createBRElement());
content.appendChild(Elements.createBRElement());
}
i++;
}
return content;
}
}
/** The singleton view instance that all tooltips use. */
private static AutoHideView<Void> tooltipViewInstance;
/**
* The currently active tooltip that is bound to the view.
*/
private static Tooltip activeTooltip;
/**
* The Tooltip is a flyweight that uses a singleton View base element.
*/
private static AutoHideView<Void> getViewInstance(Css css) {
if (tooltipViewInstance == null) {
tooltipViewInstance = new AutoHideView<Void>(Elements.createDivElement());
tooltipViewInstance.getElement().addClassName(css.tooltipPosition());
}
return tooltipViewInstance;
}
public interface Css extends CssResource {
String tooltipPosition();
String tooltip();
String triangle();
String tooltipAbove();
String tooltipRight();
String tooltipBelow();
String tooltipLeft();
String tooltipBelowRightAligned();
}
public interface Resources extends ClientBundle {
@Source({"collide/client/common/constants.css", "Tooltip.css"})
Css tooltipCss();
@Source({"collide/client/common/constants.css", "Coachmark.css"})
Coachmark.Css coachmarkCss();
}
private static final int SHOW_DELAY = Constants.MOUSE_HOVER_DELAY;
private static final int HIDE_DELAY = Constants.MOUSE_HOVER_DELAY;
/**
* Holds a reference to the css.
*/
private final Css css;
private Element contentElement;
private final JsonArray<Element> targetElements;
private final Timer showTimer;
private final TooltipRenderer renderer;
private final PositionController positionController;
private final JsonArray<EventRemover> eventRemovers;
private final Positioner positioner;
private String title;
private String maxWidth;
private boolean isEnabled = true;
private boolean isShowDelayDisabled;
private Tooltip(AutoHideView<Void> view,
Resources res,
JsonArray<Element> targetElements,
Positioner positioner,
TooltipRenderer renderer,
boolean shouldShowOnHover) {
super(view, new AutoHideModel());
this.positioner = positioner;
this.renderer = renderer;
this.css = res.tooltipCss();
this.targetElements = targetElements;
this.eventRemovers =
shouldShowOnHover ? attachToTargetElement() : JsonCollections.<EventRemover>createArray();
getView().setAnimationController(AnimationController.FADE_ANIMATION_CONTROLLER);
positionController = new PositionController(positioner, getView().getElement());
showTimer = new Timer() {
@Override
public void run() {
show();
}
};
setDelay(HIDE_DELAY);
setCaptureOutsideClickOnClose(false);
getHoverController().setHoverListener(new HoverListener() {
@Override
public void onHover() {
if (isEnabled && !isShowing()) {
deferredShow();
}
}
});
}
@Override
public void show() {
// Nothing to do if it is showing.
if (isShowing()) {
return;
}
/*
* Hide the old Tooltip. This will not actually hide the View because we set
* activeTooltip to null.
*/
Tooltip oldTooltip = activeTooltip;
activeTooltip = null;
if (oldTooltip != null) {
oldTooltip.hide();
}
ensureContent();
// Bind to the singleton view.
getView().getElement().setInnerHTML("");
getView().getElement().appendChild(contentElement);
positionController.updateElementPosition();
activeTooltip = this;
super.show();
}
@Override
public void forceHide() {
super.forceHide();
activeTooltip = null;
}
@Override
protected void hideView() {
// If another tooltip is being shown, do not hide the shared view.
if (activeTooltip == this) {
super.hideView();
}
}
public void setTitle(String title) {
this.title = title;
}
public void setMaxWidth(String maxWidth) {
this.maxWidth = maxWidth;
// Update the content element if it is already created.
if (contentElement != null) {
if (maxWidth == null) {
contentElement.getStyle().removeProperty("max-width");
} else {
contentElement.getStyle().setProperty("max-width", maxWidth);
}
}
}
/**
* Enables or disables the show delay. If disabled, the tooltip will appear
* instantly on hover. Defaults to enabled.
*
* @param isDisabled true to disable the show delay
*/
public void setShowDelayDisabled(boolean isDisabled) {
this.isShowDelayDisabled = isDisabled;
}
/**
* Enable or disable this tooltip
*/
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
private void setPositionStyle() {
VerticalAlign vAlign = positioner.getVerticalAlignment();
HorizontalAlign hAlign = positioner.getHorizontalAlignment();
switch (positioner.getVerticalAlignment()) {
case TOP:
contentElement.addClassName(css.tooltipAbove());
break;
case BOTTOM:
if (hAlign == HorizontalAlign.RIGHT) {
contentElement.addClassName(css.tooltipBelowRightAligned());
} else {
contentElement.addClassName(css.tooltipBelow());
}
break;
case MIDDLE:
if (hAlign == HorizontalAlign.LEFT) {
contentElement.addClassName(css.tooltipLeft());
} else if (hAlign == HorizontalAlign.RIGHT) {
contentElement.addClassName(css.tooltipRight());
}
break;
}
}
/**
* Adds event handlers to the target element for the tooltip to show it on
* hover, and update position on mouse move.
*/
private JsonArray<EventRemover> attachToTargetElement() {
JsonArray<EventRemover> removers = JsonCollections.createArray();
for (int i = 0; i < targetElements.size(); i++) {
final Element targetElement = targetElements.get(i);
addPartner(targetElement);
removers.add(targetElement.addEventListener(Event.MOUSEOUT, new EventListener() {
@Override
public void handleEvent(Event evt) {
MouseEvent mouseEvt = (MouseEvent) evt;
EventTarget relatedTarget = mouseEvt.getRelatedTarget();
// Ignore the event unless we mouse completely out of the target element.
if (relatedTarget == null || !targetElement.contains((Node) relatedTarget)) {
cancelPendingShow();
}
}
}, false));
removers.add(targetElement.addEventListener(Event.MOUSEDOWN, new EventListener() {
@Override
public void handleEvent(Event evt) {
cancelPendingShow();
hide();
}
}, false));
}
return removers;
}
/**
* Removes event handlers from the target element for the tooltip.
*/
private void detachFromTargetElement() {
for (int i = 0; i < targetElements.size(); i++) {
removePartner(targetElements.get(i));
}
for (int i = 0, n = eventRemovers.size(); i < n; ++i) {
eventRemovers.get(i).remove();
}
eventRemovers.clear();
}
/**
* Creates the dom for this tooltip's content.
*
* <code>
* <div class="tooltipPosition">
* <div class="tooltip tooltipAbove/Below/Left/Right">
* tooltipText
* <div class="tooltipTriangle"></div>
* </div>
* </div>
* </code>
*/
private void ensureContent() {
if (contentElement == null) {
contentElement = renderer.renderDom();
if (contentElement == null) {
// Guard against malformed renderers.
Log.warn(getClass(), "Renderer for tooltip returned a null content element");
contentElement = Elements.createDivElement();
contentElement.setTextContent("An empty Tooltip!");
}
if (title != null) {
// Insert a title if one is set.
Element titleElem = Elements.createElement("b");
titleElem.setTextContent(title);
Element breakElem = Elements.createBRElement();
contentElement.insertBefore(breakElem, contentElement.getFirstChild());
contentElement.insertBefore(titleElem, contentElement.getFirstChild());
}
// Set the maximum width.
setMaxWidth(maxWidth);
contentElement.addClassName(css.tooltip());
Element triangle = Elements.createDivElement(css.triangle());
contentElement.appendChild(triangle);
setPositionStyle();
}
}
public void destroy() {
showTimer.cancel();
forceHide();
detachFromTargetElement();
}
private void deferredShow() {
if (isShowDelayDisabled || activeTooltip != null) {
/*
* If there is already a tooltip showing and the user mouses over an item
* that has it's own tooltip, move the tooltip immediately. We don't want
* to leave a lingering tooltip on the old item.
*/
showTimer.cancel();
showTimer.run();
} else {
showTimer.schedule(SHOW_DELAY);
}
}
private void cancelPendingShow() {
showTimer.cancel();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/tooltip/Coachmark.java | client/src/main/java/com/google/collide/client/ui/tooltip/Coachmark.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.client.ui.tooltip;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.ui.menu.PositionController.HorizontalAlign;
import com.google.collide.client.ui.menu.PositionController.VerticalAlign;
import com.google.collide.client.ui.tooltip.Coachmark.View;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.resources.client.CssResource;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.html.DivElement;
/**
* An object which represents a coach mark (a tooltip like notification which is often dismissable).
*/
// TODO: Generalize the class, it currently isn't so general.
public class Coachmark extends UiComponent<View> {
public static Coachmark create(
Tooltip.Resources res, Renderer renderer, PositionController.Positioner positioner) {
View view = new View(res.coachmarkCss());
return new Coachmark(view, renderer, new PositionController(positioner, view.getElement()));
}
public interface Css extends CssResource {
public String base();
public String container();
public String arrow();
public String arrowInner();
public String alert();
public String disclaimer();
public int arrowSize();
}
/**
* A renderer which renders the contents of a {@link Coachmark}.
*/
public interface Renderer {
/**
* @param container the container to which any child elements should be attached.
*/
public void render(Element container, Coachmark coachmark);
}
public static class BasicRenderer implements Renderer {
private final String text;
public BasicRenderer(String text, Coachmark coachmark) {
this.text = text;
}
@Override
public void render(Element container, Coachmark coachmark) {
container.setTextContent(text);
}
}
public static class View extends CompositeView<Void> {
private final DivElement container;
private final DivElement arrow;
private final DivElement arrowInner;
private final Css css;
public View(Css css) {
super(Elements.createDivElement(css.base()));
this.css = css;
CssUtils.setDisplayVisibility2(getElement(), false);
this.container = Elements.createDivElement(css.container());
this.arrow = Elements.createDivElement(css.arrow());
this.arrowInner = Elements.createDivElement(css.arrowInner());
arrow.appendChild(arrowInner);
getElement().appendChild(arrow);
getElement().appendChild(container);
}
public Element getArrow() {
return arrow;
}
public Element getContainer() {
return container;
}
}
private final Renderer renderer;
private final PositionController positionController;
private boolean hasRendered = false;
private Coachmark(View view, Renderer renderer, PositionController positionController) {
super(view);
this.renderer = renderer;
this.positionController = positionController;
}
public void show() {
Element element = getView().getElement();
if (!hasRendered) {
renderer.render(getView().getContainer(), this);
hasRendered = true;
}
updatePosition();
CssUtils.setDisplayVisibility2(element, true);
}
public void hide() {
Element element = getView().getElement();
CssUtils.setDisplayVisibility2(element, false);
}
private void updatePosition() {
PositionController.Positioner positioner = positionController.getPositioner();
int x = 0;
int y = getYOffset(positioner.getVerticalAlignment());
// TODO: This is megahacked together, if you try to do a coach mark get here and find
// you need better, we should refactor this so it is more general.
updateArrow(getXOffset(positioner.getHorizontalAlignment()), y);
positionController.updateElementPosition(x, y);
}
private void updateArrow(int x, int y) {
Element arrow = getView().getArrow();
CSSStyleDeclaration style = arrow.getStyle();
HorizontalAlign alignment = positionController.getPositioner().getHorizontalAlignment();
style.setLeft("auto");
style.setRight("auto");
if (alignment == HorizontalAlign.LEFT) {
style.setLeft(-(x * 2), CSSStyleDeclaration.Unit.PX);
} else {
style.setRight((x * 2), CSSStyleDeclaration.Unit.PX);
}
style.setTop(-(y * 2), CSSStyleDeclaration.Unit.PX);
}
private int getYOffset(VerticalAlign alignment) {
int arrowSize = getView().css.arrowSize();
switch (alignment) {
case TOP:
return -arrowSize;
case BOTTOM:
return arrowSize;
default:
return 0;
}
}
private int getXOffset(HorizontalAlign alignment) {
int arrowSize = getView().css.arrowSize();
switch (alignment) {
case LEFT:
return -arrowSize;
case RIGHT:
return arrowSize;
default:
return 0;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/list/SimpleList.java | client/src/main/java/com/google/collide/client/ui/list/SimpleList.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.client.ui.list;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.ui.ElementView;
import com.google.collide.client.util.dom.DomUtils;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.UiComponent;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.js.dom.JsElement;
// TODO: Where possible, port more lists that we have hand-rolled in
// other parts of the UI to use this widget.
/**
* A simple list widget for displaying flat collections of things.
*/
// TODO: When we hit a place where a componenet wants to ditch all of
// the default simple list styles, figure out a way to make that easy.
public class SimpleList<M> extends UiComponent<SimpleList.View> {
/**
* Create using the default CSS.
*/
public static <M> SimpleList<M> create(View view, Resources res,
ListItemRenderer<M> itemRenderer, ListEventDelegate<M> eventDelegate) {
return new SimpleList<M>(view, view, view, res.defaultSimpleListCss(), itemRenderer,
eventDelegate);
}
/**
* Create with custom CSS.
*/
public static <M> SimpleList<M> create(View view, Css css, ListItemRenderer<M> itemRenderer,
ListEventDelegate<M> eventDelegate) {
return new SimpleList<M>(view, view, view, css, itemRenderer, eventDelegate);
}
/**
* Create and configure control instance.
*
* <p> Use this method when either only part of control is scrollable
* ({@code view != container}) or elements are stored in table
* ({@code container != itemHolder}) or both.
*
* @param view element that receives control decorations (shadow, etc.)
* @param container element whose content is scrolled
* @param itemHolder element to add items to
*/
public static <M> SimpleList<M> create(View view, Element container, Element itemHolder,
Css css, ListItemRenderer<M> itemRenderer, ListEventDelegate<M> eventDelegate) {
return new SimpleList<M>(view, container, itemHolder, css, itemRenderer, eventDelegate);
}
/**
* Called each time we render an item in the list. Provides an opportunity for
* implementors/clients to customize the DOM structure of each list item.
*/
public abstract static class ListItemRenderer<M> {
public abstract void render(Element listItemBase, M itemData);
/**
* A factory method for the outermost element used by a list item.
*
* The default implementation returns a div element.
*/
public Element createElement() {
return Elements.createDivElement();
}
}
/**
* Receives events fired on items in the list.
*/
public interface ListEventDelegate<M> {
void onListItemClicked(Element listItemBase, M itemData);
}
/**
* A {@link ListEventDelegate} which performs no action.
*/
public static class NoOpListEventDelegate<M> implements ListEventDelegate<M> {
@Override
public void onListItemClicked(Element listItemBase, M itemData) {
}
}
/**
* Item style selectors for a simple list item.
*/
public interface Css extends CssResource {
int menuListBorderPx();
String listItem();
String listBase();
String listContainer();
}
public interface Resources extends ClientBundle {
@Source({"SimpleList.css", "collide/client/common/constants.css"})
Css defaultSimpleListCss();
@Source({"Sidebar.css"})
SidebarListItemRenderer.Css sidebarListCss();
}
/**
* Overlay type representing the base element of the SimpleList.
*/
public static class View extends ElementView<Void> {
protected View() {
}
}
/**
* A javascript overlay object which ties a list item's DOM element to its
* associated data.
*
*/
final static class ListItem<M> extends JsElement {
/**
* Creates a new ListItem overlay object by creating a div element,
* assigning it the listItem css class, and associating it to its data.
*/
public static <M> ListItem<M> create(ListItemRenderer<M> factory, Css css, M data) {
Element element = factory.createElement();
element.addClassName(css.listItem());
ListItem<M> item = ListItem.cast(element);
item.setData(data);
return item;
}
/**
* Casts an element to its ListItem representation. This is an unchecked
* cast so we extract it into this static factory method so we don't have to
* suppress warnings all over the place.
*/
@SuppressWarnings("unchecked")
public static <M> ListItem<M> cast(Element element) {
return (ListItem<M>) element;
}
protected ListItem() {
// Unused constructor
}
public final native M getData() /*-{
return this.__data;
}-*/;
public final native void setData(M data) /*-{
this.__data = data;
}-*/;
/**
* Reuses this elements container by clearing it's contents and updating its
* data. This allows it to be sent back to the renderer.
*
* @param className The css class to set to the container. All other css
* classes are cleared.
*/
public final native void reuseContainerElement(M data, String className) /*-{
this.className = className;
this.innerHTML = "";
this.__data = data;
}-*/;
}
/**
* A model which maintains the internal state of the list including selection
* and DOM elements.
*
*/
public class Model<I> implements HasSelection<I> {
private static final int NO_SELECTION = -1;
/**
* Defines the attribute used to indicate selection.
*/
private static final String SELECTED_ATTRIBUTE = "SELECTED";
private final ListEventDelegate<I> delegate;
private final JsonArray<ListItem<I>> listItems = JsonCollections.createArray();
private int selectedIndex;
/**
* Creates a new model for use by SimpleList. The provided delegate should
* not be null.
*/
public Model(ListEventDelegate<I> delegate) {
this.delegate = delegate;
// set the initially selected item
selectedIndex = 0;
}
@Override
public int getSelectedIndex() {
return selectedIndex;
}
@Override
public I getSelectedItem() {
ListItem<I> selectedListItem = getSelectedListItem();
return selectedListItem != null ? selectedListItem.getData() : null;
}
/**
* Returns the currently selected list element or null.
*/
private ListItem<I> getSelectedListItem() {
if (selectedIndex >= 0 && selectedIndex < listItems.size()) {
return listItems.get(selectedIndex);
}
return null;
}
@Override
public boolean selectNext() {
return setSelectedItem(selectedIndex + 1);
}
@Override
public boolean selectPrevious() {
return setSelectedItem(selectedIndex - 1);
}
@Override
public boolean selectNextPage() {
return setSelectedItem(Math.min(selectedIndex + getPageSize(), size() - 1));
}
@Override
public boolean selectPreviousPage() {
return setSelectedItem(Math.max(0, selectedIndex - getPageSize()));
}
private int getPageSize() {
int indexAboveViewport = findIndexOfFirstNotInViewport(selectedIndex, false);
int indexBelowViewport = findIndexOfFirstNotInViewport(selectedIndex, true);
// A minimum size of 1
return Math.max(1, indexBelowViewport - indexAboveViewport - 1);
}
/**
* Returns the index of the first item that is not fully in the viewport. If
* all items are, it will return the last item in the given direction.
*/
private int findIndexOfFirstNotInViewport(int beginIndex, boolean forward) {
final int deltaIndex = forward ? 1 : -1;
int i = beginIndex;
for (; i >= 0 && i < size(); i += deltaIndex) {
if (!DomUtils.isFullyInScrollViewport(container, listItems.get(i))) {
return i;
}
}
return i + -deltaIndex;
}
@Override
public void handleClick() {
ListItem<I> item = getSelectedListItem();
if (item != null) {
delegate.onListItemClicked(item, item.getData());
}
}
@Override
public void clearSelection() {
maybeRemoveSelectionFromElement();
selectedIndex = NO_SELECTION;
}
@Override
public int size() {
return listItems.size();
}
@Override
public boolean setSelectedItem(int index) {
if (index >= 0 && index < listItems.size()) {
maybeRemoveSelectionFromElement();
selectedIndex = index;
getSelectedListItem().setAttribute(SELECTED_ATTRIBUTE, SELECTED_ATTRIBUTE);
ensureSelectedIsVisible();
return true;
}
return false;
}
@Override
public boolean setSelectedItem(I item) {
int index = -1;
for (int i = 0; i < listItems.size(); i++) {
if (listItems.get(i).getData().equals(item)) {
index = i;
break;
}
}
return setSelectedItem(index);
}
private void ensureSelectedIsVisible() {
DomUtils.ensureScrolledTo(container, model.getSelectedListItem());
}
/**
* Removes selection from the currently selected element if it exists.
*/
private void maybeRemoveSelectionFromElement() {
ListItem<I> element = getSelectedListItem();
if (element != null) {
element.removeAttribute(SELECTED_ATTRIBUTE);
}
}
}
private final ListEventDelegate<M> eventDelegate;
private final ListItemRenderer<M> itemRenderer;
private final Css css;
private final Model<M> model;
private final Element container;
private final Element itemHolder;
private SimpleList(View view, Element container, Element itemHolder,
Css css, ListItemRenderer<M> itemRenderer, ListEventDelegate<M> eventDelegate) {
super(view);
this.css = css;
this.model = new Model<M>(eventDelegate);
this.itemRenderer = itemRenderer;
this.eventDelegate = eventDelegate;
this.itemHolder = itemHolder;
this.container = container;
view.addClassName(css.listBase());
container.addClassName(css.listContainer());
attachEventHandlers();
}
/**
* Returns the current number of items in the simple list.
*/
public int size() {
return model.listItems.size();
}
/**
* Refreshes list of items.
*
* <p>This method tries to keep selection.
*/
public void render(JsonArray<M> items) {
M selectedItem = model.getSelectedItem();
model.clearSelection();
itemHolder.setInnerHTML("");
model.listItems.clear();
for (int i = 0; i < items.size(); i++) {
ListItem<M> elem = ListItem.create(itemRenderer, css, items.get(i));
CssUtils.setUserSelect(elem, false);
model.listItems.add(elem);
itemRenderer.render(elem, elem.getData());
itemHolder.appendChild(elem);
}
model.setSelectedItem(selectedItem);
}
public HasSelection<M> getSelectionModel() {
return model;
}
/**
* @return true if the list or any one of its element's currently have focus.
*/
public boolean hasFocus() {
return DomUtils.isElementOrChildFocused(container);
}
private void attachEventHandlers() {
getView().addEventListener(Event.CLICK, new EventListener() {
@Override
public void handleEvent(Event evt) {
Element listItemElem = CssUtils.getAncestorOrSelfWithClassName(
(Element) evt.getTarget(), css.listItem());
if (listItemElem == null) {
Log.warn(SimpleList.class,
"Unable to find an ancestor that was a list item for a click on: ", evt.getTarget());
return;
}
ListItem<M> listItem = ListItem.cast(listItemElem);
eventDelegate.onListItemClicked(listItem, listItem.getData());
}
}, false);
}
public M get(int i) {
return model.listItems.get(i).getData();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/list/BasicListItemRenderer.java | client/src/main/java/com/google/collide/client/ui/list/BasicListItemRenderer.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.client.ui.list;
import com.google.collide.client.ui.list.SimpleList.ListItemRenderer;
import com.google.collide.client.util.ImageResourceUtils;
import com.google.collide.client.util.Utils;
import com.google.gwt.resources.client.ImageResource;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
/**
* A simple list item renderer that renders the {@link Object#toString()} of the
* given model objects and optionally adds an icon.
*
*/
public class BasicListItemRenderer<M> extends ListItemRenderer<M> {
/**
* Creates a renderer which renders items with no images.
*/
public static <M> BasicListItemRenderer<M> create(M[] items) {
return new BasicListItemRenderer<M>(items, null, 0);
}
/**
* Creates a renderer which renders items with icons. Any items without an icon will be rendered
* with 0 left padding.
*/
public static <M> BasicListItemRenderer<M> createWithIcons(M[] items, ImageResource[] icons) {
return new BasicListItemRenderer<M>(items, icons, 0);
}
/**
* @param defaultPadding If no icon is found this is the amount of padding to use for alignment
* purposes.
*/
public static <M> BasicListItemRenderer<M> createWithIcons(M[] items, ImageResource[] icons,
int defaultPadding) {
return new BasicListItemRenderer<M>(items, icons, defaultPadding);
}
private static final int IMAGE_PADDING_LEFT_PX = 15;
private static final int IMAGE_PADDING_RIGHT_PX = 10;
private final M[] items;
private final ImageResource[] icons;
private final int defaultPadding;
private BasicListItemRenderer(M[] items, ImageResource[] icons, int defaultPadding) {
this.items = items;
this.icons = icons;
this.defaultPadding = defaultPadding;
}
@Override
public void render(Element listItemBase, M item) {
if (icons != null) {
ImageResource icon = findIcon(item);
int padding = defaultPadding;
if (icon != null) {
ImageResourceUtils.applyImageResource(listItemBase, icon, IMAGE_PADDING_LEFT_PX + "px",
"center");
padding = IMAGE_PADDING_LEFT_PX + icon.getWidth() + IMAGE_PADDING_RIGHT_PX;
}
// By breaking this up we can avoid overriding the listItems hover state
listItemBase.getStyle().setPaddingLeft(padding, CSSStyleDeclaration.Unit.PX);
}
listItemBase.setTextContent(item.toString());
}
private ImageResource findIcon(M item) {
for (int i = 0, n = items.length; i < n; i++) {
if (Utils.equalsOrNull(items[i], item)) {
return icons[i];
}
}
return null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/list/SidebarListItemRenderer.java | client/src/main/java/com/google/collide/client/ui/list/SidebarListItemRenderer.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.client.ui.list;
import collide.client.util.Elements;
import com.google.collide.client.ui.list.SimpleList.ListEventDelegate;
import com.google.collide.client.ui.list.SimpleList.ListItemRenderer;
import com.google.collide.client.ui.list.SimpleList.View;
import elemental.dom.Element;
import elemental.html.AnchorElement;
import elemental.html.UListElement;
/**
* Sidebar list item renderer. It is meant to render anchor tags which include an
* href. Feel free to set the href to javascript:; if that functionality is unneeded.
*
* @param <M> The underlying data type
*/
public class SidebarListItemRenderer<M> extends ListItemRenderer<M> {
public static <M> SimpleList<M> create(
SimpleList.Resources res, LinkRenderer<M> renderer, ListEventDelegate<M> delegate) {
UListElement container = (UListElement) Elements.createElement("ul");
return create(container, res, renderer, delegate);
}
public static <M> SimpleList<M> create(UListElement container, SimpleList.Resources res,
LinkRenderer<M> renderer, ListEventDelegate<M> delegate) {
SimpleList.View view = (View) container;
ListItemRenderer<M> itemRenderer =
new SidebarListItemRenderer<M>(res.sidebarListCss(), renderer);
return SimpleList.create(view, res.sidebarListCss(), itemRenderer, delegate);
}
/**
* A renderer which can provide the details for rendering an anchor tag.
*/
public interface LinkRenderer<M> {
public String getText(M item);
public String getHref(M item);
}
/**
* A helper class which encapsulates the text and href of an anchor tag for rendering purposes.
*/
public static class SidebarLink {
private final String text;
private final String href;
public SidebarLink(String text, String href) {
this.text = text;
this.href = href;
}
public String getText() {
return text;
}
public String getHref() {
return href;
}
}
/**
* A renderer which can render a {@link SidebarLink}.
*/
public static class SidebarLinkRenderer implements LinkRenderer<SidebarLink> {
@Override
public String getText(SidebarLink item) {
return item.getText();
}
@Override
public String getHref(SidebarLink item) {
return item.getHref();
}
}
public interface Css extends SimpleList.Css {
@Override
String listBase();
@Override
String listContainer();
@Override
String listItem();
String anchor();
}
private final LinkRenderer<M> renderer;
private final Css css;
public SidebarListItemRenderer(Css css, LinkRenderer<M> renderer) {
this.css = css;
this.renderer = renderer;
}
@Override
public void render(Element listItemBase, M itemData) {
AnchorElement anchor = Elements.createAnchorElement(css.anchor());
anchor.setTextContent(renderer.getText(itemData));
anchor.setHref(renderer.getHref(itemData));
listItemBase.appendChild(anchor);
}
@Override
public Element createElement() {
return Elements.createElement("li");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/list/KeyboardSelectionController.java | client/src/main/java/com/google/collide/client/ui/list/KeyboardSelectionController.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.client.ui.list;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.KeyboardEvent;
import elemental.events.KeyboardEvent.KeyCode;
/**
* A controller which attaches to an input element and proxies keyboard
* navigation events to an object which {@link HasSelection}.
*
*/
public class KeyboardSelectionController {
private final Element inputElement;
private final HasSelection<?> list;
private boolean handlerEnabled = false;
/**
* Creates a new KeyboardSelectionController which proxies keyboard events
* from inputElement to the supplied list.
*/
public KeyboardSelectionController(Element inputElement, HasSelection<?> list) {
this.inputElement = inputElement;
this.list = list;
attachHandlers();
}
/**
* Disables/Enables the keyboard navigation. When the handler is disabled the
* controller will not proxy any keyboard input. This is useful if the list is
* hidden or disabled.
*/
public void setHandlerEnabled(boolean enabled) {
handlerEnabled = enabled;
// reset the selection to the first item
list.setSelectedItem(0);
}
private void attachHandlers() {
inputElement.addEventListener(Event.KEYDOWN, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (!handlerEnabled) {
return;
}
KeyboardEvent event = (KeyboardEvent) evt;
if (event.getKeyCode() == KeyCode.DOWN) {
list.selectNext();
evt.preventDefault();
} else if (event.getKeyCode() == KeyCode.UP) {
list.selectPrevious();
evt.preventDefault();
} else if (event.getKeyCode() == KeyCode.ENTER) {
list.handleClick();
}
}
}, false);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/list/HasSelection.java | client/src/main/java/com/google/collide/client/ui/list/HasSelection.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.client.ui.list;
/**
* An interface which describes an object which maintains selection.
*/
public interface HasSelection<M> {
public void clearSelection();
/**
* Selects the next item in the list, returning false if selection cannot be
* moved for any reason.
*/
public boolean selectNext();
/**
* Selects the previous item in the list, returning false if selection cannot
* be moved for any reason.
*/
public boolean selectPrevious();
public int size();
public boolean setSelectedItem(int index);
public boolean setSelectedItem(M item);
public boolean selectNextPage();
public boolean selectPreviousPage();
/**
* Indicates that the currently selected item should be clicked and the
* appropriate action must be executed.
*/
public void handleClick();
/**
* Returns the selected item, or null.
*/
public M getSelectedItem();
public int getSelectedIndex();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/popup/Popup.java | client/src/main/java/com/google/collide/client/ui/popup/Popup.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.client.ui.popup;
import javax.annotation.Nullable;
import collide.client.util.Elements;
import com.google.collide.client.ui.menu.AutoHideComponent;
import com.google.collide.client.ui.menu.AutoHideView;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.ui.menu.PositionController.Positioner;
import com.google.common.base.Preconditions;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
/**
* Represents a floating popup, that can be attached to any element.
*
*/
public class Popup extends AutoHideComponent<Popup.View, AutoHideComponent.AutoHideModel> {
public interface Css extends CssResource {
String root();
String contentHolder();
}
public interface Resources extends ClientBundle {
@Source({"collide/client/common/constants.css", "Popup.css"})
Css popupCss();
}
/**
* The View for the Popup component.
*/
public static class View extends AutoHideView<Void> {
private final Css css;
private final Element contentHolder;
View(Resources resources) {
this.css = resources.popupCss();
contentHolder = Elements.createDivElement(css.contentHolder());
Element rootElement = Elements.createDivElement(css.root());
rootElement.appendChild(contentHolder);
setElement(rootElement);
}
void setContentElement(@Nullable Element contentElement) {
contentHolder.setInnerHTML("");
if (contentElement != null) {
contentHolder.appendChild(contentElement);
}
}
}
public static Popup create(Resources resources) {
View view = new View(resources);
return new Popup(view);
}
private PositionController positionController;
private Popup(View view) {
super(view, new AutoHideModel());
}
@Override
public void show() {
Preconditions.checkNotNull(
positionController, "You cannot show this popup without using a position controller");
positionController.updateElementPosition();
cancelPendingHide();
super.show();
}
/**
* Shows the popup anchored to a given element.
*/
public void show(Positioner positioner) {
positionController = new PositionController(positioner, getView().getElement());
show();
}
/**
* Sets the popup's content element.
*
* @param contentElement the DOM element to show in the popup, or {@code null}
* to clean up the popup's DOM
*/
public void setContentElement(@Nullable Element contentElement) {
getView().setContentElement(contentElement);
}
public void destroy() {
forceHide();
setContentElement(null);
positionController = null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/popup/CenterPanel.java | client/src/main/java/com/google/collide/client/ui/popup/CenterPanel.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.client.ui.popup;
import javax.annotation.Nullable;
import collide.client.common.CommonResources.BaseCss;
import collide.client.util.Elements;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Timer;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.KeyboardEvent.KeyCode;
import elemental.js.dom.JsElement;
import elemental.js.events.JsKeyboardEvent;
/**
* A popup that automatically centers its content, even if the dimensions of the content change. The
* centering is done in CSS, so performance is very good. A semi-transparent "glass" panel appears
* behind the popup. The glass is not optional due to the way {@link CenterPanel} is implemented.
*
* <p>
* {@link CenterPanel} animates into and out of view using the shrink in/expand out animation.
* </p>
*/
public class CenterPanel extends UiComponent<CenterPanel.View> {
/**
* Constructs a new {@link CenterPanel} that contains the specified content
* element.
*
* @param resources the resources to apply to the popup
* @param content the content to display in the center of the popup
* @return a new {@link CenterPanel} instance
*/
public static CenterPanel create(Resources resources, elemental.dom.Element content) {
View view = new View(resources, content);
return new CenterPanel(view);
}
/**
* The resources used by this UI component.
*/
public interface Resources extends ClientBundle {
@Source({"collide/client/common/constants.css", "CenterPanel.css"})
Css centerPanelCss();
}
/**
* The BaseCss Style names used by this panel.
*/
public interface Css extends CssResource {
/**
* Returns duration of the popup animation in milliseconds.
*/
int animationDuration();
String content();
String contentVisible();
String glass();
String glassVisible();
String popup();
String positioner();
}
/**
* The events sources by the View.
*/
private interface ViewEvents {
void onEscapeKey();
}
/**
* The view that renders the {@link CenterPanel}. The View consists of a glass
* panel that fades out the background, and a DOM structure that positions the
* contents in the exact center of the screen.
*/
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("CenterPanel.ui.xml")
interface MyBinder extends UiBinder<Element, View> {
}
private static MyBinder uiBinder = GWT.create(MyBinder.class);
final Resources res;
@UiField(provided = true)
final Css css;
@UiField
DivElement contentContainer;
@UiField
DivElement glass;
@UiField
DivElement popup;
View(Resources res, elemental.dom.Element content) {
this.res = res;
this.css = res.centerPanelCss();
setElement(Elements.asJsElement(uiBinder.createAndBindUi(this)));
Elements.asJsElement(contentContainer).appendChild(content);
handleEvents();
}
/**
* Returns the duration of the popup animation in milliseconds. The return
* value should equal the value of {@link BaseCss#animationDuration()}.
*/
protected int getAnimationDuration() {
return css.animationDuration();
}
/**
* Updates the View to reflect the showing state of the popup.
*
* @param showing true if showing, false if not.
*/
protected void setShowing(boolean showing) {
if (showing) {
glass.addClassName(css.glassVisible());
contentContainer.addClassName(css.contentVisible());
} else {
glass.removeClassName(css.glassVisible());
contentContainer.removeClassName(css.contentVisible());
}
}
private void handleEvents() {
getElement().addEventListener(Event.KEYDOWN, new EventListener() {
@Override
public void handleEvent(Event evt) {
JsKeyboardEvent keyEvt = (JsKeyboardEvent) evt;
int keyCode = keyEvt.getKeyCode();
if (KeyCode.ESC == keyCode) {
if (getDelegate() != null) {
getDelegate().onEscapeKey();
}
}
}
}, true);
}
}
private boolean hideOnEscapeEnabled = false;
private boolean isShowing;
CenterPanel(View view) {
super(view);
handleViewEvents();
}
/**
* Hides the {@link CenterPanel} popup. The popup will animate out of view.
*/
public void hide() {
if (!isShowing) {
return;
}
isShowing = false;
// Animate the popup out of existance.
getView().setShowing(false);
// Remove the popup when the animation completes.
new Timer() {
@Override
public void run() {
// The popup may have been shown before this timer executes.
if (!isShowing) {
Elements.asJsElement(getView().popup).removeFromParent();
}
}
}.schedule(getView().getAnimationDuration());
}
/**
* Checks if the {@link CenterPanel} is showing or animating into view.
*
* @return true if showing, false if hidden
*/
public boolean isShowing() {
return isShowing;
}
/**
* Sets whether or not the popup should hide when escape is pressed. The
* default behavior is to ignore the escape key.
*
* @param isEnabled true to close on escape, false not to
*/
// TODO: This only works if the popup has focus. We need to capture events.
// TODO: Consider making escaping the default.
public void setHideOnEscapeEnabled(boolean isEnabled) {
this.hideOnEscapeEnabled = isEnabled;
}
/**
* See {@link #show(InputElement)}.
*/
public void show() {
show(null);
}
/**
* Displays the {@link CenterPanel} popup. The popup will animate into view.
*
* @param selectAndFocusElement an {@link InputElement} to select and focus on when the panel is
* shown. If null, no element will be given focus
*/
public void show(@Nullable final InputElement selectAndFocusElement) {
if (isShowing) {
return;
}
isShowing = true;
// Attach the popup to the body.
final JsElement popup = getView().popup.cast();
if (popup.getParentElement() == null) {
// Hide the popup so it can enter its initial state without flickering.
popup.getStyle().setVisibility("hidden");
Elements.getBody().appendChild(popup);
}
// Start the animation after the element is attached.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
// The popup may have been hidden before this timer executes.
if (isShowing) {
popup.getStyle().removeProperty("visibility");
getView().setShowing(true);
if (selectAndFocusElement != null) {
selectAndFocusElement.select();
selectAndFocusElement.focus();
}
}
}
});
}
private void handleViewEvents() {
getView().setDelegate(new ViewEvents() {
@Override
public void onEscapeKey() {
if (hideOnEscapeEnabled) {
hide();
}
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/panel/PanelModel.java | client/src/main/java/com/google/collide/client/ui/panel/PanelModel.java | package com.google.collide.client.ui.panel;
public class PanelModel {
private final boolean historyIcon;
private final boolean closeIcon;
private final boolean settingsIcon;
private final boolean collapseIcon;
private final boolean clearNavigator;
protected PanelModel(boolean showHistory, boolean showClose, boolean showSettings, boolean showCollapse,
boolean showClear) {
this.historyIcon = showHistory;
this.closeIcon = showClose;
this.settingsIcon = showSettings;
this.collapseIcon = showCollapse;
this.clearNavigator = showClear;
}
public final boolean showHistoryIcon() {
return historyIcon;
}
public final boolean showCloseIcon() {
return closeIcon;
}
public final boolean showSettingsIcon() {
return settingsIcon;
}
public final boolean showCollapseIcon() {
return collapseIcon;
}
public static class Builder <M extends PanelModel> {
protected boolean historyIcon;
protected boolean closeIcon;
protected boolean settingsIcon;
protected boolean collapseIcon;
protected boolean clearNavigator;
/**
* @return the closeIcon
*/
public boolean isCloseIcon() {
return closeIcon;
}
/**
* @param closeIcon the closeIcon to set
*/
public PanelModel.Builder<M> setCloseIcon(boolean closeIcon) {
this.closeIcon = closeIcon;
return this;
}
/**
* @return the collapseIcon
*/
public boolean isCollapseIcon() {
return collapseIcon;
}
/**
* @param collapseIcon the collapseIcon to set
* @return
*/
public PanelModel.Builder<M> setCollapseIcon(boolean collapseIcon) {
this.collapseIcon = collapseIcon;
return this;
}
/**
* @return the clearFiles
*/
public boolean isClearNavigator() {
return clearNavigator;
}
/**
* @param clearFiles whether or not to clear file navigator
* @return this for chaining
*/
public PanelModel.Builder<M> setClearNavigator(boolean clearFiles) {
this.clearNavigator = clearFiles;
return this;
}
/**
* @return the historyIcon
*/
public boolean isHistoryIcon() {
return historyIcon;
}
/**
* @param historyIcon the historyIcon to set
* @return
*/
public PanelModel.Builder<M> setHistoryIcon(boolean historyIcon) {
this.historyIcon = historyIcon;
return this;
}
/**
* @return the settingsIcon
*/
public boolean isSettingsIcon() {
return settingsIcon;
}
/**
* @param settingsIcon the settingsIcon to set
* @return
*/
public PanelModel.Builder<M> setSettingsIcon(boolean settingsIcon) {
this.settingsIcon = settingsIcon;
return this;
}
@SuppressWarnings("unchecked")
public M build() {
return (M)new PanelModel(historyIcon, closeIcon, settingsIcon, collapseIcon, clearNavigator);
}
}
public static PanelModel.Builder<PanelModel> newBasicModel(){
return new PanelModel.Builder<PanelModel>();
}
/**
* @return the clearNavigator
*/
public boolean isClearNavigator() {
return clearNavigator;
}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/panel/PanelState.java | client/src/main/java/com/google/collide/client/ui/panel/PanelState.java | package com.google.collide.client.ui.panel;
public class PanelState {
private boolean maximizable, closable = true, refreshable, hotswappable;
private String namespace, title;
private boolean allHeader;
/**
* @return the closable
*/
public boolean isClosable() {
return closable;
}
/**
* @param closable the closable to set
*/
public PanelState setClosable(boolean closable) {
this.closable = closable;
return this;
}
/**
* @return the hotswappable
*/
public boolean isHotswappable() {
return hotswappable;
}
/**
* @param hotswappable the hotswappable to set
* @return
*/
public PanelState setHotswappable(boolean hotswappable) {
this.hotswappable = hotswappable;
return this;
}
/**
* @return the maximizable
*/
public boolean isMaximizable() {
return maximizable;
}
/**
* @param maximizable the maximizable to set
* @return
*/
public PanelState setMaximizable(boolean maximizable) {
this.maximizable = maximizable;
return this;
}
/**
* @return the refreshable
*/
public boolean isRefreshable() {
return refreshable;
}
/**
* @param refreshable the refreshable to set
* @return
*/
public PanelState setRefreshable(boolean refreshable) {
this.refreshable = refreshable;
return this;
}
/**
* @return the namespace
*/
public String getNamespace() {
return namespace;
}
/**
* @param namespace the namespace to set
* @return
*/
public PanelState setNamespace(String namespace) {
this.namespace = namespace;
return this;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
* @return
*/
public PanelState setTitle(String title) {
this.title = title;
return this;
}
@Override
public String toString() {
return super.toString();
}
public static PanelState fromString(String serialized) {
PanelState panel = new PanelState();
return panel;
}
public boolean isAllHeader() {
return allHeader;
}
public PanelState setAllHeader(boolean isHeader) {
allHeader = isHeader;
return this;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/panel/Panel.java | client/src/main/java/com/google/collide/client/ui/panel/Panel.java | package com.google.collide.client.ui.panel;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import collide.client.util.Elements;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.util.ResizeBounds;
import com.google.collide.client.util.ResizeController;
import com.google.collide.client.util.ResizeController.ElementInfo;
import com.google.collide.client.util.ResizeController.ResizeEventHandler;
import com.google.collide.client.util.ResizeController.ResizeProperty;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.util.ArrayOf;
import elemental.util.Collections;
public class Panel
<Delegate, V extends Panel.View<Delegate>>
extends UiComponent<V>
implements ContentReceiver
{
public static interface Css extends CssResource {
String caliper();
String content();
String headerText();
String hidden();
String east();
String handleContainer();
String header();
String north();
String northeast();
String northwest();
String positioner();
String root();
String south();
String southeast();
String southwest();
String west();
String draggable();
String refreshIcon();
String buttonBar();
String maximizeIcon();
String closeIcon();
}
public interface Resources extends ResizeController.Resources {
@Source({"collide/client/common/constants.css", "Panel.css"})
Css panelCss();
}
public static interface Interpolator {
Interpolator NO_OP = new Interpolator() {
@Override
public float interpolate(float value) {
return value;
}
};
float interpolate(float value);
}
public static class View<Delegate> extends CompositeView<Delegate> {
@UiTemplate("Panel.ui.xml")
interface PanelBinder extends UiBinder<com.google.gwt.dom.client.DivElement,View<?>> {
}
static PanelBinder binder = GWT.create(PanelBinder.class);
@UiField(provided = true)
protected final Css css;
@UiField
protected DivElement root;
@UiField
protected DivElement header;
@UiField
DivElement north;
@UiField
DivElement east;
@UiField
DivElement west;
@UiField
DivElement south;
@UiField
DivElement northeast;
@UiField
DivElement northwest;
@UiField
DivElement southeast;
@UiField
DivElement southwest;
@UiField
DivElement contentContainer;
protected View(final Resources resources) {
this.css = resources.panelCss();
binder.createAndBindUi(this);
setElement(Elements.asJsElement(root));
}
@Override
public Element getElement() {
return super.getElement();
}
void setContentElement(@Nullable Element contentElement) {
contentContainer.setInnerHTML("");
if (contentElement != null) {
Elements.asJsElement(contentContainer).appendChild(contentElement);
}
}
void setHeaderElement(@Nullable Element contentElement) {
header.setInnerHTML("");
if (contentElement != null) {
Elements.asJsElement(header).appendChild(contentElement);
}
}
}
public static class SizeLimitingElement extends ElementInfo{
private Panel<?, ?> panel;
public SizeLimitingElement(Panel<?, ?> panel, Element element, ResizeProperty property) {
super(element, property);
this.panel = panel;
}
@Override
public int getPropertyMaxValue() {
switch (getResizeProperty()) {
case BOTTOM:
float min;
case NEG_BOTTOM:
case TOP:
case NEG_TOP:
return Integer.MAX_VALUE;
case HEIGHT:
case NEG_HEIGHT:
min = panel.getBounds().getMaxHeight();
if (min <= 0) {
//when less than zero, use the panel's anchor element as boundary
Element anchor = panel.getChildAnchor();
return anchor.getClientHeight();
}
return (int) min;
case LEFT:
case NEG_LEFT:
case RIGHT:
case NEG_RIGHT:
//need to do positioning instead of sizing
return Integer.MAX_VALUE;
// return (int)panel.getBounds().getMinWidth();
case WIDTH:
case NEG_WIDTH:
min = panel.getBounds().getMaxWidth();
if (min <= 0) {
Element anchor = panel.getChildAnchor();
return anchor.getClientWidth();
}
return (int) min;
default:
throw new RuntimeException("Can't get here");
}
// if ( getResizeProperty().isVertical()) {
// float h = panel.getBounds().getMaxHeight();
// if (h <= 0) {
// //when less than zero, use the panel's anchor element as boundary
// Element anchor = panel.getParentAnchor();
//// Log.info(getClass(), "MAX H "+anchor.getBoundingClientRect().getHeight());
// Log.info(getClass(), "MAX W "+(int)anchor.getBoundingClientRect().getHeight());
// return (int)anchor.getBoundingClientRect().getHeight();
// }
//// Log.info(getClass(), "Max H "+h);
// return (int) h;
// }else {
// float w = panel.getBounds().getMaxWidth();
// if (w <= 0) {
// //when less than zero, use the panel's anchor element as boundary
// Element anchor = panel.getParentAnchor();
// Log.info(getClass(), "MAX W "+anchor.getClientWidth());
// return (int)anchor.getBoundingClientRect().getWidth();
//// return anchor.getClientWidth();
// }
// Log.info(getClass(), "Max W "+w);
// return (int) w;
// }
}
@Override
public int getPropertyMinValue() {
switch (getResizeProperty()) {
case BOTTOM:
float min;
case NEG_BOTTOM:
case TOP:
case NEG_TOP:
return Integer.MIN_VALUE;
case HEIGHT:
case NEG_HEIGHT:
min = panel.getBounds().getMinHeight();
if (min <= 0) {
//when less than zero, use the panel's anchor element as boundary
Element anchor = panel.getChildAnchor();
return anchor.getClientHeight();
}
// Log.info(getClass(), "Min value "+min);
return (int) min;
case LEFT:
case NEG_LEFT:
case RIGHT:
case NEG_RIGHT:
//need to do positioning instead of sizing
return Integer.MIN_VALUE;
// return (int)panel.getBounds().getMinWidth();
case WIDTH:
case NEG_WIDTH:
min = panel.getBounds().getMinWidth();
if (min <= 0) {
//when less than zero, use the panel's anchor element as boundary
Element anchor = panel.getChildAnchor();
// Log.info(getClass(), "Min value "+min);
return anchor.getClientWidth();
}
return (int) min;
default:
throw new RuntimeException("Can't get here");
}
}
}
protected static class DefaultHeaderBuilder implements HeaderBuilder {
elemental.html.DivElement el, buttons, close, maximize, refresh;
@Override
public Element buildHeader(String title, Css css, Panel<?, ?> panel) {
PanelState state = panel.getPanelState();
if (el == null) {
el = Elements.createDivElement(css.headerText());
}
el.setInnerHTML(title);
if (state.isClosable()) {
makeClosable(panel, el, css);
} else if (close != null) {
el.removeChild(close);
close = null;
}
if (state.isMaximizable()) {
makeMaximizable(panel, el, css);
} else if (maximize != null) {
el.removeChild(maximize);
maximize = null;
}
if (state.isRefreshable()) {
makeRefreshable(panel, el, css);
} else if (refresh != null) {
el.removeChild(refresh);
refresh = null;
}
return el;
}
protected elemental.html.DivElement getButtonBar(Css css) {
if (buttons == null) {
buttons = Elements.createDivElement(css.buttonBar());
el.appendChild(buttons);
}
return buttons;
}
protected void makeRefreshable(Panel<? , ?> panel, elemental.html.DivElement el, Css css) {
if (refresh == null) {
refresh = Elements.createDivElement(css.refreshIcon());
getButtonBar(css).appendChild(refresh);
}
}
protected void makeMaximizable(Panel<? , ?> panel, elemental.html.DivElement el, Css css) {
if (maximize == null) {
maximize = Elements.createDivElement(css.maximizeIcon());
getButtonBar(css).appendChild(maximize);
maximize.setInnerHTML("+");
}
}
protected void makeClosable(Panel<? , ?> panel, elemental.html.DivElement el, Css css) {
if (close == null) {
close = Elements.createDivElement(css.closeIcon());
getButtonBar(css).appendChild(close);
close.setInnerHTML("X");
}
}
}
private final JsonArray<Element> clickTargets = JsonCollections.createArray();
public static <Delegate> Panel<Delegate, Panel.View<Delegate>>
create(String id, final Resources resources, ResizeBounds bounds) {
return create(id, resources, bounds, null);
}
public static <Delegate> Panel<Delegate, Panel.View<Delegate>>
create(String id, Resources resources, ResizeBounds bounds, HeaderBuilder header) {
final View<Delegate> view = new View<Delegate>(resources);
return new Panel<Delegate, Panel.View<Delegate>>(id, resources, view, bounds, header);
}
private class ResizableController extends ResizeController{
private String enabledClass;
public ResizableController(Resources resources, String enabledClass, Element splitter, ElementInfo ... elementInfos) {
super(resources, splitter, elementInfos);
this.enabledClass = enabledClass;
}
@Override
protected String initCss(ElementInfo horizEl, ElementInfo vertEl) {
if (enabledClass==null)
enabledClass = super.initCss(horizEl, vertEl);
return enabledClass;
}
protected void superDelta(int deltaW, int deltaH) {
super.applyDelta(deltaW, deltaH);
}
ScheduledCommand cmd;
@Override
protected void applyDelta(final int deltaW, final int deltaH) {
if (deltaW != 0 || deltaH != 0) {
if (cmd == null) {
Scheduler.get().scheduleFinally((cmd = new ScheduledCommand() {
@Override
public void execute() {
cmd = null;
resizeHandler.whileDragging(
// isNegativeWidth() ?
-deltaW,
// : deltaW,
isNegativeHeight() ? -deltaH : deltaH,
0, 0);
}
}));
}
}
superDelta(deltaW, deltaH);
}
}
public Element getParentAnchor() {
Element anchor = getView().getElement();
Log.info(getClass(), anchor);
return
anchor.getParentElement() == null
?
getView().getElement()
: anchor.getParentElement()
;
}
public Element getChildAnchor() {
return
// getView().getElement()
Elements.asJsElement(getView().contentContainer)
;
}
private PositionController positionController;
private ResizeBounds bounds;
private ScheduledCommand resize;
private final ArrayOf<ResizeController> controllers;
private final HeaderBuilder header;
private ResizeController dragController;
private PanelState panelState;
private PanelContent panelContent;
private final String id;
protected Panel(String id, final Resources resources, final V view, ResizeBounds bounds, HeaderBuilder header) {
super(view);
this.id = id;
this.header = header == null ? new DefaultHeaderBuilder() : header;
panelState = new PanelState();
setBounds(bounds);
controllers = Collections.arrayOf();
// Use a finally command to let us pick up changes to state before we do a layout.
Scheduler.get().scheduleFinally(new ScheduledCommand() {
@Override
public void execute() {
Element n = Elements.asJsElement(view.north);
Element e = Elements.asJsElement(view.east);
Element w = Elements.asJsElement(view.west);
Element s = Elements.asJsElement(view.south);
Element ne = Elements.asJsElement(view.northeast);
Element se = Elements.asJsElement(view.southeast);
Element nw = Elements.asJsElement(view.northwest);
Element sw = Elements.asJsElement(view.southwest);
Element c = Elements.asJsElement(view.root);
ElementInfo bodyWidth = new SizeLimitingElement(Panel.this, c, ResizeProperty.WIDTH);
ElementInfo bodyHeight = new SizeLimitingElement(Panel.this, c, ResizeProperty.HEIGHT);
bodyWidth.refresh();
bodyHeight.refresh();
ElementInfo neg_bodyWidth = new SizeLimitingElement(Panel.this, c, ResizeProperty.NEG_WIDTH);
ElementInfo neg_bodyHeight = new SizeLimitingElement(Panel.this, c, ResizeProperty.NEG_HEIGHT);
ElementInfo northInfo = new SizeLimitingElement(Panel.this, c, ResizeProperty.TOP);
ElementInfo eastInfo = new SizeLimitingElement(Panel.this, c, ResizeProperty.RIGHT);
ElementInfo neg_eastInfo = new SizeLimitingElement(Panel.this, c, ResizeProperty.NEG_RIGHT);
ElementInfo westInfo = new SizeLimitingElement(Panel.this, c, ResizeProperty.LEFT);
controllers.setLength(0);
ResizeController controller;
com.google.collide.client.util.ResizeController.Css css = resources.resizeControllerCss();
controller = new ResizableController(resources, css.hSplitter(), n, northInfo, neg_bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.vSplitter(), w, westInfo, neg_bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.vSplitter(), e, eastInfo, bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.hSplitter(), s, bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.nwSplitter(), nw, northInfo, westInfo, neg_bodyWidth, neg_bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.neSplitter(), ne, northInfo, neg_eastInfo, bodyWidth, neg_bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.swSplitter(), sw, bodyHeight, westInfo, neg_bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.seSplitter(), se,neg_eastInfo, bodyHeight, bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizableController(resources, css.moveCursor(), Elements.asJsElement(view.header), northInfo, westInfo) {
@Override
protected String getResizeCursor() {
return resources.resizeControllerCss().moveCursor();
}
@Override
protected String initCss(ElementInfo horizEl, ElementInfo vertEl) {
return resources.resizeControllerCss().moveCursor();
}
};
setPanelDragController(controller);
controller.start();
controllers.push(controller);
}
});
}
protected void setPanelDragController(ResizeController controller) {
this.dragController = controller;
}
public String getId() {
return id;
}
public void hide() {
getView().getElement().addClassName(getView().css.hidden());
// CssUtils.setDisplayVisibility2(getView().getElement(), false);
// getView().getElement().setHidden(true);
}
public void show() {
getView().getElement().removeClassName(getView().css.hidden());
// getView().getElement().setHidden(false);
// CssUtils.setDisplayVisibility2(getView().getElement(), true);
scheduleResize();
}
private void scheduleResize() {
if (resize == null) {
resize = new ScheduledCommand() {
@Override
public void execute() {
resize = null;
doResize();
}
};
// grab a new execution loop, in case we are called in a heavyweight task.
// this will also prevent multiple panels from rendering at the same time.
Scheduler.get().scheduleFinally(resize);
}
}
protected void doResize() {
if (isVisible()) {
// If there is header text, we should redraw it.
for (int i = 0; i < controllers.length(); i++) {
for (ElementInfo info : controllers.get(i).getElementInfos()){
info.refresh();
}
}
if (!getPanelState().isAllHeader()) {
setHeaderContent(getPanelState().getTitle());
}
}
}
private boolean isVisible() {
return !getView().getElement().hasClassName(getView().css.hidden());
}
/**
* Sets the popup's panelContent element.
*
* @param panelContent the panelContent to display
*/
public void setContent(@Nullable PanelContent panelContent) {
if (panelContent == null) {
this.panelContent = null;
return;
}
if (this.panelContent != panelContent) {
onContentClosed(this.panelContent);
}
this.panelContent = panelContent;
getView().setContentElement(panelContent.getContentElement());
// refresh minimum sizing
scheduleResize();
}
private void onContentClosed(PanelContent panelContent2) {
}
public void setHeaderElement(@Nullable Element headerElement) {
getView().setHeaderElement(headerElement);
getPanelState().setTitle(null);
scheduleResize();
}
public void setHeaderContent(@Nonnull String headerContent) {
Preconditions.checkNotNull(headerContent, "You may not send null strings as panel headers. " +
"Use new String(0xa) for a non-breaking space.");
try {
getView().setHeaderElement(
renderHeader(getView().css, headerContent)
)
;
} finally {
// We want to update the state title, but not before the builder gets a
// chance to look at the stale data, to avoid unneeded repaints.
getPanelState().setTitle(headerContent);
}
}
protected Element renderHeader(Css res, String headerContent) {
return header.buildHeader(headerContent, getView().css, this);
}
public void destroy() {
Log.info(getClass(), "Destroying panel");
forceHide();
setContent(null);
positionController = null;
resize = null;
}
/**
* Add one or more partner elements that, when the panel is dragged, are resized and moved relative to the
* panel's delta.
*/
public void addPartnerDragElements(Element ... elems) {
if (elems != null) {
for (Element e : elems) {
clickTargets.add(e);
}
}
}
public void removePartnerDragElements(Element ... elems) {
if (elems != null) {
for (Element e : elems) {
clickTargets.remove(e);
}
}
}
private void forceHide() {
}
public void setPosition(float left, float top) {
CSSStyleDeclaration style = getView().getElement().getStyle();
if (left < 0) {
// set right
style.clearLeft();
style.setRight(-left, "px");
} else {
style.clearRight();
style.setLeft(left, "px");
}
if (top < 0) {
style.clearTop();
style.setBottom(-top, "px");
} else {
style.clearBottom();
style.setTop(top, "px");
}
}
public void setSize(float width, float height) {
CSSStyleDeclaration style = getView().getElement().getStyle();
if (width < 0) {
// set right
style.clearWidth();
} else {
style.setWidth(width, "px");
}
if (height < 0) {
style.clearHeight();
} else {
style.setHeight(height, "px");
}
}
public void setAllHeader() {
getPanelState().setAllHeader(true);
getView().setHeaderElement(Elements.asJsElement(getView().contentContainer));
}
/**
* @return the bounds
*/
public ResizeBounds getBounds() {
return bounds;
}
/**
* @param bounds the bounds to set
*/
public void setBounds(ResizeBounds bounds) {
this.bounds = bounds;
}
// @Override
// public Element getContentElement() {
// return getView().getElement();
// }
public PanelContent getContent() {
return panelContent;
}
// @Override
// public void onContentDisplayed() {
// //hookup listeners
// }
// @Override
// public void onContentDestroyed() {
// //destroy listeners
//
// }
ResizeEventHandler resizeHandler;
public void addResizeHandler(ResizeEventHandler resizeEventHandler) {
if (resizeHandler != null) {
dragController.removeEventHandler(resizeHandler);
}
resizeHandler = resizeEventHandler;
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
dragController.addEventHandler(resizeHandler);
}
});
}
protected PanelState getPanelState() {
return panelState;
}
public void setClosable(boolean b) {
getPanelState().setClosable(true);
scheduleResize();
}
public boolean isHidden() {
return getView().getElement().hasClassName(getView().css.hidden());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ui/panel/ResizablePanel.java | client/src/main/java/com/google/collide/client/ui/panel/ResizablePanel.java | package com.google.collide.client.ui.panel;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import collide.client.util.Elements;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.ui.menu.PositionController.Positioner;
import com.google.collide.client.util.ResizeBounds;
import com.google.collide.client.util.ResizeController;
import com.google.collide.client.util.ResizeController.ElementInfo;
import com.google.collide.client.util.ResizeController.ResizeProperty;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.util.ArrayOf;
import elemental.util.Collections;
public class ResizablePanel <Res extends ResizablePanel.Resources & ResizeController.Resources> extends UiComponent<ResizablePanel.View<Res>> {
public static interface Css extends CssResource {
String content();
String headerText();
String east();
String handleContainer();
String header();
String north();
String northeast();
String northwest();
String positioner();
String root();
String south();
String southeast();
String southwest();
String west();
String draggable();
}
public interface Resources extends ClientBundle {
@Source({"collide/client/common/constants.css", "Panel.css"})
Css panelCss();
}
public static interface Interpolator {
double interpolate(double value);
}
public static class View<Res extends Resources & ResizeController.Resources> extends CompositeView<Void> {
@UiTemplate("Panel.ui.xml")
interface PanelBinder extends UiBinder<com.google.gwt.dom.client.DivElement,View<?>> {
}
static PanelBinder binder = GWT.create(PanelBinder.class);
@UiField(provided = true)
final Css css;
@UiField
DivElement root;
@UiField
DivElement header;
@UiField
DivElement north;
@UiField
DivElement east;
@UiField
DivElement west;
@UiField
DivElement south;
@UiField
DivElement northeast;
@UiField
DivElement northwest;
@UiField
DivElement southeast;
@UiField
DivElement southwest;
@UiField
DivElement contentContainer;
View(final Res resources) {
this.css = resources.panelCss();
binder.createAndBindUi(this);
setElement(Elements.asJsElement(root));
}
@Override
public Element getElement() {
return super.getElement();
}
void setContentElement(@Nullable Element contentElement) {
contentContainer.setInnerHTML("");
if (contentElement != null) {
Elements.asJsElement(contentContainer).appendChild(contentElement);
}
}
void setHeaderElement(@Nullable Element contentElement) {
header.setInnerHTML("");
if (contentElement != null) {
Elements.asJsElement(header).appendChild(contentElement);
}
}
}
public static class SizeLimitingElement extends ElementInfo{
private ResizablePanel<?> panel;
public SizeLimitingElement(ResizablePanel<?> panel, Element element, ResizeProperty property) {
super(element, property);
this.panel = panel;
}
@Override
public int getPropertyMaxValue() {
switch (getResizeProperty()) {
case BOTTOM:
float min;
case NEG_BOTTOM:
case TOP:
case NEG_TOP:
return Integer.MAX_VALUE;
case HEIGHT:
case NEG_HEIGHT:
min = panel.getBounds().getMaxHeight();
if (min <= 0) {
//when less than zero, use the panel's anchor element as boundary
Element anchor = panel.getChildAnchor();
return anchor.getClientHeight();
}
return (int) min;
case LEFT:
case NEG_LEFT:
case RIGHT:
case NEG_RIGHT:
//need to do positioning instead of sizing
return Integer.MAX_VALUE;
// return (int)panel.getBounds().getMinWidth();
case WIDTH:
case NEG_WIDTH:
min = panel.getBounds().getMaxWidth();
if (min <= 0) {
Element anchor = panel.getChildAnchor();
return anchor.getClientWidth();
}
return (int) min;
default:
throw new RuntimeException("Can't get here");
}
// if ( getResizeProperty().isVertical()) {
// float h = panel.getBounds().getMaxHeight();
// if (h <= 0) {
// //when less than zero, use the panel's anchor element as boundary
// Element anchor = panel.getParentAnchor();
//// Log.info(getClass(), "MAX H "+anchor.getBoundingClientRect().getHeight());
// Log.info(getClass(), "MAX W "+(int)anchor.getBoundingClientRect().getHeight());
// return (int)anchor.getBoundingClientRect().getHeight();
// }
//// Log.info(getClass(), "Max H "+h);
// return (int) h;
// }else {
// float w = panel.getBounds().getMaxWidth();
// if (w <= 0) {
// //when less than zero, use the panel's anchor element as boundary
// Element anchor = panel.getParentAnchor();
// Log.info(getClass(), "MAX W "+anchor.getClientWidth());
// return (int)anchor.getBoundingClientRect().getWidth();
//// return anchor.getClientWidth();
// }
// Log.info(getClass(), "Max W "+w);
// return (int) w;
// }
}
@Override
public int getPropertyMinValue() {
switch (getResizeProperty()) {
case BOTTOM:
float min;
case NEG_BOTTOM:
case TOP:
case NEG_TOP:
return Integer.MIN_VALUE;
case HEIGHT:
case NEG_HEIGHT:
min = panel.getBounds().getMinHeight();
if (min <= 0) {
//when less than zero, use the panel's anchor element as boundary
Element anchor = panel.getChildAnchor();
return anchor.getClientHeight();
}
Log.info(getClass(), "Min value "+min);
return (int) min;
case LEFT:
case NEG_LEFT:
case RIGHT:
case NEG_RIGHT:
//need to do positioning instead of sizing
return Integer.MIN_VALUE;
// return (int)panel.getBounds().getMinWidth();
case WIDTH:
case NEG_WIDTH:
min = panel.getBounds().getMinWidth();
if (min <= 0) {
//when less than zero, use the panel's anchor element as boundary
Element anchor = panel.getChildAnchor();
Log.info(getClass(), "Min value "+min);
return anchor.getClientWidth();
}
return (int) min;
default:
throw new RuntimeException("Can't get here");
}
}
}
private final JsonArray<Element> clickTargets = JsonCollections.createArray();
public static <Res extends Resources & ResizeController.Resources> ResizablePanel<Res> create(final Res resources, ResizeBounds bounds) {
final View<Res> view = new View<Res>(resources);
final ResizablePanel<Res> panel = new ResizablePanel<Res>(resources, view, bounds);
return panel;
}
public Element getParentAnchor() {
Element anchor = getView().getElement();
Log.info(getClass(), anchor);
return
anchor.getParentElement() == null
?
getView().getElement()
: anchor.getParentElement()
;
}
public Element getChildAnchor() {
return
// getView().getElement()
Elements.asJsElement(getView().contentContainer)
;
}
private PositionController positionController;
private ResizeBounds bounds;
private ScheduledCommand resize;
private final ArrayOf<ResizeController> controllers;
private ResizablePanel(final Res resources, final View<Res> view, ResizeBounds bounds) {
super(view);
setBounds(bounds);
controllers = Collections.arrayOf();
Scheduler.get().scheduleFinally(new ScheduledCommand() {
@Override
public void execute() {
Element n = Elements.asJsElement(view.north);
Element e = Elements.asJsElement(view.east);
Element w = Elements.asJsElement(view.west);
Element s = Elements.asJsElement(view.south);
Element ne = Elements.asJsElement(view.northeast);
Element se = Elements.asJsElement(view.southeast);
Element nw = Elements.asJsElement(view.northwest);
Element sw = Elements.asJsElement(view.southwest);
Element c = Elements.asJsElement(view.root);
ElementInfo bodyWidth = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.WIDTH);
ElementInfo bodyHeight = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.HEIGHT);
ElementInfo neg_bodyWidth = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.NEG_WIDTH);
ElementInfo neg_bodyHeight = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.NEG_HEIGHT);
ElementInfo northInfo = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.TOP);
ElementInfo eastInfo = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.RIGHT);
ElementInfo neg_eastInfo = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.NEG_RIGHT);
ElementInfo westInfo = new SizeLimitingElement(ResizablePanel.this, c, ResizeProperty.LEFT);
controllers.setLength(0);
ResizeController controller;
controller = new ResizeController(resources, n, northInfo, neg_bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, w, westInfo, neg_bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, e, eastInfo, bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, s, bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, nw, northInfo, westInfo, neg_bodyWidth, neg_bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, ne, northInfo, neg_eastInfo, bodyWidth, neg_bodyHeight);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, sw, bodyHeight, westInfo, neg_bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, se,neg_eastInfo, bodyHeight, bodyWidth);
controller.start();
controllers.push(controller);
controller = new ResizeController(resources, Elements.asJsElement(view.header), northInfo, westInfo) {
@Override
protected String getResizeCursor() {
return resources.panelCss().draggable();
}
};
controller.start();
controllers.push(controller);
// use the controllers array to create a deactivator
}
});
}
public void show() {
Preconditions.checkNotNull(positionController,
"You cannot show this popup without using a position controller");
positionController.updateElementPosition();
}
/**
* Shows the panel anchored to a given element.
*/
public void show(Positioner positioner) {
positionController = new PositionController(positioner, getView().getElement());
show();
scheduleResize();
}
private void scheduleResize() {
if (resize == null) {
resize = new ScheduledCommand() {
@Override
public void execute() {
resize = null;
doResize();
}
};
Scheduler.get().scheduleFinally(resize);
}
}
protected void doResize() {
for (int i = 0; i < controllers.length(); i++) {
for (ElementInfo info : controllers.get(i).getElementInfos()){
info.refresh();
}
}
}
/**
* Sets the popup's content element.
*
* @param contentElement the DOM element to show in the popup, or {@code null} to clean up the popup's DOM
*/
public void setContentElement(@Nullable Element contentElement) {
getView().setContentElement(contentElement);
// refresh minimum sizing
scheduleResize();
}
public void setHeaderElement(@Nullable Element headerElement) {
getView().setHeaderElement(headerElement);
scheduleResize();
}
public void setHeaderContent(@Nonnull String headerContent) {
Preconditions.checkNotNull(headerContent, "You may not send null strings as panel headers. " +
"Use new String(0xa) for a non-breaking space.");
getView().setHeaderElement(renderHeader(getView().css, headerContent));
}
protected Element renderHeader(Css res, String headerContent) {
elemental.html.DivElement el = Elements.createDivElement(res.headerText());
el.setInnerHTML(headerContent);
return el;
}
public void destroy() {
forceHide();
setContentElement(null);
positionController = null;
}
/**
* Add one or more partner elements that, when the panel is dragged, are resized and moved relative to the
* panel's delta.
*/
public void addPartnerDragElements(Element ... elems) {
if (elems != null) {
for (Element e : elems) {
clickTargets.add(e);
}
}
}
public void removePartnerDragElements(Element ... elems) {
if (elems != null) {
for (Element e : elems) {
clickTargets.remove(e);
}
}
}
private void forceHide() {
}
public void setPosition(int left, int top) {
CSSStyleDeclaration style = getView().getElement().getStyle();
if (left < 0) {
// set right
style.clearLeft();
style.setRight(-left, "px");
} else {
style.clearRight();
style.setLeft(left, "px");
}
if (top < 0) {
style.clearTop();
style.setBottom(-top, "px");
} else {
style.clearBottom();
style.setTop(top, "px");
}
}
public void setAllHeader() {
getView().setHeaderElement(Elements.asJsElement(getView().contentContainer));
}
/**
* @return the bounds
*/
public ResizeBounds getBounds() {
return bounds;
}
/**
* @param bounds the bounds to set
*/
public void setBounds(ResizeBounds bounds) {
//TODO: resize if and only if bounds changed
this.bounds = bounds;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.