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/ClientOsOther.java | client/src/main/java/com/google/collide/client/ClientOsOther.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;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;
/**
* Information about an "other" ClientOs.
*
*/
public class ClientOsOther implements ClientOs {
protected interface MessageStrings extends Messages {
@DefaultMessage("Alt")
public String alt();
@DefaultMessage("Alt-")
public String altAbbr();
@DefaultMessage("Control")
public String ctrl();
@DefaultMessage("Ctrl-")
public String ctrlAbbr();
@DefaultMessage("Shift")
public String shift();
@DefaultMessage("Shift-")
public String shiftAbbr();
}
private static final MessageStrings messages = GWT.create(MessageStrings.class);
@Override
public String actionKeyDescription() {
return messages.ctrl();
}
@Override
public String actionKeyLabel() {
return messages.ctrlAbbr();
}
@Override
public boolean isMacintosh() {
return false;
}
@Override
public String shiftKeyDescription() {
return messages.shift();
}
@Override
public String shiftKeyLabel() {
return messages.shiftAbbr();
}
@Override
public String altKeyDescription() {
return messages.alt();
}
@Override
public String altKeyLabel() {
return messages.altAbbr();
}
@Override
public String ctrlKeyDescription() {
return messages.ctrl();
}
@Override
public String ctrlKeyLabel() {
return messages.ctrlAbbr();
}
}
| 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/ClientOs.java | client/src/main/java/com/google/collide/client/ClientOs.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;
/**
* Information about the client operating and/or windowing system.
*/
public interface ClientOs {
/**
* @return a slightly longer string for text describing action keys, i.e.
* "Command" or "Control"
*/
public String actionKeyDescription();
/**
* The canonical prefix for an action key (e.g. clover for Mac, "Ctrl" for
* others).
*
* @return a very short string suitable for menu shortcuts
*/
public String actionKeyLabel();
public boolean isMacintosh();
/**
* @return a slightly longer string for text describing shift keys, i.e.
* "Shift".
*/
public String shiftKeyDescription();
/**
* The canonical prefix for a shift key (e.g. uparrow for Mac, "Shift" for
* others).
*
* @return a very short string suitable for menu shortcuts
*/
public String shiftKeyLabel();
/**
* @return a string suitable for naming the Alt key
*/
public String altKeyDescription();
/**
* @return a very short string suitable for menu shortcuts needing the Alt key
*/
public String altKeyLabel();
/**
* @return a string suitable for naming the Ctrl key
*/
public String ctrlKeyDescription();
/**
* @return a very short string suitable for menu shortcuts needing the Ctrl key
*/
public String ctrlKeyLabel();
} | 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/ClientConfig.java | client/src/main/java/com/google/collide/client/ClientConfig.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;
import com.google.gwt.core.client.GWT;
/**
* A deferred-binding class to provide compile-time constant tests for whether a
* build is a "release" or "debug" build.
*
*/
public abstract class ClientConfig {
/**
* Base type for our deferred bound concrete implementations that statically
* determine if a build should be a debug or release permutation.
*/
public static abstract class DebugOrReleaseMode {
abstract boolean isDebug();
}
/**
* Alternative to {@link ReleaseMode}, substituted by
* {@link GWT#create(Class)} if gwt.xml properties tell it this is a debug
* build.
*/
@SuppressWarnings("unused")
private static class DebugMode extends DebugOrReleaseMode {
@Override
public boolean isDebug() {
return true;
}
}
/**
* Mode for "Release" builds, possibly replaced with {@link DebugMode} if the
* gwt.xml property tells {@link GWT#create(Class)} to do so.
*/
@SuppressWarnings("unused")
private static class ReleaseMode extends DebugOrReleaseMode {
@Override
public boolean isDebug() {
return false;
}
}
private static final DebugOrReleaseMode MODE_INSTANCE = GWT.create(DebugOrReleaseMode.class);
public static boolean isDebugBuild() {
return MODE_INSTANCE.isDebug();
}
}
| 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/ClientOsMacintosh.java | client/src/main/java/com/google/collide/client/ClientOsMacintosh.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;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;
/**
* Information about an "other" ClientOs.
*
*/
public class ClientOsMacintosh implements ClientOs {
protected interface MessageStrings extends Messages {
@DefaultMessage("Option")
public String alt();
@DefaultMessage("\u2325")
public String altAbbr();
@DefaultMessage("Control")
public String ctrl();
@DefaultMessage("Ctrl")
public String ctrlAbbr();
@DefaultMessage("Command")
public String cmd();
@DefaultMessage("\u2318")
public String cmdAbbr();
@DefaultMessage("Shift")
public String shift();
@DefaultMessage("\u21e7")
public String shiftAbbr();
}
private static final MessageStrings messages = GWT.create(MessageStrings.class);
@Override
public String actionKeyDescription() {
return messages.cmd();
}
@Override
public String actionKeyLabel() {
return messages.cmdAbbr();
}
@Override
public boolean isMacintosh() {
return true;
}
@Override
public String shiftKeyDescription() {
return messages.shift();
}
@Override
public String shiftKeyLabel() {
return messages.shiftAbbr();
}
@Override
public String altKeyDescription() {
return messages.alt();
}
@Override
public String altKeyLabel() {
return messages.altAbbr();
}
@Override
public String ctrlKeyDescription() {
return messages.ctrl();
}
@Override
public String ctrlKeyLabel() {
return messages.ctrlAbbr();
}
}
| 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/InvalidationMessageDemux.java | client/src/main/java/com/google/collide/client/InvalidationMessageDemux.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;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
import com.google.collide.clientlibs.invalidation.InvalidationManager;
import com.google.collide.dto.InvalidationMessage;
import com.google.collide.dto.RoutingTypes;
/**
* A demultiplexer that receives a single {@link InvalidationMessage} message type from the push
* channel and sends it to the appropriate listener.
*
*/
public class InvalidationMessageDemux {
public static InvalidationMessageDemux attach(
InvalidationManager invalidationManager, MessageFilter messageFilter) {
InvalidationMessageDemux demux = new InvalidationMessageDemux(invalidationManager);
messageFilter.registerMessageRecipient(RoutingTypes.INVALIDATIONMESSAGE, demux.dtoRecipient);
return demux;
}
private final InvalidationManager tangoInvalidationManager;
private final MessageRecipient<InvalidationMessage> dtoRecipient =
new MessageRecipient<InvalidationMessage>() {
@Override
public void onMessageReceived(InvalidationMessage invalidation) {
tangoInvalidationManager.handleInvalidation(invalidation.getObjectName(),
Long.parseLong(invalidation.getVersion()), invalidation.getPayload());
}
};
private InvalidationMessageDemux(InvalidationManager tangoInvalidationManager) {
this.tangoInvalidationManager = tangoInvalidationManager;
}
}
| 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/Resources.java | client/src/main/java/com/google/collide/client/Resources.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;
import collide.client.common.CommonResources.BaseResources;
import com.google.collide.client.status.StatusPresenter;
import com.google.collide.client.ui.panel.Panel;
import com.google.collide.client.ui.popup.Popup;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.client.workspace.WorkspaceShell;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.CssResource.NotStrict;
/**
* Interface for resources, e.g., css, images, text files, etc. Make sure you
* add your resource to
* {@link com.google.collide.client.Collide#onModuleLoad()}.
*/
public interface Resources
extends
BaseResources,
StatusPresenter.Resources,
WorkspaceShell.Resources,
// TODO: Once we have actual consumers of the Tooltip class, we
// can just have them extend it instead of doing it on the base interface.
Tooltip.Resources,
Popup.Resources,
Panel.Resources{
/**
* Interface for css resources.
*/
public interface AppCss extends CssResource {
}
@Source({"app.css", "collide/client/common/constants.css"})
@NotStrict
AppCss appCss();
}
| 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/Collide.java | client/src/main/java/com/google/collide/client/Collide.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;
import xapi.util.api.SuccessHandler;
import collide.client.util.Elements;
import com.google.collide.client.history.HistoryUtils;
import com.google.collide.client.history.HistoryUtils.ValueChangeListener;
import com.google.collide.client.history.RootPlace;
import com.google.collide.client.status.StatusPresenter;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.client.workspace.WorkspacePlaceNavigationHandler;
import com.google.collide.clientlibs.navigation.NavigationToken;
import com.google.collide.json.shared.JsonArray;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.EntryPoint;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Collide implements EntryPoint {
/**
* This is the entry point method.
*/
@Override
public void onModuleLoad() {
CollideBootstrap.start(new SuccessHandler<AppContext>() {
@Override
public void onSuccess(AppContext appContext) {
// Setup Places
setUpPlaces(appContext);
// Status Presenter
StatusPresenter statusPresenter = StatusPresenter.create(appContext.getResources());
Elements.getBody().appendChild(statusPresenter.getView().getElement());
appContext.getStatusManager().setHandler(statusPresenter);
// Replay History
replayHistory(HistoryUtils.parseHistoryString());
}
});
}
@VisibleForTesting
static void setUpPlaces(AppContext context) {
RootPlace.PLACE.registerChildHandler(
WorkspacePlace.PLACE, new WorkspacePlaceNavigationHandler(context), true);
// Back/forward buttons or manual manipulation of the hash.
HistoryUtils.addValueChangeListener(new ValueChangeListener() {
@Override
public void onValueChanged(String historyString) {
replayHistory(HistoryUtils.parseHistoryString(historyString));
}
});
}
private static void replayHistory(JsonArray<NavigationToken> historyPieces) {
// We don't want to snapshot history as we fire the Place events in the
// replay.
RootPlace.PLACE.disableHistorySnapshotting();
RootPlace.PLACE.dispatchHistory(historyPieces);
RootPlace.PLACE.enableHistorySnapshotting();
}
}
| 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/CollideSettings.java | client/src/main/java/com/google/collide/client/CollideSettings.java | package com.google.collide.client;
import com.google.gwt.core.client.JavaScriptObject;
public class CollideSettings extends JavaScriptObject {
protected CollideSettings() {}
public static native CollideSettings get()
/*-{
return $wnd.collide || {};
}-*/;
public final native String getMode()
/*-{
return this.mode;
}-*/;
public final native String getModule()
/*-{
return this.module;
}-*/;
public final native String getOpenFile()
/*-{
return this.open;
}-*/;
public final boolean isHidden() {
return "hidden".equals(getMode());
}
} | 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/util/ClientStringUtils.java | client/src/main/java/com/google/collide/client/util/ClientStringUtils.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.util;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.regexp.shared.RegExp;
/**
* String utility methods that delegate to native Javascript.
*
*/
public class ClientStringUtils {
private static final RegExp regexpUppercase = RegExp.compile("[A-Z]");
/**
* Returns true if the given string contains any uppercase characters.
*/
public static boolean containsUppercase(String s) {
return regexpUppercase.test(s);
}
/**
* Splits the string by the given separator string.
*
* <p>If an empty string ("") is used as the separator, the string is
* split between each character.
*
* <p>If there is no chars between separators, or separator and the start
* or end of line - then empty strings are added to result.
*/
public static native JsArrayString split(String s, String separator) /*-{
return s.split(separator);
}-*/;
/**
* Takes a given path separated by PathUtil.SEP and will hack off all but the
* specified number of paths. I.E. With a directory number of 2 it will turn
* /my/long/tree/file.txt to .../tree/file.txt.
*
* Also handles long directories such as
* /mylongdirsisstillonlyonepath/file.txt by specifying maxChars.
*
* @param path String path to operate on
* @param dirs maximum number of directory segments to leave
* @param maxChars if > 3 specifies the maximum length of the returned string
* before it is truncated
* @param sep Separator to use during split
*
* @return
*/
public static String ellipsisPath(PathUtil path, int dirs, int maxChars, String sep) {
int components = path.getPathComponentsCount();
String pathString = path.getPathString();
if (dirs != 0 && components > dirs) {
pathString = ".." + PathUtil.createExcludingFirstN(path, components - dirs).getPathString();
}
if (maxChars > 2 && pathString.length() > maxChars) {
// goto from the right maxChars - 2 for the length of the ..
pathString = ".." + pathString.substring(pathString.length() - maxChars + 2);
}
return pathString;
}
}
| 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/util/ClientTimer.java | client/src/main/java/com/google/collide/client/util/ClientTimer.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.util;
import com.google.collide.shared.util.Timer;
/**
* A client implementation of {@link Timer}.
*/
public class ClientTimer implements Timer {
public static Timer.Factory FACTORY = new Timer.Factory() {
@Override
public Timer createTimer(Runnable runnable) {
return new ClientTimer(runnable);
}
};
private final elemental.util.Timer timer;
private ClientTimer(final Runnable runnable) {
timer = new elemental.util.Timer() {
@Override
public void run() {
runnable.run();
}
};
}
@Override
public void schedule(int delayMs) {
timer.schedule(delayMs);
}
@Override
public void cancel() {
timer.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/util/WindowUnloadingController.java | client/src/main/java/com/google/collide/client/util/WindowUnloadingController.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.util;
import elemental.js.JsBrowser;
import java.util.ArrayList;
import java.util.List;
/**
* A controller used to manage messages displayed when the user attempts to
* close the browser or navigate to another page.
*
*/
public class WindowUnloadingController {
/**
* A message displayed to the user when the user tries to navigate away from
* the page.
*
*/
public static interface Message {
/**
* Returns the message to display to the user in an attempt to prevent the
* user from navigating away from the application.
*
* @return the message, or null if it is safe to close the app
*/
String getMessage();
}
private final List<Message> messages = new ArrayList<Message>();
public WindowUnloadingController() {
JsBrowser.getWindow().setOnbeforeunload(e-> handleBeforeUnloadEvent());
}
public void addMessage(Message message) {
messages.add(message);
}
public void removeMessage(Message message) {
messages.remove(message);
}
private String handleBeforeUnloadEvent() {
// Look for an active message in any of the ClosingMessages.
String toRet = null;
for (Message message : messages) {
String m = message.getMessage();
if (m != null) {
if (toRet != null) {
// Chrome does not support newlines in alert boxes, so use spaces
// instead.
toRet += " ";
}
toRet = (toRet == null) ? m : (toRet + m);
}
}
return toRet;
}
}
| 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/util/CountExecutor.java | client/src/main/java/com/google/collide/client/util/CountExecutor.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.util;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
/**
* Executes the queued commands after {@link #execute(Runnable)} has been called
* the given number of times.
*
* Any calls to {@link #execute(Runnable)} after the given count has been
* reached will be executed synchronously.
*
*/
public class CountExecutor implements Executor {
private final int totalCount;
private int curCount;
private final JsonArray<Runnable> commands = JsonCollections.createArray();
public CountExecutor(int totalCount) {
this.totalCount = totalCount;
}
/**
* Called with the intent to either have the given {@code command} executed
* and/or increase the count.
*
* @param command optional, the command to execute
*/
@Override
public void execute(Runnable command) {
if (command != null) {
commands.add(command);
}
if (++curCount == totalCount) {
for (int i = 0, n = commands.size(); i < n; i++) {
commands.get(i).run();
}
} else if (curCount > totalCount) {
command.run();
}
}
}
| 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/util/HoverController.java | client/src/main/java/com/google/collide/client/util/HoverController.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.util;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.user.client.Timer;
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;
/**
* Controller to manage a group of elements that are hovered and unhovered
* together. For example, you can use this controller to link a button to its
* submenu.
*
* When the user mouses over any of the "partner" elements, the controller calls
* {@link HoverListener#onHover()}. When the user mouses out of all partner
* elements and does not mouse over one of the elements within a fixed delay,
* the controller calls {@link UnhoverListener#onUnhover()}.
*
* The default delay is 1300ms, but you can override this. We recommend using
* one of the static values so that similar UI components use the same delay.
*/
public class HoverController {
/**
* The default unhover delay.
*/
public static final int DEFAULT_UNHOVER_DELAY = 1300;
/**
* The unhover delay used for dropdown UI components, such as button menus.
*/
public static final int DROP_DOWN_UNHOVER_DELAY = 300;
/**
* Listener interface to be notified of hover state changes.
*/
public static interface HoverListener {
/**
* Handles the event when the user hovers one of the partner elements.
*/
public void onHover();
}
/**
* Listener interface to be notified of hover state changes.
*/
public static interface UnhoverListener {
/**
* Handles the event when the user unhovers one of the partner elements, and
* does not hover another partner element within the fixed delay.
*/
public void onUnhover();
}
/**
* A helper class to store a partner element and it's event removers.
*/
private class PartnerHolder {
private final Element element;
private final EventRemover mouseOverRemover;
private final EventRemover mouseOutRemover;
PartnerHolder(final Element element) {
this.element = element;
mouseOverRemover = element.addEventListener(Event.MOUSEOVER, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (relatedTargetOutsideElement((MouseEvent) evt)) {
hover();
}
}
}, false);
mouseOutRemover = element.addEventListener(Event.MOUSEOUT, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (relatedTargetOutsideElement((MouseEvent) evt)) {
unhover();
}
}
}, false);
}
Element getElement() {
return element;
}
void teardown() {
mouseOverRemover.remove();
mouseOutRemover.remove();
}
/**
* Checks if the related target of the MouseEvent (the "from" element for a
* mouseover, the "to" element for a mouseout) is actually outside of the
* partner element. If the target element contains children, we will receive
* mouseover/mouseout events when the mouse moves over/out of the children,
* even if the mouse is still within the partner element. These
* intra-element events don't affect the hover state of the partner element,
* so we want to ignore them.
*/
private boolean relatedTargetOutsideElement(MouseEvent evt) {
EventTarget relatedTarget = evt.getRelatedTarget();
return relatedTarget == null || !element.contains((Node) relatedTarget);
}
}
private HoverListener hoverListener;
private UnhoverListener unhoverListener;
private boolean isHovering = false;
private int unhoverDelay = DEFAULT_UNHOVER_DELAY;
private Timer unhoverTimer;
private final JsonArray<PartnerHolder> partners = JsonCollections.createArray();
/**
* Adds a partner element to this controller. See class javadoc for
* an explanation of the interaction between partner elements.
*/
public void addPartner(Element element) {
if (!hasPartner(element)) {
partners.add(new PartnerHolder(element));
}
}
/**
* Removes a partner element from this controller.
*/
public void removePartner(Element element) {
for (int i = 0, n = partners.size(); i < n; ++i) {
PartnerHolder holder = partners.get(i);
if (holder.getElement() == element) {
holder.teardown();
partners.remove(i);
break;
}
}
}
private boolean hasPartner(Element element) {
for (int i = 0, n = partners.size(); i < n; ++i) {
PartnerHolder holder = partners.get(i);
if (holder.getElement() == element) {
return true;
}
}
return false;
}
/**
* Sets the listener that will receive events when any of the partner elements
* is hovered.
*/
public void setHoverListener(HoverListener listener) {
this.hoverListener = listener;
}
/**
* Sets the listener that will receive events when all of the partner elements
* are unhovered.
*/
public void setUnhoverListener(UnhoverListener listener) {
this.unhoverListener = listener;
}
/**
* Sets the delay between the last native mouseout event and when
* {@link UnhoverListener#onUnhover()} is called. If the user mouses out of
* one partner element and over another partner element within the unhover
* delay, the unhover event is not triggered.
*
* If the delay is zero, the unhover listener is called synchronously. If the
* delay is less than zero, the unhover listener is never called.
*
* @param delay the delay in milliseconds
*/
public void setUnhoverDelay(int delay) {
this.unhoverDelay = delay;
}
/**
* Cancels the unhover timer if one is pending. This will prevent an unhover
* listener from firing until the next time the user mouses out of a partner
* element.
*/
public void cancelUnhoverTimer() {
if (unhoverTimer != null) {
unhoverTimer.cancel();
unhoverTimer = null;
}
}
/**
* Flushes the unhover timer if one is pending. This will reset the hover
* controller to a state where it can fire a hover event the next time the
* element is hovered.
*/
public void flushUnhoverTimer() {
if (unhoverTimer != null) {
cancelUnhoverTimer();
unhoverNow();
}
}
/**
* Updates the state of the controller to indicate that the user is hovering
* over one of the partner elements.
*/
private void hover() {
cancelUnhoverTimer();
// Early exit if already hovering.
if (isHovering) {
return;
}
isHovering = true;
if (hoverListener != null) {
hoverListener.onHover();
}
}
/**
* Starts a timer that will update the controller to the unhover state if the
* user doesn't hover one of the partner elements within the specified unhover
* delay.
*/
private void unhover() {
// Early exit if already unhovering or if the delay is negative.
if (!isHovering || unhoverDelay < 0) {
return;
}
if (unhoverDelay == 0) {
unhoverNow();
} else if (unhoverTimer == null) {
// Wait a short time before unhovering so the user has a chance to move
// the mouse from one partner to another.
unhoverTimer = new Timer() {
@Override
public void run() {
unhoverNow();
}
};
unhoverTimer.schedule(unhoverDelay);
}
}
/**
* Updates the state of the controller to indicate that the user is no longer
* hovering any of the partner elements.
*/
private void unhoverNow() {
cancelUnhoverTimer();
isHovering = false;
if (unhoverListener != null) {
unhoverListener.onUnhover();
}
}
}
| 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/util/Executor.java | client/src/main/java/com/google/collide/client/util/Executor.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.util;
/**
* Mimics {@code java.util.concurrent.Executor} (which isn't available in GWT).
*/
public interface Executor {
public final static Executor SYNC_EXECUTOR = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
void execute(Runnable command);
} | 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/util/AnimationUtils.java | client/src/main/java/com/google/collide/client/util/AnimationUtils.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.util;
import collide.client.util.BrowserUtils;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
/**
* Utility class for using CSS3 transitions.
*/
public class AnimationUtils {
public static final double ALERT_TRANSITION_DURATION = 2.0;
public static final double LONG_TRANSITION_DURATION = 0.7;
public static final double MEDIUM_TRANSITION_DURATION = 0.3;
public static final double SHORT_TRANSITION_DURATION = 0.2;
private static final String OLD_OVERFLOW_STYLE_KEY = "__old_overflow";
private static final String TRANSITION_PROPERTIES = "all";
/**
* Handles transition ends and optionally invokes an animation callback.
*/
private static class TransitionEndHandler implements EventListener {
private EventListener animationCallback;
private TransitionEndHandler(EventListener animationCallback) {
this.animationCallback = animationCallback;
}
private void handleEndFor(Element elem, String type) {
// An element should only have 1 transition end handler at a time. We
// remove in the handle callback, but we cannot depend on the handle
// callback being correctly invoked. Over eager removal is OK.
TransitionEndHandler oldListener = getOldListener(elem, type);
if (oldListener != null) {
elem.removeEventListener(type, oldListener, false);
oldListener.maybeDispatchAnimationCallback(null);
}
elem.addEventListener(type, this, false);
replaceOldListener(elem, type, this);
}
private native void replaceOldListener(
Element elem, String type, TransitionEndHandler transitionEndHandler) /*-{
elem["__" + type + "_h"] = transitionEndHandler;
}-*/;
private native TransitionEndHandler getOldListener(Element elem, String type) /*-{
return elem["__" + type + "_h"];
}-*/;
private void maybeDispatchAnimationCallback(Event evt) {
if (animationCallback != null) {
animationCallback.handleEvent(evt);
animationCallback = null;
}
}
@Override
public void handleEvent(Event evt) {
Element target = (Element) evt.getTarget();
target.removeEventListener(evt.getType(), this, false);
removeTransitions(target.getStyle());
maybeDispatchAnimationCallback(evt);
}
}
/**
* @see: {@link #animatePropertySet(Element, String, String, double,
* EventListener)}.
*/
public static void animatePropertySet(
final Element elem, String property, String value, double duration) {
animatePropertySet(elem, property, value, duration, null);
}
/**
* Enables animations prior to setting the value for the specified style
* property on the supplied element. The end result is that there property is
* transitioned to.
*
* @param elem the {@link Element} we want to set the style property on.
* @param property the name of the style property we want to set.
* @param value the target value of the style property.
* @param duration the time in seconds we want the transition to last.
* @param animationCallback callback that is invoked when the animation
* completes. It will be passed a {@code null} event if the animation
* was pre-empted by some other animation on the same element.
*/
public static void animatePropertySet(final Element elem, String property, String value,
double duration, final EventListener animationCallback) {
final CSSStyleDeclaration style = elem.getStyle();
enableTransitions(style, duration);
if (BrowserUtils.isFirefox()) {
// For FF4.
new TransitionEndHandler(animationCallback).handleEndFor(elem, "transitionend");
} else {
// For webkit based browsers.
// TODO: Keep an eye on whether or not webkit supports the
// vendor prefix free version. If they ever do we should remove this.
new TransitionEndHandler(animationCallback).handleEndFor(elem, Event.WEBKITTRANSITIONEND);
}
style.setProperty(property, value);
}
public static void backupOverflow(CSSStyleDeclaration style) {
style.setProperty(OLD_OVERFLOW_STYLE_KEY, style.getOverflow());
style.setOverflow("hidden");
}
/**
* Disables CSS3 transitions.
*
* If you want to reset transitions after enabling them, use
* {@link #removeTransitions(CSSStyleDeclaration)} instead.
*/
public static void disableTransitions(CSSStyleDeclaration style) {
style.setProperty("-webkit-transition-property", "none");
style.setProperty("-moz-transition-property", "none");
}
/**
* @see: {@link #enableTransitions(CSSStyleDeclaration, double)}
*/
public static void enableTransitions(CSSStyleDeclaration style) {
enableTransitions(style, SHORT_TRANSITION_DURATION);
}
/**
* Enables CSS3 transitions for a given element.
*
* If you want to reset transitions after disabling them, use
* {@link #removeTransitions(CSSStyleDeclaration)} instead.
*
* @param style the style object belonging to the element we want to animate.
* @param duration the length of time we want the animation to last.
*/
public static void enableTransitions(CSSStyleDeclaration style, double duration) {
style.setProperty("-webkit-transition-property", TRANSITION_PROPERTIES);
style.setProperty("-moz-transition-property", TRANSITION_PROPERTIES);
style.setProperty("-webkit-transition-duration", duration + "s");
style.setProperty("-moz-transition-duration", duration + "s");
}
/**
* Removes CSS3 transitions, returning them to their original state.
*/
public static void removeTransitions(CSSStyleDeclaration style) {
style.removeProperty("-webkit-transition-property");
style.removeProperty("-moz-transition-property");
style.removeProperty("-webkit-transition-duration");
style.removeProperty("-moz-transition-duration");
}
public static void fadeIn(final Element elem) {
elem.getStyle().setDisplay(CSSStyleDeclaration.Display.BLOCK);
// TODO: This smells like a chrome bug to me that we need to do a
// deferred command here.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
animatePropertySet(elem, "opacity", "1.0", SHORT_TRANSITION_DURATION);
}
});
}
public static void fadeOut(final Element elem) {
animatePropertySet(elem, "opacity", "0", SHORT_TRANSITION_DURATION, new EventListener() {
@Override
public void handleEvent(Event evt) {
elem.getStyle().setDisplay("none");
}
});
}
/**
* Flashes an element to highlight that it has recently changed.
*/
public static void flash(final Element elem) {
/*
* If we interrupt a flash with another flash, we need to disable animations
* so the initial background color takes effect immediately. Animations are
* reenabled in animatePropertySet.
*/
removeTransitions(elem.getStyle());
elem.getStyle().setBackgroundColor("#f9edbe");
// Give the start color a chance to take effect.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
animatePropertySet(elem, "background-color", "", ALERT_TRANSITION_DURATION);
}
});
}
public static void restoreOverflow(CSSStyleDeclaration style) {
style.setOverflow(style.getPropertyValue(OLD_OVERFLOW_STYLE_KEY));
}
}
| 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/util/ScheduledCommandExecutor.java | client/src/main/java/com/google/collide/client/util/ScheduledCommandExecutor.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.util;
import com.google.gwt.core.client.Scheduler;
/**
* Executor of a cancellable scheduled command.
*/
public abstract class ScheduledCommandExecutor {
private boolean scheduled;
private boolean cancelled;
private final Scheduler.ScheduledCommand scheduledCommand = new Scheduler.ScheduledCommand() {
@Override
public void execute() {
scheduled = false;
if (cancelled) {
return;
}
ScheduledCommandExecutor.this.execute();
}
};
protected abstract void execute();
public void scheduleFinally() {
cancelled = false;
if (!scheduled) {
scheduled = true;
Scheduler.get().scheduleFinally(scheduledCommand);
}
}
public void scheduleDeferred() {
cancelled = false;
if (!scheduled) {
scheduled = true;
Scheduler.get().scheduleDeferred(scheduledCommand);
}
}
public void cancel() {
cancelled = 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/util/ResizeBounds.java | client/src/main/java/com/google/collide/client/util/ResizeBounds.java | package com.google.collide.client.util;
import javax.inject.Provider;
import collide.client.util.CssUtils;
import com.google.collide.client.ui.panel.Panel.Interpolator;
import elemental.client.Browser;
import elemental.dom.Element;
public class ResizeBounds {
private Provider<Float>
minWidth, maxWidth
, minHeight, maxHeight
, prefHeight, prefWidth
;
private static class ImmutableProvider implements Provider<Float> {
private float value;
public ImmutableProvider(float value) {
this.value = value;
}
@Override
public Float get() {
return value;
}
}
private static abstract class ElementalProvider implements Provider<Float> {
private final Element element;
private final Interpolator interpolator;
public ElementalProvider(Element element, Interpolator interpolator) {
this.element = element;
this.interpolator = interpolator == null ? Interpolator.NO_OP : interpolator;
}
@Override
public Float get() {
return getValue(element, interpolator);
}
protected abstract Float getValue(Element element, Interpolator interpolator);
}
private static class ElementalHeightProvider extends ElementalProvider {
public ElementalHeightProvider(Element element, Interpolator interpolator) {
super(element, interpolator);
}
@Override
protected Float getValue(Element element, Interpolator interpolator) {
return interpolator.interpolate(CssUtils.parsePixels(element.getStyle().getHeight()));
}
}
private static class ElementalWidthProvider extends ElementalProvider {
public ElementalWidthProvider(Element element, Interpolator interpolator) {
super(element, interpolator);
}
@Override
protected Float getValue(Element element, Interpolator interpolator) {
// we want to use the css width, and not the element's actual width,
// in case it has padding or borders we want to ignore.
return interpolator.interpolate(CssUtils.parsePixels(element.getStyle().getWidth()));
}
}
/**
* @return the minHeight
*/
public float getMinHeight() {
Float min = minHeight.get();
if (min < 0)
min = Browser.getWindow().getInnerHeight()+min;
return min;
}
/**
* @return the maxHeight
*/
public float getMaxHeight() {
Float max = maxHeight.get();
if (max < 0)
max = Browser.getWindow().getInnerHeight()+max;
return max;
}
/**
* @return the minWidth
*/
public float getMinWidth() {
Float min = minWidth.get();
if (min < 0)
min = Browser.getWindow().getInnerWidth()+min;
return min;
}
/**
* @return the maxWidth
*/
public float getMaxWidth() {
Float max = maxWidth.get();
if (max < 0)
max = Browser.getWindow().getInnerWidth()+max;
return max;
}
public static BoundsBuilder withMaxSize(float maxWidth, float maxHeight) {
BoundsBuilder builder = new BoundsBuilder();
builder.maxWidth = maxWidth;
builder.maxHeight = maxHeight;
return builder;
}
public static BoundsBuilder withMinSize(float minWidth, float minHeight) {
BoundsBuilder builder = new BoundsBuilder();
builder.minWidth = minWidth;
builder.minHeight = minHeight;
return builder;
}
public static BoundsBuilder withPrefSize(float minWidth, float minHeight) {
BoundsBuilder builder = new BoundsBuilder();
builder.prefWidth = minWidth;
builder.prefHeight = minHeight;
return builder;
}
public static class BoundsBuilder {
private float
minHeight=Integer.MIN_VALUE
, minWidth=Integer.MIN_VALUE
, maxWidth=Integer.MAX_VALUE
, maxHeight=Integer.MAX_VALUE
, prefWidth=-10
, prefHeight=-10
;
private Provider<Float>
minWidthProvider, maxWidthProvider,
minHeightProvider, maxHeightProvider,
prefHeightProvider, prefWidthProvider
;
public BoundsBuilder maxSize(float maxWidth, float maxHeight) {
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
return this;
}
public BoundsBuilder prefSize(float prefWidth, float prefHeight) {
this.prefWidth = prefWidth;
this.prefHeight = prefHeight;
return this;
}
public BoundsBuilder minSize(float minWidth, float minHeight) {
this.minWidth = minWidth;
this.minHeight = minHeight;
return this;
}
public BoundsBuilder minWidth(Provider<Float> minWidth) {
minWidthProvider = minWidth;
return this;
}
public BoundsBuilder minWidth(float minWidth) {
minWidthProvider = null;
this.minWidth = minWidth;
return this;
}
public BoundsBuilder minHeight(Provider<Float> minHeight) {
minHeightProvider = minHeight;
return this;
}
public BoundsBuilder minHeight(float minHeight) {
minHeightProvider = null;
this.minHeight = minHeight;
return this;
}
public BoundsBuilder maxWidth(Provider<Float> maxWidth) {
maxWidthProvider = maxWidth;
return this;
}
public BoundsBuilder maxWidth(float maxWidth) {
maxWidthProvider = null;
this.maxWidth = maxWidth;
return this;
}
public BoundsBuilder maxHeight(Provider<Float> maxHeight) {
maxHeightProvider = maxHeight;
return this;
}
public BoundsBuilder maxHeight(float maxHeight) {
maxHeightProvider = null;
this.maxHeight = maxHeight;
return this;
}
public BoundsBuilder prefWidth(Provider<Float> prefWidth) {
prefWidthProvider = prefWidth;
return this;
}
public BoundsBuilder prefWidth(float prefWidth) {
prefWidthProvider = null;
this.prefWidth = prefWidth;
return this;
}
public BoundsBuilder prefHeight(Provider<Float> prefHeight) {
prefHeightProvider = prefHeight;
return this;
}
public BoundsBuilder prefHeight(float prefHeight) {
prefHeightProvider = null;
this.prefHeight = prefHeight;
return this;
}
public ResizeBounds build() {
ResizeBounds bounds = new ResizeBounds();
if (minHeightProvider == null)
bounds.minHeight = new ImmutableProvider(minHeight);
else
bounds.minHeight = minHeightProvider;
if (minWidthProvider == null)
bounds.minWidth = new ImmutableProvider(minWidth);
else
bounds.minWidth = minWidthProvider;
if (maxHeightProvider == null)
bounds.maxHeight = new ImmutableProvider(maxHeight);
else
bounds.maxHeight = maxHeightProvider;
if (maxWidthProvider == null)
bounds.maxWidth = new ImmutableProvider(maxWidth);
else
bounds.maxWidth = maxWidthProvider;
if (prefHeightProvider == null) {
bounds.prefHeight = new ImmutableProvider(prefHeight);
}
else
bounds.prefHeight = prefHeightProvider;
if (prefWidthProvider == null)
bounds.prefWidth = new ImmutableProvider(prefWidth);
else
bounds.prefWidth = prefWidthProvider;
return bounds;
}
public BoundsBuilder maxHeight(Element body, Interpolator inter) {
maxHeightProvider = new ElementalHeightProvider(body, inter);
return this;
}
public BoundsBuilder maxWidth(Element body, Interpolator inter) {
maxWidthProvider = new ElementalWidthProvider(body, inter);
return this;
}
public BoundsBuilder minHeight(Element body, Interpolator inter) {
minHeightProvider = new ElementalHeightProvider(body, inter);
return this;
}
public BoundsBuilder minWidth(Element body, Interpolator inter) {
minWidthProvider = new ElementalWidthProvider(body, inter);
return this;
}
}
public float getPreferredWidth() {
Float pref = prefWidth.get();
if (pref < 0)
pref = getMaxWidth() + pref;
return pref;
}
public float getPreferredHeight() {
Float pref = prefHeight.get();
if (pref < 0)
pref = getMaxHeight() + pref;
return pref;
}
}
| 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/util/QueryCallback.java | client/src/main/java/com/google/collide/client/util/QueryCallback.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.util;
import com.google.collide.dto.ServerError.FailureReason;
/**
* Generic callback for any requests that return a single value.
*/
public interface QueryCallback<E> {
/**
* Failure callback.
*
* @param reason the reason for the failure, should not be null
*/
void onFail(FailureReason reason);
/**
* Callback for queries to the ProjectModel.
*/
void onQuerySuccess(E result);
}
| 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/util/ImageResourceUtils.java | client/src/main/java/com/google/collide/client/util/ImageResourceUtils.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.util;
import collide.client.util.Elements;
import com.google.gwt.resources.client.ImageResource;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.html.DivElement;
/**
* Utilities for applying {@link ImageResource}s to elements.
*/
public class ImageResourceUtils {
/**
* Applies the image resource to the specified element. The image will be
* centered, and the height and width will be set to the height and width of
* the image.
*/
public static void applyImageResource(Element elem, ImageResource image) {
applyImageResource(elem, image, "center", "center");
elem.getStyle().setHeight(image.getHeight(), "px");
elem.getStyle().setWidth(image.getWidth(), "px");
}
/**
* Applies the image resource to the specified element with the specified
* horizontal and vertical background positions.
*
* The height and width of the element are not modified under the presumption
* that if you specify the horizontal and vertical position, the image will
* not be the only content of the element.
*/
public static void applyImageResource(Element elem, ImageResource image, String hPos,
String vPos) {
CSSStyleDeclaration style = elem.getStyle();
style.setBackgroundImage("url(" + image.getSafeUri().asString() + ")");
style.setProperty("background-repeat", "no-repeat");
style.setProperty("background-position", hPos + " " + vPos);
style.setOverflow("hidden");
}
/**
* Creates a div from the specified {@link ImageResource}.
*/
public static DivElement createImageElement(ImageResource image) {
DivElement elem = Elements.createDivElement();
applyImageResource(elem, image);
return elem;
}
}
| 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/util/ResizeController.java | client/src/main/java/com/google/collide/client/util/ResizeController.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.util;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.util.dom.eventcapture.MouseCaptureListener;
import com.google.collide.shared.util.StringUtils;
import com.google.gwt.animation.client.AnimationScheduler;
import com.google.gwt.animation.client.AnimationScheduler.AnimationCallback;
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.MouseEvent;
import elemental.util.ArrayOf;
import elemental.util.Collections;
/**
* Controller that adds resizing capabilities to elements.
*/
public class ResizeController {
/**
* CSS used by the resize controller.
*/
public static interface Css extends CssResource {
String horizontalCursor();
String verticalCursor();
String northeastCursor();
String northwestCursor();
String southeastCursor();
String southwestCursor();
String elementResizing();
String hSplitter();
String vSplitter();
String moveCursor();
String neSplitter();
String nwSplitter();
String seSplitter();
String swSplitter();
}
/**
* POJO that encapsulates an element and the CSS property that should be updated as the user drags the
* splitter.
*/
public static class ElementInfo {
private final Element element;
/**
* Stores the CSS property's value. This is faster than reading the CSS property value from
* {@link #applyDelta(int)}. This is also required to avoid out-of-sync with the cursor and
* width/height-resizing elements. (For example, an element's width is to be adjusted, and the mouse moves
* to the left of the element's left. The width should be negative, but the CSS property won't store a
* negative value. When the mouse moves back to the right, it will grow the element's width, but the mouse
* pointer will not be exactly over the element anymore.)
*/
protected int propertyValue;
private int propertyMinValue = Integer.MIN_VALUE;
private int propertyMaxValue = Integer.MAX_VALUE;
private final ResizeProperty resizeProperty;
private final String resizePropertyName;
public ElementInfo(Element element, ResizeProperty resizeProperty) {
this.element = element;
this.resizeProperty = resizeProperty;
this.resizePropertyName = resizeProperty.propertyName();
}
/**
* Constructs a new {@link ElementInfo} and sets the default value of the property.
*/
public ElementInfo(Element element, ResizeProperty resizeProperty, String defaultValue) {
this(element, resizeProperty);
element.getStyle().setProperty(resizePropertyName, defaultValue);
}
public Element getElement() {
return element;
}
public int getPropertyMinValue() {
return propertyMinValue;
}
public int getPropertyMaxValue() {
return propertyMaxValue;
}
public ResizeProperty getResizeProperty() {
return resizeProperty;
}
public ElementInfo setPropertyMinValue(int value) {
propertyMinValue = value;
return this;
}
public ElementInfo setPropertyMaxValue(int value) {
propertyMaxValue = value;
return this;
}
private void applyDelta(int deltaW, int deltaH) {
if (resizeProperty.isVertical()) deltaW = deltaH;
if (resizeProperty.isNegative()) {
propertyValue -= deltaW;
} else {
propertyValue += deltaW;
}
element.getStyle().setProperty(resizePropertyName, propertyValue + CSSStyleDeclaration.Unit.PX);
}
public void refresh() {
resetPropertyValue();
int delta = computeApplicableDelta(0);
applyDelta(delta, delta);
}
protected int computeApplicableDelta(int delta) {
int nextValue;
if (getResizeProperty().isNegative()) {
nextValue = propertyValue - delta;
nextValue = Math.min(nextValue, propertyMaxValue);
nextValue = Math.max(nextValue, propertyMinValue);
return propertyValue-nextValue;
}else {
nextValue = propertyValue + delta;
nextValue = Math.min(nextValue, propertyMaxValue);
nextValue = Math.max(nextValue, propertyMinValue);
return nextValue - propertyValue;
}
}
protected void resetPropertyValue() {
// Use the value of a CSS property if it has been explicitly set.
String value = getElement().getStyle().getPropertyValue(resizeProperty.toString());
//read in from the methods once per reset; our bounds will be fresh once per drag event.
propertyMaxValue = getPropertyMaxValue();
propertyMinValue = getPropertyMinValue();
if (propertyMaxValue <= 0)
propertyMaxValue = Integer.MAX_VALUE;
if (propertyMinValue <= 0)
propertyMinValue = Integer.MIN_VALUE;
if (!StringUtils.isNullOrEmpty(value) && CssUtils.isPixels(value)) {
int index = value.indexOf('.');
if (index!=-1) {
propertyValue = Integer.parseInt(value.substring(0, index));
}else {
propertyValue = CssUtils.parsePixels(value);
}
return;
}
switch (resizeProperty) {
case WIDTH:
case NEG_WIDTH:
propertyValue = getElement().getClientWidth();
break;
case HEIGHT:
case NEG_HEIGHT:
propertyValue = getElement().getClientHeight();
break;
case LEFT:
case NEG_LEFT:
propertyValue = getElement().getOffsetLeft();
break;
case TOP:
case NEG_TOP:
propertyValue = getElement().getOffsetTop();
break;
case RIGHT:
case NEG_RIGHT:
propertyValue = getElement().getOffsetWidth() + getElement().getOffsetLeft();
break;
case BOTTOM:
case NEG_BOTTOM:
propertyValue = getElement().getOffsetHeight() + getElement().getOffsetTop();
break;
}
}
}
public static class ResizeEventHandler {
public void whileDragging(float deltaW, float deltaH, float deltaX, float deltaY) {
}
public void startDragging(ElementInfo ... elementInfos) {
}
public void doneDragging(float deltaX, float deltaY, float origX, float origY) {
}
}
/**
* Enumeration that describes which CSS property should be affected by the resize.
*/
public enum ResizeProperty {
BOTTOM(false, true), HEIGHT(false, true), LEFT(true, false),
NEG_BOTTOM(false, true, true), NEG_HEIGHT(false, true, true),
NEG_LEFT(true, false, true), NEG_RIGHT(true, false, true),
NEG_TOP(false, true, true), NEG_WIDTH(true, false, true),
RIGHT(true, false), TOP(false, true), WIDTH(true, false);
private final String propName;
private final boolean negative, horizontal, vertical;
private ResizeProperty(boolean horizontal, boolean vertical) {
this(horizontal, vertical, false);
}
public String propertyName() {
return propName;
}
private ResizeProperty(boolean horizontal, boolean vertical, boolean negative) {
this.negative = negative;
this.propName = (negative ? toString().substring(4) : toString()).toLowerCase();
this.horizontal = horizontal;
this.vertical = vertical;
}
public boolean isHorizontal() {
return horizontal;
}
public boolean isNegative() {
return negative;
}
public boolean isVertical() {
return vertical;
}
}
/**
* ClientBundle for the resize controller.
*/
public interface Resources extends ClientBundle {
@Source("ResizeController.css")
Css resizeControllerCss();
}
private final Css css;
private final ElementInfo[] elementInfos;
private final boolean horizontal, vertical;
private final MouseCaptureListener mouseCaptureListener = new MouseCaptureListener() {
@Override
protected boolean onMouseDown(MouseEvent evt) {
return canStartResizing();
}
@Override
protected void onMouseMove(MouseEvent evt) {
if (!resizing) {
resizeStarted();
if (!resizing)//let subclasses cancel in resizeStarted()
return;
}
if (horizontal) {
int delta = getDeltaX();
resizeDraggedW(negativeW ? -delta : delta);
}
if (vertical) {
int delta = getDeltaY();
resizeDraggedH(negativeH ? -delta : delta);
}
}
@Override
protected void onMouseUp(MouseEvent evt) {
if (resizing) {
resizeEnded();
}
}
};
private boolean resizing;
private AnimationCallback animationCallback;
private final Element splitter;
private boolean negativeW, negativeH;
private int unappliedW, unappliedH;
private int totalW, totalH;
private String hoverClass;
private final String enabledClass;
private final ArrayOf<ResizeEventHandler> handlers;
public void addEventHandler(ResizeEventHandler handler) {
// assert !handlers.contains(handler) : "You are adding the same resize event handler more than once; " +
// "at "+DebugUtil.getCaller(10);
handlers.push(handler);
}
public void removeEventHandler(ResizeEventHandler handler) {
handlers.remove(handler);
assert !handlers.contains(handler) : "You somehow got more than one copy of the resize event handler, " +
handler+", into the resize controller "+this;
}
/**
* @param resources the css resources used to style dom
* @param splitter the element that will act as the splitter
* @param elementInfos element(s) that will be resized as the user drags the splitter
*/
public ResizeController(Resources resources, Element splitter, ElementInfo ... elementInfos) {
this.css = resources.resizeControllerCss();
this.splitter = splitter;
this.elementInfos = elementInfos;
handlers = Collections.arrayOf();
ElementInfo horizEl = null, vertEl = null;
for (ElementInfo info : elementInfos) {
if (info.resizeProperty.isHorizontal()) {
horizEl = info;
if (vertEl != null) break;
}
if (info.resizeProperty.isVertical()) {
vertEl = info;
if (horizEl != null) break;
}
}
this.horizontal = horizEl != null;
this.vertical = vertEl != null;
enabledClass = initCss(horizEl, vertEl);
}
protected String initCss(ElementInfo horizEl, ElementInfo vertEl) {
if (horizontal) {
if (vertical) {
// need to use the correct north/south east/west class name
switch (horizEl.resizeProperty) {
case LEFT:
case NEG_LEFT:
case NEG_WIDTH:
// west
switch (vertEl.resizeProperty) {
case TOP:
case NEG_TOP:
case NEG_HEIGHT:
splitter.addClassName(css.nwSplitter());
return css.northwestCursor();
case HEIGHT:
case BOTTOM:
case NEG_BOTTOM:
splitter.addClassName(css.swSplitter());
return css.southwestCursor();
default:
throw new RuntimeException("Configuration error; " + horizEl.resizeProperty +
" was vertical but " + "was not handled correctly by switch statement.");
}
case WIDTH:
case RIGHT:
case NEG_RIGHT:
// east
switch (vertEl.resizeProperty) {
case TOP:
case NEG_BOTTOM:
case NEG_HEIGHT:
splitter.addClassName(css.neSplitter());
return css.northeastCursor();
case HEIGHT:
case BOTTOM:
case NEG_TOP:
splitter.addClassName(css.seSplitter());
return css.southeastCursor();
default:
throw new RuntimeException("Configuration error; " + horizEl.resizeProperty +
" was vertical but " + "was not handled correctly by switch statement.");
}
default:
throw new RuntimeException("Configuration error; " + horizEl.resizeProperty +
" was horizontal but " + "was not handled correctly by switch statement.");
}
} else {
splitter.addClassName(css.hSplitter());
return css.horizontalCursor();
}
} else {
splitter.addClassName(css.vSplitter());
return css.verticalCursor();
}
}
public void setNegativeDeltaW(boolean negativeDelta) {
this.negativeW = negativeDelta;
}
public void setNegativeDeltaH(boolean negativeDelta) {
this.negativeH = negativeDelta;
}
public ElementInfo[] getElementInfos() {
return elementInfos;
}
public Element getSplitter() {
return splitter;
}
public void start() {
getSplitter().addEventListener(Event.MOUSEDOWN, mouseCaptureListener, false);
}
public void stop() {
getSplitter().removeEventListener(Event.MOUSEDOWN, mouseCaptureListener, false);
mouseCaptureListener.release();
if (resizing) {
resizeEnded();
}
}
private void maybeSchedule() {
/* Give the browser a chance to redraw before applying the next delta. Otherwise, we'll end up locking the
* browser if the user moves the mouse too quickly. */
if (animationCallback == null) {
animationCallback = new AnimationCallback() {
@Override
public void execute(double arg0) {
if (this != animationCallback) {
// The resize event was already ended.
return;
}
animationCallback = null;
applyUnappliedDelta();
}
};
AnimationScheduler.get().requestAnimationFrame(animationCallback);
}
}
private void resizeDraggedW(int delta) {
unappliedW += delta;
maybeSchedule();
}
private void resizeDraggedH(int delta) {
unappliedH += delta;
maybeSchedule();
}
private void applyUnappliedDelta() {
int deltaW = unappliedW, deltaH = unappliedH;
for (ElementInfo elementInfo : getElementInfos()) {
// deltaToApply ends up being the minimum delta that any element can
// accept.
if (elementInfo.resizeProperty.horizontal) {
deltaW = elementInfo.computeApplicableDelta(deltaW);
}
if (elementInfo.resizeProperty.vertical) {
deltaH = elementInfo.computeApplicableDelta(deltaH);
}
}
totalW += deltaW;
totalH += deltaH;
unappliedW -= deltaW;
unappliedH -= deltaH;
applyDelta(deltaW, deltaH);
}
protected void applyDelta(int deltaW, int deltaH) {
//apply deltas to the elements we are resizing
float x, y, w, h;
x = y = w = h = 0;
for (ElementInfo elementInfo : getElementInfos()) {
elementInfo.applyDelta(deltaW, deltaH);
switch (elementInfo.resizeProperty) {
case LEFT:
case NEG_LEFT:
x += deltaW;
case RIGHT:
case NEG_RIGHT:
case WIDTH:
case NEG_WIDTH:
w += deltaH;
break;
case TOP:
case NEG_TOP:
y += deltaH;
case BOTTOM:
case NEG_BOTTOM:
case HEIGHT:
case NEG_HEIGHT:
h += deltaH;
break;
}
}
//also apply deltas to any added listener
for (int i = 0; i < handlers.length(); i++) {
handlers.get(i).whileDragging(w, h, x, y);
}
}
protected boolean canStartResizing() {
return true;
}
protected void resizeStarted() {
resizing = true;
if (hoverClass != null) {
splitter.addClassName(hoverClass);
}
for (ElementInfo elementInfo : getElementInfos()) {
// Disables transitions while we resize, or it will appear laggy.
elementInfo.getElement().addClassName(css.elementResizing());
elementInfo.resetPropertyValue();
// elementInfo.propertyValue;
}
totalH = totalW = 0;
//also apply deltas to any added listener
for (int i = 0; i < handlers.length(); i++) {
handlers.get(i).startDragging(getElementInfos());
}
setResizeCursorEnabled(true);
}
protected Css getCss() {
return css;
}
protected void resizeEnded() {
// Force a final resize if there is some unapplied delta.
if (unappliedW != 0 || unappliedW != 0) {
applyUnappliedDelta();
}
//notify handlers of the detach
for (int i = 0; i < handlers.length(); i++) {
handlers.get(i).doneDragging(totalW, totalH,0 ,0);
}
for (ElementInfo elementInfo : getElementInfos()) {
elementInfo.getElement().removeClassName(css.elementResizing());
}
if (hoverClass != null) {
splitter.removeClassName(hoverClass);
}
setResizeCursorEnabled(false);
resizing = false;
animationCallback = null;
unappliedW = 0;
unappliedH = 0;
}
/**
* Setting this property allows to avoid control "blinking" during resizing. Set the class to be applied
* when control is being dragged. The specified style-class should have at least the same sense as
* {@code :hover} pseudo-class applied to control.
*
* @param hoverClass style-class to be saved ad applied appropriately
*/
public void setHoverClass(String hoverClass) {
this.hoverClass = hoverClass;
}
protected String getResizeCursor() {
return enabledClass;
}
/**
* Forces all elements on the page to use the resize cursor while resizing.
*/
private void setResizeCursorEnabled(boolean enabled) {
CssUtils.setClassNameEnabled(Elements.getBody(), getResizeCursor(), enabled);
}
public boolean isNegativeWidth() {
for (ElementInfo el : elementInfos) {
switch (el.resizeProperty) {
case NEG_WIDTH:
case LEFT:
return true;
default:
}
}
return false;
}
public boolean isNegativeHeight() {
for (ElementInfo el : elementInfos) {
switch (el.resizeProperty) {
case NEG_HEIGHT:
case TOP:
return true;
default:
}
}
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/util/Utils.java | client/src/main/java/com/google/collide/client/util/Utils.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.util;
/**
* Random utility methods on the client.
*/
public class Utils {
/**
* Compares two objects.
*
* @return {@code true} if the objects are same of equal,
* or {@code false} otherwise
*/
public static boolean equalsOrNull(Object a, Object b) {
return (a != null) ? a.equals(b) : (b == 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/util/AnimationController.java | client/src/main/java/com/google/collide/client/util/AnimationController.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.util;
import collide.client.util.BrowserUtils;
import collide.client.util.CssUtils;
import com.google.collide.json.client.Jso;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
/*
* TODO: Here's the list of short-term TODOs:
*
* - Make sure our client measurements are accurate if the element has padding,
* margins, border, etc. Luckily, the current clients don't have any of these
*
* - So far, clients have used pixels for height, etc., I need to figure out
* whether other units are kosher with CSS transition.
*
* - There's a bug in Chrome that I need to file, to repro click four times
* quickly on an the expander arrow, and notice that element is no longer
* expandable (the element doesn't accept changes with setClassName anymore).
*
* - A way to give the controller multiple mutually exclusive elements and
* transition smoothly (e.g. I am doing this with the
* CollaborationNavigationSection, but manually with a show/hide. I think the
* animation aesthetics can be improved if this controller knows/manages both
* together as one.)
*
* - For things like fixed height, we can figure it out based on the element.
* But, we don't want to do it at time of animation because we have to walk the
* CSSStyleRules. Instead, allow the builder to take in a "template" element
* that will look like the elements passed to show/hide.
*
* - Add support for non-animated initial state.
*/
/**
* Controller to aid in animating elements.
*
* Rules:
* <ul>
* <li>Initialize the element by calling
* {@link AnimationController#hideWithoutAnimating(Element)}. Don't set
* "display: none" in your CSS since the animation controller cannot undo it.
* <li>Do not modify the {@link Builder} after calling its
* {@link Builder#build()}.
* <li>Padding and margins must be specified in px units.
* </ul>
*/
public class AnimationController {
public interface AnimationStateListener {
void onAnimationStateChanged(Element element, State state);
}
/**
* Expands and collapses an element into and out of view.
*/
public static final AnimationController COLLAPSE_ANIMATION_CONTROLLER =
new AnimationController.Builder().setCollapse(true).build();
/**
* Fades an element into and out of view.
*/
public static final AnimationController FADE_ANIMATION_CONTROLLER =
new AnimationController.Builder().setFade(true).build();
public static final AnimationController COLLAPSE_FADE_ANIMATION_CONTROLLER =
new AnimationController.Builder().setCollapse(true).setFade(true).build();
/**
* Does not animate.
*/
public static final AnimationController NO_ANIMATION_CONTROLLER =
new AnimationController.Builder().build();
/**
* Builder for the {@link AnimationController}. Do not modify after calling
* {@link #build()}.
*
*/
public static class Builder {
private boolean collapse;
private boolean fade;
private boolean fixedHeight;
public AnimationController build() {
return new AnimationController(this);
}
// TODO: shrink height or width?
/** Defaults to false */
public Builder setCollapse(boolean collapse) {
this.collapse = collapse;
return this;
}
/** Defaults to false */
public Builder setFade(boolean fade) {
this.fade = fade;
return this;
}
/** Defaults to false */
public Builder setFixedHeight(boolean fixedHeight) {
this.fixedHeight = fixedHeight;
return this;
}
}
/**
* Handles the end of a CSS transition.
*/
private abstract class AbstractTransitionEndHandler implements EventListener {
public void handleEndFor(Element elem) {
// TODO: Keep an eye on whether or not webkit supports the
// vendor prefix free version. If they ever do we should remove this.
elem.addEventListener(Event.WEBKITTRANSITIONEND, this, false);
// For FF4 when we are ready.
// elem.addEventListener("transitionend", this, false);
}
public void unhandleEndFor(Element elem) {
elem.removeEventListener(Event.WEBKITTRANSITIONEND, this, false);
// For FF4 when we are ready.
// elem.removeEventListener("transitionend", this, false);
}
/*
* GWT complains that AbstractTransitionEndHandler doesn't define
* handleEvent() if we do not include this abstract method to override the
* interface method.
*/
@Override
public abstract void handleEvent(Event evt);
}
/**
* Handles the end of the show transition.
*/
private class ShowTransitionEndHandler extends AbstractTransitionEndHandler {
@Override
public void handleEvent(Event evt) {
/*
* Transition events propagate, so the event target could be a child of
* the element that we are controlling. For example, the child could be a
* button (with transitions enabled) within a form that is being animated.
*
* We verify that the target is actually being animated by the
* AnimationController by checking its current state. It will only have a
* state if the AnimationController added the state attribute to the
* target.
*/
Element target = (Element) evt.getTarget();
if (isAnyState(target, State.SHOWING)) {
showWithoutAnimating(target); // Puts element in SHOWN state
}
}
}
/**
* Handles the end of the hide transition.
*/
private class HideTransitionEndHandler extends AbstractTransitionEndHandler {
@Override
public void handleEvent(Event evt) {
/*
* Transition events propagate, so the event target could be a child of
* the element that we are controlling. For example, the child could be a
* button (with transitions enabled) within a form that is being animated.
*
* We verify that the target is actually being animated by the
* AnimationController by checking its current state. It will only have a
* state if the AnimationController added the state attribute to the
* target.
*/
Element target = (Element) evt.getTarget();
if (isAnyState(target, State.HIDING)) {
hideWithoutAnimating(target); // Puts element in HIDDEN state
}
}
}
/**
* An attribute added to an element to indicate its state.
*/
private static final String ATTR_STATE = "__animControllerState";
/**
* An attribute added to an element to stash its animation state listener.
*/
private static final String ATTR_STATE_LISTENER = "__animControllerStateListener";
/**
* The states that an element can be in.
*
* The only method we call on the state is {@link State#ordinal()}, which
* allows the GWT compiler to ordinalize the enums into integer constants.
*/
public static enum State {
/**
* The element is completely hidden.
*/
HIDDEN,
/**
* The element is transitioning to the hidden state.
*/
HIDING,
/**
* The element is completely shown.
*/
SHOWN,
/**
* The element is transitioning to the shown state.
*/
SHOWING
}
final boolean isAnimated; // Visible for testing.
private final Builder options;
private final ShowTransitionEndHandler showEndHandler;
private final HideTransitionEndHandler hideEndHandler;
private AnimationController(Builder builder) {
this.options = builder;
this.showEndHandler = new ShowTransitionEndHandler();
this.hideEndHandler = new HideTransitionEndHandler();
/*
* TODO: Remove this entirely when we move
* to FF4.0. Animations do not work on older versions of FF.
*/
boolean isFirefox = BrowserUtils.isFirefox();
/*
* If none of the animated properties are being animated, then the CSS
* transition end listener may not execute at all. In that case, we
* show/hide the element immediately.
*/
this.isAnimated = !isFirefox && (options.collapse || options.fade);
}
/**
* Animate the element out of view. Do not enable transitions in the CSS for this element, or the
* animations may not work correctly. AnimationController will enable animations automatically.
*
* @see #hideWithoutAnimating(Element)
*/
public void hide(final Element element) {
// Early exit if the element is hidden or hiding.
if (isAnyState(element, State.HIDDEN, State.HIDING)) {
return;
}
if (!isAnimated) {
hideWithoutAnimating(element);
return;
}
// Cancel pending transition event listeners.
showEndHandler.unhandleEndFor(element);
final CSSStyleDeclaration style = element.getStyle();
if (options.collapse) {
// Set height because the CSS transition requires one
int height = getCurrentHeight(element);
style.setHeight(height + CSSStyleDeclaration.Unit.PX);
}
// Give the browser a chance to accept the height set above
setState(element, State.HIDING);
schedule(element, new ScheduledCommand() {
@Override
public void execute() {
// The user changed the state before this command executed.
if (!clearLastCommand(element, this) || !isAnyState(element, State.HIDING)) {
return;
}
if (options.collapse) {
/*
* Hide overflow if changing height, or the overflow will be visible
* even as the element collapses.
*/
AnimationUtils.backupOverflow(style);
}
AnimationUtils.enableTransitions(style);
if (options.collapse) {
// Animate all properties that could affect height if collapsing.
style.setHeight("0");
style.setMarginTop("0");
style.setMarginBottom("0");
style.setPaddingTop("0");
style.setPaddingBottom("0");
CssUtils.setBoxShadow(element, "0 0");
}
if (options.fade) {
style.setOpacity(0);
}
}
});
// For webkit based browsers.
hideEndHandler.handleEndFor(element);
}
/**
* Animates the element into view. Do not enable transitions in the CSS for this element, or the
* animations may not work correctly. AnimationController will enable animations automatically.
*/
public void show(final Element element) {
// Early exit if the element is shown or showing.
if (isAnyState(element, State.SHOWN, State.SHOWING)) {
return;
}
if (!isAnimated) {
showWithoutAnimating(element);
return;
}
// Cancel pending transition event listeners.
hideEndHandler.unhandleEndFor(element);
/*
* Make this "visible" again so we can measure its eventual height (required
* for CSS transitions). We will set its initial state in this event loop,
* so the element will not be fully visible.
*/
final CSSStyleDeclaration style = element.getStyle();
element.getStyle().removeProperty("display");
final int measuredHeight = getCurrentHeight(element);
/*
* Set the initial state, but not if the element is in the process of
* hiding.
*/
if (!isAnyState(element, State.HIDING)) {
if (options.collapse) {
// Start the animation at a height of zero.
style.setHeight("0");
// We want to animate from total height of 0
style.setMarginTop("0");
style.setMarginBottom("0");
style.setPaddingTop("0");
style.setPaddingBottom("0");
CssUtils.setBoxShadow(element, "0 0");
/*
* Hide overflow if expanding the element, or the entire element will be
* instantly visible. Do not do this by default, because it could hide
* absolutely positioned elements outside of the root element, such as
* the arrow on a tooltip.
*/
AnimationUtils.backupOverflow(style);
}
if (options.fade) {
style.setOpacity(0);
}
}
// Give the browser a chance to accept the properties set above
setState(element, State.SHOWING);
schedule(element, new ScheduledCommand() {
@Override
public void execute() {
// The user changed the state before this command executed.
if (!clearLastCommand(element, this) || !isAnyState(element, State.SHOWING)) {
return;
}
// Enable animations before setting the end state.
AnimationUtils.enableTransitions(style);
// Set the end state.
if (options.collapse) {
if (options.fixedHeight) {
// The element's styles have a fixed height set, so we just want to
// clear our override
style.setHeight("");
} else {
// Give it an explicit height to animate to, because the element's
// height is auto otherwise
style.setHeight(measuredHeight + CSSStyleDeclaration.Unit.PX);
}
style.removeProperty("margin-top");
style.removeProperty("margin-bottom");
style.removeProperty("padding-top");
style.removeProperty("padding-bottom");
CssUtils.removeBoxShadow(element);
}
if (options.fade) {
style.setOpacity(1);
}
}
});
// For webkit based browsers.
showEndHandler.handleEndFor(element);
}
/**
* Checks if the specified element is logically hidden, which is true if it is
* hidden or in the process of hiding.
*/
public boolean isHidden(Element element) {
return isAnyState(element, State.HIDDEN, State.HIDING);
}
/**
* Returns the height as would be set on the CSS "height" property.
*/
private int getCurrentHeight(final Element element) {
// TODO: test to see if horizontal scroll plays nicely
CSSStyleDeclaration style = CssUtils.getComputedStyle(element);
return element.getClientHeight() - CssUtils.parsePixels(style.getPaddingTop())
- CssUtils.parsePixels(style.getPaddingBottom());
}
public void setVisibilityWithoutAnimating(Element element, boolean visibile) {
if (visibile) {
showWithoutAnimating(element);
} else {
hideWithoutAnimating(element);
}
}
/**
* Hide the element without animating it out of view. Use this method to set
* the initial state of the element.
*/
public void hideWithoutAnimating(Element element) {
if (isAnyState(element, State.HIDDEN)) {
return;
}
cancel(element);
element.getStyle().setDisplay(CSSStyleDeclaration.Display.NONE);
setState(element, State.HIDDEN);
}
/**
* Show the element without animating it into view.
*/
public void showWithoutAnimating(Element element) {
if (isAnyState(element, State.SHOWN)) {
return;
}
cancel(element);
element.getStyle().removeProperty("display");
setState(element, State.SHOWN);
}
/**
* Sets the listener for animation state change events.
*
* <p>
* If an element is not visible in the UI when an animation is applied, the animation will never
* complete and the element will stay in the state HIDING until some other animation is applied.
*/
public void setAnimationStateListener(Element element, AnimationStateListener listener) {
((Jso) element).addField(ATTR_STATE_LISTENER, listener);
}
public AnimationStateListener getAnimationStateListener(Element element) {
return (AnimationStateListener) ((Jso) element).getJavaObjectField(ATTR_STATE_LISTENER);
}
/**
* Cancel the currently executing animation without completing it.
*/
private void cancel(Element element) {
// Cancel all handlers.
setLastCommandImpl(element, null);
hideEndHandler.unhandleEndFor(element);
showEndHandler.unhandleEndFor(element);
// Disable animations.
CSSStyleDeclaration style = element.getStyle();
AnimationUtils.removeTransitions(style);
if (options.collapse) {
AnimationUtils.restoreOverflow(style);
}
// Remove the height and properties we set.
if (options.collapse) {
style.removeProperty("height");
style.removeProperty("margin-top");
style.removeProperty("margin-bottom");
style.removeProperty("padding-top");
style.removeProperty("padding-bottom");
}
if (options.fade) {
style.removeProperty("opacity");
}
CssUtils.removeBoxShadow(element);
}
private void setState(Element element, State state) {
element.setAttribute(ATTR_STATE, Integer.toString(state.ordinal()));
AnimationStateListener listener = getAnimationStateListener(element);
if (listener != null) {
listener.onAnimationStateChanged(element, state);
}
}
/**
* Check if the element is in any of the specified states.
*
* @param states the states to check, null is not allowed
* @return true if in any one of the states
*/
// Visible for testing.
boolean isAnyState(Element element, State... states) {
// Get the state ordinal from the attribute.
String ordinalStr = element.getAttribute(ATTR_STATE);
// NOTE: The following NULL check makes a dramatic performance impact!
if (ordinalStr == null) {
return false;
}
int ordinal = -1;
try {
ordinal = Integer.parseInt(ordinalStr);
} catch (NumberFormatException e) {
// The element's state has not been initialized yet.
return false;
}
for (State state : states) {
if (ordinal == state.ordinal()) {
return true;
}
}
return false;
}
/**
* Schedule a command to execute on the specified element. Use
* {@link #clearLastCommand(Element, ScheduledCommand)} to verify that the
* command is still the most recent command scheduled for the element.
*/
private void schedule(Element element, ScheduledCommand command) {
setLastCommandImpl(element, command);
Scheduler.get().scheduleDeferred(command);
}
/**
* Clear the last command from the specified element if the last command
* scheduled equals the specified command.
*
* @return true if the last command equals the specified command, false if no
*/
private native boolean clearLastCommand(Element element, ScheduledCommand command) /*-{
if (element.__gwtLastCommand == command) {
element.__gwtLastCommand = null; // Clear the last command if it is about to execute.
return true;
}
return false;
}-*/;
private native void setLastCommandImpl(Element element, ScheduledCommand command) /*-{
element.__gwtLastCommand = command;
}-*/;
}
| 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/util/BasicIncrementalScheduler.java | client/src/main/java/com/google/collide/client/util/BasicIncrementalScheduler.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.util;
import com.google.collide.client.util.UserActivityManager.UserActivityListener;
import com.google.collide.client.util.logging.Log;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
import com.google.gwt.core.client.Duration;
/**
* A scheduler that can incrementally run a task.
*
*/
public class BasicIncrementalScheduler implements IncrementalScheduler {
private final AsyncRunner runner = new AsyncRunner() {
@Override
public void run() {
if (isPaused) {
return;
}
try {
double start = Duration.currentTimeMillis();
boolean keepRunning = worker.run(currentWorkAmount);
updateWorkAmount(Duration.currentTimeMillis() - start);
if (keepRunning) {
schedule();
} else {
clearWorker();
}
} catch (Throwable t) {
Log.error(getClass(), "Could not run worker", t);
}
}
};
private Task worker;
private boolean isPaused;
private int currentWorkAmount;
private final int targetExecutionMs;
private int completedWorkAmount;
private double totalTimeTaken;
public Remover userActivityRemover;
public BasicIncrementalScheduler(int targetExecutionMs, int workGuess) {
this.targetExecutionMs = targetExecutionMs;
currentWorkAmount = workGuess;
}
public BasicIncrementalScheduler(
UserActivityManager userActivityManager, int targetExecutionMs, int workGuess) {
this(targetExecutionMs, workGuess);
userActivityRemover =
userActivityManager.getUserActivityListenerRegistrar().add(new UserActivityListener() {
@Override
public void onUserActive() {
pause();
}
@Override
public void onUserIdle() {
resume();
}
});
}
@Override
public void schedule(Task worker) {
cancel();
this.worker = worker;
if (!isPaused) {
runner.run();
}
}
@Override
public void cancel() {
runner.cancel();
worker = null;
}
@Override
public void pause() {
isPaused = true;
}
/**
* Schedules the worker to resume. This will run asychronously.
*/
@Override
public void resume() {
isPaused = false;
if (worker != null) {
launch();
}
}
@Override
public boolean isPaused() {
return isPaused;
}
@Override
public void teardown() {
cancel();
if (userActivityRemover != null) {
userActivityRemover.remove();
}
}
/**
* Update the currentWorkAmount based upon the workTime it took to run the
* last command so running the worker will take ~targetExecutionMs.
*
* @param workTime ms the last run took
*/
private void updateWorkAmount(double workTime) {
if (workTime <= 0) {
currentWorkAmount *= 2;
} else {
totalTimeTaken += workTime;
completedWorkAmount += currentWorkAmount;
currentWorkAmount = (int) Math.ceil(targetExecutionMs * completedWorkAmount / totalTimeTaken);
}
}
private void clearWorker() {
worker = null;
}
@Override
public boolean isBusy() {
return worker != null;
}
/**
* Queues the worker launch.
*/
private void launch() {
runner.schedule();
}
}
| 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/util/UserActivityManager.java | client/src/main/java/com/google/collide/client/util/UserActivityManager.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.util;
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.gwt.user.client.Timer;
/**
* A class that manages the active status of the user so that other objects can
* be intelligent about performing computationally intensive work.
*/
// TODO: extract the user activity manager out of the editor and
// make it more global so objects such
public class UserActivityManager {
private static final int IDLE_DELAY_MS = 400;
/**
* A listener that is called when the user either becomes idle or becomes
* active.
*/
public interface UserActivityListener {
/**
* Called when the user is considered idle.
*/
void onUserIdle();
/**
* Called when the user is considered active. This may be called
* synchronously from critical paths (scrolling), so avoid intensive work.
*/
void onUserActive();
}
private final Dispatcher<UserActivityListener> activeListenerDispatcher =
new Dispatcher<UserActivityManager.UserActivityListener>() {
@Override
public void dispatch(UserActivityListener listener) {
listener.onUserActive();
}
};
private final Dispatcher<UserActivityListener> idleListenerDispatcher =
new Dispatcher<UserActivityManager.UserActivityListener>() {
@Override
public void dispatch(UserActivityListener listener) {
listener.onUserIdle();
}
};
private boolean isUserActive = false;
private final ListenerManager<UserActivityListener> userActivityListenerManager =
ListenerManager.create();
private final Timer switchToIdleTimer = new Timer() {
@Override
public void run() {
handleUserIdle();
}
};
public ListenerRegistrar<UserActivityListener> getUserActivityListenerRegistrar() {
return userActivityListenerManager;
}
public boolean isUserActive() {
return isUserActive;
}
public void markUserActive() {
switchToIdleTimer.schedule(IDLE_DELAY_MS);
if (isUserActive) {
return;
}
isUserActive = true;
userActivityListenerManager.dispatch(activeListenerDispatcher);
}
private void handleUserIdle() {
if (!isUserActive) {
return;
}
isUserActive = false;
userActivityListenerManager.dispatch(idleListenerDispatcher);
}
}
| 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/util/DeferredCommandExecutor.java | client/src/main/java/com/google/collide/client/util/DeferredCommandExecutor.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.util;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
/**
* Executor of a cancellable repeating command.
*
* <p>Execution can be cancelled with {@link #cancel()} and rescheduled
* with consequent {@link #schedule(int)} invocations.
*
* <p>Generally method {@link #execute()} is invoked after
* (<i>{@link #tickDurationMs} * {@link #tickCount}</i>) ms.
* If this method return {@code true} then it is called again
* after {@link #tickDurationMs} ms.
*
* <p>If method {@link #schedule(int)} is called before {@link #execute()} had
* finally returned {@code false} then {@link #execute()} will be called
* only after (<i>{@link #tickDurationMs} * {@link #tickCount}</i>) ms.
*
* <p>At any time there is at most one scheduled {@link RepeatingCommand}.
* Thus duration to the next {@link #execute()} invocation is not exact.
* Actually duration can be less than expected by, at most,
* {@link #tickDurationMs}.
*/
public abstract class DeferredCommandExecutor {
/**
* A time granule size.
*
* <p>Bigger values make scheduling less accurate.
* Lesser values lead to more frequent idle cycles.
*/
private final int tickDurationMs;
/**
* A number of the idle cycles before action is executed.
*
* <p>{@code -1} means that action is not going to be executed.
*/
private int tickCount;
/**
* Indicator that shows if {@link #repeatingCommand} is still scheduled.
*/
private boolean repeatingCommandAlive;
/**
* Synchronisation / anti-recursion safeguard.
*
* <p>{@code true} when action is executed from timer callback.
*/
private boolean isExecuting;
/**
* Command that is regularly executed to check if it is time to run action.
*/
private final RepeatingCommand repeatingCommand = new RepeatingCommand() {
@Override
public boolean execute() {
isExecuting = true;
try {
repeatingCommandAlive = DeferredCommandExecutor.this.onTick();
} finally {
isExecuting = false;
}
if (!repeatingCommandAlive) {
tickCount = -1;
}
return repeatingCommandAlive;
}
};
private boolean onTick() {
// If disarmed
if (tickCount < 0) {
return false;
}
// It is not time yet
if (tickCount > 0) {
tickCount--;
}
if (tickCount > 0) {
return true;
}
return execute();
}
/**
* Method that is invoked on schedule.
*
* <p>After scheduled invocation, method will be re-invoked each
* {@link #tickDurationMs}ms until it return {@code false}, or
* {@link #cancel()} / {@link #schedule(int)} is called.
*/
protected abstract boolean execute();
/**
* Schedule / reschedule {@link #execute()} invocation.
*/
public void schedule(int tickCount) {
Preconditions.checkState(!isExecuting);
Preconditions.checkArgument(tickCount > 0);
this.tickCount = tickCount;
if (!repeatingCommandAlive) {
repeatingCommandAlive = true;
Scheduler.get().scheduleFixedDelay(repeatingCommand, tickDurationMs);
}
}
/**
* Cancel scheduled {@link #execute()} invocation.
*/
public void cancel() {
Preconditions.checkState(!isExecuting);
tickCount = -1;
}
/**
* Check if executor is going to invoke {@link #execute()} again.
*/
public boolean isScheduled() {
Preconditions.checkState(!isExecuting);
return tickCount >= 0;
}
protected DeferredCommandExecutor(int tickDurationMs) {
this.tickDurationMs = tickDurationMs;
}
}
| 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/util/AsyncRunner.java | client/src/main/java/com/google/collide/client/util/AsyncRunner.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.util;
import collide.client.util.Elements;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.gwt.core.client.JavaScriptObject;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.js.events.JsEvent;
/*
* TODO: Make a scheduler so there's only one event listener for
* ALL things that want to asyncrun
*/
/**
* An utility class to execute some logic asynchronously as soon as possible.
*
*/
public abstract class AsyncRunner implements Runnable {
private static final String EVENT_MESSAGE = "message";
private static class MessageEvent extends JsEvent implements Event {
protected MessageEvent() {
}
public final native Object getData() /*-{
return this.data;
}-*/;
public final native JavaScriptObject getSource() /*-{
return this.source;
}-*/;
}
private static int instanceId = 0;
private final String messageName =
BootstrapSession.getBootstrapSession().getActiveClientId() + ":AsyncRunner." + instanceId++;
private final String targetOrigin = Elements.getDocument().getLocation().getProtocol() + "//"
+ Elements.getDocument().getLocation().getHost();
private boolean isCancelled;
private boolean isAttached = false;
private EventListener messageHandler = new EventListener() {
@Override
public void handleEvent(elemental.events.Event rawEvent) {
MessageEvent event = (MessageEvent) rawEvent;
if (!isCancelled && event.getData().equals(messageName)) {
detachMessageHandler();
event.stopPropagation();
run();
}
}
};
public AsyncRunner() {
}
public void cancel() {
isCancelled = true;
detachMessageHandler();
}
public void schedule() {
isCancelled = false;
attachMessageHandler();
scheduleJs();
}
private void attachMessageHandler() {
if (!isAttached) {
Elements.getWindow().addEventListener(EVENT_MESSAGE, messageHandler, true);
isAttached = true;
}
}
private void detachMessageHandler() {
if (isAttached) {
Elements.getWindow().removeEventListener(EVENT_MESSAGE, messageHandler, true);
isAttached = false;
}
}
private native void scheduleJs() /*-{
// This is more responsive than setTimeout(0)
$wnd.postMessage(this.@com.google.collide.client.util.AsyncRunner::messageName, this.
@com.google.collide.client.util.AsyncRunner::targetOrigin);
}-*/;
}
| 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/util/ViewListController.java | client/src/main/java/com/google/collide/client/util/ViewListController.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.util;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.HasView;
import com.google.collide.shared.util.JsonCollections;
import elemental.dom.Element;
/**
* Encapsulates a list of dom elements that are to be reused during rendering. This controller will
* automatically create new ones when the list grows and remove old ones when it shrinks. It is
* particularly efficient if rendering happens often.
*
* @param <P> A presenter which has a view
*/
public class ViewListController<P extends HasView<?>> {
public static <P extends HasView<?>> ViewListController<P> create(
Element container, Factory<P> factory) {
return new ViewListController<P>(container, JsonCollections.<P>createArray(), factory);
}
/**
* A factory which can return a new presenter with its view.
*
* @param <P> The presenter type
*/
public interface Factory<P extends HasView<?>> {
/**
* Creates a new presenter and appends its view to the specified container.
*/
public P create(Element container);
}
private int index = 0;
private final JsonArray<P> list;
private final Factory<P> factory;
private final Element container;
public ViewListController(Element container, JsonArray<P> list, Factory<P> factory) {
this.list = list;
this.container = container;
this.factory = factory;
}
/**
* Resets the list to element index 0.
*/
public void reset() {
index = 0;
}
/**
* Retrieves the next presenter to be used (potentially creating a new one).
*/
public P next() {
int elementIndex = index++;
if (elementIndex >= list.size()) {
P presenter = factory.create(container);
list.add(presenter);
}
return list.get(elementIndex);
}
/**
* @return the number of elements current in the list.
*/
public int size() {
return list.size();
}
/**
* Removes any remaining elements still attached to the DOM.
*/
public void prune() {
if (index >= list.size()) {
return;
}
JsonArray<P> elementsToRemove = list.splice(index, list.size() - index);
for (int i = 0; i < elementsToRemove.size(); i++) {
elementsToRemove.get(i).getView().getElement().removeFromParent();
}
}
}
| 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/util/IncrementalScheduler.java | client/src/main/java/com/google/collide/client/util/IncrementalScheduler.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.util;
/**
* A scheduler that can incrementally run a task.
*/
public interface IncrementalScheduler {
public interface Task {
/**
* @return true if the task needs to continue
*/
boolean run(int workAmount);
}
public void schedule(Task worker);
public void cancel();
public void pause();
public void resume();
public boolean isPaused();
public boolean isBusy();
public 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/util/PathUtil.java | client/src/main/java/com/google/collide/client/util/PathUtil.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.util;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Preconditions;
/**
* Utility class for dealing with File paths on the client.
*
* <p>This class is immutable.
*
* TODO: We may need the equivalent of this on the server as well. If we do,
* might want to drop the use of native collections and put it in shared.
*/
public class PathUtil implements Comparable<PathUtil> {
public static final String SEP = "/";
public static final PathUtil EMPTY_PATH = new PathUtil("");
public static final PathUtil WORKSPACE_ROOT = new PathUtil(SEP);
/**
* Creates a PathUtil composed of the components of <code>first</code>
* followed by the components of <code>second>.
*/
public static PathUtil concatenate(PathUtil first, PathUtil second) {
JsonArray<String> components = first.pathComponentsList.copy();
components.addAll(second.pathComponentsList);
return new PathUtil(components);
}
/**
* Creates a PathUtil that has all the components of the supplied from
* PathUtil, excluding some number of path components from the end.
*/
public static PathUtil createExcludingLastN(PathUtil from, int componentsToExclude) {
JsonArray<String> result = JsonCollections.createArray();
for (int i = 0, n = from.getPathComponentsCount() - componentsToExclude; i < n; ++i) {
result.add(from.getPathComponent(i));
}
return new PathUtil(result);
}
/**
* Creates a PathUtil that has all the components of the supplied from
* PathUtil, excluding some number of path components from the beginning.
*/
public static PathUtil createExcludingFirstN(PathUtil from, int componentsToExclude) {
JsonArray<String> result = JsonCollections.createArray();
for (int i = componentsToExclude, n = from.getPathComponentsCount(); i < n; ++i) {
result.add(from.getPathComponent(i));
}
return new PathUtil(result);
}
public static PathUtil createFromPathComponents(JsonArray<String> pathComponentsList) {
return new PathUtil(pathComponentsList);
}
private final JsonArray<String> pathComponentsList;
private PathUtil(JsonArray<String> pathComponentsList) {
this.pathComponentsList = pathComponentsList;
}
public PathUtil(String path) {
pathComponentsList = JsonCollections.createArray();
if (path != null && !path.isEmpty()) {
JsonArray<String> pieces = StringUtils.split(path, SEP);
for (int i = 0, n = pieces.size(); i < n; i++) {
String piece = pieces.get(i);
/*
* Ignore empty string components or "." which stands for current directory
*/
if (!StringUtils.isNullOrEmpty(piece) && !piece.equals(".")) {
pathComponentsList.add(piece);
}
}
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof PathUtil) {
PathUtil other = (PathUtil) obj;
return getPathString().equals(other.getPathString());
}
return false;
}
@Override
public int hashCode() {
return getPathString().hashCode();
}
public String getBaseName() {
int numComponents = getPathComponentsCount();
String baseName = "";
if (numComponents > 0) {
baseName = getPathComponent(numComponents - 1);
}
return baseName;
}
/**
* @return the String representation of the path. Path Strings, except for the
* EMPTY_PATH, always start with a leading "/", implying that the path
* is relative to the workspace root.
*/
public String getPathString() {
if (this == EMPTY_PATH || pathComponentsList.size() == 0) {
return "";
}
return SEP + pathComponentsList.join(SEP);
}
public int getPathComponentsCount() {
return pathComponentsList.size();
}
public String getPathComponent(int index) {
return pathComponentsList.get(index);
}
/**
* Returns whether the given {@code path} is a child of this path (or is
* the same as this path). For example, a path "/tmp" contains "/tmp" and
* it also contains "/tmp/something".
*/
public boolean containsPath(PathUtil path) {
Preconditions.checkNotNull(path, "Containing path must not be null");
JsonArray<String> otherPathComponents = path.pathComponentsList;
if (otherPathComponents.size() < pathComponentsList.size()) {
// The path given has less components than ours, it cannot be a child
return false;
}
for (int i = 0; i < pathComponentsList.size(); i++) {
if (!pathComponentsList.get(i).equals(otherPathComponents.get(i))) {
return false;
}
}
return true;
}
/**
* Returns a new path util that is relative to the given parent path. For this to work parent must
* contain the current path. i.e. if the path is /tmp/alex.txt and you pass in a path of /tmp then
* you will get /alex.txt.
*
* @return null if parent is invalid
*/
public PathUtil makeRelativeToParent(PathUtil parent) {
Preconditions.checkNotNull(parent, "Parent path cannot be null");
JsonArray<String> parentPathComponents = parent.pathComponentsList;
if (parentPathComponents.size() > pathComponentsList.size()) {
// The path given has the same or more components, it can't be a parent
return null;
}
for (int i = 0; i < parentPathComponents.size(); i++) {
// this means that this is not our parent i.e. /a/b/t.txt vs /a/c/
if (!parentPathComponents.get(i).equals(pathComponentsList.get(i))) {
return null;
}
}
return new PathUtil(pathComponentsList.slice(
parentPathComponents.size(), pathComponentsList.size()));
}
/**
* Delegates to {@link #getPathString()} to return the string representation
* of this object.
*/
@Override
public String toString() {
return getPathString();
}
/**
* Compares two {@link PathUtil}s lexicographically on each path component.
*/
@Override
public int compareTo(PathUtil that) {
JsonArray<String> components1 = this.pathComponentsList;
JsonArray<String> components2 = that.pathComponentsList;
// First compare path components except the last one (file's name).
for (int i = 0; i + 1 < components1.size() && i + 1 < components2.size(); ++i) {
int result = components1.get(i).compareTo(components2.get(i));
if (result != 0) {
return result;
}
}
// Sub-folders go after the parent folder.
int lengthDiff = components1.size() - components2.size();
if (lengthDiff != 0) {
return lengthDiff;
}
int lastComponent = components1.size() - 1;
if (lastComponent < 0) {
return 0;
}
// Finally, compare the file names.
return components1.get(lastComponent).compareTo(components2.get(lastComponent));
}
/**
* @return file extension or {@code null} if file has no extension
*/
public String getFileExtension() {
return getFileExtension(getPathString());
}
/**
* Returns the file extension of a given file path.
*
* @param filePath the file path
* @return file extension or {@code null} if file has no extension
*/
public static String getFileExtension(String filePath) {
int lastSlashPos = filePath.lastIndexOf('/');
int lastDotPos = filePath.lastIndexOf('.');
// If (lastSlashPos > lastDotPos) then dot is somewhere in parent directory and file has
// no extension.
if (lastDotPos < 0 || lastSlashPos > lastDotPos) {
return null;
}
return filePath.substring(lastDotPos + 1);
}
/**
* Builder for {@link PathUtil}.
*/
public static class Builder {
private final JsonArray<String> pathComponentsList;
public Builder() {
pathComponentsList = JsonCollections.createArray();
}
public Builder addPathComponent(String component) {
pathComponentsList.add(component);
return this;
}
public Builder addPathComponents(JsonArray<String> components) {
pathComponentsList.addAll(components);
return this;
}
public Builder addPath(PathUtil path) {
pathComponentsList.addAll(path.pathComponentsList);
return this;
}
public PathUtil build() {
return new PathUtil(pathComponentsList);
}
}
}
| 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/util/ExceptionUtils.java | client/src/main/java/com/google/collide/client/util/ExceptionUtils.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.util;
/**
* Utility class for common Exception related operations.
*/
public class ExceptionUtils {
public static final int MAX_CAUSE = 10;
public static String getStackTraceAsString(Throwable e) {
return getThrowableAsString(e, "\n", "\t");
}
public static String getThrowableAsString(Throwable e, String newline, String indent) {
if (e == null) {
return "";
}
// For each cause, print the requested number of entries of its stack
// trace, being careful to avoid getting stuck in an infinite loop.
StringBuffer s = new StringBuffer(newline);
Throwable currentCause = e;
String causedBy = "";
int causeCounter = 0;
for (; causeCounter < MAX_CAUSE && currentCause != null; causeCounter++) {
s.append(causedBy);
causedBy = newline + "Caused by: "; // after 1st, all say "caused by"
s.append(currentCause.getClass().getName());
s.append(": ");
s.append(currentCause.getMessage());
StackTraceElement[] stackElems = currentCause.getStackTrace();
if (stackElems != null) {
for (int i = 0; i < stackElems.length; ++i) {
s.append(newline);
s.append(indent);
s.append("at ");
s.append(stackElems[i].toString());
}
}
currentCause = currentCause.getCause();
}
if (causeCounter >= MAX_CAUSE) {
s.append(newline);
s.append(newline);
s.append("Exceeded the maximum number of causes.");
}
return s.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/util/RelativeClientRect.java | client/src/main/java/com/google/collide/client/util/RelativeClientRect.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.util;
import elemental.html.ClientRect;
/**
* A {@link ClientRect} which is relative to a given point.
*/
public class RelativeClientRect implements ClientRect {
public static ClientRect relativeToRect(ClientRect relativeParent, ClientRect rect) {
return new RelativeClientRect(
(int) relativeParent.getLeft(), (int) relativeParent.getTop(), rect);
}
private final ClientRect rect;
private final int offsetLeft;
private final int offsetTop;
public RelativeClientRect(int offsetLeft, int offsetTop, ClientRect rect) {
this.offsetLeft = offsetLeft;
this.offsetTop = offsetTop;
this.rect = rect;
}
@Override
public float getBottom() {
return rect.getBottom() - offsetTop;
}
@Override
public float getHeight() {
return rect.getHeight();
}
@Override
public float getLeft() {
return rect.getLeft() - offsetLeft;
}
@Override
public float getRight() {
return rect.getRight() - offsetLeft;
}
@Override
public float getTop() {
return rect.getTop() - offsetTop;
}
@Override
public float getWidth() {
return rect.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/util/QueryCallbacks.java | client/src/main/java/com/google/collide/client/util/QueryCallbacks.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.util;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.common.base.Preconditions;
/**
* Class for common implementations of a {@link QueryCallback}.
*/
public class QueryCallbacks {
/**
* A callback used when no action will be taken on success or failure (most useful to ensure the
* cache is populated for speed).
*/
public static class NoOpCallback<E> implements QueryCallback<E> {
@Override
public void onFail(FailureReason reason) {}
@Override
public void onQuerySuccess(E result) {}
}
/**
* Generic class which logs an optional warning when a query failure occurs.
*/
public static abstract class SimpleCallback<E> implements QueryCallback<E> {
private final String failWarningMessage;
public SimpleCallback(String failWarningMessage) {
Preconditions.checkNotNull(failWarningMessage, "Warning message is required");
this.failWarningMessage = failWarningMessage;
}
@Override
public void onFail(FailureReason reason) {
if (!failWarningMessage.isEmpty()) {
Log.warn(getClass(), failWarningMessage);
}
}
}
/**
* A call which automatically delegates to another {@link QueryCallback} when a failure occurs.
*/
public static abstract class DelegateFailureCallback<REQ, RESP> implements QueryCallback<REQ> {
private final QueryCallback<RESP> callback;
public DelegateFailureCallback(QueryCallback<RESP> callback) {
this.callback = callback;
}
/** Dispatches a successful result */
protected void dispatch(RESP result) {
if (callback != null) {
callback.onQuerySuccess(result);
}
}
@Override
public void onFail(FailureReason reason) {
if (callback != null) {
callback.onFail(reason);
}
}
}
/**
* Similar to {@link SimpleCallback} but will funnel execution through the given {@link Executor}.
* Implements should override {@link ExecutorDelegatingCallback#onExecute(boolean, Object)}.
*/
public static abstract class ExecutorDelegatingCallback<E> extends SimpleCallback<E>
implements Runnable {
private final Executor executor;
private E result;
private boolean failed;
public ExecutorDelegatingCallback(Executor executor, String failWarningMessage) {
super(failWarningMessage);
this.executor = executor;
}
@Override
public void onQuerySuccess(E result) {
this.result = result;
failed = false;
executor.execute(this);
}
@Override
public void onFail(FailureReason reason) {
super.onFail(reason);
failed = true;
executor.execute(this);
}
@Override
public void run() {
onExecute(failed, result);
}
public abstract void onExecute(boolean failed, E result);
}
}
| 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/util/ClientImplementationsInjector.java | client/src/main/java/com/google/collide/client/util/ClientImplementationsInjector.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.util;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.client.Jso;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.client.JsoStringSet;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.SharedLogUtils;
import com.google.collide.shared.util.StringUtils;
import com.google.gwt.core.client.GWT;
/**
* Injects delegates for optimized client implementations.
*/
public final class ClientImplementationsInjector {
public static void inject() {
SharedLogUtils.setImplementation(new SharedLogUtils.Implementation() {
@Override
public void markTimeline(Class<?> clazz, String label) {
Log.markTimeline(clazz, label);
}
@Override
public void info(Class<?> clazz, Object... objects) {
Log.info(clazz, objects);
}
@Override
public void debug(Class<?> clazz, Object... objects) {
Log.debug(clazz, objects);
}
@Override
public void error(Class<?> clazz, Object... objects) {
Log.error(clazz, objects);
}
@Override
public void warn(Class<?> clazz, Object... objects) {
Log.warn(clazz, objects);
}
});
/**
* TODO(james) : replace this with server-safe deferred binding
*/
if (GWT.isScript()) {
JsonCollections.setImplementation(new JsonCollections.Implementation() {
@Override
public <T> JsonStringMap<T> createMap() {
return JsoStringMap.create();
}
@Override
public JsonStringSet createStringSet() {
return JsoStringSet.create();
}
@Override
public <T> JsonArray<T> createArray() {
return Jso.createArray().<JsoArray<T>>cast();
}
@Override
public <T> JsonIntegerMap<T> createIntegerMap() {
return JsIntegerMap.create();
}
});
/*
* Only use the faster native JS collections if running as compiled output
* (so, use JRE collections in dev mode)
*/
StringUtils.setImplementation(new StringUtils.Implementation() {
@Override
public JsonArray<String> split(String string, String separator) {
return ClientStringUtils.split(string, separator).<JsoArray<String>>cast();
}
});
}
}
private ClientImplementationsInjector() {
}
}
| 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/util/SignalEventUtils.java | client/src/main/java/com/google/collide/client/util/SignalEventUtils.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.util;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import org.waveprotocol.wave.client.common.util.SignalEventImpl;
import elemental.events.Event;
/**
* Utility methods for dealing with {@link SignalEvent}.
*
*/
public class SignalEventUtils {
public static SignalEvent create(Event rawEvent) {
return SignalEventImpl.create((com.google.gwt.user.client.Event) rawEvent, true);
}
public static SignalEvent create(Event rawEvent, boolean cancelBubbleIfNullified) {
return SignalEventImpl.create(
(com.google.gwt.user.client.Event) rawEvent, cancelBubbleIfNullified);
}
/**
* Returns the paste contents from a "paste" event, or null if it is not a
* paste event or cannot be retrieved.
*/
public static native String getPasteContents(Event event) /*-{
if (!event.clipboardData || !event.clipboardData.getData) {
return null;
}
return event.clipboardData.getData('text/plain');
}-*/;
}
| 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/util/JsIntegerMap.java | client/src/main/java/com/google/collide/client/util/JsIntegerMap.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.util;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayNumber;
/**
* Creates a lightweight map with integer keys based on a JavaScript object.
*
* @param <T> the type contained as value in the map
*/
public class JsIntegerMap<T> extends JavaScriptObject implements JsonIntegerMap<T> {
/**
* Create a new empty map.
*
* @param <T> the type of values to be stored in the map
* @return an empty map
*/
public static native <T> JsIntegerMap<T> create() /*-{
return {};
}-*/;
protected JsIntegerMap() {
}
/**
* Removes the mapping for this key from the map.
*
* @param key
*/
@Override
public final native void erase(int key) /*-{
delete this[key];
}-*/;
/**
* Returns the value associated with the specified key.
*
* @param key
* @return the value associated with the key
*/
@Override
public final native T get(int key) /*-{
return this[key];
}-*/;
/**
* Removes and returns the value associated with the specified key.
*/
public final T remove(int key) {
T value = get(key);
erase(key);
return value;
}
/**
* Returns an array containing all the values in this map.
*
* @return a snapshot of the values contained in the map
*/
public final native JsArrayNumber getKeys() /*-{
var data = [];
for (var prop in this) {
var val = Number(prop);
if (!isNaN(val)) {
data.push(val);
}
}
return data;
}-*/;
/**
* Returns an array containing all the values in this map.
*
* @return a snapshot of the values contained in the map
*/
public final native JsoArray<T> getValues() /*-{
var data = [];
for (var i in this) {
if (this.hasOwnProperty(i)) {
data.push(this[i]);
}
}
return data;
}-*/;
/**
* Returns true if this map has an entry for the specified key.
*
* @param key
* @return true if this map has an entry for the given key
*/
@Override
public final native boolean hasKey(int key) /*-{
return this.hasOwnProperty(key);
}-*/;
@Override
public final native void iterate(JsonIntegerMap.IterationCallback<T> cb) /*-{
for (var key in this) {
if (this.hasOwnProperty(key)) {
cb.
@com.google.collide.json.shared.JsonIntegerMap.IterationCallback::onIteration(ILjava/lang/Object;)
(parseInt(key),this[key]);
}
}
}-*/;
/**
* Associates the specified value with the specified key in this map.
*
* @param key key with which the value will be associated
* @param val value to be associated with key
*/
@Override
public final native void put(int key, T val) /*-{
this[key] = val;
}-*/;
@Override
public final native boolean isEmpty() /*-{
for (var i in this) {
if (this.hasOwnProperty(i)) {
return false;
}
}
return true;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/util/logging/Log.java | client/src/main/java/com/google/collide/client/util/logging/Log.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.util.logging;
import com.google.collide.client.util.ExceptionUtils;
import com.google.collide.client.util.logging.LogConfig.LogLevel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
/**
* Simple Logging class that logs to the browser's console and to the DevMode
* console (if you are in DevMode).
*
* So long as generating the parameters to pass to the logging methods is free
* of side effects, all Logging code should compile out of your application if
* logging is disabled.
*/
public class Log {
public static void debug(Class<?> clazz, Object... args) {
if (LogConfig.isLoggingEnabled()) {
// DEBUG is the lowest log level, but we use <= for consistency, and in
// case we ever decide to introduce a SPAM level.
if (LogConfig.getLogLevel().ordinal() <= LogLevel.DEBUG.ordinal()) {
log(clazz, LogLevel.DEBUG, args);
}
}
}
public static void error(Class<?> clazz, Object... args) {
if (LogConfig.isLoggingEnabled()) {
log(clazz, LogLevel.ERROR, args);
}
}
public static void info(Class<?> clazz, Object... args) {
if (LogConfig.isLoggingEnabled()) {
if (LogConfig.getLogLevel().ordinal() <= LogLevel.INFO.ordinal()) {
log(clazz, LogLevel.INFO, args);
}
}
}
public static boolean isLoggingEnabled() {
return LogConfig.isLoggingEnabled();
}
public static void warn(Class<?> clazz, Object... args) {
if (LogConfig.isLoggingEnabled()) {
if (LogConfig.getLogLevel().ordinal() <= LogLevel.WARNING.ordinal()) {
log(clazz, LogLevel.WARNING, args);
}
}
}
public static void markTimeline(Class<?> clazz, String label) {
if (LogConfig.isLoggingEnabled()) {
markTimelineUnconditionally(label + "(" + clazz.getName() + ")");
}
}
// TODO: markTimeLine is deprecated; remove it someday.
public static native void markTimelineUnconditionally(String label) /*-{
if ($wnd.console) {
if ($wnd.console.timeStamp) {
$wnd.console.timeStamp(label);
} else if ($wnd.console.markTimeline) {
$wnd.console.markTimeline(label);
}
}
}-*/;
private static native void invokeBrowserLogger(String logFuncName, Object o) /*-{
logFuncName = logFuncName || 'log';//fix for FF>17
if ($wnd.console && $wnd.console[logFuncName]) {
$wnd.console[logFuncName](o);
}
return;
}-*/;
private static void log(Class<?> clazz, LogLevel logLevel, Object... args) {
String prefix = new StringBuilder(logLevel.toString())
.append(" (")
.append(clazz.getName())
.append("): ")
.toString();
for (Object o : args) {
if (o instanceof String) {
logToDevMode(prefix + (String) o);
logToBrowser(logLevel, prefix + (String) o);
} else if (o instanceof Throwable) {
Throwable t = (Throwable) o;
logToDevMode(prefix + "(click for stack)", t);
logToBrowser(logLevel, prefix + ExceptionUtils.getStackTraceAsString(t));
} else if (o instanceof JavaScriptObject) {
logToDevMode(prefix + "(JSO, see browser's console log for details)");
logToBrowser(logLevel, prefix + "(JSO below)");
logToBrowser(logLevel, o);
} else {
logToDevMode(prefix + (o != null ? o.toString() : "(null)"));
logToBrowser(logLevel, prefix + (o != null ? o.toString() : "(null)"));
}
}
}
private static void logToBrowser(LogLevel logLevel, Object o) {
switch (logLevel) {
case DEBUG:
invokeBrowserLogger("debug", o);
break;
case INFO:
invokeBrowserLogger("info", o);
break;
case WARNING:
invokeBrowserLogger("warn", o);
break;
case ERROR:
invokeBrowserLogger("error", o);
break;
default:
invokeBrowserLogger("log", o);
}
}
private static void logToDevMode(String msg) {
if (!GWT.isScript()) {
GWT.log(msg);
}
}
private static void logToDevMode(String msg, Throwable t) {
if (!GWT.isScript()) {
GWT.log(msg, t);
}
}
}
| 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/util/logging/LogConfig.java | client/src/main/java/com/google/collide/client/util/logging/LogConfig.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.util.logging;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
/**
* Deferred bound class to determing statically whether or not logging is
* enabled.
*
* This is package protected all the way and only used internally by
* {@link Log}.
*
*/
abstract class LogConfig {
public static enum LogLevel {
DEBUG, INFO, WARNING, ERROR
}
/**
* Deferred binding for disabling logging.
*/
static class Disabled extends LogConfig {
@Override
public boolean isLoggingEnabledImpl() {
return false;
}
}
/**
* Deferred binding for enabling logging.
*/
static class Enabled extends LogConfig {
@Override
public boolean isLoggingEnabledImpl() {
return true;
}
}
private static final String LOG_LEVEL_PARAM = "logLevel";
private static final LogConfig INSTANCE = GWT.create(LogConfig.class);
static LogLevel getLogLevel() {
return INSTANCE.getLogLevelImpl();
}
static boolean isLoggingEnabled() {
return INSTANCE.isLoggingEnabledImpl();
}
static void setLogLevel(LogLevel level) {
INSTANCE.setLogLevelImpl(level);
}
private LogLevel currentLevel = null;
protected abstract boolean isLoggingEnabledImpl();
private void ensureLogLevel() {
if (currentLevel == null) {
// First inspect the URL to see if it has one set.
setLogLevel(maybeGetLevelFromUrl());
// If it is still not set, make the default be INFO.
setLogLevel((currentLevel == null) ? LogLevel.INFO : currentLevel);
}
}
private LogLevel getLogLevelImpl() {
ensureLogLevel();
return currentLevel;
}
private LogLevel maybeGetLevelFromUrl() {
String levelStr = Window.Location.getParameter(LOG_LEVEL_PARAM);
// The common case.
if (levelStr == null) {
return null;
}
levelStr = levelStr.toUpperCase();
try {
// Extract the correct Enum value;
return LogLevel.valueOf(levelStr);
} catch (IllegalArgumentException e) {
// We had a String but it was malformed.
return null;
}
}
private void setLogLevelImpl(LogLevel level) {
currentLevel = level;
}
}
| 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/util/input/CharCodeWithModifiers.java | client/src/main/java/com/google/collide/client/util/input/CharCodeWithModifiers.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.util.input;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import com.google.common.base.Preconditions;
// TODO: Add method that builds textual representation.
/**
* Bean that holds information describing the matching key-press.
*
* <p>NOTE: Do not include {@link ModifierKeys#SHIFT} for upper case characters
* (A,%,?), only for combinations like SHIFT+TAB.
*/
public class CharCodeWithModifiers {
private final int modifiers;
private final int charCode;
private final int digest;
public CharCodeWithModifiers(int modifiers, int charCode) {
Preconditions.checkArgument(
!KeyCodeMap.needsShift(charCode) || (modifiers & ModifierKeys.SHIFT) == 0,
"Do not include ModifierKeys.SHIFT for EventShortcuts where the "
+ "key pressed could be modified by pressing shift.");
this.modifiers = modifiers;
this.charCode = charCode;
this.digest = computeKeyDigest(modifiers, charCode);
}
public int getModifiers() {
return modifiers;
}
public int getCharCode() {
return charCode;
}
public int getKeyDigest() {
return digest;
}
public static int computeKeyDigest(int modifiers, int charCode) {
return (modifiers << 16) | (0xFFFF & charCode);
}
/**
* Returns an integer representing the combination of pressed modifier keys
* and the current text key.
*
* @see ModifierKeys#ACTION for details on the action key abstraction
*/
public static int computeKeyDigest(SignalEvent event) {
return computeKeyDigest(ModifierKeys.computeModifiers(event),
KeyCodeMap.getKeyFromEvent(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/util/input/KeyCodeMap.java | client/src/main/java/com/google/collide/client/util/input/KeyCodeMap.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.util.input;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType;
import org.waveprotocol.wave.client.common.util.UserAgent;
import elemental.events.KeyboardEvent.KeyCode;
import elemental.js.util.JsArrayOfInt;
/**
* Provides a consistent map from developer-defined strings and web browser
* event.keyCode values to an internal representation.
*
* The internal representation is to map key codes to 7-bit ascii where
* possible, and map non-ascii keys like page up to the Unicode Private Use Area
* U+E000...U+F8FF
*
* NOTE: a...z are returned as uppercase A...Z, and only unshifted versions of
* symbols are returned from the keyboard.
*
*/
public class KeyCodeMap {
/**
* Map from keyCode to upper case UTF-16
*/
private static final JsArrayOfInt lowerToUpper;
static {
lowerToUpper = JsArrayOfInt.create();
// special characters
lowerToUpper.set('1', '!');
lowerToUpper.set('2', '@');
lowerToUpper.set('3', '#');
lowerToUpper.set('4', '$');
lowerToUpper.set('5', '%');
lowerToUpper.set('6', '^');
lowerToUpper.set('7', '&');
lowerToUpper.set('8', '*');
lowerToUpper.set('9', '(');
lowerToUpper.set('0', ')');
lowerToUpper.set('`', '~');
lowerToUpper.set('-', '_');
lowerToUpper.set('=', '+');
lowerToUpper.set('[', '{');
lowerToUpper.set(']', '}');
lowerToUpper.set('\\', '|');
lowerToUpper.set(';', ':');
lowerToUpper.set('\'', '"');
lowerToUpper.set(',', '<');
lowerToUpper.set('.', '>');
lowerToUpper.set('/', '?');
}
/**
* Internal representation of non-ascii characters
*/
public static final int UNICODE_PRIVATE_START = 0xE000;
public static final int UNICODE_PRIVATE_END = 0xF8FF;
public static final int ARROW_UP = UNICODE_PRIVATE_START + 0;
public static final int ARROW_DOWN = UNICODE_PRIVATE_START + 1;
public static final int ARROW_LEFT = UNICODE_PRIVATE_START + 2;
public static final int ARROW_RIGHT = UNICODE_PRIVATE_START + 3;
public static final int INSERT = UNICODE_PRIVATE_START + 4;
public static final int DELETE = UNICODE_PRIVATE_START + 5;
public static final int HOME = UNICODE_PRIVATE_START + 6;
public static final int END = UNICODE_PRIVATE_START + 7;
public static final int PAGE_UP = UNICODE_PRIVATE_START + 8;
public static final int PAGE_DOWN = UNICODE_PRIVATE_START + 9;
public static final int MAC_META = UNICODE_PRIVATE_START + 10;
public static final int F1 = UNICODE_PRIVATE_START + 11;
public static final int F4 = F1 + 3;
public static final int F12 = F1 + 11;
/**
* Bind browser field events
*/
public static final int EVENT_COPY = UNICODE_PRIVATE_START + 100;
public static final int EVENT_CUT = UNICODE_PRIVATE_START + 101;
public static final int EVENT_PASTE = UNICODE_PRIVATE_START + 102;
/**
* These map to ascii, but aren't easily written in a string representation
*/
public static final int ENTER = 10;
public static final int TAB = 9;
public static final int ESC = 27;
public static final int BACKSPACE = 8;
/**
* Map from keyCode to ascii (for characters like :?><'[])
*/
private static final JsArrayOfInt keyCodeToAscii;
static {
keyCodeToAscii = JsArrayOfInt.create();
keyCodeToAscii.set(KeyCode.SEMICOLON, ';');
keyCodeToAscii.set(KeyCode.EQUALS, '=');
keyCodeToAscii.set(KeyCode.COMMA, ',');
keyCodeToAscii.set(KeyCode.DASH, '-');
keyCodeToAscii.set(KeyCode.PERIOD, '.');
keyCodeToAscii.set(KeyCode.SLASH, '/');
keyCodeToAscii.set(KeyCode.APOSTROPHE, '`');
keyCodeToAscii.set(KeyCode.OPEN_SQUARE_BRACKET, '[');
keyCodeToAscii.set(KeyCode.CLOSE_SQUARE_BRACKET, ']');
keyCodeToAscii.set(KeyCode.BACKSLASH, '\\');
keyCodeToAscii.set(KeyCode.SINGLE_QUOTE, '\'');
keyCodeToAscii.set(KeyCode.UP, ARROW_UP);
keyCodeToAscii.set(KeyCode.DOWN, ARROW_DOWN);
keyCodeToAscii.set(KeyCode.LEFT, ARROW_LEFT);
keyCodeToAscii.set(KeyCode.RIGHT, ARROW_RIGHT);
keyCodeToAscii.set(KeyCode.INSERT, INSERT);
keyCodeToAscii.set(KeyCode.DELETE, DELETE);
keyCodeToAscii.set(KeyCode.HOME, HOME);
keyCodeToAscii.set(KeyCode.END, END);
keyCodeToAscii.set(KeyCode.PAGE_UP, PAGE_UP);
keyCodeToAscii.set(KeyCode.PAGE_DOWN, PAGE_DOWN);
keyCodeToAscii.set(KeyCode.META, MAC_META); // left meta
keyCodeToAscii.set(KeyCode.META + 1, MAC_META); // right meta
keyCodeToAscii.set(KeyCode.CONTEXT_MENU, MAC_META);
}
private KeyCodeMap() {
}
/**
* Is this a letter/symbol that changes if the SHIFT key is pressed?
*/
public static boolean needsShift(int keycode) {
if ('A' <= keycode && keycode <= 'Z') {
// upper case letter
return true;
}
if (lowerToUpper.contains(keycode)) {
// special character !@#$%...
return true;
}
return false;
}
/**
* Map from event.keyCode to internal representation (ascii+special keys)
*
* NOTE(wetherbeei): SignalEvent tends to return correct ascii values from
* keyPress events where possible, then keyCodes when they aren't available
*/
public static int getKeyFromEvent(SignalEvent event) {
int ascii = event.getKeyCode();
if (ascii > 255) {
// out of handling range - all keycodes handled are under 256
return ascii;
}
KeySignalType type = event.getKeySignalType();
if (type != KeySignalType.INPUT) {
// convert these non-ascii characters to new unicode private area
if (KeyCode.F1 <= ascii && ascii <= KeyCode.F12) {
ascii = (ascii - KeyCode.F1) + F1;
}
if (keyCodeToAscii.isSet(ascii)) {
ascii = keyCodeToAscii.get(ascii);
}
}
// map enter \r (0x0D) to \n (0x0A)
if (ascii == 0x0D) {
ascii = 0x0A;
}
/*
* Platform/browser specific modifications
*
* Firefox captures combos using keyPress, which returns the correct case of
* the pressed key in ascii. Other browsers are captured on keyDown and only
* return the keyCode value (upper case or 0-9) of the pressed key
*
* TODO: test on other browsers.
*/
if (UserAgent.isFirefox() && event.getType().equals("keypress")) {
// this is a combo event, leave it alone in firefox
} else if (event.getType().equals("keydown")) {
// other browsers keydown combo captured, need to convert keyCode to ascii
// upper case letters to lower if no shift key
if (!event.getShiftKey()) {
if ('A' <= ascii && ascii <= 'Z') {
ascii = ascii - 'A' + 'a';
}
} else {
// shift key, check for additional symbol changes
if (lowerToUpper.isSet(ascii)) {
ascii = lowerToUpper.get(ascii);
}
}
}
// anything in other ranges will be passed through
return ascii;
}
/**
* Is this a printable ascii character? Includes control flow characters like
* newline (\n) and carriage return (\r).
*/
public static boolean isPrintable(int letter) {
if ((letter < 0x20 && letter != 0x0A && letter != 0x0D) || letter == 0x7F) {
// control characters less than 0x20, but not \n 0x0A, \r 0x0D
// or delete key 0x7F
return false; // not printable
}
if (UNICODE_PRIVATE_START <= letter && letter <= UNICODE_PRIVATE_END) {
// reserved internal range for events, not printable
return false;
}
// everything else is printable
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/util/input/ModifierKeys.java | client/src/main/java/com/google/collide/client/util/input/ModifierKeys.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.util.input;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import org.waveprotocol.wave.client.common.util.UserAgent;
import elemental.events.KeyboardEvent;
/**
* Modifier key constants, safe to be ORed together.
*
*/
public final class ModifierKeys {
public static final int NONE = 0;
/**
* This is an abstraction for the primary modifier used for chording shortcuts
* in Collide. To stay consistent with native OS shortcuts, this will be set
* if CTRL is pressed on Linux or Windows, or if CMD is pressed on Mac.
*/
public static final int ACTION = 1;
public static final int ALT = 1 << 1;
public static final int SHIFT = 1 << 2;
/**
* This will only be set on Mac. (On Windows and Linux, the
* {@link ModifierKeys#ACTION} will be set instead.)
*/
public static final int CTRL = 1 << 3;
private ModifierKeys() {
// Do nothing
}
/**
* Like {@link #computeExactModifiers(KeyboardEvent)} except computes the
* shift bit depending on {@link KeyCodeMap#needsShift(int)}.
*/
public static int computeModifiers(SignalEvent event) {
int modifiers =
computeModifiersExceptShift(event.getMetaKey(), event.getCtrlKey(), event.getAltKey());
// Only add shift if it isn't changing the charCode (lower to upper case).
int keyCode = KeyCodeMap.getKeyFromEvent(event);
if (event.getShiftKey() && !KeyCodeMap.needsShift(keyCode)) {
modifiers |= SHIFT;
}
return modifiers;
}
/**
* Returns an integer with the modifier bits set based on whether the modifier
* appears in the given event. Unlike {@link #computeModifiers(SignalEvent)},
* this does a literal translation of the shift key using
* {@link KeyboardEvent#isShiftKey()} instead of going through our custom
* {@link KeyCodeMap}.
*/
public static int computeExactModifiers(KeyboardEvent event) {
int modifiers =
computeModifiersExceptShift(event.isMetaKey(), event.isCtrlKey(), event.isAltKey());
if (event.isShiftKey()) {
modifiers |= SHIFT;
}
return modifiers;
}
private static int computeModifiersExceptShift(boolean hasMeta, boolean hasCtrl, boolean hasAlt) {
int modifiers = 0;
if (hasAlt) {
modifiers |= ALT;
}
if (UserAgent.isMac() && hasCtrl) {
modifiers |= CTRL;
}
if (hasAction(hasCtrl, hasMeta)) {
modifiers |= ACTION;
}
return modifiers;
}
private static boolean hasAction(boolean hasCtrl, boolean hasMeta) {
return UserAgent.isMac() ? hasMeta : hasCtrl;
}
}
| 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/util/dom/MouseGestureListener.java | client/src/main/java/com/google/collide/client/util/dom/MouseGestureListener.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.util.dom;
import com.google.collide.client.util.dom.eventcapture.MouseCaptureListener;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
import com.google.gwt.user.client.Timer;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.EventRemover;
import elemental.events.MouseEvent;
/**
* An {@link EventListener} implementation that parses the low-level events and
* produces high-level gestures, such as triple-click.
*
* This class differs subtly from the native {@link Event#CLICK} and
* {@link Event#DBLCLICK} events by dispatching the respective callback on mouse
* down instead of mouse up. This API difference allows clients to easily handle
* for example the double-click-and-drag case.
*/
public class MouseGestureListener {
/*
* TODO: When we have time, look into learning the native OS's
* delay by checking timing between CLICK and DBLCLICK events
*/
/**
* The maximum time in milliseconds between clicks to consider the latter
* click to be part of the same gesture as the previous click.
*/
public static final int MAX_CLICK_TIMEOUT_MS = 250;
public static Remover createAndAttach(Element element, Callback callback) {
MouseGestureListener instance = new MouseGestureListener(callback);
final EventRemover eventRemover = element.addEventListener(
Event.MOUSEDOWN, instance.captureListener, false);
return new Remover() {
@Override
public void remove() {
eventRemover.remove();
}
};
}
/**
* An interface that receives callbacks from the {@link MouseGestureListener}
* when gestures occur.
*/
public interface Callback {
/**
* @return false to abort any handling of subsequent mouse events in this
* gesture
*/
boolean onClick(int clickCount, MouseEvent event);
void onDrag(MouseEvent event);
void onDragRelease(MouseEvent event);
}
private final Callback callback;
private final MouseCaptureListener captureListener = new MouseCaptureListener() {
@Override
protected boolean onMouseDown(MouseEvent evt) {
return handleNativeMouseDown(evt);
}
@Override
protected void onMouseMove(MouseEvent evt) {
handleNativeMouseMove(evt);
}
@Override
protected void onMouseUp(MouseEvent evt) {
handleNativeMouseUp(evt);
}
};
private boolean hasDragInThisGesture;
private int numberOfClicks;
private final Timer resetClickStateTimer = new Timer() {
@Override
public void run() {
resetClickState();
}
};
private MouseGestureListener(Callback callback) {
this.callback = callback;
}
private boolean handleNativeMouseDown(MouseEvent event) {
numberOfClicks++;
if (!callback.onClick(numberOfClicks, event)) {
resetClickState();
return false;
}
/*
* If the user does not click again within this timeout, we will revert
* back to a clean state
*/
resetClickStateTimer.schedule(MAX_CLICK_TIMEOUT_MS);
return true;
}
private void handleNativeMouseMove(MouseEvent event) {
if (!hasDragInThisGesture) {
// Dragging the mouse resets the click state
resetClickState();
hasDragInThisGesture = true;
}
callback.onDrag(event);
}
private void handleNativeMouseUp(MouseEvent event) {
if (hasDragInThisGesture) {
callback.onDragRelease(event);
hasDragInThisGesture = false;
}
}
private void resetClickState() {
numberOfClicks = 0;
resetClickStateTimer.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/util/dom/DomUtils.java | client/src/main/java/com/google/collide/client/util/dom/DomUtils.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.util.dom;
import collide.client.util.BrowserUtils;
import collide.client.util.Elements;
import com.google.gwt.user.client.DOM;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.MouseEvent;
import elemental.html.ClientRect;
import elemental.html.DivElement;
/**
* Utility methods for DOM manipulation.
*
*/
public final class DomUtils {
public static class Offset {
public int top = 0;
public int left = 0;
private Offset() {
}
private Offset(int top, int left) {
this.top = top;
this.left = left;
}
}
private static final EventListener STOP_PROPAGATION_EVENT_LISTENER = new EventListener() {
@Override
public void handleEvent(Event evt) {
evt.stopPropagation();
evt.preventDefault();
}
};
/**
* Returns the client offset to the top-left of the given element.
*/
@Deprecated
public static Offset calculateElementClientOffset(Element element) {
return calculateElementOffset(element, null, false);
}
/**
* Returns an offset to the top-left of a child element relative to the
* top-left of an ancestor element, optionally including any scroll top or
* left in elements from the ancestor (inclusive) to the child (exclusive).
*
* @param ancestorElement optional, if null the offset from the top-left of
* the page will be given. Should not be the childElement.
*/
@Deprecated
public static Offset calculateElementOffset(
Element childElement, Element ancestorElement, boolean includeScroll) {
Offset offset = new Offset();
Element element = childElement;
for (; element.getOffsetParent() != null && element != ancestorElement; element =
element.getOffsetParent()) {
offset.top += element.getOffsetTop();
offset.left += element.getOffsetLeft();
if (!includeScroll) {
offset.top -= element.getOffsetParent().getScrollTop();
offset.left -= element.getOffsetParent().getScrollLeft();
}
}
return offset;
}
/**
* Wrapper for getting the offsetX from a mouse event that provides a fallback
* implementation for Firefox. (See
* https://bugzilla.mozilla.org/show_bug.cgi?id=122665#c3 )
*/
public static int getOffsetX(MouseEvent event) {
if (BrowserUtils.isFirefox()) {
return event.getClientX()
- calculateElementClientOffset((Element) event.getTarget()).left;
} else {
return event.getOffsetX();
}
}
/**
* @see #getOffsetX(MouseEvent)
*/
public static int getOffsetY(MouseEvent event) {
if (BrowserUtils.isFirefox()) {
return event.getClientY()
- calculateElementClientOffset((Element) event.getTarget()).top;
} else {
return event.getOffsetY();
}
}
public static Element getNthChild(Element element, int index) {
Element child = element.getFirstChildElement();
while (child != null && index > 0) {
--index;
child = child.getNextSiblingElement();
}
return child;
}
public static Element getNthChildWithClassName(Element element, int index, String className) {
Element child = element.getFirstChildElement();
while (child != null) {
if (child.hasClassName(className)) {
--index;
if (index < 0) {
break;
}
}
child = child.getNextSiblingElement();
}
return child;
}
/**
* @return number of previous sibling elements that have the given class
*/
public static int getSiblingIndexWithClassName(Element element, String className) {
int index = 0;
while (element != null) {
element = (Element) element.getPreviousSibling();
if (element != null && element.hasClassName(className)) {
++index;
}
}
return index;
}
public static Element getFirstElementByClassName(Element element, String className) {
return (Element) element.getElementsByClassName(className).item(0);
}
public static DivElement appendDivWithTextContent(Element root, String className, String text) {
DivElement element = Elements.createDivElement(className);
element.setTextContent(text);
root.appendChild(element);
return element;
}
/**
* Ensures that the {@code scrollable} element is scrolled such that
* {@code target} is visible.
*
* Note: This can trigger a synchronous layout.
*/
public static boolean ensureScrolledTo(Element scrollable, Element target) {
ClientRect targetBounds = target.getBoundingClientRect();
ClientRect scrollableBounds = scrollable.getBoundingClientRect();
int deltaBottoms = (int) (targetBounds.getBottom() - scrollableBounds.getBottom());
int deltaTops = (int) (targetBounds.getTop() - scrollableBounds.getTop());
if (deltaTops >= 0 && deltaBottoms <= 0) {
// In bounds
return false;
}
if (targetBounds.getHeight() > scrollableBounds.getHeight() || deltaTops < 0) {
/*
* Selected is taller than viewport height or selected is scrolled above
* viewport, so set to top
*/
scrollable.setScrollTop(scrollable.getScrollTop() + deltaTops);
} else {
// Selected is scrolled below viewport
scrollable.setScrollTop(scrollable.getScrollTop() + deltaBottoms);
}
return true;
}
/**
* Checks whether the given {@code target} element is fully visible in
* {@code scrollable}'s scrolled viewport.
*
* Note: This can trigger a synchronous layout.
*/
public static boolean isFullyInScrollViewport(Element scrollable, Element target) {
ClientRect targetBounds = target.getBoundingClientRect();
ClientRect scrollableBounds = scrollable.getBoundingClientRect();
return targetBounds.getTop() >= scrollableBounds.getTop()
&& targetBounds.getBottom() <= scrollableBounds.getBottom();
}
/**
* Stops propagation for the common mouse events (down, move, up, click,
* dblclick).
*/
public static void stopMousePropagation(Element element) {
element.addEventListener(Event.MOUSEDOWN, STOP_PROPAGATION_EVENT_LISTENER, false);
element.addEventListener(Event.MOUSEMOVE, STOP_PROPAGATION_EVENT_LISTENER, false);
element.addEventListener(Event.MOUSEUP, STOP_PROPAGATION_EVENT_LISTENER, false);
element.addEventListener(Event.CLICK, STOP_PROPAGATION_EVENT_LISTENER, false);
element.addEventListener(Event.DBLCLICK, STOP_PROPAGATION_EVENT_LISTENER, false);
}
/**
* Prevent propagation of scrolling to parent containers on mouse wheeling,
* when target container can not be scrolled anymore.
*/
public static void preventExcessiveScrollingPropagation(final Element container) {
container.addEventListener(Event.MOUSEWHEEL, new EventListener() {
@Override
public void handleEvent(Event evt) {
int deltaY = DOM.eventGetMouseWheelVelocityY((com.google.gwt.user.client.Event) evt);
int scrollTop = container.getScrollTop();
if (deltaY < 0) {
if (scrollTop == 0) {
evt.preventDefault();
}
} else {
int scrollBottom = scrollTop + (int) container.getBoundingClientRect().getHeight();
if (scrollBottom == container.getScrollHeight()) {
evt.preventDefault();
}
}
evt.stopPropagation();
}
}, false);
}
/**
* Doing Elements.asJsElement(button).setDisabled(true); doesn't work for buttons, possibly
* because they're actually AnchorElements
*/
public static void setDisabled(Element element, boolean disabled) {
if (disabled) {
element.setAttribute("disabled", "disabled");
} else {
element.removeAttribute("disabled");
}
}
public static boolean getDisabled(Element element) {
return element.hasAttribute("disabled");
}
/**
* @return true if the provided element or one of its children have focus.
*/
public static boolean isElementOrChildFocused(Element element) {
Element active = element.getOwnerDocument().getActiveElement();
return element.contains(active);
}
private DomUtils() {} // COV_NF_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/util/dom/MouseMovePauseDetector.java | client/src/main/java/com/google/collide/client/util/dom/MouseMovePauseDetector.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.util.dom;
import elemental.events.MouseEvent;
import elemental.util.Timer;
/**
* A helper that detects mouse movement pause.
* <p>
* When mouse movement pause is detected, {@link Callback#onMouseMovePaused()}
* is invoked once. Even if mouse stays still for a long time,
* {@link Callback#onMouseMovePaused()} is only invoked once. Only after mouse
* starts to move again, the detector resumes.
*/
public final class MouseMovePauseDetector {
/**
* An interface that receives callback from the {@link MouseMovePauseDetector}
* when mouse move pause occur.
*/
public interface Callback {
void onMouseMovePaused();
}
private final Callback callback;
private final Timer getRevisionWhenDragTimer;
/**
* If mouse did not move after DEFAULT_PAUSE_DURATION_MS, we consider move
* paused.
*/
private static final int DEFAULT_PAUSE_DURATION_MS = 500;
private static final int MOUSE_INVALID_POSITION = Integer.MIN_VALUE;
private static final int MOUSE_MOVEMENT_THRESHOLD_SQUARED = 900;
// (lastMouseX, lastMouseY) is the last mouse location.
// It gets reset if mouse movement is over the threshold.
private int lastMouseX = MOUSE_INVALID_POSITION;
private int lastMouseY = MOUSE_INVALID_POSITION;
private boolean enabled;
public MouseMovePauseDetector(Callback callback) {
this.callback = callback;
getRevisionWhenDragTimer = new Timer() {
@Override
public void run() {
mousePaused();
}
};
}
public void start() {
enabled = true;
lastMouseX = lastMouseY = MOUSE_INVALID_POSITION;
}
public void stop() {
enabled = false;
getRevisionWhenDragTimer.cancel();
}
public void handleMouseMove(MouseEvent event) {
if (!enabled) {
return;
}
if (lastMouseX == MOUSE_INVALID_POSITION
|| isMoved(event.getClientX(), event.getClientY(), lastMouseX, lastMouseY)) {
// Cancel current timer and start timeout.
// Whenever the timer timeouts, mouse has paused long enough.
getRevisionWhenDragTimer.cancel();
getRevisionWhenDragTimer.schedule(DEFAULT_PAUSE_DURATION_MS);
lastMouseX = event.getClientX();
lastMouseY = event.getClientY();
}
}
private void mousePaused() {
if (!enabled) {
return;
}
callback.onMouseMovePaused();
}
private boolean isMoved(int x1, int y1, int x2, int y2) {
int deltaX = x1 - x2;
int deltaY = y1 - y2;
return deltaX * deltaX + deltaY * deltaY > MOUSE_MOVEMENT_THRESHOLD_SQUARED;
}
}
| 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/util/dom/ScrollbarSizeCalculator.java | client/src/main/java/com/google/collide/client/util/dom/ScrollbarSizeCalculator.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.util.dom;
import collide.client.util.Elements;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
/**
* A class that computes and caches the width of a vertical scrollbar and height
* of a horizontal scrollbar.
*/
public class ScrollbarSizeCalculator {
public static final ScrollbarSizeCalculator INSTANCE = new ScrollbarSizeCalculator();
private int heightOfHorizontalScrollbar = -1;
private int widthOfVerticalScrollbar = -1;
/**
* Calculates (or recalculates) the sizes of the scrollbars.
*/
public void calculateSize() {
Element container = createContainer();
// No scrollbars
container.getStyle().setOverflow(CSSStyleDeclaration.Overflow.HIDDEN);
int noScrollbarClientHeight = container.getClientHeight();
int noScrollbarClientWidth = container.getClientWidth();
// Force scrollbars
container.getStyle().setOverflow(CSSStyleDeclaration.Overflow.SCROLL);
heightOfHorizontalScrollbar = noScrollbarClientHeight - container.getClientHeight();
widthOfVerticalScrollbar = noScrollbarClientWidth - container.getClientWidth();
container.removeFromParent();
}
private Element createContainer() {
Element container = Elements.createDivElement();
final int containerSize = 500;
CSSStyleDeclaration containerStyle = container.getStyle();
containerStyle.setWidth(containerSize, CSSStyleDeclaration.Unit.PX);
containerStyle.setHeight(containerSize, CSSStyleDeclaration.Unit.PX);
containerStyle.setPosition(CSSStyleDeclaration.Position.ABSOLUTE);
containerStyle.setLeft(-containerSize, CSSStyleDeclaration.Unit.PX);
containerStyle.setTop(-containerSize, CSSStyleDeclaration.Unit.PX);
Elements.getBody().appendChild(container);
return container;
}
/**
* Gets the height of a horizontal scrollbar. This will calculate the size if
* it has not already been calculated.
*/
public int getHeightOfHorizontalScrollbar() {
ensureSizeCalculated();
return heightOfHorizontalScrollbar;
}
/**
* Gets the width of a vertical scrollbar. This will calculate the size if it
* has not already been calculated.
*/
public int getWidthOfVerticalScrollbar() {
ensureSizeCalculated();
return widthOfVerticalScrollbar;
}
private void ensureSizeCalculated() {
if (heightOfHorizontalScrollbar < 0 || widthOfVerticalScrollbar < 0) {
calculateSize();
}
}
}
| 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/util/dom/FontDimensionsCalculator.java | client/src/main/java/com/google/collide/client/util/dom/FontDimensionsCalculator.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.util.dom;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import elemental.css.CSSStyleDeclaration;
import elemental.css.CSSStyleDeclaration.Unit;
import elemental.dom.Element;
/**
* A class that computes the height and width of a character.
*/
public class FontDimensionsCalculator {
public interface FontDimensions {
float getBaseWidth();
float getBaseHeight();
float getWidthZoomFactor();
float getHeightZoomFactor();
float getCharacterWidth();
float getCharacterHeight();
}
private class FontDimensionsImpl implements FontDimensions {
private float baseWidth;
private float baseHeight;
private float widthFactor = 1;
private float heightFactor = 1;
/**
* Updates the width and height internally. If this has never been set
* before this will set the baseWidth and baseHeight. Otherwise it will
* adjust the zoom factor and the current character width and height.
*
* @return false if no update was required.
*/
private boolean update(float width, float height) {
if (baseWidth == 0 && baseHeight == 0) {
baseWidth = width;
baseHeight = height;
return true;
} else if (baseWidth * widthFactor != width || baseHeight * heightFactor != height) {
widthFactor = width / baseWidth;
heightFactor = height / baseHeight;
return true;
}
return false;
}
@Override
public float getBaseWidth() {
return baseWidth;
}
@Override
public float getBaseHeight() {
return baseHeight;
}
@Override
public float getWidthZoomFactor() {
return widthFactor;
}
@Override
public float getHeightZoomFactor() {
return heightFactor;
}
@Override
public float getCharacterWidth() {
return widthFactor * baseWidth;
}
@Override
public float getCharacterHeight() {
return heightFactor * baseHeight;
}
}
private static final int POLLING_CUTOFF = 10000;
private static final String SAMPLE_TEXT = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
private static final int SAMPLE_ROWS = 30;
public interface Callback {
void onFontDimensionsChanged(FontDimensions fontDimensions);
}
private static FontDimensionsCalculator INSTANCE;
public static FontDimensionsCalculator get(String fontClassName) {
if (INSTANCE == null) {
INSTANCE = new FontDimensionsCalculator(fontClassName);
}
return INSTANCE;
}
private final Element dummyElement;
/*
* This timer is called during the first 12s. When using a web font it will be
* loaded asynchronously and our initial measurements will be incorrect. By
* polling we remeasure after this font has been loaded and updated our size.
*/
private final Timer repeater = new Timer() {
@Override
public void run() {
if (pollingDelay >= POLLING_CUTOFF) {
// Terminate polling rescheduling once we cross the cutoff.
return;
}
measureAndDispatch();
schedule(pollingDelay);
pollingDelay *= 2;
}
};
private int pollingDelay = 500;
private JsonArray<Callback> callbacks = JsonCollections.createArray();
private final FontDimensionsImpl fontDimensions;
private final String fontClassName;
private FontDimensionsCalculator(String fontClassName) {
this.fontClassName = fontClassName;
// This handler will be called when the browser window zooms
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent arg0) {
measureAndDispatch();
}
});
// Build a multirow text block so we can measure it
StringBuilder htmlContent = new StringBuilder(SAMPLE_TEXT);
for (int i = 1; i < SAMPLE_ROWS; i++) {
htmlContent.append("<br/>");
htmlContent.append(SAMPLE_TEXT);
}
dummyElement = Elements.createSpanElement(fontClassName);
dummyElement.setInnerHTML(htmlContent.toString());
dummyElement.getStyle().setVisibility(CSSStyleDeclaration.Visibility.HIDDEN);
dummyElement.getStyle().setPosition(CSSStyleDeclaration.Position.ABSOLUTE);
dummyElement.getStyle().setLeft(0, Unit.PX);
dummyElement.getStyle().setTop(0, Unit.PX);
Elements.getBody().appendChild(dummyElement);
fontDimensions = new FontDimensionsImpl();
repeater.schedule(pollingDelay);
/*
* Force an initial measure (the dispatch won't happen since no one is
* attached)
*/
measureAndDispatch();
}
public void addCallback(final Callback callback) {
callbacks.add(callback);
}
public void removeCallback(final Callback callback) {
callbacks.remove(callback);
}
/**
* Returns a font dimensions that will be updated as the font dimensions
* change.
*/
public FontDimensions getFontDimensions() {
return fontDimensions;
}
public String getFontClassName() {
return fontClassName;
}
public String getFont() {
return CssUtils.getComputedStyle(dummyElement).getPropertyValue("font");
}
private void measureAndDispatch() {
float curWidth = dummyElement.getOffsetWidth() / ((float) SAMPLE_TEXT.length());
float curHeight = dummyElement.getOffsetHeight() / ((float) SAMPLE_ROWS);
if (fontDimensions.update(curWidth, curHeight)) {
dispatchToCallbacks();
}
}
private void dispatchToCallbacks() {
for (int i = 0, n = callbacks.size(); i < n; i++) {
callbacks.get(i).onFontDimensionsChanged(fontDimensions);
}
}
}
| 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/util/dom/eventcapture/MouseCaptureListener.java | client/src/main/java/com/google/collide/client/util/dom/eventcapture/MouseCaptureListener.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.util.dom.eventcapture;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.MouseEvent;
/**
* Listener that can be used for event capture. Simply add this as a
* {@link Event#MOUSEDOWN} listener and then you will get mouse capture for
* moves and mouse up for that element.
*/
public abstract class MouseCaptureListener implements EventListener {
private int prevClientX;
private int prevClientY;
private int deltaX;
private int deltaY;
private CaptureReleaser releaser;
public int getDeltaX() {
return deltaX;
}
public int getDeltaY() {
return deltaY;
}
@Override
public void handleEvent(Event evt) {
MouseEvent mouseEvent = (MouseEvent) evt;
updateXYState(mouseEvent);
if (evt.getType().equals(Event.MOUSEMOVE)) {
onMouseMove(mouseEvent);
} else if (evt.getType().equals(Event.MOUSEUP)) {
release();
onMouseUp(mouseEvent);
} else if (evt.getType().equals(Event.MOUSEDOWN)) {
if (onMouseDown(mouseEvent)) {
// Start the capture
MouseEventCapture.capture(this);
mouseEvent.preventDefault();
}
}
}
public void release() {
if (releaser != null) {
releaser.release();
}
}
/**
* Called when the mousedown event is received.
*
* @return true if the capture should be initiated for mousemove and mouseup
* events.
*/
protected boolean onMouseDown(MouseEvent evt) {
return true;
}
protected void onMouseMove(MouseEvent evt) {
}
protected void onMouseUp(MouseEvent evt) {
}
void setCaptureReleaser(CaptureReleaser releaser) {
this.releaser = releaser;
}
private void updateXYState(MouseEvent evt) {
int x = evt.getClientX();
int y = evt.getClientY();
if (evt.getType().equals(Event.MOUSEDOWN)) {
deltaX = deltaY = 0;
} else {
deltaX = x - prevClientX;
deltaY = y - prevClientY;
}
prevClientX = x;
prevClientY = y;
}
}
| 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/util/dom/eventcapture/GlobalHotKey.java | client/src/main/java/com/google/collide/client/util/dom/eventcapture/GlobalHotKey.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.util.dom.eventcapture;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import collide.client.util.Elements;
import com.google.collide.client.util.JsIntegerMap;
import com.google.collide.client.util.SignalEventUtils;
import com.google.collide.client.util.input.CharCodeWithModifiers;
import com.google.common.base.Preconditions;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
/**
* Provides a mean for registering global hot key bindings, particularly
* spring-loaded hot keys.
*
* <p>All hot keys depend on CTRL being pressed, while other modifiers are not,
* so as not to interfere with regular typing.
*/
public class GlobalHotKey {
/**
* Container for one entry in the HotKey database.
*/
public static class Data {
private final String description;
private final Handler handler;
private final CharCodeWithModifiers key;
private Data(CharCodeWithModifiers key, Handler handler, String description) {
this.key = key;
this.handler = handler;
this.description = description;
}
public String getDescription() {
return description;
}
public Handler getHandler() {
return handler;
}
public CharCodeWithModifiers getKey() {
return key;
}
}
/**
* A handler interface to receive event callbacks.
*/
public interface Handler {
/**
* Called when a hot key is initially pressed.
*
* @param event the underlying event
*/
void onKeyDown(SignalEvent event);
}
private static int handlerCount = 0;
private static JsIntegerMap<Data> handlers;
// Human readable descriptions for key codes.
private static CaptureReleaser remover;
/**
* Registers a handler to receive notification when the key corresponding to
* {@code keyCode} is used.
*
* <p>Only one handler can be tied to a particular key code. Attempting to
* register a previously registered code will result in an assertion being
* raised.
*
* @param key the key code with modifiers
* @param handler a callback handler
* @param description short human readable description for the action.
*/
public static void register(CharCodeWithModifiers key, Handler handler, String description) {
if (handlers == null) {
remover = addEventListeners();
handlers = JsIntegerMap.create();
}
Data handle = new Data(key, handler, description);
int keyDigest = key.getKeyDigest();
Preconditions.checkState(
handlers.get(keyDigest) == null, "Only one handler can be registered per a key");
handlers.put(keyDigest, handle);
++handlerCount;
}
/**
* Unregisters a previously registered handler for a particular keyCode.
*/
public static void unregister(CharCodeWithModifiers key) {
int keyDigest = key.getKeyDigest();
Preconditions.checkState(
handlers.get(keyDigest) != null, "No handler is register for this key");
handlers.erase(keyDigest);
if (--handlerCount == 0) {
remover.release();
remover = null;
handlers = null;
}
}
private static CaptureReleaser addEventListeners() {
final EventListener downListener = new EventListener() {
@Override
public void handleEvent(Event event) {
SignalEvent signalEvent = SignalEventUtils.create(event, false);
if (signalEvent == null) {
return;
}
int keyDigest = CharCodeWithModifiers.computeKeyDigest(signalEvent);
final Data data = handlers.get(keyDigest);
if (data == null) {
return;
}
Handler handler = data.getHandler();
handler.onKeyDown(signalEvent);
event.preventDefault();
}
};
// Attach the listeners.
final Element documentElement = Elements.getDocument().getDocumentElement();
documentElement.addEventListener(Event.KEYDOWN, downListener, true);
final CaptureReleaser downRemover = new CaptureReleaser() {
@Override
public void release() {
documentElement.removeEventListener(Event.KEYDOWN, downListener, true);
}
};
return new CaptureReleaser() {
@Override
public void release() {
downRemover.release();
}
};
}
/**
* This class is automatically instantiated as a singleton through the
* {@link #register} method.
*/
private GlobalHotKey() {
// Do nothing
}
}
| 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/util/dom/eventcapture/KeyBindings.java | client/src/main/java/com/google/collide/client/util/dom/eventcapture/KeyBindings.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.util.dom.eventcapture;
import com.google.collide.client.util.input.CharCodeWithModifiers;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.json.client.JsoStringMap;
/**
* Standard key bindings for Collide.
*/
public class KeyBindings {
private static final String LOCAL_REPLACE = "local_replace";
private static final String LOCAL_FIND = "local_find";
private static final String GOTO = "goto";
private static final String SNAPSHOT = "snapshot";
private JsoStringMap<CharCodeWithModifiers> map = JsoStringMap.create();
public KeyBindings() {
map.put(LOCAL_FIND, new CharCodeWithModifiers(ModifierKeys.ACTION, 'f'));
map.put(LOCAL_REPLACE, new CharCodeWithModifiers(ModifierKeys.ACTION, 'F'));
map.put(GOTO, new CharCodeWithModifiers(ModifierKeys.ACTION, 'g'));
map.put(SNAPSHOT, new CharCodeWithModifiers(ModifierKeys.ACTION, 's'));
// TODO: Add custom key bindings.
}
/**
* @return key for local find
*/
public CharCodeWithModifiers localFind() {
return map.get(LOCAL_FIND);
}
/**
* @return key for local replace
*/
public CharCodeWithModifiers localReplace() {
return map.get(LOCAL_REPLACE);
}
/**
* @return keycode for goto line/etc.
*/
public CharCodeWithModifiers gotoLine() {
return map.get(GOTO);
}
/**
* @return keycode for making a snapshot.
*/
public CharCodeWithModifiers snapshot() {
return map.get(SNAPSHOT);
}
}
| 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/util/dom/eventcapture/CaptureReleaser.java | client/src/main/java/com/google/collide/client/util/dom/eventcapture/CaptureReleaser.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.util.dom.eventcapture;
/**
* Interface defining a handle to an object for releasing Capture.
*/
interface CaptureReleaser {
void release();
} | 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/util/dom/eventcapture/MouseEventCapture.java | client/src/main/java/com/google/collide/client/util/dom/eventcapture/MouseEventCapture.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.util.dom.eventcapture;
import com.google.collide.json.client.JsoArray;
import elemental.client.Browser;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.EventTarget;
/**
* Utility class which allows simulation of Event Capture.
*
*/
public class MouseEventCapture {
private interface Remover {
public void remove();
}
/**
* Current mouse capture owner.
*/
private static MouseCaptureListener captureOwner;
/**
* These are the Remover objects for the hooks into Window that fire to this
* class. We have exactly one listener per event type that supports capture.
* When no UI component possesses capture (meaning that the captureOwner stack
* is empty) we can disconnect these.
*/
private static final JsoArray<Remover> mouseRemovers = JsoArray.create();
/**
* Capture happens on a per listener instance basis. We throw the
* CaptureListener on the top of the capture stack and then provide a handle
* to an object that can be used to
*
* @param listener
*/
public static void capture(final MouseCaptureListener listener) {
// Make sure to release the previous capture owner.
if (captureOwner != null) {
captureOwner.release();
}
// Lazily initialize event hookups (this should be below the release above
// since the above in turn clears the capture hookups)
if (mouseRemovers.isEmpty()) {
registerEventCaptureHookups();
}
captureOwner = listener;
listener.setCaptureReleaser(new CaptureReleaser() {
@Override
public void release() {
// nuke the reference to this releaser in the listener (which should
// still be the capture owner).
listener.setCaptureReleaser(null);
// nuke the captureOwner
captureOwner = null;
// Release the event listeners.
for (int i = 0, n = mouseRemovers.size(); i < n; i++) {
mouseRemovers.get(i).remove();
}
mouseRemovers.clear();
}
});
}
private static Remover addCaptureEventListener(final String type, final EventTarget source,
final EventListener listener) {
source.addEventListener(type, listener, true);
return new Remover() {
@Override
public void remove() {
source.removeEventListener(type, listener, true);
}
};
}
private static void forwardToCaptureOwner(Event event) {
if (captureOwner != null) {
captureOwner.handleEvent(event);
}
}
/**
* Registers for relevant events on the Window.
*
* Capture should be lazily initialized, and then destroyed each time nothing
* has capture (as to not cause useless event dispatch and handling for events
* like move events).
*/
private static void registerEventCaptureHookups() {
mouseRemovers.add(addCaptureEventListener(Event.MOUSEMOVE, Browser.getWindow(),
new EventListener() {
@Override
public void handleEvent(Event event) {
forwardToCaptureOwner(event);
}
}));
mouseRemovers.add(addCaptureEventListener(Event.MOUSEUP, Browser.getWindow(),
new EventListener() {
@Override
public void handleEvent(Event event) {
forwardToCaptureOwner(event);
}
}));
mouseRemovers.add(addCaptureEventListener(Event.BLUR, Browser.getWindow(),
new EventListener() {
@Override
public void handleEvent(Event event) {
captureOwner.release();
}
}));
}
}
| 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/util/collections/SimpleStringBag.java | client/src/main/java/com/google/collide/client/util/collections/SimpleStringBag.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.util.collections;
import javax.annotation.Nonnull;
import com.google.collide.json.shared.JsonArray;
import com.google.common.base.Preconditions;
/**
* Simple string multiset implementation on the base of {@link ClientStringMap}.
*
*/
public class SimpleStringBag implements StringMultiset {
private ClientStringMap<Counter> delegate;
public SimpleStringBag() {
clear();
}
@Override
public void addAll(@Nonnull JsonArray<String> items) {
// TODO: Check if iterate is faster.
for (int i = 0, l = items.size(); i < l; i++) {
add(items.get(i));
}
}
@Override
public void add(@Nonnull String item) {
Counter counter = delegate.get(item);
if (counter == null) {
counter = new Counter();
delegate.put(item, counter);
} else {
counter.increment();
}
}
@Override
public void removeAll(@Nonnull JsonArray<String> items) {
// TODO: Check if iterate is faster.
for (int i = 0, l = items.size(); i < l; i++) {
remove(items.get(i));
}
}
@Override
public void remove(@Nonnull String id) {
Counter counter = delegate.get(id);
// TODO: Remove this precondition.
Preconditions.checkNotNull(counter, "trying to remove item that is not in collection: %s", id);
if (counter.decrement()) {
delegate.remove(id);
}
}
@Override
public boolean contains(@Nonnull String item) {
return delegate.containsKey(item);
}
@Override
public void clear() {
delegate = ClientStringMap.create();
}
}
| 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/util/collections/ResumableTreeTraverser.java | client/src/main/java/com/google/collide/client/util/collections/ResumableTreeTraverser.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.util.collections;
import java.util.Iterator;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/*
* This class uses iterators since they inherently save traversal state and
* allow for removing the current item. (Less for work for this class to do.)
*/
/**
* A helper to visit a tree of objects with features like pause/resume.
*
*/
public class ResumableTreeTraverser<E> {
/**
* Listener that is notified when the traversal finishes.
*/
public interface FinishedCallback {
void onTraversalFinished();
}
/**
* Provider for the nodes in the tree.
*/
public interface NodeProvider<E> {
/**
* Returns an iterator for the children of {@code node}, or null if
* {@code node} doesn't have children.
*/
Iterator<E> getChildrenIterator(E node);
}
/**
* A visitor that is called for each node traversed in the tree.
*/
public interface Visitor<E> {
void visit(E item, VisitorApi visitorApi);
}
/**
* An object that encapsulates various API available to a
* {@link ResumableTreeTraverser.Visitor}.
*/
public static class VisitorApi {
private ResumableTreeTraverser<?> treeTraverser;
private boolean wasRemovedCalled;
private VisitorApi(ResumableTreeTraverser<?> treeTraverser) {
this.treeTraverser = treeTraverser;
}
/**
* Pauses the tree traversal.
*/
public void pause() {
treeTraverser.pause();
}
/**
* Resumes a paused tree traversal.
*/
public void resume() {
treeTraverser.resume();
}
/**
* Removes the node currently being visited.
*/
public void remove() {
if (!wasRemovedCalled) {
treeTraverser.currentNodeIterator.remove();
wasRemovedCalled = true;
}
}
private boolean resetRemoveState() {
boolean previousWasRemovedCalled = wasRemovedCalled;
wasRemovedCalled = false;
return previousWasRemovedCalled;
}
}
/**
* If paused during a dispatch, this will be the dispatch state so we can
* resume exactly where we left off.
*/
private static class DispatchPauseState<E> {
Iterator<? extends Visitor<E>> dispatchIterator;
E dispatchNode;
DispatchPauseState(Iterator<? extends Visitor<E>> visitorIterator, E dispatchNode) {
this.dispatchIterator = visitorIterator;
this.dispatchNode = dispatchNode;
}
}
private final NodeProvider<E> adapter;
private final FinishedCallback finishedCallback;
private final VisitorApi visitorApi;
private final Iterable<? extends Visitor<E>> visitorIterable;
private boolean isPaused;
private DispatchPauseState<E> dispatchPauseState;
private JsonArray<Iterator<E>> nodeIteratorStack = JsonCollections.createArray();
private Iterator<E> currentNodeIterator;
private boolean isDispatching;
public ResumableTreeTraverser(NodeProvider<E> adapter, Iterator<E> nodes,
JsonArray<? extends Visitor<E>> visitors, FinishedCallback finishedCallback) {
this.adapter = adapter;
this.finishedCallback = finishedCallback;
this.visitorIterable = visitors.asIterable();
this.visitorApi = new VisitorApi(this);
nodeIteratorStack.add(nodes);
isPaused = true;
}
@VisibleForTesting
boolean hasMore() {
return nodeIteratorStack.size() > 0;
}
/**
* Initially starts the traversal or resumes a previously paused traversal. If this is called from
* a {@link Visitor#visit(Object, VisitorApi)} dispatch, then the traversal will be resumed after
* that visit method returns. If this is not called from a visit dispatch, then the traversal will
* be resumed immediately synchronously.
*/
public void resume() {
Preconditions.checkArgument(isPaused);
isPaused = false;
if (!isDispatching) {
resumeTraversal();
}
}
private void resumeTraversal() {
if (nodeIteratorStack.size() == 0) {
// Nothing to do, exit early
return;
}
while (!isPaused && (nodeIteratorStack.size() > 0 || dispatchPauseState != null)) {
currentNodeIterator = nodeIteratorStack.isEmpty() ? null : nodeIteratorStack.peek();
while (!isPaused && ((currentNodeIterator != null && currentNodeIterator.hasNext())
|| dispatchPauseState != null)) {
E node;
Iterator<? extends Visitor<E>> visitorIterator;
if (dispatchPauseState == null) {
node = currentNodeIterator.next();
visitorIterator = visitorIterable.iterator();
} else {
node = dispatchPauseState.dispatchNode;
visitorIterator = dispatchPauseState.dispatchIterator;
dispatchPauseState = null;
}
dispatchToVisitors(visitorIterator, node, visitorApi);
/*
* A visitor could have paused at this point, if you're doing real work
* below, make sure to have a !isPaused check
*/
if (!isPaused) {
boolean wasNodeRemoved = visitorApi.resetRemoveState();
if (!wasNodeRemoved) {
Iterator<E> childrenIterator = adapter.getChildrenIterator(node);
if (childrenIterator != null) {
nodeIteratorStack.add(childrenIterator);
currentNodeIterator = childrenIterator;
}
}
}
}
if (!isPaused) {
if (!nodeIteratorStack.isEmpty()) {
nodeIteratorStack.pop();
if (nodeIteratorStack.size() == 0 && finishedCallback != null) {
finishedCallback.onTraversalFinished();
}
}
}
}
}
public void pause() {
Preconditions.checkArgument(!isPaused);
isPaused = true;
}
private void dispatchToVisitors(Iterator<? extends Visitor<E>> visitorIterator, E node,
VisitorApi visitorApi) {
// !wasRemovedCalled will prevent subsequent visitors from being called
while (!isPaused && visitorIterator.hasNext() && !visitorApi.wasRemovedCalled) {
isDispatching = true;
try {
visitorIterator.next().visit(node, visitorApi);
} finally {
isDispatching = false;
}
}
if (isPaused) {
// The visitor paused
dispatchPauseState = new DispatchPauseState<E>(visitorIterator, node);
}
}
}
| 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/util/collections/SkipListStringBag.java | client/src/main/java/com/google/collide/client/util/collections/SkipListStringBag.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.util.collections;
import javax.annotation.Nonnull;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.common.base.Preconditions;
/**
* Implementation of sorted multiset of strings based
* on {@link SkipListStringSet}.
*
* <p>This collection allows storing Strings so that <ul>
* <li>adding / removing item is performed in {@code O(1)} if there is no equal
* item in collection, otherwise {@code O(lg N)}
* <li>searching item is performed in {@code O(lg N)}
* <li>search finds earliest (in sorting order) item greater or equal to given
* <li>fetching next item is performed in {@code O(1)}
* <li>every unique item appears only once when iterating
* <li>iterator returns items in the sorted order
* </ul>
*
* <p>Actually this object is composed of skip list (for sorted search result)
* and map (for better performance).
*
* <p>{@link #remove} will fail in situation then item counter should become
* less than zero.
*
* <p>{@link #search} is delegated to {@link SkipListStringSet} instance.
*
* <p>{@code null} items should not be passed to add / remove / search.
*
*/
public final class SkipListStringBag implements StringMultiset {
private JsonStringMap<Counter> itemCounters;
private SkipListStringSet itemsSet;
public SkipListStringBag() {
clear();
}
@Override
public final void addAll(@Nonnull JsonArray<String> items) {
// TODO: Check if iterate is faster.
for (int i = 0, l = items.size(); i < l; i++) {
add(items.get(i));
}
}
@Override
public final void add(@Nonnull String item) {
Counter counter = itemCounters.get(item);
if (counter == null) {
counter = new Counter();
itemCounters.put(item, counter);
itemsSet.add(item);
} else {
counter.increment();
}
}
@Override
public final void removeAll(@Nonnull JsonArray<String> items) {
// TODO: Check if iterate is faster.
for (int i = 0, l = items.size(); i < l; i++) {
remove(items.get(i));
}
}
@Override
public final void remove(@Nonnull String item) {
Counter counter = itemCounters.get(item);
// TODO: Remove this precondition.
Preconditions.checkNotNull(counter, "trying to remove absent item: %s", item);
if (counter.decrement()) {
itemCounters.remove(item);
itemsSet.remove(item);
}
}
@Override
public boolean contains(@Nonnull String item) {
return itemCounters.containsKey(item);
}
public final Iterable<String> search(@Nonnull String item) {
return itemsSet.search(item);
}
@Override
public void clear() {
itemCounters = ClientStringMap.create();
itemsSet = SkipListStringSet.create();
}
}
| 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/util/collections/Counter.java | client/src/main/java/com/google/collide/client/util/collections/Counter.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.util.collections;
/**
* Object that is used for counting, how many times object is added to "bag".
*
* <p>New instance have counter equal to 1.
* <p>{@link #decrement()} returns {@code true} if counter reaches 0.
*/
final class Counter {
private int counter = 1;
public final void increment() {
counter++;
}
/**
* @return {@code true} if counter reaches 0.
*/
public final boolean decrement() {
counter--;
return counter == 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/util/collections/ClientStringMap.java | client/src/main/java/com/google/collide/client/util/collections/ClientStringMap.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.util.collections;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
/**
* Implementation with "__proto__" key workaround.
*
* @param <T> type of stored values.
*/
public final class ClientStringMap<T> implements JsonStringMap<T> {
private static final String PROTO_KEY = "__proto__";
private final JsoStringMap<T> delegate = JsoStringMap.create();
private boolean protoFlag;
private T protoValue;
/**
* Convenience factory method.
*/
public static <T> ClientStringMap<T> create() {
return new ClientStringMap<T>();
}
@Override
public T get(String key) {
if (PROTO_KEY.equals(key)) {
return protoValue;
}
return delegate.get(key);
}
@Override
public JsoArray<String> getKeys() {
JsoArray<String> result = delegate.getKeys();
if (protoFlag) {
result.add(PROTO_KEY);
}
return result;
}
@Override
public boolean isEmpty() {
return delegate.isEmpty() && !protoFlag;
}
@Override
public void iterate(IterationCallback<T> tIterationCallback) {
delegate.iterate(tIterationCallback);
if (protoFlag) {
tIterationCallback.onIteration(PROTO_KEY, protoValue);
}
}
@Override
public void put(String key, T value) {
if (PROTO_KEY.equals(key)) {
protoValue = value;
protoFlag = true;
} else {
delegate.put(key, value);
}
}
@Override
public void putAll(JsonStringMap<T> otherMap) {
otherMap.iterate(new IterationCallback<T>() {
@Override
public void onIteration(String key, T value) {
put(key, value);
}
});
}
@Override
public T remove(String key) {
if (PROTO_KEY.equals(key)) {
T result = protoValue;
protoValue = null;
protoFlag = false;
return result;
} else {
return delegate.remove(key);
}
}
@Override
public boolean containsKey(String key) {
if (PROTO_KEY.equals(key)) {
return protoFlag;
}
return delegate.containsKey(key);
}
@Override
public int size() {
int result = delegate.size();
if (protoFlag) {
result++;
}
return result;
}
}
| 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/util/collections/SkipListStringSet.java | client/src/main/java/com/google/collide/client/util/collections/SkipListStringSet.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.util.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.annotation.Nonnull;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.JavaScriptObject;
/**
* <a href="http://en.wikipedia.org/wiki/Skip_list">Skip List</a>
* implementation that holds Strings.
*
* <p>Actually this class provides some services similar to
* {@link java.util.SortedSet}, i.e. items can be placed / removed and
* sequentially accessed.
*
* <p>If some value is added two or more times, only one value is placed in set.
* So, when such value is removed (even one time), it will not appear in search
* results (until it is added again). Also, removing value that do not exist
* has no effect.
*
* <p>{@code null} values are not allowed for adding / removing / search.
*/
public final class SkipListStringSet {
private final LevelGenerator levelGenerator;
private final int maxLevel;
/**
* Object that generates integer values with semi-geometric
* distribution in range [0 .. maxLevel).
*
* <p>Mostly, this interface is used for testing purpose.
*/
@VisibleForTesting
interface LevelGenerator {
int generate();
}
private static class RandomLevelGenerator implements LevelGenerator {
private final int maxValue;
private final double promotionProbability;
private RandomLevelGenerator(int maxLevel, double promotionProbability) {
this.maxValue = maxLevel - 1;
this.promotionProbability = promotionProbability;
}
@Override
public int generate() {
int result = 0;
while (Math.random() < promotionProbability && result < maxValue) {
result++;
}
return result;
}
}
/**
* Skip list node.
*/
private static class Node extends JavaScriptObject {
private static native Node createHead(int maxLevel) /*-{
return new Array(maxLevel);
}-*/;
private static native Node create(String value, int maxLevel) /*-{
var result = new Array(maxLevel);
result.value = value;
return result;
}-*/;
protected Node() {
}
private Node getNext() {
return get(0);
}
private native Node get(int level) /*-{
return this[level];
}-*/;
private native void set(int level, Node node) /*-{
this[level] = node;
}-*/;
private native String getValue() /*-{
return this.value;
}-*/;
}
private static class SkipListIterator implements Iterator<String> {
private Node nextItem;
public SkipListIterator(Node nextItem) {
this.nextItem = nextItem;
}
@Override
public boolean hasNext() {
return nextItem.getNext() != null;
}
@Override
public String next() {
Node next = nextItem.getNext();
if (next == null) {
throw new NoSuchElementException();
}
nextItem = next;
return nextItem.getValue();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Height of the most "tall" item.
*/
private int currentLevel;
/**
* Special item that placed before all other items, and do not hold value,
*/
private final Node head;
public static SkipListStringSet create() {
return new SkipListStringSet(8, new RandomLevelGenerator(8, 0.25));
}
@VisibleForTesting
SkipListStringSet(int maxLevel, LevelGenerator levelGenerator) {
this.levelGenerator = levelGenerator;
this.maxLevel = maxLevel;
this.currentLevel = 0;
this.head = Node.createHead(maxLevel);
}
/**
* Adds value to "set".
*
* @param item non-{@code null} value to add.
*/
public void add(@Nonnull String item) {
Node backtrace = doSearch(item);
Node cursor = backtrace.get(0).getNext();
// If node with specified value exists: do nothing.
if (cursor != null && cursor.getValue().equals(item)) {
return;
}
int nodeLevel = levelGenerator.generate();
if (nodeLevel > currentLevel) {
for (int i = currentLevel + 1; i <= nodeLevel; i++) {
backtrace.set(i, head);
}
currentLevel = nodeLevel;
}
Node newNode = Node.create(item, nodeLevel + 1);
for (int i = 0; i <= nodeLevel; ++i) {
newNode.set(i, backtrace.get(i).get(i));
backtrace.get(i).set(i, newNode);
}
}
/**
* Searches the given node and returns "backtrace".
*/
private Node doSearch(@Nonnull String item) {
Node backtrace = Node.createHead(maxLevel);
Node cursor = head;
for (int i = currentLevel; i >= 0; --i) {
Node next = cursor.get(i);
while (next != null && next.getValue().compareTo(item) < 0) {
cursor = next;
next = cursor.get(i);
}
backtrace.set(i, cursor);
}
return backtrace;
}
/**
* Searches for the earliest (in sorting order) item greater or equal to
* the given one.
*
* @param item non-{@code null} value to search
*/
public Iterable<String> search(@Nonnull final String item) {
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new SkipListIterator(doSearch(item).get(0));
}
};
}
/**
* Returns {@link Iterable} whose iterators first value is the
* first item in this collection, so all items could be traversed.
*/
public Iterable<String> first() {
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new SkipListIterator(head);
}
};
}
/**
* Removes value from "set".
*
* @param item non-{@code null} value to search
*/
public void remove(@Nonnull String item) {
Node backtrace = doSearch(item);
Node cursor = backtrace.get(0).getNext();
// If node with specified do not exist: do nothing.
if (cursor == null || !cursor.getValue().equals(item)) {
return;
}
for (int i = 0; i <= currentLevel; i++) {
if (backtrace.get(i).get(i) == cursor) {
backtrace.get(i).set(i, cursor.get(i));
}
}
while (currentLevel > 0 && head.get(currentLevel) == null) {
currentLevel--;
}
}
}
| 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/util/collections/StringMultiset.java | client/src/main/java/com/google/collide/client/util/collections/StringMultiset.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.util.collections;
import javax.annotation.Nonnull;
import com.google.collide.json.shared.JsonArray;
// TODO: Combine with JsonStringSet?
/**
* <a href="http://en.wikipedia.org/wiki/Multiset">Multiset</a> interface.
*
*/
public interface StringMultiset {
void addAll(@Nonnull JsonArray<String> items);
void add(@Nonnull String item);
void removeAll(@Nonnull JsonArray<String> items);
void remove(@Nonnull String item);
boolean contains(@Nonnull String item);
void 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/plugin/FileAssociation.java | client/src/main/java/com/google/collide/client/plugin/FileAssociation.java | package com.google.collide.client.plugin;
public interface FileAssociation {
boolean matches(String filename);
//return a form to embed in runtime popup
//update the form from a give file model
public static abstract class FileAssociationSuffix implements FileAssociation{
private String suffix;
public FileAssociationSuffix(String suffix){
this.suffix = suffix;
}
@Override
public boolean matches(String filename) {
return filename.endsWith(suffix);
}
}
}
| 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/plugin/ClientPluginService.java | client/src/main/java/com/google/collide/client/plugin/ClientPluginService.java | package com.google.collide.client.plugin;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicServices;
import xapi.fu.Out1;
import xapi.inject.X_Inject;
public class ClientPluginService {
protected ClientPluginService() {
}
private static final Out1<ClientPluginService> SINGLETON = X_Inject.singletonLazy(ClientPluginService.class);
public static ClientPluginService initialize(AppContext appContext, MultiPanel<?,?> masterPanel
, Place workspacePlace) {
ClientPluginService plugins = SINGLETON.out1();
plugins.init(appContext, masterPanel, workspacePlace);
return plugins;
}
@SuppressWarnings({"unchecked","rawtypes"})
protected void init(AppContext appContext, MultiPanel<?, ?> masterPanel, Place workspacePlace) {
for (ClientPlugin<?> plugin : plugins()) {
plugin.initializePlugin(appContext, masterPanel, workspacePlace);
PublicService<?>[] services = plugin.getPublicServices();
if (services != null)
for (PublicService service : plugin.getPublicServices()) {
PublicServices.registerService(service.classKey(), service);
}
}
}
public static ClientPlugin<?>[] getPlugins() {
return SINGLETON.out1().plugins();
}
@SuppressWarnings("unchecked")
public static <T extends ClientPlugin<?>> T getPlugin(Class<T> cls) {
for (ClientPlugin<?> plugin : getPlugins()) {
if (cls.isAssignableFrom(plugin.getClass())) {
return (T)plugin;
}
}
return null;
}
public ClientPlugin<?>[] plugins() {
return new ClientPlugin[0];
}
public void cleanup() {
//notify any of our plugins that require cleanup.
}
}
| 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/plugin/ClientPlugin.java | client/src/main/java/com/google/collide/client/plugin/ClientPlugin.java | package com.google.collide.client.plugin;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.ui.button.ImageButton;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.workspace.Header.Resources;
import com.google.collide.shared.plugin.PublicService;
import com.google.gwt.resources.client.ImageResource;
public interface ClientPlugin <PlaceType extends Place>{
PlaceType getPlace();
void initializePlugin(
AppContext appContext, MultiPanel<?,?> masterPanel, Place currentPlace);
ImageResource getIcon(Resources res);
void onClicked(ImageButton button);
FileAssociation getFileAssociation();
RunConfiguration getRunConfig();
PublicService<?> [] getPublicServices();
}
| 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/plugin/RunConfiguration.java | client/src/main/java/com/google/collide/client/plugin/RunConfiguration.java | package com.google.collide.client.plugin;
import com.google.collide.client.AppContext;
import com.google.collide.client.util.PathUtil;
import elemental.dom.Element;
public interface RunConfiguration {
String getId();
String getLabel();
void run(AppContext appContext, PathUtil file);
Element getForm();
}
| 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/codeunderstanding/CubeUpdateListener.java | client/src/main/java/com/google/collide/client/codeunderstanding/CubeUpdateListener.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.codeunderstanding;
/**
* An interface of listener of {@link CubeClient}.
*
* <p>Listeners are notified when fresh Cube-service data is received.
*/
public interface CubeUpdateListener {
void onCubeResponse(CubeData data, CubeDataUpdates updates);
}
| 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/codeunderstanding/CubeDataUpdates.java | client/src/main/java/com/google/collide/client/codeunderstanding/CubeDataUpdates.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.codeunderstanding;
/**
* Immutable value object holding information about what fields of
* {@link CubeData} has been updated.
*/
public class CubeDataUpdates {
public static final CubeDataUpdates NO_UPDATES =
new CubeDataUpdates(false, false, false, false, false);
private final boolean fileTree;
private final boolean fullGraph;
private final boolean libsSubgraph;
private final boolean workspaceTree;
private final boolean fileReferences;
public CubeDataUpdates(boolean fileTree, boolean fullGraph, boolean libsSubgraph,
boolean workspaceTree, boolean fileReferences) {
this.fileTree = fileTree;
this.fullGraph = fullGraph;
this.libsSubgraph = libsSubgraph;
this.workspaceTree = workspaceTree;
this.fileReferences = fileReferences;
}
public boolean isFileTree() {
return fileTree;
}
public boolean isFullGraph() {
return fullGraph;
}
public boolean isLibsSubgraph() {
return libsSubgraph;
}
public boolean isWorkspaceTree() {
return workspaceTree;
}
public boolean isFileReferences() {
return fileReferences;
}
@Override
public String toString() {
return "CubeDataUpdates{" +
"\n fileTree=" + fileTree +
",\n fullGraph=" + fullGraph +
",\n libsSubgraph=" + libsSubgraph +
",\n workspaceTree=" + workspaceTree +
",\n fileReferences=" + fileReferences +
"\n}";
}
public static boolean hasUpdates(CubeDataUpdates updates) {
return updates.fileTree || updates.fullGraph || updates.libsSubgraph || updates.workspaceTree
|| updates.fileReferences;
}
}
| 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/codeunderstanding/CubeClientWrapper.java | client/src/main/java/com/google/collide/client/codeunderstanding/CubeClientWrapper.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.codeunderstanding;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.dto.CodeGraphRequest;
import com.google.collide.dto.CodeGraphResponse;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.TextChange;
import com.google.collide.shared.util.ListenerRegistrar;
import com.google.common.base.Preconditions;
/**
* Wrapper that isolates {@link CubeClient} from UI.
*
*/
public class CubeClientWrapper {
private final CubeClient cubeClient;
private ListenerRegistrar.Remover textListenerRemover;
/**
* Constructs instance of and registers {@link #cubeClient} as an appropriate
* Tango invalidation receiver.
*
* @param api Cube API
*/
public CubeClientWrapper(FrontendApi.RequestResponseApi<CodeGraphRequest,
CodeGraphResponse> api) {
this.cubeClient = new CubeClient(api);
// USED TO REGISTER WITH TANGO
}
public void cleanup() {
unsubscribeTextListener();
cubeClient.cleanup();
}
public void setDocument(Document document, String filePath) {
Preconditions.checkNotNull(document);
unsubscribeTextListener();
textListenerRemover = document.getTextListenerRegistrar().add(new Document.TextListener() {
@Override
public void onTextChange(Document document, JsonArray<TextChange> textChanges) {
cubeClient.refresh();
}
});
cubeClient.setPath(filePath);
}
private void unsubscribeTextListener() {
if (textListenerRemover != null) {
textListenerRemover.remove();
}
textListenerRemover = null;
}
public CubeClient getCubeClient() {
return cubeClient;
}
}
| 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/codeunderstanding/CubeData.java | client/src/main/java/com/google/collide/client/codeunderstanding/CubeData.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.codeunderstanding;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.CodeGraph;
import com.google.collide.dto.CodeReferences;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
/**
* A value object that holds all valuable parts of Cube response.
*/
public class CubeData {
/**
* Predefined instance that holds {@code null}'s.
*/
public static final CubeData EMPTY_DATA = new CubeData(null, null, null, null, null, null);
private final String filePath;
private final CodeBlock fileTree;
private final CodeGraph fullGraph;
private final CodeGraph libsSubgraph;
private final CodeGraph workspaceTree;
private final CodeReferences fileReferences;
public CubeData(String filePath, CodeBlock fileTree, CodeGraph fullGraph, CodeGraph libsSubgraph,
CodeGraph workspaceTree, CodeReferences fileReferences) {
this.filePath = filePath;
this.fileTree = fileTree;
this.fullGraph = fullGraph;
this.libsSubgraph = libsSubgraph;
this.workspaceTree = workspaceTree;
this.fileReferences = fileReferences;
}
public String getFilePath() {
return filePath;
}
public CodeBlock getFileTree() {
return fileTree;
}
public CodeGraph getFullGraph() {
return fullGraph;
}
public CodeGraph getLibsSubgraph() {
return libsSubgraph;
}
public CodeGraph getWorkspaceTree() {
return workspaceTree;
}
public CodeReferences getFileReferences() {
return fileReferences;
}
@Override
public String toString() {
return "CubeData{" +
"\n filePath='" + filePath + '\'' +
",\n fileTree=" + objectInfo(fileTree) +
",\n fullGraph=" + objectInfo(fullGraph) +
",\n libsSubgraph=" + objectInfo(libsSubgraph) +
",\n workspaceTree=" + objectInfo(workspaceTree) +
",\n fileReferences=" + objectInfo(fileReferences) +
"\n}";
}
private static String objectInfo(Object object) {
return object == null ? null : "object";
}
private static String objectInfo(CodeReferences object) {
return (object == null) ? null : "CodeReferences{" +
"references=" + objectInfo(object.getReferences()) +
"}";
}
private static String objectInfo(CodeGraph object) {
return (object == null) ? null : "CodeGraph{" +
"inheritanceAssociations=" + objectInfo(object.getInheritanceAssociations()) +
", typeAssociations=" + objectInfo(object.getTypeAssociations()) +
", importAssociations=" + objectInfo(object.getImportAssociations()) +
", codeBlockMap=" + objectInfo(object.getCodeBlockMap()) +
"}";
}
private static String objectInfo(JsonArray object) {
return object == null ? null : "JsonArray{size=" + object.size() + "}";
}
private static String objectInfo(JsonStringMap object) {
return object == null ? null : "JsonStringMap{size=" + object.size() + "}";
}
}
| 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/codeunderstanding/CubeState.java | client/src/main/java/com/google/collide/client/codeunderstanding/CubeState.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.codeunderstanding;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.util.DeferredCommandExecutor;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.CodeGraph;
import com.google.collide.dto.CodeGraphFreshness;
import com.google.collide.dto.CodeGraphRequest;
import com.google.collide.dto.CodeGraphResponse;
import com.google.collide.dto.CodeReferences;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.CodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphFreshnessImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphRequestImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeReferencesImpl;
import com.google.collide.json.client.Jso;
import com.google.common.base.Preconditions;
import static com.google.collide.shared.util.StringUtils.isNullOrEmpty;
/**
* An object that holds the current state of communication with Cube-service.
*
* <p>Request to service are sequenced and "collapsed".
* It means that newer request is hold until the previous response comes,
* and that if there are several new requests, only the last of them
* survives.
*
* <p>Also this class is responsible for merging updates coming from the server.
*
*/
public class CubeState implements FrontendApi.ApiCallback<CodeGraphResponse> {
/**
* An interface of a callback that is called when appropriate update
* is received.
*/
interface CubeResponseDistributor {
/**
* Notifies instances interested in Cube data.
*
* @param updates indicates which data has been changed
*/
void notifyListeners(CubeDataUpdates updates);
}
/**
* A command that gently asks outer object to perform "retry" action
* after specified timeout.
*
* <p>The command itself is executed once a second to be able to be
* dismissed.
*
* <p>When time is elapsed command calls outer object
* {@link CubeState#retryIfReady()} each iteration until it
* responds that action is taken.
*/
private class RetryExecutor extends DeferredCommandExecutor {
protected RetryExecutor() {
super(1000);
}
@Override
protected boolean execute() {
return !retryIfReady();
}
}
/**
* Cube API.
*/
private final FrontendApi.RequestResponseApi<CodeGraphRequest, CodeGraphResponse> api;
/**
* Last (merged) Cube data.
*/
private CubeData data;
/**
* Actual merged freshness of data.
*/
private CodeGraphFreshness freshness;
/**
* File path to be requested on next request.
*/
private String activeFilePath;
/**
* File path in last response.
*
* <p>If filePath to be requested is not the same as in last response -
* we reset fileTree and it's freshness.
*/
private String lastResponseFilePath;
/**
* File path in last request for which he hasn't got response yet.
*/
private String requestedFilePath;
/**
* Flag indicating that we should make a new request after
* we receive response.
*/
private boolean deferredRefresh;
/**
* Indicates that we should not further do more requests / process responses.
*/
private boolean isDismissed;
/**
* Instance that distributes data to consumers.
*/
private final CubeResponseDistributor distributor;
/**
* Number of times the retry command has been consequently (re)scheduled.
*/
private int retryRound;
/**
* Retry command executor.
*/
private final RetryExecutor retryExecutor = new RetryExecutor();
public CubeState(FrontendApi.RequestResponseApi<CodeGraphRequest, CodeGraphResponse> api,
CubeResponseDistributor distributor) {
this.api = api;
this.distributor = distributor;
data = CubeData.EMPTY_DATA;
freshness = CodeGraphFreshnessImpl.make()
.setFullGraph("0")
.setLibsSubgraph("0")
.setWorkspaceTree("0")
.setFileTree("0")
.setFileReferences("0");
}
/**
* Prevents further instance activity.
*/
public void dismiss() {
isDismissed = true;
retryExecutor.cancel();
}
public CubeData getData() {
return data;
}
/**
* Makes a next request if there is a deferred one or
* schedule retry if required.
*
* <p>This method must be called after network response or
* failure is processed to schedule next network activity.
*/
private void processDeferredActions() {
requestedFilePath = null;
if (deferredRefresh) {
deferredRefresh = false;
refresh();
} else if (retryRound > 0) {
// We should schedule retry if hasn't done it yet.
if (!retryExecutor.isScheduled()) {
retryRound++;
retryExecutor.schedule(2 + retryRound);
}
}
}
/**
* Enqueues or collapses request to Cube-service.
*/
public void refresh() {
if (isDismissed) {
return;
}
if (activeFilePath == null) {
return;
}
// Refresh is already deferred.
if (deferredRefresh) {
return;
}
// Waiting for response of equal request.
if (activeFilePath.equals(requestedFilePath)) {
return;
}
boolean activeIsCodeFilePath = checkFilePathIsCodeFile(activeFilePath);
// Will send request after response come.
if (requestedFilePath != null) {
// do not defer if we do not need fileTree
if (activeIsCodeFilePath) {
deferredRefresh = true;
}
return;
}
// Else reset fileTree, if needed.
if (!activeFilePath.equals(lastResponseFilePath) || !activeIsCodeFilePath) {
resetContextFileData();
}
String filePathToRequest = activeIsCodeFilePath ? activeFilePath : null;
// And send request.
CodeGraphRequest request = CodeGraphRequestImpl.make()
.setFreshness(freshness)
.setFilePath(filePathToRequest);
api.send(request, this);
requestedFilePath = activeFilePath;
}
/**
* Forgets stale fileTree data and freshness.
*/
private void resetContextFileData() {
freshness = CodeGraphFreshnessImpl.make()
.setLibsSubgraph(freshness.getLibsSubgraph())
.setFileTree("0")
.setFullGraph(freshness.getFullGraph())
.setWorkspaceTree(freshness.getWorkspaceTree())
.setFileReferences("0");
data = new CubeData(activeFilePath, null, data.getFullGraph(), data.getLibsSubgraph(),
data.getWorkspaceTree(), null);
}
/**
* Merges fresh server data with stored one and notifies consumers.
*
* @param message fresh Cube data.
*/
@Override
public void onMessageReceived(CodeGraphResponse message) {
if (isDismissed) {
Log.debug(getClass(), "Ignored CUBE response");
return;
}
retryRound = 0;
retryExecutor.cancel();
boolean requestedIsCode = checkFilePathIsCodeFile(requestedFilePath);
CodeGraphFreshnessImpl merged = CodeGraphFreshnessImpl.make();
CodeGraphFreshness serverFreshness = message.getFreshness();
if (serverFreshness == null) {
// temporary hack: the code from google had no implementation for this endpoint,
// so we no-op by just returning an empty object. :-/
return;
}
CodeGraph libsSubgraph = data.getLibsSubgraph();
merged.setLibsSubgraph(this.freshness.getLibsSubgraph());
boolean libsSubgraphUpdated = false;
CodeBlock fileTree = data.getFileTree();
merged.setFileTree(this.freshness.getFileTree());
merged.setFileTreeHash(this.freshness.getFileTreeHash());
boolean fileTreeUpdated = false;
CodeGraph workspaceTree = data.getWorkspaceTree();
merged.setWorkspaceTree(this.freshness.getWorkspaceTree());
boolean workspaceTreeUpdated = false;
CodeGraph fullGraph = data.getFullGraph();
merged.setFullGraph(this.freshness.getFullGraph());
boolean fullGraphUpdated = false;
CodeReferences fileReferences = data.getFileReferences();
merged.setFileReferences(this.freshness.getFileReferences());
boolean fileReferencesUpdated = false;
if (!isNullOrEmpty(message.getLibsSubgraphJson())
&& compareFreshness(serverFreshness.getLibsSubgraph(), merged.getLibsSubgraph()) > 0) {
libsSubgraph = Jso.<CodeGraphImpl>deserialize(message.getLibsSubgraphJson());
merged.setLibsSubgraph(serverFreshness.getLibsSubgraph());
libsSubgraphUpdated = true;
}
if (!isNullOrEmpty(message.getFileTreeJson()) && requestedIsCode
&& isServerFileTreeMoreFresh(merged, serverFreshness)) {
fileTree = Jso.<CodeBlockImpl>deserialize(message.getFileTreeJson());
merged.setFileTree(serverFreshness.getFileTree());
merged.setFileTreeHash(serverFreshness.getFileTreeHash());
fileTreeUpdated = true;
}
if (!isNullOrEmpty(message.getWorkspaceTreeJson())
&& compareFreshness(serverFreshness.getWorkspaceTree(), merged.getWorkspaceTree()) > 0) {
workspaceTree = Jso.<CodeGraphImpl>deserialize(message.getWorkspaceTreeJson());
merged.setWorkspaceTree(serverFreshness.getWorkspaceTree());
workspaceTreeUpdated = true;
}
if (!isNullOrEmpty(message.getFullGraphJson())
&& compareFreshness(serverFreshness.getFullGraph(), merged.getFullGraph()) > 0) {
fullGraph = Jso.<CodeGraphImpl>deserialize(message.getFullGraphJson());
merged.setFullGraph(serverFreshness.getFullGraph());
fullGraphUpdated = true;
}
if (!isNullOrEmpty(message.getFileReferencesJson())
&& compareFreshness(serverFreshness.getFileReferences(), merged.getFileReferences()) > 0) {
fileReferences = Jso.<CodeReferencesImpl>deserialize(message.getFileReferencesJson());
merged.setFileReferences(serverFreshness.getFileReferences());
fileReferencesUpdated = true;
}
if (!requestedFilePath.equals(activeFilePath)) {
fileTree = null;
fileTreeUpdated = false;
fileReferences = null;
fileReferencesUpdated = false;
}
CubeDataUpdates updates = new CubeDataUpdates(fileTreeUpdated, fullGraphUpdated,
libsSubgraphUpdated, workspaceTreeUpdated, fileReferencesUpdated);
// At this moment consumers are waiting for *activeFilePath* updates.
// If update for it is not received yet (requested != active), then
// fileTree is set to null, and consumers could try to use data from
// fullGraph using filePath stored in data.
data = new CubeData(activeFilePath, fileTree, fullGraph, libsSubgraph, workspaceTree,
fileReferences);
freshness = merged;
Log.debug(getClass(), "CUBE data updated", updates, data);
lastResponseFilePath = requestedFilePath;
distributor.notifyListeners(updates);
processDeferredActions();
}
@Override
public void onFail(FailureReason reason) {
if (isDismissed) {
return;
}
processDeferredActions(true);
}
/**
* Makes a next request if there is a deferred one or
* schedule retry if required.
*
* <p>This method must be called after network response or
* failure is processed to schedule next network activity.
*
* @param afterFail {@code true} indicates that this method
* is invoked from {@link #onFail(FailureReason)}
*/
private void processDeferredActions(boolean afterFail) {
requestedFilePath = null;
if (deferredRefresh) {
deferredRefresh = false;
refresh();
} else if (afterFail || retryRound > 0) {
// We should schedule retry if hasn't done it yet.
if (!retryExecutor.isScheduled()) {
retryRound++;
retryExecutor.schedule(2 + retryRound);
}
}
}
/**
* Compares server and client freshness.
*
* <p>The point is that server can send no freshness, which means that
* data is not ready.
*
* <p>In common case freshness is an integer written as string.
*
* @param serverFreshness string that represents server side freshness
* @param clientFreshness string that represents client side freshness
* @return {@code 0}, {@code 1}, or {@code -1} according to freshness
* relationship
*/
private static int compareFreshness(String serverFreshness, String clientFreshness) {
if (isNullOrEmpty(clientFreshness)) {
throw new IllegalArgumentException("client freshness should never be undefined");
}
if (isNullOrEmpty(serverFreshness)) {
// Assume server don't know better than we do.
return -1;
}
return Long.valueOf(serverFreshness).compareTo(Long.valueOf(clientFreshness));
}
/**
* Sets active file path and requests fresh data from service.
*
* @param filePath new active file path
*/
void setFilePath(String filePath) {
Preconditions.checkNotNull(filePath);
activeFilePath = filePath;
refresh();
}
/**
* Checks if the specified file path is acceptable for Cube.
*
* @return {@code false} if we shouldn't send request for the specified file
*/
private static boolean checkFilePathIsCodeFile(String filePath) {
Preconditions.checkNotNull(filePath);
// TODO: should we ignore case?
return filePath.endsWith(".js") || filePath.endsWith(".py") || filePath.endsWith(".dart");
}
private static boolean isServerFileTreeMoreFresh(
CodeGraphFreshness clientFreshness, CodeGraphFreshness serverFreshness) {
return compareFreshness(serverFreshness.getFileTree(), clientFreshness.getFileTree()) > 0
|| (compareFreshness(serverFreshness.getFileTree(), clientFreshness.getFileTree()) == 0
&& !serverFreshness.getFileTreeHash().equals(clientFreshness.getFileTreeHash()));
}
/**
* Resends last request.
*
* @return {@code false} if object is not ready to perform that action
* and should be notified again later
*/
private boolean retryIfReady() {
// Waiting for response.
if (requestedFilePath != null) {
return false;
}
// Force request.
deferredRefresh = false;
refresh();
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/codeunderstanding/CubeClient.java | client/src/main/java/com/google/collide/client/codeunderstanding/CubeClient.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.codeunderstanding;
import javax.annotation.Nullable;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.util.DeferredCommandExecutor;
import com.google.collide.client.util.logging.Log;
import com.google.collide.clientlibs.invalidation.InvalidationRegistrar;
import com.google.collide.dto.CodeGraphRequest;
import com.google.collide.dto.CodeGraphResponse;
import com.google.collide.dto.CubePing;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.client.DtoUtils;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.common.base.Preconditions;
/**
* A response distributor for {@link CubeState}.
*
* Presents a high level API for end clients.
*
*/
public class CubeClient
implements CubeState.CubeResponseDistributor, InvalidationRegistrar.Listener {
/**
* A command and listener that requests state refresh after text changes.
*
* <p>Idle timeout is 10 x 100ms = 1s.
*/
private class RefreshWatchdog extends DeferredCommandExecutor {
protected RefreshWatchdog() {
super(100);
}
@Override
protected boolean execute() {
state.refresh();
return false;
}
}
/**
* Request sender / response receiver & logic.
*/
private final CubeState state;
/**
* List of subscribers.
*/
private final JsonArray<CubeUpdateListener> listeners = JsoArray.create();
/**
* Text changes detector / idle period actor.
*/
private final RefreshWatchdog refreshWatchdog = new RefreshWatchdog();
/**
* Constructs object, and initialises it's state with given parameters.
*
* @param api Cube API
*/
CubeClient(
FrontendApi.RequestResponseApi<CodeGraphRequest, CodeGraphResponse> api) {
Preconditions.checkNotNull(api);
state = new CubeState(api, this);
}
public void addListener(CubeUpdateListener listener) {
listeners.add(listener);
}
/**
* Prevents further response distribution / processing.
*/
void cleanup() {
refreshWatchdog.cancel();
listeners.clear();
state.dismiss();
}
@Override
public void notifyListeners(CubeDataUpdates updates) {
if (!CubeDataUpdates.hasUpdates(updates)) {
return;
}
int l = listeners.size();
for (int i = 0; i < l; i++) {
listeners.get(i).onCubeResponse(state.getData(), updates);
}
}
@Override
public void onInvalidated(String objectName, long version, @Nullable String payload,
AsyncProcessingHandle asyncProcessingHandle) {
if (payload == null) {
// darn - we lost the payload; this just means that we should refresh
// state just in case its changed (which may be inefficient if our state
// actually isn't out of date)
} else {
CubePing message;
try {
message = DtoUtils.parseAsDto(payload, RoutingTypes.CUBEPING);
} catch (Exception e) {
Log.warn(getClass(), "Failed to deserialize Tango payload", e);
return;
}
// TODO: We should use message.getFullGraphFreshness()
}
// if we haven't returned out yet, that means we need to refresh state
state.refresh();
}
public CubeData getData() {
return state.getData();
}
public void removeListener(CubeUpdateListener listener) {
listeners.remove(listener);
}
void setPath(String filePath) {
Preconditions.checkNotNull(filePath);
state.setFilePath(filePath);
refreshWatchdog.cancel();
state.refresh();
}
void refresh() {
refreshWatchdog.schedule(10);
}
}
| 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/communication/FrontendRestApi.java | client/src/main/java/com/google/collide/client/communication/FrontendRestApi.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.communication;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
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.InvalidXsrfTokenServerError;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerError;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls;
import com.google.collide.dto.client.DtoClientImpls.EmptyMessageImpl;
import com.google.collide.dto.client.DtoUtils;
import com.google.collide.dtogen.client.RoutableDtoClientImpl;
import com.google.collide.dtogen.shared.ClientToServerDto;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.client.Jso;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
import com.google.collide.shared.FrontendConstants;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
/**
* The Servlet APIs for the Collide server.
*
* See {@package com.google.collide.dto} for data objects.
*
*/
public class FrontendRestApi {
private static FailureReason getFailureReason(Response response, ServerError responseData) {
switch (response.getStatusCode()) {
case Response.SC_OK:
return null;
case Response.SC_UNAUTHORIZED:
if (responseData != null) {
return responseData.getFailureReason();
}
return FailureReason.UNAUTHORIZED;
// TODO: Make this a server dto error.
case Response.SC_CONFLICT:
return FailureReason.STALE_CLIENT;
case Response.SC_NOT_FOUND:
if (responseData != null) {
return responseData.getFailureReason();
}
return FailureReason.UNKNOWN;
case Response.SC_NOT_IMPLEMENTED:
if (responseData != null) {
return responseData.getFailureReason();
}
return FailureReason.UNKNOWN;
default:
return FailureReason.SERVER_ERROR;
}
}
/**
* Encapsulates a servlet API that documents the message types sent to the
* frontend, and the optional message types returned as a response.
*
* @param <REQ> The outgoing message type.
* @param <RESP> The incoming message type.
*/
public static interface Api<REQ extends ClientToServerDto, RESP extends ServerToClientDto> {
public void send(REQ msg);
public void send(REQ msg, final ApiCallback<RESP> callback);
public void send(REQ msg, int retries, final RetryCallback<RESP> callback);
}
/**
* Callback interface for making requests to a frontend API.
*/
public interface ApiCallback<T extends ServerToClientDto> extends MessageRecipient<T> {
/**
* Message didn't come back OK.
*
* @param reason the reason for the failure, should not be null
*/
void onFail(FailureReason reason);
}
/**
* Production implementation of the Api. Sends XmlHttpRequests.
*
* Visible so that the {@code MockFrontendApi.MockApi} can inherit it, which
* in turn is so that {@link #send(ClientToServerDto, int, RetryCallback)} can
* be inherited and correctly be mocked as the constituent individual sends.
*/
@VisibleForTesting
public class ApiImpl<REQ extends ClientToServerDto, RESP extends ServerToClientDto>
implements Api<REQ, RESP> {
private final String url;
@VisibleForTesting
protected ApiImpl(String url) {
this.url = url;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* Calls this Api passing in the specified message. If there is a response
* that comes back, it will be dispatched on the MessageFilter.
*/
@Override
public void send(REQ msg) {
send(msg, null);
}
/**
* Calls this Api passing in the specified message.
*
* NOTE: Responses will be dispatch on the supplied callback and NOT on the
* MessageFilter (unless the callback is null).
*/
@Override
public void send(REQ msg, final ApiCallback<RESP> callback) {
doRequest(msg, new RequestCallback() {
@Override
public void onError(Request request, Throwable exception) {
Log.error(FrontendRestApi.class, "Failed: " + exception);
if (callback != null) {
callback.onFail(FailureReason.COMMUNICATION_ERROR);
}
}
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK) {
try {
// If the frontend doesn't write something back to the stream,
// invoke the callback with an empty message.
if (response.getText() == null || response.getText().equals("")) {
if (callback != null) {
@SuppressWarnings("unchecked")
RESP emptyMessage = (RESP) EmptyMessageImpl.make();
callback.onMessageReceived(emptyMessage);
}
return;
}
ServerToClientDto responseData =
(ServerToClientDto) Jso.deserialize(response.getText());
String action = "?";
try {
if (callback != null) {
action = "invoking callback";
@SuppressWarnings("unchecked")
RESP message = (RESP) responseData;
callback.onMessageReceived(message);
} else {
action = "dispatching message on MessageFilter";
Log.info(FrontendRestApi.class, "dispatching: " + response.getText());
getMessageFilter().dispatchMessage(responseData);
}
} catch (Exception e) {
Log.error(FrontendRestApi.class,
"Exception when " + action + ": " + response.getText(), e);
}
} catch (Exception e) {
Log.warn(
FrontendRestApi.class, "Failed to deserialize JSON response: " + response.getText());
}
} else {
if (callback != null) {
ServerError responseData = null;
if (!StringUtils.isNullOrEmpty(response.getText())) {
try {
responseData = DtoUtils.parseAsDto(response.getText(), RoutingTypes.SERVERERROR,
RoutingTypes.INVALIDXSRFTOKENSERVERERROR);
} catch (Exception e) {
Log.error(
FrontendRestApi.class, "Exception when deserializing " + response.getText(), e);
}
}
FailureReason error = getFailureReason(response, responseData);
if (recoverer != null) {
// TODO: Instead of just terminating retry here.
// We should instead refactor the callback's onFail semantics to also take in
// "what attempts at failure handling have already been attempted" and make the
// leaves do something intelligent wrt to handling the final failure.
boolean tryAgain = recoverer.handleFailure(FrontendRestApi.this, error, responseData);
if (tryAgain) {
// For auto-retry handlers, this will issue another XHR retry.
callback.onFail(error);
}
} else {
callback.onFail(error);
}
} else {
Log.warn(FrontendRestApi.class, "Failed: " + response.getStatusText());
}
}
}
});
}
@Override
public void send(final REQ msg, int retries, final RetryCallback<RESP> callback) {
final Countdown countdown = new Countdown(retries);
send(msg, new ApiCallback<RESP>() {
@Override
public void onFail(FailureReason reason) {
if (FailureReason.UNAUTHORIZED != reason && countdown.canTryAgain()) {
/*
* If the failure is due to an authorization issue, there is no
* reason to retry the request.
*/
final ApiCallback<RESP> apiCallback = this;
final RepeatingCommand cmd = new RepeatingCommand() {
@Override
public boolean execute() {
send(msg, apiCallback);
return false;
}
};
callback.onRetry(countdown.getRetryCount(), countdown.delayToTryAgain(), cmd);
Scheduler.get().scheduleFixedDelay(cmd, countdown.delayToTryAgain());
} else {
callback.onFail(reason);
}
}
@Override
public void onMessageReceived(RESP message) {
callback.onMessageReceived(message);
}
});
}
private void doRequest(REQ msg, RequestCallback internalCallback) {
final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, getUrl());
customHeaders.iterate(new IterationCallback<String>() {
@Override
public void onIteration(String header, String value) {
requestBuilder.setHeader(header, value);
}
});
try {
RoutableDtoClientImpl messageImpl = (RoutableDtoClientImpl) msg;
requestBuilder.sendRequest(messageImpl.serialize(), internalCallback);
} catch (RequestException e1) {
Log.error(FrontendRestApi.class, e1.getMessage());
}
}
}
/**
* Callback with built-in retry notification, so it can put up a "trying again
* in N seconds" notice if it wants to, or try again early.
*/
public abstract static class RetryCallback<T extends ServerToClientDto> implements ApiCallback<
T> {
/**
* Called when a given fails, with information about the next time it will
* be tried and a handle to early if desired.
*
* @param count a count of the number of retries so far
* @param milliseconds time between "now" and the next execution
* @param retryCmd an already-scheduled {@link RepeatingCommand}, whose
* {@link RepeatingCommand#execute()} method could be called early if
* desired.
*/
protected void onRetry(int count, int milliseconds, RepeatingCommand retryCmd) {
// by default, do nothing. Subclasses may opt to provide status feedback,
// or trigger retryCmd to try again before the regularly scheduled time.
}
}
private static class Countdown {
int retriesLeft;
int retriesDone;
private Countdown(int retries) {
this.retriesLeft = retries;
this.retriesDone = 0;
}
/**
* Decrements the retry counter, and returns {@code true} only if more
* retries are allowed.
*/
private boolean canTryAgain() {
retriesLeft--;
retriesDone++;
return retriesLeft > 0;
}
/**
* Returns milliseconds of delay before next .
*/
private int delayToTryAgain() {
return 2000 * retriesDone * retriesDone;
}
private int getRetryCount() {
return retriesDone;
}
}
/////////////////////////////////
// BEGIN AVAILABLE FRONTEND APIS
/////////////////////////////////
/*
* If one were to consider running this as a hosted service, with affordances for branch switching
* and project management. You would probably need APIs that looked like the following ;) ->
*/
// /**
// * Send a keep-alive for the client in a workspace.
// */
// public final Api<KeepAlive, EmptyMessage> KEEP_ALIVE = makeApi("/workspace/act/KeepAlive");
//
// public final Api<ClientToServerDocOp, ServerToClientDocOps> MUTATE_FILE =
// makeApi("/workspace/act/MutateFile");
//
// /**
// * Lets a client re-synchronize with the server's version of a file after
// * being offline or missing a doc op broadcast.
// */
// public final Api<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse>
// RECOVER_FROM_MISSED_DOC_OPS = makeApi("/workspace/act/RecoverFromMissedDocOps");
//
// /**
// * Leave a workspace.
// */
// public final Api<LeaveWorkspace, EmptyMessage> LEAVE_WORKSPACE =
// makeApi("/workspace/act/LeaveWorkspace");
//
// /**
// * Enter a workspace.
// */
// public final Api<EnterWorkspace, EnterWorkspaceResponse> ENTER_WORKSPACE =
// makeApi("/workspace/act/EnterWorkspace");
//
// /**
// * Get the workspace file tree and associated meta data like conflicts and the
// * tango version number for the file tree.
// */
// public final Api<GetFileTree, GetFileTreeResponse>
// GET_FILE_TREE = makeApi("/workspace/act/GetFileTree");
//
// /**
// * Get a subdirectory. Just the subtree rooted at that path. No associated
// * meta data.
// */
// public final Api<GetDirectory, GetDirectoryResponse>
// GET_DIRECTORY = makeApi("/workspace/act/GetDirectory");
//
// /**
// * Get the directory listing and any conflicts.
// */
// public final Api<GetFileContents, GetFileContentsResponse>
// GET_FILE_CONTENTS = makeApi("/workspace/mgmt/GetFileContents");
//
// /**
// * Get the sync state.
// */
// public final Api<GetSyncState, GetSyncStateResponse>
// GET_SYNC_STATE = makeApi("/workspace/mgmt/GetSyncState");
//
// /**
// * Sync from the parent workspace.
// */
// public final Api<Sync, EmptyMessage> SYNC = makeApi("/workspace/mgmt/Sync");
//
// /**
// * Undo the most recent sync.
// */
// public final Api<UndoLastSync, EmptyMessage> UNDO_LAST_SYNC =
// makeApi("/workspace/mgmt/UndoLastSync");
//
// /**
// * Submit to the parent workspace.
// */
// public final Api<Submit, SubmitResponse> SUBMIT = makeApi("/workspace/mgmt/Submit");
//
// /**
// * Archives a workspace.
// */
// public final Api<SetWorkspaceArchiveState, SetWorkspaceArchiveStateResponse> ARCHIVE_WORKSPACE =
// makeApi("/workspace/mgmt/setWorkspaceArchiveState");
//
// /**
// * Creates a project.
// */
// public final Api<CreateProject, CreateProjectResponse> CREATE_PROJECT =
// makeApi("/project/create");
//
// /**
// * Creates a workspace.
// */
// public final Api<CreateWorkspace, CreateWorkspaceResponse> CREATE_WORKSPACE =
// makeApi("/workspace/mgmt/create");
//
// /**
// * Gets a list of revisions for a particular file
// */
// public final Api<GetFileRevisions, GetFileRevisionsResponse> GET_FILE_REVISIONS =
// makeApi("/workspace/mgmt/getFileRevisions");
//
// /**
// * Gets a diff of a particular file.
// */
// public final Api<GetFileDiff, GetFileDiffResponse> GET_FILE_DIFF =
// makeApi("/workspace/mgmt/getFileDiff");
//
// /**
// * Notify the frontend that a tree conflict has been resolved.
// */
// public final Api<ResolveTreeConflict, ResolveTreeConflictResponse> RESOLVE_TREE_CONFLICT =
// makeApi("/workspace/mgmt/resolveTreeConflict");
//
// /**
// * Notify the frontend that a conflict chunk has been resolved.
// */
// public final Api<ResolveConflictChunk, ConflictChunkResolved> RESOLVE_CONFLICT_CHUNK =
// makeApi("/workspace/mgmt/resolveConflictChunk");
//
// /**
// * Retrieves code errors for a file.
// */
// public final Api<CodeErrorsRequest, CodeErrors> GET_CODE_ERRORS =
// makeApi("/workspace/code/CodeErrorsRequest");
//
// /**
// * Retrieves code parsing results.
// */
// public final Api<CodeGraphRequest, CodeGraphResponse> GET_CODE_GRAPH =
// makeApi("/workspace/code/CodeGraphRequest");
//
// /**
// * Gets a list of the templates that might seed new projects
// */
// public final Api<GetTemplates, GetTemplatesResponse> GET_TEMPLATES =
// makeApi("/project/getTemplates");
//
// /**
// * Loads a template into a workspace
// */
// public final Api<LoadTemplate, LoadTemplateResponse> LOAD_TEMPLATE =
// makeApi("/workspace/mgmt/loadTemplate");
//
// /**
// * Gets a list of the files that have changes in the workspace.
// */
// public final Api<GetWorkspaceChangeSummary, GetWorkspaceChangeSummaryResponse>
// GET_WORKSPACE_CHANGE_SUMMARY = makeApi("/workspace/mgmt/getWorkspaceChangeSummary");
//
// /**
// * Gets info about a specific set of workspaces.
// */
// public final Api<GetWorkspace, GetWorkspaceResponse> GET_WORKSPACES =
// makeApi("/workspace/mgmt/get");
//
// /**
// * Gets information about a project.
// */
// public final Api<GetProjectById, GetProjectByIdResponse> GET_PROJECT_BY_ID =
// makeApi("/project/getById");
//
// /**
// * Gets information about a user's projects.
// */
// public final Api<EmptyMessage, GetProjectsResponse> GET_PROJECTS_FOR_USER =
// makeApi("/project/getForUser");
//
// public final Api<SetActiveProject, EmptyMessage> SET_ACTIVE_PROJECT =
// makeApi("/settings/setActiveProject");
//
// public final Api<SetProjectHidden, EmptyMessage> SET_PROJECT_HIDDEN =
// makeApi("/settings/setProjectHidden");
//
// /**
// * Gets the information about the project that owns a particular workspace.
// */
// public final Api<GetOwningProject, GetOwningProjectResponse> GET_OWNING_PROJECT =
// makeApi("/project/getFromWsId");
//
// /**
// * Request to be a project member.
// */
// public final Api<RequestProjectMembership, EmptyMessage> REQUEST_PROJECT_MEMBERSHIP =
// makeApi("/project/requestProjectMembership");
//
// /**
// * Gets the list of project members, and users who requested project
// * membership.
// */
// public final Api<GetProjectMembers, GetProjectMembersResponse> GET_PROJECT_MEMBERS =
// makeApi("/project/getMembers");
//
// /**
// * Gets the list of workspace members.
// */
// public final Api<GetWorkspaceMembers, GetWorkspaceMembersResponse> GET_WORKSPACE_MEMBERS =
// makeApi("/workspace/mgmt/getMembers");
//
// /**
// * Gets the list of workspace participants.
// */
// public final Api<GetWorkspaceParticipants, GetWorkspaceParticipantsResponse>
// GET_WORKSPACE_PARTICIPANTS = makeApi("/workspace/act/getParticipants");
//
// /**
// * Add members to a project.
// */
// public final Api<AddProjectMembers, AddMembersResponse> ADD_PROJECT_MEMBERS =
// makeApi("/project/addProjectMembers");
//
// /**
// * Add members to a workspace.
// */
// public final Api<AddWorkspaceMembers, AddMembersResponse> ADD_WORKSPACE_MEMBERS =
// makeApi("/workspace/mgmt/addWorkspaceMembers");
//
// /**
// * Set the project role for a single user.
// */
// public final Api<SetProjectRole, SetRoleResponse> SET_PROJECT_ROLE =
// makeApi("/project/setProjectRole");
//
// /**
// * Set the workspace role for a single user.
// */
// public final Api<SetWorkspaceRole, SetRoleResponse> SET_WORKSPACE_ROLE =
// makeApi("/workspace/mgmt/setWorkspaceRole");
//
// /**
// * Log an exception to the server and potentially receive an unobfuscated
// * response.
// */
// public final Api<LogFatalRecord, LogFatalRecordResponse> LOG_REMOTE =
// makeApi("/logging/logFatal");
//
// /** Sends an ADD_FILE, ADD_DIR, COPY, MOVE, or DELETE tree mutation. */
// public final Api<WorkspaceTreeUpdate, WorkspaceTreeUpdateResponse> MUTATE_WORKSPACE_TREE =
// makeApi("/workspace/mgmt/mutateTree");
//
// // TODO: this may want to move to browser channel instead, for
// // search-as-you-type streaming. No sense to it yet until we have a real
// // backend, though.
// public final Api<Search, SearchResponse> SEARCH = makeApi("/workspace/mgmt/search");
//
// /** Updates the name and summary of a project. */
// public final Api<UpdateProject, EmptyMessage> UPDATE_PROJECT = makeApi("/project/updateProject");
//
// /** Requests that we get updated information about a workspace. */
// public final Api<UpdateWorkspace, EmptyMessage> UPDATE_WORKSPACE =
// makeApi("/workspace/mgmt/updateWorkspace");
//
// /** Requests that we get updated information about a workspace's run targets. */
// public final Api<UpdateWorkspaceRunTargets, EmptyMessage> UPDATE_WORKSPACE_RUN_TARGETS =
// makeApi("/workspace/mgmt/updateWorkspaceRunTargets");
//
// public final Api<GetUserAppEngineAppIds, GetUserAppEngineAppIdsResponse>
// GET_USER_APP_ENGINE_APP_IDS = makeApi("/settings/getUserAppEngineAppIds");
//
// public final Api<BeginUploadSession, EmptyMessage> BEGIN_UPLOAD_SESSION =
// makeApi("/uploadcontrol/beginUploadSession");
//
// public final Api<EndUploadSession, EmptyMessage> END_UPLOAD_SESSION =
// makeApi("/uploadcontrol/endUploadSession");
//
// public final Api<RetryAlreadyTransferredUpload, EmptyMessage> RETRY_ALREADY_TRANSFERRED_UPLOAD =
// makeApi("/uploadcontrol/retryAlreadyTransferredUpload");
//
// public final Api<EmptyMessage, GetStagingServerInfoResponse> GET_MIMIC_INFO =
// makeApi("/settings/getStagingServerInfo");
//
// public final Api<SetStagingServerAppId, EmptyMessage> SET_MIMIC_APP_ID =
// makeApi("/settings/setStagingServerAppId");
//
// public final Api<GetDeployInformation, GetDeployInformationResponse> GET_DEPLOY_INFORMATION =
// makeApi("/workspace/mgmt/getDeployInformation");
//
// public final Api<UpdateUserWorkspaceMetadata, EmptyMessage> UPDATE_USER_WORKSPACE_METADATA =
// makeApi("/settings/updateUserWorkspaceMetadata");
//
// public final Api<RecoverFromDroppedTangoInvalidation, RecoverFromDroppedTangoInvalidationResponse>
// RECOVER_FROM_DROPPED_INVALIDATION = makeApi("/payload/recover");
//
// /**
// * Deploy a workspace.
// */
// public final Api<DeployWorkspace, EmptyMessage> DEPLOY_WORKSPACE =
// makeApi("/workspace/act/DeployWorkspace");
///////////////////////////////
// END AVAILABLE FRONTEND APIS
///////////////////////////////
/**
* Generic mechanism for dealing with failed XHRs and responding to them in
* some sensible fashion.
*/
public interface XhrFailureHandler {
/**
* Returns whether or not the Client should continue retrying RPCs.
*/
boolean handleFailure(FrontendRestApi api, FailureReason failure, ServerError responseData);
}
/**
* Creates a FrontendApi and initializes it.
*/
public static FrontendRestApi create(MessageFilter messageFilter, final StatusManager statusManager) {
// Make a new FrontendApi with a failure recoverer that knows how to deal
// with XSRF token recovery.
FrontendRestApi frontendApi = new FrontendRestApi(messageFilter, new XhrFailureHandler() {
@Override
public boolean handleFailure(FrontendRestApi api, FailureReason failure, ServerError errorDto) {
switch (failure) {
case INVALID_XSRF_TOKEN:
// Update our XSRF token.
InvalidXsrfTokenServerError xsrfError = (InvalidXsrfTokenServerError) errorDto;
BootstrapSession.getBootstrapSession().setXsrfToken(xsrfError.getNewXsrfToken());
api.initCustomHeaders();
return true;
case CLIENT_FRONTEND_VERSION_SKEW:
// Display a message to the user that he needs to reload the client.
StatusMessage skewMsg = new StatusMessage(statusManager, MessageType.LOADING,
"A new version of Collide is available. Please Reload.");
skewMsg.setDismissable(false);
skewMsg.addAction(StatusMessage.RELOAD_ACTION);
skewMsg.fireDelayed(500);
return false;
case NOT_LOGGED_IN:
// Display a message to the user that he needs to reload the client.
StatusMessage loginMsg = new StatusMessage(statusManager, MessageType.LOADING,
"You have been signed out. Please reload to sign in.");
loginMsg.setDismissable(true);
loginMsg.addAction(StatusMessage.RELOAD_ACTION);
loginMsg.fireDelayed(500);
return false;
default:
// Allow the RPC retry logic to proceed.
return true;
}
}
});
frontendApi.initCustomHeaders();
return frontendApi;
}
private final MessageFilter messageFilter;
private final JsonStringMap<String> customHeaders = JsonCollections.createMap();
private final XhrFailureHandler recoverer;
public FrontendRestApi(MessageFilter messageFilter) {
this(messageFilter, null);
}
public FrontendRestApi(MessageFilter messageFilter, XhrFailureHandler recoverer) {
this.messageFilter = messageFilter;
this.recoverer = recoverer;
}
private void initCustomHeaders() {
addCustomHeader(FrontendConstants.CLIENT_BOOTSTRAP_ID_HEADER,
BootstrapSession.getBootstrapSession().getActiveClientId());
addCustomHeader(
FrontendConstants.XSRF_TOKEN_HEADER, BootstrapSession.getBootstrapSession().getXsrfToken());
addCustomHeader(FrontendConstants.CLIENT_VERSION_HASH_HEADER,
DtoClientImpls.CLIENT_SERVER_PROTOCOL_HASH);
}
/**
* Adds a custom header which is appended to every api request.
*/
public void addCustomHeader(String header, String value) {
customHeaders.put(header, value);
}
protected MessageFilter getMessageFilter() {
return messageFilter;
}
/**
* Makes an API given the URL.
*
* @param <REQ> the request object
* @param <RESP> the response object
*/
protected <REQ extends ClientToServerDto, RESP extends ServerToClientDto> Api<REQ, RESP> makeApi(
String url) {
return new ApiImpl<REQ, RESP>(url);
}
}
| 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/communication/RetryCallbackWithStatus.java | client/src/main/java/com/google/collide/client/communication/RetryCallbackWithStatus.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.communication;
import com.google.collide.client.communication.FrontendRestApi.RetryCallback;
import com.google.collide.client.status.StatusAction;
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.dto.ServerError.FailureReason;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import elemental.html.SpanElement;
/**
* A {@link RetryCallback} which also updates {@link StatusMessage}s as it goes.
*
*/
public class RetryCallbackWithStatus<T extends ServerToClientDto>
extends RetryCallback<T> {
private StatusManager manager;
private String messageText;
private StatusMessage pendingMessage;
/**
* Constructs a retry-with-status callback for a given trying-to-reload message.
*
* @param message text to display when retrying
*/
public RetryCallbackWithStatus(StatusManager statusManager, String message) {
this(statusManager, message, null);
}
/**
* Constructs a retrying callback with a given trying-to-reload message, but
* also managing a given operation-is-pending message (probably a deferred
* status for the first call).
*
* @param message text to display when retrying
* @param pending an already-fired message that should be cancelled when
* either a new message is needed, or when the operation completes.
*/
public RetryCallbackWithStatus(StatusManager statusManager, String message,
StatusMessage pending) {
manager = statusManager;
messageText = message;
pendingMessage = pending;
}
public void dismissMessage() {
if (pendingMessage != null) {
pendingMessage.cancel();
}
}
@Override
public void onFail(FailureReason reason) {
dismissMessage();
}
@Override
public void onMessageReceived(T message) {
dismissMessage();
}
@Override
protected void onRetry(int count, int milliseconds, final RepeatingCommand retryCmd) {
dismissMessage();
if (milliseconds > 2000) {
pendingMessage = new StatusMessage(manager,
MessageType.LOADING, messageText);
pendingMessage.addAction(new StatusAction() {
@Override
public void renderAction(SpanElement actionContainer) {
actionContainer.setTextContent("Retry now");
}
@Override
public void onAction() {
retryCmd.execute();
}
});
pendingMessage.expire(milliseconds);
pendingMessage.fire();
}
}
}
| 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/communication/MessageFilter.java | client/src/main/java/com/google/collide/client/communication/MessageFilter.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.communication;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.shared.JsonIntegerMap;
import com.google.collide.shared.util.JsonCollections;
/**
* Class responsible for routing JsonMessages based on the message type that get
* sent to the client from the server.
*
*/
public class MessageFilter {
/**
* Interface for receiving JSON messages.
*/
public interface MessageRecipient<T extends ServerToClientDto> {
void onMessageReceived(T message);
}
private final JsonIntegerMap<MessageRecipient<? extends ServerToClientDto>> messageRecipients =
JsonCollections.createIntegerMap();
/**
* Dispatches an incoming DTO message to a registered recipient.
*
* @param message
*/
public <T extends ServerToClientDto> void dispatchMessage(T message) {
@SuppressWarnings("unchecked")
MessageRecipient<T> recipient = (MessageRecipient<T>) messageRecipients.get(message.getType());
if (recipient != null) {
recipient.onMessageReceived(message);
}
}
/**
* Adds a MessageRecipient for a given message type.
*
* @param messageType
* @param recipient
*/
public void registerMessageRecipient(
int messageType, MessageRecipient<? extends ServerToClientDto> recipient) {
messageRecipients.put(messageType, recipient);
}
/**
* Removes any MessageRecipient registered for a given type.
*
* @param messageType
*/
public void removeMessageRecipient(int messageType) {
messageRecipients.erase(messageType);
}
}
| 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/communication/PushChannel.java | client/src/main/java/com/google/collide/client/communication/PushChannel.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.communication;
import java.util.ArrayList;
import java.util.List;
import com.google.collide.client.bootstrap.BootstrapSession;
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.clientlibs.vertx.VertxBus;
import com.google.collide.clientlibs.vertx.VertxBus.MessageHandler;
import com.google.collide.clientlibs.vertx.VertxBus.ReplyHandler;
import com.google.collide.clientlibs.vertx.VertxBus.ReplySender;
import com.google.collide.clientlibs.vertx.VertxBusImpl;
import com.google.collide.dtogen.client.RoutableDtoClientImpl;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.client.Jso;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerRegistrar;
import com.google.gwt.user.client.Timer;
import elemental.js.util.JsArrayOfString;
import elemental.js.util.JsMapFromStringTo;
/**
* A PushChannel abstraction on top of the {@link VertxBus}.
*
*/
public class PushChannel {
public interface Listener {
void onReconnectedSuccessfully();
}
public static PushChannel create(MessageFilter messageFilter, StatusManager statusManager) {
// If we do not have a valid client ID... bail.
if (BootstrapSession.getBootstrapSession().getActiveClientId() == null) {
StatusMessage fatal =
new StatusMessage(statusManager, MessageType.FATAL, "You are not logged in!");
fatal.addAction(StatusMessage.RELOAD_ACTION);
fatal.setDismissable(false);
fatal.fire();
return null;
}
VertxBus eventBus = VertxBusImpl.create();
PushChannel pushChannel = new PushChannel(eventBus, messageFilter, statusManager);
pushChannel.init();
return pushChannel;
}
private class DisconnectedTooLongTimer extends Timer {
private static final int DELAY_MS = 60 * 1000;
@Override
public void run() {
// reconnection effort failed.
StatusMessage fatal = new StatusMessage(
statusManager, MessageType.FATAL, "Lost communication with the server.");
fatal.addAction(StatusMessage.RELOAD_ACTION);
fatal.setDismissable(false);
fatal.fire();
}
void schedule() {
//TODO(james) fire an event to display that we are not connected.
schedule(DELAY_MS);
}
}
private class QueuedMessage {
final String address;
final String msg;
final ReplyHandler replyHandler;
QueuedMessage(String address, String msg, ReplyHandler replyHandler) {
this.address = address;
this.msg = msg;
this.replyHandler = replyHandler;
}
}
private final ListenerManager<PushChannel.Listener> listenerManager = ListenerManager.create();
private final DisconnectedTooLongTimer disconnectedTooLongTimer = new DisconnectedTooLongTimer();
private final VertxBus.ConnectionListener connectionListener = new VertxBus.ConnectionListener() {
private boolean hasReceivedOnDisconnected;
private VertxBus.MessageHandler messageHandler = null;
@Override
public void onOpen() {
// Lazily initialize the messageHandler and register to handle messages.
if (messageHandler == null) {
messageHandler = new VertxBus.MessageHandler() {
@Override
public void onMessage(String message, ReplySender replySender) {
ServerToClientDto dto =
(ServerToClientDto) Jso.deserialize(message).<RoutableDtoClientImpl>cast();
messageFilter.dispatchMessage(dto);
}
};
eventBus.register(
"client." + BootstrapSession.getBootstrapSession().getActiveClientId(), messageHandler);
JsArrayOfString keys = queuedReceivers.keys();
for (int i = keys.length();i-->0;){
String key = keys.get(i);
MessageHandler receiver = queuedReceivers.get(key);
if (null!=receiver)
eventBus.register(key, receiver);
}
}
// Notify listeners who handle reconnections.
if (hasReceivedOnDisconnected) {
disconnectedTooLongTimer.cancel();
listenerManager.dispatch(new ListenerManager.Dispatcher<PushChannel.Listener>() {
@Override
public void dispatch(PushChannel.Listener listener) {
listener.onReconnectedSuccessfully();
}
});
hasReceivedOnDisconnected = false;
}
// Drain any messages that came in while the channel was not open.
for (QueuedMessage msg : queuedMessages) {
eventBus.send(msg.address, msg.msg, msg.replyHandler);
}
queuedMessages.clear();
}
@Override
public void onClose() {
hasReceivedOnDisconnected = true;
disconnectedTooLongTimer.schedule();
}
};
private final MessageFilter messageFilter;
private final StatusManager statusManager;
private final VertxBus eventBus;
private final List<QueuedMessage> queuedMessages = new ArrayList<QueuedMessage>();
private final JsMapFromStringTo<MessageHandler> queuedReceivers = JsMapFromStringTo.<MessageHandler>create();
private PushChannel(VertxBus eventBus, MessageFilter messageFilter, StatusManager statusManager) {
this.eventBus = eventBus;
this.messageFilter = messageFilter;
this.statusManager = statusManager;
}
private void init() {
eventBus.setOnOpenCallback(connectionListener);
eventBus.setOnCloseCallback(connectionListener);
}
/**
* Listens to all messages published to a given address.
* This is NOT secure, but can be very useful for keeping all collaborators updated.
*/
public void receive(String address, MessageHandler listener) {
if (eventBus.getReadyState() != VertxBus.OPEN) {
Log.debug(PushChannel.class,
"Tried to add a message receiver on address " +
address+ " before vertx was initialized");
queuedReceivers.put(address,listener);
return;
}
eventBus.register(address, listener);
}
/**
* Sends a message to an address, providing a replyHandler.
*/
public void send(String address, String message, ReplyHandler replyHandler) {
if (eventBus.getReadyState() != VertxBus.OPEN) {
Log.debug(PushChannel.class,
"Message sent to '" + address + "' while channel was disconnected: " + message);
queuedMessages.add(new QueuedMessage(address, message, replyHandler));
return;
}
eventBus.send(address, message, replyHandler);
}
/**
* Sends a message to an address, providing a replyHandler.
*/
public void request(String address, ReplyHandler replyHandler) {
if (eventBus.getReadyState() != VertxBus.OPEN) {
Log.debug(PushChannel.class,
"Data requested from '" + address + "' while channel was disconnected.");
queuedMessages.add(new QueuedMessage(address, null, replyHandler));
return;
}
eventBus.send(address, null, replyHandler);
}
/**
* Sends a message to an address.
*/
public void send(String address, String message) {
send(address, message, null);
}
public ListenerRegistrar<PushChannel.Listener> getListenerRegistrar() {
return listenerManager;
}
}
| 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/communication/FrontendApi.java | client/src/main/java/com/google/collide/client/communication/FrontendApi.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.communication;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.util.logging.Log;
import com.google.collide.clientlibs.vertx.VertxBus.ReplyHandler;
import com.google.collide.dto.ClientToServerDocOp;
import com.google.collide.dto.CodeErrors;
import com.google.collide.dto.CodeErrorsRequest;
import com.google.collide.dto.CodeGraphRequest;
import com.google.collide.dto.CodeGraphResponse;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.EmptyMessage;
import com.google.collide.dto.GetDirectory;
import com.google.collide.dto.GetDirectoryResponse;
import com.google.collide.dto.GetFileContents;
import com.google.collide.dto.GetFileContentsResponse;
import com.google.collide.dto.GetFileRevisions;
import com.google.collide.dto.GetFileRevisionsResponse;
import com.google.collide.dto.GetRunConfig;
import com.google.collide.dto.GetRunConfigResponse;
import com.google.collide.dto.GetWorkspaceMetaData;
import com.google.collide.dto.GetWorkspaceMetaDataResponse;
import com.google.collide.dto.GetWorkspaceParticipants;
import com.google.collide.dto.GetWorkspaceParticipantsResponse;
import com.google.collide.dto.GwtCompile;
import com.google.collide.dto.GwtKill;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.GwtSettings;
import com.google.collide.dto.HasModule;
import com.google.collide.dto.KeepAlive;
import com.google.collide.dto.LogFatalRecord;
import com.google.collide.dto.LogFatalRecordResponse;
import com.google.collide.dto.RecoverFromMissedDocOps;
import com.google.collide.dto.RecoverFromMissedDocOpsResponse;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.Search;
import com.google.collide.dto.SearchResponse;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.ServerToClientDocOps;
import com.google.collide.dto.SetMavenConfig;
import com.google.collide.dto.UpdateWorkspaceRunTargets;
import com.google.collide.dto.WorkspaceTreeUpdate;
import com.google.collide.dto.client.DtoClientImpls.ServerErrorImpl;
import com.google.collide.dto.shared.JsonFieldConstants;
import com.google.collide.dtogen.client.RoutableDtoClientImpl;
import com.google.collide.dtogen.shared.ClientToServerDto;
import com.google.collide.dtogen.shared.RoutableDto;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.client.Jso;
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.common.annotations.VisibleForTesting;
/**
* The EventBus APIs for the Collide server.
*
* See {@package com.google.collide.dto} for data objects.
*
*/
public class FrontendApi {
/**
* EventBus API that documents the message types sent to the frontend. This API is fire and
* forget, since it does not expect a response.
*
* @param <REQ> The outgoing message type.
*/
public static interface SendApi<REQ extends ClientToServerDto> {
public void send(REQ msg);
}
/**
* EventBus API that documents the message types sent to the frontend. This API is fire and
* forget, since it does not expect a response.
*
* @param <RESP> The outgoing message type.
*/
public static interface ReceiveApi<RESP extends ServerToClientDto> {
public void request(final ApiCallback<RESP> msg);
}
/**
* EventBus API that documents the message types sent to the frontend, and the message type
* expected to be returned as a response.
*
* @param <REQ> The outgoing message type.
* @param <RESP> The incoming message type.
*/
public static interface RequestResponseApi<
REQ extends ClientToServerDto, RESP extends ServerToClientDto> {
public void send(REQ msg, final ApiCallback<RESP> callback);
}
/**
* Callback interface for receiving a matched response for requests to a frontend API.
*/
public interface ApiCallback<T extends ServerToClientDto> extends MessageRecipient<T> {
void onFail(FailureReason reason);
}
@VisibleForTesting
protected class ApiImpl<REQ extends ClientToServerDto, RESP extends ServerToClientDto>
implements
RequestResponseApi<REQ, RESP>,
SendApi<REQ>,
ReceiveApi<RESP>{
private final String address;
protected ApiImpl(String address) {
this.address = address;
}
@Override
public void send(REQ msg) {
RoutableDtoClientImpl messageImpl = (RoutableDtoClientImpl) msg;
addCustomFields(messageImpl);
pushChannel.send(address, messageImpl.serialize());
}
@Override
public void send(REQ msg, final ApiCallback<RESP> callback) {
RoutableDtoClientImpl messageImpl = (RoutableDtoClientImpl) msg;
addCustomFields(messageImpl);
pushChannel.send(address, messageImpl.serialize(), new ReplyHandler() {
@Override
public void onReply(String message) {
Jso jso = Jso.deserialize(message);
Log.debug(getClass(), "sent message: "+ message);
if (RoutingTypes.SERVERERROR == jso.getIntField(RoutableDto.TYPE_FIELD)) {
ServerErrorImpl serverError = (ServerErrorImpl) jso;
callback.onFail(serverError.getFailureReason());
return;
}
ServerToClientDto messageDto = (ServerToClientDto) jso;
@SuppressWarnings("unchecked")
RESP resp = (RESP) messageDto;
callback.onMessageReceived(resp);
}
});
}
@Override
public void request(final ApiCallback<RESP> callback) {
Log.debug(getClass(), "Performing request on address "+address);
pushChannel.request(address, new ReplyHandler() {
@Override
public void onReply(String message) {
Log.debug(getClass(), "received message: "+message);
Jso jso = Jso.deserialize(message);
if (RoutingTypes.SERVERERROR == jso.getIntField(RoutableDto.TYPE_FIELD)) {
ServerErrorImpl serverError = (ServerErrorImpl) jso;
callback.onFail(serverError.getFailureReason());
return;
}
ServerToClientDto messageDto = (ServerToClientDto) jso;
@SuppressWarnings("unchecked")
RESP resp = (RESP) messageDto;
callback.onMessageReceived(resp);
}
});
}
private void addCustomFields(final RoutableDtoClientImpl messageImpl) {
customHeaders.iterate(new IterationCallback<String>() {
@Override
public void onIteration(String header, String value) {
messageImpl.<Jso>cast().addField(header, value);
}
});
}
}
// ///////////////////////////////
// BEGIN AVAILABLE FRONTEND APIS
// ///////////////////////////////
/*
* IMPORTANT!
*
* By convention (and ignore the entries that ignore this convention :) ) we try to have
* GetDto/ResponseDto pairs for each unique servlet path. This helps us guard against
* client/frontend API version skew via a simple hash of all of the DTO messages.
*
* So if you add a new Servlet Path, please also add a new Get/Response Dto pair.
*/
public final RequestResponseApi<ClientToServerDocOp, ServerToClientDocOps> MUTATE_FILE =
makeApi("documents.mutate");
/**
* Lets a client re-synchronize with the server's version of a file after being offline or missing
* a doc op broadcast.
*/
public final RequestResponseApi<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse>
RECOVER_FROM_MISSED_DOC_OPS = makeApi("documents.recoverMissedDocop");
/**
* Get the contents of a file and provisions an edit session so that it can be edited.
*/
public final RequestResponseApi<GetFileContents, GetFileContentsResponse> GET_FILE_CONTENTS =
makeApi("documents.createEditSession");
/**
* Get the revisions for a file to enable reversioning.
*/
public final RequestResponseApi<GetFileRevisions, GetFileRevisionsResponse> GET_FILE_REVISIONS =
makeApi("documents.getRevisions");
/**
* Get a subdirectory. Just the subtree rooted at that path. No associated meta data.
*/
public final RequestResponseApi<GetDirectory, GetDirectoryResponse> GET_DIRECTORY =
makeApi("tree.get");
/** Sends an ADD_FILE, ADD_DIR, COPY, MOVE, or DELETE tree mutation. */
public final RequestResponseApi<WorkspaceTreeUpdate, EmptyMessage>
MUTATE_WORKSPACE_TREE = makeApi("tree.mutate");
/**
* Send a keep-alive for the client in a workspace.
*/
public final SendApi<KeepAlive> KEEP_ALIVE = makeApi("participants.keepAlive");
/**
* Gets the list of workspace participants.
*/
public final RequestResponseApi<GetWorkspaceParticipants, GetWorkspaceParticipantsResponse>
GET_WORKSPACE_PARTICIPANTS = makeApi("participants.getParticipants");
/** Requests that we get updated information about a workspace's run targets. */
public final SendApi<UpdateWorkspaceRunTargets> UPDATE_WORKSPACE_RUN_TARGETS =
makeApi("workspace.updateRunTarget");
/** Requests workspace state like the last opened files and run targets. */
public final RequestResponseApi<GetWorkspaceMetaData, GetWorkspaceMetaDataResponse>
GET_WORKSPACE_META_DATA = makeApi("workspace.getMetaData");
/**
* Retrieves code errors for a file.
*/
public final RequestResponseApi<CodeErrorsRequest, CodeErrors> GET_CODE_ERRORS =
makeApi("todo.implementMe");
/**
* Updates a maven config
*/
public final SendApi<SetMavenConfig> SET_MAVEN_CONFIG =
makeApi("maven.save");
// public final RequestResponseApi<SetMavenConfig,MavenConfig> SET_MAVEN_CONFIG =
// makeApi("maven.save");
public final RequestResponseApi<GetRunConfig, GetRunConfigResponse> GET_RUN_CONFIG =
makeApi("run.get");
// public final RequestResponseApi<GetRunConfig,GwtStatus> COMPILE_GWT =
// makeApi("gwt.compile");
public final RequestResponseApi<GwtCompile,GwtCompile> TEST_GWT =
makeApi("gwt.test");
public final RequestResponseApi<GwtCompile,CompileResponse> COMPILE_GWT =
makeApi("gwt.compile");
public final RequestResponseApi<GwtRecompile,CompileResponse> RE_COMPILE_GWT =
makeApi("gwt.recompile");
public final RequestResponseApi<GwtKill, CompileResponse> KILL_GWT =
makeApi("gwt.kill");
public final ReceiveApi<GwtSettings> GWT_SETTINGS =
makeApi("gwt.settings");
public final SendApi<GwtRecompile> GWT_SAVE =
makeApi("gwt.save");
public final RequestResponseApi<HasModule, GwtRecompile> GWT_LOAD =
makeApi("gwt.load");
/**
* Retrieves code parsing results.
*/
public final RequestResponseApi<CodeGraphRequest, CodeGraphResponse> GET_CODE_GRAPH =
makeApi("codegraph.get");
/**
* Log an exception to the server and potentially receive an unobfuscated response.
*/
public final RequestResponseApi<LogFatalRecord, LogFatalRecordResponse> LOG_REMOTE =
makeApi("todo.implementMe");
// TODO: this may want to move to browser channel instead, for
// search-as-you-type streaming. No sense to it yet until we have a real
// backend, though.
public final RequestResponseApi<Search, SearchResponse> SEARCH = makeApi("todo.implementMe");
// /////////////////////////////
// END AVAILABLE FRONTEND APIS
// /////////////////////////////
/**
* Creates a FrontendApi and initializes it.
*/
public static FrontendApi create(PushChannel pushChannel, StatusManager statusManager) {
FrontendApi frontendApi = new FrontendApi(pushChannel, statusManager);
frontendApi.initCustomFields();
return frontendApi;
}
private final JsonStringMap<String> customHeaders = JsonCollections.createMap();
private final PushChannel pushChannel;
private final StatusManager statusManager;
public FrontendApi(PushChannel pushChannel, StatusManager statusManager) {
this.pushChannel = pushChannel;
this.statusManager = statusManager;
}
private void initCustomFields() {
customHeaders.put(
JsonFieldConstants.SESSION_USER_ID, BootstrapSession.getBootstrapSession().getUserId());
}
/**
* Makes an API given the URL.
*
* @param <REQ> the request object
* @param <RESP> the response object
*/
protected <
REQ extends ClientToServerDto, RESP extends ServerToClientDto> ApiImpl<REQ, RESP> makeApi(
String url) {
return new ApiImpl<REQ, RESP>(url);
}
}
| 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/communication/ResourceUriUtils.java | client/src/main/java/com/google/collide/client/communication/ResourceUriUtils.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.communication;
import com.google.collide.client.util.PathUtil;
import elemental.client.Browser;
import elemental.html.Location;
/**
* Utility class to work with resource URIs and local paths.
*
*/
public class ResourceUriUtils {
/**
* @see #getAbsoluteResourceUri(String)
*/
public static String getAbsoluteResourceUri(PathUtil path) {
return getAbsoluteResourceUri(path.getPathString());
}
/**
* Calculates an absolute URI of a resource by a given path.
*
* @param path relative path from the workspace root
* @return an absolute URI
*/
public static String getAbsoluteResourceUri(String path) {
return getAbsoluteResourceBaseUri() + ensurePrefixSlash(path);
}
public static String getAbsoluteResourceBaseUri() {
return getBaseUri() + "/res";
}
private static String getBaseUri() {
Location location = Browser.getWindow().getLocation();
return location.getProtocol() + "//" + location.getHost();
}
public static String extractBaseUri(String absoluteUri) {
int pos = absoluteUri.indexOf("://");
if (pos != -1) {
pos += 3;
} else {
pos = 0;
}
pos = absoluteUri.indexOf("/", pos);
if (pos != -1) {
return absoluteUri.substring(0, pos);
} else {
return absoluteUri;
}
}
private static String ensurePrefixSlash(String path) {
if (path.startsWith("/")) {
return path;
}
return "/" + path;
}
}
| 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/logging/LogView.java | client/src/main/java/com/google/collide/client/logging/LogView.java | package com.google.collide.client.logging;
public class LogView {
}
| 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/documentparser/ParseResult.java | client/src/main/java/com/google/collide/client/documentparser/ParseResult.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.documentparser;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* POJO that holds parser state and token array.
*
* <p>This object represents line parsing results:
* array of tokens produced by parser and
* parser state when parsing is finished.
*
* @param <T> actual {@link State} type.
*
*/
public class ParseResult<T extends State> {
private final JsonArray<Token> tokens;
private final T state;
@VisibleForTesting
public ParseResult(JsonArray<Token> tokens, T state) {
Preconditions.checkNotNull(tokens, "tokens");
Preconditions.checkNotNull(state, "state");
this.tokens = tokens;
this.state = state;
}
public JsonArray<Token> getTokens() {
return tokens;
}
public T 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/documentparser/DocumentParserWorker.java | client/src/main/java/com/google/collide/client/documentparser/DocumentParserWorker.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.documentparser;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.collide.client.util.logging.Log;
import com.google.collide.codemirror2.Parser;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.Stream;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
/**
* Worker that performs the actual parsing of the document by delegating to
* CodeMirror.
*
*/
class DocumentParserWorker {
private static final int LINE_LENGTH_LIMIT = 1000;
private static class ParserException extends Exception {
/**
*
*/
private static final long serialVersionUID = 6948743423268020824L;
ParserException(Throwable t) {
super(t);
}
}
private interface ParsedTokensRecipient {
void onTokensParsed(Line line, int lineNumber, @Nonnull JsonArray<Token> tokens);
}
private static final String LINE_TAG_END_OF_LINE_PARSER_STATE_SNAPSHOT =
DocumentParserWorker.class.getName() + ".endOfLineParserStateSnapshot";
private final Parser codeMirrorParser;
private final DocumentParser documentParser;
private final ParsedTokensRecipient documentParserDispatcher = new ParsedTokensRecipient() {
@Override
public void onTokensParsed(Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) {
documentParser.dispatch(line, lineNumber, tokens);
}
};
DocumentParserWorker(DocumentParser documentParser, Parser codeMirrorParser) {
this.documentParser = documentParser;
this.codeMirrorParser = codeMirrorParser;
}
/**
* Parses the given lines and updates the parser position {@code anchorToUpdate}.
*
* @return {@code true} is parsing should continue
*/
boolean parse(Line line, int lineNumber, int numLinesToProcess, Anchor anchorToUpdate) {
return parseImplCm2(line, lineNumber, numLinesToProcess, anchorToUpdate,
documentParserDispatcher);
}
/**
* @param lineNumber the line number of {@code line}. This can be -1 if
* {@code anchorToUpdate} is null
* @param anchorToUpdate the optional anchor that this method will update
*/
private boolean parseImplCm2(Line line, int lineNumber, int numLinesToProcess,
@Nullable Anchor anchorToUpdate, ParsedTokensRecipient tokensRecipient) {
State parserState = loadParserStateForBeginningOfLine(line);
if (parserState == null) {
return false;
}
Line previousLine = line.getPreviousLine();
for (int numLinesProcessed = 0; line != null && numLinesProcessed < numLinesToProcess;) {
State stateToSave = parserState;
if (line.getText().length() > LINE_LENGTH_LIMIT) {
// Save the initial state instead of state at the end of line.
stateToSave = parserState.copy(codeMirrorParser);
}
JsonArray<Token> tokens;
try {
tokens = parseLine(parserState, line.getText());
} catch (ParserException e) {
Log.error(getClass(), "Could not parse line:", line, e);
return false;
}
// Restore the initial line state if it was preserved.
parserState = stateToSave;
saveEndOfLineParserState(line, parserState);
tokensRecipient.onTokensParsed(line, lineNumber, tokens);
previousLine = line;
line = line.getNextLine();
numLinesProcessed++;
if (lineNumber != -1) {
lineNumber++;
}
}
if (anchorToUpdate != null) {
if (lineNumber == -1) {
throw new IllegalArgumentException("lineNumber cannot be -1 if anchorToUpdate is given");
}
if (line != null) {
line.getDocument().getAnchorManager()
.moveAnchor(anchorToUpdate, line, lineNumber, AnchorManager.IGNORE_COLUMN);
} else {
previousLine.getDocument().getAnchorManager()
.moveAnchor(anchorToUpdate, previousLine, lineNumber - 1, AnchorManager.IGNORE_COLUMN);
}
}
return line != null;
}
private void debugPrintTokens(JsonArray<Token> tokens) {
StringBuilder buffer = new StringBuilder();
for (Token token : tokens.asIterable()) {
if (TokenType.NEWLINE != token.getType()) {
buffer
.append("[").append(token.getValue())
.append("|").append(token.getType())
.append("|").append(token.getMode())
.append("]");
}
}
Log.warn(getClass(), buffer.toString());
}
/**
* @return the parsed tokens, or {@code null} if the line could not be parsed
* because there isn't a snapshot and it's not the first line
*/
JsonArray<Token> parseLine(Line line) {
class TokensRecipient implements ParsedTokensRecipient {
JsonArray<Token> tokens;
@Override
public void onTokensParsed(Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) {
this.tokens = tokens;
}
}
TokensRecipient tokensRecipient = new TokensRecipient();
parseImplCm2(line, -1, 1, null, tokensRecipient);
return tokensRecipient.tokens;
}
int getIndentation(Line line) {
State stateBefore = loadParserStateForBeginningOfLine(line);
String textAfter = line.getText();
textAfter = textAfter.substring(StringUtils.lengthOfStartingWhitespace(textAfter));
return codeMirrorParser.indent(stateBefore, textAfter);
}
/**
* Create a copy of a parser state corresponding to the beginning of
* the given line.
*
* <p>Actually, the state we are looking for is a final state of
* parser after processing the previous line, since codemirror parsers are
* line-based.
*
* <p>Parser state for the first line is a default parser state.
*
* <p>We always return a copy to avoid changes to persisted state.
*
* @return copy of corresponding parser state, or {@code null} if the state
* if not known yet (previous line wasn't parsed).
*/
private <T extends State> T loadParserStateForBeginningOfLine(TaggableLine line) {
State state;
if (line.isFirstLine()) {
state = codeMirrorParser.defaultState();
} else {
state = line.getPreviousLine().getTag(LINE_TAG_END_OF_LINE_PARSER_STATE_SNAPSHOT);
state = (state == null) ? null : state.copy(codeMirrorParser);
}
@SuppressWarnings("unchecked")
T result = (T) state;
return result;
}
/**
* Calculates mode at the beginning of line.
*
* @see #loadParserStateForBeginningOfLine
*/
@Nullable
String getInitialMode(@Nonnull TaggableLine line) {
State state = loadParserStateForBeginningOfLine(line);
if (state == null) {
return null;
}
return codeMirrorParser.getName(state);
}
private void saveEndOfLineParserState(Line line, State parserState) {
State copiedParserState = parserState.copy(codeMirrorParser);
line.putTag(LINE_TAG_END_OF_LINE_PARSER_STATE_SNAPSHOT, copiedParserState);
}
/**
* Parse line text and return tokens.
*
* <p>New line char at the end of line is transformed to newline token.
*/
@Nonnull
private JsonArray<Token> parseLine(State parserState, String lineText) throws ParserException {
boolean endsWithNewline = lineText.endsWith("\n");
lineText = endsWithNewline ? lineText.substring(0, lineText.length() - 1) : lineText;
String tail = null;
if (lineText.length() > LINE_LENGTH_LIMIT) {
tail = lineText.substring(LINE_LENGTH_LIMIT);
lineText = lineText.substring(0, LINE_LENGTH_LIMIT);
}
try {
Stream stream = codeMirrorParser.createStream(lineText);
JsonArray<Token> tokens = JsonCollections.createArray();
while (!stream.isEnd()) {
codeMirrorParser.parseNext(stream, parserState, tokens);
}
if (tail != null) {
tokens.add(new Token(codeMirrorParser.getName(parserState), TokenType.ERROR, tail));
}
if (endsWithNewline) {
tokens.add(Token.NEWLINE);
}
return tokens;
} catch (Throwable t) {
throw new ParserException(t);
}
}
/**
* Parse given line to the given column (optionally appending the given text)
* and return result containing final parsing state and list of produced
* tokens.
*
* @param appendedText {@link String} to be appended after a cursor position;
* if {@code null} then nothing is appended.
* @return {@code null} if it is currently impossible to parse.
*/
<T extends State> ParseResult<T> getParserState(
Position position, @Nullable String appendedText) {
Line line = position.getLine();
T parserState = loadParserStateForBeginningOfLine(line);
if (parserState == null) {
return null;
}
String lineText = line.getText().substring(0, position.getColumn());
if (appendedText != null) {
lineText = lineText + appendedText;
}
JsonArray<Token> tokens;
try {
tokens = parseLine(parserState, lineText);
return new ParseResult<T>(tokens, parserState);
} catch (ParserException e) {
Log.error(getClass(), "Could not parse line:", line, e);
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/documentparser/DocumentParser.java | client/src/main/java/com/google/collide/client/documentparser/DocumentParser.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.documentparser;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.collide.client.util.BasicIncrementalScheduler;
import com.google.collide.client.util.IncrementalScheduler;
import com.google.collide.client.util.UserActivityManager;
import com.google.collide.codemirror2.Parser;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.document.TextChange;
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.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.ListenerRegistrar.Remover;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* Parser for a document that delegates to CodeMirror.
*
* This class attaches to a document and re-parses whenever the contents
* changes. It uses an incremental parser allowing it to resume parsing from the
* beginning of the changed line.
*
*/
public class DocumentParser {
public static DocumentParser create(Document document, Parser codeMirrorParser,
UserActivityManager userActivityManager) {
/*
* Guess that parsing 300 lines takes 50ms, let scheduler balance actual
* parsing time per machine.
*/
BasicIncrementalScheduler scheduler = new BasicIncrementalScheduler(
userActivityManager, 50, 300);
return create(document, codeMirrorParser, scheduler);
}
@VisibleForTesting
public static DocumentParser create(Document document, Parser codeMirrorParser,
IncrementalScheduler scheduler) {
return new DocumentParser(document, codeMirrorParser, scheduler);
}
/**
* A listener that receives a callback as lines of the document get parsed.
* Can be called synchronously with user keyboard interactions
* or asynchronously in batch mode, parsing a few lines in a row.
*/
public interface Listener {
/**
* This method is called to mark the start of asynchronous parsing
* iteration.
*
* @param lineNumber number of a line iteration started from
*/
void onIterationStart(int lineNumber);
/**
* This method is called to mark the finish of asynchronous parsing
* iteration.
*/
void onIterationFinish();
/**
* Note: This may be called synchronously with a user's key press, so do not
* do too much work synchronously.
*/
void onDocumentLineParsed(Line line, int lineNumber, @Nonnull JsonArray<Token> tokens);
}
private static final AnchorType PARSER_ANCHOR_TYPE = AnchorType.create(DocumentParser.class,
"parser");
private Anchor createParserPosition(Document document) {
Anchor position =
document.getAnchorManager().createAnchor(PARSER_ANCHOR_TYPE, document.getFirstLine(), 0,
AnchorManager.IGNORE_COLUMN);
position.setRemovalStrategy(RemovalStrategy.SHIFT);
return position;
}
private final Parser codeMirrorParser;
private final Document.TextListener documentTextListener = new Document.TextListener() {
@Override
public void onTextChange(Document document, JsonArray<TextChange> textChanges) {
/*
* Tracks the earliest change in the document, so that can be used as a
* starting point for the parser
*/
Line earliestLine = parserPosition.getLine();
int earliestLineNumber = parserPosition.getLineNumber();
for (int i = 0, n = textChanges.size(); i < n; i++) {
TextChange textChange = textChanges.get(i);
Line line = textChange.getLine();
int lineNumber = textChange.getLineNumber();
if (lineNumber < earliestLineNumber) {
earliestLine = line;
earliestLineNumber = lineNumber;
}
// Synchronously parse this line
worker.parse(line, lineNumber, 1, null);
}
// Queue the earliest
document.getAnchorManager().moveAnchor(
parserPosition, earliestLine, earliestLineNumber, AnchorManager.IGNORE_COLUMN);
scheduler.schedule(parserTask);
}
};
private final ListenerManager<Listener> listenerManager;
private final Anchor parserPosition;
private final IncrementalScheduler.Task parserTask = new IncrementalScheduler.Task() {
@Override
public boolean run(int workAmount) {
return executeWorker(workAmount);
}
};
private final IncrementalScheduler scheduler;
private final DocumentParserWorker worker;
private final Remover textListenerRemover;
private DocumentParser(
Document document, Parser codeMirrorParser, IncrementalScheduler scheduler) {
Preconditions.checkNotNull(codeMirrorParser);
Preconditions.checkNotNull(scheduler);
this.codeMirrorParser = codeMirrorParser;
this.listenerManager = ListenerManager.create();
this.scheduler = scheduler;
this.worker = new DocumentParserWorker(this, codeMirrorParser);
this.parserPosition = createParserPosition(document);
this.textListenerRemover = document.getTextListenerRegistrar().add(documentTextListener);
}
/**
* Schedules the parsing of the document from the last parsed position, or the
* beginning of the document if this is the first time parsing.
*/
public void begin() {
scheduler.schedule(parserTask);
}
public ListenerRegistrar<Listener> getListenerRegistrar() {
return listenerManager;
}
/**
* Parses the given line synchronously, returning the tokens on the line.
*
* <p>This will NOT schedule parsing of subsequent lines.
*
* @return the parsed tokens, or {@code null} if there isn't a snapshot
* and it's not the first line
*/
@Nullable
public JsonArray<Token> parseLineSync(@Nonnull Line line) {
return worker.parseLine(line);
}
/**
* @return true if this parser mode supports smart indentation
*/
public boolean hasSmartIndent() {
return codeMirrorParser.hasSmartIndent();
}
/**
* Return the indentation for this line, based upon the line above it.
*/
public int getIndentation(Line line) {
return worker.getIndentation(line);
}
public void teardown() {
parserPosition.getLine().getDocument().getAnchorManager().removeAnchor(parserPosition);
textListenerRemover.remove();
scheduler.teardown();
}
void dispatchIterationStart(final int lineNumber) {
listenerManager.dispatch(new Dispatcher<Listener>() {
@Override
public void dispatch(Listener listener) {
listener.onIterationStart(lineNumber);
}
});
}
void dispatchIterationFinish() {
listenerManager.dispatch(new Dispatcher<Listener>() {
@Override
public void dispatch(Listener listener) {
listener.onIterationFinish();
}
});
}
void dispatch(final Line line, final int lineNumber, @Nonnull final JsonArray<Token> tokens) {
listenerManager.dispatch(new Dispatcher<Listener>() {
@Override
public void dispatch(Listener listener) {
listener.onDocumentLineParsed(line, lineNumber, tokens);
}
});
}
private boolean executeWorker(int workAmount) {
dispatchIterationStart(parserPosition.getLineNumber());
boolean result = worker.parse(parserPosition.getLine(), parserPosition.getLineNumber(),
workAmount, parserPosition);
dispatchIterationFinish();
return result;
}
public SyntaxType getSyntaxType() {
return codeMirrorParser.getSyntaxType();
}
/**
* Checks if line has been parsed since last changes (in this line or
* in lines above it).
*
* @param lineNumber number of line to check
* @return {@code true} if line is to be parsed.
*/
public boolean isLineDirty(int lineNumber) {
// Without this check last line never becomes "clean".
if (!scheduler.isBusy()) {
return false;
}
return parserPosition.getLineNumber() <= lineNumber;
}
/**
* Calculates parser mode at the beginning of line.
*
* @return {@code null} if previous line is not parsed yet
*/
@Nullable
public String getInitialMode(@Nonnull TaggableLine line) {
return worker.getInitialMode(line);
}
/**
* Synchronously parse beginning of the line and safely cast resulting state.
*
* <p>It is explicitly checked that current syntax type corresponds to
* specified state class.
*
* If the parser hasn't asynchronously reached previous line (may be it is
* appeared too recently) then {@code null} is returned.
*
* @see DocumentParserWorker#getParserState
*/
public <T extends State> ParseResult<T> getState(Class<T> stateClass, Position position,
@Nullable String appendedText) {
Preconditions.checkArgument(getSyntaxType().checkStateClass(stateClass));
Preconditions.checkNotNull(position);
return worker.getParserState(position, appendedText);
}
}
| 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/documentparser/AsyncParser.java | client/src/main/java/com/google/collide/client/documentparser/AsyncParser.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.documentparser;
import javax.annotation.Nonnull;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* An adapter for {@link DocumentParser.Listener} that performs only async
* parsing while collecting some line-dependent data.
*/
public abstract class AsyncParser<T extends AsyncParser.LineAware>
implements DocumentParser.Listener {
/**
* Data item base interface. It is important that they are associated with
* lines because we clear data for lines that are invalidated and need to
* be parsed again.
*/
public static interface LineAware {
/**
* @return line number this data belongs to
*/
int getLineNumber();
}
/**
* Called before parsing has started.
*/
protected void onBeforeParse() {}
/**
* Called when the data parsed earlier is discarded. Implementations
* should clear everything associated with this data. This method may
* be called on any time and should not depend on parsing cycle state.
*
* @param cleanedData data items that will be deleted
*/
protected void onCleanup(JsonArray<T> cleanedData) {}
/**
* Called when a line is being parsed. This is guaranteed to be called after
* {@link #onBeforeParse} and before {@link #onAfterParse}.
*
* @param line line being parsed
* @param lineNumber line number being parsed
* @param tokens tokens collected on the line
*/
protected void onParseLine(Line line, int lineNumber, JsonArray<Token> tokens) {}
/**
* Called just after chunk parsing has finished. This does not mean that
* parsing for the whole file has finished. You have to use what you get
* here.
*
* @param nodes resulting array of all nodes collected so far for the whole
* file
*/
protected void onAfterParse(JsonArray<T> nodes) {}
/**
* Flag that prevents work after instance was cleaned.
*/
private boolean detached;
/**
* Flag indicating that block of lines is being parsed
*/
private boolean iterating;
/**
* Array of data items.
*
* When new block of lines is parsed, this list is truncated.
*/
private JsonArray<T> nodes = JsonCollections.createArray();
@Override
public final void onDocumentLineParsed(
Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) {
if (detached) {
return;
}
if (!iterating) {
return;
}
onParseLine(line, lineNumber, tokens);
}
@Override
public final void onIterationFinish() {
Preconditions.checkState(iterating);
if (detached) {
return;
}
iterating = false;
onAfterParse(nodes);
}
@Override
public final void onIterationStart(int lineNumber) {
Preconditions.checkState(!iterating);
if (detached) {
return;
}
iterating = true;
cutTail(lineNumber);
onBeforeParse();
}
/**
* Adds given data to collected set while parsing.
*
* @param dataNode data to add
*/
protected final void addData(T dataNode) {
nodes.add(dataNode);
}
private void cutTail(int lineNumber) {
if (nodes.size() != 0) {
int cutTailIndex = findCutTailIndex(nodes, lineNumber);
if (cutTailIndex < nodes.size()) {
JsonArray<T> tail = nodes.splice(cutTailIndex, nodes.size() - cutTailIndex);
onCleanup(tail);
}
}
}
/**
* Find index for tail truncation in nodes array.
*
* <p>We support nodes array sorted by line number.
* Now we use that property in modified binarySuffix search.
*/
@VisibleForTesting
public static <T extends LineAware> int findCutTailIndex(JsonArray<T> nodes,
int lineNumber) {
int low = 0;
int high = nodes.size() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
if (lineNumber > nodes.get(mid).getLineNumber()) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
/**
* Cleanup object. Overriding implementations should call this method before
* any custom cleanup.
*
* After cleanup is invoked this instance should never be used.
*/
public void cleanup() {
cutTail(0);
detached = 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/bootstrap/BootstrapSession.java | client/src/main/java/com/google/collide/client/bootstrap/BootstrapSession.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.bootstrap;
import com.google.collide.dto.shared.JsonFieldConstants;
import com.google.collide.json.client.Jso;
/**
* Bootstrap information for the client.
*
* <p>This gets injected to the page with the initial page request.
*
* <p>It contains a description of the files contained in the project workspace,
* as well as user identification information and a sessionID token that is sent
* along with subsequent requests.
*
*/
public final class BootstrapSession extends Jso {
/**
* Use this method to obtain an instance of the Session object.
*/
public static native BootstrapSession getBootstrapSession() /*-{
return $wnd['__session'] || {};
}-*/;
protected BootstrapSession() {
}
/**
* @return The active client ID for the current tab.
*/
public String getActiveClientId() {
return getStringField(JsonFieldConstants.SESSION_ACTIVE_ID);
}
/**
* @return The user's handle. This is his name or email.
*/
public String getUsername() {
return getStringField(JsonFieldConstants.SESSION_USERNAME);
}
/**
* @return The user's unique ID (obfuscated GAIA ID).
*/
public String getUserId() {
return getStringField(JsonFieldConstants.SESSION_USER_ID);
}
/**
* @return The user's XSRF token that it sends with each request to validate
* that it originated from the client.
*/
public String getXsrfToken() {
return getStringField(JsonFieldConstants.XSRF_TOKEN);
}
/**
* @return The domain that we must talk to in order to fetch static
* file content from user branches.
*/
public String getStaticContentServingDomain() {
return getStringField(JsonFieldConstants.STATIC_FILE_CONTENT_DOMAIN);
}
/**
* Updates the client's XSRF token.
*
* @param newXsrfToken
*/
public void setXsrfToken(String newXsrfToken) {
this.addField(JsonFieldConstants.XSRF_TOKEN, newXsrfToken);
}
/**
* @return The url for the user's profile image.
*/
public String getProfileImageUrl() {
return getStringField(JsonFieldConstants.PROFILE_IMAGE_URL);
}
}
| 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/code/EditorBundle.java | client/src/main/java/com/google/collide/client/code/EditorBundle.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.code;
import collide.client.filetree.FileTreeModel;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.autoindenter.Autoindenter;
import com.google.collide.client.code.autocomplete.integration.AutocompleterFacade;
import com.google.collide.client.code.debugging.DebuggingModel;
import com.google.collide.client.code.debugging.DebuggingModelController;
import com.google.collide.client.code.errorrenderer.EditorErrorListener;
import com.google.collide.client.code.errorrenderer.ErrorReceiver;
import com.google.collide.client.code.errorrenderer.ErrorRenderer;
import com.google.collide.client.code.gotodefinition.GoToDefinitionHandler;
import com.google.collide.client.code.lang.LanguageHelper;
import com.google.collide.client.code.lang.LanguageHelperResolver;
import com.google.collide.client.code.parenmatch.ParenMatchHighlighter;
import com.google.collide.client.code.popup.EditorPopupController;
import com.google.collide.client.codeunderstanding.CubeClient;
import com.google.collide.client.codeunderstanding.CubeClientWrapper;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.Editor.Css;
import com.google.collide.client.editor.TextActions;
import com.google.collide.client.editor.input.RootActionExecutor;
import com.google.collide.client.history.Place;
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.client.util.logging.Log;
import com.google.collide.client.workspace.outline.OutlineController;
import com.google.collide.client.workspace.outline.OutlineModel;
import com.google.collide.codemirror2.CodeMirror2;
import com.google.collide.codemirror2.Parser;
import com.google.collide.shared.document.Document;
import elemental.dom.Element;
/**
* A class that bundles together all of the editor-related components, such as the editor widget,
* the collaboration controller, the document parser and syntax highlighter.
*/
public class EditorBundle implements FileContent {
/**
* Static factory method for obtaining an instance of the EditorBundle.
*/
public static EditorBundle create(AppContext appContext,
Place currentPlace,
DocumentManager documentManager,
ParticipantModel participantModel,
OutlineModel outlineModel,
FileTreeModel fileTreeModel,
ErrorReceiver errorReceiver) {
final Editor editor = Editor.create(appContext);
EditorErrorListener editorErrorListener = new EditorErrorListener(
editor, errorReceiver, new ErrorRenderer(appContext.getResources()));
EditorPopupController editorPopupController = EditorPopupController.create(
appContext.getResources(), editor);
// TODO: clean this up when things stabilize.
CubeClientWrapper cubeClientWrapper = new CubeClientWrapper(
appContext.getFrontendApi().GET_CODE_GRAPH);
CubeClient cubeClient = cubeClientWrapper.getCubeClient();
AutocompleterFacade autocompleter = AutocompleterFacade.create(
editor, cubeClient, appContext.getResources());
GoToDefinitionHandler goToDefinition = new GoToDefinitionHandler(currentPlace,
editor,
fileTreeModel,
appContext.getResources(),
cubeClient,
editorPopupController);
// Here is where to add support for rendering links / nested content
SelectionRestorer selectionRestorer = new SelectionRestorer(editor);
DebuggingModel debuggingModel = new DebuggingModel();
DebuggingModelController<?> debuggingModelController =
DebuggingModelController.create(currentPlace,
appContext.getResources(),
debuggingModel,
editor,
editorPopupController,
documentManager);
WorkspaceLocationBreadcrumbs breadcrumbs = new WorkspaceLocationBreadcrumbs();
OutlineController outlineController = new OutlineController(outlineModel, cubeClient, editor);
final EditorBundle editorBundle = new EditorBundle(documentManager,
editor,
editorErrorListener,
autocompleter,
goToDefinition,
selectionRestorer,
debuggingModelController,
breadcrumbs,
cubeClientWrapper,
outlineController,
appContext.getUserActivityManager(),
editorPopupController,
appContext.getResources().workspaceEditorCss());
return editorBundle;
}
private final AutocompleterFacade autocompleter;
private Autoindenter autoindenter;
private final DocumentManager documentManager;
private final Editor editor;
private final GoToDefinitionHandler goToDefinition;
private DocumentParser parser;
private final SelectionRestorer selectionRestorer;
private final DebuggingModelController<?> debuggingModelController;
private final WorkspaceLocationBreadcrumbs breadcrumbs;
private final CubeClientWrapper cubeClientWrapper;
private final OutlineController outlineController;
/*
* TODO: EditorBundle shouldn't have path. It's here to satisfy legacy dependency
*/
private PathUtil path;
private SyntaxHighlighter syntaxHighlighter;
private final EditorErrorListener editorErrorListener;
private final UserActivityManager userActivityManager;
private final EditorPopupController editorPopupController;
private ParenMatchHighlighter matchHighlighter;
private RootActionExecutor.Remover languageActionsRemover;
private RootActionExecutor.Remover textActionsRemover;
private final Css editorCss;
private final boolean isReadOnly = false;
private EditorBundle(DocumentManager documentManager,
Editor editor,
EditorErrorListener editorErrorListener,
AutocompleterFacade autoCompleter,
GoToDefinitionHandler goToDefinition,
SelectionRestorer selectionRestorer,
DebuggingModelController<?> debuggingModelController,
WorkspaceLocationBreadcrumbs breadcrumbs,
CubeClientWrapper cubeClientWrapper,
OutlineController outlineController,
UserActivityManager userActivityManager,
EditorPopupController editorPopupController,
Editor.Css editorCss) {
this.documentManager = documentManager;
this.editor = editor;
this.editorErrorListener = editorErrorListener;
this.autocompleter = autoCompleter;
this.goToDefinition = goToDefinition;
this.selectionRestorer = selectionRestorer;
this.debuggingModelController = debuggingModelController;
this.breadcrumbs = breadcrumbs;
this.cubeClientWrapper = cubeClientWrapper;
this.outlineController = outlineController;
this.userActivityManager = userActivityManager;
this.editorPopupController = editorPopupController;
this.editorCss = editorCss;
}
public Editor getEditor() {
return editor;
}
/**
* The readonly state of this workspace. The readonly state of the editor can change (i.e. when a
* file is deleted, the workspace temporarily goes into readonly mode until a current file is
* open), but the readonly state of the EditorBundle is final based on the workspace. This is now
* hardcoded to false.
*/
public boolean isReadOnly() {
return isReadOnly;
}
public WorkspaceLocationBreadcrumbs getBreadcrumbs() {
return breadcrumbs;
}
public PathUtil getPath() {
return path;
}
public DebuggingModelController<?> getDebuggingModelController() {
return debuggingModelController;
}
public void cleanup() {
reset();
goToDefinition.cleanup();
autocompleter.cleanup();
editorErrorListener.cleanup();
editor.cleanup();
outlineController.cleanup();
cubeClientWrapper.cleanup();
editorPopupController.cleanup();
debuggingModelController.cleanup();
// TODO: remove
Element readOnlyElement = Elements.getElementById("readOnly");
if (readOnlyElement != null) {
readOnlyElement.removeFromParent();
}
}
/**
* Detach services attached on {@link #setDocument}.
*
* <p>
* These services are constructed on the base of document and path, When active document is
* changed or editor is closed, they should gracefully cleanup.
*/
private void reset() {
if (parser != null) {
parser.teardown();
parser = null;
}
if (syntaxHighlighter != null) {
editor.removeLineRenderer(syntaxHighlighter.getRenderer());
syntaxHighlighter.teardown();
syntaxHighlighter = null;
}
if (autoindenter != null) {
autoindenter.teardown();
autoindenter = null;
}
if (matchHighlighter != null) {
matchHighlighter.teardown();
}
if (languageActionsRemover != null) {
languageActionsRemover.remove();
languageActionsRemover = null;
}
if (textActionsRemover != null) {
textActionsRemover.remove();
textActionsRemover = null;
}
}
@Override
public PathUtil filePath() {
return path;
}
/**
* Replaces the document for the editor and related components.
*/
public void setDocument(Document document, PathUtil path, String fileEditSessionKey) {
selectionRestorer.onBeforeDocumentChanged();
reset();
this.path = path;
documentManager.attachToEditor(document, editor);
Parser codeMirrorParser = CodeMirror2.getParser(path);
parser = codeMirrorParser == null ? null
: DocumentParser.create(document, codeMirrorParser, userActivityManager);
LanguageHelper languageHelper = LanguageHelperResolver.getHelper(parser.getSyntaxType());
RootActionExecutor actionExecutor = editor.getInput().getActionExecutor();
languageActionsRemover = actionExecutor.addDelegate(languageHelper.getActionExecutor());
textActionsRemover = actionExecutor.addDelegate(TextActions.INSTANCE);
cubeClientWrapper.setDocument(document, path.getPathString());
goToDefinition.editorContentsReplaced(path, parser);
selectionRestorer.onDocumentChanged(fileEditSessionKey);
editorErrorListener.onDocumentChanged(document, fileEditSessionKey);
debuggingModelController.setDocument(document, path, parser);
outlineController.onDocumentChanged(parser);
try {
autocompleter.editorContentsReplaced(path, parser);
} catch (Throwable t) {
Log.error(getClass(), "Autocompletion subsystem failed to accept the changed document", t);
}
syntaxHighlighter = SyntaxHighlighter.create(document,
editor.getRenderer(),
editor.getViewport(),
editor.getSelection(),
parser,
editorCss);
editor.addLineRenderer(syntaxHighlighter.getRenderer());
/*
* Make sure we open the editor in the right state according to the workspace readonly state.
* (For example, deleting a file will temporarily set the editor in readonly mode while it's
* still open).
*/
editor.setReadOnly(isReadOnly);
autoindenter = Autoindenter.create(parser, editor);
parser.begin();
breadcrumbs.setPath(path);
if (!isReadOnly) {
matchHighlighter = ParenMatchHighlighter.create(document,
editor.getViewport(),
document.getAnchorManager(),
editor.getView().getResources(),
editor.getRenderer(),
editor.getSelection());
}
}
@Override
public Element getContentElement() {
return getEditor().getElement();
}
@Override
public void onContentDisplayed() {
getEditor().getBuffer().synchronizeScrollTop();
}
@Override
public void onContentDestroyed() {
}
public OutlineController getOutlineController() {
return outlineController;
}
}
| 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/code/ParticipantModel.java | client/src/main/java/com/google/collide/client/code/ParticipantModel.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.code;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
import com.google.collide.client.util.QueryCallbacks.SimpleCallback;
import com.google.collide.dto.GetWorkspaceParticipants;
import com.google.collide.dto.GetWorkspaceParticipantsResponse;
import com.google.collide.dto.ParticipantUserDetails;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.UserDetails;
import com.google.collide.dto.client.DtoClientImpls.GetWorkspaceParticipantsImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.client.JsoStringSet;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.util.JsonCollections;
/**
* Model for the participants in the current workspace.
*/
// TODO: Pass the initial list of participants from the workspace bootstrap response
public class ParticipantModel {
/**
* Listener for changes in the participant model.
*
*/
public interface Listener {
void participantAdded(Participant participant);
void participantRemoved(Participant participant);
}
private static class ColorGenerator {
private static final String[] COLORS = new String[] {"#FC9229", // Orange
"#51D13F", // Green
"#B744D1", // Purple
"#3BC9D1", // Cyan
"#D13B45", // Pinky Red
"#465FE6", // Blue
"#F41BDB", // Magenta
"#B7AC4A", // Mustard
"#723226" // Brown
};
private int previousColorIndex = -1;
private String nextColor() {
previousColorIndex = (previousColorIndex + 1) % COLORS.length;
return COLORS[previousColorIndex];
}
}
public static ParticipantModel create(FrontendApi frontendApi, MessageFilter messageFilter) {
ParticipantModel model = new ParticipantModel(frontendApi);
model.registerForInvalidations(messageFilter);
model.requestAllParticipants();
return model;
}
private final JsoArray<Listener> listeners;
/**
* The last callback created when requesting all participants. If this is null, then the last
* request was for specific participants.
*/
private SimpleCallback<JsonArray<ParticipantUserDetails>> lastRequestAllCallback;
/**
* The set of all active participant ids, including participants who have not been added to the
* participant list because we don't have user details yet.
*/
private JsonStringSet presentParticipantsTracker = JsoStringSet.create();
private final JsoStringMap<Participant> participantsByUserId = JsoStringMap.create();
private final JsoStringMap<String> clientIdToUserId = JsoStringMap.create();
/**
* A map of user ID to the {@link UserDetails} for the participant. We cache participant info in
* case users connect and disconnect rapidly. We keep the cache here so we can discard it when the
* user leaves the workspace.
*/
// TODO: Should we persist user details for the entire session?
private final JsoStringMap<UserDetails> participantUserDetails = JsoStringMap.create();
/**
* Tracks the number of participants (optimization for otherwise having to iterate participants to
* get its size).
*/
private int count;
private final ColorGenerator colorGenerator;
private Participant self;
private final FrontendApi frontendApi;
private ParticipantModel(FrontendApi frontendApi) {
this.frontendApi = frontendApi;
colorGenerator = new ColorGenerator();
listeners = JsoArray.create();
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public int getCount() {
return count;
}
public String getUserId(final String clientId) {
return clientIdToUserId.get(clientId);
}
public Participant getParticipantByUserId(final String id) {
return participantsByUserId.get(id);
}
/**
* Gets the participants keyed by user id. Do not modify the returned map (not enforced for
* performance reasons).
*/
public JsoStringMap<Participant> getParticipants() {
return participantsByUserId;
}
public Participant getSelf() {
return self;
}
private void registerForInvalidations(MessageFilter messageFilter) {
messageFilter.registerMessageRecipient(RoutingTypes.GETWORKSPACEPARTICIPANTSRESPONSE,
new MessageRecipient<GetWorkspaceParticipantsResponse>() {
@Override
public void onMessageReceived(GetWorkspaceParticipantsResponse message) {
handleParticipantUserDetails(message.getParticipants(), true);
}
});
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
private void createAndAddParticipant(
com.google.collide.dto.Participant participantDto, UserDetails userDetails) {
boolean isSelf =
participantDto.getUserId().equals(BootstrapSession.getBootstrapSession().getUserId());
String color = isSelf ? "black" : colorGenerator.nextColor();
Participant participant = Participant.create(
participantDto, userDetails.getDisplayName(), userDetails.getDisplayEmail(), color, isSelf);
participantsByUserId.put(participantDto.getUserId(), participant);
count++;
if (isSelf) {
self = participant;
}
dispatchParticipantAdded(participant);
}
private void dispatchParticipantAdded(Participant participant) {
for (int i = 0, n = listeners.size(); i < n; i++) {
listeners.get(i).participantAdded(participant);
}
}
private void dispatchParticipantRemoved(Participant participant) {
for (int i = 0, n = listeners.size(); i < n; i++) {
listeners.get(i).participantRemoved(participant);
}
}
/**
* Requests all participants.
*/
private void requestAllParticipants() {
lastRequestAllCallback =
new SimpleCallback<JsonArray<ParticipantUserDetails>>("Failed to retrieve participants") {
@Override
public void onQuerySuccess(JsonArray<ParticipantUserDetails> result) {
/*
* If there is still an outstanding request for all participants, we should replace all
* participants with these results. Even if this request isn't the last request for all
* participants, we should still replace all participants or we might flail in a busy
* workspace and never update the list.
*
* If we've received a tango message containing the updated list of participants,
* lastRequestAllCallback will be null and we should not replace all participants.
*/
boolean replaceAll = (lastRequestAllCallback != null);
/*
* If this is the last callback, then set lastRequestAllCallback to null so older
* lastRequestAllCallbacks received out of order do not overwrite the most recent callback.
*/
if (this == lastRequestAllCallback) {
lastRequestAllCallback = null;
}
handleParticipantUserDetails(result, replaceAll);
}
};
GetWorkspaceParticipants req = GetWorkspaceParticipantsImpl.make();
frontendApi.GET_WORKSPACE_PARTICIPANTS.send(
req, new ApiCallback<GetWorkspaceParticipantsResponse>() {
@Override
public void onMessageReceived(GetWorkspaceParticipantsResponse message) {
lastRequestAllCallback.onQuerySuccess(message.getParticipants());
}
@Override
public void onFail(FailureReason reason) {
// Do nothing.
}
});
}
/**
* Updates the model with the participant user details.
*
* @param isAllParticipants true if the result contains the complete list of participants
*/
private void handleParticipantUserDetails(
JsonArray<ParticipantUserDetails> result, boolean isAllParticipants) {
// Reset the tracker if the result is all inclusive.
if (isAllParticipants) {
presentParticipantsTracker = JsonCollections.createStringSet();
}
for (int i = 0; i < result.size(); i++) {
ParticipantUserDetails item = result.get(i);
UserDetails userDetails = item.getUserDetails();
String userId = userDetails.getUserId();
// Cache the participants' user details.
participantUserDetails.put(userId, userDetails);
clientIdToUserId.put(item.getParticipant().getId(), userId);
if (isAllParticipants) {
presentParticipantsTracker.add(userId);
if (!participantsByUserId.containsKey(userId)) {
createAndAddParticipant(item.getParticipant(), userDetails);
}
} else {
/*
* Add the participant to the list. If the user is not in presentParticipantsTracker set,
* then the participant has since disconnected. If the user is in the participants map, then
* the user was already added to the view.
*/
if (presentParticipantsTracker.contains(userId)
&& !participantsByUserId.containsKey(userId)) {
createAndAddParticipant(item.getParticipant(), userDetails);
}
}
}
// Sweep through participants to find removed participants.
removeOldParticipants();
}
/**
* Removes users who have left the workspace from the participant list.
*/
private void removeOldParticipants() {
// NOTE: Iterating collection that is not affected by removing.
for (String userId : participantsByUserId.getKeys().asIterable()) {
if (!presentParticipantsTracker.contains(userId)) {
Participant participant = participantsByUserId.remove(userId);
if (participant != null) {
count--;
dispatchParticipantRemoved(participant);
}
for (String clientId : clientIdToUserId.getKeys().asIterable()) {
if (clientIdToUserId.get(clientId).equals(userId)) {
clientIdToUserId.remove(clientId);
}
}
}
}
}
}
| 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/code/Participant.java | client/src/main/java/com/google/collide/client/code/Participant.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.code;
import com.google.collide.dto.client.DtoClientImpls;
/**
* Model object for a participant. This extends the
* {@link com.google.collide.dto.Participant} class used for data
* transfer.
*/
public class Participant extends DtoClientImpls.ParticipantImpl {
private static final String DISPLAY_NAME_KEY = "__displayName";
private static final String DISPLAY_EMAIL_KEY = "__email";
private static final String COLOR_KEY = "__color";
private static final String IS_SELF_KEY = "__isSelf";
static Participant create(
com.google.collide.dto.Participant participantDto, String displayName,
String displayEmail, String color, boolean isSelf) {
DtoClientImpls.ParticipantImpl participantDtoImpl =
(DtoClientImpls.ParticipantImpl) participantDto;
// TODO: Wrap Participant instead of adding fields to the DTO.
participantDtoImpl.addField(DISPLAY_NAME_KEY, displayName);
participantDtoImpl.addField(DISPLAY_EMAIL_KEY, displayEmail);
participantDtoImpl.addField(COLOR_KEY, color);
participantDtoImpl.addField(IS_SELF_KEY, isSelf);
return participantDtoImpl.cast();
}
protected Participant() {
}
public final String getColor() {
return getStringField(COLOR_KEY);
}
public final String getDisplayName() {
return isSelf() ? "Me" : getStringField(DISPLAY_NAME_KEY);
}
public final String getDisplayEmail() {
return getStringField(DISPLAY_EMAIL_KEY);
}
public final boolean isSelf() {
return getBooleanField(IS_SELF_KEY);
}
}
| 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/code/WorkspaceNavigationSection.java | client/src/main/java/com/google/collide/client/code/WorkspaceNavigationSection.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.code;
import collide.client.common.CommonResources;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
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.AnchorElement;
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.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
/**
* Presenter for a section in the navigation bar. A section consists of a header
* and a content area.
*
*/
public class WorkspaceNavigationSection<V extends WorkspaceNavigationSection.View<?>> extends
UiComponent<V> {
public interface Css extends CssResource {
String closeX();
String contentArea();
String contentAreaScrollable();
String header();
String root();
String stretch();
String blue();
String underlineHeader();
String headerLink();
String menuButton();
}
public interface Resources extends CommonResources.BaseResources {
@Source({"WorkspaceNavigationSection.css", "constants.css",
"collide/client/common/constants.css"})
Css workspaceNavigationSectionCss();
}
public interface ViewEvents {
void onTitleClicked();
void onCloseClicked();
void onMenuButtonClicked();
}
public static abstract class AbstractViewEventsImpl implements ViewEvents {
@Override
public void onTitleClicked() {
}
@Override
public void onCloseClicked() {
}
@Override
public void onMenuButtonClicked() {
}
}
@VisibleForTesting
public static class View<D extends ViewEvents> extends CompositeView<D> {
@UiTemplate("WorkspaceNavigationSection.ui.xml")
interface MyBinder extends UiBinder<DivElement, View<?>> {
}
static MyBinder binder = GWT.create(MyBinder.class);
@UiField(provided = true)
final CommonResources.BaseCss baseCss;
@UiField(provided = true)
final Css css;
@UiField(provided = true)
final Resources res;
@UiField
DivElement header;
@UiField
AnchorElement closeX;
@UiField
DivElement contentArea;
@UiField
AnchorElement menuButton;
@UiField
AnchorElement title;
private Element contentElement;
protected View(Resources res) {
this.css = res.workspaceNavigationSectionCss();
this.baseCss = res.baseCss();
this.res = res;
setElement(Elements.asJsElement(binder.createAndBindUi(this)));
attachEventHandlers();
setCloseable(false);
setShowMenuButton(false);
}
private void attachEventHandlers() {
Elements.asJsElement(closeX).setOnclick(new EventListener() {
@Override
public void handleEvent(Event arg0) {
if (getDelegate() != null) {
getDelegate().onCloseClicked();
}
}
});
Elements.asJsElement(title).setOnclick(new EventListener() {
@Override
public void handleEvent(Event arg0) {
if (getDelegate() != null) {
getDelegate().onTitleClicked();
}
}
});
Elements.asJsElement(menuButton).setOnclick(new EventListener() {
@Override
public void handleEvent(Event arg0) {
if (getDelegate() != null) {
getDelegate().onMenuButtonClicked();
}
}
});
}
@VisibleForTesting
public Element getContentElement() {
return contentElement;
}
protected void setContent(Element newContentElement) {
if (contentElement == newContentElement) {
return;
}
if (contentElement != null) {
Elements.asJsElement(contentArea).replaceChild(newContentElement, contentElement);
} else {
Elements.asJsElement(contentArea).appendChild(newContentElement);
}
contentElement = newContentElement;
}
protected void setContentAreaScrollable(boolean scrollable) {
Element contentAreaElement = Elements.asJsElement(contentArea);
CssUtils.setClassNameEnabled(contentAreaElement, css.contentAreaScrollable(), scrollable);
}
protected void setStretch(boolean stretch) {
CssUtils.setClassNameEnabled(getElement(), css.stretch(), stretch);
}
protected void setBlue(boolean blue) {
CssUtils.setClassNameEnabled(getElement(), css.blue(), blue);
}
public void setTitle(String title) {
Elements.asJsElement(this.title).setTextContent(title);
}
public void setCloseable(boolean closeable) {
CssUtils.setDisplayVisibility(Elements.asJsElement(closeX), closeable);
}
public void setShowMenuButton(boolean visible) {
CssUtils.setDisplayVisibility(Elements.asJsElement(menuButton), visible);
}
protected void setUnderlineHeader(boolean underline) {
CssUtils.setClassNameEnabled(Elements.asJsElement(header), css.underlineHeader(), underline);
}
}
public void setVisible(boolean visible) {
CssUtils.setDisplayVisibility(getView().getElement(), visible);
}
public void makeTitleLink() {
}
protected WorkspaceNavigationSection(V view) {
super(view);
}
}
| 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/code/IndexTrackingDocOpCursor.java | client/src/main/java/com/google/collide/client/code/IndexTrackingDocOpCursor.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.code;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.DocOpCursor;
// TODO: clean up the API such that clients do not have to call super
/**
* {@link DocOpCursor} implementation that tracks the current index.
*
* Subclasses must call through to the super methods of each override. This
* class overrides some {@link DocOpCursor} methods with an empty implementation
* as a convenience.
*/
public abstract class IndexTrackingDocOpCursor implements DocOpCursor {
/**
* The index where the most recently-visited component began.
*/
private int beginIndex;
/**
* The index where the most recently-visited component ended. (Inclusive)
*/
private int endIndex = -1;
@Override
public void annotationBoundary(AnnotationBoundaryMap map) {
}
@Override
public void characters(String chars) {
beginIndex = endIndex + 1;
endIndex = beginIndex + chars.length() - 1;
}
@Override
public void deleteCharacters(String chars) {
}
@Override
public void deleteElementEnd() {
}
@Override
public void deleteElementStart(String type, Attributes attrs) {
}
@Override
public void elementEnd() {
beginIndex = ++endIndex;
}
@Override
public void elementStart(String type, Attributes attrs) {
beginIndex = ++endIndex;
}
@Override
public void replaceAttributes(Attributes oldAttrs, Attributes newAttrs) {
}
@Override
public void retain(int itemCount) {
beginIndex = endIndex + 1;
endIndex = beginIndex + itemCount - 1;
}
@Override
public void updateAttributes(AttributesUpdate attrUpdate) {
}
protected int getBeginIndex() {
return beginIndex;
}
protected int getEndIndex() {
return endIndex;
}
}
| 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/code/NoFileSelectedPanel.java | client/src/main/java/com/google/collide/client/code/NoFileSelectedPanel.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.code;
import collide.client.util.Elements;
import com.google.collide.client.history.Place;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.util.PathUtil;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.ParagraphElement;
import com.google.gwt.resources.client.ClientBundle;
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;
import elemental.events.EventRemover;
/**
* The screen you first see when opening a workspace that has no file selected.
*
*/
public class NoFileSelectedPanel extends UiComponent<NoFileSelectedPanel.View>
implements FileContent, PanelContent.HiddenContent {
private static final String REGULAR_MESSAGE = "Choose a file to begin editing.";
public static NoFileSelectedPanel create(Place place, Resources res) {
View view = new View(res);
view.setMessage(REGULAR_MESSAGE);
NoFileSelectedPanel panel = new NoFileSelectedPanel(view);
return panel;
}
/**
* Images and CSS.
*/
public interface Resources extends ClientBundle {
@Source({"collide/client/common/constants.css", "NoFileSelectedPanel.css"})
Css noFileSelectedPanelCss();
@Source("editor.png")
ImageResource editorLogo();
}
/**
* Styles names.
*/
public interface Css extends CssResource {
String base();
String bigger();
String center();
String logo();
String text();
}
/**
* Events sourced by this View.
*/
public interface ViewEvents {
// TODO: Add desktop Drag n' drop event.
void onClicked();
}
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("NoFileSelectedPanel.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, View> {
}
private static MyBinder binder = GWT.create(MyBinder.class);
final Resources res;
@UiField(provided = true)
final Css css;
@UiField
ParagraphElement message;
private EventRemover remover;
public View(Resources res) {
this.res = res;
this.css = res.noFileSelectedPanelCss();
setElement(Elements.asJsElement(binder.createAndBindUi(this)));
handleEvents();
}
public void detach() {
// Remove ourselves, we have served our purpose.
getElement().removeFromParent();
// Unhook the eventlistener just case.
if (remover != null) {
remover.remove();
}
}
/*
* Set the message (the last line) of the panel.
*/
public void setMessage(String msg) {
message.setInnerText(msg);
}
private void handleEvents() {
remover = getElement().addEventListener(Event.CLICK, new EventListener() {
@Override
public void handleEvent(Event evt) {
if (getDelegate() != null) {
getDelegate().onClicked();
}
}
}, false);
}
}
@Override
public PathUtil filePath() {
return null;
}
public NoFileSelectedPanel(View view) {
super(view);
getView().setMessage(REGULAR_MESSAGE);
}
public void detach() {
getView().detach();
}
@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/code/RightSidebarToggleEvent.java | client/src/main/java/com/google/collide/client/code/RightSidebarToggleEvent.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.code;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Simple event that is fired within a {@link WorkspacePlace} that toggles the
* right sidebar on the workspace.
*
*/
public class RightSidebarToggleEvent extends GwtEvent<RightSidebarToggleEvent.Handler> {
/**
* Handler interface for getting notified when the right sidebar is toggled.
*/
public interface Handler extends EventHandler {
void onRightSidebarToggled(RightSidebarToggleEvent evt);
}
public static final Type<Handler> TYPE = new Type<Handler>();
@Override
public Type<Handler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(Handler handler) {
handler.onRightSidebarToggled(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/code/NavigationAreaExpansionEvent.java | client/src/main/java/com/google/collide/client/code/NavigationAreaExpansionEvent.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.code;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Simple event that is fired within a {@link WorkspacePlace} that changes the
* expansion state of the Navigation area on the workspace.
*
*/
public class NavigationAreaExpansionEvent extends GwtEvent<NavigationAreaExpansionEvent.Handler> {
/**
* Handler interface for getting notified when the NavigationArea is expanded
* or collapsed.
*/
public interface Handler extends EventHandler {
void onNavAreaExpansion(NavigationAreaExpansionEvent evt);
}
public static final Type<Handler> TYPE = new Type<Handler>();
private final boolean shouldExpand;
public NavigationAreaExpansionEvent(boolean isExpanded) {
this.shouldExpand = isExpanded;
}
@Override
public GwtEvent.Type<Handler> getAssociatedType() {
return TYPE;
}
public boolean shouldExpand() {
return shouldExpand;
}
@Override
protected void dispatch(Handler handler) {
handler.onNavAreaExpansion(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/code/FileSelectedPlace.java | client/src/main/java/com/google/collide/client/code/FileSelectedPlace.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.code;
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.util.logging.Log;
import com.google.collide.client.workspace.WorkspacePlaceNavigationHandler;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
import com.google.common.base.Strings;
/**
* Place representing the selection of a file when already in the "Code"
* perspective.
*
*/
public class FileSelectedPlace extends Place {
/**
* The event that gets dispatched in order to arrive at the Workspace.
*
* @See {@link WorkspacePlaceNavigationHandler}.
*/
public class NavigationEvent extends PlaceNavigationEvent<FileSelectedPlace> {
public static final int IGNORE_LINE_NUMBER = -1;
public static final int IGNORE_COLUMN = -1;
private static final String PATH_KEY = "path";
private static final String LINE_KEY = "line";
private static final String COLUMN_KEY = "column";
private static final String FORCE_RELOAD_KEY = "forceReload";
private final boolean forceReload;
private final int lineNumber;
private final int column;
private final PathUtil path;
private NavigationEvent(PathUtil path, int lineNumber, int column, boolean forceReload) {
super(FileSelectedPlace.this);
this.path = path;
this.lineNumber = lineNumber;
this.column = column;
this.forceReload = forceReload;
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> state = JsoStringMap.create();
state.put(PATH_KEY, path.getPathString());
/*
* Only put things that deviate from the default (so we don't pollute the
* URL)
*/
if (lineNumber != IGNORE_LINE_NUMBER) {
state.put(LINE_KEY, Integer.toString(lineNumber));
}
if (column != IGNORE_COLUMN) {
state.put(COLUMN_KEY, Integer.toString(column));
}
if (forceReload) {
state.put(FORCE_RELOAD_KEY, Boolean.toString(forceReload));
}
return state;
}
public PathUtil getPath() {
return path;
}
/**
* Returns the line number to pre-scroll to, or {@link #IGNORE_LINE_NUMBER}
* if the dispatcher does not have a preference for the line number.
*/
public int getLineNo() {
return lineNumber;
}
public int getColumn() {
return column;
}
public boolean shouldForceReload() {
return forceReload;
}
}
public static final FileSelectedPlace PLACE = new FileSelectedPlace();
private FileSelectedPlace() {
super(PlaceConstants.FILE_SELECTED_PLACE_NAME);
}
@Override
public PlaceNavigationEvent<FileSelectedPlace> createNavigationEvent(
JsonStringMap<String> decodedState) {
String lineNumberStr = decodedState.get(NavigationEvent.LINE_KEY);
int lineNumber = NavigationEvent.IGNORE_LINE_NUMBER;
if (!Strings.isNullOrEmpty(lineNumberStr)) {
try {
lineNumber = Integer.parseInt(lineNumberStr);
if (lineNumber < 0 && lineNumber != NavigationEvent.IGNORE_LINE_NUMBER) {
Log.warn(getClass(), "Line number can not to be negative!");
lineNumber = NavigationEvent.IGNORE_LINE_NUMBER;
}
} catch (NumberFormatException e) {
Log.warn(getClass(), "Illegal line number format!");
}
}
String columnStr = decodedState.get(NavigationEvent.COLUMN_KEY);
int column = NavigationEvent.IGNORE_COLUMN;
if (!Strings.isNullOrEmpty(columnStr)) {
try {
column = Integer.parseInt(columnStr);
if (column < 0 && column != NavigationEvent.IGNORE_COLUMN) {
Log.warn(getClass(), "Column can not to be negative!");
column = NavigationEvent.IGNORE_COLUMN;
}
} catch (NumberFormatException e) {
Log.warn(getClass(), "Illegal column format!");
}
}
// parseBoolean maps null and non-"true" (ignoring case) to false
boolean forceReload = Boolean.parseBoolean(decodedState.get(NavigationEvent.FORCE_RELOAD_KEY));
return createNavigationEvent(new PathUtil(decodedState.get(NavigationEvent.PATH_KEY)),
lineNumber, column, forceReload);
}
public PlaceNavigationEvent<FileSelectedPlace> createNavigationEvent(PathUtil path) {
return createNavigationEvent(path, NavigationEvent.IGNORE_LINE_NUMBER);
}
public PlaceNavigationEvent<FileSelectedPlace> createNavigationEvent(PathUtil path, int lineNo) {
return createNavigationEvent(path, lineNo, NavigationEvent.IGNORE_COLUMN, false);
}
public PlaceNavigationEvent<FileSelectedPlace> createNavigationEvent(PathUtil path, int lineNo,
int column, boolean forceReload) {
checkNullPath(path);
return new NavigationEvent(path, lineNo, column, forceReload);
}
private void checkNullPath(PathUtil path) {
if (path == null) {
Log.warn(getClass(), "Trying to select a null file!");
}
}
}
| 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/code/CollaborationSection.java | client/src/main/java/com/google/collide/client/code/CollaborationSection.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.code;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.util.AnimationController;
/**
* The Presenter for the Collaboration/People section at the bottom of the
* Workspace Navigator.
*/
public class CollaborationSection extends WorkspaceNavigationSection<CollaborationSection.View>
implements ParticipantModel.Listener {
/**
* Static factory method for obtaining an instance of a CollaborationSection.
*/
public static CollaborationSection create(
CollaborationSection.View view, ParticipantModel participantModel, AppContext appContext) {
// Create sub-presenters.
ShareWorkspacePane shareWorkspacePane =
ShareWorkspacePane.create(view.shareWorkspacePaneView, appContext);
ParticipantList participantList = ParticipantList.create(
view.participantListView, appContext.getResources(), participantModel);
// Create and initialize the CollaborationSection.
CollaborationSection presenter =
new CollaborationSection(view, shareWorkspacePane, participantList,
new AnimationController.Builder().setFade(true).setCollapse(true).build());
presenter.init();
participantModel.addListener(presenter);
return presenter;
}
/**
* Styles and images.
*/
public interface Resources extends WorkspaceNavigationSection.Resources,
ShareWorkspacePane.Resources, ParticipantList.Resources {
}
/**
* The View for the CollaborationSection.
*/
public static class View extends WorkspaceNavigationSection.View<WorkspaceNavigationSection.ViewEvents> {
ShareWorkspacePane.View shareWorkspacePaneView;
ParticipantList.View participantListView;
public View(Resources res) {
super(res);
// Create subviews.
this.shareWorkspacePaneView = new ShareWorkspacePane.View(res);
this.participantListView = new ParticipantList.View(res);
// Initialize View;
setTitle("Collaborate");
setStretch(true);
setBlue(true);
setContent(Elements.createDivElement());
getContentElement().appendChild(participantListView.getElement());
getContentElement().appendChild(shareWorkspacePaneView.getElement());
}
}
private final ShareWorkspacePane shareWorkspacePane;
private final ParticipantList participantList;
private final AnimationController animator;
CollaborationSection(View view, ShareWorkspacePane shareWorkspacePane,
ParticipantList participantList, AnimationController animator) {
super(view);
this.shareWorkspacePane = shareWorkspacePane;
this.participantList = participantList;
this.animator = animator;
}
@Override
public void participantAdded(Participant participant) {
updateViewFromModel();
}
@Override
public void participantRemoved(Participant participant) {
updateViewFromModel();
}
private void init() {
updateViewFromModel();
}
/**
* Update the visibility of view components based on the number of
* participants.
*/
private void updateViewFromModel() {
boolean isCollaborative = participantList.getModel().getCount() > 1;
shareWorkspacePane.setInstructionsVisible(!isCollaborative, animator);
// TODO: follow up CL will properly clean all of this up
CssUtils.setDisplayVisibility2(participantList.getView().getElement(), 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/code/ShareWorkspacePane.java | client/src/main/java/com/google/collide/client/code/ShareWorkspacePane.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.code;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.HistoryUtils;
import com.google.collide.client.util.AnimationController;
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 elemental.client.Browser;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.InputElement;
/**
* The presenter for the pane that asks the user to share the workspace.
*/
public class ShareWorkspacePane extends UiComponent<ShareWorkspacePane.View>
implements HistoryUtils.SetHistoryListener {
/**
* Static factory method for obtaining an instance of ShareWorkspacePane.
*/
static ShareWorkspacePane create(View view, AppContext context) {
AnimationController ruleAnimator = new AnimationController.Builder()
.setCollapse(true)
.setFade(true)
.setFixedHeight(true)
.build();
return new ShareWorkspacePane(view, ruleAnimator);
}
public interface Css extends CssResource {
String label();
String root();
String rule();
String url();
}
interface Resources extends ClientBundle {
@Source("ShareWorkspacePane.css")
Css workspaceNavigationShareWorkspacePaneCss();
}
static class View extends CompositeView<Void> {
private final Css css;
private Element label;
private Element rule;
private InputElement url;
View(Resources res) {
this.css = res.workspaceNavigationShareWorkspacePaneCss();
setElement(createShareContents());
}
Element createShareContents() {
Element root = Elements.createDivElement(css.root());
rule = Elements.createDivElement(css.rule());
label = Elements.createElement("p", css.label());
label.setTextContent("Collaborate with others by pasting this link into an email or IM.");
url = Elements.createInputTextElement(css.url());
url.addEventListener(Event.CLICK, new EventListener() {
@Override
public void handleEvent(Event evt) {
url.setSelectionRange(0, url.getValue().length());
}
}, false);
// TODO: the elements above aren't added because we don't want them -- but I'm
// not actually removing them because I want ot reduce code change
return root;
}
}
private final AnimationController ruleAnimator;
private ShareWorkspacePane(View view, AnimationController ruleAnimator) {
super(view);
this.ruleAnimator = ruleAnimator;
HistoryUtils.addSetHistoryListener(this);
}
@Override
public void onHistorySet(String historyString) {
getView().url.setValue(Browser.getWindow().getLocation().getHref());
}
public void setInstructionsVisible(boolean visible, AnimationController animator) {
View view = getView();
CssUtils.setDisplayVisibility2(view.label, visible);
CssUtils.setDisplayVisibility2(view.rule, !visible);
}
}
| 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/code/WorkspaceLocationBreadcrumbs.java | client/src/main/java/com/google/collide/client/code/WorkspaceLocationBreadcrumbs.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.code;
import collide.client.util.Elements;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.NodeConflictDto.ConflictedPath;
import com.google.collide.dto.TreeNodeInfo;
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.gwt.core.client.Scheduler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.DataResource;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
/**
* A trail of "breadcrumbs" representing the current file path and the current
* code scope where the cursor is placed. If the cursor is inside a function
* foo() {...} inside class bar, with the current file being
* /www/widgets/widget.js, then the breadcrumb trail would look like: www >
* widgets > widget.js > bar > foo.
*/
public class WorkspaceLocationBreadcrumbs extends UiComponent<WorkspaceLocationBreadcrumbs.View> {
/**
* BaseCss resources for breadcrumbs.
*/
public interface Css extends CssResource {
String breadcrumbBar();
String breadcrumbWrap();
String breadcrumbSlash();
String breadcrumb();
String start();
String hide();
/** Icons */
String directory();
String file();
String cls();
String function();
String field();
}
/**
* Client bundle for breadcrumbs.
*/
/*
* TODO: Figure out a way to break the css reliance on data resources
* then use the folder() and file() from base.
*/
public interface Resources extends ClientBundle {
@Source("WorkspaceLocationBreadcrumbs.css")
Css workspaceLocationBreadcrumbsCss();
@Source("collide/client/common/folder_breadcrumb.png")
DataResource directoryImg();
@Source("collide/client/common/file_breadcrumb.png")
DataResource fileImg();
@Source("path_slash.png")
DataResource pathSlashImg();
}
private static enum PathType {
FOLDER, FILE, CLASS, FUNCTION, FIELD
}
/**
* A class representing a single breadcrumb.
*/
static class Breadcrumb extends UiComponent<Breadcrumb.View> {
/**
* The view for a single breadcrumb.
*/
class View extends CompositeView<Void> {
private Element breadcrumb;
private final Css css;
View(Resources res, String name, String iconClass) {
css = res.workspaceLocationBreadcrumbsCss();
Element breadcrumbSlash = Elements.createSpanElement(css.breadcrumbSlash());
breadcrumbSlash.setTextContent("/");
breadcrumb = Elements.createSpanElement(css.breadcrumb());
breadcrumb.addClassName(iconClass);
breadcrumb.setTextContent(name);
Element breadcrumbWrap = Elements.createSpanElement(css.breadcrumbWrap());
breadcrumbWrap.appendChild(breadcrumbSlash);
breadcrumbWrap.appendChild(breadcrumb);
// Start hidden
breadcrumb.addClassName(css.start());
setElement(breadcrumbWrap);
}
/**
* Show by fading+sliding in from the left.
*/
void show(int startDelay, int duration) {
CSSStyleDeclaration style = breadcrumb.getStyle();
// TODO: extract constants
style.setProperty("-webkit-transition-duration", duration + "ms");
style.setProperty("-webkit-transition-delay", startDelay + "ms");
breadcrumb.removeClassName(css.start());
}
/**
* Hide by fading+sliding out to the left.
*/
void hide(int startDelay) {
CSSStyleDeclaration style = breadcrumb.getStyle();
style.setProperty("-webkit-transition-delay", startDelay + "ms");
getElement().addClassName(css.hide());
}
void detach() {
getElement().removeFromParent();
}
}
private String name;
private String iconClass;
Breadcrumb(Resources res, String name, String iconClass) {
View view = new View(res, name, iconClass);
setView(view);
this.name = name;
this.iconClass = iconClass;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Breadcrumb)) {
return false;
}
Breadcrumb crumb = (Breadcrumb) other;
return crumb.name.equals(name) && crumb.iconClass.equals(iconClass);
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + name.hashCode();
result = 37 * result + iconClass.hashCode();
return result;
}
}
/**
* Number of milliseconds to delay between each breadcrumb being animated, to
* create a path buildup/teardown effect.
*/
private static final int DELAY_SHOW_TIME_MIN = 100;
private static final int DELAY_SHOW_TIME_MAX = 200;
private static final int DELAY_HIDE_TIME = 150;
private PathUtil currentFilePath = null;
private JsonArray<Breadcrumb> currentPathCrumbs = JsonCollections.createArray();
/**
* The view for the breadcrumbs.
*/
public static class View extends CompositeView<Void> {
private final Css css;
private final Resources res;
View(Resources res) {
this.res = res;
this.css = res.workspaceLocationBreadcrumbsCss();
Element breadcrumbBar = Elements.createDivElement(css.breadcrumbBar());
setElement(breadcrumbBar);
}
public Breadcrumb createBreadcrumb(String name, PathType type) {
String iconStyle = "";
switch (type) {
case FOLDER:
iconStyle = css.directory();
break;
case FILE:
iconStyle = css.file();
break;
case CLASS:
iconStyle = css.cls();
break;
case FUNCTION:
iconStyle = css.function();
break;
case FIELD:
iconStyle = css.field();
break;
}
return new Breadcrumb(res, name, iconStyle);
}
/**
* First fade out all elements in remove, then fade in elements in add.
*/
void updateElements(
final JsonArray<Breadcrumb.View> remove, final JsonArray<Breadcrumb.View> add) {
for (int i = remove.size() - 1; i >= 0; i--) {
remove.get(i).hide(0);
}
// Detach elements after animation finishes, then start the add animation
Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
for (int i = 0, n = remove.size(); i < n; i++) {
remove.get(i).detach();
}
int n = add.size();
if (n > 0) {
for (int i = 0; i < n; i++) {
getElement().appendChild(add.get(i).getElement());
}
// Trigger a browser layout so CSS3 transitions fire
add.get(0).getElement().getClientWidth();
int showDuration = Math.min(n * DELAY_SHOW_TIME_MIN, DELAY_SHOW_TIME_MAX) / n;
for (int i = 0; i < n; i++) {
add.get(i).show(showDuration * i, showDuration);
}
}
return false;
}
}, DELAY_HIDE_TIME);
}
}
/**
* Calculate the difference between the currently displayed path and the new
* file+scope paths and animate the change.
*/
void changeBreadcrumbPath(JsonArray<Breadcrumb> newPath) {
// find path difference
JsonArray<Breadcrumb.View> remove = JsonCollections.createArray();
JsonArray<Breadcrumb.View> add = JsonCollections.createArray();
/*
* Walk from the existing beginning to the end, and once a difference is
* found, mark the rest of the existing path to be removed and the rest of
* the new path to be added.
*/
Breadcrumb newBreadcrumb;
Breadcrumb curBreadcrumb;
boolean isMatchingPath = true;
int i = 0;
for (int n = currentPathCrumbs.size(), m = newPath.size(); i < n || i < m; i++) {
if (i < n && i < m) {
// Check for path conflict, add and remove
curBreadcrumb = currentPathCrumbs.get(i);
newBreadcrumb = newPath.get(i);
if (!isMatchingPath || !curBreadcrumb.equals(newBreadcrumb)) {
isMatchingPath = false;
remove.add(curBreadcrumb.getView());
add.add(newBreadcrumb.getView());
} else {
// Equal, update new list with old Breadcrumb
newPath.set(i, curBreadcrumb);
}
} else if (i >= n) {
// No current path here, add new path
add.add(newPath.get(i).getView());
} else if (i >= m) {
// No new path here, remove current path
remove.add(currentPathCrumbs.get(i).getView());
}
}
currentPathCrumbs = newPath;
getView().updateElements(remove, add);
}
/**
* Clears the current breadcrumb path.
*/
public void clearPath() {
currentFilePath = null;
changeBreadcrumbPath(JsonCollections.<Breadcrumb>createArray());
}
/**
* Returns the current breadcrumb path.
*/
public PathUtil getPath() {
return currentFilePath;
}
/**
* Sets the path that these breadcrumbs display.
*/
public void setPath(PathUtil newPath) {
// TODO: Uncomment when onCursorLocationChanged is implemented.
// editor.getSelection().getCursorListenerRegistrar().add(cursorListener);
JsonArray<Breadcrumb> newFilePath = JsonCollections.createArray();
for (int i = 0, n = newPath.getPathComponentsCount(); i < n; i++) {
if (i == n - 1) {
newFilePath.add(getView().createBreadcrumb(newPath.getPathComponent(i), PathType.FILE));
} else {
newFilePath.add(getView().createBreadcrumb(newPath.getPathComponent(i), PathType.FOLDER));
}
}
currentFilePath = newPath;
changeBreadcrumbPath(newFilePath);
}
/**
* Sets the path and type that these breadcrumbs display.
*/
public void setPath(ConflictedPath conflictedPath) {
PathUtil newPath = new PathUtil(conflictedPath.getPath());
JsonArray<Breadcrumb> newFilePath = JsonCollections.createArray();
for (int i = 0, n = newPath.getPathComponentsCount(); i < n; i++) {
if (i == n - 1 && conflictedPath.getNodeType() == TreeNodeInfo.FILE_TYPE) {
newFilePath.add(getView().createBreadcrumb(newPath.getPathComponent(i), PathType.FILE));
} else {
newFilePath.add(getView().createBreadcrumb(newPath.getPathComponent(i), PathType.FOLDER));
}
}
currentFilePath = newPath;
changeBreadcrumbPath(newFilePath);
}
/*
* TODO: Implement to show the current scope of the cursor.
*/
public void onCursorLocationChanged(int lineNumber, int column) {
// TODO: Do this async to avoid cursor lag.
JsonArray<Breadcrumb> newPath = currentPathCrumbs.copy();
// JsoArray<String> scope = autocompleter.getLocationScope(lineNumber,
// column);
newPath.add(getView().createBreadcrumb("Line " + lineNumber, PathType.CLASS));
newPath.add(getView().createBreadcrumb("Column " + column, PathType.FUNCTION));
changeBreadcrumbPath(newPath);
}
}
| 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/code/FileSelectedPlaceNavigationHandler.java | client/src/main/java/com/google/collide/client/code/FileSelectedPlaceNavigationHandler.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.code;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.FileSelectedPlace.NavigationEvent;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
/**
* {@link PlaceNavigationHandler} responsible for handling the selection of files.
*/
public class FileSelectedPlaceNavigationHandler
extends PlaceNavigationHandler<FileSelectedPlace.NavigationEvent> {
private final AppContext appContext;
private final FileSelectionController fileSelectionController;
private final EditableContentArea contentArea;
public FileSelectedPlaceNavigationHandler(AppContext appContext,
CodePerspective codePerspective,
FileSelectionController fileSelectionController,
EditableContentArea contentArea) {
this.appContext = appContext;
this.fileSelectionController = fileSelectionController;
this.contentArea = contentArea;
}
@Override
public void cleanup() {
contentArea.getEditorToolBar().hide();
}
@Override
protected void enterPlace(final NavigationEvent navigationEvent) {
contentArea.getEditorToolBar().show();
selectFile(navigationEvent);
}
@Override
protected void reEnterPlace(final NavigationEvent navigationEvent, boolean hasNewState) {
if (!hasNewState && !navigationEvent.shouldForceReload()) {
// Nothing to do.
return;
}
selectFile(navigationEvent);
}
private void selectFile(final NavigationEvent navigationEvent) {
/*
* The navigation event will not be active until all handlers have been called, so wait until
* the end of the event loop for the navigation event to become active.
*/
Scheduler.get().scheduleFinally(new ScheduledCommand() {
@Override
public void execute() {
if (navigationEvent.isActiveLeaf()) {
fileSelectionController.selectFile(navigationEvent);
contentArea.getEditorToolBar().setCurrentPath(navigationEvent.getPath(),
fileSelectionController.getFileTreeModel().getLastAppliedTreeMutationRevision());
}
}
});
}
}
| 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/code/DefaultEditorToolBar.java | client/src/main/java/com/google/collide/client/code/DefaultEditorToolBar.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.code;
import collide.client.editor.EditorToolbar;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.filehistory.FileHistoryPlace;
import com.google.collide.client.history.Place;
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.tooltip.Tooltip;
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.ShowableUiComponent;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Node;
import com.google.gwt.resources.client.ClientBundle;
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;
/**
* Editor toolbar for the workspace (contains buttons for file history,
* annotate, and debugging)
*
*
*/
public class DefaultEditorToolBar
extends ShowableUiComponent<DefaultEditorToolBar.View>
implements EditorToolbar {
/**
* Creates the default version of the toolbar to be used in the editor shell.
*/
public static DefaultEditorToolBar create(
View view, Place currentPlace, final AppContext appContext, final EditorBundle editorBundle) {
return new DefaultEditorToolBar(view, currentPlace, appContext, editorBundle);
}
@Override public ShowableUiComponent<?> asComponent() {
return this;
}
/**
* Style names associated with elements in the toolbar.
*/
public interface Css extends CssResource {
String toolButtons();
String button();
String detached();
String historyButton();
String historyIcon();
String debugButton();
String debugIcon();
String hspace();
String hspaceIcon();
}
/**
* Images and CssResources consumed by the DefaultEditorToolBar.
*/
public interface Resources extends ClientBundle, Tooltip.Resources {
@Source("history_icon.png")
ImageResource historyIcon();
@Source("debug_icon.png")
ImageResource debugIcon();
@Source("hspace.png")
ImageResource hspaceIcon();
@Source("DefaultEditorToolBar.css")
Css editorToolBarCss();
}
/**
* The View for the DefaultEditorToolBar.
*/
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("DefaultEditorToolBar.ui.xml")
interface MyBinder extends UiBinder<DivElement, View> {
}
static MyBinder binder = GWT.create(MyBinder.class);
@UiField
DivElement toolButtons;
@UiField
DivElement historyButton;
@UiField
DivElement historyIcon;
@UiField
DivElement debugButton;
@UiField
DivElement debugIcon;
@UiField(provided = true)
final Resources res;
public View(DefaultEditorToolBar.Resources res, boolean detached) {
this.res = res;
setElement(Elements.asJsElement(binder.createAndBindUi(this)));
attachHandlers();
// Make these tooltips right aligned since they're so close to the edge of the screen.
PositionerBuilder positioner = new Tooltip.TooltipPositionerBuilder().setHorizontalAlign(
HorizontalAlign.RIGHT).setPosition(Position.OVERLAP);
Positioner historyTooltipPositioner =
positioner.buildAnchorPositioner(Elements.asJsElement(historyIcon));
new Tooltip.Builder(
res, Elements.asJsElement(historyIcon), historyTooltipPositioner).setTooltipText(
"Explore this file's changes over time.").build().setTitle("History");
Positioner debugTooltipPositioner =
positioner.buildAnchorPositioner(Elements.asJsElement(debugIcon));
new Tooltip.Builder(
res, Elements.asJsElement(debugIcon), debugTooltipPositioner).setTooltipText(
"Opens the debug panel where you can set breakpoints and watch expressions.")
.build().setTitle("Debugging Controls");
if (detached)
toolButtons.addClassName(res.editorToolBarCss().detached());
}
protected void attachHandlers() {
getElement().setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
ViewEvents delegate = getDelegate();
if (delegate == null) {
return;
}
Node target = (Node) evt.getTarget();
if (historyButton.isOrHasChild(target)) {
delegate.onHistoryButtonClicked();
} else if (debugButton.isOrHasChild(target)) {
delegate.onDebugButtonClicked();
}
}
});
}
/**
* Hide or display the history button.
*/
public void setHistoryButtonVisible(boolean visible) {
CssUtils.setDisplayVisibility2(
Elements.asJsElement(historyButton), visible, false, "inline-block");
}
}
/**
* Events reported by the DefaultEditorToolBar's View.
*/
private interface ViewEvents {
void onDebugButtonClicked();
void onHistoryButtonClicked();
}
/**
* The delegate implementation for handling events reported by the View.
*/
private class ViewEventsImpl implements ViewEvents {
@Override
public void onHistoryButtonClicked() {
if (currentPath != null && pathRootId != null) {
currentPlace.fireChildPlaceNavigation(
FileHistoryPlace.PLACE.createNavigationEvent(currentPath, pathRootId));
}
}
@Override
public void onDebugButtonClicked() {
/*
* TODO: Make the RightSidebarToggleEvent live on
* CodePerspective's place scope
*/
WorkspacePlace.PLACE.fireEvent(new RightSidebarToggleEvent());
}
}
private final AppContext appContext;
private final EditorBundle editorBundle;
private final Place currentPlace;
private PathUtil currentPath;
/**
* currentPath is correct with respect to pathRootId.
*/
private String pathRootId;
public DefaultEditorToolBar(View view, Place currentPlace, AppContext appContext, EditorBundle editorBundle) {
super(view);
this.currentPlace = currentPlace;
this.appContext = appContext;
this.editorBundle = editorBundle;
view.setDelegate(new ViewEventsImpl());
}
public void setCurrentPath(PathUtil currentPath, String pathRootId) {
this.currentPath = Preconditions.checkNotNull(currentPath);
this.pathRootId = Preconditions.checkNotNull(pathRootId);
}
/* Methods for toggling toolbar visibility */
@Override
public void doShow() {
Element toolBar = Elements.asJsElement(getView().toolButtons);
CssUtils.setDisplayVisibility(toolBar, true);
}
@Override
public void doHide() {
Element toolBar = Elements.asJsElement(getView().toolButtons);
CssUtils.setDisplayVisibility(toolBar, 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/code/SelectionRestorer.java | client/src/main/java/com/google/collide/client/code/SelectionRestorer.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.code;
import com.google.collide.client.editor.Buffer;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.client.util.PathUtil;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.LineFinder;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.util.LineUtils;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import elemental.js.util.JsMapFromStringTo;
/**
* A simple class for saving/restoring the user's selection as he moves between
* files. This only persists the saved selections in the client's memory, not to
* the server. This will try to restore the relative position of the cursor on
* the screen too (e.g. if the cursor was 30px from the top of the viewport, it
* will stay 30px from the top of the viewport when restored).
*
* The client must call {@link #onBeforeDocumentChanged()} and
* {@link #onDocumentChanged(PathUtil)}.
*/
class SelectionRestorer {
private static class Selection {
final int baseColumn;
final int baseLineNumber;
final int cursorColumn;
final int cursorLineNumber;
/**
* Tracks the gap between the top of the viewport and the top of the
* cursor's line
*/
final int cursorScrollTopOffset;
Selection(int baseLineNumber, int baseColumn, int cursorLineNumber, int cursorColumn,
int cursorScrollTopOffset) {
this.baseColumn = baseColumn;
this.baseLineNumber = baseLineNumber;
this.cursorColumn = cursorColumn;
this.cursorLineNumber = cursorLineNumber;
this.cursorScrollTopOffset = cursorScrollTopOffset;
}
}
private final Editor editor;
private String fileEditSessionKey;
/** Map from file edit session key to {@link Selection} */
private final JsMapFromStringTo<Selection> selections = JsMapFromStringTo.create();
SelectionRestorer(Editor editor) {
this.editor = editor;
}
void onBeforeDocumentChanged() {
saveSelection();
}
private void saveSelection() {
if (fileEditSessionKey == null) {
return;
}
SelectionModel selectionModel = editor.getSelection();
Buffer buffer = editor.getBuffer();
int cursorLineNumber = selectionModel.getCursorLineNumber();
int cursorScrollTopOffset = buffer.calculateLineTop(cursorLineNumber) - buffer.getScrollTop();
selections.put(fileEditSessionKey, new Selection(selectionModel.getBaseLineNumber(),
selectionModel.getBaseColumn(), cursorLineNumber, selectionModel.getCursorColumn(),
cursorScrollTopOffset));
}
void onDocumentChanged(String fileEditSessionKey) {
this.fileEditSessionKey = fileEditSessionKey;
restoreSelection();
}
private void restoreSelection() {
if (fileEditSessionKey == null) {
return;
}
final Selection selection = selections.get(fileEditSessionKey);
if (selection == null) {
return;
}
Document document = editor.getDocument();
LineFinder lineFinder = document.getLineFinder();
LineInfo baseLineInfo =
lineFinder.findLine(Math.min(selection.baseLineNumber, document.getLastLineNumber()));
int baseColumn = LineUtils.rubberbandColumn(baseLineInfo.line(), selection.baseColumn);
final LineInfo cursorLineInfo =
lineFinder.findLine(Math.min(selection.cursorLineNumber, document.getLastLineNumber()));
int cursorColumn = LineUtils.rubberbandColumn(cursorLineInfo.line(), selection.cursorColumn);
editor.getSelection().setSelection(baseLineInfo, baseColumn, cursorLineInfo, cursorColumn);
// Defer to match editor's initially deferred scrolling
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
Buffer buffer = editor.getBuffer();
int targetScrollTop = buffer.calculateLineTop(cursorLineInfo.number())
- selection.cursorScrollTopOffset;
buffer.setScrollTop(Math.max(0, targetScrollTop));
}
});
}
}
| 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/code/CodePanelBundle.java | client/src/main/java/com/google/collide/client/code/CodePanelBundle.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.code;
import collide.client.editor.EditorConfiguration;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeNodeMoveController;
import com.google.collide.client.AppContext;
import com.google.collide.client.CollideSettings;
import com.google.collide.client.code.CodePerspective.Resources;
import com.google.collide.client.code.CodePerspective.View;
import com.google.collide.client.code.FileSelectionController.FileOpenedEvent;
import com.google.collide.client.code.errorrenderer.EditorErrorListener;
import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.editor.Editor.DocumentListener;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.client.plugin.ClientPluginService;
import com.google.collide.client.search.FileNameSearch;
import com.google.collide.client.search.SearchPlace;
import com.google.collide.client.search.SearchPlaceNavigationHandler;
import com.google.collide.client.search.awesomebox.AwesomeBoxContext;
import com.google.collide.client.search.awesomebox.FileNameNavigationSection;
import com.google.collide.client.search.awesomebox.GotoActionSection;
import com.google.collide.client.search.awesomebox.OutlineViewAwesomeBoxSection;
import com.google.collide.client.search.awesomebox.PrimaryWorkspaceActionSection;
import com.google.collide.client.search.awesomebox.PrimaryWorkspaceActionSection.FindActionSelectedCallback;
import com.google.collide.client.search.awesomebox.components.FindReplaceComponent;
import com.google.collide.client.search.awesomebox.components.FindReplaceComponent.FindMode;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponentHost.AwesomeBoxComponentHiddenListener;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.dom.eventcapture.GlobalHotKey;
import com.google.collide.client.util.logging.Log;
import com.google.collide.client.workspace.WorkspaceShell;
import com.google.collide.client.workspace.outline.OutlineModel;
import com.google.collide.client.workspace.outline.OutlineSection;
import com.google.collide.dto.GetWorkspaceMetaDataResponse;
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;
import com.google.gwt.core.client.Scheduler;
import elemental.dom.Element;
/**
* Dependencies and Presenter setup code for everything under the workspace header involved with
* code editing.
*/
/*
* TODO: Some cleanup in here now that the this class is created and invoked synchronously.
* Particularly lets extract the AwesomeBox cruft and see if anything else makes sense to bundle
* together into a separate class.
*/
public class CodePanelBundle {
// Dependencies passed in at Handler construction time.
private final AppContext appContext;
private final WorkspaceShell shell;
private final FileTreeModel fileTreeModel;
private final DocumentManager documentManager;
private final ParticipantModel participantModel;
private final IncomingDocOpDemultiplexer docOpReceiver;
// AwesomeBox Related
public final FileNameSearch searchIndex;
public final AwesomeBoxContext awesomeBoxCodeContext;
public EditableContentArea contentArea;
private CodePerspective codePerspective;
private final FileNameNavigationSection fileNavSection;
private final PrimaryWorkspaceActionSection primaryWorkspaceActionsSection;
private final GotoActionSection gotoActionSection;
private final OutlineViewAwesomeBoxSection outlineViewAwesomeBoxSection;
private final Place currentPlace;
// AwesomeBox Components
private final FindReplaceComponent findReplaceComponent;
// Presenters and Controllers that require cleanup.
private EditorBundle editorBundle;
private EditorReloadingFileTreeListener editorReloadingFileTreeListener;
private NoFileSelectedPanel welcomePanel;
private FileSelectionController fileSelectionController;
private FileTreeNodeMoveController treeNodeMoveController;
private FileTreeSection fileTreeSection;
private ClientPluginService plugins;
private MultiPanel<?,?> masterPanel;
private final FileTreeController<?> fileTreeController;
public CodePanelBundle(AppContext appContext,
WorkspaceShell shell,
FileTreeController<?> fileTreeController,
FileTreeModel fileTreeModel,
FileNameSearch searchIndex,
DocumentManager documentManager,
ParticipantModel participantModel,
IncomingDocOpDemultiplexer docOpReceiver,
Place place) {
this.appContext = appContext;
this.shell = shell;
this.fileTreeController = fileTreeController;
this.fileTreeModel = fileTreeModel;
this.searchIndex = searchIndex;
this.documentManager = documentManager;
this.participantModel = participantModel;
this.docOpReceiver = docOpReceiver;
this.currentPlace = place;
awesomeBoxCodeContext = new AwesomeBoxContext(new AwesomeBoxContext.Builder().setWaterMarkText(
"Type to find files and use actions").setPlaceholderText("Actions"));
fileNavSection = new FileNameNavigationSection(appContext.getResources(), searchIndex);
primaryWorkspaceActionsSection = new PrimaryWorkspaceActionSection(appContext.getResources());
gotoActionSection = new GotoActionSection(appContext.getResources());
outlineViewAwesomeBoxSection = new OutlineViewAwesomeBoxSection(appContext.getResources());
// Special Components
findReplaceComponent =
new FindReplaceComponent(new FindReplaceComponent.View(appContext.getResources()));
initializeAwesomeBoxContext();
}
private void initializeAwesomeBoxContext() {
primaryWorkspaceActionsSection.getFindActionSelectionListener()
.add(new FindActionSelectedCallback() {
@Override
public void onSelected(FindMode mode) {
findReplaceComponent.setFindMode(mode);
appContext.getAwesomeBoxComponentHostModel().setActiveComponent(findReplaceComponent);
shell.getHeader().getAwesomeBoxComponentHost().show();
}
});
awesomeBoxCodeContext.addSection(outlineViewAwesomeBoxSection);
awesomeBoxCodeContext.addSection(fileNavSection);
awesomeBoxCodeContext.addSection(gotoActionSection);
awesomeBoxCodeContext.addSection(primaryWorkspaceActionsSection);
}
public void cleanup() {
editorReloadingFileTreeListener.cleanup();
editorBundle.cleanup();
if (welcomePanel != null) {
welcomePanel.detach();
}
treeNodeMoveController.cleanup();
fileTreeSection.cleanup();
plugins.cleanup();
if (masterPanel != null)
masterPanel.destroy();
GlobalHotKey.unregister(appContext.getKeyBindings().localFind());
GlobalHotKey.unregister(appContext.getKeyBindings().localReplace());
GlobalHotKey.unregister(appContext.getKeyBindings().gotoLine());
GlobalHotKey.unregister(appContext.getKeyBindings().snapshot());
}
public void attach(boolean detached, EditorConfiguration config) {
// Construct the Root View for the CodePerspective.
CodePerspective.Resources res = appContext.getResources();
CodePerspective.View codePerspectiveView = initCodePerspective(res, detached);
// Then create all the Presenters.
OutlineModel outlineModel = new OutlineModel();
editorBundle = EditorBundle.create(appContext,
currentPlace,
documentManager,
participantModel,
outlineModel,
fileTreeModel,
EditorErrorListener.NOOP_ERROR_RECEIVER);
// AwesomeBox Section Setup
appContext.getAwesomeBoxModel().changeContext(awesomeBoxCodeContext);
outlineViewAwesomeBoxSection.setOutlineModelAndEditor(outlineModel, editorBundle.getEditor());
registerAwesomeBoxEvents();
editorReloadingFileTreeListener =
EditorReloadingFileTreeListener.create(currentPlace, editorBundle, fileTreeModel);
fileTreeSection = FileTreeSection.create(
currentPlace, fileTreeController, fileTreeModel, editorBundle.getDebuggingModelController());
fileTreeSection.getTree().renderTree(0);
// TODO: The term "Section" is overloaded here. It
// conflates the NavigationSection (the File Tree and the Conflict List)
// with panels in the NavigationToolBar. The Collab and Outline Sections
// here are actually panels on the NavigationToolBar. Clean this up.
CollaborationSection collabSection = CollaborationSection.create(
new CollaborationSection.View(res), participantModel, appContext);
treeNodeMoveController = new FileTreeNodeMoveController(
appContext, fileTreeSection.getFileTreeUiController(), fileTreeModel);
OutlineSection outlineSection = OutlineSection.create(
new OutlineSection.View(res), appContext, outlineModel,
editorBundle.getOutlineController());
final WorkspaceNavigationToolBar navigationToolBar = WorkspaceNavigationToolBar.create(
codePerspectiveView.getNavigationView().getNavigationToolBarView(), collabSection,
outlineSection);
WorkspaceNavigation workspaceNavigation = WorkspaceNavigation.create(
codePerspectiveView.getNavigationView(),
new WorkspaceNavigationSection[] {fileTreeSection},
new WorkspaceNavigationSection[] {collabSection, outlineSection}, navigationToolBar);
navigationToolBar.setWorkspaceNavigation(workspaceNavigation);
contentArea = initContentArea(codePerspectiveView, appContext, editorBundle,fileTreeSection);
codePerspective = CodePerspective.create(
codePerspectiveView, currentPlace, workspaceNavigation, contentArea, appContext, detached);
// Connect views to the DOM.
Element rightSidebarContentContainer = codePerspectiveView.getSidebarElement();
rightSidebarContentContainer.appendChild(
editorBundle.getDebuggingModelController().getDebuggingSidebarElement());
attachShellToDom(shell, codePerspectiveView);
}
protected View initCodePerspective(Resources res, boolean detached) {
return new CodePerspective.View(res, detached);
}
protected EditableContentArea initContentArea(View codePerspectiveView,
AppContext appContext, EditorBundle editorBundle,
FileTreeSection fileTreeSection) {
return EditableContentArea.create(codePerspectiveView.getContentView(), appContext, editorBundle,
fileTreeSection.getFileTreeUiController());
}
protected void attachShellToDom(WorkspaceShell shell, View codePerspectiveView) {
shell.setPerspective(codePerspectiveView.getElement());
}
public void enterWorkspace(boolean isActiveLeaf, final Place place,
final GetWorkspaceMetaDataResponse metadata) {
if (!isActiveLeaf) {
return;
}
// If there are no previously open files, show the welcome panel.
JsonArray<String> open = metadata.getLastOpenFiles();
String openFile = CollideSettings.get().getOpenFile();
Log.info(getClass(), "Opening ",open);
if (openFile != null){
open = JsoArray.create();
open.add(openFile);
}
if (open.size() == 0) {
showNoFileSelectedPanel();
return;
}
Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
// we check the very first file since that's all we support right now
String file = metadata.getLastOpenFiles().get(0);
Preconditions.checkNotNull(file, "Somehow the file to navigate to was null");
PlaceNavigationEvent<FileSelectedPlace> event =
FileSelectedPlace.PLACE.createNavigationEvent(new PathUtil(file));
place.fireChildPlaceNavigation(event);
}
});
}
public void showNoFileSelectedPanel() {
editorBundle.getBreadcrumbs().clearPath();
contentArea.setContent(welcomePanel, contentArea.newBuilder().setHistoryIcon(false).build());
}
/**
* Register's events that the AwesomeBox context uses.
*/
private void registerAwesomeBoxEvents() {
// If these fail someone called the registerAwesomeBoxEvents method
// to early in enterPlace. Lets notify them clearly.
Preconditions.checkArgument(
editorBundle != null, "Editor must be created before registering awesome box events.");
// Register Hiding Listener
shell.getHeader().getAwesomeBoxComponentHost().getComponentHiddenListener()
.add(new AwesomeBoxComponentHiddenListener() {
@Override
public void onHidden(Reason reason) {
if (reason != Reason.OTHER) {
editorBundle.getEditor().getFocusManager().focus();
}
}
});
// Attach the editor to the editorActionSection
gotoActionSection.attachEditorAndPlace(currentPlace, editorBundle.getEditor());
// We register the file opened events.
fileNavSection.registerOnFileOpenedHandler(currentPlace);
primaryWorkspaceActionsSection.registerOnFileOpenedHandler(currentPlace);
currentPlace.registerSimpleEventHandler(FileOpenedEvent.TYPE, new FileOpenedEvent.Handler() {
@Override
public void onFileOpened(boolean isEditable, PathUtil filePath) {
shell.getHeader().getAwesomeBoxComponentHost().hide();
}
});
// Hook find/replace upto the editor.
editorBundle.getEditor().getDocumentListenerRegistrar().add(new DocumentListener() {
@Override
public void onDocumentChanged(Document oldDocument, Document newDocument) {
findReplaceComponent.attachEditor(editorBundle.getEditor());
}
});
// Register any hotkeys
GlobalHotKey.Handler findAndReplaceHandler = new GlobalHotKey.Handler() {
@Override
public void onKeyDown(SignalEvent event) {
if (fileSelectionController.isSelectedFileEditable()) {
findReplaceComponent.setFindMode(event.getShiftKey() ? FindMode.REPLACE : FindMode.FIND);
String selectedText = editorBundle.getEditor().getSelection().getSelectedText();
boolean isFindActive = findReplaceComponent.isActive();
boolean shouldReplaceIfInFindMode = isFindActive && !selectedText.isEmpty();
// TODO: Check the AB query once it exists
// && !abQuery.isEmpty();
boolean shouldReplaceIfNotInFindMode = !isFindActive && !selectedText.isEmpty();
if (shouldReplaceIfInFindMode || shouldReplaceIfNotInFindMode) {
findReplaceComponent.setQuery(selectedText);
}
appContext.getAwesomeBoxComponentHostModel().setActiveComponent(findReplaceComponent);
}
shell.getHeader().getAwesomeBoxComponentHost().show();
}
};
GlobalHotKey.register(
appContext.getKeyBindings().localFind(), findAndReplaceHandler, "local find");
GlobalHotKey.register(
appContext.getKeyBindings().localReplace(), findAndReplaceHandler, "local replace");
GlobalHotKey.register(appContext.getKeyBindings().gotoLine(), new GlobalHotKey.Handler() {
@Override
public void onKeyDown(SignalEvent event) {
// TODO: Make a component which handles goto only.
shell.getHeader().getAwesomeBoxComponentHost().show();
}
}, "goto line");
}
public void setMasterPanel(MultiPanel<?,?> masterPanel) {
this.masterPanel = masterPanel;
UneditableDisplay uneditableDisplay = UneditableDisplay.create(new UneditableDisplay.View(appContext.getResources()));
fileSelectionController = new FileSelectionController(documentManager,
editorBundle,
uneditableDisplay,
fileTreeModel,
fileTreeSection.getFileTreeUiController(),
masterPanel);
// Creates the welcome panel
welcomePanel = NoFileSelectedPanel.create(currentPlace, appContext.getResources());
// Register navigation handler for FileSelection.
FileSelectedPlaceNavigationHandler fileSelectionHandler =
new FileSelectedPlaceNavigationHandler(appContext,
codePerspective,
fileSelectionController,
contentArea);
currentPlace.registerChildHandler(FileSelectedPlace.PLACE, fileSelectionHandler);
// Register navigation handler for searching within files.
SearchPlaceNavigationHandler searchHandler = new SearchPlaceNavigationHandler(appContext,
masterPanel, fileTreeSection.getFileTreeUiController(), currentPlace);
currentPlace.registerChildHandler(SearchPlace.PLACE, searchHandler);
plugins = initPlugins(masterPanel);
}
protected ClientPluginService initPlugins(MultiPanel<?, ?> masterPanel) {
return ClientPluginService.initialize(appContext, masterPanel, currentPlace);
}
}
| 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/code/FileContent.java | client/src/main/java/com/google/collide/client/code/FileContent.java | package com.google.collide.client.code;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.util.PathUtil;
public interface FileContent extends PanelContent{
PathUtil filePath();
}
| 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/code/FileSelectionController.java | client/src/main/java/com/google/collide/client/code/FileSelectionController.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.code;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeModel.NodeRequestCallback;
import collide.client.filetree.FileTreeNode;
import collide.client.filetree.FileTreeUiController;
import collide.client.treeview.TreeNodeElement;
import collide.client.util.Elements;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.document.DocumentManager.GetDocumentCallback;
import com.google.collide.client.document.DocumentMetadata;
import com.google.collide.client.history.RootPlace;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.dto.FileContents;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.json.client.JsoArray;
import com.google.collide.shared.document.Document;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Handler for file selection that drives file contents and the file tree selection.
*
*/
public class FileSelectionController implements GetDocumentCallback {
/**
* Event that broadcasts that a file's contents have been received over the network and we have
* determined if it is editable.
*
*/
public static class FileOpenedEvent extends GwtEvent<FileOpenedEvent.Handler> {
public interface Handler extends EventHandler {
public void onFileOpened(boolean isEditable, PathUtil filePath);
}
public static final Type<Handler> TYPE = new Type<Handler>();
private final boolean isFileEditable;
private final PathUtil filePath;
public FileOpenedEvent(boolean isEditable, PathUtil filePath) {
this.isFileEditable = isEditable;
this.filePath = filePath;
}
@Override
protected void dispatch(Handler handler) {
handler.onFileOpened(isFileEditable, filePath);
}
public boolean isEditable() {
return isFileEditable;
}
public PathUtil getFilePath() {
return filePath;
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() {
return TYPE;
}
}
private FileSelectedPlace.NavigationEvent mostRecentNavigationEvent;
private boolean isSelectedFileEditable = false;
private final FileTreeUiController treeUiController;
private final FileTreeModel fileTreeModel;
private final MultiPanel<?,?> contentArea;
private final EditorBundle editorBundle;
private final UneditableDisplay uneditableDisplay;
private final DocumentManager documentManager;
public FileSelectionController(DocumentManager documentManager,
EditorBundle editorBundle,
UneditableDisplay uneditableDisplay,
FileTreeModel fileTreeModel,
FileTreeUiController treeUiController,
MultiPanel<?,?> masterPanel) {
this.documentManager = documentManager;
this.editorBundle = editorBundle;
this.uneditableDisplay = uneditableDisplay;
this.fileTreeModel = fileTreeModel;
this.treeUiController = treeUiController;
this.contentArea = masterPanel;
}
/**
* Deselects the currently selected file, if one is selected.
*/
public void deselectFile() {
mostRecentNavigationEvent = null;
treeUiController.clearSelectedNodes();
}
public void selectFile(FileSelectedPlace.NavigationEvent navigationEvent) {
// The root is a special case no-op.
if (!navigationEvent.getPath().equals(PathUtil.WORKSPACE_ROOT)) {
doSelectTreeNode(navigationEvent);
}
}
public boolean isSelectedFileEditable() {
return isSelectedFileEditable;
}
FileTreeModel getFileTreeModel() {
return fileTreeModel;
}
private void doSelectTreeNode(final FileSelectedPlace.NavigationEvent navigationEvent) {
mostRecentNavigationEvent = navigationEvent;
fileTreeModel.requestWorkspaceNode(navigationEvent.getPath(), new NodeRequestCallback() {
@Override
public void onNodeAvailable(FileTreeNode node) {
// If we have since navigated away, exit early and don't select the
// file.
if (mostRecentNavigationEvent != navigationEvent
|| !mostRecentNavigationEvent.isActiveLeaf()) {
return;
}
// Expand the tree to reveal the node if it happens to be hidden (in the
// case of deep linking)
TreeNodeElement<FileTreeNode> renderedElement = node.getRenderedTreeNode();
if (renderedElement == null
|| !renderedElement.isActive(treeUiController.getTree().getResources().treeCss())) {
// Select the node without dispatching the node selection action.
treeUiController.autoExpandAndSelectNode(node, false);
}
}
@Override
public void onNodeUnavailable() {
// This can happen if a history event is dispatched for a path not
// found in our file tree.
// TODO: Throw up some UI to show that no such file exists.
// For now simply ignore the selection.
}
@Override
public void onError(FailureReason reason) {
// Already logged by the FileTreeModel.
}
});
documentManager.getDocument(navigationEvent.getPath(), this);
}
@Override
public void onDocumentReceived(Document document) {
PathUtil path = DocumentMetadata.getPath(document);
if (mostRecentNavigationEvent == null || !mostRecentNavigationEvent.isActiveLeaf()
|| !path.equals(mostRecentNavigationEvent.getPath())) {
// User selected another file or navigated away since this request, ignore
return;
}
openDocument(document, path);
WorkspacePlace.PLACE.fireEvent(new FileOpenedEvent(true, path));
}
private void openDocument(final Document document, PathUtil path) {
isSelectedFileEditable = true;
contentArea.setContent(editorBundle);
// Note that we dont use the name from the incoming FileContents. They
// should generally be the same. But in the case of a rename or a move, they
// might not be. Those changes get propagated separately, so we stick with
// the client's view of the world wrt to naming.
editorBundle.setDocument(document, path, DocumentMetadata.getFileEditSessionKey(document));
if (mostRecentNavigationEvent.getLineNo()
!= FileSelectedPlace.NavigationEvent.IGNORE_LINE_NUMBER) {
/*
* TODO: This scheduled deferred is so we set scroll AFTER the selection
* restorer. After demo, I'll create a better API on editor for components that want to set
* initial selection/scroll.
*/
final FileSelectedPlace.NavigationEvent savedNavigationEvent = mostRecentNavigationEvent;
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
if (mostRecentNavigationEvent == savedNavigationEvent) {
editorBundle.getEditor().scrollTo(mostRecentNavigationEvent.getLineNo(),
Math.max(0, mostRecentNavigationEvent.getColumn()));
}
}
});
}
// Set the tab title to the current open file
Elements.setCollideTitle(path.getBaseName());
editorBundle.getEditor().getFocusManager().focus();
// Save the list of open documents.
// TODO: Send a list of files when we support tabs.
JsoArray<String> openFiles = JsoArray.create();
openFiles.add(path.getPathString());
}
@Override
public void onUneditableFileContentsReceived(FileContents uneditableFile) {
showDisplayOnly(uneditableFile);
WorkspacePlace.PLACE.fireEvent(
new FileOpenedEvent(false, new PathUtil(uneditableFile.getPath())));
}
/**
* Changes the display for an uneditable file.
*/
private void showDisplayOnly(FileContents uneditableFile) {
PathUtil filePath = new PathUtil(uneditableFile.getPath());
if (!filePath.equals(mostRecentNavigationEvent.getPath())) {
// User selected another file since this request, ignore
return;
}
isSelectedFileEditable = false;
// Set the tab title to the current open file
Elements.setCollideTitle(filePath.getBaseName());
contentArea.setContent(uneditableDisplay);
uneditableDisplay.displayUneditableFileContents(uneditableFile);
editorBundle.getBreadcrumbs().setPath(filePath);
}
@Override
public void onFileNotFoundReceived() {
// TODO: pretty file not found message
RootPlace.PLACE.fireChildPlaceNavigation(
WorkspacePlace.PLACE.createNavigationEvent());
}
}
| 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/code/EditorReloadingFileTreeListener.java | client/src/main/java/com/google/collide/client/code/EditorReloadingFileTreeListener.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.code;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeNode;
import com.google.collide.client.history.Place;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
/**
* A controller whose sole responsibility it is to listen for changes on the
* file tree model and reload the editor contents when a relevant change occurs.
*
*/
public class EditorReloadingFileTreeListener implements FileTreeModel.TreeModelChangeListener {
public static EditorReloadingFileTreeListener create(
Place currentPlace, EditorBundle editorBundle, FileTreeModel fileTreeModel) {
EditorReloadingFileTreeListener listener =
new EditorReloadingFileTreeListener(currentPlace, editorBundle, fileTreeModel);
fileTreeModel.addModelChangeListener(listener);
return listener;
}
private final Place currentPlace;
private final EditorBundle editorBundle;
private final FileTreeModel fileTreeModel;
private EditorReloadingFileTreeListener(
Place currentPlace, EditorBundle editorBundle, FileTreeModel fileTreeModel) {
this.currentPlace = currentPlace;
this.editorBundle = editorBundle;
this.fileTreeModel = fileTreeModel;
}
public void cleanup() {
fileTreeModel.removeModelChangeListener(this);
}
@Override
public void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode) {
}
@Override
public void onNodeMoved(
PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode) {
// if the moved node is currently open in the editor, or is a dir that is
// somewhere in the path of whatever is open in the editor, then fix the
// breadcrumbs
PathUtil editorPath = editorBundle.getBreadcrumbs().getPath();
if (editorPath == null) {
return;
}
if (oldPath.containsPath(editorPath)) {
// replace the start of the editor's path with the node's new path
final PathUtil newEditorPath = PathUtil.concatenate(newPath,
PathUtil.createExcludingFirstN(editorPath, oldPath.getPathComponentsCount()));
editorBundle.getBreadcrumbs().setPath(newEditorPath);
// Wait until DocumentManagerFileTreeModelListener updates the path in the document.
Scheduler.get().scheduleFinally(new ScheduledCommand() {
@Override
public void execute() {
currentPlace.fireChildPlaceNavigation(
FileSelectedPlace.PLACE.createNavigationEvent(newEditorPath));
}
});
}
}
@Override
public void onNodesRemoved(JsonArray<FileTreeNode> oldNodes) {
// do nothing
}
@Override
public void onNodeReplaced(FileTreeNode oldNode, FileTreeNode newNode) {
if (oldNode == null || !isRelevantPath(oldNode.getNodePath())) {
return;
}
/*
* TODO: If we synchronously fire the place
* navigation, eventually we get into a state where the FileTree attempts to
* autoselect the node, but fails with an assertion error (rushing, so no
* time to investigate right now)
*/
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
// Reload the file
currentPlace.fireChildPlaceNavigation(
FileSelectedPlace.PLACE.createNavigationEvent(editorBundle.getPath(),
FileSelectedPlace.NavigationEvent.IGNORE_LINE_NUMBER,
FileSelectedPlace.NavigationEvent.IGNORE_COLUMN, true));
}
});
}
private boolean isRelevantPath(PathUtil changePath) {
PathUtil editorPath = editorBundle.getPath();
return editorPath != null && changePath.containsPath(editorPath);
}
}
| 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/code/RightSidebarExpansionEvent.java | client/src/main/java/com/google/collide/client/code/RightSidebarExpansionEvent.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.code;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Simple event that is fired within a {@link WorkspacePlace} that changes the
* expansion state of the right sidebar on the workspace.
*
*/
public class RightSidebarExpansionEvent extends GwtEvent<RightSidebarExpansionEvent.Handler> {
/**
* Handler interface for getting notified when the right sidebar is expanded
* or collapsed.
*/
public interface Handler extends EventHandler {
void onRightSidebarExpansion(RightSidebarExpansionEvent evt);
}
public static final Type<Handler> TYPE = new Type<Handler>();
private final boolean shouldExpand;
public RightSidebarExpansionEvent(boolean isExpanded) {
this.shouldExpand = isExpanded;
}
@Override
public Type<Handler> getAssociatedType() {
return TYPE;
}
public boolean shouldExpand() {
return shouldExpand;
}
@Override
protected void dispatch(Handler handler) {
handler.onRightSidebarExpansion(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/code/ParticipantList.java | client/src/main/java/com/google/collide/client/code/ParticipantList.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.code;
import collide.client.util.Elements;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
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 elemental.html.DivElement;
import elemental.html.SpanElement;
/**
* Presenter for the participant list in the navigation bar.
*
*/
public class ParticipantList extends UiComponent<ParticipantList.View>
implements ParticipantModel.Listener {
/**
* Static factory method for obtaining an instance of the ParticipantList.
*/
public static ParticipantList create(View view, Resources res, ParticipantModel model) {
ParticipantList participantList = new ParticipantList(view, model);
participantList.init();
return participantList;
}
/**
* CSS for the participant list.
*
*/
public interface Css extends CssResource {
String name();
String root();
String row();
String swatch();
}
interface Resources extends ClientBundle {
@Source("ParticipantList.css")
Css workspaceNavigationParticipantListCss();
}
static class View extends CompositeView<Void> {
final Resources res;
final Css css;
private final JsoStringMap<DivElement> rows = JsoStringMap.create();
View(Resources res) {
this.res = res;
this.css = res.workspaceNavigationParticipantListCss();
setElement(Elements.createDivElement(css.root()));
}
private void addParticipant(String userId, String displayEmail, String name, String color) {
DivElement rowElement = Elements.createDivElement(css.row());
DivElement swatchElement = Elements.createDivElement(css.swatch());
swatchElement.setAttribute("style", "background-color: " + color);
rowElement.appendChild(swatchElement);
SpanElement nameElement = Elements.createSpanElement(css.name());
nameElement.setTextContent(name);
nameElement.setTitle(displayEmail);
rowElement.appendChild(nameElement);
getElement().appendChild(rowElement);
rows.put(userId, rowElement);
}
private void removeParticipant(String userId) {
DivElement row = rows.get(userId);
if (row != null) {
row.removeFromParent();
}
}
}
private final ParticipantModel model;
private ParticipantList(View view, ParticipantModel model) {
super(view);
this.model = model;
}
@Override
public void participantAdded(Participant participant) {
addParticipantToView(participant);
}
@Override
public void participantRemoved(Participant participant) {
getView().removeParticipant(participant.getUserId());
}
public ParticipantModel getModel() {
return model;
}
private void init() {
model.addListener(this);
populateViewFromModel();
}
private void addParticipantToView(Participant participant) {
getView().addParticipant(participant.getUserId(),
participant.getDisplayEmail(), participant.getDisplayName(), participant.getColor());
}
private void populateViewFromModel() {
JsoStringMap<Participant> participants = getModel().getParticipants();
participants.iterate(new IterationCallback<Participant>() {
@Override
public void onIteration(String userId, Participant participant) {
addParticipantToView(participant);
}
});
}
}
| 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.