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/server/src/main/java/collide/server/StartServer.java | server/src/main/java/collide/server/StartServer.java | package collide.server;
import collide.plugin.server.ant.AntServerPlugin;
import collide.plugin.server.gwt.GwtServerPlugin;
import collide.server.codegraph.CodeGraphMonitor;
import collide.server.configuration.CollideOpts;
import collide.vertx.VertxService;
import collide.vertx.VertxServiceImpl;
import com.google.collide.server.documents.EditSessions;
import com.google.collide.server.fe.WebFE;
import com.google.collide.server.filetree.FileTree;
import com.google.collide.server.maven.MavenController;
import com.google.collide.server.participants.Participants;
import com.google.collide.server.workspace.WorkspaceState;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.Arrays;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/28/16.
*/
public class StartServer {
static {
// We're going to do some nefarious things with classloaders...
System.setProperty("jdk.net.URLClassPath.disableRestrictedPermissions", "true");
}
private static final String ASYNC_CLUSTERING_PROPERTY = "vertx.hazelcast.async-api";
public static void main(String[] args) {
final CollideOpts opts = CollideOpts.getOpts();
if (!opts.processArgs(args)) {
System.err.println("Unable to start server from arguments " + Arrays.asList(args));
return;
}
if (System.getProperty(ASYNC_CLUSTERING_PROPERTY) == null) {
System.setProperty(ASYNC_CLUSTERING_PROPERTY, "true");
}
VertxServiceImpl.service(opts, StartServer::startNode);
}
private static void startNode(VertxService service) {
String webRoot = "/opt/xapi";
String staticFiles = "/opt/collide/client/build/putnami/out/Demo";
final JsonObject webConfig = new JsonObject()
.put("port", 1337)
.put("host", "0.0.0.0")
.put("bridge", true)
.put("webRoot", webRoot)
.put("staticFiles", staticFiles)
.put("in_permitted", new JsonArray()
.add(".*")
)
.put("out_permitted", new JsonArray()
.add(".*")
)
;
final JsonObject participantsConfig = new JsonObject()
.put("usernames", new JsonArray().add("James"))
;
final JsonObject workspaceConfig = new JsonObject()
.put("plugins", new JsonArray()
.add("gwt").add("ant"))
.put("webRoot", webRoot)
;
final JsonObject pluginConfig = new JsonObject()
.put("usernames", webRoot)
.put("plugins", new JsonArray()
.add("gwt").add("ant"))
.put("includes", new JsonArray()
.add("gwt").add("ant"))
.put("preserve-cwd", true)
.put("webRoot", webRoot)
.put("staticFiles", staticFiles)
;
final JsonObject filetreeConfig = new JsonObject()
.put("webRoot", webRoot)
.put("packages", new JsonArray()
.add("api/src/main/java")
.add("shared/src/main/java")
.add("client/src/main/java")
.add("server/src/main/java")
)
;
final Vertx vertx = service.vertx();
vertx.deployVerticle(WebFE.class.getCanonicalName(), opts(webConfig)
.setInstances(10));
deploy(vertx, Participants.class, participantsConfig);
deploy(vertx, CodeGraphMonitor.class);
deploy(vertx, EditSessions.class);
deploy(vertx, FileTree.class, filetreeConfig);
deploy(vertx, WorkspaceState.class, workspaceConfig);
deploy(vertx, MavenController.class, workspaceConfig);
deploy(vertx, GwtServerPlugin.class, pluginConfig);
deploy(vertx, AntServerPlugin.class, pluginConfig);
}
public static <T extends Verticle> void deploy(Vertx vertx, Class<T> type, JsonObject config) {
vertx.deployVerticle(type.getCanonicalName(), opts(config));
}
public static <T extends Verticle> void deploy(Vertx vertx, Class<T> type) {
vertx.deployVerticle(type.getCanonicalName());
}
private static DeploymentOptions opts(JsonObject config) {
return new DeploymentOptions().setConfig(config);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/CollideServer.java | server/src/main/java/collide/server/CollideServer.java | package collide.server;
import collide.server.handler.WebAppHandler;
import collide.vertx.VertxService;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseException;
import com.github.javaparser.ast.expr.UiContainerExpr;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import xapi.collect.X_Collect;
import xapi.collect.api.StringTo;
import xapi.inject.X_Inject;
import xapi.log.X_Log;
import xapi.scope.request.RequestScope;
import xapi.server.api.Route;
import xapi.server.api.Route.RouteType;
import xapi.server.api.WebApp;
import xapi.server.vertx.VertxRequest;
import xapi.server.vertx.VertxResponse;
import xapi.server.vertx.XapiVertxServer;
import xapi.util.X_String;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import static xapi.model.X_Model.create;
/**
* Created by James X. Nelson (james @wetheinter.net) on 10/2/16.
*/
public class CollideServer extends XapiVertxServer {
private final class CachedResponse {
String path;
UiContainerExpr source;
FileTime timestamp;
volatile boolean result;
public CachedResponse(String path, UiContainerExpr source, FileTime timestamp) {
this.path = path;
this.source = source;
this.timestamp = timestamp;
}
}
private final String staticFiles;
private final String webRoot;
private final String workDir;
private final String warDir;
private final String collideHome;
private final VertxService service;
private final String xapiRoot;
private final StringTo<CachedResponse> xapiCache;
public CollideServer(
String bundledStaticFilesPrefix,
String webRootPrefix,
String workDir,
String warDir,
String collideHome
) {
this(defaultApp(), bundledStaticFilesPrefix, webRootPrefix, workDir, warDir, collideHome);
}
private static WebApp defaultApp() {
WebApp app = create(WebApp.class);
// for our default app, we'll start with just
// auth and a hello world page:
final Route login = create(Route.class);
login.setPath("/login");
login.setRouteType(RouteType.Template);
login.setPayload("<>");
app.getRoute().add(login);
return app;
}
public CollideServer(
WebApp app,
String bundledStaticFilesPrefix,
String webRootPrefix,
String workDir,
String warDir,
String collideHome
) {
super(app);
this.staticFiles = bundledStaticFilesPrefix;
this.webRoot = webRootPrefix;
this.workDir = workDir;
this.warDir = warDir;
this.collideHome = collideHome;
this.xapiRoot = collideHome + "server/src/main/xapi/";
this.service = X_Inject.singleton(VertxService.class);
xapiCache = X_Collect.newStringMap(CachedResponse.class);
}
@Override
protected void handleError(HttpServerRequest req, VertxResponse resp, Throwable error) {
String path = req.path().replace("/xapi", "");
if (path.isEmpty() || "/".equals(path)) {
path = "index";
}
if (path.startsWith("/")) {
path = path.substring(1);
}
Path file = Paths.get(xapiRoot + path + ".xapi");
if (xapiCache.containsKey(path)) {
// Use the cache, but check freshness on the file
final CachedResponse cached = xapiCache.get(path);
try {
if (Files.getLastModifiedTime(file).compareTo(cached.timestamp) <= 0) {
// we can just serve the cached response
cached.result = serveContainer(req, cached.source);
if (cached.result) {
return;
}
}
} catch (FileNotFoundException ignored) {
} catch (IOException e) {
X_Log.warn(CollideServer.class, "Unexpected IOException", e);
}
}
try {
String contents = X_String.join("\n", Files.readAllLines(file));
final UiContainerExpr container = JavaParser.parseUiContainer(contents);
final CachedResponse cached = new CachedResponse(path, container, Files.getLastModifiedTime(file));
xapiCache.put(path, cached);
cached.result = serveContainer(req, container);
if (cached.result) {
return;
}
} catch (ParseException | IOException e) {
X_Log.error(getClass(), "Unable to load xapi files; expect bad things to happen", e);
}
// Nope, no xapi files to serve... let's 404
super.handleError(req, resp, error);
}
private boolean serveContainer(HttpServerRequest req, UiContainerExpr container) {
// create request scope and user scope.
final RequestScope<VertxRequest, VertxResponse> scope = service.scope().requestScope(req);
WebAppHandler visitor = new WebAppHandler(xapiRoot);
return visitor.handle(scope, container);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/codegraph/CodeGraphMonitor.java | server/src/main/java/collide/server/codegraph/CodeGraphMonitor.java | package collide.server.codegraph;
import com.google.collide.dto.server.DtoServerImpls.CodeGraphResponseImpl;
import com.google.collide.server.shared.util.Dto;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/29/16.
*/
public class CodeGraphMonitor extends AbstractVerticle {
@Override
public void start() throws Exception {
vertx.eventBus().<JsonObject>consumer("codegraph.get",
request->{
request.reply(Dto.wrap(CodeGraphResponseImpl
.make())
);
});
super.start();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/configuration/EditorHomeHandler.java | server/src/main/java/collide/server/configuration/EditorHomeHandler.java | package collide.server.configuration;
import xapi.args.ArgHandlerPath;
import xapi.fu.In1;
import xapi.fu.Out1;
import java.nio.file.Path;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/29/16.
*/
public abstract class EditorHomeHandler extends ArgHandlerPath {
public static EditorHomeHandler handle(In1<Path> consumer) {
return new EditorHomeHandler() {
@Override
public void setPath(Path path) {
consumer.in(path);
}
};
}
@Override
public Out1<String>[] getDefaultArgs() {
return new Out1[]{
()->"-" + getTag(), ()->"/opt/collide"
};
}
@Override
public String getPurpose() {
return "The directory to display in the editor\n" +
"Default is $COLLIDE_HOME (or the directory where CollIDE is compiled)";
}
@Override
public String getTag() {
return "files";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/configuration/ClusteringHandler.java | server/src/main/java/collide/server/configuration/ClusteringHandler.java | package collide.server.configuration;
import xapi.args.ArgHandlerFlag;
import xapi.fu.In1;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/29/16.
*/
public abstract class ClusteringHandler extends ArgHandlerFlag {
public static ClusteringHandler handle(In1<Boolean> consumer) {
return new ClusteringHandler() {
@Override
public boolean setFlag() {
consumer.in(true);
return true;
}
};
}
@Override
public String getPurpose() {
return "Whether to run with or without clustering (slower startup).";
}
@Override
public String getTag() {
return "clustered";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/configuration/CollideOpts.java | server/src/main/java/collide/server/configuration/CollideOpts.java | package collide.server.configuration;
import xapi.args.ArgProcessorBase;
import java.nio.file.Path;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/29/16.
*/
public class CollideOpts extends ArgProcessorBase {
private static CollideOpts SINGLETON = new CollideOpts();
Path editorHome;
Path staticFiles;
boolean clustered;
private CollideOpts() {
registerHandler(EditorHomeHandler.handle(p->editorHome=p));
registerHandler(WebFilesHandler.handle(p->staticFiles=p));
registerHandler(ClusteringHandler.handle(p->clustered=p));
}
public static CollideOpts getOpts() {
return SINGLETON;
}
public Path getEditorHome() {
return editorHome;
}
public boolean isClustered() {
return clustered;
}
public Path getStaticFiles() {
if (staticFiles == null) {
staticFiles = getEditorHome().resolve("client/build/putnami/out/Demo");
System.out.println(staticFiles);
}
return staticFiles;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/configuration/WebFilesHandler.java | server/src/main/java/collide/server/configuration/WebFilesHandler.java | package collide.server.configuration;
import xapi.args.ArgHandlerPath;
import xapi.fu.In1;
import java.nio.file.Path;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/29/16.
*/
public abstract class WebFilesHandler extends ArgHandlerPath {
public static WebFilesHandler handle(In1<Path> consumer) {
return new WebFilesHandler() {
@Override
public void setPath(Path path) {
consumer.in(path);
}
};
}
@Override
public String getPurpose() {
return "The /static/ web files to serve for CollIDE.\n" +
"Default is $COLLIDE_HOME/client/build/putnami/out/Collide";
}
@Override
public String getTag() {
return "web";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/server/handler/WebAppHandler.java | server/src/main/java/collide/server/handler/WebAppHandler.java | package collide.server.handler;
import com.github.javaparser.ast.expr.UiContainerExpr;
import xapi.log.X_Log;
import xapi.scope.request.RequestScope;
import xapi.server.vertx.VertxRequest;
import xapi.server.vertx.VertxResponse;
import xapi.time.X_Time;
/**
* Created by James X. Nelson (james @wetheinter.net) on 10/2/16.
*/
public class WebAppHandler {
private final String xapiRoot;
public WebAppHandler(String xapiRoot) {
this.xapiRoot = xapiRoot;
}
public boolean handle(RequestScope<VertxRequest, VertxResponse> scope, UiContainerExpr app) {
X_Time.runLater(()->{
X_Log.warn(getClass(), scope, app);
});
return true;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/dto/server/DtoServerImpls.java | server/src/main/java/com/google/collide/dto/server/DtoServerImpls.java | // GENERATED SOURCE. DO NOT EDIT.
package com.google.collide.dto.server;
import com.google.collide.dtogen.server.JsonSerializable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import java.util.Map;
@SuppressWarnings({"cast", "unchecked", "rawtypes"})
public class DtoServerImpls {
private static final Gson gson = new GsonBuilder().serializeNulls().create();
private DtoServerImpls() {}
public static final String CLIENT_SERVER_PROTOCOL_HASH = "18d5484025fe6d9b7a998e2c0d8088aa544eff10";
public static class AddMembersResponseImpl extends com.google.collide.dtogen.server.RoutableDtoServerImpl implements com.google.collide.dto.AddMembersResponse, JsonSerializable {
private AddMembersResponseImpl() {
super(1);
}
protected AddMembersResponseImpl(int type) {
super(type);
}
public static AddMembersResponseImpl make() {
return new AddMembersResponseImpl();
}
protected java.util.List<UserDetailsWithRoleImpl> newMembers;
private boolean _hasNewMembers;
protected java.util.List<java.lang.String> invalidEmails;
private boolean _hasInvalidEmails;
public boolean hasNewMembers() {
return _hasNewMembers;
}
@Override
public com.google.collide.json.shared.JsonArray<com.google.collide.dto.UserDetailsWithRole> getNewMembers() {
ensureNewMembers();
return (com.google.collide.json.shared.JsonArray) new com.google.collide.json.server.JsonArrayListAdapter(newMembers);
}
public AddMembersResponseImpl setNewMembers(java.util.List<UserDetailsWithRoleImpl> v) {
_hasNewMembers = true;
newMembers = v;
return this;
}
public void addNewMembers(UserDetailsWithRoleImpl v) {
ensureNewMembers();
newMembers.add(v);
}
public void clearNewMembers() {
ensureNewMembers();
newMembers.clear();
}
void ensureNewMembers() {
if (!_hasNewMembers) {
setNewMembers(newMembers != null ? newMembers : new java.util.ArrayList<UserDetailsWithRoleImpl>());
}
}
public boolean hasInvalidEmails() {
return _hasInvalidEmails;
}
@Override
public com.google.collide.json.shared.JsonArray<java.lang.String> getInvalidEmails() {
ensureInvalidEmails();
return (com.google.collide.json.shared.JsonArray) new com.google.collide.json.server.JsonArrayListAdapter(invalidEmails);
}
public AddMembersResponseImpl setInvalidEmails(java.util.List<java.lang.String> v) {
_hasInvalidEmails = true;
invalidEmails = v;
return this;
}
public void addInvalidEmails(java.lang.String v) {
ensureInvalidEmails();
invalidEmails.add(v);
}
public void clearInvalidEmails() {
ensureInvalidEmails();
invalidEmails.clear();
}
void ensureInvalidEmails() {
if (!_hasInvalidEmails) {
setInvalidEmails(invalidEmails != null ? invalidEmails : new java.util.ArrayList<java.lang.String>());
}
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
if (!(o instanceof AddMembersResponseImpl)) {
return false;
}
AddMembersResponseImpl other = (AddMembersResponseImpl) o;
if (this._hasNewMembers != other._hasNewMembers) {
return false;
}
if (this._hasNewMembers) {
if (!this.newMembers.equals(other.newMembers)) {
return false;
}
}
if (this._hasInvalidEmails != other._hasInvalidEmails) {
return false;
}
if (this._hasInvalidEmails) {
if (!this.invalidEmails.equals(other.invalidEmails)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = hash * 31 + (_hasNewMembers ? newMembers.hashCode() : 0);
hash = hash * 31 + (_hasInvalidEmails ? invalidEmails.hashCode() : 0);
return hash;
}
@Override
public JsonElement toJsonElement() {
JsonObject result = new JsonObject();
JsonArray newMembersOut = new JsonArray();
ensureNewMembers();
for (UserDetailsWithRoleImpl newMembers_ : newMembers) {
JsonElement newMembersOut_ = newMembers_ == null ? JsonNull.INSTANCE : newMembers_.toJsonElement();
newMembersOut.add(newMembersOut_);
}
result.add("newMembers", newMembersOut);
JsonArray invalidEmailsOut = new JsonArray();
ensureInvalidEmails();
for (java.lang.String invalidEmails_ : invalidEmails) {
JsonElement invalidEmailsOut_ = (invalidEmails_ == null) ? JsonNull.INSTANCE : new JsonPrimitive(invalidEmails_);
invalidEmailsOut.add(invalidEmailsOut_);
}
result.add("invalidEmails", invalidEmailsOut);
result.add("_type", new JsonPrimitive(getType()));
return result;
}
@Override
public String toJson() {
return gson.toJson(toJsonElement());
}
@Override
public String toString() {
return toJson();
}
public static AddMembersResponseImpl fromJsonElement(JsonElement jsonElem) {
if (jsonElem == null || jsonElem.isJsonNull()) {
return null;
}
AddMembersResponseImpl dto = new AddMembersResponseImpl();
JsonObject json = jsonElem.getAsJsonObject();
if (json.has("newMembers")) {
JsonElement newMembersIn = json.get("newMembers");
java.util.ArrayList<UserDetailsWithRoleImpl> newMembersOut = null;
if (newMembersIn != null && !newMembersIn.isJsonNull()) {
newMembersOut = new java.util.ArrayList<UserDetailsWithRoleImpl>();
java.util.Iterator<JsonElement> newMembersInIterator = newMembersIn.getAsJsonArray().iterator();
while (newMembersInIterator.hasNext()) {
JsonElement newMembersIn_ = newMembersInIterator.next();
UserDetailsWithRoleImpl newMembersOut_ = UserDetailsWithRoleImpl.fromJsonElement(newMembersIn_);
newMembersOut.add(newMembersOut_);
}
}
dto.setNewMembers(newMembersOut);
}
if (json.has("invalidEmails")) {
JsonElement invalidEmailsIn = json.get("invalidEmails");
java.util.ArrayList<java.lang.String> invalidEmailsOut = null;
if (invalidEmailsIn != null && !invalidEmailsIn.isJsonNull()) {
invalidEmailsOut = new java.util.ArrayList<java.lang.String>();
java.util.Iterator<JsonElement> invalidEmailsInIterator = invalidEmailsIn.getAsJsonArray().iterator();
while (invalidEmailsInIterator.hasNext()) {
JsonElement invalidEmailsIn_ = invalidEmailsInIterator.next();
java.lang.String invalidEmailsOut_ = gson.fromJson(invalidEmailsIn_, java.lang.String.class);
invalidEmailsOut.add(invalidEmailsOut_);
}
}
dto.setInvalidEmails(invalidEmailsOut);
}
return dto;
}
public static AddMembersResponseImpl fromJsonString(String jsonString) {
if (jsonString == null) {
return null;
}
return fromJsonElement(new JsonParser().parse(jsonString));
}
}
public static class MockAddMembersResponseImpl extends AddMembersResponseImpl {
protected MockAddMembersResponseImpl() {}
public static AddMembersResponseImpl make() {
return new AddMembersResponseImpl();
}
}
public static class AddProjectMembersImpl extends com.google.collide.dtogen.server.RoutableDtoServerImpl implements com.google.collide.dto.AddProjectMembers, JsonSerializable {
private AddProjectMembersImpl() {
super(2);
}
protected AddProjectMembersImpl(int type) {
super(type);
}
protected ChangeRoleInfoImpl changeRoleInfo;
private boolean _hasChangeRoleInfo;
protected java.lang.String projectId;
private boolean _hasProjectId;
protected java.lang.String userEmails;
private boolean _hasUserEmails;
public boolean hasChangeRoleInfo() {
return _hasChangeRoleInfo;
}
@Override
public com.google.collide.dto.ChangeRoleInfo getChangeRoleInfo() {
return changeRoleInfo;
}
public AddProjectMembersImpl setChangeRoleInfo(ChangeRoleInfoImpl v) {
_hasChangeRoleInfo = true;
changeRoleInfo = v;
return this;
}
public boolean hasProjectId() {
return _hasProjectId;
}
@Override
public java.lang.String getProjectId() {
return projectId;
}
public AddProjectMembersImpl setProjectId(java.lang.String v) {
_hasProjectId = true;
projectId = v;
return this;
}
public boolean hasUserEmails() {
return _hasUserEmails;
}
@Override
public java.lang.String getUserEmails() {
return userEmails;
}
public AddProjectMembersImpl setUserEmails(java.lang.String v) {
_hasUserEmails = true;
userEmails = v;
return this;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
if (!(o instanceof AddProjectMembersImpl)) {
return false;
}
AddProjectMembersImpl other = (AddProjectMembersImpl) o;
if (this._hasChangeRoleInfo != other._hasChangeRoleInfo) {
return false;
}
if (this._hasChangeRoleInfo) {
if (!this.changeRoleInfo.equals(other.changeRoleInfo)) {
return false;
}
}
if (this._hasProjectId != other._hasProjectId) {
return false;
}
if (this._hasProjectId) {
if (!this.projectId.equals(other.projectId)) {
return false;
}
}
if (this._hasUserEmails != other._hasUserEmails) {
return false;
}
if (this._hasUserEmails) {
if (!this.userEmails.equals(other.userEmails)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = hash * 31 + (_hasChangeRoleInfo ? changeRoleInfo.hashCode() : 0);
hash = hash * 31 + (_hasProjectId ? projectId.hashCode() : 0);
hash = hash * 31 + (_hasUserEmails ? userEmails.hashCode() : 0);
return hash;
}
@Override
public JsonElement toJsonElement() {
JsonObject result = new JsonObject();
JsonElement changeRoleInfoOut = changeRoleInfo == null ? JsonNull.INSTANCE : changeRoleInfo.toJsonElement();
result.add("changeRoleInfo", changeRoleInfoOut);
JsonElement projectIdOut = (projectId == null) ? JsonNull.INSTANCE : new JsonPrimitive(projectId);
result.add("projectId", projectIdOut);
JsonElement userEmailsOut = (userEmails == null) ? JsonNull.INSTANCE : new JsonPrimitive(userEmails);
result.add("userEmails", userEmailsOut);
result.add("_type", new JsonPrimitive(getType()));
return result;
}
@Override
public String toJson() {
return gson.toJson(toJsonElement());
}
@Override
public String toString() {
return toJson();
}
public static AddProjectMembersImpl fromJsonElement(JsonElement jsonElem) {
if (jsonElem == null || jsonElem.isJsonNull()) {
return null;
}
AddProjectMembersImpl dto = new AddProjectMembersImpl();
JsonObject json = jsonElem.getAsJsonObject();
if (json.has("changeRoleInfo")) {
JsonElement changeRoleInfoIn = json.get("changeRoleInfo");
ChangeRoleInfoImpl changeRoleInfoOut = ChangeRoleInfoImpl.fromJsonElement(changeRoleInfoIn);
dto.setChangeRoleInfo(changeRoleInfoOut);
}
if (json.has("projectId")) {
JsonElement projectIdIn = json.get("projectId");
java.lang.String projectIdOut = gson.fromJson(projectIdIn, java.lang.String.class);
dto.setProjectId(projectIdOut);
}
if (json.has("userEmails")) {
JsonElement userEmailsIn = json.get("userEmails");
java.lang.String userEmailsOut = gson.fromJson(userEmailsIn, java.lang.String.class);
dto.setUserEmails(userEmailsOut);
}
return dto;
}
public static AddProjectMembersImpl fromJsonString(String jsonString) {
if (jsonString == null) {
return null;
}
return fromJsonElement(new JsonParser().parse(jsonString));
}
}
public static class MockAddProjectMembersImpl extends AddProjectMembersImpl {
protected MockAddProjectMembersImpl() {}
public static AddProjectMembersImpl make() {
return new AddProjectMembersImpl();
}
}
public static class AddWorkspaceMembersImpl extends com.google.collide.dtogen.server.RoutableDtoServerImpl implements com.google.collide.dto.AddWorkspaceMembers, JsonSerializable {
private AddWorkspaceMembersImpl() {
super(3);
}
protected AddWorkspaceMembersImpl(int type) {
super(type);
}
protected java.lang.String workspaceId;
private boolean _hasWorkspaceId;
protected ChangeRoleInfoImpl changeRoleInfo;
private boolean _hasChangeRoleInfo;
protected java.lang.String projectId;
private boolean _hasProjectId;
protected java.lang.String userEmails;
private boolean _hasUserEmails;
public boolean hasWorkspaceId() {
return _hasWorkspaceId;
}
@Override
public java.lang.String getWorkspaceId() {
return workspaceId;
}
public AddWorkspaceMembersImpl setWorkspaceId(java.lang.String v) {
_hasWorkspaceId = true;
workspaceId = v;
return this;
}
public boolean hasChangeRoleInfo() {
return _hasChangeRoleInfo;
}
@Override
public com.google.collide.dto.ChangeRoleInfo getChangeRoleInfo() {
return changeRoleInfo;
}
public AddWorkspaceMembersImpl setChangeRoleInfo(ChangeRoleInfoImpl v) {
_hasChangeRoleInfo = true;
changeRoleInfo = v;
return this;
}
public boolean hasProjectId() {
return _hasProjectId;
}
@Override
public java.lang.String getProjectId() {
return projectId;
}
public AddWorkspaceMembersImpl setProjectId(java.lang.String v) {
_hasProjectId = true;
projectId = v;
return this;
}
public boolean hasUserEmails() {
return _hasUserEmails;
}
@Override
public java.lang.String getUserEmails() {
return userEmails;
}
public AddWorkspaceMembersImpl setUserEmails(java.lang.String v) {
_hasUserEmails = true;
userEmails = v;
return this;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
if (!(o instanceof AddWorkspaceMembersImpl)) {
return false;
}
AddWorkspaceMembersImpl other = (AddWorkspaceMembersImpl) o;
if (this._hasWorkspaceId != other._hasWorkspaceId) {
return false;
}
if (this._hasWorkspaceId) {
if (!this.workspaceId.equals(other.workspaceId)) {
return false;
}
}
if (this._hasChangeRoleInfo != other._hasChangeRoleInfo) {
return false;
}
if (this._hasChangeRoleInfo) {
if (!this.changeRoleInfo.equals(other.changeRoleInfo)) {
return false;
}
}
if (this._hasProjectId != other._hasProjectId) {
return false;
}
if (this._hasProjectId) {
if (!this.projectId.equals(other.projectId)) {
return false;
}
}
if (this._hasUserEmails != other._hasUserEmails) {
return false;
}
if (this._hasUserEmails) {
if (!this.userEmails.equals(other.userEmails)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = hash * 31 + (_hasWorkspaceId ? workspaceId.hashCode() : 0);
hash = hash * 31 + (_hasChangeRoleInfo ? changeRoleInfo.hashCode() : 0);
hash = hash * 31 + (_hasProjectId ? projectId.hashCode() : 0);
hash = hash * 31 + (_hasUserEmails ? userEmails.hashCode() : 0);
return hash;
}
@Override
public JsonElement toJsonElement() {
JsonObject result = new JsonObject();
JsonElement workspaceIdOut = (workspaceId == null) ? JsonNull.INSTANCE : new JsonPrimitive(workspaceId);
result.add("workspaceId", workspaceIdOut);
JsonElement changeRoleInfoOut = changeRoleInfo == null ? JsonNull.INSTANCE : changeRoleInfo.toJsonElement();
result.add("changeRoleInfo", changeRoleInfoOut);
JsonElement projectIdOut = (projectId == null) ? JsonNull.INSTANCE : new JsonPrimitive(projectId);
result.add("projectId", projectIdOut);
JsonElement userEmailsOut = (userEmails == null) ? JsonNull.INSTANCE : new JsonPrimitive(userEmails);
result.add("userEmails", userEmailsOut);
result.add("_type", new JsonPrimitive(getType()));
return result;
}
@Override
public String toJson() {
return gson.toJson(toJsonElement());
}
@Override
public String toString() {
return toJson();
}
public static AddWorkspaceMembersImpl fromJsonElement(JsonElement jsonElem) {
if (jsonElem == null || jsonElem.isJsonNull()) {
return null;
}
AddWorkspaceMembersImpl dto = new AddWorkspaceMembersImpl();
JsonObject json = jsonElem.getAsJsonObject();
if (json.has("workspaceId")) {
JsonElement workspaceIdIn = json.get("workspaceId");
java.lang.String workspaceIdOut = gson.fromJson(workspaceIdIn, java.lang.String.class);
dto.setWorkspaceId(workspaceIdOut);
}
if (json.has("changeRoleInfo")) {
JsonElement changeRoleInfoIn = json.get("changeRoleInfo");
ChangeRoleInfoImpl changeRoleInfoOut = ChangeRoleInfoImpl.fromJsonElement(changeRoleInfoIn);
dto.setChangeRoleInfo(changeRoleInfoOut);
}
if (json.has("projectId")) {
JsonElement projectIdIn = json.get("projectId");
java.lang.String projectIdOut = gson.fromJson(projectIdIn, java.lang.String.class);
dto.setProjectId(projectIdOut);
}
if (json.has("userEmails")) {
JsonElement userEmailsIn = json.get("userEmails");
java.lang.String userEmailsOut = gson.fromJson(userEmailsIn, java.lang.String.class);
dto.setUserEmails(userEmailsOut);
}
return dto;
}
public static AddWorkspaceMembersImpl fromJsonString(String jsonString) {
if (jsonString == null) {
return null;
}
return fromJsonElement(new JsonParser().parse(jsonString));
}
}
public static class MockAddWorkspaceMembersImpl extends AddWorkspaceMembersImpl {
protected MockAddWorkspaceMembersImpl() {}
public static AddWorkspaceMembersImpl make() {
return new AddWorkspaceMembersImpl();
}
}
public static class BeginUploadSessionImpl extends com.google.collide.dtogen.server.RoutableDtoServerImpl implements com.google.collide.dto.BeginUploadSession, JsonSerializable {
private BeginUploadSessionImpl() {
super(4);
}
protected BeginUploadSessionImpl(int type) {
super(type);
}
protected java.util.List<java.lang.String> workspacePathsToReplace;
private boolean _hasWorkspacePathsToReplace;
protected java.util.List<java.lang.String> workspacePathsToUnzip;
private boolean _hasWorkspacePathsToUnzip;
protected java.util.List<java.lang.String> workspaceDirsToCreate;
private boolean _hasWorkspaceDirsToCreate;
protected java.lang.String clientId;
private boolean _hasClientId;
protected java.lang.String workspaceId;
private boolean _hasWorkspaceId;
protected java.lang.String sessionId;
private boolean _hasSessionId;
public boolean hasWorkspacePathsToReplace() {
return _hasWorkspacePathsToReplace;
}
@Override
public com.google.collide.json.shared.JsonArray<java.lang.String> getWorkspacePathsToReplace() {
ensureWorkspacePathsToReplace();
return (com.google.collide.json.shared.JsonArray) new com.google.collide.json.server.JsonArrayListAdapter(workspacePathsToReplace);
}
public BeginUploadSessionImpl setWorkspacePathsToReplace(java.util.List<java.lang.String> v) {
_hasWorkspacePathsToReplace = true;
workspacePathsToReplace = v;
return this;
}
public void addWorkspacePathsToReplace(java.lang.String v) {
ensureWorkspacePathsToReplace();
workspacePathsToReplace.add(v);
}
public void clearWorkspacePathsToReplace() {
ensureWorkspacePathsToReplace();
workspacePathsToReplace.clear();
}
void ensureWorkspacePathsToReplace() {
if (!_hasWorkspacePathsToReplace) {
setWorkspacePathsToReplace(workspacePathsToReplace != null ? workspacePathsToReplace : new java.util.ArrayList<java.lang.String>());
}
}
public boolean hasWorkspacePathsToUnzip() {
return _hasWorkspacePathsToUnzip;
}
@Override
public com.google.collide.json.shared.JsonArray<java.lang.String> getWorkspacePathsToUnzip() {
ensureWorkspacePathsToUnzip();
return (com.google.collide.json.shared.JsonArray) new com.google.collide.json.server.JsonArrayListAdapter(workspacePathsToUnzip);
}
public BeginUploadSessionImpl setWorkspacePathsToUnzip(java.util.List<java.lang.String> v) {
_hasWorkspacePathsToUnzip = true;
workspacePathsToUnzip = v;
return this;
}
public void addWorkspacePathsToUnzip(java.lang.String v) {
ensureWorkspacePathsToUnzip();
workspacePathsToUnzip.add(v);
}
public void clearWorkspacePathsToUnzip() {
ensureWorkspacePathsToUnzip();
workspacePathsToUnzip.clear();
}
void ensureWorkspacePathsToUnzip() {
if (!_hasWorkspacePathsToUnzip) {
setWorkspacePathsToUnzip(workspacePathsToUnzip != null ? workspacePathsToUnzip : new java.util.ArrayList<java.lang.String>());
}
}
public boolean hasWorkspaceDirsToCreate() {
return _hasWorkspaceDirsToCreate;
}
@Override
public com.google.collide.json.shared.JsonArray<java.lang.String> getWorkspaceDirsToCreate() {
ensureWorkspaceDirsToCreate();
return (com.google.collide.json.shared.JsonArray) new com.google.collide.json.server.JsonArrayListAdapter(workspaceDirsToCreate);
}
public BeginUploadSessionImpl setWorkspaceDirsToCreate(java.util.List<java.lang.String> v) {
_hasWorkspaceDirsToCreate = true;
workspaceDirsToCreate = v;
return this;
}
public void addWorkspaceDirsToCreate(java.lang.String v) {
ensureWorkspaceDirsToCreate();
workspaceDirsToCreate.add(v);
}
public void clearWorkspaceDirsToCreate() {
ensureWorkspaceDirsToCreate();
workspaceDirsToCreate.clear();
}
void ensureWorkspaceDirsToCreate() {
if (!_hasWorkspaceDirsToCreate) {
setWorkspaceDirsToCreate(workspaceDirsToCreate != null ? workspaceDirsToCreate : new java.util.ArrayList<java.lang.String>());
}
}
public boolean hasClientId() {
return _hasClientId;
}
@Override
public java.lang.String getClientId() {
return clientId;
}
public BeginUploadSessionImpl setClientId(java.lang.String v) {
_hasClientId = true;
clientId = v;
return this;
}
public boolean hasWorkspaceId() {
return _hasWorkspaceId;
}
@Override
public java.lang.String getWorkspaceId() {
return workspaceId;
}
public BeginUploadSessionImpl setWorkspaceId(java.lang.String v) {
_hasWorkspaceId = true;
workspaceId = v;
return this;
}
public boolean hasSessionId() {
return _hasSessionId;
}
@Override
public java.lang.String getSessionId() {
return sessionId;
}
public BeginUploadSessionImpl setSessionId(java.lang.String v) {
_hasSessionId = true;
sessionId = v;
return this;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
if (!(o instanceof BeginUploadSessionImpl)) {
return false;
}
BeginUploadSessionImpl other = (BeginUploadSessionImpl) o;
if (this._hasWorkspacePathsToReplace != other._hasWorkspacePathsToReplace) {
return false;
}
if (this._hasWorkspacePathsToReplace) {
if (!this.workspacePathsToReplace.equals(other.workspacePathsToReplace)) {
return false;
}
}
if (this._hasWorkspacePathsToUnzip != other._hasWorkspacePathsToUnzip) {
return false;
}
if (this._hasWorkspacePathsToUnzip) {
if (!this.workspacePathsToUnzip.equals(other.workspacePathsToUnzip)) {
return false;
}
}
if (this._hasWorkspaceDirsToCreate != other._hasWorkspaceDirsToCreate) {
return false;
}
if (this._hasWorkspaceDirsToCreate) {
if (!this.workspaceDirsToCreate.equals(other.workspaceDirsToCreate)) {
return false;
}
}
if (this._hasClientId != other._hasClientId) {
return false;
}
if (this._hasClientId) {
if (!this.clientId.equals(other.clientId)) {
return false;
}
}
if (this._hasWorkspaceId != other._hasWorkspaceId) {
return false;
}
if (this._hasWorkspaceId) {
if (!this.workspaceId.equals(other.workspaceId)) {
return false;
}
}
if (this._hasSessionId != other._hasSessionId) {
return false;
}
if (this._hasSessionId) {
if (!this.sessionId.equals(other.sessionId)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = hash * 31 + (_hasWorkspacePathsToReplace ? workspacePathsToReplace.hashCode() : 0);
hash = hash * 31 + (_hasWorkspacePathsToUnzip ? workspacePathsToUnzip.hashCode() : 0);
hash = hash * 31 + (_hasWorkspaceDirsToCreate ? workspaceDirsToCreate.hashCode() : 0);
hash = hash * 31 + (_hasClientId ? clientId.hashCode() : 0);
hash = hash * 31 + (_hasWorkspaceId ? workspaceId.hashCode() : 0);
hash = hash * 31 + (_hasSessionId ? sessionId.hashCode() : 0);
return hash;
}
@Override
public JsonElement toJsonElement() {
JsonObject result = new JsonObject();
JsonArray workspacePathsToReplaceOut = new JsonArray();
ensureWorkspacePathsToReplace();
for (java.lang.String workspacePathsToReplace_ : workspacePathsToReplace) {
JsonElement workspacePathsToReplaceOut_ = (workspacePathsToReplace_ == null) ? JsonNull.INSTANCE : new JsonPrimitive(workspacePathsToReplace_);
workspacePathsToReplaceOut.add(workspacePathsToReplaceOut_);
}
result.add("workspacePathsToReplace", workspacePathsToReplaceOut);
JsonArray workspacePathsToUnzipOut = new JsonArray();
ensureWorkspacePathsToUnzip();
for (java.lang.String workspacePathsToUnzip_ : workspacePathsToUnzip) {
JsonElement workspacePathsToUnzipOut_ = (workspacePathsToUnzip_ == null) ? JsonNull.INSTANCE : new JsonPrimitive(workspacePathsToUnzip_);
workspacePathsToUnzipOut.add(workspacePathsToUnzipOut_);
}
result.add("workspacePathsToUnzip", workspacePathsToUnzipOut);
JsonArray workspaceDirsToCreateOut = new JsonArray();
ensureWorkspaceDirsToCreate();
for (java.lang.String workspaceDirsToCreate_ : workspaceDirsToCreate) {
JsonElement workspaceDirsToCreateOut_ = (workspaceDirsToCreate_ == null) ? JsonNull.INSTANCE : new JsonPrimitive(workspaceDirsToCreate_);
workspaceDirsToCreateOut.add(workspaceDirsToCreateOut_);
}
result.add("workspaceDirsToCreate", workspaceDirsToCreateOut);
JsonElement clientIdOut = (clientId == null) ? JsonNull.INSTANCE : new JsonPrimitive(clientId);
result.add("clientId", clientIdOut);
JsonElement workspaceIdOut = (workspaceId == null) ? JsonNull.INSTANCE : new JsonPrimitive(workspaceId);
result.add("workspaceId", workspaceIdOut);
JsonElement sessionIdOut = (sessionId == null) ? JsonNull.INSTANCE : new JsonPrimitive(sessionId);
result.add("sessionId", sessionIdOut);
result.add("_type", new JsonPrimitive(getType()));
return result;
}
@Override
public String toJson() {
return gson.toJson(toJsonElement());
}
@Override
public String toString() {
return toJson();
}
public static BeginUploadSessionImpl fromJsonElement(JsonElement jsonElem) {
if (jsonElem == null || jsonElem.isJsonNull()) {
return null;
}
BeginUploadSessionImpl dto = new BeginUploadSessionImpl();
JsonObject json = jsonElem.getAsJsonObject();
if (json.has("workspacePathsToReplace")) {
JsonElement workspacePathsToReplaceIn = json.get("workspacePathsToReplace");
java.util.ArrayList<java.lang.String> workspacePathsToReplaceOut = null;
if (workspacePathsToReplaceIn != null && !workspacePathsToReplaceIn.isJsonNull()) {
workspacePathsToReplaceOut = new java.util.ArrayList<java.lang.String>();
java.util.Iterator<JsonElement> workspacePathsToReplaceInIterator = workspacePathsToReplaceIn.getAsJsonArray().iterator();
while (workspacePathsToReplaceInIterator.hasNext()) {
JsonElement workspacePathsToReplaceIn_ = workspacePathsToReplaceInIterator.next();
java.lang.String workspacePathsToReplaceOut_ = gson.fromJson(workspacePathsToReplaceIn_, java.lang.String.class);
workspacePathsToReplaceOut.add(workspacePathsToReplaceOut_);
}
}
dto.setWorkspacePathsToReplace(workspacePathsToReplaceOut);
}
if (json.has("workspacePathsToUnzip")) {
JsonElement workspacePathsToUnzipIn = json.get("workspacePathsToUnzip");
java.util.ArrayList<java.lang.String> workspacePathsToUnzipOut = null;
if (workspacePathsToUnzipIn != null && !workspacePathsToUnzipIn.isJsonNull()) {
workspacePathsToUnzipOut = new java.util.ArrayList<java.lang.String>();
java.util.Iterator<JsonElement> workspacePathsToUnzipInIterator = workspacePathsToUnzipIn.getAsJsonArray().iterator();
while (workspacePathsToUnzipInIterator.hasNext()) {
JsonElement workspacePathsToUnzipIn_ = workspacePathsToUnzipInIterator.next();
java.lang.String workspacePathsToUnzipOut_ = gson.fromJson(workspacePathsToUnzipIn_, java.lang.String.class);
workspacePathsToUnzipOut.add(workspacePathsToUnzipOut_);
}
}
dto.setWorkspacePathsToUnzip(workspacePathsToUnzipOut);
}
if (json.has("workspaceDirsToCreate")) {
JsonElement workspaceDirsToCreateIn = json.get("workspaceDirsToCreate");
java.util.ArrayList<java.lang.String> workspaceDirsToCreateOut = null;
if (workspaceDirsToCreateIn != null && !workspaceDirsToCreateIn.isJsonNull()) {
workspaceDirsToCreateOut = new java.util.ArrayList<java.lang.String>();
java.util.Iterator<JsonElement> workspaceDirsToCreateInIterator = workspaceDirsToCreateIn.getAsJsonArray().iterator();
while (workspaceDirsToCreateInIterator.hasNext()) {
JsonElement workspaceDirsToCreateIn_ = workspaceDirsToCreateInIterator.next();
java.lang.String workspaceDirsToCreateOut_ = gson.fromJson(workspaceDirsToCreateIn_, java.lang.String.class);
workspaceDirsToCreateOut.add(workspaceDirsToCreateOut_);
}
}
dto.setWorkspaceDirsToCreate(workspaceDirsToCreateOut);
}
if (json.has("clientId")) {
JsonElement clientIdIn = json.get("clientId");
java.lang.String clientIdOut = gson.fromJson(clientIdIn, java.lang.String.class);
dto.setClientId(clientIdOut);
}
if (json.has("workspaceId")) {
JsonElement workspaceIdIn = json.get("workspaceId");
java.lang.String workspaceIdOut = gson.fromJson(workspaceIdIn, java.lang.String.class);
dto.setWorkspaceId(workspaceIdOut);
}
if (json.has("sessionId")) {
JsonElement sessionIdIn = json.get("sessionId");
java.lang.String sessionIdOut = gson.fromJson(sessionIdIn, java.lang.String.class);
dto.setSessionId(sessionIdOut);
}
return dto;
}
public static BeginUploadSessionImpl fromJsonString(String jsonString) {
if (jsonString == null) {
return null;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | true |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/dto/server/ServerDocOpFactory.java | server/src/main/java/com/google/collide/dto/server/ServerDocOpFactory.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dto.server;
import static com.google.collide.dto.DocOpComponent.Type.DELETE;
import static com.google.collide.dto.DocOpComponent.Type.INSERT;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN_LINE;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent.Delete;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.DocOpComponent.Retain;
import com.google.collide.dto.DocOpComponent.RetainLine;
import com.google.collide.dto.server.DtoServerImpls.DeleteImpl;
import com.google.collide.dto.server.DtoServerImpls.DocOpImpl;
import com.google.collide.dto.server.DtoServerImpls.InsertImpl;
import com.google.collide.dto.server.DtoServerImpls.RetainImpl;
import com.google.collide.dto.server.DtoServerImpls.RetainLineImpl;
import com.google.collide.dto.shared.DocOpFactory;
// TODO: These should be moved to an Editor2-specific package
/**
*/
public final class ServerDocOpFactory implements DocOpFactory {
public static final ServerDocOpFactory INSTANCE = new ServerDocOpFactory();
private ServerDocOpFactory() {
}
@Override
public Delete createDelete(String text) {
return (Delete) DeleteImpl.make().setText(text).setType(DELETE);
}
@Override
public DocOp createDocOp() {
return DocOpImpl.make();
}
@Override
public Insert createInsert(String text) {
return (Insert) InsertImpl.make().setText(text).setType(INSERT);
}
@Override
public Retain createRetain(int count, boolean hasTrailingNewline) {
return (Retain) RetainImpl.make().setCount(count).setHasTrailingNewline(hasTrailingNewline)
.setType(RETAIN);
}
@Override
public RetainLine createRetainLine(int lineCount) {
return (RetainLine) RetainLineImpl.make().setLineCount(lineCount).setType(RETAIN_LINE);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/dtogen/server/RoutableDtoServerImpl.java | server/src/main/java/com/google/collide/dtogen/server/RoutableDtoServerImpl.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dtogen.server;
import com.google.collide.dtogen.shared.RoutableDto;
/**
* Server side base class for all DTO implementations.
*/
public abstract class RoutableDtoServerImpl implements RoutableDto {
private final int _type;
protected RoutableDtoServerImpl(int type) {
this._type = type;
}
@Override
public int getType() {
return _type;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof RoutableDtoServerImpl)) {
return false;
}
return _type == ((RoutableDtoServerImpl) other)._type;
}
@Override
public int hashCode() {
return _type;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/dtogen/server/JsonSerializable.java | server/src/main/java/com/google/collide/dtogen/server/JsonSerializable.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dtogen.server;
import com.google.gson.JsonElement;
/**
* An entity that may serialize itself to JSON.
* Now used only for server-side DTOs.
*
*/
public interface JsonSerializable {
/**
* Serializes DTO to JSON format.
*/
String toJson();
JsonElement toJsonElement();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/filetree/FileTree.java | server/src/main/java/com/google/collide/server/filetree/FileTree.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.filetree;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.FileInfo;
import com.google.collide.dto.Mutation;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.WorkspaceTreeUpdate;
import com.google.collide.dto.server.DtoServerImpls.*;
import com.google.collide.json.server.JsonArrayListAdapter;
import com.google.collide.server.participants.Participants;
import com.google.collide.server.shared.BusModBase;
import com.google.collide.server.shared.util.Dto;
import com.google.collide.shared.util.PathUtils;
import com.google.collide.shared.util.PathUtils.PathVisitor;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import xapi.log.X_Log;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Stack;
/**
* Backend service that manages the representation of "files and folders" in the workspace
* directory.
* <p>
* This service is responsible for applying all file tree mutations to the files on disk.
* <p>
* It is also responsible for managing meta-data about files (like resource identifiers).
*/
public class FileTree extends BusModBase {
/**
* Local data model extension. Note that toJsonElement is NOT overridden since extra fields are
* private to us, we don't want them serialized.
*/
private static interface NodeInfoExt extends TreeNodeInfo {
Path getPath();
}
private static class DirInfoExt extends DirInfoImpl implements NodeInfoExt {
private final Path path;
private final Map<String, NodeInfoExt> children = new HashMap<String, NodeInfoExt>();
public DirInfoExt(Path path, long resourceId) {
this.path = path;
super.setNodeType(TreeNodeInfo.DIR_TYPE);
super.setFileEditSessionKey(Long.toString(resourceId));
if (path.toString().length() == 0) {
// root
super.setName("/");
} else {
super.setName(path.getFileName().toString());
}
}
@Override
public Path getPath() {
return path;
}
public void addChild(DirInfoExt dir) {
NodeInfoExt prior = children.put(dir.getPath().getFileName().toString(), dir);
assert prior == null;
super.addSubDirectories(dir);
if (isPackage()) {
dir.setIsPackage(true);
}
}
public void addChild(FileInfoExt file) {
NodeInfoExt prior = children.put(file.getPath().getFileName().toString(), file);
assert prior == null;
super.addFiles(file);
}
public NodeInfoExt getChild(String name) {
return children.get(name);
}
public Iterable<NodeInfoExt> getChildren() {
return children.values();
}
public NodeInfoExt removeChild(String name) {
NodeInfoExt removed = children.remove(name);
assert removed != null : "Cannot remove non-existent child " + name;
if (removed.getNodeType() == TreeNodeInfo.FILE_TYPE) {
JsonArrayListAdapter<FileInfo> list = (JsonArrayListAdapter<FileInfo>) super.getFiles();
super.clearFiles();
boolean didRemove = false;
for (FileInfo item : list.asList()) {
if (item == removed) {
didRemove = true;
break;
}
super.addFiles((FileInfoImpl) item);
}
} else {
JsonArrayListAdapter<DirInfo> list =
(JsonArrayListAdapter<DirInfo>) super.getSubDirectories();
super.clearSubDirectories();
boolean didRemove = false;
for (DirInfo item : list.asList()) {
if (item == removed) {
didRemove = true;
break;
}
super.addSubDirectories((DirInfoImpl) item);
}
}
return removed;
}
}
private static class FileInfoExt extends FileInfoImpl implements NodeInfoExt {
private final Path path;
public FileInfoExt(Path path, long resourceId, long fileSize) {
this.path = path;
super.setName(path.getFileName().toString());
super.setNodeType(TreeNodeInfo.FILE_TYPE);
super.setFileEditSessionKey(Long.toString(resourceId));
super.setSize(Long.toString(fileSize));
}
@Override
public Path getPath() {
return path;
}
}
/**
* Receives and applies file tree mutations. Is responsible for subsequently broadcasting the
* mutation to collaborators after successful application of the mutation.
*/
class FileTreeMutationHandler implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> message) {
WorkspaceTreeUpdate update = WorkspaceTreeUpdateImpl.fromJsonString(Dto.get(message));
synchronized (FileTree.this.lock) {
try {
for (Mutation mutation : update.getMutations().asIterable()) {
final Path oldPath = resolvePathString(mutation.getOldPath());
final Path newPath = resolvePathString(mutation.getNewPath());
switch (mutation.getMutationType()) {
case ADD:
if (mutation.getNewNodeInfo().getNodeType() == TreeNodeInfo.DIR_TYPE) {
Files.createDirectory(newPath);
} else {
assert mutation.getNewNodeInfo().getNodeType() == TreeNodeInfo.FILE_TYPE;
Files.createFile(newPath);
}
break;
case COPY:
System.out.println("copy: " + oldPath + " to: " + newPath);
if (!Files.isDirectory(oldPath)) {
Files.copy(oldPath, newPath);
continue;
}
Files.walkFileTree(oldPath, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
Path target = newPath.resolve(oldPath.relativize(dir));
Files.copy(dir, target);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Path target = newPath.resolve(oldPath.relativize(file));
Files.copy(file, target);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (exc != null) {
throw exc;
}
return FileVisitResult.CONTINUE;
}
});
break;
case DELETE:
if (!Files.isDirectory(oldPath)) {
Files.delete(oldPath);
continue;
}
Files.walkFileTree(oldPath, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
break;
case MOVE:
expectMoves.add(new ExpectedMove(oldPath, newPath));
Files.move(oldPath, newPath);
break;
default:
throw new IllegalArgumentException(mutation.getMutationType().toString());
}
}
EmptyMessageImpl response = EmptyMessageImpl.make();
message.reply(Dto.wrap(response));
// The file listener will broadcast the applied mutations to all clients.
} catch (Exception exc) {
exc.printStackTrace(System.out);
ServerErrorImpl response = ServerErrorImpl.make();
response.setFailureReason(FailureReason.SERVER_ERROR);
StringWriter sw = new StringWriter();
exc.printStackTrace(new PrintWriter(sw));
response.setDetails(sw.toString());
message.reply(Dto.wrap(response));
}
}
}
private Path resolvePathString(String pathString) {
if (pathString == null) {
return null;
}
return root.getPath().resolve(stripSlashes(pathString));
}
}
/**
* Replies to the requester with the File Tree rooted at the path requested by the requester.
*/
class FileTreeGetter implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> message) {
GetDirectoryImpl request = GetDirectoryImpl.fromJsonString(Dto.get(message));
final GetDirectoryResponseImpl response = GetDirectoryResponseImpl.make();
synchronized (FileTree.this.lock) {
response.setRootId(Long.toString(currentTreeVersion));
PathUtils.walk(request.getPath(), "/", new PathVisitor() {
@Override
public void visit(String path, String name) {
// Special case root.
if ("/".equals(path)) {
response.setBaseDirectory(root);
response.setPath(path);
return;
}
// Search for the next directory.
DirInfo lastDir = response.getBaseDirectory();
if (lastDir != null) {
for (DirInfo dir : lastDir.getSubDirectories().asIterable()) {
if (dir.getName().equals(name)) {
response.setBaseDirectory((DirInfoImpl) dir);
response.setPath(path);
return;
}
}
}
// Didn't find it.
response.setBaseDirectory(null);
}
});
}
message.reply(Dto.wrap(response));
}
}
/**
* Takes in a list of resource IDs and returns a list of String paths for the resources as they
* currently exist.
*/
class PathResolver implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> message) {
JsonArray resourceIds = message.body().getJsonArray("resourceIds");
JsonObject result = new JsonObject();
JsonArray paths = new JsonArray();
result.put("paths", paths);
synchronized (FileTree.this.lock) {
for (Object id : resourceIds) {
assert id instanceof String;
NodeInfoExt node = resourceIdToNode.get(id);
if (node == null) {
paths.addNull();
} else {
paths.add('/' + node.getPath().toString());
}
}
}
message.reply(result);
}
}
/**
* Takes in a list of paths and replies with a list of resource IDs. A resource ID is a stable
* identifier for a resource that survives across renames/moves. This identifier is currently only
* stable for the lifetime of this verticle.
*/
class ResourceIdResolver implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> message) {
JsonArray paths = message.body().getJsonArray("paths");
JsonObject result = new JsonObject();
JsonArray resourceIds = new JsonArray();
result.put("resourceIds", resourceIds);
synchronized (FileTree.this.lock) {
for (Object path : paths) {
NodeInfoExt found = findResource(stripSlashes((String) path));
if (found == null) {
resourceIds.addNull();
} else {
resourceIds.add(found.getFileEditSessionKey());
}
}
}
message.reply(result);
}
private NodeInfoExt findResource(String path) {
if (path.length() == 0) {
return root;
}
DirInfoExt cur = root;
while (true) {
int pos = path.indexOf('/');
if (pos < 0) {
// Last item.
return cur.getChild(path);
} else {
String component = path.substring(0, pos);
NodeInfoExt found = cur.getChild(component);
// Better be a directory or we can't search anymore.
if (!(found instanceof DirInfoExt)) {
return null;
}
cur = (DirInfoExt) found;
path = path.substring(pos + 1);
}
}
}
}
/**
* Scans the file tree, or a subsection, adding new nodes to the tree. Also sets up watchers to
* listen for file and directory changes.
*/
private class TreeScanner {
public final Stack<DirInfoExt> parents = new Stack<FileTree.DirInfoExt>();
private final FileVisitor<Path> visitor = new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) {
DirInfoExt dir = new DirInfoExt(path, resourceIdAllocator++);
if (packages.contains(path)) {
dir.setIsPackage(true);
}
if (blacklist.contains(dir.getName()))
return FileVisitResult.SKIP_SUBTREE;
if (parents.isEmpty()) {
// System.out.println("scanning from: " + path.toAbsolutePath() + '/');
root = dir;
} else {
parents.peek().addChild(dir);
}
resourceIdToNode.put(dir.getFileEditSessionKey(), dir);
parents.push(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
// System.out.println("add: /" + path);
FileInfoExt file = new FileInfoExt(path, resourceIdAllocator++, attrs.size());
parents.peek().addChild(file);
resourceIdToNode.put(file.getFileEditSessionKey(), file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("visitFileFailed: " + file);
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
System.out.println("postVisitDirectory failed: " + dir);
throw exc;
}
DirInfoExt dirInfo = parents.pop();
dirInfo.setIsComplete(true);
WatchKey key = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW);
if (!blacklist.contains(dirInfo.getName()))
watchkeyToDir.put(key, dirInfo);
return FileVisitResult.CONTINUE;
}
};
/**
* @param start the path to start scanning from
* @param parent the parent node to scan under
*/
public void walk(Path start, DirInfoExt parent) throws IOException {
assert parents.isEmpty();
parents.push(parent);
Files.walkFileTree(start, visitor);
parents.pop();
assert parents.isEmpty();
}
/**
* @param root the path to start scanning from
*/
public void walkFromRoot(Path root) throws IOException {
assert root != null;
assert parents.isEmpty();
Files.walkFileTree(root, visitor);
assert parents.isEmpty();
}
}
/** NOT IDEAL: a lock for communicating between the threads. */
final Object lock = new Object();
/** The root of the tree. */
DirInfoExt root = null;
/** The tree is versioned to reconcile racey client mutations. */
long currentTreeVersion = 0;
/** Simple in-memory allocator for resource Ids. */
long resourceIdAllocator = 0;
static class ExpectedMove {
public ExpectedMove(Path oldPath, Path newPath) {
this.oldPath = oldPath;
this.newPath = newPath;
}
final Path oldPath;
final Path newPath;
NodeInfoExt oldNode = null;
NodeInfoExt newNode = null;
}
final List<ExpectedMove> expectMoves = new ArrayList<ExpectedMove>();
/** Map resourceId to node. */
HashMap<String, NodeInfoExt> resourceIdToNode = new HashMap<String, NodeInfoExt>();
/** Scans to find new files. */
final TreeScanner treeScanner = new TreeScanner();
/** The watch service for listening for tree changes. */
WatchService watchService;
/** A map of watch keys to directories. */
final Map<WatchKey, DirInfoExt> watchkeyToDir = new HashMap<WatchKey, DirInfoExt>();
Thread watcherThread = null;
HashSet<String> blacklist = new HashSet<>();
HashSet<Path> packages = new HashSet<>();
@Override
public void start() {
super.start();
blacklist.add("classes");
blacklist.add("eclipse");
blacklist.add(".git");
blacklist.add(".idea");
String webRoot = getOptionalStringConfig("webRoot", "");
if (webRoot.length() > 0) {
JsonArray packages = getOptionalArrayConfig("packages", new JsonArray());
for (Object pkg : packages) {
this.packages.add(Paths.get(String.valueOf(pkg)));
}
} else {
X_Log.info(getClass(), "No webRoot property specified for FileTree");
}
try {
watchService = FileSystems.getDefault().newWatchService();
Path rootPath = new File("").toPath();
treeScanner.walkFromRoot(rootPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
vertx.eventBus().consumer("tree.mutate", new FileTreeMutationHandler());
vertx.eventBus().consumer("tree.get", new FileTreeGetter());
vertx.eventBus().consumer("tree.getCurrentPaths", new PathResolver());
vertx.eventBus().consumer("tree.getResourceIds", new ResourceIdResolver());
/*
* This is not the one true vertx way... but it's easier for now! The watcher thread and the
* vertx thread really do need to sync up regarding tree state.
*/
watcherThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
processAllWatchEvents(watchService.take());
} catch (InterruptedException e) {
// Just exit the thread.
return;
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
});
watcherThread.setDaemon(true);
watcherThread.start();
}
@Override
public void stop() throws Exception {
synchronized (this.lock) {
watcherThread.interrupt();
}
watcherThread.join();
super.stop();
}
void processAllWatchEvents(WatchKey key) {
List<NodeInfoExt> adds = new ArrayList<NodeInfoExt>();
List<NodeInfoExt> removes = new ArrayList<NodeInfoExt>();
List<NodeInfoExt> modifies = new ArrayList<NodeInfoExt>();
HashMap<Path, ExpectedMove> movesByOld = new HashMap<Path, ExpectedMove>();
HashMap<Path, ExpectedMove> movesByNew = new HashMap<Path, ExpectedMove>();
List<ExpectedMove> completedMoves = new ArrayList<ExpectedMove>();
boolean treeDirty = false;
long treeVersion;
// System.out.println("-----");
synchronized (this.lock) {
treeVersion = this.currentTreeVersion;
// Grab all the outstanding moves.
for (ExpectedMove move : this.expectMoves) {
movesByOld.put(move.oldPath, move);
movesByNew.put(move.newPath, move);
}
this.expectMoves.clear();
do {
DirInfoExt parent = watchkeyToDir.get(key);
// process events
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind().type() == Path.class) {
Path path = (Path) event.context();
Path resolved = parent.getPath().resolve(path);
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
treeDirty = true;
try {
treeScanner.walk(resolved, parent);
NodeInfoExt added = parent.getChild(resolved.getFileName().toString());
ExpectedMove move = movesByNew.get(resolved);
if (move != null) {
move.newNode = added;
} else {
adds.add(added);
}
} catch (IOException e) {
// Just ignore it for now.
continue;
}
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
NodeInfoExt modified = parent.getChild(resolved.getFileName().toString());
modifies.add(modified);
} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
treeDirty = true;
NodeInfoExt removed = parent.removeChild(resolved.getFileName().toString());
ExpectedMove move = movesByOld.get(resolved);
if (move != null) {
move.oldNode = removed;
} else {
unmapResourceIds(removed);
removes.add(removed);
}
} else {
assert false : "Unknown event type: " + event.kind().name();
}
} else {
assert event.kind() == StandardWatchEventKinds.OVERFLOW;
System.out.print(event.kind().name() + ": ");
System.out.println(event.count());
// TODO: reload the entire tree???
}
}
// reset the key
boolean valid = key.reset();
if (!valid) {
// object no longer registered
watchkeyToDir.remove(key);
}
// Process all available events without blocking to minimize jitter.
key = watchService.poll();
} while (key != null);
if (treeDirty) {
treeVersion = currentTreeVersion++;
}
// Post-process moves.
for (ExpectedMove move : movesByOld.values()) {
if (move.oldNode == null) {
if (move.newNode == null) {
// Got nothing, put it back on the queue.
this.expectMoves.add(move);
} else {
// Convert to a create.
adds.add(move.newNode);
}
} else {
if (move.newNode == null) {
// Convert to a delete.
unmapResourceIds(move.oldNode);
removes.add(move.oldNode);
} else {
// Completed the move.
completedMoves.add(move);
// Update the edit session key to retain identity.
TreeNodeInfoImpl newNode = (TreeNodeInfoImpl) move.newNode;
newNode.setFileEditSessionKey(move.oldNode.getFileEditSessionKey());
resourceIdToNode.put(newNode.getFileEditSessionKey(), move.newNode);
}
}
}
// TODO: post-process deletes so that child deletes are subsumed by parent deletes.
}
// Notify the edit session verticle of the changes.
JsonObject message = new JsonObject();
JsonArray messageDelete = new JsonArray();
JsonArray messageModify = new JsonArray();
message.put("delete", messageDelete);
message.put("modify", messageModify);
// Broadcast a tree mutation to all clients.
WorkspaceTreeUpdateBroadcastImpl broadcast = WorkspaceTreeUpdateBroadcastImpl.make();
for (NodeInfoExt node : adds) {
System.out.println("add: " + pathString(node));
// Edit session doesn't care.
// Broadcast to clients.
MutationImpl mutation =
MutationImpl.make().setMutationType(Mutation.Type.ADD).setNewPath(pathString(node));
/*
* Do not strip the node; in the case of a newly scanned directory (e.g. recursive copy), its
* children to not get their own mutations, it's just a single tree.
*/
mutation.setNewNodeInfo((TreeNodeInfoImpl) node);
broadcast.getMutations().add(mutation);
}
for (NodeInfoExt node : removes) {
System.out.println("del: " + pathString(node));
// Edit session wants deletes.
messageDelete.add(node.getFileEditSessionKey());
// Broadcast to clients.
MutationImpl mutation =
MutationImpl.make().setMutationType(Mutation.Type.DELETE).setOldPath(pathString(node));
broadcast.getMutations().add(mutation);
}
for (ExpectedMove move : completedMoves) {
System.out.println("mov: " + pathString(move.oldNode) + " to: " + pathString(move.newNode));
// Edit session doesn't care.
// Broadcast to clients.
MutationImpl mutation = MutationImpl.make()
.setMutationType(Mutation.Type.MOVE).setNewPath(pathString(move.newNode))
.setOldPath(pathString(move.oldNode));
// Strip the node; the client should already have the children.
mutation.setNewNodeInfo(stripChildren(move.newNode));
broadcast.getMutations().add(mutation);
}
for (NodeInfoExt node : modifies) {
if (node == null) {
continue;
}
System.out.println("mod: " + pathString(node));
// Edit session wants modifies.
messageModify.add(node.getFileEditSessionKey());
// No broadcast, edit session will handle.
}
vertx.eventBus().send("documents.fileSystemEvents", message);
if (treeDirty) {
broadcast.setNewTreeVersion(Long.toString(treeVersion));
vertx.eventBus().send("participants.broadcast", new JsonObject().put(
Participants.PAYLOAD_TAG, broadcast.toJson()));
}
}
/**
* Strips out directory children for broadcast.
*/
private TreeNodeInfoImpl stripChildren(NodeInfoExt newNode) {
if (newNode.getNodeType() == TreeNodeInfo.FILE_TYPE) {
return (TreeNodeInfoImpl) newNode;
}
DirInfoImpl dir = (DirInfoImpl) newNode;
if ((dir.hasFiles() && dir.getFiles().size() > 0) || dir.hasSubDirectories()
&& dir.getSubDirectories().size() > 0) {
// Make a copy; modifying the node would change the real tree.
dir = DirInfoImpl.fromJsonElement(dir.toJsonElement());
dir.clearFiles();
dir.clearSubDirectories();
dir.setIsComplete(false);
}
return dir;
}
private String pathString(NodeInfoExt node) {
if (node.getNodeType() == TreeNodeInfo.FILE_TYPE) {
return '/' + node.getPath().toString();
} else {
return '/' + node.getPath().toString() + '/';
}
}
/**
* @param removed
*/
private void unmapResourceIds(NodeInfoExt removed) {
NodeInfoExt didRemove = resourceIdToNode.remove(removed.getFileEditSessionKey());
assert removed == didRemove;
if (removed instanceof DirInfoExt) {
DirInfoExt dir = (DirInfoExt) removed;
for (NodeInfoExt child : dir.getChildren()) {
unmapResourceIds(child);
}
}
}
/**
* This verticle needs to take "workspace rooted paths", which begin with a leading '/', and make
* them relative to the base directory for the associated classloader for this verticle. That is,
* assume that all paths are relative to what our local view of '.' is on the file system. We
* simply strip the leading slash. Also strip a trailing slash.
*/
private String stripSlashes(String relative) {
if (relative == null) {
return null;
} else if (relative.length() == 0) {
return relative;
} else {
relative = relative.charAt(0) == '/' ? relative.substring(1) : relative;
int last = relative.length() - 1;
if (last >= 0) {
relative = relative.charAt(last) == '/' ? relative.substring(0, last) : relative;
}
return relative;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/workspace/WorkspaceState.java | server/src/main/java/com/google/collide/server/workspace/WorkspaceState.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.workspace;
import com.google.collide.dto.server.DtoServerImpls.GetWorkspaceMetaDataResponseImpl;
import com.google.collide.dto.server.DtoServerImpls.RunTargetImpl;
import com.google.collide.server.shared.BusModBase;
import com.google.collide.server.shared.util.Dto;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import xapi.log.X_Log;
import java.util.ArrayList;
import java.util.List;
/**
* Persistent workspace state.
*/
public class WorkspaceState extends BusModBase {
private RunTargetImpl runTarget = RunTargetImpl.make().setRunMode("PREVIEW_CURRENT_FILE");
private String addressBase;
private String lastOpenedFileId;
private String webRoot;
@Override
public void start() {
super.start();
this.addressBase = getOptionalStringConfig("address", "workspace");
this.webRoot = getMandatoryStringConfig("webRoot");
vertx.eventBus()
.consumer(addressBase + ".getMetaData", requestEvent -> {
final GetWorkspaceMetaDataResponseImpl metaData =
GetWorkspaceMetaDataResponseImpl.make()
.setRunTarget(runTarget).setWorkspaceName(webRoot);
X_Log.trace(getClass(), "Last opened file: ", lastOpenedFileId);
if (lastOpenedFileId != null) {
// Resolve file to a path.
vertx.eventBus().<JsonObject>send("tree.getCurrentPaths", new JsonObject().put(
"resourceIds", new JsonArray().add(lastOpenedFileId)),
async -> {
Message<JsonObject> event = async.result();
List<String> openFiles = new ArrayList<String>();
openFiles.addAll(event.body().getJsonArray("paths").getList());
metaData.setLastOpenFiles(openFiles);
requestEvent.reply(Dto.wrap(metaData));
});
}
});
vertx.eventBus()
.<JsonObject>consumer(addressBase + ".setLastOpenedFile", event->lastOpenedFileId = event.body().getString("resourceId"));
vertx.eventBus()
.<JsonObject>consumer(addressBase + ".updateRunTarget",event-> {
RunTargetImpl runTarget = RunTargetImpl.fromJsonString(Dto.get(event));
WorkspaceState.this.runTarget = runTarget;
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/participants/Participants.java | server/src/main/java/com/google/collide/server/participants/Participants.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.participants;
import com.google.collide.dto.server.DtoServerImpls.GetWorkspaceParticipantsResponseImpl;
import com.google.collide.dto.server.DtoServerImpls.ParticipantImpl;
import com.google.collide.dto.server.DtoServerImpls.ParticipantUserDetailsImpl;
import com.google.collide.dto.server.DtoServerImpls.UserDetailsImpl;
import com.google.collide.server.shared.BusModBase;
import com.google.collide.server.shared.util.Dto;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
/**
* Acts as the authentication provider, with a compatible API subset with the bundled default
* AuthManager that comes with Vertx.
*
* This one however is in-memory, and also has affordances for broadcasting to joined participants.
* Also, this implementation allows for a single username to be logged in as multiple different
* sessions.
*/
public class Participants extends BusModBase {
public static final String CLIENT_ADDRESS_PREFX = "client";
public static final String PAYLOAD_TAG = "payload";
public static final String OMIT_SENDER_TAG = "omitSender";
public static final String TARGET_SPECIFIC_CLIENT_TAG = "sendToClient";
public static final String TARGET_USERS_TABS_TAG = "sendToUsersTabs";
private static final long DEFAULT_LOGIN_TIMEOUT = 60 * 60 * 1000; // 1 hour
// TODO: This is temporarily set to 30 mins for testing.
private static final long DEFAULT_KEEP_ALIVE_TIMEOUT = 30 * 1000 * 60; // 30 secs
/**
* A single Collide tab for a logged in user that is connected to the eventbus.
*/
private static final class ConnectedTab {
final LoggedInUser loginInfo;
long timerId;
ConnectedTab(LoggedInUser loginInfo, long tabDisconnectTimerId) {
this.loginInfo = loginInfo;
this.timerId = tabDisconnectTimerId;
}
}
/**
* A logged in user that may have multiple tabs open.
*/
private static final class LoggedInUser {
final String username;
/** Stable user ID for the lifetime of the server. */
final String userId;
long timerId;
private LoggedInUser(String username) {
this.username = username;
this.userId = getStableUserId(username);
}
/** Stable identifier for a username. Stable for the lifetime of the server. */
static final Map<String, String> usernameToStableIdMap = new HashMap<String, String>();
static String getStableUserId(String username) {
String stableId = usernameToStableIdMap.get(username);
if (stableId == null) {
stableId = UUID.randomUUID().toString();
usernameToStableIdMap.put(username, stableId);
}
return stableId;
}
}
private String password;
private long tabKeepAliveTimeout;
private long loginSessionTimeout;
/** Map of per-tab active client IDs to ConnectedTabs. */
protected final Map<String, ConnectedTab> connectedTabs = new HashMap<String, ConnectedTab>();
/** Map of per-user session IDs LoggedInUsers. */
protected final Map<String, LoggedInUser> loggedInUsers = new HashMap<String, LoggedInUser>();
@Override
public void start() {
super.start();
this.password = getOptionalStringConfig("password", "");
this.loginSessionTimeout = getOptionalLongConfig("session_timeout", DEFAULT_LOGIN_TIMEOUT);
this.tabKeepAliveTimeout = getOptionalLongConfig("keep_alive_timeout", DEFAULT_KEEP_ALIVE_TIMEOUT);
String addressBase = getOptionalStringConfig("address", "participants");
eb.consumer(addressBase + ".login", this::doLogin);
eb.consumer(addressBase + ".logout", this::doLogout);
eb.consumer(addressBase + ".authorise", this::doAuthorise);
eb.consumer(addressBase + ".keepAlive", this::doKeepAlive);
eb.consumer(addressBase + ".getParticipants", this::doGetParticipants);
eb.consumer(addressBase + ".broadcast", this::doBroadcast);
eb.consumer(addressBase + ".sendTo", this::doSendTo);
}
void doBroadcast(Message<JsonObject> event) {
String payload = event.body().getString(PAYLOAD_TAG);
String senderActiveClientId = event.body().getString(OMIT_SENDER_TAG);
Set<Entry<String, ConnectedTab>> entries = connectedTabs.entrySet();
for (Entry<String, ConnectedTab> entry : entries) {
String activeClientId = entry.getKey();
String address = CLIENT_ADDRESS_PREFX + "." + activeClientId;
// Send to everyone except the optionally specified sender that we wish to ignore.
if (!activeClientId.equals(senderActiveClientId)) {
vertx.eventBus().send(address, Dto.wrap(payload));
}
}
}
void doSendTo(Message<JsonObject> event) {
String payload = event.body().getString(PAYLOAD_TAG);
List<String> clientsToMessage = new ArrayList<String>();
String activeClientId = event.body().getString(TARGET_SPECIFIC_CLIENT_TAG);
if (activeClientId != null) {
// Send to a specific tab.
ConnectedTab tab = connectedTabs.get(activeClientId);
if (tab != null) {
clientsToMessage.add(activeClientId);
}
} else {
String username = event.body().getString(TARGET_USERS_TABS_TAG);
if (username != null) {
// Collect the ids of all this user's open tabs.
Set<Entry<String, ConnectedTab>> allClients = connectedTabs.entrySet();
for (Entry<String, ConnectedTab> entry : allClients) {
if (username.equals(entry.getValue().loginInfo.username)) {
clientsToMessage.add(entry.getKey());
}
}
}
}
// Message the clients.
for (String cid : clientsToMessage) {
vertx.eventBus().send(CLIENT_ADDRESS_PREFX + "." + cid, Dto.wrap(payload));
}
}
/**
* Returns all the connected tabs, as well as the user information for the user that owns each
* tab.
*/
void doGetParticipants(Message<JsonObject> event) {
GetWorkspaceParticipantsResponseImpl resp = GetWorkspaceParticipantsResponseImpl.make();
List<ParticipantUserDetailsImpl> collaboratorsArr = new ArrayList<ParticipantUserDetailsImpl>();
Set<Entry<String, ConnectedTab>> collaborators = connectedTabs.entrySet();
for (Entry<String, ConnectedTab> entry : collaborators) {
String userId = entry.getValue().loginInfo.userId;
String username = entry.getValue().loginInfo.username;
ParticipantUserDetailsImpl participantDetails = ParticipantUserDetailsImpl.make();
ParticipantImpl participant = ParticipantImpl.make().setId(entry.getKey()).setUserId(userId);
UserDetailsImpl userDetails = UserDetailsImpl.make()
.setUserId(userId).setDisplayEmail(username).setDisplayName(username)
.setGivenName(username);
participantDetails.setParticipant(participant);
participantDetails.setUserDetails(userDetails);
collaboratorsArr.add(participantDetails);
}
resp.setParticipants(collaboratorsArr);
event.reply(Dto.wrap(resp));
}
void doKeepAlive(Message<JsonObject> event) {
final String activeClientId = event.body().getString("activeClient");
if (activeClientId != null) {
ConnectedTab loginInfo = connectedTabs.get(activeClientId);
if (loginInfo != null) {
vertx.cancelTimer(loginInfo.timerId);
loginInfo.timerId = vertx.setTimer(tabKeepAliveTimeout,
id-> connectedTabs.remove(activeClientId));
}
}
}
void doLogin(final Message<JsonObject> message) {
System.out.println("Doing login: " + message.body());
final String username = message.body().getString("username", null);
if (username == null) {
sendStatus("denied", message);
return;
}
String password = message.body().getString("password", null);
if (password == null && !"".equals(this.password)) {
sendStatus("denied", message, new JsonObject().put("reason", "needs-pass"));
return;
}
if(!authenticate(username, password)) {
sendStatus("denied", message);
return;
}
// Passed authentication. Create a logged in user and a timer to expire his session.
if (alreadyLoggedIn(username)) {
// Cancel the previous session logout timer.
LoggedInUser existing = loggedInUsers.remove(LoggedInUser.getStableUserId(username));
vertx.cancelTimer(existing.timerId);
}
final LoggedInUser user = new LoggedInUser(username);
loggedInUsers.put(user.userId, user);
user.timerId = vertx.setTimer(loginSessionTimeout, e->logout(user.userId));
// The spelling "sessionID" is needed to work with the vertx eventbus bridge whitelist.
JsonObject jsonReply = new JsonObject().put("sessionID", user.userId);
sendOK(message, jsonReply);
}
/**
* This is NOT the same as authenticating. This just checks to see if we are tracking a login
* session for this username already.
*/
private boolean alreadyLoggedIn(String username) {
return loggedInUsers.get(LoggedInUser.getStableUserId(username)) != null;
}
private String createActiveTab(LoggedInUser user) {
final String activeClient = UUID.randomUUID().toString();
long timerId = vertx.setTimer(tabKeepAliveTimeout, id-> connectedTabs.remove(activeClient));
connectedTabs.put(activeClient, new ConnectedTab(user, timerId));
return activeClient;
}
private boolean authenticate(String username, String password) {
return "".equals(this.password) || password.equals(this.password);
}
void doLogout(final Message<JsonObject> message) {
final String sessionID = getMandatoryString("sessionID", message);
if (sessionID != null) {
if (logout(sessionID)) {
sendOK(message);
} else {
super.sendError(message, "Not logged in");
}
}
}
private boolean logout(String userId) {
LoggedInUser user = loggedInUsers.remove(userId);
if (user != null) {
List<Entry<String, ConnectedTab>> usersTabs = new ArrayList<Entry<String, ConnectedTab>>();
Set<Entry<String, ConnectedTab>> entries = connectedTabs.entrySet();
for (Entry<String, ConnectedTab> entry : entries) {
if (userId.equals(entry.getValue().loginInfo.userId)) {
usersTabs.add(entry);
}
}
for (int i=0;i<usersTabs.size();i++) {
connectedTabs.remove(usersTabs.get(i).getKey());
vertx.cancelTimer(usersTabs.get(i).getValue().timerId);
}
return true;
} else {
return false;
}
}
void doAuthorise(Message<JsonObject> message) {
String userId = getMandatoryString("sessionID", message);
if (userId == null) {
sendStatus("denied", message);
return;
}
LoggedInUser user = loggedInUsers.get(userId);
if (user != null || "".equals(password)) {
String username = message.body().getString("username", "anonymous");
if (user != null) {
username = user.username;
} else {
user = new LoggedInUser(username);
}
JsonObject reply = new JsonObject().put("username", username);
if (message.body().getBoolean("createClient", false)) {
String activeClient = createActiveTab(user);
reply.put("activeClient", activeClient);
}
sendOK(message, reply);
} else {
sendStatus("denied", message);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/DocOpComponentDeserializer.java | server/src/main/java/com/google/collide/server/documents/DocOpComponentDeserializer.java | // Copyright 2012 Google Inc. All Rights Reserved.
package com.google.collide.server.documents;
import static com.google.collide.dto.DocOpComponent.Type.DELETE;
import static com.google.collide.dto.DocOpComponent.Type.INSERT;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN_LINE;
import java.lang.reflect.Type;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.DocOpComponent.Delete;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.DocOpComponent.Retain;
import com.google.collide.dto.DocOpComponent.RetainLine;
import com.google.collide.dto.server.DtoServerImpls.DocOpComponentImpl;
import com.google.collide.dto.server.ServerDocOpFactory;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/*
* TODO(jasonparekh): consider creating custom deserializers for subclasses as a
* feature in our DTO generator, or at minimum constants for the JSON property
* keys.
*/
/**
* Custom {@link Gson} deserializer for {@link DocOpComponent} subclasses.
*
* @author jasonparekh@google.com (Jason Parekh)
*/
public class DocOpComponentDeserializer
implements
JsonDeserializer<DocOpComponentImpl>,
JsonSerializer<DocOpComponentImpl> {
@Override
public DocOpComponentImpl deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject componentJo = json.getAsJsonObject();
switch (componentJo.get("type").getAsInt()) {
case DELETE:
return (DocOpComponentImpl) ServerDocOpFactory.INSTANCE.createDelete(componentJo
.get("text")
.getAsString());
case INSERT:
return (DocOpComponentImpl) ServerDocOpFactory.INSTANCE.createInsert(componentJo
.get("text")
.getAsString());
case RETAIN:
return (DocOpComponentImpl) ServerDocOpFactory.INSTANCE.createRetain(
componentJo.get("count").getAsInt(),
componentJo.get("hasTrailingNewline").getAsBoolean());
case RETAIN_LINE:
return (DocOpComponentImpl) ServerDocOpFactory.INSTANCE.createRetainLine(componentJo.get(
"lineCount").getAsInt());
default:
throw new IllegalArgumentException("Could not deserialize DocOpComponent: "
+ componentJo);
}
}
@Override
public JsonElement serialize(DocOpComponentImpl component, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject componentJo = new JsonObject();
componentJo.addProperty("type", component.getType());
switch (component.getType()) {
case DELETE:
componentJo.addProperty("text", ((Delete) component).getText());
break;
case INSERT:
componentJo.addProperty("text", ((Insert) component).getText());
break;
case RETAIN:
componentJo.addProperty("count", ((Retain) component).getCount());
componentJo.addProperty("hasTrailingNewline", ((Retain) component).hasTrailingNewline());
break;
case RETAIN_LINE:
componentJo.addProperty("lineCount", ((RetainLine) component).getLineCount());
break;
default:
throw new IllegalArgumentException("Could not serialize DocOpComponent: " + component);
}
return componentJo;
}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/FileEditSessionImpl.java | server/src/main/java/com/google/collide/server/documents/FileEditSessionImpl.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.documents;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.server.documents.VersionedDocument.DocumentOperationException;
import com.google.collide.server.documents.VersionedDocument.VersionedText;
import com.google.collide.server.shared.merge.ConflictChunk;
import com.google.collide.server.shared.merge.MergeChunk;
import com.google.collide.server.shared.merge.MergeResult;
import com.google.collide.server.shared.util.FileHasher;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.Anchor.ShiftListener;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.collide.shared.document.anchor.InsertionPlacementStrategy;
import com.google.collide.shared.ot.DocOpUtils;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.protobuf.ByteString;
import io.vertx.core.logging.Logger;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Default implementation of {@link FileEditSession}.
*
* <p>
* This class is thread-safe.
*
*/
final class FileEditSessionImpl implements FileEditSession {
/**
* Bundles together a snapshot of the text of this file with any conflict chunks.
*/
private static class VersionedTextAndConflictChunksImpl
implements
VersionedTextAndConflictChunks {
private final VersionedText text;
private final List<AnchoredConflictChunk> conflictChunks;
VersionedTextAndConflictChunksImpl(
VersionedText text, List<AnchoredConflictChunk> conflictChunks) {
this.text = text;
this.conflictChunks = conflictChunks;
}
@Override
public VersionedText getVersionedText() {
return text;
}
@Override
public List<AnchoredConflictChunk> getConflictChunks() {
return conflictChunks;
}
}
private static class AnchoredConflictChunk extends ConflictChunk {
private static final AnchorType CONFLICT_CHUNK_START_LINE =
AnchorType.create(FileEditSessionImpl.class, "conflictChunkStart");
private static final AnchorType CONFLICT_CHUNK_END_LINE =
AnchorType.create(FileEditSessionImpl.class, "conflictChunkEnd");
public final Anchor startLineAnchor;
public final Anchor endLineAnchor;
public AnchoredConflictChunk(ConflictChunk chunk, VersionedDocument doc) {
super(chunk, chunk.isResolved());
// Add anchors at the conflict regions' boundaries, so their position/size
// gets adjusted automatically as the user enters text in and around them.
startLineAnchor = doc.addAnchor(
CONFLICT_CHUNK_START_LINE, chunk.getStartLine(), AnchorManager.IGNORE_COLUMN);
startLineAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT);
startLineAnchor.getShiftListenerRegistrar().add(new ShiftListener() {
@Override
public void onAnchorShifted(Anchor anchor) {
setStartLine(anchor.getLineNumber());
}
});
endLineAnchor =
doc.addAnchor(CONFLICT_CHUNK_END_LINE, chunk.getEndLine(), AnchorManager.IGNORE_COLUMN);
endLineAnchor.setInsertionPlacementStrategy(InsertionPlacementStrategy.LATER);
endLineAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT);
endLineAnchor.getShiftListenerRegistrar().add(new ShiftListener() {
@Override
public void onAnchorShifted(Anchor anchor) {
setEndLine(anchor.getLineNumber());
}
});
}
}
/**
* Given a merge result from the originally conflicted state, construct conflict chunks for it.
*/
private static List<ConflictChunk> constructConflictChunks(MergeResult mergeResult) {
List<ConflictChunk> conflicts = Lists.newArrayList();
for (MergeChunk mergeChunk : mergeResult.getMergeChunks()) {
if (mergeChunk.hasConflict()) {
conflicts.add(new ConflictChunk(mergeChunk));
}
}
return conflicts;
}
/**
* Document that contains the file contents.
*/
private VersionedDocument contents;
/** The list of conflict chunks for this file. */
private final List<AnchoredConflictChunk> conflictChunks = Lists.newArrayList();
/*
* The size and sha1 fields don't actually need to stay in lock-step with the doc contents since
* there's no public API for retrieving a snapshot of both values. Thus, we don't need blocking
* synchronization. We do however need to ensure that updates made by one thread are seen by other
* threads, so they must be declared volatile.
*/
/** Size of the file, in bytes. Lazily computed by {@link #getSize()}. */
private Integer size = null;
/** SHA-1 hash of the file contents. Lazily computed by {@link #getSha1()}. */
private ByteString sha1 = null;
/** CC revision of the document that we last saved */
private int lastSavedCcRevision;
/** CC revision of the document after the last mutation was applied */
private int lastMutationCcRevision;
/** True if the file-edit session has been closed */
private boolean closed = false;
/** When this file edit session was closed. Makes sense only if closed = true. */
private long closedTimeMs;
/** Time that this FileEditSession was created (millis since epoch) */
private final long createdAt = System.currentTimeMillis();
private OnCloseListener onCloseListener;
/** The ID of the resource this edit session is opened for. */
private final String resourceId;
private final Logger logger;
protected String lastSavedPath;
/**
* Constructs a {@link FileEditSessionImpl} for a file.
*
* @param resourceId the identifier for the resource we are editing.
* @param initialContents the initial contents of the file
* @param mergeResult if non-null the merge info related to the out of date
*/
FileEditSessionImpl(String resourceId, String path, String initialContents,
@Nullable MergeResult mergeResult, Logger logger) {
this.resourceId = resourceId;
this.lastSavedPath = path;
this.logger = logger;
this.contents = new VersionedDocument(initialContents, logger);
if (mergeResult != null) {
// Construct conflict chunks.
List<ConflictChunk> chunks = constructConflictChunks(mergeResult);
this.contents = new VersionedDocument(mergeResult.getMergedText(), logger);
if (chunks.size() == 0) {
logger.error(String.format("Non-null MergeResult passed to FileEditSession for file that"
+ " should have merged cleanly: [%s]", this));
}
for (ConflictChunk chunk : chunks) {
this.conflictChunks.add(new AnchoredConflictChunk(chunk, contents));
}
}
this.lastSavedCcRevision = contents.getCcRevision();
this.lastMutationCcRevision = 0;
logger.debug(String.format("FileEditSession [%s] was created at [%d]", this, createdAt));
}
@Override
protected void finalize() throws Throwable {
try {
if (!closed) {
logger.warn(
String.format("FileEditSession [%s] finalized without being closed first", this));
close();
}
} catch (Throwable thrown) {
logger.error(
String.format("Uncaught Throwable in FileEditSessionImpl.finalize of [%s]", this),
thrown);
} finally {
super.finalize();
}
}
private void checkNotClosed() {
if (closed) {
throw new FileEditSessionClosedException(resourceId, closedTimeMs);
}
}
@Override
public void close() {
// if already closed, do nothing and silently return
if (!closed) {
closed = true;
return;
}
closedTimeMs = System.currentTimeMillis();
// TODO: Maybe change the semantics of this method to block until
// all outstanding calls to other methods guarded by checkNotClosed()
// finish. IncrementableCountDownLatch would do the trick.
if (hasChanges()) {
logger.warn(String.format("FileEditSession [%s] closed while dirty", this));
}
if (onCloseListener != null) {
onCloseListener.onClosed();
}
}
@Override
public synchronized void setOnCloseListener(OnCloseListener listener) {
if (this.onCloseListener != null) {
throw new IllegalStateException("One listener already registered.");
}
this.onCloseListener = listener;
}
@Override
public VersionedDocument.ConsumeResult consume(List<DocOp> docOps, String authorClientId,
int intendedCcRevision, DocumentSelection selection) throws DocumentOperationException {
checkNotClosed();
boolean containsMutation = DocOpUtils.containsMutation(docOps);
VersionedDocument.ConsumeResult result =
contents.consume(docOps, authorClientId, intendedCcRevision, selection);
if (containsMutation) {
lastMutationCcRevision = contents.getCcRevision();
// Reset the cached size and SHA-1. We'll wait until someone actually calls getSize() or
// getSha1() to recompute them.
size = null;
sha1 = null;
}
return result;
}
private String getText() {
return contents.asText().text;
}
@Override
public String getContents() {
checkNotClosed();
return getText();
}
public int getCcRevision() {
return lastMutationCcRevision;
}
@Override
public int getSize() {
checkNotClosed();
if (size == null) {
try {
size = getText().getBytes("UTF-8").length;
} catch (UnsupportedEncodingException e) {
// UTF-8 is a charset required by Java spec, per javadoc of
// java.nio.charset.Charset, so this can't happen.
throw new RuntimeException("UTF-8 not supported in this JVM?!", e);
}
}
return size;
}
@Override
public ByteString getSha1() {
checkNotClosed();
if (sha1 == null) {
sha1 = FileHasher.getSha1(getText());
}
return sha1;
}
@Override
public VersionedDocument getDocument() {
checkNotClosed();
return contents;
}
@Override
public String getFileEditSessionKey() {
// probably ok to call on a closed FileEditSession
return resourceId;
}
@Override
public boolean hasChanges() {
return lastSavedCcRevision < lastMutationCcRevision;
}
@Override
public void save(String currentPath) throws IOException {
checkNotClosed();
if (currentPath == null) {
logger.fatal(String.format("We do do not know the path for edit session [%s]!", this));
return;
}
// Get a consistent snapshot of the raw text and conflict chunks
VersionedTextAndConflictChunksImpl snapshot = getContentsAndConflictChunks();
String text = snapshot.getVersionedText().text;
List<AnchoredConflictChunk> conflictChunks = snapshot.getConflictChunks();
if (hasUnresolvedConflictChunks(conflictChunks)) {
// TODO: There are conflict chunks in this file that need resolving.
saveConflictChunks(currentPath, text, conflictChunks);
} else {
// Remove all conflict chunk anchors from the document
for (AnchoredConflictChunk conflict : conflictChunks) {
contents.removeAnchor(conflict.startLineAnchor);
contents.removeAnchor(conflict.endLineAnchor);
}
conflictChunks.clear();
}
saveChanges(currentPath, text);
lastSavedCcRevision = snapshot.getVersionedText().ccRevision;
lastSavedPath = currentPath;
logger.debug(String.format("Saved file [%s]", this));
}
private void saveChanges(String path, String text) throws IOException {
/*
* TODO: what we really should do is track lastModified. Then we can lock,
* check the lastModified, and merge in any local FS changes that happened
* since we last saved.
*
* We should also listen on "documents.fileSystemEvents" for to get
* notified instantly when the FS version changes, so we can eagerly apply
* the delta and push to clients.
*/
logger.debug(String.format("Saving file [%s]", path));
File file = new File(path);
Files.write(text, file, Charsets.UTF_8);
}
private void saveConflictChunks(
String path, String text, List<AnchoredConflictChunk> conflictChunks) {
// TODO: Write the conflict chunks to some out of band location.
}
@Override
public List<ConflictChunk> getConflictChunks() {
return Lists.newArrayList((Iterable<? extends ConflictChunk>) conflictChunks);
}
@Override
public VersionedTextAndConflictChunksImpl getContentsAndConflictChunks() {
checkNotClosed();
return new VersionedTextAndConflictChunksImpl(contents.asText(), Lists.newArrayList(
conflictChunks));
}
@Override
public boolean resolveConflictChunk(int chunkIndex) throws IOException {
checkNotClosed();
AnchoredConflictChunk chunk = conflictChunks.get(chunkIndex);
if (chunk.isResolved()) {
/*
* This chunk can't be resolved because it is already resolved. This can happen if another
* collaborator resolved the chunk, but this client did not get the notification until they
* sent their own resolve message.
*/
return false;
}
chunk.markResolved(true);
logger.debug(String.format("Resolved conflict #%d in file [%s]", chunkIndex, this));
/*
* Immediately save the file.
*
* TODO: how to store chunk resolution?
*/
// TODO: Resolve path prior to calling save.
save(getSavedPath());
return true;
}
@Override
public boolean hasUnresolvedConflictChunks() {
return hasUnresolvedConflictChunks(getConflictChunks());
}
private static boolean hasUnresolvedConflictChunks(List<? extends ConflictChunk> conflictChunks) {
for (ConflictChunk conflict : conflictChunks) {
if (!conflict.isResolved()) {
return true;
}
}
return false;
}
@Override
public String toString() {
return resourceId;
}
@Override
public String getSavedPath() {
return lastSavedPath;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/EditSessions.java | server/src/main/java/com/google/collide/server/documents/EditSessions.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.documents;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.FileContents;
import com.google.collide.dto.FileContents.ContentType;
import com.google.collide.dto.server.DtoServerImpls.*;
import com.google.collide.json.server.JsonArrayListAdapter;
import com.google.collide.server.documents.VersionedDocument.AppliedDocOp;
import com.google.collide.server.documents.VersionedDocument.DocumentOperationException;
import com.google.collide.server.participants.Participants;
import com.google.collide.server.shared.BusModBase;
import com.google.collide.server.shared.util.Dto;
import com.google.collide.shared.MimeTypes;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
/**
* Backend service that maintains in-memory edit sessions for documents that are being
* collaboratively edited.
*
* All text mutations and document related changes are handled by this service.
*
*/
public class EditSessions extends BusModBase {
private static final Gson gson = new GsonBuilder().registerTypeAdapter(
DocOpComponentImpl.class, new DocOpComponentDeserializer()).serializeNulls().create();
/**
* Receives Document operations and applies them to the corresponding FileEditSession.
*
* If there is no associated FileEditSession, we need log an error since that probably means we
* have a stale client.
*/
class DocumentMutator implements Handler<Message<JsonObject>> {
private final SelectionTracker selectionTracker = new SelectionTracker();
@Override
public void handle(Message<JsonObject> message) {
ClientToServerDocOpImpl wrappedDocOp =
ClientToServerDocOpImpl.fromJsonString(Dto.get(message));
String resourceId = wrappedDocOp.getFileEditSessionKey();
FileEditSession editSession = editSessions.get(resourceId);
// Apply the DocOp.
if (editSession != null) {
List<String> docOps = ((JsonArrayListAdapter<String>) wrappedDocOp.getDocOps2()).asList();
ServerToClientDocOpsImpl appliedDocOps = applyMutation(
docOps, wrappedDocOp.getClientId(), wrappedDocOp.getCcRevision(),
wrappedDocOp.getSelection(), resourceId, editSession);
message.reply(Dto.wrap(appliedDocOps));
}
}
private List<DocOp> deserializeDocOps(List<String> serializedDocOps) {
List<DocOp> docOps = new ArrayList<DocOp>();
for (String serializedDocOp : serializedDocOps) {
docOps.add(gson.fromJson(serializedDocOp, DocOpImpl.class));
}
return docOps;
}
private ServerToClientDocOpsImpl applyMutation(List<String> serializedDocOps, String authorId,
int ccRevision, DocumentSelection selection, String resourceId, FileEditSession editSession) {
try {
List<DocOp> docOps = deserializeDocOps(serializedDocOps);
VersionedDocument.ConsumeResult result =
editSession.consume(docOps, authorId, ccRevision, selection);
// See if we need to update the selection
checkForSelectionChange(
authorId, resourceId, editSession.getDocument(), result.transformedDocumentSelection);
// Construct the Applied DocOp that we want to broadcast.
SortedMap<Integer, AppliedDocOp> appliedDocOps = result.appliedDocOps;
List<ServerToClientDocOpImpl> appliedDocOpsList = Lists.newArrayList();
for (Entry<Integer, VersionedDocument.AppliedDocOp> entry : appliedDocOps.entrySet()) {
DocOpImpl docOp = (DocOpImpl) entry.getValue().docOp;
ServerToClientDocOpImpl wrappedBroadcastDocOp = ServerToClientDocOpImpl.make()
.setClientId(authorId).setAppliedCcRevision(entry.getKey()).setDocOp2(docOp)
.setFileEditSessionKey(resourceId)
.setFilePath(editSession.getSavedPath());
appliedDocOpsList.add(wrappedBroadcastDocOp);
}
// Add the selection to the last DocOp if there was one.
if (result.transformedDocumentSelection != null && appliedDocOpsList.size() > 0) {
appliedDocOpsList.get(appliedDocOpsList.size() - 1)
.setSelection((DocumentSelectionImpl) result.transformedDocumentSelection);
}
// Broadcast the applied DocOp all the participants, ignoring the sender.
ServerToClientDocOpsImpl broadcastedDocOps =
ServerToClientDocOpsImpl.make().setDocOps(appliedDocOpsList);
vertx.eventBus().send("participants.broadcast", new JsonObject().put(
Participants.OMIT_SENDER_TAG, authorId).put(
"payload", broadcastedDocOps.toJson()));
return broadcastedDocOps;
} catch (DocumentOperationException e) {
logger.error(String.format("Failed to apply DocOps [%s]", serializedDocOps));
}
return null;
}
private void checkForSelectionChange(String clientId, String resourceId,
VersionedDocument document, DocumentSelection documentSelection) {
/*
* Currently, doc ops either contain text changes or selection changes (via annotation doc op
* components). Both of these modify the user's selection/cursor.
*/
selectionTracker.selectionChanged(clientId, resourceId, document, documentSelection);
}
}
/**
* Replies with the DocOps that were missed by the requesting client.
*/
class DocOpRecoverer implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> event) {
RecoverFromMissedDocOpsImpl req = RecoverFromMissedDocOpsImpl.fromJsonString(Dto.get(event));
String resourceId = req.getFileEditSessionKey();
FileEditSession editSession = editSessions.get(resourceId);
if (editSession == null) {
logger.error("No edit session for resourceId " + resourceId);
// TODO: This is going to leave the reply handler hanging.
return;
}
List<String> docOps = ((JsonArrayListAdapter<String>) req.getDocOps2()).asList();
// If the client is re-sending any unacked doc ops, apply them first
if (req.getDocOps2().size() > 0) {
documentMutator.applyMutation(
docOps, req.getClientId(), req.getCurrentCcRevision(), null, resourceId, editSession);
}
// Get all the applied doc ops the client doesn't know about
SortedMap<Integer, VersionedDocument.AppliedDocOp> appliedDocOps =
editSession.getDocument().getAppliedDocOps(req.getCurrentCcRevision() + 1);
List<ServerToClientDocOpImpl> appliedDocOpsList = Lists.newArrayList();
for (Entry<Integer, VersionedDocument.AppliedDocOp> entry : appliedDocOps.entrySet()) {
DocOpImpl docOp = (DocOpImpl) entry.getValue().docOp;
ServerToClientDocOpImpl wrappedBroadcastDocOp = ServerToClientDocOpImpl.make()
.setClientId(req.getClientId()).setAppliedCcRevision(entry.getKey()).setDocOp2(docOp)
.setFileEditSessionKey(resourceId)
.setFilePath(editSession.getSavedPath());
appliedDocOpsList.add(wrappedBroadcastDocOp);
}
RecoverFromMissedDocOpsResponseImpl resp =
RecoverFromMissedDocOpsResponseImpl.make().setDocOps(appliedDocOpsList);
event.reply(Dto.wrap(resp));
}
}
/**
* Creates a FileEditSession if there is not one already present and
*/
class EditSessionCreator implements Handler<Message<JsonObject>> {
/**
* Whether or not to provision an edit session if one is missing, before sending the file
* contents
*/
private final boolean provisionEditSession;
EditSessionCreator(boolean provisionEditSession) {
this.provisionEditSession = provisionEditSession;
}
@Override
public void handle(final Message<JsonObject> message) {
final GetFileContentsImpl request = GetFileContentsImpl.fromJsonString(Dto.get(message));
// Resolve the resource IDs from the requested path.
vertx.eventBus().<JsonObject>send("tree.getResourceIds",
new JsonObject().put("paths", new JsonArray().add(request.getPath())),
async -> {
/**
* Sends the contents of a file to the requester. The files will be served out of the
* FileEditSession if the contents are being edited, otherwise they will simply be
* served from disk.
*/
Message<JsonObject> event = async.result();
JsonArray resourceIdArr = event.body().getJsonArray("resourceIds");
List<String> resourceIds = resourceIdArr.getList();
String resourceId = resourceIds.get(0);
String currentPath = stripLeadingSlash(request.getPath());
FileEditSession editSession = editSessions.get(resourceId);
// Create the DTO for the file contents response. We will build it up later in the
// method.
String mimeType = MimeTypes.guessMimeType(currentPath, false);
FileContentsImpl fileContentsDto =
FileContentsImpl.make().setMimeType(mimeType).setPath(currentPath);
if (editSession == null) {
// We need to start a new edit session.
String text = "";
File file = new File(currentPath);
try {
text = Files.toString(file, Charsets.UTF_8);
} catch (IOException e) {
logger.error(
String.format("Failed to read text contents for path [%s]", currentPath));
// Send back a no file indicating that file does not exist.
sendContent(message, currentPath, null, false);
return;
}
if (provisionEditSession) {
// Provision a new edit session and fall through.
editSession =
new FileEditSessionImpl(resourceId, currentPath, text, null, logger);
editSessions.put(resourceId, editSession);
// Update the last opened file.
vertx.eventBus().send("workspace.setLastOpenedFile",
new JsonObject().put("resourceId", resourceId));
} else {
// Just send the contents as they were read from disk and return.
String dataBase64 = MimeTypes.looksLikeImage(mimeType) ? StringUtils
.newStringUtf8(Base64.encodeBase64(text.getBytes())) : null;
fileContentsDto.setContents(dataBase64).setContentType(
dataBase64 == null ? ContentType.UNKNOWN_BINARY : ContentType.IMAGE);
sendContent(message, currentPath, fileContentsDto, true);
return;
}
}
// Populate file contents response Dto with information from the edit session.
fileContentsDto.setFileEditSessionKey(resourceId)
.setCcRevision(editSession.getDocument().getCcRevision())
.setContents(editSession.getContents()).setContentType(ContentType.TEXT);
// Extract the contents from the edit session before sending.
sendContent(message, currentPath, fileContentsDto, true);
});
}
}
void sendContent(
Message<JsonObject> event, String path, FileContents fileContents, boolean fileExists) {
GetFileContentsResponseImpl response = GetFileContentsResponseImpl.make()
.setFileExists(fileExists).setFileContents((FileContentsImpl) fileContents);
event.reply(Dto.wrap(response.toJson()));
}
/**
* Iterates through all open, dirty edit sessions and saves them to disk.
*/
class FileSaver implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> message) {
saveAll();
}
void saveAll() {
Set<Entry<String, FileEditSession>> entries = editSessions.entrySet();
Iterator<Entry<String, FileEditSession>> entryIter = entries.iterator();
final JsonArray resourceIds = new JsonArray();
while (entryIter.hasNext()) {
Entry<String, FileEditSession> entry = entryIter.next();
String resourceId = entry.getKey();
FileEditSession editSession = entry.getValue();
if (editSession.hasChanges()) {
resourceIds.add(resourceId);
}
}
// Resolve the current paths of opened files in case they have been moved.
eb.<JsonObject>send("tree.getCurrentPaths", new JsonObject().put("resourceIds", resourceIds),
message -> {
final Message<JsonObject> event = message.result();
if (message.failed()) {
logger.error("Message failed calling tree.getCurrentPaths for resourceIds " + resourceIds, message.cause());
return;
}
JsonArray currentPaths = event.body().getJsonArray("paths");
Iterator<Object> pathIter = currentPaths.iterator();
Iterator<Object> resourceIter = resourceIds.iterator();
if (currentPaths.size() != resourceIds.size()) {
logger.error(String.format(
"Received [%d] paths in response to a request specifying [%d] resourceIds",
currentPaths.size(), resourceIds.size()));
}
// Iterate through all the resolved paths and save the files to disk.
while (pathIter.hasNext()) {
String path = (String) pathIter.next();
String resourceId = (String) resourceIter.next();
if (path != null) {
FileEditSession editSession = editSessions.get(resourceId);
if (editSession != null) {
try {
editSession.save(stripLeadingSlash(path));
} catch (IOException e) {
logger.error(String.format("Failed to save file [%s]", path), e);
}
}
}
}
}
);
}
}
/**
* Removes an edit session, and notifies clients that they should reload their opened document.
*/
class EditSessionRemover implements Handler<Message<JsonObject>> {
@Override
public void handle(Message<JsonObject> message) {
String resourceId = message.body().getString("resourceId");
if (resourceId != null) {
editSessions.remove(resourceId);
}
// TODO: Notify clients to reload their opened document.
}
}
private final Map<String, FileEditSession> editSessions = new HashMap<String, FileEditSession>();
private final FileSaver fileSaver = new FileSaver();
private final DocumentMutator documentMutator = new DocumentMutator();
private String addressBase;
@Override
public void start() {
super.start();
this.addressBase = getOptionalStringConfig("address", "documents");
vertx.eventBus().consumer(addressBase + ".mutate", documentMutator);
vertx.eventBus().consumer(
addressBase + ".createEditSession", new EditSessionCreator(true));
vertx.eventBus().consumer(
addressBase + ".getFileContents", new EditSessionCreator(false));
vertx.eventBus().consumer(addressBase + ".saveAll", fileSaver);
vertx.eventBus().consumer(addressBase + ".removeEditSession", new EditSessionRemover());
vertx.eventBus().consumer(addressBase + ".recoverMissedDocop", new DocOpRecoverer());
// TODO: Handle content changes on disk and synthesize a docop to apply to the in-memory edit
// session, and broadcast to all clients.
// Set up a regular save interval to flush to disk.
vertx.setPeriodic(1500, new Handler<Long>() {
@Override
public void handle(Long event) {
fileSaver.saveAll();
}
});
}
/**
* This verticle needs to take "workspace rooted paths", which begin with a leading '/', and make
* them relative to the base directory for the associated classloader for this verticle. That is,
* assume that all paths are relative to what our local view of '.' is on the file system. We
* simply strip the leading slash.
*/
private static String stripLeadingSlash(String relative) {
if (relative == null) {
return null;
} else {
return relative.charAt(0) == '/' ? relative.substring(1) : relative;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/FileEditSession.java | server/src/main/java/com/google/collide/server/documents/FileEditSession.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.documents;
import java.io.IOException;
import java.util.List;
import com.google.collide.dto.ClientToServerDocOp;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.server.documents.VersionedDocument.DocumentOperationException;
import com.google.collide.server.documents.VersionedDocument.VersionedText;
import com.google.collide.server.shared.merge.ConflictChunk;
/**
* A single workspace file, backed by a {@link VersionedDocument}. Its contents
* can be accessed as plain text. However, it can be mutated <em>only</em> via
* the application of doc ops passed to
* {@link FileEditSession#consume(List, String, int, DocumentSelection)}.
*
*/
public interface FileEditSession extends ImmutableFileEditSession {
public class FileEditSessionClosedException extends IllegalStateException {
/**
*
*/
private static final long serialVersionUID = -5178850406109791383L;
public FileEditSessionClosedException(String resourceId, long closedTimeMs) {
super(String.format(
"Operation not allowed on closed FileEditSession [%s], closed [%d] ms ago", resourceId,
System.currentTimeMillis() - closedTimeMs));
}
}
public interface VersionedTextAndConflictChunks {
VersionedText getVersionedText();
List<? extends ConflictChunk> getConflictChunks();
}
interface OnCloseListener {
void onClosed();
}
/**
* Releases the resources for this {@code FileEditSession}. Many methods will
* throw IllegalStateException if called on a closed session object. However,
* this method can return before outstanding calls to those methods finish
* executing.
*/
void close();
/**
* Sets a listener that is called when this file edit session is closed.
* Only one listener can be set.
*
* @param onCloseListener listener to call when file edit session is closed.
* @throws IllegalStateException if there is already a listener attached
*/
void setOnCloseListener(OnCloseListener onCloseListener);
/**
* Applies a list of doc ops to the backing document.
*
* @param docOps the list of doc ops being applied
* @param authorClientId clientId who sent the doc ops
* @param intendedCcRevision the revision of the document that the doc ops are
* intended to be applied to
* @param selection see {@link ClientToServerDocOp#getSelection()}
* @return the result of the consume operation
* @throws DocumentOperationException if there was a problem with consuming
* the document operation
*/
VersionedDocument.ConsumeResult consume(List<DocOp> docOps, String authorClientId,
int intendedCcRevision, DocumentSelection selection) throws DocumentOperationException;
VersionedDocument getDocument();
/**
* Saves the file.
* @throws IOException
*/
void save(String currentPath) throws IOException;
/**
* @return the text and any conflict chunks, along with a revision
*/
VersionedTextAndConflictChunks getContentsAndConflictChunks();
List<ConflictChunk> getConflictChunks();
/**
* @return true if the conflict chunk is now resolved. false if the chunk was already resolved
* (e.g., a collaborator raced for the resolution and won).
* @throws IOException
*/
boolean resolveConflictChunk(int chunkIndex) throws IOException;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/VersionedDocument.java | server/src/main/java/com/google/collide/server/documents/VersionedDocument.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.documents;
import com.google.collide.dto.ClientToServerDocOp;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.server.DtoServerImpls.DocumentSelectionImpl;
import com.google.collide.dto.server.DtoServerImpls.FilePositionImpl;
import com.google.collide.dto.server.ServerDocOpFactory;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.collide.shared.ot.Composer;
import com.google.collide.shared.ot.Composer.ComposeException;
import com.google.collide.shared.ot.DocOpApplier;
import com.google.collide.shared.ot.DocOpUtils;
import com.google.collide.shared.ot.OperationPair;
import com.google.collide.shared.ot.PositionTransformer;
import com.google.collide.shared.ot.Transformer;
import com.google.collide.shared.ot.Transformer.TransformException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.vertx.core.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A document at a specific revision. It can be converted to and from raw text, and can be mutated
* via the application of document operations passed to
* {@link #consume(List, String, int, DocumentSelection)}.
*
* <p>
* This class is thread-safe.
*
*/
public class VersionedDocument {
/**
* A simple class for the result of the {@link VersionedDocument#consume} method.
*/
public static class ConsumeResult {
/**
* The set of transformed DocOps, where the value is the DocOp and the key is the revision of
* the document resulting from the application of that DocOp. The size of the returned Map will
* equal that of the List of input DocOps.
*/
public final SortedMap<Integer, AppliedDocOp> appliedDocOps;
/**
* The transformed selection of the user, or null if one was not given.
*
* @see ClientToServerDocOp#getSelection()
*/
public final DocumentSelection transformedDocumentSelection;
private ConsumeResult(SortedMap<Integer, AppliedDocOp> appliedDocOps,
DocumentSelection transformedDocumentSelection) {
this.appliedDocOps = appliedDocOps;
this.transformedDocumentSelection = transformedDocumentSelection;
}
}
/**
* Doc op that was applied to the document, tagged with its author.
*/
public static class AppliedDocOp {
public final DocOp docOp;
public final String authorClientId;
private AppliedDocOp(DocOp docOp, String authorClientId) {
this.docOp = docOp;
this.authorClientId = authorClientId;
}
@Override
public String toString() {
return "[" + authorClientId + ", " + DocOpUtils.toString(docOp, true) + "]";
}
}
/**
* Serialized form of the document at a particular revision.
*/
public static class VersionedText {
public final int ccRevision;
public final String text;
private VersionedText(int ccRevision, String text) {
this.ccRevision = ccRevision;
this.text = text;
}
}
/**
* Thrown when there was a problem with document operations transformation or composition.
*/
public static class DocumentOperationException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7596186181810388015L;
public DocumentOperationException(String text, Throwable cause) {
super(text, cause);
}
public DocumentOperationException(String text) {
super(text);
}
}
/** Revision number of the document */
private int ccRevision;
/** Backing document */
private final Document contents;
/**
* Stores the doc ops used to build the document, where the doc op at index i was applied to form
* the document at revision i. There is a null value at index 0 since there was no doc op that
* gave birth to the document.
*/
private final List<AppliedDocOp> docOpHistory;
/**
* Intended revision of the last doc op from each client. If we see the same revision twice, we
* consider the second a duplicate and discard it. One such scenario would be when the client
* re-sends an unacked doc op after being momentarily disconnected, but the original doc op
* actually did make it to the server.
*/
private final Map<String, Integer> lastIntendedCcRevisionPerClient = Maps.newHashMap();
private final Logger logger;
/**
* Constructs a new {@link VersionedDocument} with the given contents and revision number
*/
public VersionedDocument(Document contents, int ccRevision, Logger logger) {
this.ccRevision = ccRevision;
this.contents = contents;
this.logger = logger;
// See javadoc for docOpHistory to understand the null element
this.docOpHistory = Lists.newArrayList((AppliedDocOp) null);
}
/**
* Constructs a new {@link VersionedDocument} with the given initial contents. The revision number
* starts at zero.
*/
public VersionedDocument(String initialContents, Logger logger) {
this(Document.createFromString(initialContents), 0, logger);
}
public int getCcRevision() {
return ccRevision;
}
/**
* Applies the given list of {@link DocOp DocOps} to the backing document.
*
* @param docOps the list of {@code DocOp}s being applied
* @param authorClientId clientId who sent the doc ops
* @param intendedCcRevision the revision of the document that the DocOps are intended to be
* applied to
* @param selection see {@link ClientToServerDocOp#getSelection()}
* @return the transformed doc ops, or <code>null</code> if we discarded them as duplicates
*/
public ConsumeResult consume(List<? extends DocOp> docOps, String authorClientId,
int intendedCcRevision, DocumentSelection selection) throws DocumentOperationException {
return consumeWithoutLocking(docOps, authorClientId, intendedCcRevision, selection);
}
/**
* Private helper method that does the actual work of consuming doc ops. The publicly-visible
* {@link #consume(List, String, int, DocumentSelection)} takes care of acquiring/releasing the
* write lock around calls to this method.
*/
private ConsumeResult consumeWithoutLocking(List<? extends DocOp> docOps, String authorClientId,
int intendedCcRevision, DocumentSelection selection) throws DocumentOperationException {
// Check the incoming intended revision against what we last got from this
// client
Integer lastIntendedCcRevision = lastIntendedCcRevisionPerClient.get(authorClientId);
if (lastIntendedCcRevision != null) {
if (intendedCcRevision == lastIntendedCcRevision.intValue()) {
// We've already seen a doc op from this client intended for this
// revision, assume this is a retry and ignore
logger.debug(String.format(
"clientId [%s] already sent a doc op intended for revision [%d]; "
+ "ignoring this one ", authorClientId, intendedCcRevision));
return null;
}
// Sanity check that the client is not sending an obsolete doc op
if (intendedCcRevision < lastIntendedCcRevision.intValue()) {
logger.error(String.format(
"clientId [%s] is sending a doc op intended for revision [%d] older than "
+ "the last one [%d] we saw from that client", authorClientId, intendedCcRevision,
lastIntendedCcRevision.intValue()));
return null;
}
}
/*
* First step, build the bridge from the intended revision to the latest revision by composing
* all of the doc ops between these ranges. This bridge will be used to update a client doc op
* that's intended to be applied to a document in the past.
*/
DocOp bridgeDocOp = null;
int bridgeBeginIndex = intendedCcRevision + 1;
int bridgeEndIndexInclusive = ccRevision;
for (int i = bridgeBeginIndex; i <= bridgeEndIndexInclusive; i++) {
DocOp curDocOp = docOpHistory.get(i).docOp;
try {
bridgeDocOp = bridgeDocOp == null ? curDocOp : Composer.compose(
ServerDocOpFactory.INSTANCE, bridgeDocOp, curDocOp);
} catch (ComposeException e) {
throw newExceptionForConsumeWithoutLocking("Could not build bridge",
e,
intendedCcRevision,
bridgeBeginIndex,
bridgeEndIndexInclusive,
docOps);
}
}
/*
* Second step, iterate through doc ops from the client and transform each against the bridge.
* Take the server op result of the transformation and make that the new bridge. Record each
* into our map that will be returned to the caller of this method.
*/
SortedMap<Integer, AppliedDocOp> appliedDocOps = new TreeMap<Integer, AppliedDocOp>();
for (int i = 0, n = docOps.size(); i < n; i++) {
DocOp clientDocOp = docOps.get(i);
if (bridgeDocOp != null) {
try {
OperationPair transformedPair =
Transformer.transform(ServerDocOpFactory.INSTANCE, clientDocOp, bridgeDocOp);
clientDocOp = transformedPair.clientOp();
bridgeDocOp = transformedPair.serverOp();
} catch (TransformException e) {
throw newExceptionForConsumeWithoutLocking("Could not transform doc op\ni: " + i + "\n",
e,
intendedCcRevision,
bridgeBeginIndex,
bridgeEndIndexInclusive,
docOps);
}
}
try {
DocOpApplier.apply(clientDocOp, contents);
} catch (Throwable t) {
throw newExceptionForConsumeWithoutLocking("Could not apply doc op\nDoc op being applied: "
+ DocOpUtils.toString(clientDocOp, true) + "\n",
t,
intendedCcRevision,
bridgeBeginIndex,
bridgeEndIndexInclusive,
docOps);
}
AppliedDocOp appliedDocOp = new AppliedDocOp(clientDocOp, authorClientId);
docOpHistory.add(appliedDocOp);
ccRevision++;
appliedDocOps.put(ccRevision, appliedDocOp);
lastIntendedCcRevisionPerClient.put(authorClientId, intendedCcRevision);
}
if (bridgeDocOp != null && selection != null) {
PositionTransformer cursorTransformer = new PositionTransformer(
selection.getCursorPosition().getLineNumber(), selection.getCursorPosition().getColumn());
cursorTransformer.transform(bridgeDocOp);
PositionTransformer baseTransformer = new PositionTransformer(
selection.getBasePosition().getLineNumber(), selection.getBasePosition().getColumn());
baseTransformer.transform(bridgeDocOp);
FilePositionImpl basePosition = FilePositionImpl.make().setLineNumber(
baseTransformer.getLineNumber()).setColumn(baseTransformer.getColumn());
FilePositionImpl cursorPosition = FilePositionImpl.make().setLineNumber(
cursorTransformer.getLineNumber()).setColumn(cursorTransformer.getColumn());
DocumentSelectionImpl transformedSelection = DocumentSelectionImpl.make()
.setBasePosition(basePosition).setCursorPosition(cursorPosition)
.setUserId(selection.getUserId());
selection = transformedSelection;
}
return new ConsumeResult(appliedDocOps, selection);
}
private DocumentOperationException newExceptionForConsumeWithoutLocking(String customMessage,
Throwable e,
int intendedCcRevision,
int bridgeBeginIndex,
int bridgeEndIndexInclusive,
List<? extends DocOp> clientDocOps) {
StringBuilder msg = new StringBuilder(customMessage).append('\n');
msg.append("ccRevision: ").append(ccRevision).append('\n');
msg.append("intendedCcRevision: ").append(intendedCcRevision).append('\n');
msg.append("Bridge from ")
.append(bridgeBeginIndex)
.append(" to ")
.append(bridgeEndIndexInclusive)
.append(" doc ops:\n")
.append(docOpHistory.subList(bridgeBeginIndex, bridgeEndIndexInclusive + 1))
.append("\n");
msg.append("Document (hyphens are line separators):\n").append(contents.asDebugString());
msg.append("Client doc ops:\n")
.append(DocOpUtils.toString(clientDocOps, 0, clientDocOps.size() - 1, true)).append("\n");
msg.append("Recent doc ops from server history:\n").append(docOpHistoryToString());
return new DocumentOperationException(msg.toString(), e);
}
public SortedMap<Integer, AppliedDocOp> getAppliedDocOps(int startingCcRevision) {
SortedMap<Integer, AppliedDocOp> appliedDocOps = new TreeMap<Integer, AppliedDocOp>();
if (startingCcRevision > (docOpHistory.size() - 1)) {
logger.error(String.format(
"startingCcRevision [%d] is larger than last revision in docOpHistory [%d]",
startingCcRevision, docOpHistory.size()));
return appliedDocOps;
}
for (int i = startingCcRevision; i < docOpHistory.size(); i++) {
appliedDocOps.put(i, docOpHistory.get(i));
}
return appliedDocOps;
}
public VersionedText asText() {
return new VersionedText(ccRevision, contents.asText());
}
/**
* @param column the column of the anchor, or {@link AnchorManager#IGNORE_COLUMN} for a line
* anchor
*/
public Anchor addAnchor(AnchorType type, int lineNumber, int column) {
LineInfo lineInfo = contents.getLineFinder().findLine(lineNumber);
return contents.getAnchorManager()
.createAnchor(type, lineInfo.line(), lineInfo.number(), column);
}
/**
* @param column the column of the anchor, or {@link AnchorManager#IGNORE_COLUMN} for a line
* anchor
*/
public void moveAnchor(Anchor anchor, int lineNumber, int column) {
LineInfo lineInfo = contents.getLineFinder().findLine(lineNumber);
contents.getAnchorManager().moveAnchor(anchor, lineInfo.line(), lineInfo.number(), column);
}
public void removeAnchor(Anchor anchor) {
contents.getAnchorManager().removeAnchor(anchor);
}
private String docOpHistoryToString() {
List<DocOp> docOps = Lists.newArrayListWithExpectedSize(docOpHistory.size());
for (AppliedDocOp appliedDocOp : docOpHistory) {
docOps.add(appliedDocOp == null ? null : appliedDocOp.docOp);
}
return DocOpUtils.toString(
docOps, Math.max(0, docOps.size() - 10), Math.max(0, docOps.size() - 1), false);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/ImmutableFileEditSession.java | server/src/main/java/com/google/collide/server/documents/ImmutableFileEditSession.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.documents;
import com.google.protobuf.ByteString;
/**
* A read-only view of a {@link FileEditSession}.
*/
public interface ImmutableFileEditSession {
String getContents();
int getSize();
ByteString getSha1();
String getFileEditSessionKey();
boolean hasChanges();
/**
* @return last known saved full path of the file
*/
String getSavedPath();
boolean hasUnresolvedConflictChunks();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/documents/SelectionTracker.java | server/src/main/java/com/google/collide/server/documents/SelectionTracker.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.documents;
import java.util.List;
import java.util.Map;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.dto.server.DtoServerImpls.DocumentSelectionImpl;
import com.google.collide.dto.server.DtoServerImpls.FilePositionImpl;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Helper that tracks the selection (cursor and base positions) for each user.
*
*/
public class SelectionTracker {
private class UserSelection {
private final String clientId;
private VersionedDocument document;
private String resourceId;
private Anchor cursorAnchor;
private Anchor baseAnchor;
private UserSelection(String clientId) {
this.clientId = clientId;
}
private synchronized void teardown() {
removeAnchors();
}
private synchronized void markActive(
final String resourceId, VersionedDocument document, DocumentSelection documentSelection) {
if (this.document != document) {
/*
* The user switched files or the VersionedDocument instance swapped underneath us (in the
* latter case, just checking the equality of FileEditSessionKeys would not be enough)
*/
removeAnchors();
this.resourceId = resourceId;
this.document = document;
}
if (documentSelection != null) {
// Cursor/selection has moved via explicit movement action
moveOrCreateAnchors(document, documentSelection);
}
}
private synchronized void moveOrCreateAnchors(
VersionedDocument document, DocumentSelection documentSelection) {
if (cursorAnchor != null) {
document.moveAnchor(cursorAnchor, documentSelection.getCursorPosition().getLineNumber(),
documentSelection.getCursorPosition().getColumn());
document.moveAnchor(baseAnchor, documentSelection.getBasePosition().getLineNumber(),
documentSelection.getBasePosition().getColumn());
} else {
cursorAnchor = document.addAnchor(
CURSOR_ANCHOR_TYPE, documentSelection.getCursorPosition().getLineNumber(),
documentSelection.getCursorPosition().getColumn());
cursorAnchor.setRemovalStrategy(RemovalStrategy.SHIFT);
baseAnchor = document.addAnchor(
BASE_ANCHOR_TYPE, documentSelection.getBasePosition().getLineNumber(),
documentSelection.getBasePosition().getColumn());
baseAnchor.setRemovalStrategy(RemovalStrategy.SHIFT);
}
}
private synchronized void removeAnchors() {
if (cursorAnchor != null) {
document.removeAnchor(cursorAnchor);
cursorAnchor = null;
}
if (baseAnchor != null) {
document.removeAnchor(baseAnchor);
baseAnchor = null;
}
}
@Override
public boolean equals(Object obj) {
return obj instanceof UserSelection && clientId.equals(((UserSelection) obj).clientId);
}
@Override
public int hashCode() {
return clientId.hashCode();
}
}
private static final AnchorType CURSOR_ANCHOR_TYPE =
AnchorType.create(SelectionTracker.class, "cursor");
private static final AnchorType BASE_ANCHOR_TYPE =
AnchorType.create(SelectionTracker.class, "base");
/**
* All active selections, keyed by the user's gaia ID.
*/
private final Map<String, UserSelection> userSelections = Maps.newHashMap();
@VisibleForTesting
SelectionTracker() {
// TODO: Listen for client disconnections to remove selections.
}
/**
* Releases all resources.
*/
public void close() {
for (UserSelection selection : userSelections.values()) {
selection.teardown();
}
}
/**
* Called when the selection for a user changes.
*
* @param clientId the ID for the user's tab
* @param resourceId the key for the file edit session that holds the active selection
* @param documentSelection the position of the selection after any mutations currently being
* processed
*/
public void selectionChanged(String clientId, String resourceId, VersionedDocument document,
DocumentSelection documentSelection) {
UserSelection selection = userSelections.get(clientId);
if (selection == null) {
selection = new UserSelection(clientId);
userSelections.put(clientId, selection);
}
selection.markActive(resourceId, document, documentSelection);
}
public List<DocumentSelection> getDocumentSelections(String resourceId) {
List<DocumentSelection> selections = Lists.newArrayList();
for (UserSelection userSelection : userSelections.values()) {
if (userSelection.resourceId.equals(resourceId)) {
Anchor cursorAnchor = userSelection.cursorAnchor;
Anchor baseAnchor = userSelection.baseAnchor;
if (cursorAnchor != null && baseAnchor != null) {
FilePositionImpl basePosition = FilePositionImpl.make()
.setColumn(baseAnchor.getColumn()).setLineNumber(baseAnchor.getLineNumber());
FilePositionImpl cursorPosition = FilePositionImpl.make().setColumn(
cursorAnchor.getColumn()).setLineNumber(cursorAnchor.getLineNumber());
DocumentSelectionImpl selection = DocumentSelectionImpl.make()
.setUserId(userSelection.clientId).setBasePosition(basePosition)
.setCursorPosition(cursorPosition);
selections.add(selection);
}
}
}
return selections;
}
public void removeSelection(String clientId) {
UserSelection selection = userSelections.remove(clientId);
if (selection != null) {
selection.teardown();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/maven/MavenResources.java | server/src/main/java/com/google/collide/server/maven/MavenResources.java | package com.google.collide.server.maven;
import xapi.fu.Lazy;
import xapi.fu.lazy.ResettableLazy;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
/**
*
* Project configuration settings to use during maven builds.
*
* These settings can be used for any multi-module project configuration.
*
* @author James X. Nelson (james@wetheinter.net, @james)
*/
public class MavenResources implements Serializable{
private static final long serialVersionUID = -8124340238103827275L;
private String srcRoot="";
private String warSrcDir="";
private String warTargetDir="";
private String workDir="";
private final ResettableLazy<File> srcRootFolder = new ResettableLazy<>(this::initSourceRoot);
private final ResettableLazy<File> warSrcFolder = new ResettableLazy<>(this::initWarSource);
private final ResettableLazy<File> warTargetFolder = new ResettableLazy<>(this::initWarTarget);
private final ResettableLazy<File> workFolder = new ResettableLazy<>(this::initWorkFolder);
/**
* @return the srcRoot
*/
public File getSrcRoot() {
return srcRootFolder.out1();
}
/**
* @param srcRoot the srcRoot to set
*/
public void setSrcRoot(String srcRoot) {
this.srcRoot = srcRoot;
srcRootFolder.reset();
}
/**
* @return the war Source Directory
*
* This is the folder containing your "clean" Web App Resource files (no generated source)
*/
public File getWarSrcDir() {
return warSrcFolder.out1();
}
/**
* @param warSrcDir the war Source Directory to set
*/
public void setWarSrcDir(String warSrcDir) {
this.warSrcDir = warSrcDir;
warSrcFolder.reset();
}
/**
* @return the war Target Directory
*
* This is the folder to which your clean Web App BaseResources will be merged with generated war.
*/
public File getWarTargetDir() {
return warTargetFolder.out1();
}
/**
* @param warTargetDir the war Target Directory to set
*/
public void setWarTargetDir(String warTargetDir) {
this.warTargetDir = warTargetDir;
warTargetFolder.reset();
}
/**
* @return the workDir, where temporary files are written.
*/
public File getWorkDir() {
return workFolder.out1();
}
/**
* @param workDir the work Directory to set
*/
public void setWorkDir(String workDir) {
this.workDir = workDir;
workFolder.reset();
}
//One-time initialization methods; only called the first time a property is accessed,
//and the next access after a property is set.
protected File initSourceRoot() {
if (srcRoot.length()==0){
throw new RuntimeException("You MUST specifiy a source root directory to use MavenConfig. ");
}
File file = new File(srcRoot);
if (!file.exists())
if (!file.mkdirs())
throw new Error("Could not create MavenConfig source root directory: "+file+". Please ensure this file exists, and is writable.");
return file;
}
protected File initWarSource() {
if (warSrcDir.length()==0){
warSrcDir = "war";
}
File file = new File(warSrcDir);
if (!file.exists()){//absolute lookup failed; try relative
file = new File(getSrcRoot(),warSrcDir);
}
if (!file.exists())
if (!file.mkdirs())
throw new Error("Could not create war source directory: "+file+". Please ensure this file exists, and is writable.");
return file;
}
protected File initWarTarget() {
if (warTargetDir.length()==0){
warTargetDir = "war";
}
File file = new File(warTargetDir);
if (!file.exists()){//absolute lookup failed; try relative
file = new File(getSrcRoot(),warTargetDir);
}
if (!file.exists())
if (!file.mkdirs())
throw new Error("Could not create war target directory: "+file+". Please ensure this file exists, and is writable.");
return file;
}
protected File initWorkFolder() {
if (workDir.length()==0){
workDir = "/tmp";
}
File file = new File(workDir);
if (!file.exists()){//absolute lookup failed; try relative
try {
//create new temp file to detect /tmp folder directory.
file = File.createTempFile("project", "tmp");
file.deleteOnExit();//clean up after ourselves
file = file.getParentFile();
file.deleteOnExit();
} catch (IOException e) {
throw new Error("Could not create work directory: "+file+". Please ensure this file exists, and is writable.",e);
}
}
return file;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/maven/MavenController.java | server/src/main/java/com/google/collide/server/maven/MavenController.java | package com.google.collide.server.maven;
import com.google.collide.dto.server.DtoServerImpls.MavenConfigImpl;
import com.google.collide.server.shared.BusModBase;
import com.google.collide.server.shared.util.Dto;
public class MavenController extends BusModBase{
private String addressBase;
@Override
public void start() {
super.start();
this.addressBase = getOptionalStringConfig("address", "maven");
vertx.eventBus().consumer(addressBase+".save", message -> {
System.out.println(message.body());
MavenConfigImpl cfg = MavenConfigImpl.make();
message.reply(Dto.wrap(cfg));
// vertx.eventBus().send("gwt.status", Dto.wrap(GwtStatusImpl.make().setModule("grrrawr!")));
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/fe/WebFE.java | server/src/main/java/com/google/collide/server/fe/WebFE.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.fe;
import collide.server.CollideServer;
import com.google.collide.dto.shared.JsonFieldConstants;
import com.google.collide.server.maven.MavenResources;
import com.google.collide.server.shared.BusModBase;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.Message;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.JksOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.Shareable;
import io.vertx.ext.bridge.PermittedOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions;
import org.apache.http.HttpStatus;
import xapi.gwtc.api.CompiledDirectory;
import xapi.log.X_Log;
import xapi.reflect.X_Reflect;
import xapi.server.vertx.VertxContext;
import xapi.server.vertx.scope.RequestScopeVertx;
import xapi.server.vertx.VertxRequest;
import xapi.server.vertx.VertxResponse;
import xapi.util.api.Pointer;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A simple web server module that can serve static files bundled with the webserver, as well as
* serve files from the directory that the webserver was launched in via simple URL path prefixes.
*
* This web server can also bridge event bus messages to/from client side JavaScript and the server
* side event bus.
*
* (Implementation based on the stock WebServer module bundled with the Vert.x distribution)
*/
public class WebFE extends BusModBase implements Handler<HttpServerRequest> {
private static final String WEBROOT_PATH = "/res/";
private static final String BUNDLED_STATIC_FILES_PATH = "/static/";
private static final String AUTH_PATH = "/_auth";
private static final String CODESERVER_FRAGMENT = "/code/";
private static final String EVENTBUS_FRAGMENT = "/eventbus";
private static final String SOURCEMAP_PATH = "/sourcemaps/";
private static final String AUTH_COOKIE_NAME = "_COLLIDE_SESSIONID";
/**
* The directory that we will be serving our bundled web application client form. We serve content
* from here when the URL matches {@link #WEBROOT_PATH}
*/
private String bundledStaticFilesPrefix;
/**
* The directory that we are serving files from as the "web root". We serve content from here when
* the URL matches {@link #BUNDLED_STATIC_FILES_PATH}
*/
private String webRootPrefix;
/**
* The directory in which we are compiling temporary files (for gwt builds),
* used when invoking the code server /{@link #CODESERVER_FRAGMENT}/your.gwt.module/command
* where command = compile | clean | kill
*
* Defaults to the value from MavenConfig, which will default to /tmp
*/
private String workDir;
/**
* The master production directory for your webapp, to which we will sync all changes.
* If this value == webRootPrefix, then mvn collide:deploy will sync to your collide work directory.
* Web invoke: /{@link #CODESERVER_FRAGMENT}/deploy
*
* Defaults to the value from MavenConfig, which will default to {@link #WEBROOT_PATH}/war
*/
private String warDir;
/**
* Your project / maven configuration file.
*/
private MavenResources config;
private SockJSHandler sjsServer;
private Router router;
private String collideHome;
private CollideServer server;
@Override
public void start() {
super.start();
final HttpServerOptions opts = new HttpServerOptions();
// Configure SSL.
if (getOptionalBooleanConfig("ssl", false)) {
opts.setSsl(true)
.setLogActivity(true)
.setKeyStoreOptions(new JksOptions()
.setPassword(getOptionalStringConfig("keyStorePassword", "password"))
.setPath(getOptionalStringConfig("keyStorePath", "server-keystore.jks"))
);
}
// Configure the event bus bridge.
boolean bridge = getOptionalBooleanConfig("bridge", false);
if (bridge) {
final SockJSHandlerOptions sockOpts = new SockJSHandlerOptions()
.setHeartbeatInterval(2_000)
.setSessionTimeout(15_000)
// .setLibraryURL(getOptionalStringConfig("suffix", "") + "/eventbus")
;
JsonArray inboundPermitted = getOptionalArrayConfig("in_permitted", new JsonArray());
JsonArray outboundPermitted = getOptionalArrayConfig("out_permitted", new JsonArray());
final BridgeOptions bridgeOpts = new BridgeOptions()
.setReplyTimeout(15_000)
.setPingTimeout(15_000);
bridgeOpts.setInboundPermitted(toOpts(inboundPermitted));
bridgeOpts.setOutboundPermitted(toOpts(outboundPermitted));
sjsServer = SockJSHandler.create(vertx, sockOpts);
sjsServer.bridge(bridgeOpts);
router = Router.router(vertx);
//
router.route("/eventbus/*").handler(sjsServer);
// getOptionalStringConfig("auth_address", "participants.authorise"));
}
HttpServer server = vertx.createHttpServer(opts);
server.requestHandler(this);
String bundledStaticFiles = getMandatoryStringConfig("staticFiles");
String webRoot = getMandatoryStringConfig("webRoot");
String workDirectory = getOptionalStringConfig("workDir", "/tmp");
String collide = getOptionalStringConfig("collideHome",
X_Reflect.getFileLoc(WebFE.class).replace(
"/server/build/classes/main/".replace('/', File.separatorChar) , ""));
String warDirectory = getOptionalStringConfig("warDir", webRoot + File.separator + "war");
bundledStaticFilesPrefix = bundledStaticFiles + File.separator;
webRootPrefix = webRoot + File.separator;
workDir = workDirectory + File.separator;
warDir = warDirectory + File.separator;
collideHome = collide + File.separator;
this.server = new CollideServer(
bundledStaticFilesPrefix, webRootPrefix, workDir, warDir, collideHome
);
int port = getOptionalIntConfig("port", 8080);
String host = getOptionalStringConfig("host", "127.0.0.1");
System.out.println("Connecting to "+host+":"+port);
server.listen(port, host);
vertx.eventBus().<JsonObject>consumer("frontend.symlink", event -> {
//TODO: require these messages to be signed by code private to the server
try{
String dto = event.body().getString("dto");
X_Log.trace("Symlinking",dto);
CompiledDirectory dir = CompiledDirectory.fromString(dto, ShareableCompileDirectory::new);
vertx.sharedData().getLocalMap("symlinks").put(
dir.getUri()
, dir);
}catch (Exception e) {
e.printStackTrace();
}
});
}
public static class ShareableCompileDirectory extends CompiledDirectory implements Shareable{}
private List<PermittedOptions> toOpts(JsonArray inboundPermitted) {
return ((List<?>)inboundPermitted.getList())
.stream()
.map(name->new PermittedOptions().setAddressRegex(String.valueOf(name)))
.collect(Collectors.toList());
}
private class SymlinkRequest{
String urlFragment;
String defaultTarget;
String userAgent;
HttpServerResponse response;
}
private class SymlinkResponse{
boolean handled;
String resolved;
}
@Override
public void handle(HttpServerRequest req) {
if (req.path().startsWith("/xapi")) {
handleXapi(req);
return;
}
if (req.path().equals("/") || req.path().equals("/demo")) {
//send login page
authAndWriteHostPage(req);
return;
}
String path = req.path().replace("/demo/", "/");
if (path.contains("..")) {
//sanitize hack attempts
sendStatusCode(req, 404);
return;
} else if (path.startsWith(EVENTBUS_FRAGMENT)) {
System.out.println("Sending to event bus: " + router.get(req.path()));
router.accept(req);
// req.upgrade()
return;
} else if (path.startsWith(CODESERVER_FRAGMENT)) {
sendToCodeServer(req);//listen on http so we can send compile requests without sockets hooked up.
return;
} else if (path.startsWith(AUTH_PATH)) {
writeSessionCookie(req);
return;
} else if (path.startsWith(WEBROOT_PATH) && (webRootPrefix != null)){
//TODO: sanitize this path
//check for symlinks
logger.info(path);
SymlinkRequest request = new SymlinkRequest();
request.urlFragment = path.substring(WEBROOT_PATH.length());
request.defaultTarget = webRootPrefix;
request.response = req.response();
SymlinkResponse response = processSymlink(request);
if (response.handled)
return;
} else if (path.contains(SOURCEMAP_PATH)){
//forward sourcemap paths to appropriate internal server
SymlinkRequest request = new SymlinkRequest();
request.urlFragment = path;
// dump headers in case we can pull in the permutation here...
request.userAgent = req.headers().get("User-Agent");
request.defaultTarget = webRootPrefix;
request.response = req.response();
SymlinkResponse response = processSymlink(request);
if (response.handled)
return;
} else if (path.startsWith(BUNDLED_STATIC_FILES_PATH) && (bundledStaticFilesPrefix != null)) {
Pointer<String> file = new Pointer<String>(path.substring(BUNDLED_STATIC_FILES_PATH.length()));
//check for symlinks
SymlinkRequest request = new SymlinkRequest();
request.urlFragment = file.get();
request.defaultTarget = bundledStaticFilesPrefix;
request.response = req.response();
SymlinkResponse response = processSymlink(request);
if (response.handled)
return;
}
//if we didn't return, we're out of options.
doFail(req);
}
private void doFail(HttpServerRequest req) {
//TODO: add a pluggable proxy here.
sendStatusCode(req, HttpStatus.SC_NOT_FOUND);
}
private SymlinkResponse processSymlink(final SymlinkRequest request) {
SymlinkResponse response = new SymlinkResponse();
LocalMap<String, Object> map = vertx.sharedData().getLocalMap("symlinks");
Set<String> keys= map.keySet();
String uri = request.urlFragment;
// System.out.println("Dereferencing request uri: "+uri+" against "+keys);
if (uri.length() == 0) {
return response;
}
if (uri.charAt(0)=='/')uri = uri.substring(1);
for (Object key : keys){
final String symlink = String.valueOf(key);
if (uri.contains(symlink)){
Object link = map.get(symlink);
//TODO: also serve up _gen, _extra, _source, etc.
if (("/"+uri).contains(SOURCEMAP_PATH)){
X_Log.info("Checking against symlink ",uri," .contains( ",symlink," )");
//serve up file from our sourcemap directory
try{
if (uri.endsWith(".java")||uri.endsWith("gwtSourceMap.json")){
//client is requesting actual source file.
//try to proxy the request to tcp server in gwt compiler.
int port =
(int) link.getClass().getMethod("getPort").invoke(link);
final String cls = uri;
final Pointer<Boolean> success = new Pointer<Boolean>(false);
vertx.createNetClient().connect(port, "localhost",
async -> {
final NetSocket event = async.result();
if (cls.endsWith("json")) {
// requesting sourcemap file
request.response.headers().set("Content-Type","application/json");
event.write(cls+"\n" + "User-Agent: "+request.userAgent);
} else {
// requesting source file
// chop off the module name from cls
event.write(cls.substring(1+cls.indexOf('/',SOURCEMAP_PATH.length())));
request.response.headers().set("Content-Type","text/plain");
}
final Buffer buf = Buffer.buffer(4096);
event.handler(buf::appendBuffer);
event.closeHandler(ev-> {
int len = buf.length();
if (len > 0) {
success.set(true);
request.response.putHeader("Content-Length", Integer.toString(buf.length()));
request.response.putHeader("Content-Type",
cls.endsWith("json") ? "application/json" : "text/plain");
request.response.end(buf);
synchronized (success) {
success.notify();
}
}
});
});
synchronized (success) {
success.wait(5000);
}
response.handled = success.get();
return response;
}
String base = String.valueOf(link.getClass().getMethod("getSourceMapDir").invoke(link));
//current super dev mode only produces one permutation for chrome,
//so there >should< only be be one sourcemap file to find.
//in the future, we will have to resolve the correct permutation to send.
//for now, we'll just search for the file requested.
File f = new File(base);
if (f.exists()&&f.isDirectory()){
String suffix = uri.substring(1+uri.lastIndexOf('.'));
for (File child : f.listFiles()){
if (child.getName().endsWith(suffix)){
response.handled=true;
response.resolved = child.getAbsolutePath();
applySourceMapHeader(request.response, response.resolved);
request.response.sendFile(response.resolved);
return response;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
try{
response.resolved =
link.getClass().getMethod("getWarDir").invoke(link)+"/"+symlink
+uri.substring(symlink.length());
logger.info("Symlink resolved to "+response.resolved);
response.handled = true;
applySourceMapHeader(request.response, response.resolved);
request.response.sendFile(response.resolved);
return response;
}catch (Exception e) {
e.printStackTrace();
}
}
}
response.handled=true;
if (request.urlFragment.contains(SOURCEMAP_PATH)) {
// This is for statically compiled gwt source (built through gradle),
// which will have a different structure than our dynamic superdev compiles;
String[] bits = request.urlFragment.split("/");
String moduleName = bits[2];
if (request.urlFragment.endsWith(".json")) {
// we are safe to assume _sourceMap0 since there will never be more than 1 iteration on a full compile
String extras = bundledStaticFilesPrefix.replace("out/"+moduleName, "extra/"+moduleName);
if (bits[4].contains("sourceMap0.json")) {
// super dev mode...
String mapFile = bits[4].replaceAll("(_sourcemap)?[.]json", "_sourceMap0.json");
response.resolved = extras + "/symbolMaps/" + mapFile;
} else {
// full compile; source maps are stored per split point, in a different structure...
String mapFile = bits[4].replaceAll("([A-F0-9]+)[.]json", "$1");
if (mapFile.matches("^[0-9]+$")) {
response.resolved = extras + "symbolMaps/" + moduleName + "_sourceMap" + mapFile + ".json";
} else {
response.resolved = extras + "symbolMaps/" + mapFile + "_sourceMap0.json";
}
}
} else {
String sourceFolder = bundledStaticFilesPrefix.replace("out/"+moduleName, "sourcemaps") + moduleName+ "/src/";
response.resolved = sourceFolder + request.urlFragment.split(SOURCEMAP_PATH)[1];
}
} else {
response.resolved = request.defaultTarget+request.urlFragment;
applySourceMapHeader(request.response, response.resolved);
}
request.response.sendFile(response.resolved);
return response ;
}
private void applySourceMapHeader(HttpServerResponse response, String moduleName) {
if (moduleName.endsWith(".cache.js")){
int last = moduleName.lastIndexOf('/');
String strongName = moduleName.substring(last+1).split("[.]cache")[0];
moduleName = moduleName.substring(moduleName.lastIndexOf('/',last-1)+1,last);
// TODO: perform reverse-lookup on shortened module name
// TODO: link strong name to user session for this module
response.putHeader("X-SourceMap",BUNDLED_STATIC_FILES_PATH+moduleName +SOURCEMAP_PATH+strongName+".json");
response.putHeader("Access-Control-Allow-Origin", "*");
}
}
private void sendToCodeServer(HttpServerRequest req) {
Cookie cookie = Cookie.getCookie(AUTH_COOKIE_NAME, req);
if (cookie == null) {
sendRedirect(req, "/static/login.html");
return;
}
//TODO: forward commands to message bus, so we can allow throttled guest compiles.
// QueryStringDecoder qsd = new QueryStringDecoder(req.query, false);
// Map<String, List<String>> params = qsd.getParameters();
//
// List<String> loginSessionIdList = params.get(JsonFieldConstants.SESSION_USER_ID);
// List<String> usernameList = params.get(JsonFieldConstants.SESSION_USERNAME);
// if (loginSessionIdList == null || loginSessionIdList.size() == 0 ||
// usernameList == null || usernameList.size() == 0) {
// sendStatusCode(req, 400);
// return;
// }
//
// final String sessionId = loginSessionIdList.get(0);
// final String username = usernameList.get(0);
// List<String> modules = qsd.getParameters().get("module");
//
// if (modules != null){
// MavenResources config = getConfig(req);
// CodeSvr.startOrRefresh(logToVertx(req),config,modules);
// }
}
private MavenResources getConfig(HttpServerRequest req) {
// req.response.
MavenResources res = new MavenResources();
res.setSrcRoot(webRootPrefix);
res.setWorkDir(workDir);
res.setWarTargetDir(warDir);
res.setWarSrcDir(warDir);
return res;
}
private void authAndWriteHostPage(HttpServerRequest req) {
Cookie cookie = Cookie.getCookie(AUTH_COOKIE_NAME, req);
if (cookie != null) {
// We found a session ID. Lets go ahead and serve up the host page.
doAuthAndWriteHostPage(req, cookie.value);
return;
}
// We did not find the session ID. Lets go ahead and serve up the login page that should take
// care of installing a cookie and reloading the page.
sendRedirect(req, "/static/login.html");
}
// TODO: If we want to make this secure, setup SSL and set this as a Secure cookie.
// Also probably want to resurrect XsrfTokens and the whole nine yards. But for now, this is
// purely a tracking cookie.
/**
* Writes cookies for the session ID that is posted to it.
*/
private void writeSessionCookie(final HttpServerRequest req) {
if (!"POST".equals(req.method().name())) {
sendStatusCode(req, HttpStatus.SC_METHOD_NOT_ALLOWED);
return;
}
// Extract the post data.
req.bodyHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer buff) {
String contentType = req.headers().get("Content-Type");
if (String.valueOf(contentType).startsWith("application/x-www-form-urlencoded")) {
QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
Map<String, List<String>> params = qsd.parameters();
List<String> loginSessionIdList = params.get(JsonFieldConstants.SESSION_USER_ID);
List<String> usernameList = params.get(JsonFieldConstants.SESSION_USERNAME);
if (loginSessionIdList == null || loginSessionIdList.size() == 0 ||
usernameList == null || usernameList.size() == 0) {
System.out.println("Failed to write session cookie; "+loginSessionIdList+" / "+usernameList);
sendStatusCode(req, 400);
return;
}
final String sessionId = loginSessionIdList.get(0);
final String username = usernameList.get(0);
X_Log.info("Writing session cookie; ",username," / ",sessionId);
vertx.eventBus().<JsonObject>send("participants.authorise",
new JsonObject().put("sessionID", sessionId).put("username", username),
async -> {
final Message<JsonObject> event = async.result();
X_Log.trace("Writing session cookie; ",event.body());
if ("ok".equals(event.body().getString("status"))) {
req.response().headers().set("Set-Cookie",
AUTH_COOKIE_NAME + "=" + sessionId + "__" + username + "; HttpOnly");
sendStatusCode(req, HttpStatus.SC_OK);
} else {
sendStatusCode(req, HttpStatus.SC_FORBIDDEN);
}
}
);
} else {
sendRedirect(req, "/static/login.html");
}
}
});
}
private void doAuthAndWriteHostPage(final HttpServerRequest req, String authCookie) {
String[] cookieParts = authCookie.split("__");
if (cookieParts.length != 2) {
sendRedirect(req, "/static/login.html");
return;
}
final String sessionId = cookieParts[0];
String username = cookieParts[1];
final HttpServerResponse response = req.response();
vertx.eventBus().<JsonObject>send("participants.authorise", new JsonObject().put(
"sessionID", sessionId).put("username", username).put("createClient", true),
async -> {
final Message<JsonObject> event = async.result();
if ("ok".equals(event.body().getString("status"))) {
String activeClientId = event.body().getString("activeClient");
String username1 = event.body().getString("username");
if (activeClientId == null || username1 == null) {
sendStatusCode(req, HttpStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
String path = req.path();
String module = "Demo";
if (path.endsWith("demo/")) {
path = path.replace("/demo", "");
module = "Demo";
}
String responseText = getHostPage(path, module, sessionId, username1, activeClientId);
response.setStatusCode(HttpStatus.SC_OK);
byte[] page = responseText.getBytes(Charset.forName("UTF-8"));
response.putHeader("Content-Length", Integer.toString(page.length));
response.putHeader("Content-Type", "text/html");
response.end(Buffer.buffer(page));
} else {
sendRedirect(req, "/static/login.html");
}
}
);
}
/**
* Generate the header for the host page that includes the client bootstrap information as well as
* relevant script includes.
*/
private String getHostPage(String path, String module, String userId, String username, String activeClientId) {
StringBuilder sb = new StringBuilder();
sb.append("<!doctype html>\n");
sb.append("<html>\n");
sb.append(" <head>\n");
sb.append("<title>CollIDE - Collaborative Development</title>\n");
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
// if (module.indexOf('/') == -1)
// module = module + '/' + module;
sb.append("<script src=\"" + path +"/static/sockjs.js\"></script>\n");
sb.append("<script src=\"" + path+"/static/vertxbus.js\"></script>\n");
sb.append("<script src=\"" +path+"/static/" + module + "." +
"nocache.js\"></script>\n");
// Embed the bootstrap session object.
emitBootstrapJson(sb, userId, username, activeClientId);
emitDefaultStyles(sb);
sb.append(" </head>\n<body><div id='gwt_root'></div></body>\n</html>");
return sb.toString();
}
private void emitDefaultStyles(StringBuilder sb) {
sb.append("<style>\n#gwt_root {\n")
.append("position: absolute;\n")
.append("top: 0;\n")
.append("left: 0;\n")
.append("bottom: 0;\n")
.append("right: 0;\n")
.append("}\n</style>");
}
private void emitBootstrapJson(
StringBuilder sb, String userId, String username, String activeClientId) {
sb.append("<script>\n")
.append("window['__session'] = {\n")
.append(JsonFieldConstants.SESSION_USER_ID).append(": \"").append(userId).append("\",\n")
.append(JsonFieldConstants.SESSION_ACTIVE_ID).append(": \"").append(activeClientId)
.append("\",\n").append(JsonFieldConstants.SESSION_USERNAME).append(": \"")
.append(username).append("\"\n};\n")
.append("window['collide'] = {\n")
.append("name: 'Guest', module: 'collide.demo.Child', open: '" +
//"/core/fu/src/main/xapi" +
//"/xapi/fu/In.xapi"
"/test.wti"
+ "' };")
.append("</script>");
}
private void sendRedirect(HttpServerRequest req, String url) {
if (req.path().startsWith("/collide")) {
url = "/collide" + url;
url = url.replace("login.html", "login_collide.html");
System.out.println("Got it"+req.path());
}
System.out.println(req.path());
req.response().putHeader("Location", url);
sendStatusCode(req, HttpStatus.SC_MOVED_TEMPORARILY);
}
private void sendStatusCode(HttpServerRequest req, int statusCode) {
req.response().setStatusCode(statusCode);
req.response().end();
}
private void handleXapi(HttpServerRequest req) {
// VertxContext.fromNative()
final VertxRequest request = new VertxRequest(req, null);
final VertxResponse resp = new VertxResponse(req.response());
Cookie cookie = Cookie.getCookie(AUTH_COOKIE_NAME, req);
String sessionId = null;
if (cookie != null) {
sessionId = cookie.value.split("__")[0];
}
server.inScope(sessionId, session->(RequestScopeVertx) session.getRequestScope(request, resp), (scope, fail, onDone)->{
if (fail != null) {
authAndWriteHostPage(req);
onDone.done();
} else {
server.serviceRequest(scope, (r, error)-> {
if (error != null) {
authAndWriteHostPage(req);
}
onDone.done();
});
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/fe/Cookie.java | server/src/main/java/com/google/collide/server/fe/Cookie.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.fe;
import io.vertx.core.http.HttpServerRequest;
/**
* Super simple class for extracting and handling Cookies. Should probably replace with an existing
* implementation.
*
*/
public class Cookie {
/**
* Get an array of Cookies from a request.
*/
public static Cookie[] extractCookies(HttpServerRequest req) {
String cookies = req.headers().get("Cookie");
if (cookies == null) {
return new Cookie[0];
}
String[] cookieStrArr = cookies.split(";");
Cookie[] cookieArr = new Cookie[cookieStrArr.length];
for (int i = 0; i < cookieStrArr.length; i++) {
String cookie = cookieStrArr[i].trim();
String[] cookieTup = cookie.split("=");
cookieArr[i] = new Cookie(cookieTup[0], cookieTup[1]);
}
return cookieArr;
}
/**
* @return a specific Cookie by name or {@code null} if it doesn't exist.
*/
public static Cookie getCookie(String name, HttpServerRequest req) {
Cookie[] cookies = extractCookies(req);
for (Cookie cookie : cookies) {
if (name.equals(cookie.name)) {
return cookie;
}
}
return null;
}
public final String name;
public final String value;
public Cookie(String name, String value) {
this.name = name;
this.value = value;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/BusModBase.java | server/src/main/java/com/google/collide/server/shared/BusModBase.java | package com.google.collide.server.shared;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
/**
* Created by James X. Nelson (james @wetheinter.net) on 8/28/16.
*/
public abstract class BusModBase extends AbstractVerticle {
protected static final Logger logger = LoggerFactory.getLogger(BusModBase.class);
protected EventBus eb;
protected JsonObject config;
/**
* Start the busmod
*/
public void start() {
eb = vertx.eventBus();
config = config();
}
protected void sendOK(Message<JsonObject> message) {
sendOK(message, null);
}
protected void sendStatus(String status, Message<JsonObject> message) {
sendStatus(status, message, null);
}
protected void sendStatus(String status, Message<JsonObject> message, JsonObject json) {
if (json == null) {
json = new JsonObject();
}
json.put("status", status);
message.reply(json);
}
protected void sendOK(Message<JsonObject> message, JsonObject json) {
sendStatus("ok", message, json);
}
protected void sendError(Message<JsonObject> message, String error) {
sendError(message, error, null);
}
protected void sendError(Message<JsonObject> message, String error, Exception e) {
logger.error(error, e);
JsonObject json = new JsonObject().put("status", "error").put("message", error);
message.reply(json);
}
protected String getMandatoryString(String field, Message<JsonObject> message) {
String val = message.body().getString(field);
if (val == null) {
sendError(message, field + " must be specified");
}
return val;
}
protected JsonObject getMandatoryObject(String field, Message<JsonObject> message) {
JsonObject val = message.body().getJsonObject(field);
if (val == null) {
sendError(message, field + " must be specified");
}
return val;
}
protected boolean getOptionalBooleanConfig(String fieldName, boolean defaultValue) {
Boolean b = config.getBoolean(fieldName);
return b == null ? defaultValue : b.booleanValue();
}
protected String getOptionalStringConfig(String fieldName, String defaultValue) {
String b = config.getString(fieldName);
return b == null ? defaultValue : b;
}
protected int getOptionalIntConfig(String fieldName, int defaultValue) {
Integer b = config.getInteger(fieldName);
return b == null ? defaultValue : b.intValue();
}
protected long getOptionalLongConfig(String fieldName, long defaultValue) {
Long l = config.getLong(fieldName);
return l == null ? defaultValue : l.longValue();
}
protected JsonObject getOptionalObjectConfig(String fieldName, JsonObject defaultValue) {
JsonObject o = config.getJsonObject(fieldName);
return o == null ? defaultValue : o;
}
protected JsonArray getOptionalArrayConfig(String fieldName, JsonArray defaultValue) {
JsonArray a = config.getJsonArray(fieldName);
return a == null ? defaultValue : a;
}
protected boolean getMandatoryBooleanConfig(String fieldName) {
Boolean b = config.getBoolean(fieldName);
if (b == null) {
throw new IllegalArgumentException(fieldName + " must be specified in config for busmod");
}
return b;
}
protected String getMandatoryStringConfig(String fieldName) {
String s = config.getString(fieldName);
if (s == null) {
throw new IllegalArgumentException(fieldName + " must be specified in config for busmod");
}
return s;
}
protected int getMandatoryIntConfig(String fieldName) {
Integer i = config.getInteger(fieldName);
if (i == null) {
throw new IllegalArgumentException(fieldName + " must be specified in config for busmod");
}
return i;
}
protected long getMandatoryLongConfig(String fieldName) {
Long l = config.getLong(fieldName);
if (l == null) {
throw new IllegalArgumentException(fieldName + " must be specified in config for busmod");
}
return l;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/util/FileHasher.java | server/src/main/java/com/google/collide/server/shared/util/FileHasher.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.shared.util;
import com.google.common.hash.Hashing;
import com.google.protobuf.ByteString;
/**
* Calculates hashes of file contents and records metrics about the run time.
*/
public class FileHasher {
public static ByteString getSha1(String contents) {
ByteString sha1 = ByteString.copyFrom(Hashing.sha1().hashUnencodedChars(contents).asBytes());
return sha1;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/util/Dto.java | server/src/main/java/com/google/collide/server/shared/util/Dto.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.shared.util;
import com.google.collide.dtogen.server.JsonSerializable;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
/**
* Utility for wrapping and unwrapping serialized Dtos.
*/
public class Dto {
public static String get(Message<JsonObject> vertxMsg) {
String serializedDto = vertxMsg.body().getString("dto", null);
if (serializedDto == null) {
throw new IllegalArgumentException("Missing dto field on vertx message!");
}
return serializedDto;
}
public static <T extends JsonSerializable> JsonObject wrap(T dto) {
return wrap(dto.toJson());
}
public static JsonObject wrap(String serializedDto) {
return new JsonObject().put("dto", serializedDto);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/util/DtoManifestUtil.java | server/src/main/java/com/google/collide/server/shared/util/DtoManifestUtil.java | package com.google.collide.server.shared.util;
import com.google.collide.dto.GwtCompile;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.server.DtoServerImpls.GwtCompileImpl;
import xapi.collect.api.IntTo;
import xapi.gwtc.api.GwtManifest;
import xapi.log.X_Log;
import static collide.shared.collect.Collections.asArray;
import java.util.ArrayList;
import java.util.List;
public class DtoManifestUtil {
public static GwtManifest loadCompile(GwtManifest manifest, GwtCompile compile) {
loadRecompile(manifest, compile);
manifest.setDeployDir(compile.getDeployDir());
manifest.setExtraArgs(asArray(compile.getExtraArgs()));
manifest.setExtrasDir(compile.getExtrasDir());
manifest.setFragments(compile.getFragments());
manifest.setGenDir(compile.getGenDir());
manifest.setGwtVersion(compile.getGwtVersion());
manifest.setClosureCompiler(compile.isClosureCompiler());
manifest.setDisableAggressiveOptimize(compile.isDisableAggressiveOptimize());
manifest.setDisableCastCheck(compile.isDisableCastCheck());
manifest.setDisableClassMetadata(compile.isDisableClassMetadata());
manifest.setDisableRunAsync(compile.isDisableRunAsync());
manifest.setDisableThreadedWorkers(compile.isDisableThreadedWorkers());
manifest.setDisableUnitCache(compile.isDisableUnitCache());
manifest.setDraftCompile(compile.isDraftCompile());
manifest.setEnableAssertions(compile.isEnableAssertions());
manifest.setSoyc(compile.isSoyc());
manifest.setSoycDetailed(compile.isSoycDetailed());
manifest.setStrict(compile.isStrict());
manifest.setValidateOnly(compile.isValidateOnly());
manifest.setLocalWorkers(compile.getLocalWorkers());
manifest.setLogLevel(compile.getLogLevel());
manifest.setPort(compile.getPort());
manifest.setSystemProperties(asArray(compile.getSystemProperties()));
manifest.setUnitCacheDir(compile.getUnitCacheDir());
manifest.setWorkDir(compile.getWorkDir());
manifest.setWarDir(compile.getWarDir());
return manifest;
}
public static GwtManifest loadRecompile(GwtManifest manifest, GwtRecompile compile) {
manifest.setModuleName(compile.getModule());
manifest.setAutoOpen(compile.getAutoOpen());
if (compile.getLogLevel() != null) {
manifest.setLogLevel(compile.getLogLevel());
}
if (compile.getOpenAction() != null) {
manifest.setOpenAction(compile.getOpenAction());
}
if (compile.getObfuscationLevel() != null) {
manifest.setObfuscationLevel(compile.getObfuscationLevel());
}
manifest.setPort(compile.getPort());
for (String src : compile.getSources().asIterable()) {
manifest.addSource(src);
}
for (String src : compile.getDependencies().asIterable()) {
X_Log.info(src);
manifest.addDependency(src);
}
return manifest;
}
public static GwtManifest newGwtManifest(GwtCompile compileRequest) {
return loadCompile(new GwtManifest(), compileRequest);
}
public static GwtManifest newGwtManifest(GwtRecompile compileRequest) {
return loadRecompile(new GwtManifest(), compileRequest);
}
public GwtCompileImpl toDto(GwtManifest m) {
GwtCompileImpl gwtc = GwtCompileImpl.make();
gwtc.setAutoOpen(m.isAutoOpen());
gwtc.setLogLevel(m.getLogLevel());
gwtc.setModule(m.getModuleName());
gwtc.setObfuscationLevel(m.getObfuscationLevel());
gwtc.setOpenAction(m.getOpenAction());
gwtc.setPort(m.getPort());
gwtc.setSources(asList(m.getSources()));
List<String> deps = new ArrayList<>();
m.getDependencies().forEach(deps::add);
gwtc.setDependencies(deps);
gwtc.setDeployDir(m.getDeployDir());
gwtc.setExtraArgs(asList(m.getExtraArgs()));
gwtc.setExtrasDir(m.getExtrasDir());
gwtc.setFragments(m.getFragments());
gwtc.setGenDir(m.getGenDir());
gwtc.setGwtVersion(m.getGwtVersion());
gwtc.setIsClosureCompiler(m.isClosureCompiler());
gwtc.setIsDisableAggressiveOptimize(m.isDisableAggressiveOptimize());
gwtc.setIsDisableCastCheck(m.isDisableCastCheck());
gwtc.setIsDisableClassMetadata(m.isDisableClassMetadata());
gwtc.setIsDisableRunAsync(m.isDisableRunAsync());
gwtc.setIsDisableThreadedWorkers(m.isDisableThreadedWorkers());
gwtc.setIsDisableUnitCache(m.isDisableUnitCache());
gwtc.setIsDraftCompile(m.isDraftCompile());
gwtc.setIsEnableAssertions(m.isEnableAssertions());
gwtc.setIsRecompile(false);
gwtc.setIsSoyc(m.isSoyc());
gwtc.setIsSoycDetailed(m.isSoycDetailed());
gwtc.setIsStrict(m.isStrict());
gwtc.setIsValidateOnly(m.isValidateOnly());
gwtc.setLocalWorkers(m.getLocalWorkers());
gwtc.setLogLevel(m.getLogLevel());
gwtc.setPort(m.getPort());
gwtc.setSystemProperties(asList(m.getSystemProperties()));
gwtc.setUnitCacheDir(m.getUnitCacheDir());
return gwtc;
}
private List<String> asList(IntTo<String> sources) {
return sources == null ? new ArrayList<String>() : sources.asList();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/util/ReflectionChannel.java | server/src/main/java/com/google/collide/server/shared/util/ReflectionChannel.java | package com.google.collide.server.shared.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.google.collide.shared.util.Channel;
import xapi.fu.Lazy;
import xapi.fu.lazy.ResettableLazy;
public class ReflectionChannel implements Channel<String>{
private ClassLoader cl;
private Object that;
private final ResettableLazy<Method> in = new ResettableLazy<>(() -> {
try {
return getInputMethod(getClassLoader(), that);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
});
private final ResettableLazy<Method> out = new ResettableLazy<>(() -> {
try {
return getOutputMethod(getClassLoader(), that);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
});
private Object destroy;
public ReflectionChannel(ClassLoader cl, Object otherChannel) {
this.cl = cl;
this.that = otherChannel;
}
public void setChannel(Object otherChannel){
this.that = otherChannel;
//clears our singletons, so the next invocation will rip the methods again
in.reset();
out.reset();
}
public ClassLoader getClassLoader(){
return cl;
}
/**
* @throws ClassNotFoundException
*/
protected Method getInputMethod(ClassLoader cl, Object from) throws NoSuchMethodException, SecurityException, ClassNotFoundException {
return from.getClass().getMethod("receive");
}
protected Method getOutputMethod(ClassLoader cl, Object from) throws NoSuchMethodException, SecurityException {
return from.getClass().getMethod("send", String.class);
}
@Override
public void send(String t) {
try{
invokeSend(out.out1(),that, t);
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public String receive() {
try{
return invokeReceive(in.out1(), that);
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
protected String invokeReceive(Method method, Object that) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//because this method and object are from a different classloader,
//we can't invoke the .invoke method directly...
Object o = method.invoke(that);
return o == null ? null : String.valueOf(o);
}
protected void invokeSend(Method method, Object that, String message) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
method.invoke(that, message);
}
public void setOnDestroy(Object runOnDestroy) {
this.destroy = runOnDestroy;
}
public void destroy() throws Exception{
System.out.println("DESTROYING GWT COMPILER IMPLEMENTATION");
if (destroy != null){
destroy.getClass().getMethod("run").invoke(destroy);
destroy = null;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/launcher/VertxLauncher.java | server/src/main/java/com/google/collide/server/shared/launcher/VertxLauncher.java | package com.google.collide.server.shared.launcher;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import xapi.fu.Lazy;
import xapi.log.X_Log;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
public class VertxLauncher {
private static AtomicInteger unusedPort = new AtomicInteger(13370);
private int port;
private final Lazy<Vertx> vertx;
public VertxLauncher() {
vertx = Lazy.deferred1Unsafe(()->{
while (true) {
synchronized (unusedPort) {
int port = unusedPort.getAndAdd(1 + (int) (Math.random() * 20));
try {
Vertx vertx = Vertx.vertx();
initialize(vertx, port);
return vertx;
} catch (Exception e) {
e.printStackTrace();
if (port > 15000) {
synchronized (unusedPort) {
unusedPort.set(10002);
}
return null;
}
}
}
}
});
}
protected NetServer initialize(Vertx vertx, int port) {
final NetServer server = vertx.createNetServer(new NetServerOptions()
.setTcpKeepAlive(true)
.setReuseAddress(true)
);
server
.connectHandler(event->{
//called
event.exceptionHandler(Throwable::printStackTrace);
event.closeHandler(e->X_Log.debug("Closed"));
event.handler( buffer -> {
X_Log.debug("Buffering");
try{
handleBuffer(event, buffer);
}catch (Exception e) {
X_Log.error(VertxLauncher.class, "Error handling buffer", e);
}
});
event.endHandler(e->X_Log.debug("Ending"));
})
.listen(port, "0.0.0.0");
this.port = port;
vertx.setTimer(1000, e-> {
//keep heap clean; the generated gwt classes will fill permgen quickly if they survive;
System.gc();
});
return server;
}
/**
* @throws IOException
*/
protected void handleBuffer(NetSocket event, Buffer buffer) throws IOException {
}
public int getPort() {
return port;
}
public Vertx ensureStarted() {
return vertx.out1();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/merge/MergeChunk.java | server/src/main/java/com/google/collide/server/shared/merge/MergeChunk.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.shared.merge;
import com.google.collide.shared.util.StringUtils;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Represents a part of a document that is the result of a 3-way merge.
*
* <p>
* Note: This class uses identity semantics for equality.
*
*/
public class MergeChunk {
private final static int MAX_DISPLAY_LENGTH = 8;
// Set iff hasConflict is true.
private int startLine;
// Set iff hasConflict is true.
private int endLine;
// Set iff hasConflict is true.
private String baseData;
// Set iff hasConflict is true.
private String parentData;
// Set iff hasConflict is true.
private String childData;
// Set iff hasConflict is false.
private String mergedData;
private boolean hasConflict;
public MergeChunk() {
}
/*
* Copy-constructor.
*/
public MergeChunk(MergeChunk chunk) {
this.startLine = chunk.startLine;
this.endLine = chunk.endLine;
this.baseData = chunk.baseData;
this.childData = chunk.childData;
this.parentData = chunk.parentData;
this.mergedData = chunk.mergedData;
this.hasConflict = chunk.hasConflict;
}
public String getBaseData() {
return StringUtils.nullToEmpty(baseData);
}
public int getEndLine() {
return endLine;
}
public String getChildData() {
return StringUtils.nullToEmpty(childData);
}
public String getMergedData() {
return mergedData;
}
public String getParentData() {
return StringUtils.nullToEmpty(parentData);
}
public int getStartLine() {
return startLine;
}
public boolean hasConflict() {
return hasConflict;
}
public void setBaseData(String baseData) {
this.baseData = baseData;
}
public void setEndLine(int line) {
this.endLine = line;
}
public void setHasConflict(boolean hasConflict) {
this.hasConflict = hasConflict;
}
public void setChildData(String childData) {
this.childData = childData;
}
public void setMergedData(String mergedData) {
this.mergedData = mergedData;
}
public void setParentData(String parentData) {
this.parentData = parentData;
}
public void setStartLine(int line) {
this.startLine = line;
}
@Override
public String toString() {
return toStringFields(Objects.toStringHelper(this)).toString();
}
protected ToStringHelper toStringFields(ToStringHelper toStringHelper) {
return toStringHelper
.add(
"baseData",
StringUtils.truncateAtMaxLength(StringUtils.nullToEmpty(baseData), MAX_DISPLAY_LENGTH,
true))
.add(
"parentData",
StringUtils.truncateAtMaxLength(StringUtils.nullToEmpty(parentData), MAX_DISPLAY_LENGTH,
true))
.add(
"childData",
StringUtils.truncateAtMaxLength(StringUtils.nullToEmpty(childData), MAX_DISPLAY_LENGTH,
true))
.add(
"mergedData",
StringUtils.truncateAtMaxLength(StringUtils.nullToEmpty(mergedData), MAX_DISPLAY_LENGTH,
true)).add("hasConflict", hasConflict).add("startLine", startLine)
.add("endLine", endLine);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/merge/MergeResult.java | server/src/main/java/com/google/collide/server/shared/merge/MergeResult.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.shared.merge;
import java.util.List;
import com.google.common.collect.ImmutableList;
/**
* Captures the result of a 3-way-merge with {@link JGitMerger}.
*
* <p>Note: This class uses identity semantics for equality.
*/
public class MergeResult {
private final ImmutableList<MergeChunk> mergeChunks;
private final String mergedText;
public MergeResult(List<MergeChunk> mergeChunks, String mergedText) {
this.mergeChunks = ImmutableList.copyOf(mergeChunks);
this.mergedText = mergedText;
}
/**
* Returns a list of merge chunks that represent the result of the merge in
* chunks.
*/
public List<MergeChunk> getMergeChunks() {
return mergeChunks;
}
/**
* Returns the merged text if the files merge cleanly.
*/
public String getMergedText() {
return mergedText;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/merge/ConflictChunk.java | server/src/main/java/com/google/collide/server/shared/merge/ConflictChunk.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.shared.merge;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Represents a chunk of text that could not be automatically merged. After the
* necessary edits, it can be marked as resolved. It can subsequently also be
* marked as unresolved (i.e. you can undo marking it as resolved).
*
*/
public class ConflictChunk extends MergeChunk {
private boolean isResolved = false;
public ConflictChunk(MergeChunk chunk) {
this(chunk, false);
}
public ConflictChunk(MergeChunk chunk, boolean isResolved) {
super(chunk);
this.isResolved = isResolved;
}
public boolean isResolved() {
return isResolved;
}
public void markResolved(boolean isResolved) {
this.isResolved = isResolved;
}
@Override
public String toString() {
return toStringFields(Objects.toStringHelper(this)).toString();
}
@Override
protected ToStringHelper toStringFields(ToStringHelper toStringHelper) {
return super.toStringFields(toStringHelper).add("isResolved", isResolved);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/collide/server/shared/merge/JGitMerger.java | server/src/main/java/com/google/collide/server/shared/merge/JGitMerger.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.server.shared.merge;
import java.util.List;
import org.eclipse.jgit.diff.RawText;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.merge.MergeAlgorithm;
import org.eclipse.jgit.merge.MergeChunk.ConflictState;
import com.google.common.collect.Lists;
/**
* Merger for performing a 3-way-merge using JGit.
*
*/
public class JGitMerger {
private static MergeAlgorithm mergeAlgorithm = new MergeAlgorithm();
public static MergeResult merge(String base, String child, String parent) {
// Jgit Merge
org.eclipse.jgit.merge.MergeResult<RawText> jgitMergeResult =
mergeAlgorithm.merge(RawTextComparator.DEFAULT, new RawText(base.getBytes()),
new RawText(child.getBytes()), new RawText(parent.getBytes()));
return formatMerge(jgitMergeResult);
}
public static MergeResult formatMerge(org.eclipse.jgit.merge.MergeResult<RawText> results) {
int runningIndex = 0;
int numLines = 0;
List<MergeChunk> mergeChunks = Lists.newArrayList();
MergeChunk currentMergeChunk = null;
StringBuilder fileContent = new StringBuilder();
int conflictIndex = 0;
for (org.eclipse.jgit.merge.MergeChunk chunk : results) {
RawText seq = results.getSequences().get(chunk.getSequenceIndex());
String chunkContent = seq.getString(chunk.getBegin(), chunk.getEnd(), false);
if (chunk.getConflictState() == ConflictState.NO_CONFLICT
|| chunk.getConflictState() == ConflictState.FIRST_CONFLICTING_RANGE) {
if (currentMergeChunk != null) {
mergeChunks.add(currentMergeChunk);
}
currentMergeChunk = new MergeChunk();
}
switch (chunk.getConflictState()) {
case NO_CONFLICT:
currentMergeChunk.setHasConflict(false);
currentMergeChunk.setMergedData(chunkContent);
fileContent.append(chunkContent);
numLines = chunk.getEnd() - chunk.getBegin();
runningIndex = setRanges(currentMergeChunk, runningIndex, numLines);
break;
case FIRST_CONFLICTING_RANGE:
currentMergeChunk.setHasConflict(true);
currentMergeChunk.setChildData(chunkContent);
fileContent.append(chunkContent);
numLines = chunk.getEnd() - chunk.getBegin();
runningIndex = setRanges(currentMergeChunk, runningIndex, numLines);
break;
case NEXT_CONFLICTING_RANGE:
currentMergeChunk.setParentData(chunkContent);
break;
}
}
mergeChunks.add(currentMergeChunk);
MergeResult mergeResult =
new MergeResult(mergeChunks, (conflictIndex > 0) ? "" : fileContent.toString());
return mergeResult;
}
private static int setRanges(MergeChunk mergeChunk, int runningChildIndex, int numLines) {
mergeChunk.setStartLine(runningChildIndex);
// JGit end index is exclusive, Collide's is inclusive. numLines can be 0.
int endLine = runningChildIndex + numLines;
if (numLines > 0) {
endLine--;
}
mergeChunk.setEndLine(endLine);
runningChildIndex += numLines;
return runningChildIndex;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/com/google/gwt/dev/codeserver/GwtCompilerThread.java | server/src/main/java/com/google/gwt/dev/codeserver/GwtCompilerThread.java | package com.google.gwt.dev.codeserver;
import collide.plugin.server.AbstractCompileThread;
import collide.plugin.server.IsCompileThread;
import collide.plugin.server.ReflectionChannelTreeLogger;
import collide.plugin.server.gwt.CompilerBusyException;
import collide.server.configuration.CollideOpts;
import com.google.collide.dto.CompileResponse.CompilerState;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.server.DtoServerImpls.CompileResponseImpl;
import com.google.collide.dto.server.DtoServerImpls.GwtRecompileImpl;
import com.google.collide.server.shared.util.ReflectionChannel;
import com.google.collide.shared.util.DebugUtil;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import xapi.collect.X_Collect;
import xapi.dev.gwtc.api.GwtcJob;
import xapi.dev.gwtc.api.GwtcProjectGenerator;
import xapi.dev.gwtc.api.GwtcService;
import xapi.dev.gwtc.impl.GwtcManifestImpl;
import xapi.gwtc.api.CompiledDirectory;
import xapi.gwtc.api.GwtManifest;
import xapi.inject.X_Inject;
import xapi.time.X_Time;
import java.io.IOException;
import java.util.HashMap;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.dev.util.log.PrintWriterTreeLogger;
public final class GwtCompilerThread extends AbstractCompileThread<GwtRecompile>
implements IsCompileThread<GwtRecompile> {
private GwtCompilationServer compileServer;
public GwtCompilerThread() {
}
public GwtCompilerThread(String module) {
messageKey = this.module = module;
}
private final HashMap<String, CompiledDirectory> modules = new HashMap<>();
ReflectionChannelTreeLogger logger;
private boolean started, recompile;
@Override
protected TreeLogger logger() {
return logger == null ? new PrintWriterTreeLogger() : logger;
}
GwtcJob controller;
private String module;
private String messageKey;
final GwtcService service = X_Inject.instance(GwtcService.class);
// these are native objects, created using reflection
@Override
public void run() {
while (!Thread.interrupted())
try {
// grab our request from originating thread
String compileRequest = io.receive();
if (compileRequest == null) {
working = false;
// no request means we should just sleep for a while
try {
synchronized (GwtCompilerThread.class) {
GwtCompilerThread.class.wait(20000);
}
} catch (InterruptedException e) {// wake up!
Thread.interrupted();
}
continue;
}
working = true;
GwtRecompile request = GwtRecompileImpl.fromJsonString(compileRequest);
module = request.getModule();
messageKey = request.getMessageKey() == null ? module : request.getMessageKey();
// prepare a response to let the user know we are working
final CompileResponseImpl response = CompileResponseImpl.make();
response.setModule(messageKey).setStaticName(module);
response.setCompilerStatus(CompilerState.RUNNING);
Type logLevel = request.getLogLevel();
if (logLevel != null)
logger.setMaxDetail(logLevel);
logger.setModule(messageKey);
io.send(response.toJson());
server.ensureStarted();
final GwtcProjectGenerator project = service.getProject(module);
final GwtManifest manifest = project.getManifest();
toManifest(request, manifest);
controller = service.getJobManager().getJob(module);
service.doCompile(manifest, 0, null, (dir, err)->{
modules.put(messageKey, dir);
// notify user we completed successfully
response.setCompilerStatus(CompilerState.FINISHED);
try {
// also notify our frontend that the compiled output has changed
// start or update a proxy server to pull source files from this
// compile.
synchronized (getClass()) {
status = response;
startOrUpdateProxy(dir, controller);
}
initialize(server.ensureStarted(), server.getPort());
} finally {
final String status = response.toJson();
X_Time.runLater(new Runnable() {
@Override
public void run() {
X_Time.trySleep(500, 0);
io.send(status);
}
});
}
// This message is routed to WebFE
io.send("_frontend.symlink_" + dir.toString());
logger.log(Type.INFO, "Finished gwt compile for "
+ request.getModule());
});
// reset interrupted flag so we loop back to the beginning
Thread.interrupted();
} catch (Throwable e) {
System.out.println("Exception caught...");
logger.log(Type.ERROR, "Error encountered during compile : " + e);
Throwable cause = e;
while (cause != null) {
for (StackTraceElement trace : cause.getStackTrace())
logger.log(Type.ERROR, trace.toString());
cause = cause.getCause();
}
if (status == null) {
status = CompileResponseImpl.make();
status.setModule(messageKey);
status.setStaticName(module);
}
status.setCompilerStatus(CompilerState.FAILED);
io.send(status.toJson());
if (isFatal(e))
try {
logger.log(Type.INFO, "Destroying thread " + getClass());
io.destroy();
} catch (Exception ex) {
ex.printStackTrace();
}
return;
} finally {
working = false;
}
}
private GwtManifest toManifest(GwtRecompile request, GwtManifest manifest) {
// GwtManifest manifest = new GwtcManifestImpl(request.getModule());
manifest.setPort(request.getPort());
manifest.setAutoOpen(request.getAutoOpen());
manifest.setSources(X_Collect.asList(String.class, request.getSources().asIterable()));
manifest.setDependencies(X_Collect.asList(String.class, request.getDependencies().asIterable()));
manifest.setLogLevel(request.getLogLevel());
manifest.setExtraArgs(X_Collect.asList(String.class, request.getExtraArgs().asIterable()));
manifest.setObfuscationLevel(request.getObfuscationLevel());
manifest.setOpenAction(request.getOpenAction());
manifest.setRecompile(request.isRecompile());
manifest.setWarDir(CollideOpts.getOpts().getStaticFiles().toString());
return manifest;
}
protected boolean isFatal(Throwable e) {
return true;
}
@Override
public void setChannel(ClassLoader cl, Object io) {
ReflectionChannel channel = new ReflectionChannel(cl, io);
this.io = channel;
logger = new ReflectionChannelTreeLogger(channel, Type.INFO);
}
@Override
public void setOnDestroy(Object runOnDestroy) {
assert io != null : "You must call .setChannel() before calling .setOnDestroy()."
+ " Called from " + DebugUtil.getCaller();
this.io.setOnDestroy(runOnDestroy);
}
@Override
public void compile(String request) throws CompilerBusyException {
if (working)
throw new CompilerBusyException(GwtRecompileImpl.fromJsonString(request).getModule());
synchronized (GwtCompilerThread.class) {
working = true;
try {
if (!isAlive()) {
start();
}
} catch (Exception e) {
logger().log(Type.ERROR, "Fatal error trying to start gwt compiler", e);
try {
io.destroy();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
// wake everyone up to check if they have work to do
getClass().notify();
}
}
}
@Override
protected void handleBuffer(NetSocket event, Buffer buffer)
throws IOException {
// called when this compile is open for business
// status.setCompilerStatus(CompileStatus.SERVING);
// io.send(status.toJson());
compileServer = new GwtCompilationServer();
compileServer.handleBuffer(event, buffer, controller, modules::get);
}
@Override
public boolean isRunning() {
return working;
}
@Override
public boolean isStarted() {
return started;
}
@Override
public void kill() {
if (controller != null) {
controller.destroy();
}
}
@Override
public void doRecompile() {
recompile = 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/collide/gwtc/GwtCompileStatus.java | client/src/main/java/collide/gwtc/GwtCompileStatus.java | package collide.gwtc;
public enum GwtCompileStatus {
Pending, Good, Warn, Error, Fail, Success, PartialSuccess;
} | 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/collide/gwtc/GwtcController.java | client/src/main/java/collide/gwtc/GwtcController.java | package collide.gwtc;
public interface GwtcController {
void onCloseClicked();
void onRefreshClicked();
void onReloadClicked();
}
| 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/collide/gwtc/view/GwtcModuleControlView.java | client/src/main/java/collide/gwtc/view/GwtcModuleControlView.java | package collide.gwtc.view;
import xapi.inject.impl.SingletonProvider;
import xapi.log.X_Log;
import collide.client.common.CanRunApplication;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeModelNetworkController.OutgoingController;
import collide.client.filetree.FileTreeNodeRenderer;
import collide.client.filetree.FileTreeNodeRenderer.Css;
import collide.client.util.Elements;
import collide.gwtc.GwtCompileStatus;
import collide.gwtc.GwtcController;
import collide.gwtc.resources.GwtcResources;
import com.google.collide.client.code.FileTreeSection;
import com.google.collide.client.code.debugging.DebuggingModelController;
import com.google.collide.client.code.debugging.DebuggingModelRenderer;
import com.google.collide.client.code.debugging.DebuggingSidebar;
import com.google.collide.client.code.debugging.EvaluationPopupController;
import com.google.collide.client.code.debugging.SourceMapping;
import com.google.collide.client.code.debugging.StaticSourceMapping;
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.PushChannel;
import com.google.collide.client.communication.ResourceUriUtils;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.ui.dropdown.DropdownWidgets;
import com.google.collide.client.ui.menu.PositionController.Position;
import com.google.collide.client.ui.menu.PositionController.PositionerBuilder;
import com.google.collide.client.ui.menu.PositionController.VerticalAlign;
import com.google.collide.client.ui.popup.Popup;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.PopupBlockedInstructionalPopup;
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.WorkspaceTreeUpdate;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.SpanElement;
import elemental.js.dom.JsElement;
public class GwtcModuleControlView {
public interface FileResources extends DropdownWidgets.Resources,
Tooltip.Resources,
FileTreeNodeRenderer.Resources,
FileTreeSection.Resources,
Popup.Resources,
DebuggingModelRenderer.Resources,
PopupBlockedInstructionalPopup.Resources,
EvaluationPopupController.Resources,
DebuggingSidebar.Resources
{
}
final FileResources resources = GWT.create(FileResources.class);
// This is a class that binds our ui.xml file to GwtcModuleControlView class
@UiTemplate("GwtcModuleControlView.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, GwtcModuleControlView> {}
// This is a generated instance of the above interface. It fills in this class's values.
static MyBinder binder = GWT.create(MyBinder.class);
// A provider for our resources; this object will create one and only one copy of resources,
// and make sure the css is injected into the hostpage before returning the resource provider.
private static final SingletonProvider<GwtcResources> resourceProvider = new SingletonProvider<GwtcResources>(){
protected GwtcResources initialValue() {
GwtcResources res = GWT.create(GwtcResources.class);
res.panelHeaderCss().ensureInjected();
return res;
};
};
/**
* Creates a new panel header with the given resources, all of which may be null.
*
* @param moduleContainer - The element in which to append the header.
* If null, you must attach the header somewhere.
* @param res - GwtcCss resource overrides. If null, our defaults are applied.
* @param model - A model for the panel, which contains values like isMaximizable, isClosable, etc.
*
* @return - A GwtcModuleControlView widget.
*/
public static GwtcModuleControlView create(GwtcController controller) {
return new GwtcModuleControlView(null, controller);
}
// The elements from our .ui.xml file. These are filled in by the compiler.
@UiField public Element header;
@UiField Element headerContainer;
@UiField Element controls;
@UiField Element close;
@UiField Element icons;
@UiField Element reload;
@UiField Element status;
@UiField Element generated;
// This is our css data; the compiler uses this object when filling in values.
@UiField(provided=true) final GwtcResources res;
private GwtCompileStatus currentStatus = GwtCompileStatus.Pending;
public GwtcModuleControlView(GwtcResources res, final GwtcController controller) {
// Allow users to override default css.
this.res = res == null ? resourceProvider.get() : res;
// Calls into the generated ui binder, creating html elements and filling in our values.
binder.createAndBindUi(this);
Css css = this.res.workspaceNavigationFileTreeNodeRendererCss();
JsoStringMap<String> map = FileTreeNodeRenderer.createFileTypeMap(css);
SpanElement contents = FileTreeNodeRenderer.renderNodeContents(css, "Generated", false, true, map, new EventListener() {
@Override
public void handleEvent(Event evt) {
FileTreeSection files = testFileTree();
generated.<JsElement>cast().appendChild(files.getView().getElement());
files.getTree().renderTree(0);
Popup popup = Popup.create(resources);
popup.addPartner(generated.<JsElement>cast());
popup.setContentElement(files.getView().getElement());
popup.show(new PositionerBuilder()
.setVerticalAlign(VerticalAlign.BOTTOM)
.setPosition(Position.NO_OVERLAP)
.buildAnchorPositioner(generated.<JsElement>cast()));
}
}, true);
Elements.asJsElement(generated).appendChild(contents);
reload.<JsElement>cast().setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
controller.onRefreshClicked();
}
});
close.<JsElement>cast().setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
controller.onCloseClicked();
}
});
status.<JsElement>cast().setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
if (currentStatus == null) {
controller.onReloadClicked();
return;
}
switch (currentStatus) {
case PartialSuccess:
case Pending:
case Success:
case Fail:
controller.onReloadClicked();
default:
// TODO warn that a compile is in progress
}
}
});
}
public elemental.dom.Element getElement() {
return (elemental.dom.Element)headerContainer;
}
public void setCompileStatus(GwtCompileStatus compileStatus) {
assert compileStatus != null;
X_Log.info("Setting compile status", compileStatus.name(), this);
if (currentStatus == compileStatus) {
return;
}
status.removeClassName(classFor(currentStatus));
status.addClassName(classFor(compileStatus));
currentStatus = compileStatus;
}
private String classFor(GwtCompileStatus status) {
switch (status) {
case Pending:
return res.panelHeaderCss().gear();
case Success:
return res.panelHeaderCss().success();
case PartialSuccess:
return res.panelHeaderCss().warn();
case Good:
return res.panelHeaderCss().radarGreen();
case Warn:
return res.panelHeaderCss().radarYellow();
case Error:
return res.panelHeaderCss().radarRed();
case Fail:
return res.panelHeaderCss().fail();
}
throw new IllegalStateException();
}
public void setHeader(String id) {
header.setInnerHTML(id);
}
private FileTreeSection testFileTree() {
Place place = new Place("Generated") {
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(
final JsonStringMap<String> decodedState) {
return new PlaceNavigationEvent<Place>(this) {
@Override
public JsonStringMap<String> getBookmarkableState() {
return decodedState;
}
};
}
};
FileTreeController<?> fileTreeController = new FileTreeController<FileResources>() {
protected StatusManager statusManager;
protected MessageFilter messageFilter;
protected PushChannel pushChannel;
protected FrontendApi frontendApi;
{
this.statusManager = new StatusManager();
this.messageFilter = new MessageFilter();
// Things that depend on message filter/frontendApi/statusManager
this.pushChannel = PushChannel.create(messageFilter, statusManager);
this.frontendApi = FrontendApi.create(pushChannel, statusManager);
}
@Override
public FileResources getResources() {
return resources;
}
@Override
public void mutateWorkspaceTree(WorkspaceTreeUpdate msg, ApiCallback<EmptyMessage> callback) {
frontendApi.MUTATE_WORKSPACE_TREE.send(msg, callback);
}
@Override
public void getFileContents(GetFileContents getFileContents,
ApiCallback<GetFileContentsResponse> callback) {
frontendApi.GET_FILE_CONTENTS.send(getFileContents, callback);
}
@Override
public StatusManager getStatusManager() {
return statusManager;
}
@Override
public void getDirectory(GetDirectory getDirectoryAndPath,
ApiCallback<GetDirectoryResponse> callback) {
frontendApi.GET_DIRECTORY.send(getDirectoryAndPath, callback);
}
@Override
public MessageFilter getMessageFilter() {
return messageFilter;
}
};
OutgoingController networkController = new OutgoingController(fileTreeController);
FileTreeModel fileTreeModel = new FileTreeModel(networkController);
CanRunApplication runner = new CanRunApplication() {
@Override
public boolean runApplication(PathUtil applicationPath) {
String baseUri = ResourceUriUtils.getAbsoluteResourceBaseUri();
SourceMapping sourceMapping = StaticSourceMapping.create(baseUri);
elemental.html.Window popup = DebuggingModelController.createOrOpenPopup(resources);
if (popup != null) {
String absoluteResourceUri = sourceMapping.getRemoteSourceUri(applicationPath);
popup.getLocation().assign(absoluteResourceUri);
}
return false;
}
};
return FileTreeSection.create(place, fileTreeController, fileTreeModel, runner);
}
}
| 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/collide/gwtc/ui/RunningGwtModule.java | client/src/main/java/collide/gwtc/ui/RunningGwtModule.java | package collide.gwtc.ui;
import collide.gwtc.ui.GwtCompilerShell.View;
import collide.plugin.client.terminal.TerminalLogHeader;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.LogMessage;
import elemental.client.Browser;
import elemental.dom.Element;
import elemental.html.DivElement;
import xapi.util.impl.StringId;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.user.client.Window;
public class RunningGwtModule extends StringId implements TerminalLogHeader {
DivElement el;
Type type = Type.ALL;
public RunningGwtModule(String module) {
super(module);
el = Browser.getDocument().createDivElement();
el.setInnerHTML("Compiling "+module);
}
@Override
public void viewLog(LogMessage log) {
}
@Override
public Element getElement() {
return el;
}
@Override
public String getName() {
return getId();
}
@SuppressWarnings("incomplete-switch")
public void processResponse(CompileResponse status, View view) {
switch (status.getCompilerStatus()) {
case BLOCKING:
//confirm if the user wants to kill previous compile
if (Window.confirm("There is already a compile in progress for " +
"the module "+status.getModule()+". "
+(status.isAuthorized()?
"Do you wish to kill the running task?":
"Press ok to wait for the running task to complete.")
)) {
return;
}
// kill the compiler
view.getDelegate().onKillButtonClicked();
break;
case RUNNING:
view.updateStatus("Compiling "+status.getModule());
break;
case SERVING:
view.updateStatus("Serving module "+status.getModule());
if (view.gwtSettings.radioIframe.isChecked()){
if (status.getStaticName() != null) {
view.setMessageKey(status.getModule(), status.getStaticName());
}
String key = status.getStaticName() == null ? status.getModule() : status.getStaticName();
view.getDelegate().openIframe(key, status.getPort());
}else if (view.gwtSettings.radioSelf.isChecked()){
Window.Location.reload();
}else if (view.gwtSettings.radioWindow.isChecked()){
view.getDelegate().openWindow(status.getModule(), status.getPort());
}
break;
case UNLOADED:
case FINISHED:
view.updateStatus("Finished compiling "+status.getModule());
}
}
}
| 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/collide/gwtc/ui/GwtClientPlugin.java | client/src/main/java/collide/gwtc/ui/GwtClientPlugin.java | package collide.gwtc.ui;
import xapi.log.X_Log;
import com.google.collide.client.AppContext;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.FrontendApi.RequestResponseApi;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.FileAssociation;
import com.google.collide.client.plugin.RunConfiguration;
import com.google.collide.client.ui.button.ImageButton;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.Header.Resources;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.CompileResponse.CompilerState;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.GwtCompileImpl;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicServices;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Window;
import elemental.dom.Element;
public class GwtClientPlugin
implements ClientPlugin<GwtCompilePlace>, RunConfiguration
{
private AppContext appContext;
private GwtCompileNavigationHandler handler;
private Place place;
private final FileAssociation GWT_FILE_ASSOCIATION;
private final PublicService<?>[] services = new PublicService[1];
public GwtClientPlugin() {
GWT_FILE_ASSOCIATION = new FileAssociation() {
@Override
public boolean matches(String filename) {
return filename.matches(".*gwt[.]*xml");
}
};
}
@Override
public GwtCompilePlace getPlace() {
return GwtCompilePlace.PLACE;
}
@Override
public void initializePlugin(
AppContext appContext, MultiPanel<?,?> masterPanel, Place parentPlace) {
handler = new GwtCompileNavigationHandler(appContext, masterPanel, parentPlace);
services[0] = PublicServices.createProvider(GwtCompilerService.class, handler);
parentPlace.registerChildHandler(getPlace(), handler);
this.place = parentPlace;
this.appContext = appContext;
}
@Override
public ImageResource getIcon(Resources res) {
return res.gwtIcon();
}
@Override
public void onClicked(ImageButton button) {
GwtRecompileImpl gwtCompile = getCompilerSettings();
PlaceNavigationEvent<GwtCompilePlace> action = GwtCompilePlace.PLACE.createNavigationEvent(gwtCompile);
place.fireChildPlaceNavigation(action);
}
protected GwtCompileImpl getCompilerSettings() {
GwtCompileImpl gwtCompile = handler.getValue();
if (null==gwtCompile.getModule()||gwtCompile.getModule().length()==0) {
gwtCompile.setModule("com.google.collide.plugin.StandalonePlugin");
}
if (null==gwtCompile.getSources()||gwtCompile.getSources().size()==0) {
gwtCompile.setSources(JsoArray.<String>from(
//our source list. These come before gwt sdk
"java","bin/gen", "plugin" // workspace relative source paths (hardcoded to collide)
//ok to add jars as source if you wish
,"xapi-gwt.jar"
,"gson-2.7.jar"
,"guava-gwt-12.0.jar"
,"collide-client.jar"
))
.setDependencies(JsoArray.<String>from(
//our dependencies. These come after gwt sdk
"xapi-dev.jar"
,"elemental.jar"
,"client-src.jar"
,"client-common-src.jar"
,"client-scheduler-src.jar"
,"common-src.jar"
,"concurrencycontrol-src.jar"
,"model-src.jar"
,"media-src.jar"
,"waveinabox-import-0.3.jar"
,"jsr305.jar"
,"guava-12.0.jar"
));
}
return gwtCompile;
}
@Override
public FileAssociation getFileAssociation() {
return GWT_FILE_ASSOCIATION;
}
@Override
public RunConfiguration getRunConfig() {
return this;
}
@Override
public String getId() {
return "GWT_COMPILE";
}
@Override
public String getLabel() {
return "Compile GWT Module";
}
@Override
public Element getForm() {
return null;
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void run(AppContext appContext, PathUtil file) {
GwtRecompileImpl gwtCompile = getCompilerSettings();
RequestResponseApi endpoint =
gwtCompile.isRecompile()
? appContext.getFrontendApi().RE_COMPILE_GWT
: appContext.getFrontendApi().COMPILE_GWT;
endpoint.send(gwtCompile , new ApiCallback<CompileResponse>() {
@Override
public void onMessageReceived(CompileResponse message) {
CompilerState state = message.getCompilerStatus();
X_Log.info("Gwt state",state);
if (state == CompilerState.RUNNING) {
}
}
@Override
public void onFail(FailureReason reason) {
Window.alert("Gwt compile failure: " + reason);
}
});
}
@Override
public PublicService<?>[] getPublicServices() {
return services ;
}
}
| 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/collide/gwtc/ui/GwtCompilePlace.java | client/src/main/java/collide/gwtc/ui/GwtCompilePlace.java | package collide.gwtc.ui;
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.workspace.WorkspacePlace;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
import elemental.client.Browser;
import elemental.dom.Node;
import elemental.dom.NodeList;
import elemental.dom.TimeoutHandler;
import xapi.fu.Lazy;
public class GwtCompilePlace extends Place{
public class NavigationEvent extends PlaceNavigationEvent<GwtCompilePlace> {
public static final String MODULE_KEY = "m";
public static final String SRC_KEY = "s";
public static final String DEPS_KEY = "d";
private final String module;
private final JsoArray<String> srcDir;
private final JsoArray<String> depsDir;
private final boolean recompile;
private NavigationEvent(GwtRecompile module) {
super(GwtCompilePlace.this);
this.module = module.getModule();
this.recompile = module.isRecompile();
if (module.getSources() == null) {
this.srcDir = JsoArray.create();
this.depsDir = JsoArray.create();
} else {
this.srcDir = JsoArray.from(module.getSources());
this.depsDir = JsoArray.from(module.getDependencies());
}
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> map = JsoStringMap.create();
map.put(MODULE_KEY, module);
map.put(SRC_KEY, srcDir.join("::"));
map.put(DEPS_KEY, depsDir.join("::"));
return map;
}
public String getModule() {
return module;
}
public boolean isRecompile() {
return recompile;
}
public JsoArray<String> getSourceDirectory() {
return srcDir;
}
public JsoArray<String> getLibsDirectory() {
return depsDir;
}
}
public static final GwtCompilePlace PLACE = new GwtCompilePlace();
private GwtCompilePlace() {
super(PlaceConstants.GWT_PLACE_NAME);
setIsStrict(false);
}
private final Lazy<String> guessModuleFromHostPage
= new Lazy<>(() -> {
//first try guessing from head
NodeList kids = Browser.getDocument().getHead().getChildNodes();
int limit = kids.getLength();
//search backwards, as gwt .nocache.js generally comes after other js imports
while(limit-->0){
Node n = kids.item(limit);
if (n.getNodeName().equalsIgnoreCase("script")){
Node srcAttr = n.getAttributes().getNamedItem("src");
if (srcAttr == null) continue;
String src = srcAttr.getNodeName();
if (src.contains(".nocache.js")){
//we have a winner!
src = src.substring(src.lastIndexOf('/')+1);
return src.substring(0, src.length() - 11);
}
}
}
return null;
});
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(
JsonStringMap<String> decodedState) {
String srcDir = decodedState.get(NavigationEvent.SRC_KEY);
if (srcDir == null) {
srcDir = "";
}
String libDir = decodedState.get(NavigationEvent.DEPS_KEY);
if (libDir == null) {
libDir = "";
}
String module = decodedState.get(NavigationEvent.MODULE_KEY);
if (module == null){
//guess our own module source
module = guessModuleFromHostPage.out1();
}
GwtRecompileImpl compile = GwtRecompileImpl.make();
compile.setModule(module);
JsoArray<String>
array = JsoArray.splitString(srcDir, "::");
compile.setSources(array);
array = JsoArray.splitString(libDir, "::");
compile.setDependencies(array);
return new NavigationEvent(compile);
}
/**
* @param compile the gwt module to compile
* @return a new navigation event
*/
public PlaceNavigationEvent<GwtCompilePlace> createNavigationEvent(GwtRecompile compile) {
return new NavigationEvent(compile);
}
@Override
public boolean isActive() {
return true;
}
public void fireCompile(String module) {
GwtRecompileImpl compile = GwtRecompileImpl.make();
compile.setModule(module);
compile.setIsRecompile(false);
fire(compile);
}
public void fireRecompile(String module){
GwtRecompileImpl compile = GwtRecompileImpl.make();
compile.setModule(module);
compile.setIsRecompile(true);
fire(compile);
}
private void fire(GwtRecompileImpl compile) {
final PlaceNavigationEvent<?> child = WorkspacePlace.PLACE.getCurrentChildPlaceNavigation();
new Exception();
WorkspacePlace.PLACE.disableHistorySnapshotting();
setIsActive(true, WorkspacePlace.PLACE);
WorkspacePlace.PLACE.fireChildPlaceNavigation(createNavigationEvent(compile));
WorkspacePlace.PLACE.enableHistorySnapshotting();
Browser.getWindow().setTimeout(new TimeoutHandler() {
@Override
public void onTimeoutHandler() {
WorkspacePlace.PLACE.disableHistorySnapshotting();
WorkspacePlace.PLACE.fireChildPlaceNavigation(child);
WorkspacePlace.PLACE.enableHistorySnapshotting();
}
}, 1);
}
}
| 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/collide/gwtc/ui/GwtController.java | client/src/main/java/collide/gwtc/ui/GwtController.java | package collide.gwtc.ui;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.GwtRecompile;
import com.google.gwt.core.ext.TreeLogger.Type;
public interface GwtController {
void onCompileButtonClicked();
void onStatusMessageReceived(CompileResponse status);
void setLogLevel(Type type);
void onDraftButtonClicked();
void onKillButtonClicked();
void openIframe(String module, int port);
void openWindow(String module, int port);
void recompile(GwtRecompile existing);
void setAutoOpen(boolean auto);
void onSaveButtonClicked();
void onLoadButtonClicked();
void onTestButtonClicked();
} | 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/collide/gwtc/ui/GwtCompilerService.java | client/src/main/java/collide/gwtc/ui/GwtCompilerService.java | package collide.gwtc.ui;
import xapi.util.api.SuccessHandler;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.GwtRecompile;
public interface GwtCompilerService {
void compile(GwtRecompile module, SuccessHandler<CompileResponse> response);
void recompile(String module, SuccessHandler<CompileResponse> response);
void kill(String module);
GwtCompilerShell getShell();
}
| 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/collide/gwtc/ui/GwtModuleView.java | client/src/main/java/collide/gwtc/ui/GwtModuleView.java | package collide.gwtc.ui;
import xapi.gwtc.api.GwtManifest;
import xapi.util.api.ReceivesValue;
import xapi.util.api.RemovalHandler;
import com.google.collide.client.CollideSettings;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.shared.CookieKeys;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.DOM;
import elemental.client.Browser;
import elemental.dom.Node;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.DataListElement;
import elemental.html.DivElement;
import elemental.html.HTMLCollection;
import elemental.html.InputElement;
import elemental.html.LabelElement;
import elemental.html.OptionElement;
import elemental.util.ArrayOf;
import elemental.util.Collections;
import elemental.util.MapFromStringTo;
public class GwtModuleView extends CompositeView<GwtController>{
@UiTemplate("GwtModuleView.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, GwtModuleView> {
}
static MyBinder binder = GWT.create(MyBinder.class);
public interface Css extends CssResource {
String moduleInput();
String centered();
}
public interface Resources extends
ClientBundle
{
@Source("GwtModuleView.css")
Css gwtModuleCss();
}
//TODO: turn into a module typeahead box.
@UiField com.google.gwt.dom.client.InputElement input;
@UiField com.google.gwt.dom.client.DivElement body;
@UiField com.google.gwt.dom.client.LabelElement inputLabel;
@UiField com.google.gwt.dom.client.Element data;
private final DataListElement list;
private MapFromStringTo<GwtRecompile> modules;
private final ArrayOf<ReceivesValue<GwtRecompile>> listeners;
public GwtModuleView(Resources res, GwtManifest model) {
listeners = Collections.arrayOf();
modules = Collections.mapFromStringTo();
binder.createAndBindUi(this);
input.setId(DOM.createUniqueId());
data.setId(DOM.createUniqueId());
InputElement in = (InputElement)input;
//associate our data list in the browser's typeahead
(in).setAttribute("list", data.getId());
//associate label to our input; this should be done in generator
((LabelElement)inputLabel).setHtmlFor(input.getId());
setModuleTextbox(model.getModuleName());
list = (elemental.html.DataListElement)data;
//TODO restore module from cookie
EventListener ev = new EventListener() {
String was = "";
@Override
public void handleEvent(Event evt) {
String is = input.getValue().trim();
if (is.equals(was))return;
was = is;
GwtRecompile module = modules.get(is);
if (module != null) {
showModule(module);
}
}
};
in.setOninput(ev);
res.gwtModuleCss().ensureInjected();
}
protected void showModule(GwtRecompile module) {
setModuleTextbox(module.getModule());
input.select();
for (int i = 0, m = listeners.length(); i < m; i++) {
ReceivesValue<GwtRecompile> listener = listeners.get(i);
listener.set(module);
}
}
public static GwtModuleView create(DivElement moduleContainer, Resources res,
GwtManifest model) {
GwtModuleView mod = new GwtModuleView(res, model);
moduleContainer.appendChild((DivElement)mod.body);
return mod;
}
private void setModuleTextbox(String module) {
Log.info(getClass(), "Got Module",module);
input.setValue(module);
input.setDefaultValue(module);
}
public GwtRecompile getModule(String module) {
return modules.get(module);
}
public void showResults(JsonArray<GwtRecompile> modules, GwtClasspathView classpath) {
if (modules.size() == 0)
return;
CollideSettings settings = CollideSettings.get();
String requested = settings.getModule();
GwtRecompile best = null;
if (requested == null) {
requested = Browser.getWindow().getLocalStorage().getItem(CookieKeys.GWT_COMPILE_TARGET);
}
if (requested != null) {
for (GwtRecompile compile : modules.asIterable()) {
if (requested.equals(compile.getModule())) {
best = compile;
break;
}
}
}
this.modules = Collections.mapFromStringTo();
HTMLCollection opts = (list).getOptions();
int m = opts.length();
if (m == 0) {
m = modules.size();
for (int i = 0; i < m; i++) {
list.appendChild(createOption(modules.get(i), i == 0));
}
} else {
// There are modules, let's merge
MapFromStringTo<Node> existing = Collections.mapFromStringTo();
for (int i = 0; i < m; i++) {
Node opt = opts.item(i);
Node attr = opt.getAttributes().getNamedItem("value");
if (attr != null)
existing.put(attr.getNodeValue(), opt);
}
m = modules.size();
for (int i = 0; i < m; i++) {
GwtRecompile module = modules.get(i);
Node duplicate = existing.get(module.getModule());
if (duplicate != null) {
// TODO check revision # and take freshest
duplicate.removeFromParent();
}
OptionElement opt = createOption(module, i == 0);
list.appendChild(opt);
}
}
if (best == null)
best = modules.get(0);
setModuleTextbox(best.getModule());
classpath.setClasspath(best.getSources(), best.getDependencies());
}
protected OptionElement createOption(GwtRecompile module, boolean selected) {
modules.put(module.getModule(), module);
OptionElement option = Browser.getDocument().createOptionElement();
option.setDefaultSelected(selected);
option.setAttribute("name", module.getModule());
option.setText(module.getModule());
option.setValue(module.getModule());
return option;
}
public RemovalHandler addSelectListener(final ReceivesValue<GwtRecompile> receivesValue) {
listeners.push(receivesValue);
return new RemovalHandler() {
@Override
public void remove() {
listeners.remove(receivesValue);
}
};
}
public String getModule() {
return input.getValue();
}
}
| 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/collide/gwtc/ui/GwtLogView.java | client/src/main/java/collide/gwtc/ui/GwtLogView.java | package collide.gwtc.ui;
import collide.client.common.CommonResources;
import collide.client.util.Elements;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.LogMessage;
import com.google.collide.json.client.JsoArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
public class GwtLogView extends UiComponent<GwtLogView.View>{
int scrollHeight = 0;
protected GwtLogView() {
}
public GwtLogView(collide.gwtc.ui.GwtCompilerShell.Resources res) {
super();
View view = new View(res);
setView(view);
view.setDelegate(new ViewEventsImpl());
}
public static GwtLogView create(DivElement gwtLogContainer, collide.gwtc.ui.GwtCompilerShell.Resources res){
GwtLogView log = new GwtLogView();
collide.gwtc.ui.GwtLogView.View view = new View(res);
log.setView(view);
gwtLogContainer.appendChild(view.root);
return log;
}
public interface Css extends CssResource {
String bottomPlaceHolder();
String fullSize();
String logAll();
String logDebug();
String logSpam();
String logTrace();
String logInfo();
String logWarning();
String logError();
String logContainer();
String logHeader();
String logBody();
String logPad();
}
public interface Resources extends
ClientBundle
,CommonResources.BaseResources
{
@Source("GwtLogView.css")
Css gwtLogCss();
}
public static interface ViewEvents{
}
public static class ViewEventsImpl implements ViewEvents{
}
public static class View extends CompositeView<ViewEvents>{
@UiTemplate("GwtLogView.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, View> {
}
static MyBinder binder = GWT.create(MyBinder.class);
@UiField
DivElement root;
@UiField(provided = true)
Resources res;
@UiField
DivElement logHeader;
@UiField
DivElement logBody;
@UiField
DivElement background;
public View(collide.gwtc.ui.GwtCompilerShell.Resources res) {
this.res = res;
binder.createAndBindUi(this);
}
}
public void addLog(LogMessage log) {
//get or make a tab header for the desired module
Css css = getView().res.gwtLogCss();
String clsName = css.logInfo();
switch(log.getLogLevel()){
case ERROR:
clsName = css.logError();
break;
case WARN:
clsName = css.logWarning();
break;
case INFO:
clsName = css.logInfo();
break;
case TRACE:
clsName = css.logTrace();
break;
case DEBUG:
clsName = css.logDebug();
break;
case SPAM:
clsName = css.logSpam();
break;
case ALL:
clsName = css.logAll();
break;
}
elemental.html.DivElement el = Elements.createDivElement(clsName);
el.setInnerHTML(log.getMessage().replaceAll("\t", " ").replaceAll(" ", " "));
//TODO: use a page list-view so we can avoid painting 6,000,000 elements at once
enqueue(el);
}
private final JsoArray<elemental.html.DivElement> cached = JsoArray.create();
private final JsoArray<elemental.html.DivElement> els = JsoArray.create();
private ScheduledCommand cmd;
private void enqueue(elemental.html.DivElement el) {
els.add(el);
if (cmd == null){
Scheduler.get().scheduleDeferred(
(cmd = new ScheduledCommand() {
@Override
public void execute() {
cmd = null;
int size = els.size();
elemental.html.DivElement into = (elemental.html.DivElement)getView().logBody;
if (size>500){
//TODO: put in paging instead of truncation
elemental.html.DivElement pager = Elements.createDivElement();
pager.setInnerHTML("...Logs truncated, (" +cached.size()+") elements hidden...");
els.unshift(pager);
cached.addAll(els.splice(0, size-500));
Log.debug(getClass(), "Log overflow; cache-size: "+cached.size()+", element-size: "+els.size());
into.setInnerHTML("");
}
for (elemental.html.DivElement el : els.asIterable()){
into.appendChild(el);
}
updateScrolling();
}
})
);
}
}
private void updateScrolling() {
elemental.html.DivElement body = (elemental.html.DivElement)getView().root;
int sH = body.getScrollHeight(), sT = body.getScrollTop(), h = body.getClientHeight();
if (scrollHeight - h <= sT){//user was scrolled to the bottom last update,
body.setScrollTop(sH);//force back to bottom
}
scrollHeight = sH;
}
}
| 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/collide/gwtc/ui/GwtSettingsView.java | client/src/main/java/collide/gwtc/ui/GwtSettingsView.java | package collide.gwtc.ui;
import xapi.gwtc.api.GwtManifest;
import xapi.gwtc.api.OpenAction;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.mvp.CompositeView;
import com.google.common.base.Strings;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.LabelElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.DOM;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.DivElement;
import elemental.js.html.JsInputElement;
public class GwtSettingsView extends CompositeView<GwtController>{
@UiTemplate("GwtSettings.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, GwtSettingsView> {
}
static MyBinder binder = GWT.create(MyBinder.class);
public interface Css extends CssResource {
String settingsContainer();
String urlBox();
String urlBoxContainer();
}
public interface Resources extends
ClientBundle
{
@Source("GwtSettings.css")
Css gwtSettingsCss();
}
@UiField com.google.gwt.dom.client.DivElement body;
@UiField(provided=true) collide.gwtc.ui.GwtCompilerShell.Resources res;
//run taget radios
@UiField InputElement radioIframe;
@UiField LabelElement labelIframe;
@UiField InputElement radioSelf;
@UiField LabelElement labelSelf;
@UiField InputElement radioWindow;
@UiField LabelElement labelWindow;
@UiField InputElement radioNoOpen;
@UiField LabelElement labelNoOpen;
@UiField com.google.gwt.dom.client.DivElement containerToOpen;
@UiField InputElement inputToOpen;
@UiField LabelElement labelToOpen;
@UiField InputElement inputAutoOpen;
@UiField LabelElement labelAutoOpen;
//log level radios
@UiField InputElement radioLogAll;
@UiField LabelElement labelLogAll;
@UiField InputElement radioLogSpam;
@UiField LabelElement labelLogSpam;
@UiField InputElement radioLogDebug;
@UiField LabelElement labelLogDebug;
@UiField InputElement radioLogTrace;
@UiField LabelElement labelLogTrace;
@UiField InputElement radioLogInfo;
@UiField LabelElement labelLogInfo;
@UiField InputElement radioLogWarn;
@UiField LabelElement labelLogWarn;
@UiField InputElement radioLogError;
@UiField LabelElement labelLogError;
@UiField InputElement checkDraftMode;
@UiField LabelElement labelDraftMode;
private final GwtManifest model;
public GwtSettingsView(collide.gwtc.ui.GwtCompilerShell.Resources res, GwtManifest gwtModel) {
this.res = res;
binder.createAndBindUi(this);
this.model = gwtModel;
res.gwtSettingsCss().ensureInjected();
setLabelFor(radioIframe, labelIframe);
setLabelFor(radioSelf, labelSelf);
setLabelFor(radioWindow, labelWindow);
setLabelFor(radioNoOpen, labelNoOpen);
setLabelFor(inputToOpen, labelToOpen);
setLabelFor(inputAutoOpen, labelAutoOpen);
model.setUrlToOpen(inputToOpen.getValue());
((elemental.html.InputElement)inputToOpen).setOnchange(new EventListener() {
@Override
public void handleEvent(Event evt) {
model.setUrlToOpen(inputToOpen.getValue());
}
});
((elemental.html.InputElement)inputAutoOpen).setOnchange(new EventListener() {
@Override
public void handleEvent(Event evt) {
boolean auto = isAutoOpen();
model.setAutoOpen(auto);
getDelegate().setAutoOpen(auto);
}
});
addCompileTargetChangeListener((elemental.dom.Element)radioIframe,OpenAction.IFRAME);
addCompileTargetChangeListener((elemental.dom.Element)radioSelf, OpenAction.RELOAD);
addCompileTargetChangeListener((elemental.dom.Element)radioWindow,OpenAction.WINDOW);
addCompileTargetChangeListener((elemental.dom.Element)radioNoOpen,OpenAction.NO_ACTION);
setLabelFor(radioLogAll, labelLogAll);
setLabelFor(radioLogSpam, labelLogSpam);
setLabelFor(radioLogDebug, labelLogDebug);
setLabelFor(radioLogTrace, labelLogTrace);
setLabelFor(radioLogWarn, labelLogWarn);
setLabelFor(radioLogInfo, labelLogInfo);
setLabelFor(radioLogError, labelLogError);
addLogLevelChangeListener((elemental.html.InputElement)radioLogAll, Type.ALL);
addLogLevelChangeListener((elemental.html.InputElement)radioLogSpam, Type.SPAM);
addLogLevelChangeListener((elemental.html.InputElement)radioLogDebug, Type.DEBUG);
addLogLevelChangeListener((elemental.html.InputElement)radioLogTrace, Type.TRACE);
addLogLevelChangeListener((elemental.html.InputElement)radioLogInfo, Type.INFO);
addLogLevelChangeListener((elemental.html.InputElement)radioLogWarn, Type.WARN);
addLogLevelChangeListener((elemental.html.InputElement)radioLogError, Type.ERROR);
refreshDom();
}
private void addLogLevelChangeListener(elemental.html.InputElement radio, final Type type) {
radio.addEventListener("change",
new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().setLogLevel(type);
}
}, false);
}
private void setLabelFor(InputElement radio, LabelElement label) {
if (Strings.isNullOrEmpty(radio.getId()))
radio.setId(DOM.createUniqueId());
label.setHtmlFor(radio.getId());
}
private void addCompileTargetChangeListener(Element el, final OpenAction action) {
el.addEventListener("change",
new EventListener() {
@Override
public void handleEvent(Event evt) {
model.setOpenAction(action);
switch (action) {
case IFRAME:
case WINDOW:
containerToOpen.getStyle().setHeight(60, Unit.PX);
break;
case NO_ACTION:
case RELOAD:
containerToOpen.getStyle().setHeight(0, Unit.PX);
break;
}
saveState(model);
}
},false);
}
protected void saveState(GwtManifest model) {
}
protected void refreshDom() {
inputAutoOpen.setChecked(model.isAutoOpen());
switch (model.getOpenAction()) {
case IFRAME:
radioIframe.setChecked(true);
containerToOpen.getStyle().setHeight(60, Unit.PX);
inputToOpen.setValue(model.getUrlToOpen());
break;
case NO_ACTION:
containerToOpen.getStyle().setHeight(0, Unit.PX);
radioNoOpen.setChecked(true);
break;
case RELOAD:
containerToOpen.getStyle().setHeight(0, Unit.PX);
radioSelf.setChecked(true);
break;
case WINDOW:
radioWindow.setChecked(true);
containerToOpen.getStyle().setHeight(60, Unit.PX);
inputToOpen.setValue(model.getUrlToOpen());
break;
}
switch (model.getLogLevel()){
case ALL:
radioLogAll.setChecked(true);break;
case SPAM:
radioLogSpam.setChecked(true);break;
case DEBUG:
radioLogDebug.setChecked(true);break;
case TRACE:
radioLogTrace.setChecked(true);break;
case INFO:
radioLogInfo.setChecked(true);break;
case WARN:
radioLogWarn.setChecked(true);break;
case ERROR:
radioLogError.setChecked(true);break;
}
}
public static GwtSettingsView create(DivElement moduleContainer, collide.gwtc.ui.GwtCompilerShell.Resources res,
GwtManifest model) {
GwtSettingsView mod = new GwtSettingsView(res, model);
moduleContainer.appendChild((DivElement)mod.body);
return mod;
}
public void applySettings(GwtRecompile module) {
Type logLevel;
inputAutoOpen.setChecked(module.getAutoOpen());
logLevel = module.getLogLevel();
if (logLevel != null)
switch (logLevel) {
case ALL:
case SPAM:
case DEBUG:
radioLogDebug.setChecked(true);
break;
case TRACE:
radioLogTrace.setChecked(true);
break;
case INFO:
radioLogInfo.setChecked(true);
break;
case WARN:
radioLogWarn.setChecked(true);
break;
case ERROR:
radioLogError.setChecked(true);
break;
}
}
protected boolean isAutoOpen() {
return inputAutoOpen.<JsInputElement>cast().isChecked() &&
radioIframe.isChecked();
}
protected Type getLogLevel() {
// order based on expected probability of popularity
if (radioLogInfo.isChecked())
return Type.INFO;
if (radioLogWarn.isChecked())
return Type.WARN;
if (radioLogTrace.isChecked())
return Type.TRACE;
if (radioLogError.isChecked())
return Type.ERROR;
if (radioLogDebug.isChecked())
return Type.DEBUG;
if (radioLogSpam.isChecked())
return Type.SPAM;
if (radioLogAll.isChecked())
return Type.ALL;
return Type.INFO;
}
public String getPageToOpen() {
return inputToOpen.getValue();
}
public int getPort() {
return 13377;
}
}
| 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/collide/gwtc/ui/GwtCompilerShell.java | client/src/main/java/collide/gwtc/ui/GwtCompilerShell.java | package collide.gwtc.ui;
import collide.client.common.CommonResources;
import collide.client.util.Elements;
import collide.plugin.client.launcher.LauncherService;
import collide.plugin.client.terminal.TerminalClientPlugin;
import collide.plugin.client.terminal.TerminalService;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.PluginContent;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.plugin.ClientPluginService;
import com.google.collide.client.util.ResizeBounds;
import com.google.collide.client.util.ResizeBounds.BoundsBuilder;
import com.google.collide.client.util.logging.Log;
import com.google.collide.clientlibs.vertx.VertxBus.MessageHandler;
import com.google.collide.clientlibs.vertx.VertxBus.ReplySender;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.CompileResponse.CompilerState;
import com.google.collide.dto.GwtCompile;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.GwtSettings;
import com.google.collide.dto.LogMessage;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.SearchResult;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.CompileResponseImpl;
import com.google.collide.dto.client.DtoClientImpls.GwtCompileImpl;
import com.google.collide.dto.client.DtoClientImpls.GwtKillImpl;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.dto.client.DtoClientImpls.HasModuleImpl;
import com.google.collide.dto.client.DtoClientImpls.LogMessageImpl;
import com.google.collide.json.client.Jso;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.collide.shared.plugin.PublicServices;
import com.google.collide.shared.util.DebugUtil;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.AnchorElement;
import elemental.util.ArrayOf;
import elemental.util.Collections;
import elemental.util.MapFromStringTo;
import xapi.collect.impl.InitMapDefault;
import xapi.fu.In1Out1;
import xapi.gwtc.api.GwtManifest;
import xapi.log.X_Log;
import xapi.util.X_String;
import xapi.util.api.ConvertsValue;
import xapi.util.api.ReceivesValue;
import xapi.util.api.RemovalHandler;
import xapi.util.api.SuccessHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Style.Unit;
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 com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
public class GwtCompilerShell extends UiComponent<GwtCompilerShell.View>
implements PluginContent, In1Out1<String, RunningGwtModule> {
public interface Css extends CssResource {
String container();
String leftPanel();
String moduleContainer();
String next();
String options();
String otherpage();
String pager();
String previous();
String radioLabel();
String rightPanel();
String second();
String srcContainer();
String settingsContainer();
String snippet();
String status();
String statusHidden();
String thispage();
String title();
}
public interface Resources extends
ClientBundle
,CommonResources.BaseResources
,GwtLogView.Resources
,GwtModuleView.Resources
,GwtClasspathView.Resources
,GwtSettingsView.Resources
{
@Source("collide/gwtc/resources/green-radar-small.gif")
ImageResource radarGreenSmall();
@Source("GwtCompilerShell.css")
Css gwtCompilerCss();
}
public static class View extends CompositeView<GwtController> {
@UiTemplate("GwtCompilerShell.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, View> {
}
static MyBinder binder = GWT.create(MyBinder.class);
@UiField(provided = true)
final Resources res;
@UiField(provided = true)
final GwtManifest compileState;
final Css css;
@UiField
DivElement status;
@UiField DivElement buttonContainer;
@UiField DivElement srcContainer;
@UiField DivElement settingsContainer;
@UiField DivElement moduleContainer;
GwtModuleView gwtModule;
GwtClasspathView gwtSrc;
GwtSettingsView gwtSettings;
@UiField
com.google.gwt.dom.client.AnchorElement compileButton;
@UiField
com.google.gwt.dom.client.AnchorElement testButton;
@UiField
com.google.gwt.dom.client.AnchorElement draftButton;
@UiField
com.google.gwt.dom.client.AnchorElement killButton;
@UiField
com.google.gwt.dom.client.AnchorElement save;
@UiField
com.google.gwt.dom.client.AnchorElement load;
public View(AppContext context, GwtManifest model, Resources res) {
this.res = res;
this.css = res.gwtCompilerCss();
this.compileState = model;
setElement(Elements.asJsElement(binder.createAndBindUi(this)));
((AnchorElement)draftButton).setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onDraftButtonClicked();
}
});
((AnchorElement)compileButton).setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onCompileButtonClicked();
}
});
((AnchorElement)testButton).setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onTestButtonClicked();
}
});
((AnchorElement)killButton).setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onKillButtonClicked();
}
});
((AnchorElement)save).setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onSaveButtonClicked();
}
});
((AnchorElement)load).setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
getDelegate().onLoadButtonClicked();
}
});
gwtModule = GwtModuleView.create((elemental.html.DivElement)moduleContainer, res, model);
gwtSrc = GwtClasspathView.create((elemental.html.DivElement)srcContainer, res, model);
gwtSettings = GwtSettingsView.create((elemental.html.DivElement)settingsContainer, res, model);
addListeners();
}
@Override
public void setDelegate(GwtController delegate) {
super.setDelegate(delegate);
gwtModule.setDelegate(delegate);
gwtSrc.setDelegate(delegate);
gwtSettings.setDelegate(delegate);
}
protected void addListeners() {
gwtModule.addSelectListener(new ReceivesValue<GwtRecompile>(){
@Override
public void set(GwtRecompile module) {
gwtSrc.setClasspath(module.getSources(), module.getDependencies());
gwtSettings.applySettings(module);
}
});
}
public void clear() {
gwtSettings.refreshDom();
}
private Timer clear;
public void updateStatus(String string) {
if (clear != null){
clear.cancel();
clear = null;
}
if (X_String.isEmptyTrimmed(string)) {
status.addClassName(res.gwtCompilerCss().statusHidden());
status.getStyle().setHeight(0, Unit.PX);
} else {
status.getStyle().setHeight(30, Unit.PX);
status.removeClassName(res.gwtCompilerCss().statusHidden());
status.setInnerHTML("<pre>"+string+"</pre>");
clear = new Timer() {
@Override
public void run() {
clear = null;
status.addClassName(res.gwtCompilerCss().statusHidden());
status.getStyle().setHeight(0, Unit.PX);
}
};
clear.schedule(15000);
}
}
public GwtCompileImpl getValue() {
GwtCompileImpl compile = GwtCompileImpl.make();
String val = gwtModule.input.getValue();
if (val != null && val.length()>0)
compile.setModule(val);
compile.setAutoOpen(gwtSettings.isAutoOpen());
compile.setLogLevel(gwtSettings.getLogLevel());
compile.setSources(gwtSrc.getSources());
compile.setDependencies(gwtSrc.getDependencies());
return compile;
}
public void clearStatus() {
if (clear != null)
clear.run();
}
public boolean isAutoOpen() {
return gwtSettings.isAutoOpen();
}
public String getModule() {
return gwtModule.getModule();
}
public void setMessageKey(String module, String key) {
}
}
public class GwtControllerImpl implements GwtController{
@Override
public void onDraftButtonClicked() {
GwtRecompileImpl value = getValue();
value.setIsRecompile(true);
context.getFrontendApi().RE_COMPILE_GWT.send(value, new ApiCallback<CompileResponse>() {
@Override
public void onMessageReceived(CompileResponse message) {
if (message == null)
Log.error(getClass(), "Null gwt status message received");
else
onStatusMessageReceived(message);
}
@Override
public void onFail(FailureReason reason) {
}
});
}
@Override
public void onLoadButtonClicked() {
HasModuleImpl msg = HasModuleImpl.make();
msg.setModule(getModule());
context.getFrontendApi().GWT_LOAD.send(msg, new ApiCallback<GwtRecompile>() {
@Override
public void onMessageReceived(GwtRecompile message) {
setValue(message);
}
@Override
public void onFail(FailureReason reason) {
}
});
}
@Override
public void onSaveButtonClicked() {
context.getFrontendApi().GWT_SAVE.send(getValue());
}
@Override
public void setAutoOpen(boolean auto) {
if (auto) {
openIframe();
}
}
@Override
public void onCompileButtonClicked() {
GwtCompileImpl value = getValue();
value.setIsRecompile(false);
context.getFrontendApi().COMPILE_GWT.send(value, new ApiCallback<CompileResponse>() {
@Override
public void onMessageReceived(CompileResponse message) {
if (message == null)
Log.error(getClass(), "Null gwt status message received");
else
onStatusMessageReceived(message);
}
@Override
public void onFail(FailureReason reason) {
}
});
}
@Override
public void onTestButtonClicked() {
GwtCompileImpl value = getValue();
value.setIsRecompile(false);
context.getFrontendApi().TEST_GWT.send(value, new ApiCallback<GwtCompile>() {
@Override
public void onMessageReceived(GwtCompile message) {
if (message == null)
Log.error(getClass(), "Null gwt status message received");
else {
// Turbo hack :(
TerminalClientPlugin plugin = ClientPluginService.getPlugin(TerminalClientPlugin.class);
plugin.setRename(message.getMessageKey(), message.getModule());
X_Log.info(message);
setValue(message);
// CompileResponse status = new CompileResponseImpl();
// onStatusMessageReceived(status);
}
}
@Override
public void onFail(FailureReason reason) {
}
});
}
@Override
public void onKillButtonClicked() {
GwtKillImpl kill = GwtKillImpl.make();
kill.setModule(getModule());
context.getFrontendApi().KILL_GWT.send(kill, new ApiCallback<CompileResponse>() {
@Override
public void onFail(FailureReason reason) {
Window.alert("Failed to kill gwt compile: "+reason+".");
}
@Override
public void onMessageReceived(CompileResponse message) {
Window.alert("Killed compile: "+message.getModule()+".");
RemovalHandler handler = iframeRemovals.get(message.getModule());
if (handler != null) {
handler.remove();
iframeRemovals.remove(message.getModule());
}
}
});
}
@Override
public void onStatusMessageReceived(CompileResponse status) {
updateStatus(status);
}
@Override
public void openIframe(String module, int port) {
LauncherService service = PublicServices.getService(LauncherService.class);
String url = getView().compileState.getUrlToOpen();
if (X_String.isEmptyTrimmed(url))
url = "xapi/gwt/"+module;
url = url.replace("$module", module);
service.openInIframe(module, url);
}
@Override
public void openWindow(String module, int port) {
LauncherService service = PublicServices.getService(LauncherService.class);
service.openInNewWindow(module, "");
}
@Override
public void setLogLevel(Type type) {
assert type != null : "Sent null loglevel from "+DebugUtil.getCaller();
level = type;
getView().compileState.setLogLevel(type);
}
@Override
public void recompile(GwtRecompile existing) {
setValue(existing);
onDraftButtonClicked();
}
private void openIframe() {
String module = getMessageKey();
int port = getView().gwtSettings.getPort();
openIframe(module, port);
}
}
public static GwtCompilerShell create(View view, AppContext context){
return new GwtCompilerShell(view, context);
}
private JsoStringMap<String> keys = JsoStringMap.create();
public void setMessageKey(String module, String key) {
if (key != null) {
keys.put(module, key);
}
}
public String getMessageKey() {
String module = getView().gwtModule.getModule();
String key = keys.get(module);
return key == null ? module : key;
}
public void setValue(GwtRecompile existing) {
getView().gwtModule.showModule(existing);
getView().gwtSettings.applySettings(existing);
getView().gwtSrc.setClasspath(existing.getSources(), existing.getDependencies());
}
private AppContext context;
private Type level;
private final BoundsBuilder bounds = ResizeBounds.withMaxSize(640, -10).minSize(550, 400);
private final ArrayOf<GwtStatusListener> listeners = Collections.arrayOf();
private final MapFromStringTo<RemovalHandler> iframeRemovals = Collections.mapFromStringTo();
protected void updateStatus(CompileResponse status) {
notifyListeners(status);
if(status.getCompilerStatus() == CompilerState.SERVING) {
String page = getView().gwtSettings.getPageToOpen();
if (!X_String.isEmptyTrimmed(page)) {
}
}
}
private void notifyLogLevel(String id, Type level) {
for (int i = 0, m = listeners.length(); i < m; i++) {
listeners.get(i).onLogLevelChange(id, level);
}
}
private void notifyListeners(CompileResponse status) {
loggers.get(status.getModule()).processResponse(status, getView());
for (int i = 0, m = listeners.length(); i < m; i++) {
listeners.get(i).onGwtStatusUpdate(status);
}
}
public void addCompileStateListener(GwtStatusListener listener) {
assert !listeners.contains(listener) : "Don't add the same GwtStatusListener twice: "+listener;
listeners.push(listener);
}
public static class LoggerMap extends InitMapDefault<String, RunningGwtModule> {
public LoggerMap(In1Out1<String, RunningGwtModule> factory) {
super(PASS_THRU, factory);
}
}
private LoggerMap loggers;
public GwtCompilerShell(View view, AppContext context) {
super(view);
this.context = context;
loggers = new LoggerMap(this);
view.setDelegate(createViewDelegate());
context.getPushChannel().receive("gwt.log", new MessageHandler() {
@Override
public void onMessage(String message, ReplySender replySender) {
Jso jso = Jso.deserialize(message);
int type = jso.getIntField("_type");
if (type==RoutingTypes.LOGMESSAGE){
addLog(jso.<LogMessageImpl>cast());
} else if (type == RoutingTypes.COMPILERESPONSE){
updateStatus(jso.<CompileResponseImpl>cast());
} else {
Log.info(getClass(), "Unhandled response type "+type+"; from:\n"+message);
}
}
});
}
public String getModule() {
return getView().getModule();
}
public GwtCompileImpl getValue() {
return getView().getValue();
}
private com.google.collide.client.Resources getIframeResources() {
return context.getResources();
}
protected void addLog(LogMessage log) {
RunningGwtModule logger = loggers.get(log.getModule());
PublicServices.getService(TerminalService.class).addLog(log, logger);
Type type = log.getLogLevel();
logger.type = type;
if (type.ordinal() < type.ordinal()) {
notifyLogLevel(log.getModule(), type);
}
if (type == Type.WARN) {
} else if (type == Type.ERROR) {
}
}
protected GwtController createViewDelegate() {
return new GwtControllerImpl();
}
/**
* Updates with new results.
*
* @param message the message containing the new results.
*/
public void showResults(GwtSettings message) {
getView().clear();
showResultsImpl(message.getModules());
}
@Override
public Element getContentElement() {
return getView().getElement();
}
@Override
public void onContentDisplayed() {
Log.info(getClass(), "Showing compiler controller");
}
/**
* Updates the view to displays results and appropriate pager widgetry.
*
* @param jsonArray the {@link SearchResult} items on this page.
*/
protected void showResultsImpl(JsonArray<GwtRecompile> jsonArray) {
getView().gwtModule.showResults(jsonArray, getView().gwtSrc);
}
public void setPlace(GwtCompilePlace.NavigationEvent place) {
if (place.isRecompile()) {
recompile(place.getModule(), null);
}
}
@Override
public void onContentDestroyed() {
}
@Override
public BoundsBuilder getBounds() {
return bounds;
}
@Override
public String getNamespace() {
return "Gwt Compiler";
}
@Override
public RunningGwtModule io(String from) {
return new RunningGwtModule(from);
}
public void compile(GwtRecompile module,
SuccessHandler<CompileResponse> response) {
}
public void recompile(String module, SuccessHandler<CompileResponse> response) {
GwtRecompile existing = getView().gwtModule.getModule(module);
if (existing != null) {
getView().getDelegate().recompile(existing);
// TODO: use a per-module multi-map of CompileResponse event listeners.
}
}
public void kill(String module) {
}
public boolean isAutoOpen() {
return getView().isAutoOpen();
}
}
| 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/collide/gwtc/ui/GwtClasspathView.java | client/src/main/java/collide/gwtc/ui/GwtClasspathView.java | package collide.gwtc.ui;
import xapi.gwtc.api.GwtManifest;
import xapi.util.X_String;
import collide.client.filetree.FileTreeNodeRenderer;
import collide.client.util.Elements;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.mvp.CompositeView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.DOM;
import elemental.html.DivElement;
import elemental.html.LIElement;
import elemental.html.LabelElement;
import elemental.html.UListElement;
public class GwtClasspathView extends CompositeView<GwtController>{
@UiTemplate("GwtClasspathView.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, GwtClasspathView> {}
static MyBinder binder = GWT.create(MyBinder.class);
public interface Css extends CssResource {
String classpathContainer();
String classpathInput();
}
public interface Resources extends
ClientBundle, FileTreeNodeRenderer.Resources
{
@Source("GwtClasspathView.css")
Css gwtClasspathCss();
}
@UiField com.google.gwt.dom.client.UListElement classpath;
@UiField com.google.gwt.dom.client.DivElement body;
@UiField com.google.gwt.dom.client.LabelElement classpathLabel;
@UiField(provided=true) Resources res;
private JsoArray<String> deps;
private JsoArray<String> srcs;
public GwtClasspathView(Resources res, GwtManifest model) {
this.res = res;
binder.createAndBindUi(this);
//hookup label; should be doing this in generator using ui:field...
classpath.setId(DOM.createUniqueId());
((LabelElement)classpathLabel).setHtmlFor(classpath.getId());
setClasspath(model);
res.gwtClasspathCss().ensureInjected();
}
public static GwtClasspathView create(DivElement moduleContainer, Resources res,
GwtManifest model) {
GwtClasspathView mod = new GwtClasspathView(res, model);
moduleContainer.appendChild((DivElement)mod.body);
return mod;
}
private void setClasspath(GwtManifest model) {
UListElement form = (UListElement) classpath;
form.setInnerHTML("");//clear
JsoArray<String> sources = JsoArray.create();
JsoArray<String> deps = JsoArray.create();
for (String src : model.getClasspath()){
if (!X_String.isEmpty(src))
(src.contains(".jar") ? deps : sources).add(src);
}
setClasspath(sources, deps);
}
public void setClasspath(JsonArray<String> src, JsonArray<String> dep) {
UListElement form = (UListElement) classpath;
form.setInnerHTML("");//clear
this.srcs = JsoArray.create();
this.deps = JsoArray.create();
for (String source : src.asIterable()){
if (!X_String.isEmptyTrimmed(source)){
srcs.add(source);
form.appendChild(buildElement(source));
}
}
for (String source : dep.asIterable()){
if (!X_String.isEmptyTrimmed(source)){
deps.add(source);
form.appendChild(buildElement(source));
}
}
}
private LIElement buildElement(String source) {
LIElement li = Elements.createLiElement(res.gwtClasspathCss().classpathInput());
// TODO add icon for jar v. folder, and add open handlers.
if (source.contains(".jar")) {
markupJar(li, source);
} else {
markupFolder(li, source);
}
return li;
}
protected void markupJar(LIElement li, String source) {
li.setInnerHTML(
jarIcon() +
"<a href=\"" +
openJarLink(source)+
"\">"+source+"</a>");
}
protected void markupFolder(LIElement li, String source) {
li.setInnerHTML(
folderIcon() +
"<a href=\"" +
openFileLink(source)+
"\">"+source+"</a>");
}
protected String jarIcon() {
return "<div class='"
+ res.workspaceNavigationFileTreeNodeRendererCss().jarIcon()
+ "'></div>";
}
protected String folderIcon() {
return "<div class='"
+ res.workspaceNavigationFileTreeNodeRendererCss().folder()
+ "'></div>";
}
protected String openJarLink(String source) {
return "#!jar:"+source;
}
protected String openFileLink(String source) {
return "#!file:"+source;
}
public JsoArray<String> getDependencies() {
return deps;
}
public JsoArray<String> getSources() {
return srcs;
}
}
| 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/collide/gwtc/ui/GwtStatusListener.java | client/src/main/java/collide/gwtc/ui/GwtStatusListener.java | package collide.gwtc.ui;
import com.google.collide.dto.CompileResponse;
import com.google.gwt.core.ext.TreeLogger.Type;
public interface GwtStatusListener {
void onGwtStatusUpdate(CompileResponse status);
void onLogLevelChange(String id, Type 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/collide/gwtc/ui/GwtCompileNavigationHandler.java | client/src/main/java/collide/gwtc/ui/GwtCompileNavigationHandler.java | package collide.gwtc.ui;
import xapi.collect.X_Collect;
import xapi.collect.api.IntTo;
import xapi.fu.Lazy;
import xapi.gwtc.api.GwtManifest;
import xapi.time.impl.RunOnce;
import xapi.util.api.SuccessHandler;
import collide.gwtc.ui.GwtCompilerShell.Resources;
import collide.gwtc.ui.GwtCompilerShell.View;
import com.google.collide.client.AppContext;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.ui.panel.PanelModel;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.GwtSettings;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.GwtCompileImpl;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.shared.GWT;
import elemental.util.ArrayOfString;
import elemental.util.Collections;
public class GwtCompileNavigationHandler
extends PlaceNavigationHandler<GwtCompilePlace.NavigationEvent>
implements GwtCompilerService
{
private final AppContext context;
private final MultiPanel<? extends PanelModel,?> contentArea;
private final Place currentPlace;
private final GwtManifest model;
private final Lazy<GwtCompilerShell> gwtContainer;
private final Lazy<Resources> gwtResources;
public GwtCompileNavigationHandler(AppContext context, MultiPanel<?,?> masterPanel, Place currentPlace) {
this.context = context;
this.contentArea = masterPanel;
this.currentPlace = currentPlace;
this.model = GWT.create(GwtManifest.class);
//TODO load defaults from local storage
//create our view lazily
this.gwtContainer = Lazy.deferred1(this::initializeView);
this.gwtResources = Lazy.deferred1(()->{
Resources res = GWT.create(Resources.class);
res.gwtCompilerCss().ensureInjected();
res.gwtLogCss().ensureInjected();
res.gwtClasspathCss().ensureInjected();
res.gwtModuleCss().ensureInjected();
return res;
});
}
protected GwtCompilerShell initializeView() {
View view = new GwtCompilerShell.View(context,model,gwtResources.out1());
return GwtCompilerShell.create(view, context);
}
@Override
public void cleanup() {
contentArea.getToolBar().show();
}
double nextRefresh;
RunOnce once = new RunOnce();
@Override
protected void enterPlace(GwtCompilePlace.NavigationEvent navigationEvent) {
boolean run = once.shouldRun(false);
if (run) {
contentArea.setHeaderVisibility(false);
contentArea.clearNavigator();
}else {
model.setModuleName(navigationEvent.getModule());
IntTo<String> all = X_Collect.newList(String.class);
for (String src : navigationEvent.getSourceDirectory().asIterable()) {
all.push(src);
}
model.setSources(all);
all = X_Collect.newList(String.class);
for (String src : navigationEvent.getLibsDirectory().asIterable()) {
all.push(src);
}
model.setDependencies(all);
gwtContainer.out1().setPlace(navigationEvent);
return;
}
PanelContent panelContent = gwtContainer.out1();
contentArea.setContent(panelContent,
contentArea.newBuilder().setCollapseIcon(true).setClearNavigator(true).build());
contentArea.getToolBar().hide();
final StatusMessage message =
new StatusMessage(context.getStatusManager(), StatusMessage.MessageType.LOADING,
"Checking Compiler...");
message.fireDelayed(100);
double now = Duration.currentTimeMillis();
if (now > nextRefresh) {
nextRefresh = now + 10000;
context.getFrontendApi().GWT_SETTINGS.request(
new ApiCallback<GwtSettings>() {
@Override
public void onFail(FailureReason reason) {
new StatusMessage(context.getStatusManager(), StatusMessage.MessageType.ERROR,
"Retrieving gwt settings failed in 3 attempts. Try again later.").fire();
}
@Override
public void onMessageReceived(GwtSettings response) {
gwtContainer.out1().showResults(response);
message.expire(1);
}
});
}
}
public Place getCurrentPlace() {
return currentPlace;
}
public GwtCompileImpl getValue() {
return gwtContainer.out1().getValue();
}
@Override
public void compile(GwtRecompile module,
SuccessHandler<CompileResponse> response) {
// We lazy-load the gwt shell, and just defer to it.
gwtContainer.out1().compile(module, response);
}
@Override
public void recompile(String module, SuccessHandler<CompileResponse> response) {
gwtContainer.out1().recompile(module, response);
}
@Override
public void kill(String module) {
gwtContainer.out1().kill(module);
}
@Override
public GwtCompilerShell getShell() {
return gwtContainer.out1();
}
}
| 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/collide/gwtc/resources/GwtcResources.java | client/src/main/java/collide/gwtc/resources/GwtcResources.java | package collide.gwtc.resources;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import collide.client.filetree.FileTreeNodeRenderer;
// A resource bundle is a container for css, images and other media compiled into the app.
public interface GwtcResources extends
ClientBundle, FileTreeNodeRenderer.Resources
{
@Source("Gwtc.css")
GwtcCss panelHeaderCss();
@Source("gwt-logo-small.png")
ImageResource gwt();
@Source("gear.png")
ImageResource gear();
@Source("green-radar-small.gif")
ImageResource radarGreenAnim();
@Source("red-radar-small.gif")
ImageResource radarRedAnim();
@Source("yellow-radar-small.gif")
ImageResource radarYellowAnim();
@Source("green-radar-still.png")
ImageResource radarGreenSmall();
@Source("red-radar-still.png")
ImageResource radarRedSmall();
@Source("yellow-radar-still.png")
ImageResource radarYellowSmall();
@Source("reload.png")
ImageResource reload();
@Source("close.png")
ImageResource close();
} | 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/collide/gwtc/resources/GwtcCss.java | client/src/main/java/collide/gwtc/resources/GwtcCss.java | package collide.gwtc.resources;
import com.google.gwt.resources.client.CssResource;
// An interface of css classnames. These must match .classNames in the .css file.
public interface GwtcCss extends CssResource {
String close();
String gwt();
String gear();
String headerContainer();
String header();
String icons();
String controls();
String reloadIcon();
String radarGreen();
String radarYellow();
String radarRed();
String success();
String warn();
String fail();
String bottomHeader();
String topHeader();
} | 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/collide/plugin/PluginAggregator.java | client/src/main/java/collide/plugin/PluginAggregator.java | package collide.plugin;
import collide.gwtc.ui.GwtClientPlugin;
import collide.plugin.client.terminal.TerminalClientPlugin;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.ClientPluginService;
import xapi.annotation.inject.SingletonDefault;
@SingletonDefault(implFor=ClientPluginService.class)
public class PluginAggregator extends ClientPluginService{
private final ClientPlugin<?>[] plugins;
public PluginAggregator() {
plugins = initPlugins();
}
protected ClientPlugin<?>[] initPlugins() {
return new ClientPlugin[] {
new TerminalClientPlugin()
,new GwtClientPlugin()
};
}
@Override
public ClientPlugin<?>[] plugins() {
return plugins;
}
@Override
public void cleanup() {
super.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/collide/plugin/client/PluginNavigationHandler.java | client/src/main/java/collide/plugin/client/PluginNavigationHandler.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.plugin.client;
import collide.client.util.Elements;
import collide.plugin.client.PluginPlace.NavigationEvent;
import collide.plugin.client.standalone.StandaloneContext;
import com.google.collide.client.history.PlaceConstants;
import com.google.collide.client.history.PlaceNavigationHandler;
import elemental.dom.Element;
/**
* Handler for the selection of a Workspace.
*/
public class PluginNavigationHandler extends PlaceNavigationHandler<PluginPlace.NavigationEvent>{
private StandaloneContext standaloneContext;
private boolean once;
public PluginNavigationHandler(StandaloneContext standaloneContext) {
this.standaloneContext = standaloneContext;
once = true;
}
@Override
protected void enterPlace(NavigationEvent ev) {
if (ev.isShow()) {
standaloneContext.getPanel().show();
Element devMode = Elements.getElementById("developer-mode");
if (devMode != null)
devMode.setAttribute("href", devMode.getAttribute("href").replace("show=true", "show=false"));
} else if (ev.isHide()) {
standaloneContext.getPanel().hide();
Element devMode = Elements.getElementById("developer-mode");
if (devMode != null)
devMode.setAttribute("href", devMode.getAttribute("href").replace("show=false", "show=true"));
}
if (once) {
once = false;
Elements.getWindow().getLocation().setHash("/"+PlaceConstants.WORKSPACE_PLACE_NAME);
}
}
}
| 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/collide/plugin/client/PluginPlace.java | client/src/main/java/collide/plugin/client/PluginPlace.java | package collide.plugin.client;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
public class PluginPlace extends Place{
public class NavigationEvent extends PlaceNavigationEvent<PluginPlace> {
public static final String SHOW_HIDE = "show";
private Boolean show;
protected NavigationEvent(Boolean show) {
super(PluginPlace.this);
this.show = show;
}
public boolean isShow() {
return Boolean.TRUE.equals(show);
}
public boolean isHide() {
return Boolean.FALSE.equals(show);
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> state = JsoStringMap.create();
if (show != null) {
state.put(SHOW_HIDE, Boolean.toString(show));
}
return state;
}
}
public static final PluginPlace PLACE = new PluginPlace();
protected PluginPlace() {
super("collide");
}
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(JsonStringMap<String> decodedState) {
Boolean show = null;
if (decodedState.containsKey(NavigationEvent.SHOW_HIDE))
show = Boolean.parseBoolean(decodedState.get(NavigationEvent.SHOW_HIDE));
return new NavigationEvent(show);
}
}
| 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/collide/plugin/client/launcher/LauncherService.java | client/src/main/java/collide/plugin/client/launcher/LauncherService.java | package collide.plugin.client.launcher;
import xapi.util.api.RemovalHandler;
public interface LauncherService {
RemovalHandler openInIframe(String id, String url);
void openInNewWindow(String id, String 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/collide/plugin/client/inspector/ElementInspector.java | client/src/main/java/collide/plugin/client/inspector/ElementInspector.java | package collide.plugin.client.inspector;
import com.google.collide.json.client.JsoArray;
import elemental.client.Browser;
import elemental.dom.Attr;
import elemental.dom.Node;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.js.dom.JsNode;
import elemental.js.events.JsMouseEvent;
import xapi.inject.impl.SingletonProvider;
import xapi.util.api.ReceivesValue;
import xapi.util.api.RemovalHandler;
import com.google.gwt.core.client.JavaScriptObject;
public class ElementInspector extends JavaScriptObject{
protected ElementInspector() {}
private static SingletonProvider<ElementInspector> singleton =
new SingletonProvider<ElementInspector>(){
protected ElementInspector initialValue() {
Browser.getWindow().addEventListener("click", new EventListener() {
@Override
public void handleEvent(Event evt) {
JsNode el = ((JsMouseEvent)evt).getToElement();
ElementInspector inspector = ElementInspector.get();
JsoArray<Node> withData = JsoArray.create();
while (el != null && !"html".equalsIgnoreCase(el.getNodeName())) {
if (inspector.hasData(el)) {
withData.add(el);
}
el = el.getParentNode();
}
if (withData.size() > 0) {
inspector.fireEvent(withData);
}
}
}, false);
return create();
}
private native ElementInspector create()
/*-{ return {}; }-*/;
};
public static ElementInspector get() {
return singleton.get();
}
public final native void monitorInspection(ReceivesValue<JsoArray<Node>> receiver)
/*-{
if (!this.monitors)
this.monitors = [];
this.monitors.push(receiver);
}-*/;
public final native void fireEvent(JsoArray<Node> withData)
/*-{
if (this.monitors) {
for (var i in this.monitors)
this.monitors[i].@xapi.util.api.ReceivesValue::set(*)(withData);
}
}-*/;
private static int cnt;
private static String uuid() {
StringBuilder b = new StringBuilder("x_");
int id = cnt++;
while(id > 0) {
char digit = (char)(id % 32);
b.append(Character.forDigit(digit, 32));
id >>= 5;
}
return b.toString();
}
private final String getDebugId(Node node) {
Node debug = node.getAttributes().getNamedItem("xapi.debug");
if (debug == null) {
Attr attr = Browser.getDocument().createAttribute("xapi.debug");
attr.setNodeValue(uuid());
node.getAttributes().setNamedItem((debug=attr));
}
return debug.getNodeValue();
}
public final RemovalHandler makeInspectable(Node node, final Object data) {
final String id = getDebugId(node);
remember(id, data);
return new RemovalHandler() {
@Override
public void remove() {
forget(id, data);
}
};
}
public final void forget(Node node, Object data) {
forget(getDebugId(node), data);
}
public final JsoArray<Object> recall(Node node) {
return recall(getDebugId(node));
}
public final boolean hasData(Node node) {
return hasData(getDebugId(node));
}
public final void remember(Node node, Object data) {
remember(getDebugId(node), data);
}
private final native void forget(String nodeId, Object data)
/*-{
var arr = this[nodeId];
if (!arr) return;
if (data == null) {
delete this[nodeId];
return;
}
var i = arr.length;
for (;i --> 0;) {
if (arr[i] == data)
arr.splice(i, 1);
}
if (arr.length == 0)
delete this[nodeId];
}-*/;
private final native boolean hasData(String id)
/*-{
return this[id] && this[id].length > 0;
}-*/;
private final native JsoArray<Object> recall(String id)
/*-{
// Return a mutable array, for convenience
if (!this[id]) this[id] = [];
this [id];
}-*/;
private final native void remember(String id, Object data)
/*-{
if (!this[id]) this[id] = [];
this[id].push(data);
}-*/;
}
| 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/collide/plugin/client/inspector/InspectorPlace.java | client/src/main/java/collide/plugin/client/inspector/InspectorPlace.java | package collide.plugin.client.inspector;
import xapi.fu.Lazy;
import xapi.util.X_String;
import com.google.collide.client.CollideSettings;
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.dto.GwtRecompile;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
import elemental.client.Browser;
import elemental.dom.Node;
import elemental.dom.NodeList;
public class InspectorPlace extends Place{
public class NavigationEvent extends PlaceNavigationEvent<InspectorPlace> {
public static final String MODULE_KEY = "m";
public static final String SRC_KEY = "s";
public static final String DEPS_KEY = "d";
private final String module;
private final JsoArray<String> srcDir;
private final JsoArray<String> depsDir;
private NavigationEvent(GwtRecompile module) {
super(InspectorPlace.this);
this.module = module.getModule();
this.srcDir = JsoArray.from(module.getSources());
this.depsDir = JsoArray.from(module.getDependencies());
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> map = JsoStringMap.create();
map.put(MODULE_KEY, module);
map.put(SRC_KEY, srcDir.join("::"));
map.put(DEPS_KEY, depsDir.join("::"));
return map;
}
public String getModule() {
return module;
}
public JsoArray<String> getSourceDirectory() {
return srcDir;
}
public JsoArray<String> getLibsDirectory() {
return depsDir;
}
}
public static final InspectorPlace PLACE = new InspectorPlace();
private InspectorPlace() {
super(PlaceConstants.INSPECTOR_PLACE_NAME);
}
private final Lazy<String> guessModuleFromHostPage
= new Lazy<>(() -> {
// first try guessing from values embedded in page
String module = CollideSettings.get().getModule();
if (!X_String.isEmptyTrimmed(module))return module.trim();
// else, look for a script tage
NodeList kids = Browser.getDocument().getHead().getChildNodes();
int limit = kids.getLength();
// search backwards, as gwt .nocache.js generally comes after other js imports
while(limit-->0){
Node n = kids.item(limit);
if (n.getNodeName().equalsIgnoreCase("script")){
Node srcAttr = n.getAttributes().getNamedItem("src");
if (srcAttr == null) continue;
String src = srcAttr.getNodeName();
if (src.contains(".nocache.js")){
// we have a winner!
src = src.substring(src.lastIndexOf('/')+1);
// TODO if nocache name is shortened, ask server to find correct gwt.xml.
return src.substring(0, src.length() - 11);
}
}
}
return null;
});
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(
JsonStringMap<String> decodedState) {
String srcDir = decodedState.get(NavigationEvent.SRC_KEY);
if (srcDir == null) {
srcDir = "";
}
String libDir = decodedState.get(NavigationEvent.DEPS_KEY);
if (libDir == null) {
libDir = "";
}
String module = decodedState.get(NavigationEvent.MODULE_KEY);
if (module == null){
//guess our own module source
module = guessModuleFromHostPage.out1();
}
GwtRecompileImpl compile = GwtRecompileImpl.make();
compile.setModule(module);
JsoArray<String>
array = JsoArray.splitString(srcDir, "::");
compile.setSources(array);
array = JsoArray.splitString(libDir, "::");
compile.setDependencies(array);
return new NavigationEvent(compile);
}
/**
* @param compile the gwt module to compile
* @return a new navigation event
*/
public PlaceNavigationEvent<InspectorPlace> createNavigationEvent(GwtRecompile compile) {
return new NavigationEvent(compile);
}
}
| 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/collide/plugin/client/inspector/InspectorPlugin.java | client/src/main/java/collide/plugin/client/inspector/InspectorPlugin.java | package collide.plugin.client.inspector;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.FileAssociation;
import com.google.collide.client.plugin.RunConfiguration;
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 class InspectorPlugin
implements ClientPlugin<InspectorPlace>
{
@Override
public InspectorPlace getPlace() {
return InspectorPlace.PLACE;
}
@Override
public void initializePlugin(
AppContext appContext, MultiPanel<?, ?> masterPanel, Place currentPlace) {
}
@Override
public ImageResource getIcon(Resources res) {
return null;
}
@Override
public void onClicked(ImageButton button) {
// TODO Auto-generated method stub
}
@Override
public FileAssociation getFileAssociation() {
// TODO Auto-generated method stub
return null;
}
@Override
public RunConfiguration getRunConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public PublicService<?>[] getPublicServices() {
// TODO Auto-generated method stub
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/collide/plugin/client/inspector/InspectorService.java | client/src/main/java/collide/plugin/client/inspector/InspectorService.java | package collide.plugin.client.inspector;
import elemental.dom.Element;
public interface InspectorService {
void inspect(Element el);
}
| 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/collide/plugin/client/common/ZIndexService.java | client/src/main/java/collide/plugin/client/common/ZIndexService.java | package collide.plugin.client.common;
import collide.client.util.Elements;
import com.google.common.base.Preconditions;
import elemental.dom.Element;
import elemental.util.ArrayOf;
import elemental.util.Collections;
import xapi.log.X_Log;
import xapi.log.api.LogLevel;
import xapi.util.api.ReceivesValue;
import xapi.util.api.RemovalHandler;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
public class ZIndexService {
private static class ElementalReceiver implements ReceivesValue<Integer> {
private Element element;
public ElementalReceiver(Element e) {
Preconditions.checkNotNull(e,"Do not send null elements to a ZIndexService.");
this.element = e;
}
@Override
public void set(Integer value) {
if (element.getStyle().getZIndex() < value)
element.getStyle().setZIndex(value);
}
}
private ScheduledCommand recalc;
private final ArrayOf<String> zIndexes;
private final ArrayOf<ReceivesValue<Integer>> alwaysOnTop;
public ZIndexService() {
alwaysOnTop = Collections.arrayOf();
zIndexes = Collections.arrayOf();
// always pack 0, so we can ignore it and any elements w/out zindex
zIndexes.push(Elements.getOrSetId(Elements.getBody()));
}
public void setNextZindex(Element e) {
int zindex = e.getStyle().getZIndex();
String id = Elements.getOrSetId(e);
int nextZ = zIndexes.length();// one higher than anything still attached
if (zindex > 0) {
if (nextZ == zindex + 1) {
//already highest. just quit.
return;
}
if (id.equals(zIndexes.get(zindex))) {
// only remove index when owned by this known element; to avoid user-set zindex collision woes
if (nextZ == zindex + 2) {
return;
}
zIndexes.removeByIndex(zindex);
}else {
// run cleanup to remove leaked ids, so we can trace leaked classes
zIndexes.remove(id);
}
}
// returned value is one more than the highest index in our ArrayOf<String id>
zindex = nextZ;
zIndexes.set(zindex, id);// store the id, not the element
e.getStyle().setZIndex(zindex);
// Log.info(getClass(), zIndexes, id+": "+zindex);
// applies zindex+1 to anything marked AlwaysOnTop
applyAlwaysOnTop();
}
protected void applyAlwaysOnTop() {
if (recalc == null) {
recalc = new ScheduledCommand() {
@Override
public void execute() {
recalc = null;
int zindex = zIndexes.length()+1;
for (int i = alwaysOnTop.length(); i-- > 0;) {
alwaysOnTop.get(i).set(zindex);
}
}
};
Scheduler.get().scheduleFinally(recalc);
}
}
public RemovalHandler setAlwaysOnTop(Element receiver) {
return setAlwaysOnTop(new ElementalReceiver(receiver));
}
public RemovalHandler setAlwaysOnTop(final ReceivesValue<Integer> receiver) {
assert !alwaysOnTop.contains(receiver) : "You are adding the same receiver to always on top more than once;"
+ " you DO have the returned handler on tap to do a null check, don't you? ;)";
alwaysOnTop.push(receiver);
applyAlwaysOnTop();
return new RemovalHandler() {
@Override
public void remove() {
alwaysOnTop.remove(receiver);
}
};
}
public void destroy() {
if (X_Log.loggable(LogLevel.TRACE)) {
// detect leaks:
for (int i = 1; // starting at one because we pad 0 with document.body
i < zIndexes.length(); i++) {
String id = zIndexes.get(i);
if (id == null) continue;
Element attached = Elements.getDocument().getElementById(id);
if (attached == null) {
X_Log.trace("Leaked zindex assignment; possible memory leak in detached element w/ id " + id);
} else {
X_Log.trace("Leaked zindex assignment; possible memory leak in element w/ id " + id, attached);
}
}
for (int i = 0; i < alwaysOnTop.length(); i++) {
ReceivesValue<Integer> listener = alwaysOnTop.get(i);
if (listener != null)
X_Log.trace("Leaked zindex always on top; possible memory leak in receiver: ", listener.getClass(),
listener);
}
}
zIndexes.setLength(0);
alwaysOnTop.setLength(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/collide/plugin/client/terminal/TerminalService.java | client/src/main/java/collide/plugin/client/terminal/TerminalService.java | package collide.plugin.client.terminal;
import com.google.collide.dto.LogMessage;
public interface TerminalService {
void setHeader(String module, TerminalLogHeader header);
void addLog(LogMessage log, TerminalLogHeader header);
}
| 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/collide/plugin/client/terminal/TerminalClientPlugin.java | client/src/main/java/collide/plugin/client/terminal/TerminalClientPlugin.java | package collide.plugin.client.terminal;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.FileAssociation;
import com.google.collide.client.plugin.RunConfiguration;
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.dto.LogMessage;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicService.DefaultServiceProvider;
import com.google.gwt.resources.client.ImageResource;
public class TerminalClientPlugin implements ClientPlugin<TerminalPlace>, TerminalService{
private Place parentPlace;
private TerminalNavigationHandler handler;
@Override
public TerminalPlace getPlace() {
return TerminalPlace.PLACE;
}
@Override
public void initializePlugin(
AppContext appContext, MultiPanel<?,?> masterPanel, Place currentPlace) {
this.parentPlace = currentPlace;
handler = new TerminalNavigationHandler(appContext, masterPanel, currentPlace);
parentPlace.registerChildHandler(getPlace(), handler);
}
@Override
public ImageResource getIcon(Resources res) {
return res.terminalIcon();
}
@Override
public void onClicked(ImageButton button) {
//show terminal
PlaceNavigationEvent<?> action = TerminalPlace.PLACE.createNavigationEvent();
parentPlace.fireChildPlaceNavigation(action);
}
@Override
public FileAssociation getFileAssociation() {
return new FileAssociation.FileAssociationSuffix(".*[.]sh"){
};
}
@Override
public RunConfiguration getRunConfig() {
return null;
}
@Override
public void addLog(LogMessage log, TerminalLogHeader header) {
handler.addLog(log, header);
}
@Override
public void setHeader(String module, TerminalLogHeader header) {
handler.setHeader(module, header);
}
@Override
public PublicService<?>[] getPublicServices() {
return new PublicService[] {
new DefaultServiceProvider<TerminalService>(TerminalService.class, this)
};
}
public void setRename(String from, String to) {
handler.setRename(from, to);
}
}
| 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/collide/plugin/client/terminal/TerminalNavigationHandler.java | client/src/main/java/collide/plugin/client/terminal/TerminalNavigationHandler.java | package collide.plugin.client.terminal;
import xapi.collect.impl.AbstractInitMap;
import xapi.collect.impl.AbstractMultiInitMap;
import xapi.fu.In1Out1;
import xapi.inject.impl.SingletonProvider;
import xapi.util.X_String;
import xapi.util.api.ConvertsValue;
import xapi.util.api.HasId;
import xapi.util.api.Pair;
import collide.client.util.Elements;
import collide.demo.view.TabPanel;
import collide.demo.view.TabPanel.TabView;
import collide.demo.view.TabPanelResources;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.ui.panel.PanelModel;
import com.google.collide.dto.LogMessage;
import com.google.collide.mvp.View;
import collide.plugin.client.terminal.TerminalLogView.Resources;
import collide.plugin.client.terminal.TerminalLogView.ViewEvents;
import com.google.gwt.core.shared.GWT;
import elemental.dom.Element;
import elemental.html.DivElement;
@SuppressWarnings("ALL")
public class TerminalNavigationHandler extends
PlaceNavigationHandler<TerminalPlace.NavigationEvent>
implements In1Out1<Pair<String, TerminalLogHeader>, TerminalLogView> {
private final AppContext context;
private final MultiPanel<? extends PanelModel,?> contentArea;
private final Place parentPlace;
private final SingletonProvider<Resources> terminalResources;
private final AbstractMultiInitMap<String, TerminalLogView, TerminalLogHeader> views;
private final TabPanel logTabs;
public TerminalNavigationHandler(AppContext context, final MultiPanel<?,?> masterPanel, Place parentPlace) {
this.context = context;
logTabs = TabPanel.create(getTabPanelResources());
masterPanel.setContent(logTabs);
this.contentArea = masterPanel;
this.parentPlace = parentPlace;
views = new AbstractMultiInitMap<String, TerminalLogView, TerminalLogHeader>(AbstractInitMap.PASS_THRU, this);
//create and inject our resources lazily
this.terminalResources = new SingletonProvider<Resources>(){
@Override
protected Resources initialValue() {
Resources res = GWT.create(Resources.class);
res.terminalLogCss().ensureInjected();
return res;
};
};
}
protected TabPanelResources getTabPanelResources() {
return TabPanel.DEFAULT_RESOURCES.get();
}
protected TerminalLogView initializeView(String from, MultiPanel<?,?> masterPanel) {
final TabView[] tab = new TabView[1];
final TerminalLogView[] view = new TerminalLogView[1];
view[0] = TerminalLogView.create(from, terminalResources.get(), new ViewEvents() {
@Override
public void onLogsFlushed() {
if (logTabs.unhide(tab[0])) {
view[0].clear();
}
}
});
tab[0] = logTabs.addContent(view[0].getView());
logTabs.select(tab[0]);
return view[0];
}
@Override
public void cleanup() {
contentArea.getToolBar().show();
}
@Override
protected void enterPlace(TerminalPlace.NavigationEvent navigationEvent) {
contentArea.clearNavigator();
contentArea.setHeaderVisibility(false);
String module = navigationEvent.getModule();
PanelContent panelContent = views.get(module, null);
contentArea.setContent(panelContent,
contentArea.newBuilder().setCollapseIcon(true).setClearNavigator(true).build());
contentArea.getToolBar().hide();
}
public Place getCurrentPlace() {
return parentPlace;
}
public void addLog(LogMessage log, TerminalLogHeader header) {
String id = X_String.firstNotEmpty(log.getModule(),"global");
views.get(id, header).addLog(log);
}
@Override
public TerminalLogView io(Pair<String, TerminalLogHeader> from) {
TerminalLogView view = initializeView(from.get0(), contentArea);
view.setHeader(from.get1());
return view;
}
public void setHeader(String module, TerminalLogHeader header) {
views.get(module, header).setHeader(header);
}
public void setRename(String from, String to) {
TerminalLogView is = views.getValue(from);
views.setValue(to, is);
}
}
| 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/collide/plugin/client/terminal/TerminalPlace.java | client/src/main/java/collide/plugin/client/terminal/TerminalPlace.java | package collide.plugin.client.terminal;
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.dto.GwtRecompile;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
import elemental.client.Browser;
import elemental.dom.Node;
import elemental.dom.NodeList;
import xapi.fu.Lazy;
public class TerminalPlace extends Place{
public class NavigationEvent extends PlaceNavigationEvent<TerminalPlace> {
public static final String MODULE_KEY = "m";
public static final String SRC_KEY = "s";
public static final String DEPS_KEY = "d";
private final String module;
private final JsoArray<String> srcDir;
private final JsoArray<String> depsDir;
private NavigationEvent(GwtRecompile module) {
super(TerminalPlace.this);
this.module = module.getModule();
this.srcDir = JsoArray.from(module.getSources());
this.depsDir = JsoArray.from(module.getDependencies());
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> map = JsoStringMap.create();
map.put(MODULE_KEY, module);
map.put(SRC_KEY, srcDir.join("::"));
map.put(DEPS_KEY, depsDir.join("::"));
return map;
}
public String getModule() {
return module;
}
public JsoArray<String> getSourceDirectory() {
return srcDir;
}
public JsoArray<String> getLibsDirectory() {
return depsDir;
}
}
public static final TerminalPlace PLACE = new TerminalPlace();
private TerminalPlace() {
super(PlaceConstants.TERMINAL_PLACE_NAME);
}
private final Lazy<String> guessModuleFromHostPage
= new Lazy<>(() -> {
//first try guessing from head
NodeList kids = Browser.getDocument().getHead().getChildNodes();
int limit = kids.getLength();
//search backwards, as gwt .nocache.js generally comes after other js imports
while(limit-->0){
Node n = kids.item(limit);
if (n.getNodeName().equalsIgnoreCase("script")){
Node srcAttr = n.getAttributes().getNamedItem("src");
if (srcAttr == null) continue;
String src = srcAttr.getNodeName();
if (src.contains(".nocache.js")){
//we have a winner!
src = src.substring(src.lastIndexOf('/')+1);
return src.substring(0, src.length() - 11);
}
}
}
return null;
});
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(
JsonStringMap<String> decodedState) {
String srcDir = decodedState.get(NavigationEvent.SRC_KEY);
if (srcDir == null) {
srcDir = "";
}
String libDir = decodedState.get(NavigationEvent.DEPS_KEY);
if (libDir == null) {
libDir = "";
}
String module = decodedState.get(NavigationEvent.MODULE_KEY);
if (module == null){
//guess our own module source
module = guessModuleFromHostPage.out1();
}
GwtRecompileImpl compile = GwtRecompileImpl.make();
compile.setModule(module);
JsoArray<String>
array = JsoArray.splitString(srcDir, "::");
compile.setSources(array);
array = JsoArray.splitString(libDir, "::");
compile.setDependencies(array);
return new NavigationEvent(compile);
}
/**
* @param compile the gwt module to compile
* @return a new navigation event
*/
public PlaceNavigationEvent<TerminalPlace> createNavigationEvent(GwtRecompile compile) {
return new NavigationEvent(compile);
}
}
| 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/collide/plugin/client/terminal/TerminalLogHeader.java | client/src/main/java/collide/plugin/client/terminal/TerminalLogHeader.java | package collide.plugin.client.terminal;
import com.google.collide.dto.LogMessage;
import elemental.dom.Element;
/**
* A simple interface to give to a {@link TerminalService} as a header element.
*
* @author "James X. Nelson (james@wetheinter.net)"
*
*/
public interface TerminalLogHeader {
String getName();
void viewLog(LogMessage log);
Element getElement();
}
| 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/collide/plugin/client/terminal/TerminalLogView.java | client/src/main/java/collide/plugin/client/terminal/TerminalLogView.java | package collide.plugin.client.terminal;
import xapi.util.api.HasId;
import collide.client.common.CommonResources;
import collide.client.util.Elements;
import com.google.collide.client.code.PluginContent;
import com.google.collide.client.util.ResizeBounds;
import com.google.collide.client.util.ResizeBounds.BoundsBuilder;
import com.google.collide.dto.LogMessage;
import com.google.collide.json.client.JsoArray;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import elemental.dom.Element;
public class TerminalLogView extends UiComponent<TerminalLogView.View> implements PluginContent {
int scrollHeight = 0;
private final BoundsBuilder bounds = ResizeBounds.withMaxSize(500, Integer.MAX_VALUE).minSize(350, 300);
public TerminalLogView(View view, ViewEvents events) {
super();
setView(view);
view.setDelegate(events);
}
public static TerminalLogView create(String id, Resources res, ViewEvents delegate){
View view = new View(id, res);
TerminalLogView log = new TerminalLogView(view, delegate);
return log;
}
public interface Css extends CssResource {
String bottomPlaceHolder();
String logAll();
String logDebug();
String logSpam();
String logTrace();
String logInfo();
String logWarning();
String logError();
String logContainer();
String logHeader();
String logBody();
String logPad();
String cliContainer();
}
public interface Resources extends
ClientBundle
,CommonResources.BaseResources
{
@Source("TerminalLogView.css")
Css terminalLogCss();
}
public static interface ViewEvents{
void onLogsFlushed();
}
public static class View extends CompositeView<ViewEvents> implements HasId {
@UiTemplate("TerminalLogView.ui.xml")
interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, View> {
}
static MyBinder binder = GWT.create(MyBinder.class);
@UiField
DivElement root;
@UiField(provided = true)
Resources res;
@UiField
DivElement logHeader;
@UiField
DivElement logBody;
@UiField
DivElement background;
private final String id;
public View(String id, Resources res) {
this.res = res;
this.id = id;
setElement(Elements.asJsElement(
binder.createAndBindUi(this)));
logBody.setInnerHTML("Logger ready");
}
public void setHeader(TerminalLogHeader el) {
logHeader.setInnerHTML("");
Elements.asJsElement(logHeader).appendChild(el.getElement());
}
@Override
public String getId() {
return id;
}
}
public void addLog(LogMessage log) {
if (header != null ) {
header.viewLog(log);
}
Css css = getView().res.terminalLogCss();
String clsName = css.logInfo();
switch(log.getLogLevel()){
case ERROR:
clsName = css.logError();
break;
case WARN:
clsName = css.logWarning();
break;
case INFO:
clsName = css.logInfo();
break;
case TRACE:
clsName = css.logTrace();
break;
case DEBUG:
clsName = css.logDebug();
break;
case SPAM:
clsName = css.logSpam();
break;
case ALL:
clsName = css.logAll();
break;
}
elemental.html.PreElement el = Elements.createPreElement(clsName);
el.setInnerText(log.getMessage());
//TODO: use a page list-view so we can avoid painting 6,000,000 elements at once
enqueue(el);
}
private final JsoArray<elemental.dom.Element> cached = JsoArray.create();
private final JsoArray<elemental.dom.Element> visible = JsoArray.create();
private final JsoArray<elemental.dom.Element> pending = JsoArray.create();
private ScheduledCommand cmd;
private Type logLevel = Type.INFO;
TerminalLogHeader header;
private void enqueue(elemental.dom.Element el) {
pending.add(el);
if (cmd == null){
Scheduler.get().scheduleDeferred(
(cmd = new ScheduledCommand() {
@Override
public void execute() {
cmd = null;
if (getView().getDelegate() != null) {
getView().getDelegate().onLogsFlushed();
}
scrollDelta = 0;
visible.addAll(pending);
int size = visible.size();
elemental.html.DivElement into = (elemental.html.DivElement)getView().logBody;
if (size>700){
//TODO: put in paging / see more link instead of truncation
elemental.html.DivElement pager = Elements.createDivElement();
pager.setInnerHTML("...Logs truncated, (" +cached.size()+") elements hidden...");
visible.unshift(pager);
cached.addAll(visible.splice(0, size-500));
if (cached.size() > 10000) {
cached.setLength(10000);
}
into.setInnerHTML("");
for (elemental.dom.Element el : visible.asIterable()){
into.appendChild(el);
scrollDelta += el.getClientHeight();
}
} else {
for (elemental.dom.Element el : pending.asIterable()){
into.appendChild(el);
scrollDelta += el.getClientHeight();
}
}
pending.clear();
updateScrolling();
}
})
);
}
}
int scrollDelta;
private void updateScrolling() {
elemental.html.DivElement body = (elemental.html.DivElement)getView().root;
int sH = body.getScrollHeight(), sT = body.getScrollTop(), h = body.getClientHeight();
if (scrollHeight - h - scrollDelta <= sT){//user was scrolled to the bottom last update,
body.setScrollTop(sH);//force back to bottom
}
scrollHeight = sH;
}
@Override
public Element getContentElement() {
return getView().getElement();
}
@Override
public void onContentDisplayed() {
}
@Override
public void onContentDestroyed() {
}
@Override
public String getNamespace() {
return "Terminal";
}
@Override
public BoundsBuilder getBounds() {
return bounds;
}
public void setHeader(TerminalLogHeader el) {
header = el;
getView().setHeader(el);
}
public void clear() {
cached.clear();
visible.clear();
pending.clear();
getView().logBody.setInnerHTML("");
}
}
| 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/collide/plugin/client/standalone/StandaloneCodeBundle.java | client/src/main/java/collide/plugin/client/standalone/StandaloneCodeBundle.java | package collide.plugin.client.standalone;
import collide.client.editor.EditorToolbar;
import collide.client.editor.MarkupToolbar;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.*;
import com.google.collide.client.code.CodePerspective.View;
import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.history.Place;
import com.google.collide.client.search.FileNameSearch;
import com.google.collide.client.workspace.WorkspaceShell;
public class StandaloneCodeBundle extends CodePanelBundle {
public StandaloneCodeBundle(AppContext appContext,
WorkspaceShell shell,
FileTreeController<?> fileTreeController,
FileTreeModel fileTreeModel,
FileNameSearch searchIndex,
DocumentManager documentManager,
ParticipantModel participantModel,
IncomingDocOpDemultiplexer docOpReceiver,
Place place) {
super(appContext, shell, fileTreeController, fileTreeModel,
searchIndex, documentManager, participantModel, docOpReceiver, place);
}
@Override
protected void attachShellToDom(final WorkspaceShell shell, final View codePerspectiveView) {
Elements.replaceContents(StandaloneConstants.WORKSPACE_PANEL, codePerspectiveView.detach());
shell.setPerspective(codePerspectiveView.getElement());
}
@Override
protected EditableContentArea initContentArea(View codePerspectiveView,
AppContext appContext, EditorBundle editorBundle, FileTreeSection fileTreeSection) {
EditableContentArea.View view = codePerspectiveView.getContentView();
final EditorToolbar toolBar = new DefaultEditorToolBar(view.getEditorToolBarView(), FileSelectedPlace.PLACE, appContext, editorBundle);
// Hook presenter in the editor bundle to the view in the header
editorBundle.getBreadcrumbs().setView(view.getBreadcrumbsView());
return new EditableContentArea(view, toolBar, fileTreeSection.getFileTreeUiController());
}
}
| 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/collide/plugin/client/standalone/StandaloneContext.java | client/src/main/java/collide/plugin/client/standalone/StandaloneContext.java | package collide.plugin.client.standalone;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.CollideSettings;
public class StandaloneContext {
static StandaloneContext create(AppContext ctx) {
return new StandaloneContext(ctx);
}
private final StandaloneWorkspace panel;
private final AppContext ctx;
public StandaloneContext(AppContext ctx) {
this.ctx = ctx;
this.panel = new StandaloneWorkspace(ctx.getResources(), Elements.getBody(), CollideSettings.get());
}
/**
* @return the panel
*/
public StandaloneWorkspace getPanel() {
return panel;
}
public AppContext getAppContext() {
return ctx;
}
}
| 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/collide/plugin/client/standalone/StandalonePlugin.java | client/src/main/java/collide/plugin/client/standalone/StandalonePlugin.java | package collide.plugin.client.standalone;
import collide.client.util.Elements;
import collide.plugin.client.PluginNavigationHandler;
import collide.plugin.client.PluginPlace;
import com.google.collide.client.AppContext;
import com.google.collide.client.CollideBootstrap;
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.clientlibs.navigation.NavigationToken;
import com.google.collide.json.shared.JsonArray;
import xapi.util.api.SuccessHandler;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
public class StandalonePlugin implements EntryPoint {
@Override
public void onModuleLoad() {
CollideBootstrap.start(new SuccessHandler<AppContext>() {
@Override
public void onSuccess(AppContext appContext) {
// Elements.replaceContents(AppContext.GWT_ROOT, panel.getView().getElement());
StandaloneContext ctx = StandaloneContext.create(appContext);
WorkspacePlace.PLACE.setIsStrict(false);
StandaloneNavigationHandler handler = new StandaloneNavigationHandler(ctx);
RootPlace.PLACE.registerChildHandler(WorkspacePlace.PLACE, handler,
false);
PluginNavigationHandler api = new PluginNavigationHandler(ctx);
RootPlace.PLACE.registerChildHandler(PluginPlace.PLACE, api, true);
// Back/forward buttons or manual manipulation of the hash.
HistoryUtils.addValueChangeListener(new ValueChangeListener() {
@Override
public void onValueChanged(String historyString) {
replayHistory(HistoryUtils.parseHistoryString(historyString));
}
});
// Status Presenter
StatusPresenter statusPresenter = StatusPresenter.create(appContext.getResources());
Elements.getBody().appendChild(statusPresenter.getView().getElement());
appContext.getStatusManager().setHandler(statusPresenter);
Scheduler.get().scheduleFinally(new ScheduledCommand() {
@Override
public void execute() {
// Replay History
replayHistory(HistoryUtils.parseHistoryString());
}
});
}
});
}
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/collide/plugin/client/standalone/StandaloneWorkspace.java | client/src/main/java/collide/plugin/client/standalone/StandaloneWorkspace.java | package collide.plugin.client.standalone;
import collide.client.util.Elements;
import collide.plugin.client.common.ZIndexService;
import com.google.collide.client.CollideSettings;
import com.google.collide.client.Resources;
import com.google.collide.client.code.FileContent;
import com.google.collide.client.code.NoFileSelectedPanel;
import com.google.collide.client.code.PluginContent;
import com.google.collide.client.history.HistoryUtils;
import com.google.collide.client.history.PlaceConstants;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.ui.menu.PositionController.PositionerBuilder;
import com.google.collide.client.ui.panel.AbstractPanelPositioner;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.ui.panel.Panel;
import com.google.collide.client.ui.panel.Panel.Interpolator;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.ui.panel.PanelModel;
import com.google.collide.client.util.ResizeBounds;
import com.google.collide.client.util.ResizeBounds.BoundsBuilder;
import com.google.collide.client.util.ResizeController;
import com.google.collide.client.util.ResizeController.ElementInfo;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.client.JsoArray;
import com.google.collide.mvp.ShowableUiComponent;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.DivElement;
import elemental.util.ArrayOf;
import elemental.util.Collections;
import xapi.log.X_Log;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
public class StandaloneWorkspace extends MultiPanel<StandaloneWorkspace.Model,StandaloneWorkspace.View> {
private static class Namespace {
static final String workspace = "Workspace";
static final String fileNav = "Explorer";
static final String header = "Header";
}
public static class Model extends PanelModel {
private Model(boolean showHistory, boolean showClose, boolean showSettings, boolean showCollapse,
boolean clearNavigator) {
super(showHistory, showClose, showSettings, showCollapse, clearNavigator);
}
public static Builder newStandaloneBuilder() {
return new Builder();
}
public static class Builder extends PanelModel.Builder<Model> {
@Override
public Model build() {
return new Model(historyIcon, closeIcon, settingsIcon, collapseIcon, clearNavigator);
}
}
}
public static class View extends MultiPanel.View<Model> {
private final Element root, dummy;
private final Panel<?,?> headerPanel;
private final Panel<?,?> fileNavPanel;
private final Panel<?,?> workspacePanel;
// private final MapFromStringTo<Panel<?,?>> panels;
private final AbstractPanelPositioner positioner;
private final Resources resources;
private final ZIndexService zIndexer;
private boolean hidden = false;
public View(Resources res, Element root, CollideSettings settings) {
super(root, true);
// panels = Collections.mapFromStringTo();
positioner = new AbstractPanelPositioner();
this.resources = res;
this.root = root;
this.zIndexer = new ZIndexService();
dummy = Elements.createDivElement(res.panelCss().hidden());
root.appendChild(dummy);
final DivElement header = Elements.createDivElement();
final DivElement files = Elements.createDivElement();
final DivElement workspace = Elements.createDivElement();
header.setId(StandaloneConstants.HEADER_PANEL);
files.setId(StandaloneConstants.FILES_PANEL);
workspace.setId(StandaloneConstants.WORKSPACE_PANEL);
setElement(root);
Interpolator inter = new Interpolator() {
@Override
public float interpolate(float value) {
return value - 20;
}
};
// add a full size 100%x100% sizing panel to root @ z-index -1.
// this is so we don't force users to have a bounds-limited body element
final DivElement caliper = Elements.createDivElement(res.panelCss().caliper());
root.appendChild(caliper);
// set a window-resizing method
EventListener listener = new EventListener() {
@Override
public void handleEvent(Event evt) {
caliper.getStyle().setWidth(Elements.getWindow().getInnerWidth(), "px");
caliper.getStyle().setHeight(Elements.getWindow().getInnerHeight(), "px");
// TODO also fire a redraw event for all attached panels
positioner.recalculate();
}
};
Elements.getWindow().setOnresize(listener);
fileNavPanel = getOrMakePanel(Namespace.fileNav, new PanelContent.AbstractContent(files),
ResizeBounds
.withMinSize(275, 300)
.maxSize(375, 0)
.maxHeight(caliper, inter)
);
// fileNavPanel.setPosition(-55, 5);
// This is to workaround the main collide entry point's default css
fileNavPanel.getChildAnchor().getParentElement().getStyle().setTop(-28, "px");
fileNavPanel.getView().getElement().getStyle().setHeight(Elements.getWindow().getInnerHeight()-20, "px");
fileNavPanel.setHeaderContent(Namespace.fileNav);
workspacePanel = getOrMakePanel(Namespace.workspace, new PanelContent.AbstractContent(workspace),
ResizeBounds.withMinSize(450, 300)
.maxSize(900, -1)
.maxHeight(caliper, inter));
workspacePanel.setClosable(true);
// workspacePanel.setPosition(405, 5);
workspacePanel.setHeaderContent(Namespace.workspace);
hideWorkspace();
headerPanel = getOrMakePanel(Namespace.header, new PanelContent.AbstractContent(header),
ResizeBounds.withMaxSize(200, 59).minSize(150, 59));
headerPanel.setAllHeader();
headerPanel.setPosition(-5, 0);
workspacePanel.getView().getElement().getStyle().setWidth("100%");
workspacePanel.getView().getElement().getStyle().setHeight("100%");
zIndexer.setAlwaysOnTop(headerPanel.getView().getElement());
// restore state...
zIndexer.setNextZindex(workspacePanel.getView().getElement());
zIndexer.setNextZindex(fileNavPanel.getView().getElement());
// resize immediately
listener.handleEvent(null);
if (settings.isHidden()) {
hide();
}
}
@Override
public Element getContentElement() {
return root;
}
@Override
public Element getHeaderElement() {
return headerPanel.getView().getElement();
}
protected Panel<?,?> getOrMakePanel(String namespace, final PanelContent panelContent, BoundsBuilder bounds) {
final Panel<?,?> panel;
if (positioner.hasPanel(namespace)) {
panel = positioner.getPanel(namespace).panel;
if (hidden || panelContent instanceof PanelContent.HiddenContent) {
panel.hide();
}
if (panel.getView().getElement().getParentElement() == dummy) {
root.appendChild(panel.getView().getElement());
}
}
else {
panel = Panel.create(namespace, resources, bounds.build());
// only top-level panels are fixed.
panel.getView().getElement().getStyle().setPosition("fixed");
if (namespace.equals(Namespace.workspace)) {
panel.hide();
}
if (!namespace.equals(Namespace.header))
positioner.addPanel(panel);
if (hidden || shouldHide(panelContent.getContentElement().getId())) {
panel.hide();
dummy.appendChild(panel.getView().getElement());
} else {
root.appendChild(panel.getView().getElement());
}
attachResizeHandler(panel, namespace, panelContent);
// Position this panel in a sane manner
}
panel.setContent(panelContent);
panel.setHeaderContent(namespace);
zIndexer.setNextZindex(panelContent.getContentElement());
return panel;
}
private void attachResizeHandler(final Panel<?,?> panel, final String namespace, final PanelContent panelContent) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
panel.addResizeHandler(new ResizeController.ResizeEventHandler() {
@Override
public void startDragging(ElementInfo ... elementInfos) {
zIndexer.setNextZindex(panel.getView().getElement());
}
@Override
public void whileDragging(float deltaW, float deltaH, float deltaX, float deltaY) {
// Notify the positioner of resizes.
if (Math.abs(deltaW)>0.001 || Math.abs(deltaX) > 0.001) {
positioner.adjustHorizontal(panel, deltaX, deltaW);
}
if (Math.abs(deltaH)>0.001 || Math.abs(deltaY) > 0.001) {
positioner.adjustVertical(panel, deltaY, deltaH);
}
// TODO periodically run a z-index check and adapt as needed
}
@Override
public void doneDragging(float deltaX, float deltaY, float origX, float origY) {
// if this panel currently covers another one completely, we should raise the concealed panels
detectCollisions(panel, namespace, panelContent);
positioner.recalculate();
};
});
}
});
}
protected void detectCollisions(Panel<?,?> panel, String namespace, PanelContent panelContent) {
JsoArray<String> keys = positioner.keys();
ArrayOf<Panel<?,?>> collisions = Collections.arrayOf();
for (int i = keys.size(); i-->0;) {//count backwards to maintain order when we re-index
String key = keys.get(i);
if (!key.equals(namespace)) {
Panel<?,?> test = positioner.getPanel(key).panel;
if (covers(panel, test)) collisions.push(test);
}
}
for (int i = 0; i < collisions.length(); i++) {
zIndexer.setNextZindex(collisions.get(i).getView().getElement());
}
}
private void hide() {
hidden = true;
//also do the mapped panels.
JsoArray<String> keys = positioner.keys();
while(!keys.isEmpty()){
positioner.getPanel(keys.pop()).panel.hide();
}
}
private void show() {
hidden = false;
//also do the mapped panels.
JsoArray<String> keys = positioner.keys();
PositionerBuilder builder = new PositionController.PositionerBuilder();
while(!keys.isEmpty()) {
Panel<?,?> panel = positioner.getPanel(keys.pop()).panel;
panel.show();
}
}
private boolean covers(Panel<?,?> moved, Panel<?,?> covered) {
Element elMoved = moved.getView().getElement();
Element elCovered = covered.getView().getElement();
// first and easiest, if elCovered is a higher zIndex, do nothing.
if (elCovered.getStyle().getZIndex() - elMoved.getStyle().getZIndex() > 0) {
return false;
}
// now compute overlap. We can be lazy and use offsets because we control the panel wrappers.
if (elMoved.getOffsetLeft() > elCovered.getOffsetLeft() + 20) {// TODO replace hardcoded 10 w/ snap
// values
return false;
}
if (elMoved.getOffsetTop() > elCovered.getOffsetTop() + 20) {
return false;
}
if (elMoved.getOffsetLeft() + elMoved.getOffsetWidth() < elCovered.getOffsetLeft() +
elCovered.getOffsetWidth() - 20) {
return false;
}
if (elMoved.getOffsetTop() + elMoved.getOffsetHeight() < elCovered.getOffsetTop() +
elCovered.getOffsetHeight() - 20) {
return false;
}
return true;
}
public void hideWorkspace() {
workspacePanel.hide();
positioner.removePanel(workspacePanel);
}
public void showWorkspace() {
if (workspacePanel.getView().getElement().getParentElement() == dummy) {
root.appendChild(workspacePanel.getView().getElement());
}
workspacePanel.show();
// positionPanel(workspacePanel);
}
}
public interface ViewController {
}
@Override
public void setContent(PanelContent panelContent, PanelModel settings) {
if (currentContent == panelContent) {
return;
}
if (panelContent == null) {
//TODO minimize
} else {
if (panelContent instanceof FileContent) {
// When opening file content, we aim to use a new window,
// if there is room for it. Otherwise, we minimize the first of:
// The oldest FileContent currently open
// The oldest minimizable PanelContent of any kind
// The file navigator (the default root panel.)
if (currentContent instanceof FileContent) {
// There's already one file open.
currentContent.onContentDestroyed();
currentContent.getContentElement().removeFromParent();
}
getView().workspacePanel.setContent(panelContent);
currentContent = panelContent;
currentContent.onContentDisplayed();
if (panelContent instanceof NoFileSelectedPanel) {
getView().hideWorkspace();
} else {
getView().showWorkspace();
}
} else if (panelContent instanceof PluginContent) {
PluginContent pluggedin = (PluginContent)panelContent;
// any other command routing through workspace; currently this is where the plugins are living.
// TODO move them to their own Place
BoundsBuilder bounds = pluggedin.getBounds();
Panel<?,?> asPanel = getView().getOrMakePanel(
pluggedin.getNamespace(), pluggedin, bounds
.maxHeight(getView().root, Interpolator.NO_OP)
);
asPanel.setContent(panelContent);
panelContent.onContentDisplayed();
} else {
Log.warn(getClass(), "Unhandled content of type ", panelContent.getClass(), panelContent);
}
}
setHeaderVisibility(true);
}
public static boolean shouldHide(String id) {
return StandaloneConstants.WORKSPACE_PANEL.equals(id) &&
!HistoryUtils.getHistoryString().contains(PlaceConstants.WORKSPACE_PLACE_NAME);
}
@Override
public ShowableUiComponent<? extends com.google.collide.mvp.View<?>> getToolBar() {
return new ShowableUiComponent<View>() {
@Override
public void doHide() {
X_Log.trace("Hiding panel");
}
@Override
public void doShow() {
X_Log.trace("Showing panel");
}
};
}
public StandaloneWorkspace(Resources resources, Element root, CollideSettings standaloneSettings) {
super(new View(resources, root, standaloneSettings));
}
public void hide() {
X_Log.trace("Hiding collide");
getView().hide();
}
public void show() {
X_Log.trace("Showing collide");
getView().show();
}
public void closeEditor() {
getView().hideWorkspace();
}
public void showEditor() {
getView().showWorkspace();
}
@Override
public com.google.collide.client.ui.panel.PanelModel.Builder<Model> newBuilder() {
return new Model.Builder();
}
}
| 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/collide/plugin/client/standalone/StandaloneConstants.java | client/src/main/java/collide/plugin/client/standalone/StandaloneConstants.java | package collide.plugin.client.standalone;
public class StandaloneConstants {
public static String HEADER_PANEL = "header$";
public static String FILES_PANEL = "files$";
public static String WORKSPACE_PANEL = "workspace$";
}
| 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/collide/plugin/client/standalone/StandaloneNavigationHandler.java | client/src/main/java/collide/plugin/client/standalone/StandaloneNavigationHandler.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.plugin.client.standalone;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.Resources;
import com.google.collide.client.code.CodePanelBundle;
import com.google.collide.client.code.ParticipantModel;
import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.search.FileNameSearch;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.workspace.Header;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.client.workspace.WorkspacePlace.NavigationEvent;
import com.google.collide.client.workspace.WorkspacePlaceNavigationHandler;
import com.google.collide.client.workspace.WorkspaceShell;
import com.google.gwt.core.client.Scheduler;
/**
* Handler for the selection of a Workspace.
*/
public class StandaloneNavigationHandler extends WorkspacePlaceNavigationHandler {
private final StandaloneWorkspace panel;
private boolean once;
public StandaloneNavigationHandler(StandaloneContext ctx) {
super(ctx.getAppContext());
this.panel = ctx.getPanel();
once = true;
}
@Override
protected void cleanup() {
// super.cleanup();
}
@Override
protected void attachComponents(WorkspaceShell shell, Header header) {
Elements.replaceContents(StandaloneConstants.HEADER_PANEL, header.getView().getElement());
Elements.replaceContents(StandaloneConstants.FILES_PANEL, shell.getView().getElement());
}
@Override
protected MultiPanel<?,?> createMasterPanel(Resources resources){
return panel;
}
@Override
protected boolean isDetached() {
return true;
}
@Override
protected CodePanelBundle createCodePanelBundle(AppContext appContext, WorkspaceShell shell,
FileTreeController<?> fileTreeController, FileTreeModel fileTreeModel, FileNameSearch searchIndex, DocumentManager documentManager,
ParticipantModel participantModel, IncomingDocOpDemultiplexer docOpRecipient, WorkspacePlace place) {
return new StandaloneCodeBundle(appContext, shell, fileTreeController, fileTreeModel, searchIndex, documentManager,
participantModel, docOpRecipient, place);
}
@Override
protected void enterPlace(final NavigationEvent navigationEvent) {
if (once) {
once = false;
super.enterPlace(navigationEvent);
Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
if (navigationEvent.isActiveLeaf()) {
onNoFileSelected();
}
}
});
}
}
@Override
protected void onNoFileSelected() {
super.onNoFileSelected();
panel.closeEditor();
}
}
| 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/collide/xapi/plugin/XapiPlugin.java | client/src/main/java/collide/xapi/plugin/XapiPlugin.java | package collide.xapi.plugin;
import collide.gwtc.ui.GwtCompileNavigationHandler;
import collide.gwtc.ui.GwtCompilerService;
import collide.xapi.nav.XapiNavigationHandler;
import collide.xapi.nav.XapiPlace;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.FileAssociation;
import com.google.collide.client.plugin.RunConfiguration;
import com.google.collide.client.ui.button.ImageButton;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.Header.Resources;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicServices;
import elemental.dom.Element;
import com.google.gwt.resources.client.ImageResource;
/**
* Created by James X. Nelson (james @wetheinter.net) on 9/26/16.
*/
public class XapiPlugin implements ClientPlugin<XapiPlace>, RunConfiguration {
private final FileAssociation XAPI_FILE_ASSOCIATION;
private final PublicService<?>[] services = new PublicService[1];
private XapiNavigationHandler handler;
private Place place;
private AppContext appContext;
public XapiPlugin() {
XAPI_FILE_ASSOCIATION = f->f.endsWith("xapi");
}
@Override
public String getId() {
return "XAPI";
}
@Override
public String getLabel() {
return "Run XApi File";
}
@Override
public void run(AppContext appContext, PathUtil file) {
}
@Override
public Element getForm() {
return null;
}
@Override
public XapiPlace getPlace() {
return XapiPlace.PLACE;
}
@Override
public void initializePlugin(
AppContext appContext, MultiPanel<?, ?> masterPanel, Place currentPlace
) {
handler = new XapiNavigationHandler(appContext, masterPanel, currentPlace);
services[0] = PublicServices.createProvider(XapiRunnerService.class, handler);
currentPlace.registerChildHandler(getPlace(), handler);
this.place = currentPlace;
this.appContext = appContext;
}
@Override
public ImageResource getIcon(Resources res) {
return res.xapiIcon();
}
@Override
public void onClicked(ImageButton button) {
}
@Override
public FileAssociation getFileAssociation() {
return XAPI_FILE_ASSOCIATION;
}
@Override
public RunConfiguration getRunConfig() {
return this;
}
@Override
public PublicService<?>[] getPublicServices() {
return new PublicService<?>[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/collide/xapi/plugin/XapiRunnerService.java | client/src/main/java/collide/xapi/plugin/XapiRunnerService.java | package collide.xapi.plugin;
/**
* Created by James X. Nelson (james @wetheinter.net) on 9/26/16.
*/
public interface XapiRunnerService {
}
| 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/collide/xapi/nav/XapiPlace.java | client/src/main/java/collide/xapi/nav/XapiPlace.java | package collide.xapi.nav;
import collide.gwtc.ui.GwtCompilePlace;
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.dto.GwtRecompile;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
/**
* Created by James X. Nelson (james @wetheinter.net) on 9/26/16.
*/
public class XapiPlace extends Place {
public static final XapiPlace PLACE = new XapiPlace();
public class NavigationEvent extends PlaceNavigationEvent<XapiPlace> {
public static final String MODULE_KEY = "m";
public static final String SRC_KEY = "s";
public static final String DEPS_KEY = "d";
private final String module;
private final JsoArray<String> srcDir;
private final JsoArray<String> depsDir;
private final boolean recompile;
private NavigationEvent(GwtRecompile module) {
super(XapiPlace.this);
this.module = module.getModule();
this.recompile = module.isRecompile();
if (module.getSources() == null) {
this.srcDir = JsoArray.create();
this.depsDir = JsoArray.create();
} else {
this.srcDir = JsoArray.from(module.getSources());
this.depsDir = JsoArray.from(module.getDependencies());
}
}
@Override
public JsonStringMap<String> getBookmarkableState() {
JsoStringMap<String> map = JsoStringMap.create();
map.put(MODULE_KEY, module);
map.put(SRC_KEY, srcDir.join("::"));
map.put(DEPS_KEY, depsDir.join("::"));
return map;
}
public String getModule() {
return module;
}
public boolean isRecompile() {
return recompile;
}
public JsoArray<String> getSourceDirectory() {
return srcDir;
}
public JsoArray<String> getLibsDirectory() {
return depsDir;
}
}
protected XapiPlace() {
super(PlaceConstants.XAPI_PLACE_NAME);
}
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(JsonStringMap<String> decodedState) {
String srcDir = decodedState.get(XapiPlace.NavigationEvent.SRC_KEY);
if (srcDir == null) {
srcDir = "";
}
String libDir = decodedState.get(XapiPlace.NavigationEvent.DEPS_KEY);
if (libDir == null) {
libDir = "";
}
String module = decodedState.get(XapiPlace.NavigationEvent.MODULE_KEY);
GwtRecompileImpl compile = GwtRecompileImpl.make();
compile.setModule(module);
JsoArray<String>
array = JsoArray.splitString(srcDir, "::");
compile.setSources(array);
array = JsoArray.splitString(libDir, "::");
compile.setDependencies(array);
return new NavigationEvent(compile);
}
}
| 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/collide/xapi/nav/XapiNavigationHandler.java | client/src/main/java/collide/xapi/nav/XapiNavigationHandler.java | package collide.xapi.nav;
import collide.xapi.nav.XapiPlace.NavigationEvent;
import collide.xapi.plugin.XapiRunnerService;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.ui.panel.PanelModel;
/**
* Created by James X. Nelson (james @wetheinter.net) on 9/26/16.
*/
public class XapiNavigationHandler extends PlaceNavigationHandler<XapiPlace.NavigationEvent> implements
XapiRunnerService {
private final AppContext context;
private final MultiPanel<? extends PanelModel,?> contentArea;
private final Place currentPlace;
public XapiNavigationHandler(
AppContext context,
MultiPanel<? extends PanelModel, ?> contentArea,
Place currentPlace
) {
this.context = context;
this.contentArea = contentArea;
this.currentPlace = currentPlace;
}
@Override
protected void enterPlace(NavigationEvent navigationEvent) {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/filetree/AppContextFileTreeController.java | client/src/main/java/collide/client/filetree/AppContextFileTreeController.java | package collide.client.filetree;
import com.google.collide.client.AppContext;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.status.StatusManager;
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.WorkspaceTreeUpdate;
public class AppContextFileTreeController implements
FileTreeController<com.google.collide.client.Resources> {
private final AppContext appContext;
public AppContextFileTreeController(AppContext appContext) {
this.appContext = appContext;
}
@Override
public MessageFilter getMessageFilter() {
return appContext.getMessageFilter();
}
@Override
public com.google.collide.client.Resources getResources() {
return appContext.getResources();
}
@Override
public void mutateWorkspaceTree(WorkspaceTreeUpdate msg, ApiCallback<EmptyMessage> callback) {
appContext.getFrontendApi().MUTATE_WORKSPACE_TREE.send(msg, callback);
}
@Override
public void getFileContents(GetFileContents getFileContents,
ApiCallback<GetFileContentsResponse> callback) {
appContext.getFrontendApi().GET_FILE_CONTENTS.send(getFileContents, callback);
}
@Override
public void getDirectory(GetDirectory getDirectory, ApiCallback<GetDirectoryResponse> callback) {
appContext.getFrontendApi().GET_DIRECTORY.send(getDirectory, callback);
}
@Override
public StatusManager getStatusManager() {
return appContext.getStatusManager();
}
}
| 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/collide/client/filetree/FileTreeContextMenuController.java | client/src/main/java/collide/client/filetree/FileTreeContextMenuController.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import java.util.ArrayList;
import java.util.List;
import collide.client.common.CanRunApplication;
import collide.client.filetree.FileTreeModel.NodeRequestCallback;
import collide.client.treeview.SelectionModel;
import collide.client.treeview.Tree;
import collide.client.treeview.TreeNodeElement;
import collide.client.treeview.TreeNodeLabelRenamer;
import collide.client.treeview.TreeNodeLabelRenamer.LabelRenamerCallback;
import collide.client.util.BrowserUtils;
import collide.client.util.Elements;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.ResourceUriUtils;
import com.google.collide.client.history.Place;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.testing.DebugAttributeSetter;
import com.google.collide.client.ui.dropdown.DropdownController;
import com.google.collide.client.ui.dropdown.DropdownController.DropdownPositionerBuilder;
import com.google.collide.client.ui.dropdown.DropdownWidgets;
import com.google.collide.client.ui.list.SimpleList.ListItemRenderer;
import com.google.collide.client.ui.menu.PositionController;
import com.google.collide.client.ui.menu.PositionController.HorizontalAlign;
import com.google.collide.client.ui.menu.PositionController.Positioner;
import com.google.collide.client.ui.tooltip.Tooltip;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.UploadClickedEvent;
import com.google.collide.client.workspace.UploadClickedEvent.UploadType;
import com.google.collide.client.workspace.WorkspaceUtils;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.EmptyMessage;
import com.google.collide.dto.FileInfo;
import com.google.collide.dto.Mutation;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.WorkspaceTreeUpdate;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.FileInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.TreeNodeInfoImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.FrontendConstants;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.user.client.Window;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.IFrameElement;
/**
* Handles File tree context menu actions.
*/
public class FileTreeContextMenuController {
/**
* The data for a menu item in the context menu.
*/
abstract class FileTreeMenuItem {
abstract void onClicked(TreeNodeElement<FileTreeNode> node);
boolean isDisabled() {
return false;
}
@Override
public abstract String toString();
}
class FileTreeItemRenderer extends ListItemRenderer<FileTreeMenuItem> {
final String DISABLED_COLOR = "#ccc";
@Override
public void render(Element listItemBase, FileTreeMenuItem item) {
if (item.isDisabled()) {
listItemBase.getStyle().setColor(DISABLED_COLOR);
}
new DebugAttributeSetter().add("disabled", Boolean.toString(item.isDisabled()))
.on(listItemBase);
listItemBase.setTextContent(item.toString());
}
}
/**
* Specifies the current mode of the context menu. Some modes may indicate that the context menu
* retains control of the cursor, for example in RENAME mode. When the mode is READY, the context
* menu will not capture the cursor.
*/
public enum ContextMenuMode {
/** the cursor will not be captured by the context menu */
READY,
/** the cursor will be captured and used for placing the caret in the rename text field */
RENAME
}
private static final String NEW_FILE_NAME = "untitled";
/**
* The parameter used to enable file tree cut.
*/
private static final String FILE_TREE_CUT_URL_PARAM = "fileTreeCutEnabled";
public static final String DOWNLOAD_FRAME_ID = "download";
/**
* Static factory method for obtaining an instance of FileTreeContextMenuController.
*/
public static FileTreeContextMenuController create(Place place,
DropdownWidgets.Resources res,
FileTreeUiController fileTreeUiController,
FileTreeModel fileTreeModel,
TreeNodeLabelRenamer<FileTreeNode> nodeLabelMutator,
FileTreeController<?> controller,
CanRunApplication applicationRunner) {
FileTreeContextMenuController ctxMenuController = new FileTreeContextMenuController(place,
fileTreeUiController,
fileTreeModel,
nodeLabelMutator,
controller,
applicationRunner);
ctxMenuController.installContextMenu(res);
return ctxMenuController;
}
private final FileTreeController<?> controller;
private DropdownController<FileTreeMenuItem> contextDropdownController;
private DropdownController<FileTreeMenuItem> buttonDropdownController;
private final JsoArray<FileTreeNode> copiedNodes = JsoArray.create();
private boolean copiedNodesAreCut = false;
private final JsonArray<FileTreeMenuItem> rootMenuItems = JsonCollections.createArray();
private final JsonArray<FileTreeMenuItem> dirMenuItems = JsonCollections.createArray();
private final JsonArray<FileTreeMenuItem> fileMenuItems = JsonCollections.createArray();
private final JsonArray<FileTreeMenuItem> readonlyRootMenuItems = JsonCollections.createArray();
private final JsonArray<FileTreeMenuItem> readonlyDirMenuItems = JsonCollections.createArray();
private final JsonArray<FileTreeMenuItem> readonlyFileMenuItems = JsonCollections.createArray();
private final boolean isReadOnly = false;
private final FileTreeItemRenderer renderer;
private final List<FileTreeMenuItem> allMenuItems = new ArrayList<FileTreeMenuItem>();
private final FileTreeModel fileTreeModel;
private final FileTreeUiController fileTreeUiController;
private final TreeNodeLabelRenamer<FileTreeNode> nodeLabelMutator;
private final Place place;
private final CanRunApplication applicationRunner;
private Tooltip invalidNameTooltip;
private ContextMenuMode mode = ContextMenuMode.READY;
private TreeNodeElement<FileTreeNode> selectedNode;
FileTreeContextMenuController(Place place,
FileTreeUiController fileTreeUiController,
FileTreeModel fileTreeModel,
TreeNodeLabelRenamer<FileTreeNode> nodeLabelMutator,
FileTreeController<?> controller,
CanRunApplication applicationRunner) {
this.place = place;
this.fileTreeUiController = fileTreeUiController;
this.fileTreeModel = fileTreeModel;
this.controller = controller;
this.nodeLabelMutator = nodeLabelMutator;
this.applicationRunner = applicationRunner;
createMenuItems();
renderer = new FileTreeItemRenderer();
}
/**
* Creates an additional dropdown menu attached to a button instead of a right click.
*
* @param anchorElement the element to attach the button to
*/
public void createMenuDropdown(Element anchorElement) {
// Create the dropdown controller for the file tree menu button.
DropdownController.Listener<FileTreeMenuItem> listener =
new DropdownController.BaseListener<FileTreeMenuItem>() {
@Override
public void onItemClicked(FileTreeMenuItem item) {
if (item.isDisabled()) {
return;
}
item.onClicked(null);
}
};
Positioner positioner = new DropdownPositionerBuilder().setHorizontalAlign(
HorizontalAlign.RIGHT).buildAnchorPositioner(anchorElement);
buttonDropdownController = new DropdownController.Builder<FileTreeMenuItem>(positioner,
anchorElement, controller.getResources(), listener, renderer).setShouldAutoFocusOnOpen(true)
.build();
buttonDropdownController.setItems(rootMenuItems);
}
/**
* Simply handles the copy command from the context menu. Doesn't actually do anything other than
* stash a reference to the copied node until a paste is issued.
*
* @param node the copied node
* @param isCut true if the node is cut
*/
private void handleCopy(TreeNodeElement<FileTreeNode> node, boolean isCut) {
copiedNodesAreCut = isCut;
copiedNodes.clear();
SelectionModel<FileTreeNode> selectionModel =
fileTreeUiController.getTree().getSelectionModel();
copiedNodes.addAll(selectionModel.getSelectedNodes());
// If there is no active selection, simply make the clicked on node the
// copiedNode.
if (copiedNodes.isEmpty()) {
copiedNodes.add(node.getData());
}
}
public void handleDelete(final TreeNodeElement<FileTreeNode> nodeToDelete) {
WorkspaceTreeUpdate msg = fileTreeModel.makeEmptyTreeUpdate();
JsoArray<FileTreeNode> selectedNodes =
fileTreeUiController.getTree().getSelectionModel().getSelectedNodes();
for (int i = 0, n = selectedNodes.size(); i < n; i++) {
FileTreeNode node = selectedNodes.get(i);
copiedNodes.remove(node);
msg.getMutations().add(FileTreeUtils.makeMutation(
Mutation.Type.DELETE, node.getNodePath(), null, node.isDirectory(),
node.getFileEditSessionKey()));
}
controller.mutateWorkspaceTree(
msg, new ApiCallback<EmptyMessage>() {
@Override
public void onMessageReceived(EmptyMessage message) {
// We lean on the Tango broadcast to mutate the
// tree.
}
@Override
public void onFail(FailureReason reason) {
// Do nothing.
}
});
}
public void handleNewFile(TreeNodeElement<FileTreeNode> parentTreeNode) {
handleNodeWillBeAdded();
FileTreeNode parentData = getDirData(parentTreeNode);
String newFileName = FileTreeUtils.allocateName(parentData.<DirInfoImpl>cast(), NEW_FILE_NAME);
FileInfoImpl newFile = FileInfoImpl.make().setSize("0");
newFile.<TreeNodeInfoImpl>cast().setNodeType(TreeNodeInfo.FILE_TYPE);
newFile.setName(newFileName);
handleNewNode(parentTreeNode, parentData, newFile.<FileTreeNode>cast());
}
public void handleNewFolder(TreeNodeElement<FileTreeNode> parentTreeNode) {
handleNodeWillBeAdded();
FileTreeNode parentData = getDirData(parentTreeNode);
String newDirName =
FileTreeUtils.allocateName(parentData.<DirInfoImpl>cast(), NEW_FILE_NAME + "Folder");
DirInfoImpl newDir = DirInfoImpl.make()
.setFiles(JsoArray.<FileInfo>create()).setSubDirectories(JsoArray.<DirInfo>create())
.setIsComplete(false);
newDir.<TreeNodeInfoImpl>cast().setNodeType(TreeNodeInfo.DIR_TYPE);
newDir.setName(newDirName);
handleNewNode(parentTreeNode, parentData, newDir.<FileTreeNode>cast());
}
/**
* Notify that a file is going to be added so that we can hide the template picker. This is
* workspace/user specific, so we don't need to broadcast the message. The actual add will be
* broadcast.
*/
private void handleNodeWillBeAdded() {
fileTreeUiController.nodeWillBeAdded();
}
public void handleDownload(TreeNodeElement<FileTreeNode> parentTreeNode, final boolean asZip) {
FileTreeNode parentData = getDirData(parentTreeNode);
final String path = parentData == null ? "/" : parentData.getNodePath().getPathString();
if (parentTreeNode != null) {
handleDownloadImpl(asZip, path, path.substring(path.lastIndexOf('/') + 1));
} else {
// TODO: Re-enable workspace downloading.
// workspaceManager.getWorkspace(new QueryCallback<Workspace>() {
// @Override
// public void onFail(FailureReason reason) {
// handleDownloadImpl(asZip, "/", "workspace-" + );
// }
//
// @Override
// public void onQuerySuccess(Workspace result) {
// // Lose special characters that would confuse OS'es, shells, or
// // people. We replace spaces and tabs; slash, colon and backslash;
// // semicolon and quotes with underbar. To avoid confusing HTTP
// // agents, we then URL-encode the result.
// String name = result.getWorkspaceInfo().getName().replaceAll("[\\s/:\\\\;'\"]", "_");
// name = URL.encodeQueryString(name);
// handleDownloadImpl(asZip, "/", name);
// }
// });
}
}
private void handleDownloadImpl(boolean asZip, String path, String fileSource) {
String relativeUri =
ResourceUriUtils.getAbsoluteResourceUri(fileSource);
// actual .zip resources we download raw; anything else we do as a zip
String source = relativeUri + (asZip ? ".zip?rt=zip" : "?rt=download") + "&cl="
+ BootstrapSession.getBootstrapSession().getActiveClientId();
source = source + "&" + FrontendConstants.FILE_PARAM_NAME + "=" + path;
// we're going to download the zip into a hidden iframe, which because
// it's a zip the browser should offer to save on disk.
final IFrameElement iframe = Elements.createIFrameElement();
iframe.setId(DOWNLOAD_FRAME_ID);
iframe.getStyle().setDisplay("none");
iframe.setOnload(new EventListener() {
@Override
public void handleEvent(Event event) {
iframe.removeFromParent();
}
});
iframe.setSrc(source);
Elements.getBody().appendChild(iframe);
}
/**
* We do not do an optimistic UI update here since we potentially will need to re-fetch an entire
* subtree of data, and doing an eager deep clone on the client seems like it would short circuit
* a lot of our DTO->model data transformation.
*
* Note that we do not support CUT for nodes in the tree. Only COPY and MOVE. Therefore PASTE
* only has to consider the COPY case.
*
* @param parentDirNode the parent dir node (which may be incomplete), or null for the root
*/
public void handlePaste(TreeNodeElement<FileTreeNode> parentDirNode) {
if (copiedNodes.isEmpty()) {
return;
}
// Figure out where it is being pasted to.
FileTreeNode parentDirData = getDirData(parentDirNode);
if (!parentDirData.isComplete()) {
// Ensure we have its children so our duplicate check works
fileTreeModel.requestDirectoryChildren(parentDirData, new NodeRequestCallback() {
@Override
public void onNodeAvailable(FileTreeNode node) {
handlePasteForCompleteParent(node);
}
@Override
public void onNodeUnavailable() {
/*
* This should be very rare, if you paste into an incomplete directory at the same time a
* collaborator deletes it (your XHR response comes faster than the tree mutation push
* message)
*/
new StatusMessage(controller.getStatusManager(), MessageType.ERROR,
"The destination folder for the paste no longer exists.").fire();
}
@Override
public void onError(FailureReason reason) {
new StatusMessage(controller.getStatusManager(), MessageType.ERROR,
"The paste had a problem, please try again.").fire();
}
});
} else {
handlePasteForCompleteParent(parentDirData);
}
}
private void handlePasteForCompleteParent(FileTreeNode parentDirData) {
// TODO: Figure out if we are pasting on top of files that already
// exist with the same name. If we do, we need to handle that via a prompted
// replace.
Mutation.Type mutationType = copiedNodesAreCut ? Mutation.Type.MOVE : Mutation.Type.COPY;
WorkspaceTreeUpdate msg = fileTreeModel.makeEmptyTreeUpdate();
for (int i = 0, n = copiedNodes.size(); i < n; i++) {
FileTreeNode copiedNode = copiedNodes.get(i);
PathUtil targetPath = new PathUtil.Builder().addPath(parentDirData.getNodePath())
.addPathComponent(FileTreeUtils.allocateName(
parentDirData.<DirInfoImpl>cast(), copiedNode.getName())).build();
msg.getMutations().add(FileTreeUtils.makeMutation(
mutationType, copiedNode.getNodePath(), targetPath, copiedNode.isDirectory(),
copiedNode.getFileEditSessionKey()));
}
// Cut nodes can only be pasted once.
if (copiedNodesAreCut) {
copiedNodes.clear();
}
controller.mutateWorkspaceTree(
msg, new ApiCallback<EmptyMessage>() {
@Override
public void onMessageReceived(EmptyMessage message) {
// Do nothing. We lean on the multicasted COPY to have the action
// update our local model.
}
@Override
public void onFail(FailureReason reason) {
// Do nothing.
}
});
}
/**
* Renames the specified node via an inline edit UI.
*
* In the event of a failure on the FE, the appropriate action is to restore the previous name of
* the node.
*/
public void handleRename(TreeNodeElement<FileTreeNode> renamedNode) {
// We hang on to the old name in case we need to roll back the rename.
FileTreeNode data = renamedNode.getData();
final String oldName = data.getName();
final PathUtil oldPath = data.getNodePath();
// Go into "rename node" mode.
setMode(ContextMenuMode.RENAME);
nodeLabelMutator.enterMutation(renamedNode, new LabelRenamerCallback<FileTreeNode>() {
@Override
public void onCommit(String oldLabel, final TreeNodeElement<FileTreeNode> node) {
if (invalidNameTooltip != null) {
// if we were showing a tooltip related to the rename, hide it now
invalidNameTooltip.destroy();
invalidNameTooltip = null;
}
// If the name didn't change. Do nothing.
if (oldLabel.equals(node.getData().getName())) {
setMode(ContextMenuMode.READY);
return;
}
// The node should have been renamed in the UI. This is where we
// send a message to the frontend.
WorkspaceTreeUpdate msg = fileTreeModel.makeEmptyTreeUpdate();
msg.getMutations().add(FileTreeUtils.makeMutation(
Mutation.Type.MOVE, oldPath, node.getData().getNodePath(), node.getData().isDirectory(),
node.getData().getFileEditSessionKey()));
controller.mutateWorkspaceTree(
msg, new ApiCallback<EmptyMessage>() {
@Override
public void onFail(FailureReason reason) {
// TODO: Differentiate between a server mutation problem
// and some other failure. If the mutation succeeded,
// this revert might be overzealous since the change
// could have been applied, but timeout or something
// afterwards. This is a rare corner case though.
// Roll back!
nodeLabelMutator.mutateNodeKey(node, oldName);
}
@Override
public void onMessageReceived(EmptyMessage message) {
// Notification of tree mutation will come via Tango.
// If this file was open, EditorReloadingFileTreeListener will
// ensure that the editor now points to the new path.
}
});
setMode(ContextMenuMode.READY);
}
@Override
public boolean passValidation(TreeNodeElement<FileTreeNode> node, String newLabel) {
if (newLabel.equals(node.getData().getName())) {
return true;
}
return notifyIfNameNotValid(node, newLabel);
}
});
}
private void handleViewFile(TreeNodeElement<FileTreeNode> node) {
applicationRunner.runApplication(node.getData().getNodePath());
}
/**
* Shows the context menu at the specified X and Y coordinates, for a given {@link FileTreeNode}.
*/
public void show(int mouseX, int mouseY, TreeNodeElement<FileTreeNode> node) {
if (fileTreeModel.getWorkspaceRoot() == null) {
return;
}
selectedNode = node;
if (isReadOnly) {
if (node == null) {
contextDropdownController.setItems(readonlyRootMenuItems);
} else if (node.getData().isDirectory()) {
contextDropdownController.setItems(readonlyDirMenuItems);
} else {
contextDropdownController.setItems(readonlyFileMenuItems);
}
} else {
if (node == null) {
contextDropdownController.setItems(rootMenuItems);
} else if (node.getData().isDirectory()) {
contextDropdownController.setItems(dirMenuItems);
} else {
contextDropdownController.setItems(fileMenuItems);
}
}
contextDropdownController.showAtPosition(mouseX, mouseY);
}
/**
* Sends a {@link WorkspaceTreeUpdate} message for an ADD mutation to the frontend to be
* broadcasted to all clients.
*
* Additions create a placeholder node in order to obtain a name for the new node via inline
* editing of the node. In the event of a failure, we simply need to pop the added node out of the
* tree.
*/
private void broadcastAdd(final FileTreeNode installedNode) {
TreeNodeElement<FileTreeNode> placeholderNode = installedNode.getRenderedTreeNode();
assert (placeholderNode != null) : "Placeholder node was not allocated for newly added node: "
+ installedNode.getName();
// Go into "rename node" mode.
nodeLabelMutator.enterMutation(placeholderNode, new LabelRenamerCallback<FileTreeNode>() {
@Override
public void onCommit(String oldLabel, final TreeNodeElement<FileTreeNode> node) {
if (invalidNameTooltip != null) {
// if we were showing a tooltip related to the rename, hide it now
invalidNameTooltip.destroy();
invalidNameTooltip = null;
}
WorkspaceTreeUpdate msg = fileTreeModel.makeEmptyTreeUpdate();
msg.getMutations().add(FileTreeUtils.makeMutation(Mutation.Type.ADD, null,
installedNode.getNodePath(), installedNode.isDirectory(), null));
controller.mutateWorkspaceTree(
msg, new ApiCallback<EmptyMessage>() {
@Override
public void onFail(FailureReason reason) {
// TODO: Differentiate between a server mutation problem
// and some other failure. If the mutation succeeded,
// this revert might be overzealous since the change
// could have been applied, but timeout or something
// afterwards. This is a rare corner case though.
// Roll back! Pop the node out of the tree since the add failed
// on the FE. Note that the node that was added was "optimistic"
// and would not have been able to bump the tracked tip ID, so
// just pass in the existing one.
fileTreeModel.removeNode(
installedNode, fileTreeModel.getLastAppliedTreeMutationRevision());
}
@Override
public void onMessageReceived(EmptyMessage message) {
// Notification will come via Tango and ignored. Rerender the
// parent directory so that we can get sort order.
fileTreeUiController.reRenderSubTree(node.getData().getParent());
fileTreeUiController.autoExpandAndSelectNode(node.getData(), true);
}
});
}
@Override
public boolean passValidation(TreeNodeElement<FileTreeNode> node, String newLabel) {
return notifyIfNameNotValid(node, newLabel);
}
});
}
private FileTreeNode getDirData(TreeNodeElement<FileTreeNode> parentDirNode) {
return (parentDirNode == null) ? fileTreeModel.getWorkspaceRoot() : parentDirNode.getData();
}
private void handleNewNode(TreeNodeElement<FileTreeNode> parentTreeNode, FileTreeNode parentData,
FileTreeNode newNodeData) {
// Add a node that we will then open a label renamer for. We don't want the
// model to synchronously update any model listeners since we want to wait
// until the label rename action succeeds.
fileTreeModel.setDisableChangeNotifications(true);
try {
// This is an optimistic addition. We cannot bump tracked tip, so just
// pass in the existing one.
// TODO: Add some affordance to FileTreeNode so that we can
// know when a node has not yet been committed.
fileTreeModel.addNode(
parentData, newNodeData, fileTreeModel.getLastAppliedTreeMutationRevision());
} finally {
fileTreeModel.setDisableChangeNotifications(false);
}
// If we are adding to the root node, then we need to simply append nodes to
// the tree's root container.
if (parentTreeNode == null) {
Tree<FileTreeNode> tree = fileTreeUiController.getTree();
TreeNodeElement<FileTreeNode> newRenderedNode = tree.createNode(newNodeData);
tree.getView().getElement().appendChild(newRenderedNode);
} else {
// Open the parent node which should create the rendered placeholder for
// the new node.
parentData.invalidateUnifiedChildrenCache();
fileTreeUiController.expandNode(parentTreeNode);
}
broadcastAdd(newNodeData);
}
private void createMenuItems() {
FileTreeMenuItem newFile = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleNewFile(node);
}
@Override
public String toString() {
return "New File";
}
};
FileTreeMenuItem newFolder = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleNewFolder(node);
}
@Override
public String toString() {
return "New Folder";
}
};
// Check if the cut menu option is enabled.
FileTreeMenuItem cut = null;
if (BrowserUtils.hasUrlParameter(FILE_TREE_CUT_URL_PARAM, "t")) {
cut = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleCopy(node, true);
}
@Override
public String toString() {
return "Cut";
}
};
}
FileTreeMenuItem copy = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleCopy(node, false);
}
@Override
public String toString() {
return "Copy";
}
};
FileTreeMenuItem rename = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleRename(node);
}
@Override
boolean isDisabled() {
return fileTreeUiController.getTree().getSelectionModel().getSelectedNodes().size() > 1;
}
@Override
public String toString() {
return "Rename";
}
};
FileTreeMenuItem delete = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleDelete(node);
}
@Override
public String toString() {
return "Delete";
}
};
FileTreeMenuItem viewFile = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleViewFile(node);
}
@Override
public String toString() {
return "View in Browser";
}
};
FileTreeMenuItem paste = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handlePaste(node);
}
@Override
boolean isDisabled() {
return copiedNodes.isEmpty();
}
@Override
public String toString() {
return "Paste";
}
};
FileTreeMenuItem folderAsZip = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleDownload(node, true);
}
@Override
public String toString() {
return "Download Folder as a Zip";
}
};
FileTreeMenuItem branchAsZip = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleDownload(node, true);
}
@Override
public String toString() {
return "Download Branch as a Zip";
}
};
FileTreeMenuItem download = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
handleDownload(node, false);
}
@Override
public String toString() {
return "Download";
}
};
final PathUtil rootPath = PathUtil.EMPTY_PATH;
FileTreeMenuItem uploadFile = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
place.fireEvent(new UploadClickedEvent(UploadType.FILE, node == null ? rootPath
: node.getData().getNodePath()));
}
@Override
public String toString() {
return "Upload File";
}
};
FileTreeMenuItem uploadZip = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
place.fireEvent(new UploadClickedEvent(UploadType.ZIP, node == null ? rootPath
: node.getData().getNodePath()));
}
@Override
public String toString() {
return "Upload and Extract Zip";
}
};
FileTreeMenuItem uploadFolder = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
place.fireEvent(new UploadClickedEvent(UploadType.DIRECTORY, node == null ? rootPath
: node.getData().getNodePath()));
}
@Override
public String toString() {
return "Upload Folder";
}
};
FileTreeMenuItem newTab = new FileTreeMenuItem() {
@Override
public void onClicked(TreeNodeElement<FileTreeNode> node) {
String link = WorkspaceUtils.createDeepLinkToFile(node.getData().getNodePath());
Window.open(link, node.getData().getName(), null);
}
@Override
public String toString() {
return "Open in New Tab";
}
};
rootMenuItems.add(newFile);
rootMenuItems.add(newFolder);
rootMenuItems.add(paste);
rootMenuItems.add(uploadFile);
rootMenuItems.add(uploadFolder);
rootMenuItems.add(uploadZip);
rootMenuItems.add(branchAsZip);
dirMenuItems.add(newFile);
dirMenuItems.add(newFolder);
if (cut != null) {
dirMenuItems.add(cut);
}
dirMenuItems.add(copy);
dirMenuItems.add(paste);
dirMenuItems.add(rename);
dirMenuItems.add(delete);
dirMenuItems.add(uploadFile);
dirMenuItems.add(uploadFolder);
dirMenuItems.add(uploadZip);
dirMenuItems.add(folderAsZip);
if (cut != null) {
fileMenuItems.add(cut);
}
fileMenuItems.add(copy);
fileMenuItems.add(viewFile);
fileMenuItems.add(newTab);
fileMenuItems.add(rename);
fileMenuItems.add(delete);
fileMenuItems.add(download);
// Read Only Variety
readonlyRootMenuItems.add(branchAsZip);
readonlyDirMenuItems.add(folderAsZip);
readonlyFileMenuItems.add(viewFile);
readonlyFileMenuItems.add(newTab);
readonlyFileMenuItems.add(download);
allMenuItems.add(newFile);
allMenuItems.add(newFolder);
if (cut != null) {
allMenuItems.add(cut);
}
allMenuItems.add(copy);
allMenuItems.add(paste);
allMenuItems.add(rename);
allMenuItems.add(delete);
allMenuItems.add(uploadFile);
allMenuItems.add(uploadFolder);
allMenuItems.add(uploadZip);
allMenuItems.add(folderAsZip);
allMenuItems.add(branchAsZip);
allMenuItems.add(download);
}
/**
* Create the context menu.
*/
private void installContextMenu(DropdownWidgets.Resources res) {
DropdownController.Listener<FileTreeMenuItem> listener =
new DropdownController.BaseListener<FileTreeMenuItem>() {
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | true |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/filetree/FileTreeNodeDataAdapter.java | client/src/main/java/collide/client/filetree/FileTreeNodeDataAdapter.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import collide.client.treeview.NodeDataAdapter;
import collide.client.treeview.TreeNodeElement;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
/**
*/
public class FileTreeNodeDataAdapter implements NodeDataAdapter<FileTreeNode> {
@Override
public int compare(FileTreeNode a, FileTreeNode b) {
// Directories are listed before files. This is also implicitly codified in
// the constants.
int comparison = a.getNodeType() - b.getNodeType();
// If they are nodes of different types, we can return.
if (comparison != 0) {
return comparison;
}
return a.getName().compareTo(b.getName());
}
@Override
public boolean hasChildren(FileTreeNode data) {
return data.isDirectory() && (!data.isComplete() || data.getUnifiedChildren().size() > 0);
}
@Override
public JsonArray<FileTreeNode> getChildren(FileTreeNode data) {
return data.isDirectory() ? data.getUnifiedChildren() :
JsonCollections.<FileTreeNode>createArray();
}
@Override
public String getNodeId(FileTreeNode data) {
return data.getName();
}
@Override
public String getNodeName(FileTreeNode data) {
return data.getName();
}
@Override
public FileTreeNode getParent(FileTreeNode data) {
return data.getParent();
}
@Override
public TreeNodeElement<FileTreeNode> getRenderedTreeNode(FileTreeNode data) {
return data.getRenderedTreeNode();
}
@Override
public void setNodeName(FileTreeNode data, String key) {
data.setName(key);
}
@Override
public void setRenderedTreeNode(FileTreeNode data, TreeNodeElement<FileTreeNode> renderedNode) {
data.setRenderedTreeNode(renderedNode);
}
@Override
public FileTreeNode getDragDropTarget(FileTreeNode data) {
return data.isDirectory() ? data : data.getParent();
}
@Override
public JsonArray<String> getNodePath(FileTreeNode data) {
return NodeDataAdapter.PathUtils.getNodePath(this, data);
}
@Override
public FileTreeNode getNodeByPath(FileTreeNode root, JsonArray<String> relativeNodePath) {
return root.findChildNode(PathUtil.createFromPathComponents(relativeNodePath));
}
}
| 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/collide/client/filetree/FileTreeModelNetworkController.java | client/src/main/java/collide/client/filetree/FileTreeModelNetworkController.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import collide.client.filetree.FileTreeModel.NodeRequestCallback;
import collide.client.filetree.FileTreeModel.RootNodeRequestCallback;
import com.google.collide.client.bootstrap.BootstrapSession;
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.history.Place;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.GetDirectoryResponse;
import com.google.collide.dto.Mutation;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.WorkspaceTreeUpdateBroadcast;
import com.google.collide.dto.client.DtoClientImpls.GetDirectoryImpl;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.FrontendConstants;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
/**
* Controller responsible for receiving DTOs that come off the {@link MessageFilter} that were sent
* from the frontend, and updating the {@link FileTreeModel}.
*
*/
public class FileTreeModelNetworkController implements FileTreeInvalidatedEvent.Handler {
/**
* Static factory method to obtain an instance of FileTreeModelNetworkController.
*/
public static FileTreeModelNetworkController create(FileTreeModel fileTreeModel,
FileTreeController<?> fileTreeController, Place currentPlace) {
FileTreeModelNetworkController networkController =
new FileTreeModelNetworkController(fileTreeModel, fileTreeController);
currentPlace.registerSimpleEventHandler(FileTreeInvalidatedEvent.TYPE, networkController);
networkController.registerForInvalidations(fileTreeController.getMessageFilter());
// Load the tree.
networkController.reloadDirectory(PathUtil.WORKSPACE_ROOT);
return networkController;
}
/**
* A controller for the outgoing network requests for fetching nodes. This logic is used mainly
* for lazy tree loading.
*
* <p>
* This class is a static class to prevent circular instance dependencies between the
* {@link FileTreeModel} and the {@link FileTreeModelNetworkController}.
*/
public static class OutgoingController {
private final FileTreeController<?> fileTreeController;
public OutgoingController(FileTreeController<?> fileTreeController) {
this.fileTreeController = fileTreeController;
}
/**
* @see FileTreeModel#requestWorkspaceNode
*/
void requestWorkspaceNode(final FileTreeModel fileTreeModel, final PathUtil path,
final NodeRequestCallback callback) {
// Wait until the root node has been loaded.
fileTreeModel.requestWorkspaceRoot(new RootNodeRequestCallback() {
@Override
public void onRootNodeAvailable(FileTreeNode root) {
// Find the closest node in the tree, which might be the node we want.
final FileTreeNode closest = root.findClosestChildNode(path);
if (closest == null) {
// The node does not exist in the tree.
callback.onNodeUnavailable();
return;
} else if (path.equals(closest.getNodePath())) {
// The node is already in the tree.
callback.onNodeAvailable(closest);
return;
}
// Get the directory that contains the path.
final PathUtil dirPath = PathUtil.createExcludingLastN(path, 1);
// Request the node and its parents, starting from the closest node.
/*
* TODO: We should revisit deep linking in the file tree and possible only show
* the directory that is deep linked. Otherwise, we may have to load a lot of parent
* directories when deep linking to a very deep directory.
*/
GetDirectoryImpl getDirectoryAndPath = GetDirectoryImpl.make()
.setPath(dirPath.getPathString())
.setDepth(FrontendConstants.DEFAULT_FILE_TREE_DEPTH)
.setRootId(fileTreeModel.getLastAppliedTreeMutationRevision());
// Include the root path so we load parent directories leading up to the file.
//.setRootPath(closest.getNodePath().getPathString());
fileTreeController.getDirectory(
getDirectoryAndPath, new ApiCallback<GetDirectoryResponse>() {
@Override
public void onMessageReceived(GetDirectoryResponse response) {
DirInfo baseDir = response.getBaseDirectory();
if (baseDir == null) {
/*
* The folder was most probably deleted before the server received our request.
* We should receive a tango notification to update the client.
*/
return;
}
FileTreeNode incomingSubtree = FileTreeNode.transform(baseDir);
fileTreeModel.replaceNode(
new PathUtil(response.getPath()), incomingSubtree, response.getRootId());
// Check if the node now exists.
FileTreeNode child = fileTreeModel.getWorkspaceRoot().findChildNode(path);
if (child == null) {
callback.onNodeUnavailable();
} else {
callback.onNodeAvailable(child);
}
}
@Override
public void onFail(FailureReason reason) {
Log.error(getClass(), "Failed to retrieve directory path "
+ dirPath.getPathString());
// Update the callback.
callback.onError(reason);
}
});
}
});
}
/**
* @see FileTreeModel#requestDirectoryChildren
*/
void requestDirectoryChildren(
final FileTreeModel fileTreeModel, FileTreeNode node, final NodeRequestCallback callback) {
Preconditions.checkArgument(node.isDirectory(), "Cannot request children of a file");
final PathUtil path = node.getNodePath();
GetDirectoryImpl getDirectory = GetDirectoryImpl.make()
.setPath(path.getPathString())
.setDepth(FrontendConstants.DEFAULT_FILE_TREE_DEPTH)
.setRootId(fileTreeModel.getLastAppliedTreeMutationRevision());
fileTreeController.getDirectory(getDirectory,
new ApiCallback<GetDirectoryResponse>() {
@Override
public void onMessageReceived(GetDirectoryResponse response) {
DirInfo baseDir = response.getBaseDirectory();
if (baseDir == null) {
/*
* The folder was most probably deleted before the server received our request. We
* should receive a tango notification to update the client.
*/
if (callback != null) {
callback.onNodeUnavailable();
}
return;
}
FileTreeNode incomingSubtree = FileTreeNode.transform(baseDir);
fileTreeModel.replaceNode(
new PathUtil(response.getPath()), incomingSubtree, response.getRootId());
if (callback != null) {
callback.onNodeAvailable(incomingSubtree);
}
}
@Override
public void onFail(FailureReason reason) {
Log.error(getClass(), "Failed to retrieve children for directory "
+ path.getPathString());
if (callback != null) {
callback.onError(reason);
} else {
StatusMessage fatal = new StatusMessage(
fileTreeController.getStatusManager(), MessageType.FATAL,
"Could not retrieve children of directory. Please try again.");
fatal.setDismissable(true);
fatal.fire();
}
}
});
}
}
private final FileTreeController<?> fileTreeController;
private final FileTreeModel fileTreeModel;
FileTreeModelNetworkController(FileTreeModel fileTreeModel, FileTreeController<?> fileTreeController) {
this.fileTreeModel = fileTreeModel;
this.fileTreeController = fileTreeController;
}
/**
* Adds a node to our model from a broadcasted workspace tree mutation.
*/
private void handleExternalAdd(String newPath, TreeNodeInfo newNode, String newTipId) {
String ourClientId = BootstrapSession.getBootstrapSession().getActiveClientId();
PathUtil path = new PathUtil(newPath);
FileTreeNode rootNode = fileTreeModel.getWorkspaceRoot();
// If the root is null... then we are receiving mutations before we even got
// the workspace in the first place. So we should ignore.
// TODO: This is a potential race. We need to schedule a pending
// referesh for the tree!!
if (rootNode == null) {
Log.warn(getClass(), "Receiving ADD tree mutations before the root node is set for node: "
+ path.getPathString());
return;
}
FileTreeNode existingNode = rootNode.findChildNode(path);
if (existingNode == null) {
fileTreeModel.addNode(path, (FileTreeNode) newNode, newTipId);
} else {
// If it's already there, it's probably a placeholder node we created.
existingNode.setFileEditSessionKey(newNode.getFileEditSessionKey());
// Because adding new node via context menu disable change notifications,
// we need explicitly notify listeners.
fileTreeModel.dispatchAddNode(existingNode.getParent(), existingNode, newTipId);
}
}
private void handleExternalCopy(String newpath, TreeNodeInfo newNode, String newTipId) {
PathUtil path = new PathUtil(newpath);
FileTreeNode rootNode = fileTreeModel.getWorkspaceRoot();
// If the root is null... then we are receiving mutations before we even got
// the workspace in the first place. So we should ignore.
// TODO: This is a potential race. We need to schedule a pending
// referesh for the tree!!
if (rootNode == null) {
Log.warn(getClass(), "Receiving COPY tree mutations before the root node is set for node: "
+ path.getPathString());
return;
}
FileTreeNode installedNode = (FileTreeNode) newNode;
fileTreeModel.addNode(path, installedNode, newTipId);
}
/**
* Removes a node from the model and from the rendered Tree.
*/
private void handleExternalDelete(JsonArray<Mutation> deletedNodes, String newTipId) {
// Note that for deletes we do NOT currently optimistically update the UI.
// So we need to remove the node, even if we triggered said delete.
JsonArray<PathUtil> pathsToDelete = JsonCollections.createArray();
for (int i = 0; i < deletedNodes.size(); i++) {
pathsToDelete.add(new PathUtil(deletedNodes.get(i).getOldPath()));
}
fileTreeModel.removeNodes(pathsToDelete, newTipId);
}
private void handleExternalMove(String oldPathStr, String newPathStr, String newTipId) {
PathUtil oldPath = new PathUtil(oldPathStr);
PathUtil newPath = new PathUtil(newPathStr);
FileTreeNode rootNode = fileTreeModel.getWorkspaceRoot();
// If the root is null... then we are receiving mutations before we even got
// the workspace in the first place. So we should ignore.
// TODO: This is a potential race. We need to schedule a pending
// referesh for the tree!!
if (rootNode == null) {
Log.warn(getClass(), "Receiving MOVE tree mutations before the root node is set for node: "
+ oldPath.getPathString());
return;
}
fileTreeModel.moveNode(oldPath, newPath, newTipId);
}
/**
* Handles ADD, RENAME, DELETE, or COPY messages.
*/
private void handleFileTreeMutation(WorkspaceTreeUpdateBroadcast treeUpdate) {
JsonArray<Mutation> mutations = treeUpdate.getMutations();
for (int i = 0, n = mutations.size(); i < n; i++) {
Mutation mutation = mutations.get(i);
switch (mutation.getMutationType()) {
case ADD:
handleExternalAdd(
mutation.getNewPath(), mutation.getNewNodeInfo(), treeUpdate.getNewTreeVersion());
break;
case DELETE:
handleExternalDelete(treeUpdate.getMutations(), treeUpdate.getNewTreeVersion());
break;
case MOVE:
handleExternalMove(mutation.getOldPath(), mutation.getNewPath(), treeUpdate.getNewTreeVersion());
break;
case COPY:
handleExternalCopy(mutation.getNewPath(), mutation.getNewNodeInfo(), treeUpdate.getNewTreeVersion());
break;
default:
assert (false) : "We got some kind of malformed workspace tree mutation!";
break;
}
// Bump the tracked tip.
fileTreeModel.maybeSetLastAppliedTreeMutationRevision(treeUpdate.getNewTreeVersion());
}
}
public void handleSubtreeReplaced(GetDirectoryResponse response) {
FileTreeNode incomingSubtree = FileTreeNode.transform(response.getBaseDirectory());
fileTreeModel.replaceNode(
new PathUtil(response.getPath()), incomingSubtree, response.getRootId());
if (PathUtil.WORKSPACE_ROOT.equals(new PathUtil(response.getPath()))) {
fileTreeModel.maybeSetLastAppliedTreeMutationRevision(response.getRootId());
}
}
@Override
public void onFileTreeInvalidated(PathUtil invalidatedPath) {
// Check if the invalidated path points to a file
if (!invalidatedPath.equals(PathUtil.WORKSPACE_ROOT)) {
if (fileTreeModel.getWorkspaceRoot() != null) {
FileTreeNode invalidatedNode =
fileTreeModel.getWorkspaceRoot().findChildNode(invalidatedPath);
if (invalidatedNode == null) {
// Our lazy tree does not contain the node, we don't have to do anything
return;
}
if (invalidatedNode.isFile()) {
reloadDirectory(PathUtil.createExcludingLastN(invalidatedPath, 1));
return;
}
} else {
/*
* We don't have enough information yet to invalidate the specific node, so we just
* invalidate the workspace root
*/
invalidatedPath = PathUtil.WORKSPACE_ROOT;
}
}
reloadDirectory(invalidatedPath);
}
private void reloadDirectory(final PathUtil invalidatedPath) {
GetDirectoryImpl request = GetDirectoryImpl.make().setRootId(
fileTreeModel.getLastAppliedTreeMutationRevision())
.setDepth(FrontendConstants.DEFAULT_FILE_TREE_DEPTH);
// Fetch the parent directory of the file
request.setPath(invalidatedPath.toString());
fileTreeController.getDirectory(request,
new ApiCallback<GetDirectoryResponse>() {
@Override
public void onMessageReceived(GetDirectoryResponse response) {
handleSubtreeReplaced(response);
}
@Override
public void onFail(FailureReason reason) {
Log.error(getClass(), "Failed to retrieve file metadata for workspace.");
StatusMessage fatal = new StatusMessage(
fileTreeController.getStatusManager(), MessageType.FATAL,
"There was a problem refreshing changes within the file tree :(.");
fatal.addAction(StatusMessage.RELOAD_ACTION);
fatal.setDismissable(true);
fatal.fire();
}
});
}
public void registerForInvalidations(MessageFilter messageFilter) {
messageFilter.registerMessageRecipient(RoutingTypes.WORKSPACETREEUPDATEBROADCAST,
new MessageRecipient<WorkspaceTreeUpdateBroadcast>() {
@Override
public void onMessageReceived(WorkspaceTreeUpdateBroadcast update) {
if (update != null) {
handleFileTreeMutation(update);
} else {
// Either the invalidation was not the next sequential one or we
// didn't get the payload. Reload the entire tree.
onFileTreeInvalidated(PathUtil.WORKSPACE_ROOT);
}
}
});
}
}
| 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/collide/client/filetree/FileTreeInvalidatedEvent.java | client/src/main/java/collide/client/filetree/FileTreeInvalidatedEvent.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import com.google.collide.client.util.PathUtil;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* An event that describes an invalidation to the entire or part of the file tree. If the
* invalidation is at the root of the file tree ({@link #getInvalidatedPath()} is {@code /}), then
* conflicts are invalidated also.
*/
public class FileTreeInvalidatedEvent extends GwtEvent<FileTreeInvalidatedEvent.Handler> {
public interface Handler extends EventHandler {
void onFileTreeInvalidated(PathUtil invalidatedPath);
}
public static final Type<Handler> TYPE = new Type<Handler>();
/**
* The subtree that was invalidated; '/' means the entire file tree (including conflicts)
*/
private final PathUtil invalidatedPath;
public FileTreeInvalidatedEvent(PathUtil invalidatedPath) {
this.invalidatedPath = invalidatedPath;
}
@Override
public Type<Handler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(Handler handler) {
handler.onFileTreeInvalidated(invalidatedPath);
}
public PathUtil getInvalidatedPath() {
return invalidatedPath;
}
}
| 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/collide/client/filetree/FileTreeUiController.java | client/src/main/java/collide/client/filetree/FileTreeUiController.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import collide.client.common.CanRunApplication;
import collide.client.filetree.FileTreeContextMenuController.ContextMenuMode;
import collide.client.treeview.Tree;
import collide.client.treeview.TreeNodeElement;
import collide.client.treeview.TreeNodeLabelRenamer;
import com.google.collide.client.code.FileSelectedPlace;
import com.google.collide.client.communication.ResourceUriUtils;
import com.google.collide.client.history.Place;
import com.google.collide.client.ui.dropdown.DropdownWidgets;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonArray;
import elemental.html.Location;
import elemental.js.html.JsDragEvent;
/**
* Listens for changes to the model via callbacks from {@link FileTreeModel} and updates the Tree.
* Similarly, this controller takes events reported from the {@link Tree} (like clicks and
* selections) and handles them.
*/
public class FileTreeUiController implements FileTreeModel.TreeModelChangeListener {
/**
* Static factory method for obtaining an instance of a FileTreeUiController.
*/
public static FileTreeUiController create(Place place,
FileTreeModel fileTreeModel,
Tree<FileTreeNode> tree,
FileTreeController<?> controller,
CanRunApplication applicationRunner) {
// Set the initial root node for the tree. This will simply be null on first
// load. But if it isn't we should probably still render what ever was in
// the FileTreeModel.
tree.getModel().setRoot(fileTreeModel.getWorkspaceRoot());
TreeNodeLabelRenamer<FileTreeNode> nodeLabelMutator = new TreeNodeLabelRenamer<FileTreeNode>(
tree.getModel().getNodeRenderer(), tree.getModel().getDataAdapter(),
controller.getResources().workspaceNavigationFileTreeNodeRendererCss());
FileTreeUiController treeUiController = new FileTreeUiController(place,
controller.getResources(),
fileTreeModel,
tree,
nodeLabelMutator,
controller,
applicationRunner);
fileTreeModel.addModelChangeListener(treeUiController);
treeUiController.attachEventHandlers();
return treeUiController;
}
/** Listener for drag-and-drop events on nodes in the file tree. */
public interface DragDropListener {
void onDragStart(FileTreeNode node, JsDragEvent event);
void onDragDrop(FileTreeNode node, JsDragEvent event);
}
private final FileTreeContextMenuController contextMenuController;
private DragDropListener uploadDragDropListener;
private DragDropListener treeNodeMoveListener;
private final FileTreeModel fileTreeModel;
private final Tree<FileTreeNode> tree;
private final Place currentPlace;
FileTreeUiController(Place place,
DropdownWidgets.Resources res,
FileTreeModel fileTreeModel,
Tree<FileTreeNode> tree,
TreeNodeLabelRenamer<FileTreeNode> nodeLabelMutator,
FileTreeController<?> controller,
CanRunApplication applicationRunner) {
this.currentPlace = place;
this.fileTreeModel = fileTreeModel;
this.tree = tree;
this.contextMenuController = FileTreeContextMenuController.create(place,
res,
this,
fileTreeModel,
nodeLabelMutator,
controller,
applicationRunner);
}
/**
* Programmatically selects a node in the tree. This will cause any external handlers of the
* {@link Tree} to have their {@link collide.client.treeview.Tree.Listener#onNodeAction(TreeNodeElement)}
* method get invoked.
*/
public void autoExpandAndSelectNode(FileTreeNode nodeToSelect, boolean dispatchNodeAction) {
tree.autoExpandAndSelectNode(nodeToSelect, dispatchNodeAction);
}
public void expandNode(TreeNodeElement<FileTreeNode> parentTreeNode) {
tree.expandNode(parentTreeNode);
}
public void clearSelectedNodes() {
tree.getSelectionModel().clearSelections();
}
public FileTreeContextMenuController getContextMenuController() {
return contextMenuController;
}
public Tree<FileTreeNode> getTree() {
return tree;
}
public void setUploadDragDropListener(DragDropListener listener) {
uploadDragDropListener = listener;
}
public void setFileTreeNodeMoveListener(DragDropListener listener) {
treeNodeMoveListener = listener;
}
public void nodeWillBeAdded() {
}
/**
* Called when a node is added to the model. This will re-render the subtree rooted at this nodes
* parent iff the parent node is already rendered.
*/
@Override
public void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode) {
FileTreeNode rootNode = tree.getModel().getRoot();
if (rootNode == null) {
return;
}
if (PathUtil.WORKSPACE_ROOT.getPathString().equals(parentDirPath.getPathString())) {
// This means that we are adding to the base of the tree and should reRender.
reRenderSubTree(rootNode);
return;
}
FileTreeNode parentDir = rootNode.findChildNode(parentDirPath);
if (parentDir != null && parentDir.isComplete()) {
// Add the node.
TreeNodeElement<FileTreeNode> parentDirTreeNode = tree.getNode(parentDir);
if (parentDirTreeNode != null) {
reRenderSubTree(parentDir);
}
}
}
@Override
public void onNodeMoved(
PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode) {
FileTreeNode rootNode = tree.getModel().getRoot();
if (rootNode == null) {
return;
}
if (node != null) {
FileTreeNode oldParent = rootNode.findChildNode(PathUtil.createExcludingLastN(oldPath, 1));
onNodeRemoved(oldParent, node.getRenderedTreeNode());
// do not kill the back reference (as in onNodeRemoved)!
}
if (newNode != null) {
PathUtil parentDirPath = PathUtil.createExcludingLastN(newPath, 1);
onNodeAdded(parentDirPath, newNode);
}
}
@Override
public void onNodesRemoved(JsonArray<FileTreeNode> oldNodes) {
FileTreeNode rootNode = tree.getModel().getRoot();
if (rootNode == null) {
return;
}
for (int i = 0; i < oldNodes.size(); i++) {
FileTreeNode oldNode = oldNodes.get(i);
// If we found a node at the specified path, then remove it.
if (oldNode != null) {
onNodeRemoved(oldNode.getParent(), oldNode.getRenderedTreeNode());
// Kill the back reference so we don't leak.
oldNode.setRenderedTreeNode(null);
}
}
}
@Override
public void onNodeReplaced(FileTreeNode oldNode, FileTreeNode newNode) {
if (!newNode.isDirectory()) {
// We don't need to do anything with files being replaced
return;
}
if (PathUtil.WORKSPACE_ROOT.getPathString().equals(newNode.getNodePath().getPathString())) {
// Install the workspace root for the tree and render it. Expansion state
// should be restored by this method.
tree.replaceSubtree(tree.getModel().getRoot(), newNode, false);
} else if (oldNode != null) {
TreeNodeElement<FileTreeNode> oldRenderedElement = oldNode.getRenderedTreeNode();
// If the node that we just replaced had a rendered tree node, we need
// to re-render.
if (oldRenderedElement != null) {
// If the node was loading, animate it open now that the children are available.
tree.replaceSubtree(oldNode, newNode, oldNode.isLoading());
// Kill the back reference so we don't leak.
oldNode.setRenderedTreeNode(null);
}
}
}
/**
* Re-renders the subtree rooted at the specified {@link FileTreeNode}, ensuring that its direct
* children are sorted.
*/
/* TODO : restore selection state */
public void reRenderSubTree(FileTreeNode parentDir) {
parentDir.invalidateUnifiedChildrenCache();
tree.replaceSubtree(parentDir, parentDir, false);
}
private void attachEventHandlers() {
tree.setTreeEventHandler(new Tree.Listener<FileTreeNode>() {
@Override
public void onNodeAction(TreeNodeElement<FileTreeNode> node) {
if (node.getData().isFile()
&& getContextMenuController().getMode() == ContextMenuMode.READY) {
currentPlace.fireChildPlaceNavigation(
FileSelectedPlace.PLACE.createNavigationEvent(node.getData().getNodePath()));
}
}
@Override
public void onNodeClosed(TreeNodeElement<FileTreeNode> node) {}
@Override
public void onNodeContextMenu(int mouseX, int mouseY, TreeNodeElement<FileTreeNode> node) {
getContextMenuController().show(mouseX, mouseY, node);
}
@Override
public void onNodeDragDrop(TreeNodeElement<FileTreeNode> node, JsDragEvent event) {
if (treeNodeMoveListener != null) {
treeNodeMoveListener.onDragDrop(node.getData(), event);
}
if (uploadDragDropListener != null) {
uploadDragDropListener.onDragDrop(node.getData(), event);
}
}
@Override
public void onRootDragDrop(JsDragEvent event) {
if (treeNodeMoveListener != null) {
treeNodeMoveListener.onDragDrop(fileTreeModel.getWorkspaceRoot(), event);
}
if (uploadDragDropListener != null) {
uploadDragDropListener.onDragDrop(fileTreeModel.getWorkspaceRoot(), event);
}
}
@Override
public void onNodeDragStart(TreeNodeElement<FileTreeNode> node, JsDragEvent event) {
// When drag starts in tree, we do not know if users want to drop it
// outside tree or in tree. So, we prepare for both cases.
prepareForDraggingToOutside(node, event);
if (treeNodeMoveListener != null) {
treeNodeMoveListener.onDragStart(node.getData(), event);
}
if (uploadDragDropListener != null) {
uploadDragDropListener.onDragStart(node.getData(), event);
}
}
@Override
public void onNodeExpanded(TreeNodeElement<FileTreeNode> node) {
if (!node.getData().isComplete() && !node.getData().isLoading()) {
// Mark the node as loading.
node.getData().setLoading(true);
tree.getModel().getNodeRenderer().updateNodeContents(node);
// Load the children of the directory.
fileTreeModel.requestDirectoryChildren(node.getData(), null);
}
}
@Override
public void onRootContextMenu(int mouseX, int mouseY) {
getContextMenuController().show(mouseX, mouseY, null);
}
private void prepareForDraggingToOutside(
TreeNodeElement<FileTreeNode> node, JsDragEvent event) {
FileTreeNode fileTreeNode = node.getData();
PathUtil nodePath = fileTreeNode.getNodePath();
String downloadFileName = fileTreeNode.isDirectory() ? nodePath.getBaseName() + ".zip"
: nodePath.getBaseName();
Location location = elemental.client.Browser.getWindow().getLocation();
String urlHttpHostPort = location.getProtocol() + "//" + location.getHost();
String downloadUrl = "application/octet-stream:" + downloadFileName + ":"
+ ResourceUriUtils.getAbsoluteResourceUri(nodePath)
+ (fileTreeNode.isDirectory() ? "?rt=zip" : "");
event.getDataTransfer().setData("DownloadURL", downloadUrl);
}
});
}
private void onNodeRemoved(FileTreeNode oldParent, TreeNodeElement<FileTreeNode> oldNode) {
tree.removeNode(oldNode);
// Make sure to remove expansion controls from any directory that might
// now be empty
if (oldParent != null && oldParent.getRenderedTreeNode() != null) {
if (oldParent.getUnifiedChildren().isEmpty()) {
oldParent.getRenderedTreeNode().makeLeafNode(tree.getResources().treeCss());
}
}
}
}
| 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/collide/client/filetree/FileTreeNode.java | client/src/main/java/collide/client/filetree/FileTreeNode.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import java.util.Comparator;
import collide.client.treeview.TreeNodeElement;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.FileInfo;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.FileInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.TreeNodeInfoImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.annotations.VisibleForTesting;
/**
* The Model for the FileTree. This data structure is constructed (without
* copying) from the DTO based DirInfo workspace file tree.
*
* We visit our workspace file tree that we JSON.parsed into existence, and
* install back references to their parent nodes. We simply eagerly mutate the
* same object graph (not copy it), and when needed we can cast each node to a
* {@link FileTreeNode} to get access to this API.
*
*/
public class FileTreeNode extends TreeNodeInfoImpl {
private static final Comparator<DirInfo> dirSortFunction = new Comparator<DirInfo>() {
@Override
public int compare(DirInfo a, DirInfo b) {
return compareNames(a, b);
}
};
private static final Comparator<FileInfo> fileSortFunction =
new Comparator<FileInfo>() {
@Override
public int compare(FileInfo a, FileInfo b) {
return compareNames(a, b);
}
};
/**
* Converts the DTO object graph into one suitable to act as the model for our
* FileTree.
*
* @param workspaceFiles {@link DirInfo} that represents the files in a
* workspace. This is literally what we JSON.parsed() off the wire.
* @return (@link FileTreeNode} that is the result of mutating the supplied
* {@link DirInfo} tree
*/
public static FileTreeNode transform(DirInfo workspaceFiles) {
transformImpl(workspaceFiles);
return ((DirInfoImpl) workspaceFiles).cast();
}
static native FileTreeNode installBackRef(DirInfo parent, TreeNodeInfo child) /*-{
child.__parentRef = parent;
return child;
}-*/;
private static int compareNames(TreeNodeInfo a, TreeNodeInfo b) {
return a.getName().compareTo(b.getName());
}
private static FileTreeNode getChildNode(FileTreeNode parentNode, String name) {
if (!parentNode.isDirectory()) {
return null;
}
DirInfoImpl asDirInfo = parentNode.cast();
JsonArray<DirInfo> childDirs = asDirInfo.getSubDirectories();
for (int i = 0, n = childDirs.size(); i < n; i++) {
if (childDirs.get(i).getName().equals(name)) {
return (FileTreeNode) childDirs.get(i);
}
}
JsonArray<FileInfo> childFiles = asDirInfo.getFiles();
for (int i = 0, n = childFiles.size(); i < n; i++) {
if (childFiles.get(i).getName().equals(name)) {
return (FileTreeNode) childFiles.get(i);
}
}
return null;
}
private static void transformImpl(DirInfo node) {
JsonArray<DirInfo> subDirsArray = node.getSubDirectories();
for (int i = 0, n = subDirsArray.size(); i < n; i++) {
DirInfo childDir = subDirsArray.get(i);
installBackRef(node, childDir);
transformImpl(childDir);
}
JsonArray<FileInfo> files = node.getFiles();
for (int i = 0, n = files.size(); i < n; i++) {
FileInfo childFile = files.get(i);
installBackRef(node, childFile);
}
}
protected FileTreeNode() {
}
public final void addChild(FileTreeNode newNode) {
assert (isDirectory()) : "You are only allowed to add new files and folders to a directory!";
DirInfoImpl parentDir = this.cast();
// Install the new node in our model by adding it to the child list of the
// parent.
if (newNode.isFile()) {
parentDir.getFiles().add(newNode.<FileInfoImpl>cast());
} else if (newNode.isDirectory()) {
parentDir.getSubDirectories().add(newNode.<DirInfoImpl>cast());
} else {
throw new IllegalArgumentException(
"We somehow made a new node that was neither a directory not a file.");
}
// Install a backreference to the parent to enable path resolution.
installBackRef(parentDir, newNode);
}
/**
* Finds a node with the given path relative to this node.
*
* @return the node if it was found, or null if it was not found or if this
* node is not a directory
*/
public final FileTreeNode findChildNode(PathUtil path) {
FileTreeNode closest = findClosestChildNode(path);
PathUtil absolutePath = PathUtil.concatenate(getNodePath(), path);
if (closest == null || !absolutePath.equals(closest.getNodePath())) {
return null;
}
return closest;
}
/**
* Finds a node with the given path relative to this node, or the closest parent node if the
* branch is incomplete (not loaded).
*
* @return the node if it was found, or the closest node in the path if the branch is not
* complete, or null if the branch is complete and the node is not found
*/
public final FileTreeNode findClosestChildNode(PathUtil path) {
FileTreeNode parentNode = this;
int dirnameComponents = path.getPathComponentsCount() - 1;
if (dirnameComponents < 0) {
return parentNode;
}
for (int i = 0; i < dirnameComponents; i++) {
if (!parentNode.isComplete()) {
return parentNode;
}
String childName = path.getPathComponent(i);
parentNode = getChildNode(parentNode, childName);
if (parentNode == null) {
return null;
}
}
// The immediate parent is not complete.
if (!parentNode.isComplete()) {
return parentNode;
}
// We match the very last path component against parentNode, which should
// now point to the directory containing the requested resource.
return getChildNode(parentNode, path.getPathComponent(dirnameComponents));
}
/**
* Returns a node for the child of the given name, or null.
*/
public final FileTreeNode getChildNode(String name) {
return getChildNode(this, name);
}
/**
* @return Path from the root node to this node.
*/
public final PathUtil getNodePath() {
// TODO: Consider caching this somewhere.
return new PathUtil.Builder()
.addPathComponents(getNodePathComponents())
.build();
}
private JsonArray<String> getNodePathComponents() {
JsonArray<String> pathArray = JsonCollections.createArray();
// We want to always exclude adding a path entry for the root, since the
// root is an implicit node. Paths should always be implicitly relative to
// this workspace root.
for (FileTreeNode node = this; node.getParent() != null; node = node.getParent()) {
pathArray.add(node.getName());
}
pathArray.reverse();
return pathArray;
}
public native final FileTreeNode getParent() /*-{
return this.__parentRef;
}-*/;
/**
* @return The associated rendered {@link TreeNodeElement}. If there is no
* tree node element rendered yet, then {@code null} is returned.
*/
public final native TreeNodeElement<FileTreeNode> getRenderedTreeNode() /*-{
return this.__renderedNode;
}-*/;
/**
* @return the sub directories concatenated with the files list, guaranteed to
* be sorted and is only computed once (and subsequently cached).
*/
@VisibleForTesting
public final JsoArray<FileTreeNode> getUnifiedChildren() {
assert isDirectory() : "Only directories have children!";
enusureUnifiedChildren();
return getUnifiedChildrenImpl();
}
public final boolean isDirectory() {
return getNodeType() == TreeNodeInfo.DIR_TYPE;
}
/**
* Checks whether or not this directory's children have been loaded.
*
* @return true if children have been loaded, false if not
*/
public final boolean isComplete() {
assert isDirectory() : "Only directories can be complete";
DirInfoImpl dirView = this.cast();
return dirView.isComplete();
}
/**
* Checks whether or not the children of this directory have been requested.
*
* @return true if loading, false if not
*/
public final native boolean isLoading() /*-{
return !!this.__isLoading;
}-*/;
public final boolean isFile() {
return getNodeType() == TreeNodeInfo.FILE_TYPE;
}
/**
* Removes a child node.
*/
public final void removeChild(FileTreeNode child) {
assert (isDirectory()) : "I am not a directory!";
if (child.isDirectory()) {
removeChild(child.getName(), this.<DirInfoImpl>cast().getSubDirectories());
} else {
removeChild(child.getName(), this.<DirInfoImpl>cast().getFiles());
}
invalidateUnifiedChildrenCache();
}
/**
* Removes a node from the subDirectories list that has the same name as the
* specified targetName.
*/
public final void removeChild(String targetName, JsonArray<? extends TreeNodeInfo> children) {
assert (isDirectory()) : "I am not a directory!";
for (int i = 0, n = children.size(); i < n; i++) {
if (targetName.equals(children.get(i).getName())) {
children.remove(i);
return;
}
}
}
/**
* Patches the tree rooted at the current node with an incoming directory sent
* from the server.
*
* We actually replace the current node in the tree with the incoming node by
* walking up one directory and replacing the entry in the subDirectories
* collection.
*
* This method is a no-op if the current node is the workspace root.
*/
public final void replaceWith(FileTreeNode newNode) {
FileTreeNode parent = getParent();
if (parent == null) {
return;
}
installBackRef(parent.<DirInfoImpl>cast(), newNode);
parent.removeChild(this);
parent.addChild(newNode);
parent.invalidateUnifiedChildrenCache();
}
/**
* Specifies whether or not this directory's children have been requested.
*/
public final native void setLoading(boolean isLoading) /*-{
this.__isLoading = isLoading;
}-*/;
/**
* Associates this FileTreeNode with the supplied {@link TreeNodeElement} as
* the rendered node in the tree. This allows us to go from model -> rendered
* tree element in order to reflect model mutations in the tree.
*/
public final native void setRenderedTreeNode(TreeNodeElement<FileTreeNode> renderedNode) /*-{
this.__renderedNode = renderedNode;
}-*/;
final native boolean hasUnifiedChildren() /*-{
return !!this.__childrenCache;
}-*/;
final native void invalidateUnifiedChildrenCache() /*-{
this.__childrenCache = null;
}-*/;
private native void cacheUnifiedChildren(JsoArray<FileTreeNode> children) /*-{
this.__childrenCache = children;
}-*/;
/**
* Sorts the directory and file children arrays (in place), and then caches
* the concatenation of the two.
*/
private void enusureUnifiedChildren() {
assert isDirectory() : "Only directories have children!";
if (!hasUnifiedChildren()) {
DirInfoImpl dirView = this.cast();
JsoArray<DirInfo> dirs = (JsoArray<DirInfo>) dirView.getSubDirectories();
JsoArray<FileInfo> files = (JsoArray<FileInfo>) dirView.getFiles();
dirs.sort(dirSortFunction);
files.sort(fileSortFunction);
cacheUnifiedChildren(JsoArray.concat(dirs, files).<JsoArray<FileTreeNode>>cast());
}
}
private native JsoArray<FileTreeNode> getUnifiedChildrenImpl() /*-{
return this.__childrenCache;
}-*/;
}
| 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/collide/client/filetree/FileTreeNodeMoveController.java | client/src/main/java/collide/client/filetree/FileTreeNodeMoveController.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import collide.client.filetree.FileTreeUiController.DragDropListener;
import collide.client.treeview.SelectionModel;
import com.google.collide.client.AppContext;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.WorkspaceReadOnlyChangedEvent;
import com.google.collide.dto.EmptyMessage;
import com.google.collide.dto.Mutation;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.WorkspaceTreeUpdate;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.json.client.JsoArray;
import com.google.common.annotations.VisibleForTesting;
import elemental.js.html.JsDragEvent;
/**
* A controller to manage the in-tree drag and drop.
* <p>
* Dragging started outside file tree is not handled here.
*/
public class FileTreeNodeMoveController implements WorkspaceReadOnlyChangedEvent.Handler {
// TODO: Change to custom format (such as
// "application/collide-nodes-move-started") once Chrome supports it.
private static final String MOVE_START_INDICATOR_FORMAT = "text/plain";
private static final String MOVE_START_INDICATOR = "NODES_MOVE_STARTED";
private final FileTreeUiController fileTreeUiController;
private boolean isReadOnly;
private final JsoArray<FileTreeNode> nodesToMove = JsoArray.create();
private final AppContext appContext;
private final FileTreeModel fileTreeModel;
public FileTreeNodeMoveController(AppContext appContext,
FileTreeUiController fileTreeUiController, FileTreeModel fileTreeModel) {
this.appContext = appContext;
this.fileTreeUiController = fileTreeUiController;
this.fileTreeModel = fileTreeModel;
attachEventHandlers();
}
private void attachEventHandlers() {
if (fileTreeUiController == null) {
return;
}
fileTreeUiController.setFileTreeNodeMoveListener(new DragDropListener() {
@Override
public void onDragDrop(FileTreeNode node, JsDragEvent event) {
event.getDataTransfer().clearData(MOVE_START_INDICATOR_FORMAT);
if (isReadOnly || !wasDragInTree(event)) {
return;
}
handleMove(node);
nodesToMove.clear();
}
@Override
public void onDragStart(FileTreeNode node, JsDragEvent event) {
// Save the selected nodes. Users may drop them in tree.
saveSelectedNodesOrParam(node);
// TODO: once Chrome supports dataTransfer.addElement, add
// nodesToMove to provide move feedback.
event.getDataTransfer().setData(MOVE_START_INDICATOR_FORMAT, MOVE_START_INDICATOR);
}
});
}
@Override
public void onWorkspaceReadOnlyChanged(WorkspaceReadOnlyChangedEvent event) {
isReadOnly = event.isReadOnly();
}
public static boolean wasDragInTree(JsDragEvent event) {
return MOVE_START_INDICATOR.equals(
event.getDataTransfer().getData(MOVE_START_INDICATOR_FORMAT));
}
private void saveSelectedNodesOrParam(FileTreeNode node) {
nodesToMove.clear();
SelectionModel<FileTreeNode> selectionModel =
fileTreeUiController.getTree().getSelectionModel();
JsoArray<FileTreeNode> selectedNodes = selectionModel.getSelectedNodes();
if (selectedNodes.contains(node)) {
// Drag is starting from one of the selected nodes.
// We move all selected nodes.
nodesToMove.addAll(selectedNodes);
} else {
// Drag is starting outside all selected nodes.
// We only move the drag-start-node.
nodesToMove.add(node);
}
}
/**
* For test only.
*/
@VisibleForTesting
void setNodesToMove(JsoArray<FileTreeNode> nodesToMove) {
this.nodesToMove.clear();
this.nodesToMove.addAll(nodesToMove);
}
@VisibleForTesting
boolean isMoveAllowed(FileTreeNode parentDirData) {
// File should not be moved to its original place, i.e., /a/b/1.js ==> under
// /a/b
// Folder should not be moved to its original place and to under itself or
// under any of its subfolders, i.e., /a/b/c ==> under /a/b, under /a/b/c,
// under /a/b/c/d.
for (int i = 0, n = nodesToMove.size(); i < n; i++) {
FileTreeNode nodeToMove = nodesToMove.get(i);
if (nodeToMove.isFile()) {
if (nodeToMove.getParent().getNodePath().equals(parentDirData.getNodePath())) {
return false;
}
} else {
// is folder.
// source folder won't be root, so it has parent.
if (nodeToMove.getParent().getNodePath().equals(parentDirData.getNodePath())) {
return false;
}
if (nodeToMove.getNodePath().containsPath(parentDirData.getNodePath())) {
return false;
}
}
}
return true;
}
private void handleMove(FileTreeNode parentDirData) {
if (nodesToMove.isEmpty()) {
return;
}
// Check each selected node to make sure it can be moved.
if (!isMoveAllowed(parentDirData)) {
return;
}
WorkspaceTreeUpdate msg = fileTreeModel.makeEmptyTreeUpdate();
for (int i = 0, n = nodesToMove.size(); i < n; i++) {
FileTreeNode nodeToMove = nodesToMove.get(i);
PathUtil targetPath = new PathUtil.Builder().addPath(parentDirData.getNodePath())
.addPathComponent(FileTreeUtils.allocateName(
parentDirData.<DirInfoImpl>cast(), nodeToMove.getName())).build();
msg.getMutations().add(FileTreeUtils.makeMutation(Mutation.Type.MOVE,
nodeToMove.getNodePath(), targetPath, nodeToMove.isDirectory(),
nodeToMove.getFileEditSessionKey()));
}
appContext.getFrontendApi().MUTATE_WORKSPACE_TREE.send(
msg, new ApiCallback<EmptyMessage>() {
@Override
public void onMessageReceived(EmptyMessage message) {
// Do nothing. We lean on the multicasted MOVE to have the action
// update our local model.
}
@Override
public void onFail(FailureReason reason) {
// Do nothing.
}
});
}
public void cleanup() {
fileTreeUiController.setFileTreeNodeMoveListener(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/collide/client/filetree/FileTreeNodeRenderer.java | client/src/main/java/collide/client/filetree/FileTreeNodeRenderer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import collide.client.common.CommonResources;
import collide.client.treeview.NodeRenderer;
import collide.client.treeview.Tree;
import collide.client.treeview.TreeNodeElement;
import collide.client.treeview.TreeNodeMutator;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.workspace.WorkspaceUtils;
import com.google.collide.dto.DirInfo;
import com.google.collide.json.client.JsoStringMap;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.MouseEvent;
import elemental.html.AnchorElement;
import elemental.html.SpanElement;
/**
* Renderer for nodes in the file tree.
*/
public class FileTreeNodeRenderer implements NodeRenderer<FileTreeNode> {
public static FileTreeNodeRenderer create(Resources res) {
return new FileTreeNodeRenderer(res);
}
public static interface Css extends TreeNodeMutator.Css {
String file();
String cssIcon();
String emptyFolder();
String emptyPackageIcon();
String folder();
String htmlIcon();
String jarIcon();
String javaIcon();
String javascriptIcon();
String xmlIcon();
String packageIcon();
String folderOpen();
String folderLoading();
String icon();
String label();
String root();
@Override
String nodeNameInput();
}
public static interface Resources extends CommonResources.BaseResources, Tree.Resources {
@Source({"FileTreeNodeRenderer.css", "collide/client/common/constants.css"})
Css workspaceNavigationFileTreeNodeRendererCss();
}
/**
* Renders the given information as a node.
* @param fileTypes
* @param b
*
* @param mouseDownListener an optional listener to be attached to the anchor. If not given, the
* label will not be an anchor.
*/
public static SpanElement renderNodeContents(
Css css, String name, boolean isFile, boolean isPackage, JsoStringMap<String> fileTypes, EventListener mouseDownListener, boolean renderIcon) {
SpanElement root = Elements.createSpanElement(css.root());
if (renderIcon) {
SpanElement icon = Elements.createSpanElement(css.icon());
if (isFile) {
String clsName = css.file();
int ind = name.lastIndexOf('.');
if (ind > -1) {
String type = name.substring(ind+1);
if (fileTypes.containsKey(type)) {
clsName = fileTypes.get(type);
}
}
icon.addClassName(clsName);
} else {
if (isPackage) {
icon.addClassName(css.packageIcon());
} else {
icon.addClassName(css.folder());
}
}
root.appendChild(icon);
}
final Element label;
if (mouseDownListener != null) {
label = Elements.createAnchorElement(css.label());
((AnchorElement) label).setHref("javascript:;");
label.addEventListener(Event.MOUSEDOWN, mouseDownListener, false);
} else {
label = Elements.createSpanElement(css.label());
}
label.setTextContent(name);
root.appendChild(label);
return root;
}
private final EventListener mouseDownListener = new EventListener() {
@Override
public void handleEvent(Event evt) {
MouseEvent event = (MouseEvent) evt;
AnchorElement anchor = (AnchorElement) evt.getTarget();
if (event.getButton() == MouseEvent.Button.AUXILIARY) {
Element parent = CssUtils.getAncestorOrSelfWithClassName(anchor, res.treeCss().treeNode());
if (parent != null) {
@SuppressWarnings("unchecked")
TreeNodeElement<FileTreeNode> fileNode = (TreeNodeElement<FileTreeNode>) parent;
anchor.setHref(
WorkspaceUtils.createDeepLinkToFile(fileNode.getData().getNodePath()));
}
}
}
};
private final Css css;
private final Resources res;
private final JsoStringMap<String> fileTypes;
private FileTreeNodeRenderer(Resources resources) {
this.res = resources;
this.css = res.workspaceNavigationFileTreeNodeRendererCss();
fileTypes = createFileTypeMap(css);
}
public static JsoStringMap<String> createFileTypeMap(Css css) {
JsoStringMap<String> fileTypes = JsoStringMap.create();
fileTypes.put("css", css.cssIcon());
fileTypes.put("html", css.htmlIcon());
fileTypes.put("jar", css.jarIcon());
fileTypes.put("java", css.javaIcon());
fileTypes.put("js", css.javascriptIcon());
fileTypes.put("xml", css.xmlIcon());
return fileTypes;
}
@Override
public Element getNodeKeyTextContainer(SpanElement treeNodeLabel) {
return (Element) treeNodeLabel.getChildNodes().item(1);
}
@Override
public SpanElement renderNodeContents(FileTreeNode data) {
if (data.isDirectory()) {
DirInfo dir = (DirInfo) data;
return renderNodeContents(css, data.getName(), data.isFile(), dir.isPackage(), fileTypes, mouseDownListener, true);
} else {
return renderNodeContents(css, data.getName(), data.isFile(), false, fileTypes, mouseDownListener, true);
}
}
@Override
public void updateNodeContents(TreeNodeElement<FileTreeNode> treeNode) {
if (treeNode.getData().isDirectory()) {
// Update folder icon based on icon state.
Element icon = treeNode.getNodeLabel().getFirstChildElement();
icon.setClassName(css.icon());
if (treeNode.getData().isLoading()) {
icon.addClassName(css.folderLoading());
} else if (((DirInfo)treeNode.getData()).isPackage()) {
icon.addClassName(css.packageIcon());
} else if (treeNode.isOpen()) {
icon.addClassName(css.folderOpen());
} else {
icon.addClassName(css.folder());
}
}
}
}
| 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/collide/client/filetree/FileTreeUtils.java | client/src/main/java/collide/client/filetree/FileTreeUtils.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.Mutation;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.MutationImpl;
import com.google.collide.dto.client.DtoClientImpls.TreeNodeInfoImpl;
import com.google.collide.json.shared.JsonArray;
/**
* Utility methods for file tree.
*
*/
public class FileTreeUtils {
private FileTreeUtils() {
}
/**
* Allocates a name String that is guaranteed not to exist in the children of
* the specified DirInfo.
*
* @param parentDir the directory we will be scanning.
* @param seedName the initial name we want to try to use.
*/
static String allocateName(DirInfo parentDir, String seedName) {
if (parentDir == null) {
return seedName;
}
String uniqueName = ensureUniqueChildName(parentDir.getSubDirectories(), seedName);
return ensureUniqueChildName(parentDir.getFiles(), uniqueName);
}
private static String ensureUniqueChildName(
JsonArray<? extends TreeNodeInfo> children, String seedName) {
String uniqueName = null;
boolean foundUnique = false;
int retryNumber = 0;
while (!foundUnique) {
// Generate a name to try.
uniqueName = (retryNumber > 0) ? generateName(seedName, retryNumber) : seedName;
// Test the name.
foundUnique = isNameUnique(children, null, uniqueName);
retryNumber++;
}
return uniqueName;
}
private static String generateName(String name, int retryNumber) {
int dotIndex = name.indexOf('.');
dotIndex = (dotIndex == -1) ? name.length() : dotIndex;
String base = name.substring(0, dotIndex);
// This will either be the extension including the '.', or the empty String
// if dotIndex is == to the size of the String.
String extension = name.substring(dotIndex, name.length());
return base + "(" + retryNumber + ")" + extension;
}
/**
* Test if there is a sibling node (file or directory) with specified name.
*
* <p>
* Specified node (whose siblings are checked) itself is not checked.
*/
static boolean hasNoPeerWithName(FileTreeNode nodeToCheck, String name) {
DirInfoImpl parentDir = nodeToCheck.getParent().cast();
return isNameUnique(parentDir.getSubDirectories(), nodeToCheck, name) && isNameUnique(
parentDir.getFiles(), nodeToCheck, name);
}
private static boolean isNameUnique(
JsonArray<? extends TreeNodeInfo> children, FileTreeNode nodeToCheck, String name) {
for (int i = 0, n = children.size(); i < n; i++) {
FileTreeNode child = (FileTreeNode) children.get(i);
if (child != nodeToCheck && name.equals(child.getName())) {
// Whoops. We collided.
return false;
}
}
return true;
}
static Mutation makeMutation(Mutation.Type mutatonType, PathUtil oldPath, PathUtil newPath,
boolean isDirectory, String resourceId) {
// We make a placeholder for the new node solely to install information
// about whether or not this is a directory.
TreeNodeInfoImpl placeHolderNode = TreeNodeInfoImpl.make().setNodeType(
isDirectory ? TreeNodeInfo.DIR_TYPE
: TreeNodeInfo.FILE_TYPE).setFileEditSessionKey(resourceId);
return MutationImpl.make()
.setMutationType(mutatonType)
.setNewNodeInfo(placeHolderNode)
.setOldPath(oldPath == null ? null : oldPath.getPathString())
.setNewPath(newPath == null ? null : newPath.getPathString());
}
}
| 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/collide/client/filetree/FileTreeController.java | client/src/main/java/collide/client/filetree/FileTreeController.java | package collide.client.filetree;
import com.google.collide.client.code.FileTreeSection;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.ui.dropdown.DropdownWidgets;
import com.google.collide.client.ui.tooltip.Tooltip;
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.WorkspaceTreeUpdate;
public interface FileTreeController
<R extends
DropdownWidgets.Resources &
Tooltip.Resources &
FileTreeNodeRenderer.Resources &
FileTreeSection.Resources> {
R getResources();
void mutateWorkspaceTree(WorkspaceTreeUpdate msg, ApiCallback<EmptyMessage> apiCallback);
StatusManager getStatusManager();
void getDirectory(
GetDirectory getDirectoryAndPath,
ApiCallback<GetDirectoryResponse> apiCallback
);
MessageFilter getMessageFilter();
void getFileContents(
GetFileContents getFileContents,
ApiCallback<GetFileContentsResponse> apiCallback
);
}
| 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/collide/client/filetree/FileTreeModel.java | client/src/main/java/collide/client/filetree/FileTreeModel.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.filetree;
import javax.annotation.Nullable;
import collide.client.filetree.FileTreeModelNetworkController.OutgoingController;
import collide.client.treeview.TreeNodeElement;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.Mutation;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.WorkspaceTreeUpdate;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.WorkspaceTreeUpdateImpl;
import com.google.collide.json.client.JsoArray;
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;
/**
* Public API for interacting with the client side workspace file tree model.
* Also exposes callbacks for mutations that have been applied to the model.
*
* If you want to mutate the workspace file tree, which is a tree of
* {@link FileTreeNode}'s you need to go through here.
*/
public class FileTreeModel {
/**
* Callback interface for requesting the root node, potentially
* asynchronously.
*/
public interface RootNodeRequestCallback {
void onRootNodeAvailable(FileTreeNode root);
}
/**
* Callback interface for requesting a node, potentially asynchronously.
*/
public interface NodeRequestCallback {
void onNodeAvailable(FileTreeNode node);
/**
* Called if the node does not exist.
*/
void onNodeUnavailable();
/**
* Called if an error occurs while loading the node.
*/
void onError(FailureReason reason);
}
/**
* Callback interface for getting notified about changes to the workspace tree
* model that have been applied by the FileTreeController.
*/
public interface TreeModelChangeListener {
/**
* Notification that a node was added.
*/
void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode);
/**
* Notification that a node was moved/renamed.
*
* @param oldPath the old node path
* @param node the node that was moved, or null if the old path is not loaded. If both the old
* path and the new path are loaded, node == newNode and node's parent will be the target
* directory of the new path. If the new path is not loaded, node is the node that was in
* the old path.
* @param newPath the new node path
* @param newNode the new node, or null if the target directory is not loaded
*/
void onNodeMoved(PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode);
/**
* Notification that a set of nodes was removed.
*
* @param oldNodes a list of nodes that we removed. Every node will still have its parent filled
*/
void onNodesRemoved(JsonArray<FileTreeNode> oldNodes);
/**
* Notification that a node was replaced (can be either a file or directory).
*
* @param oldNode the existing node that used to be in the file tree, or null if the workspace
* root is being set for the first time
* @param newNode the node that replaces the {@code oldNode}. This will be the same
* {@link FileTreeNode#getNodeType()} as the node it is replacing.
*/
void onNodeReplaced(@Nullable FileTreeNode oldNode, FileTreeNode newNode);
}
/**
* A {@link TreeModelChangeListener} which does not perform any operations in
* response to an event. Its only purpose is to allow clients to only override
* the events matter to them.
*/
public abstract static class AbstractTreeModelChangeListener implements TreeModelChangeListener {
@Override
public void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode) {
// intentional no-op, clients should override if needed
}
@Override
public void onNodeMoved(
PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode) {
// intentional no-op, clients should override if needed
}
@Override
public void onNodesRemoved(JsonArray<FileTreeNode> oldNodes) {
// intentional no-op, clients should override if needed
}
@Override
public void onNodeReplaced(FileTreeNode oldDir, FileTreeNode newDir) {
// intentional no-op, clients should override if needed
}
}
/**
* A {@link TreeModelChangeListener} that performs the exact same action in
* response to any and all tree mutations.
*/
public abstract static class BasicTreeModelChangeListener implements TreeModelChangeListener {
public abstract void onTreeModelChange();
@Override
public void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode) {
onTreeModelChange();
}
@Override
public void onNodeMoved(
PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode) {
onTreeModelChange();
}
@Override
public void onNodesRemoved(JsonArray<FileTreeNode> oldNodes) {
onTreeModelChange();
}
@Override
public void onNodeReplaced(FileTreeNode oldDir, FileTreeNode newDir) {
onTreeModelChange();
}
}
private interface ChangeDispatcher {
void dispatch(TreeModelChangeListener changeListener);
}
private final JsoArray<TreeModelChangeListener> modelChangeListeners = JsoArray.create();
private final OutgoingController outgoingNetworkController;
private FileTreeNode workspaceRoot;
private boolean disableChangeNotifications;
/**
* Tree revision that corresponds to the revision of the last
* successfully applied tree mutation that this client is aware of.
*/
private String lastAppliedTreeMutationRevision = "0";
public FileTreeModel(
FileTreeModelNetworkController.OutgoingController outgoingNetworkController) {
this.outgoingNetworkController = outgoingNetworkController;
}
/**
* Adds a node to our model by path.
*/
public void addNode(PathUtil path, final FileTreeNode newNode, String workspaceRootId) {
if (workspaceRoot == null) {
// TODO: queue up this add?
Log.warn(getClass(), "Attempting to add a node before the root is set", path);
return;
}
// Find the parent directory of the node.
final PathUtil parentDirPath = PathUtil.createExcludingLastN(path, 1);
FileTreeNode parentDir = getWorkspaceRoot().findChildNode(parentDirPath);
if (parentDir != null && parentDir.isComplete()) {
// The parent directory is complete, so add the node.
addNode(parentDir, newNode, workspaceRootId);
} else {
// The parent directory isn't complete, so do not add the node to the model, but update the
// workspace root id.
maybeSetLastAppliedTreeMutationRevision(workspaceRootId);
}
}
/**
* Adds a node to the model under the specified parent node.
*/
public void addNode(FileTreeNode parentDir, FileTreeNode childNode, String workspaceRootId) {
addNodeNoDispatch(parentDir, childNode);
dispatchAddNode(parentDir, childNode, workspaceRootId);
}
private void addNodeNoDispatch(final FileTreeNode parentDir, final FileTreeNode childNode) {
if (parentDir == null) {
Log.error(getClass(), "Trying to add a child to a null parent!", childNode);
return;
}
Log.debug(getClass(), "Adding ", childNode, " - to - ", parentDir);
parentDir.addChild(childNode);
}
/**
* Manually dispatch that a node was added.
*/
void dispatchAddNode(
final FileTreeNode parentDir, final FileTreeNode childNode, final String workspaceRootId) {
dispatchModelChange(new ChangeDispatcher() {
@Override
public void dispatch(TreeModelChangeListener changeListener) {
changeListener.onNodeAdded(parentDir.getNodePath(), childNode);
}
}, workspaceRootId);
}
/**
* Moves/renames a node in the model.
*/
public void moveNode(
final PathUtil oldPath, final PathUtil newPath, final String workspaceRootId) {
if (workspaceRoot == null) {
// TODO: queue up this move?
Log.warn(getClass(), "Attempting to move a node before the root is set", oldPath);
return;
}
// Remove the node from its old path if the old directory is complete.
final FileTreeNode oldNode = workspaceRoot.findChildNode(oldPath);
if (oldNode == null) {
/*
* No node found at the old path - either it isn't loaded, or we optimistically updated
* already. Verify that one of those is the case.
*/
Preconditions.checkState(workspaceRoot.findClosestChildNode(oldPath) != null ||
workspaceRoot.findChildNode(newPath) != null);
} else {
oldNode.setName(newPath.getBaseName());
oldNode.getParent().removeChild(oldNode);
}
// Apply the new root id.
maybeSetLastAppliedTreeMutationRevision(workspaceRootId);
// Prepare a callback that will dispatch the onNodeMove event to listeners.
NodeRequestCallback callback = new NodeRequestCallback() {
@Override
public void onNodeAvailable(FileTreeNode newNode) {
/*
* If we had to request the target directory, replace the target node with the oldNode to
* ensure that all properties (such as the rendered node and the fileEditSessionKey) are
* copied over correctly.
*/
if (oldNode != null && newNode != null && newNode != oldNode) {
newNode.replaceWith(oldNode);
newNode = oldNode;
}
// Dispatch a change event.
final FileTreeNode finalNewNode = newNode;
dispatchModelChange(new ChangeDispatcher() {
@Override
public void dispatch(TreeModelChangeListener changeListener) {
changeListener.onNodeMoved(oldPath, oldNode, newPath, finalNewNode);
}
}, workspaceRootId);
}
@Override
public void onNodeUnavailable() {
// The node should be available because we are requesting the node using the root ID
// immediately after the move.
Log.error(getClass(),
"Could not find moved node using the workspace root ID immediately after the move");
}
@Override
public void onError(FailureReason reason) {
// Error already logged.
}
};
// Request the target directory.
final PathUtil parentDirPath = PathUtil.createExcludingLastN(newPath, 1);
FileTreeNode parentDir = workspaceRoot.findChildNode(parentDirPath);
if (parentDir == null || !parentDir.isComplete()) {
if (oldNode == null) {
// Early exit if neither the old node nor the target directory is loaded.
return;
} else {
// If the parent directory was not loaded, don't bother loading it.
callback.onNodeAvailable(null);
}
} else {
if (oldNode == null) {
// The old node doesn't exist, so we need to force a refresh of the target directory's
// children by marking the target directory incomplete.
DirInfoImpl parentDirView = parentDir.cast();
parentDirView.setIsComplete(false);
} else {
// The old node exists and the target directory is loaded, so add the node to the target.
parentDir.addChild(oldNode);
}
// Request the new node.
requestWorkspaceNode(newPath, callback);
}
}
/**
* Removes a node from the model.
*
* @param toDelete the {@link FileTreeNode} we want to remove.
* @param workspaceRootId the new file tree revision
* @return the node that was deleted from the model. This will return
* {@code null} if the input node is null or if the input node does
* not have a parent. Meaning if the input node is the root, this
* method will return {@code null}.
*/
public FileTreeNode removeNode(final FileTreeNode toDelete, String workspaceRootId) {
// If we found a node at the specified path, then remove it.
if (deleteNodeNoDispatch(toDelete)) {
final JsonArray<FileTreeNode> deletedNode = JsonCollections.createArray(toDelete);
dispatchModelChange(new ChangeDispatcher() {
@Override
public void dispatch(TreeModelChangeListener changeListener) {
changeListener.onNodesRemoved(deletedNode);
}
}, workspaceRootId);
return toDelete;
}
return null;
}
/**
* Removes a set of nodes from the model.
*
* @param toDelete the {@link PathUtil}s for the nodes we want to remove.
* @param workspaceRootId the new file tree revision
* @return the nodes that were deleted from the model. This will return an
* empty list if we try to add a node before we have a root node set,
* or if the specified path does not exist..
*/
public JsonArray<FileTreeNode> removeNodes(
final JsonArray<PathUtil> toDelete, String workspaceRootId) {
if (workspaceRoot == null) {
// TODO: queue up this remove?
Log.warn(getClass(), "Attempting to remove nodes before the root is set");
return null;
}
final JsonArray<FileTreeNode> deletedNodes = JsonCollections.createArray();
for (int i = 0; i < toDelete.size(); i++) {
FileTreeNode node = workspaceRoot.findChildNode(toDelete.get(i));
if (deleteNodeNoDispatch(node)) {
deletedNodes.add(node);
}
}
if (deletedNodes.size() == 0) {
// if none of the nodes created a need to update the UI, just return an
// empty list.
return deletedNodes;
}
dispatchModelChange(new ChangeDispatcher() {
@Override
public void dispatch(TreeModelChangeListener changeListener) {
changeListener.onNodesRemoved(deletedNodes);
}
}, workspaceRootId);
return deletedNodes;
}
/**
* Deletes a single node (does not update the UI).
*/
private boolean deleteNodeNoDispatch(FileTreeNode node) {
if (node == null || node.getParent() == null) {
return false;
}
FileTreeNode parent = node.getParent();
// Guard against someone installing a node of the same name in the parent
// (meaning we are already gone.
if (!node.equals(parent.getChildNode(node.getName()))) {
// This means that the node we are removing from the tree is already
// effectively removed from where it thinks it is.
return false;
}
node.getParent().removeChild(node);
return true;
}
/**
* Replaces either the root node for this tree model, or replaces an existing directory node, or
* replaces an existing file node.
*/
public void replaceNode(PathUtil path, final FileTreeNode newNode, String workspaceRootId) {
if (newNode == null) {
return;
}
if (PathUtil.WORKSPACE_ROOT.equals(path)) {
// Install the workspace root.
final FileTreeNode oldDir = workspaceRoot;
workspaceRoot = newNode;
dispatchModelChange(new ChangeDispatcher() {
@Override
public void dispatch(TreeModelChangeListener changeListener) {
changeListener.onNodeReplaced(oldDir, newNode);
}
}, workspaceRootId);
} else {
// Patch the model if there is one.
if (workspaceRoot != null) {
final FileTreeNode nodeToReplace = workspaceRoot.findChildNode(path);
// Note. We do not support patching subtrees that don't already
// exist. This subtree must have already existed, or have been
// preceded by an ADD or COPY mutation.
if (nodeToReplace == null) {
return;
}
nodeToReplace.replaceWith(newNode);
dispatchModelChange(new ChangeDispatcher() {
@Override
public void dispatch(TreeModelChangeListener changeListener) {
changeListener.onNodeReplaced(nodeToReplace, newNode);
}
}, workspaceRootId);
}
}
}
/**
* @return the current value of the workspaceRoot. Potentially {@code null} if
* the model has not yet been populated.
*/
public FileTreeNode getWorkspaceRoot() {
return workspaceRoot;
}
/**
* Asks for the root node, potentially asynchronously if the model is not yet
* populated. If the root node is already available then the callback will be
* invoked synchronously.
*/
public void requestWorkspaceRoot(final RootNodeRequestCallback callback) {
FileTreeNode rootNode = getWorkspaceRoot();
if (rootNode == null) {
// Wait for the model to be populated.
addModelChangeListener(new AbstractTreeModelChangeListener() {
@Override
public void onNodeReplaced(FileTreeNode oldNode, FileTreeNode newNode) {
Preconditions.checkArgument(newNode.getNodePath().equals(PathUtil.WORKSPACE_ROOT),
"Unexpected non-workspace root subtree replaced before workspace root was replaced: "
+ newNode.toString());
// Should be resilient to concurrent modification!
removeModelChangeListener(this);
callback.onRootNodeAvailable(getWorkspaceRoot());
}
});
return;
}
callback.onRootNodeAvailable(rootNode);
}
/**
* Adds a {@link TreeModelChangeListener} to be notified of mutations applied
* by the FileTreeController to the underlying workspace file tree model.
*
* @param modelChangeListener the listener we are adding
*/
public void addModelChangeListener(TreeModelChangeListener modelChangeListener) {
modelChangeListeners.add(modelChangeListener);
}
/**
* Removes a {@link TreeModelChangeListener} from the set of listeners
* subscribed to model changes.
*/
public void removeModelChangeListener(TreeModelChangeListener modelChangeListener) {
modelChangeListeners.remove(modelChangeListener);
}
public void setDisableChangeNotifications(boolean disable) {
this.disableChangeNotifications = disable;
}
private void dispatchModelChange(ChangeDispatcher dispatcher, String workspaceRootId) {
// Update the tracked tip ID.
maybeSetLastAppliedTreeMutationRevision(workspaceRootId);
if (disableChangeNotifications) {
return;
}
JsoArray<TreeModelChangeListener> copy = modelChangeListeners.slice(
0, modelChangeListeners.size());
for (int i = 0, n = copy.size(); i < n; i++) {
dispatcher.dispatch(copy.get(i));
}
}
/**
* @return the file tree revision associated with the last seen Tree mutation.
*/
public String getLastAppliedTreeMutationRevision() {
return lastAppliedTreeMutationRevision;
}
/**
* Bumps the tracked Root ID for the last applied tree mutation, if the
* version happens to be larger than the version we are tracking.
*/
public void maybeSetLastAppliedTreeMutationRevision(String lastAppliedTreeMutationRevision) {
// TODO: Ensure numeric comparison survives ID obfuscation.
try {
long newRevision = StringUtils.toLong(lastAppliedTreeMutationRevision);
long lastRevision = StringUtils.toLong(this.lastAppliedTreeMutationRevision);
this.lastAppliedTreeMutationRevision = (newRevision > lastRevision)
? lastAppliedTreeMutationRevision : this.lastAppliedTreeMutationRevision;
// TODO: this should be monotonically increasing; if it's not, we missed an update.
} catch (NumberFormatException e) {
Log.error(getClass(), "Root ID is not a numeric long!", lastAppliedTreeMutationRevision);
}
}
/**
* Folks that want to mutate the file tree should obtain a skeletal {@link WorkspaceTreeUpdate}
* using this factory method.
*/
public WorkspaceTreeUpdateImpl makeEmptyTreeUpdate() {
if (this.lastAppliedTreeMutationRevision == null) {
throw new IllegalStateException(
"Attempted to mutate the tree before the workspace file tree was loaded at least once!");
}
return WorkspaceTreeUpdateImpl.make()
.setAuthorClientId(BootstrapSession.getBootstrapSession().getActiveClientId())
.setMutations(JsoArray.<Mutation>create());
}
/**
* Calculates the list of expanded paths. The list only contains the paths of the deepest expanded
* directories. Parent directories are assumed to be open as well.
*
* @return the list of expanded paths, or null if the workspace root is not loaded
*/
public JsoArray<String> calculateExpandedPaths() {
// Early exit if the root isn't loaded yet.
if (workspaceRoot == null) {
return null;
}
// Walk the tree looking for expanded paths.
JsoArray<String> expandedPaths = JsoArray.create();
calculateExpandedPathsRecursive(workspaceRoot, expandedPaths);
return expandedPaths;
}
/**
* Calculates the list of expanded paths beneath the specified node and adds them to expanded
* path. If none of the children
*
* @param node the directory containing the expanded paths
* @param expandedPaths the running list of expanded paths
*/
private void calculateExpandedPathsRecursive(FileTreeNode node, JsoArray<String> expandedPaths) {
assert node.isDirectory() : "node must be a directory";
// Check if the directory is expanded. The root is always expanded.
if (node != workspaceRoot) {
TreeNodeElement<FileTreeNode> dirElem = node.getRenderedTreeNode();
if (!dirElem.isOpen()) {
return;
}
}
// Recursively search for expanded subdirectories.
int expandedPathsCount = expandedPaths.size();
DirInfoImpl dir = node.cast();
JsonArray<DirInfo> subDirs = dir.getSubDirectories();
if (subDirs != null) {
for (int i = 0; i < subDirs.size(); i++) {
DirInfo subDir = subDirs.get(i);
calculateExpandedPathsRecursive((FileTreeNode) subDir, expandedPaths);
}
}
// Add this directory if none of its descendants were added.
if (expandedPathsCount == expandedPaths.size()) {
expandedPaths.add(node.getNodePath().getPathString());
}
}
/**
* Asks for the node at the specified path, potentially asynchronously if the model does not yet
* contain the node. If the node is already available then the callback will be invoked
* synchronously.
*
* @param path the path to the node, which must be a file (not a directory)
* @param callback the callback to invoke when the node is ready
*/
public void requestWorkspaceNode(final PathUtil path, final NodeRequestCallback callback) {
outgoingNetworkController.requestWorkspaceNode(this, path, callback);
}
/**
* Asks for the children of the specified node.
*
* @param node a directory node
* @param callback an optional callback that will be notified once the children are fetched. If
* null, this method will alert the user if there was an error
*/
public void requestDirectoryChildren(FileTreeNode node,
@Nullable final NodeRequestCallback callback) {
outgoingNetworkController.requestDirectoryChildren(this, node, callback);
}
}
| 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/collide/client/editor/EditorConfiguration.java | client/src/main/java/collide/client/editor/EditorConfiguration.java | package collide.client.editor;
/**
* This class is a place to control the mode of operation of the editor.
*
* The current implementation is ...very hardcoded together,
* and to inject more easily customizable control,
* we will use this as the master class to expose new versions of internal components,
* to do a more gradual refactoring.
*
* We can (probably) IoC this class out of existence later,
* though it would likely still be handy for quick hardcoded overrides.
*
*
* Created by James X. Nelson (james @wetheinter.net) on 7/4/17.
*/
public interface EditorConfiguration {
EditorToolbar getEditorToolbar();
}
| 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/collide/client/editor/EditorToolbar.java | client/src/main/java/collide/client/editor/EditorToolbar.java | package collide.client.editor;
import com.google.collide.client.util.PathUtil;
import com.google.collide.mvp.ShowableComponent;
import com.google.collide.mvp.ShowableUiComponent;
/**
* Basic interface for the editor toolbar; we are going to move the legacy
* implementation into {@link com.google.collide.client.code.DefaultEditorToolBar},
* so we can plug in something custom for wti/xapi files.
*
*
* Created by James X. Nelson (james @wetheinter.net) on 7/4/17.
*/
public interface EditorToolbar extends ShowableComponent {
ShowableUiComponent<?> asComponent();
void setCurrentPath(PathUtil path, String lastAppliedRevision);
}
| 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/collide/client/editor/MarkupToolbar.java | client/src/main/java/collide/client/editor/MarkupToolbar.java | package collide.client.editor;
import collide.client.util.Elements;
import com.google.collide.client.AppContext;
import com.google.collide.client.code.DefaultEditorToolBar;
import com.google.collide.client.code.EditorBundle;
import com.google.collide.client.code.FileSelectedPlace;
import com.google.collide.client.code.RightSidebarToggleEvent;
import com.google.collide.client.filehistory.FileHistoryPlace;
import com.google.collide.client.history.Place;
import com.google.collide.client.ui.menu.PositionController;
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.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
/**
* Created by James X. Nelson (james @wetheinter.net) on 7/4/17.
*/
public class MarkupToolbar extends ShowableUiComponent<MarkupToolbar.View>
implements EditorToolbar {
private final Place currentPlace;
private final AppContext appContext;
private final EditorBundle editorBundle;
public MarkupToolbar(MarkupToolbar.View view, Place place,
AppContext appContext, EditorBundle bundle) {
super(view);
this.currentPlace = place;
this.appContext = appContext;
this.editorBundle = bundle;
view.setDelegate(new ViewEventsImpl());
}
/**
* The View for the MarkupToolbar.
*/
public static class View extends CompositeView<ViewEvents> {
@UiTemplate("MarkupToolbar.ui.xml") interface MyBinder
extends UiBinder<DivElement, MarkupToolbar.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 DefaultEditorToolBar.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.
PositionController.PositionerBuilder positioner =
new Tooltip.TooltipPositionerBuilder().setHorizontalAlign(
PositionController.HorizontalAlign.RIGHT)
.setPosition(PositionController.Position.OVERLAP);
PositionController.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");
PositionController.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());
}
}
}
/**
* Events reported by the DefaultEditorToolBar's View.
*/
private interface ViewEvents {
void onDebugButtonClicked();
void onHistoryButtonClicked();
}
private class ViewEventsImpl implements ViewEvents {
@Override
public void onHistoryButtonClicked() {
}
@Override
public void onDebugButtonClicked() {
WorkspacePlace.PLACE.fireEvent(new RightSidebarToggleEvent());
}
}
@Override
public ShowableUiComponent<?> asComponent() {
return this;
}
@Override public void setCurrentPath(PathUtil path, String lastAppliedRevision) {
}
@Override public void doShow() {
}
@Override public void doHide() {
}
}
| 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/collide/client/editor/DefaultEditorConfiguration.java | client/src/main/java/collide/client/editor/DefaultEditorConfiguration.java | package collide.client.editor;
/**
* Created by James X. Nelson (james @wetheinter.net) on 7/4/17.
*/
public class DefaultEditorConfiguration implements EditorConfiguration {
@Override public EditorToolbar getEditorToolbar() {
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/collide/client/common/CanRunApplication.java | client/src/main/java/collide/client/common/CanRunApplication.java | package collide.client.common;
import com.google.collide.client.util.PathUtil;
public interface CanRunApplication {
boolean runApplication(PathUtil applicationPath);
}
| 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/collide/client/common/CommonResources.java | client/src/main/java/collide/client/common/CommonResources.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.common;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.resources.client.ImageResource;
/**
* ClientBundle resources that are shared across multiple top level presenters.
*
*/
public class CommonResources {
public interface BaseCss extends CssResource {
/**
* Returns the left and right side padding on buttons.
*/
int buttonHorizontalPadding();
/**
* Applies to internally linking anchor elements.
*/
// TODO: see if this style can be removed after project membership
// flow is reworked (Only place used is the membership requests link).
String anchor();
/**
* The class name to apply to buttons.
*
* Recommended to use an anchor element. Adding <code>
*href = "javascript:;"</code> to the anchor element ensures that
* it triggers a click event when the ENTER key is pressed. This is useful for keyboard
* navigation through a form.
*/
String button();
/**
* A smaller button variant.
*/
String buttonSmall();
/**
* Append this class to the button class to make a blue button.
*/
String buttonBlue();
/**
* Append this class to the button class to make a red button.
*/
String buttonRed();
/**
* Append this class to the button class to make a green button.
*/
String buttonGreen();
/**
* Append this class to an inner button div that is only a
* background image rendered using the @sprite command. This will style it
* like a native img tag inside a button.
*/
String buttonImage();
/**
* Append this class to make the element appear hovered.
*/
String buttonHover();
/**
* Append this class to make the element appear active.
*/
String buttonActive();
/**
* Returns the style to apply to drawer icon buttons, which are used to show sub content.
*/
String drawerIconButton();
/**
* Returns the style to apply to drawer icon buttons that are active.
*/
String drawerIconButtonActive();
/**
* Returns the style to apply to drawer icon buttons that are active, using
* a slightly lighter background if the default active style blends with the
* surrounding contents too much.
*/
String drawerIconButtonActiveLight();
String documentScrollable();
String checkbox();
String radio();
String textArea();
String textInput();
String textInputSmall();
String closeX();
String fileLabelErrorIcon();
String headerBg();
String modalDialogTitle();
String modalDialogMessage();
String searchBox();
String searchBoxInUse();
String downArrow();
/* Tabs */
String tabOuterContainer();
String tabContainer();
String tab();
String activeTab();
}
public interface BaseResources extends ClientBundle {
@Source({"base.css", "collide/client/common/constants.css"})
BaseCss baseCss();
@Source("check_no_box.png")
DataResource checkNoBoxData();
@Source("close_x_icon.png")
ImageResource closeXIcon();
@Source("default_proj_icon.png")
ImageResource defaultProjectIcon();
@Source("disclosure_arrow_dk_grey_down.png")
ImageResource disclosureArrowDkGreyDown();
@Source("disclosure_arrow_lt_grey_down.png")
ImageResource disclosureArrowLtGreyDown();
@Source("file_label_error_icon.png")
ImageResource fileLabelErrorIcon();
@Source("fork_lg_white.png")
ImageResource forkIconLgWhite();
@Source("fork_sm_off.png")
ImageResource forkIconOff();
@Source("fork_sm_on.png")
ImageResource forkIconOn();
@Source("logo.png")
ImageResource logo();
@Source("add_plus.png")
ImageResource addPlus();
@Source("cancel.png")
ImageResource cancel();
@Source("search.png")
ImageResource search();
@Source("file.png")
ImageResource file();
@Source("folder.png")
ImageResource folder();
@Source("folder_open.png")
ImageResource folderOpen();
@Source("folder_loading.gif")
ImageResource folderLoading();
@Source("pageDown.png")
ImageResource pageDownArrow();
@Source("pageUp.png")
ImageResource pageUpArrow();
@Source("gear_flower.png")
ImageResource settingsIcon();
@Source("snapshot_camera.png")
ImageResource snapshotCamera();
@Source("wrench.png")
ImageResource wrench();
}
}
| 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/collide/client/common/Constants.java | client/src/main/java/collide/client/common/Constants.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.common;
import collide.client.util.BrowserUtils;
/**
* Constants that we can use in CssResource expressions.
*/
public final class Constants {
public static final int SCROLLBAR_SIZE = BrowserUtils.isFirefox() ? 17 : 16;
/**
* A timer delay for actions that happen after a "hover" period.
*/
public static final int MOUSE_HOVER_DELAY = 600;
private Constants() {} // 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/collide/client/treeview/Tree.java | client/src/main/java/collide/client/treeview/Tree.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.treeview;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import org.waveprotocol.wave.client.common.util.SignalEventImpl;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.util.AnimationController;
import com.google.collide.client.util.dom.MouseGestureListener;
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.Duration;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
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.user.client.Timer;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.MouseEvent;
import elemental.js.dom.JsElement;
import elemental.js.html.JsDragEvent;
/**
* A tree widget that is capable of rendering any tree data structure whose node
* data type is specified in the class parameterization.
*
* Users of this widget must specify an appropriate
* {@link collide.client.treeview.NodeDataAdapter} and
* {@link collide.client.treeview.NodeRenderer}.
*
* The DOM structure for a tree is a recursive structure of the following form
* (note that class names will be obfuscated at runtime, and are just specified
* in human readable form for documentation purposes):
*
* <pre>
*
* <ul class="treeRoot childrenContainer">
* <li class="treeNode">
* <div class="treeNodeBody">
* <div class="expandControl"></div>
* <span class="treeNodeContents"></span>
* </div>
* <ul class="childrenContainer">
* ...
* ...
* </ul>
* </li>
* </ul>
*
* </pre>
*/
public class Tree<D> extends UiComponent<Tree.View<D>> {
/**
* Static factory method for obtaining an instance of the Tree.
*/
public static <NodeData> Tree<NodeData> create(View<NodeData> view,
NodeDataAdapter<NodeData> dataAdapter, NodeRenderer<NodeData> nodeRenderer,
Resources resources) {
Model<NodeData> model = new Model<NodeData>(dataAdapter, nodeRenderer, resources);
return new Tree<NodeData>(view, model);
}
/**
* BaseCss selectors applied to DOM elements in the tree.
*/
public interface Css extends CssResource {
String active();
String childrenContainer();
String closedIcon();
String expandControl();
String isDropTarget();
String leafIcon();
String openedIcon();
String selected();
String treeNode();
String treeNodeBody();
String treeNodeLabel();
String treeRoot();
}
/**
* Listener interface for being notified about tree events.
*/
public interface Listener<D> {
void onNodeAction(TreeNodeElement<D> node);
void onNodeClosed(TreeNodeElement<D> node);
void onNodeContextMenu(int mouseX, int mouseY, TreeNodeElement<D> node);
void onNodeDragStart(TreeNodeElement<D> node, JsDragEvent event);
void onNodeDragDrop(TreeNodeElement<D> node, JsDragEvent event);
void onNodeExpanded(TreeNodeElement<D> node);
void onRootContextMenu(int mouseX, int mouseY);
void onRootDragDrop(JsDragEvent event);
}
/**
* A visitor interface to visit nodes of the tree.
*/
public interface Visitor<D> {
/**
* @return whether to visit a given node. This is useful to prune a subtree
* from being visited
*/
boolean shouldVisit(D node);
/**
* Called for nodes that pass the {@link #shouldVisit} check.
*
* @param node the node being iterated
* @param willVisitChildren true if the given node has a child that will be
* (or has been) visited
*/
void visit(D node, boolean willVisitChildren);
}
/**
* Instance state for the Tree.
*/
public static class Model<D> {
private final NodeDataAdapter<D> dataAdapter;
private Listener<D> externalEventDelegate;
private final NodeRenderer<D> nodeRenderer;
private D root;
private final SelectionModel<D> selectionModel;
private final Resources resources;
private final AnimationController animator;
public Model(
NodeDataAdapter<D> dataAdapter, NodeRenderer<D> nodeRenderer, Resources resources) {
this.dataAdapter = dataAdapter;
this.nodeRenderer = nodeRenderer;
this.resources = resources;
this.selectionModel = new SelectionModel<D>(dataAdapter, resources.treeCss());
this.animator = new AnimationController.Builder().setCollapse(true).setFade(true).build();
}
public NodeDataAdapter<D> getDataAdapter() {
return dataAdapter;
}
public NodeRenderer<D> getNodeRenderer() {
return nodeRenderer;
}
public D getRoot() {
return root;
}
public void setRoot(D root) {
this.root = root;
}
}
/**
* Images and BaseCss resources used by the Tree.
*
* In order to theme the Tree, you extend this interface and override
* {@link Resources#treeCss()}.
*/
public interface Resources extends ClientBundle {
@Source("closed-folder-icon.png")
ImageResource closedFolderIcon();
@Source("css-icon.png")
ImageResource cssIcon();
@Source("empty-folder-icon.png")
ImageResource emptyFolderIcon();
@Source("expansionIcon.png")
ImageResource expansionIcon();
@Source("html-icon.png")
ImageResource htmlIcon();
@Source("jar-icon.png")
ImageResource jarIcon();
@Source("java-icon.png")
ImageResource javaIcon();
@Source("javascript-icon.png")
ImageResource javascriptIcon();
@Source("open-folder-icon.png")
ImageResource openFolderIcon();
@Source("package-icon.png")
ImageResource packageIcon();
@Source("empty-package-icon.png")
ImageResource emptyPackageIcon();
@Source("xml-icon.png")
ImageResource xmlIcon();
// Default Stylesheet.
@Source({"collide/client/common/constants.css",
"Tree.css"})
Css treeCss();
}
/**
* The view for a Tree is simply a thin wrapper around a ULElement.
*/
public static class View<D> extends CompositeView<ViewEvents<D>> {
/**
* Base event listener for DOM events fired by elements in the view.
*/
private abstract class TreeNodeEventListener implements EventListener {
private final boolean primaryMouseButtonOnly;
/** The {@link Duration#currentTimeMillis()} of the most recent click, or 0 */
private double previousClickMs;
private Element previousClickTreeNodeBody;
TreeNodeEventListener(boolean primaryMouseButtonOnly) {
this.primaryMouseButtonOnly = primaryMouseButtonOnly;
}
@Override
public void handleEvent(Event evt) {
// Don't even bother to do anything unless we have someone ready to
// handle events.
if (getDelegate() == null || (primaryMouseButtonOnly
&& ((MouseEvent) evt).getButton() != MouseEvent.Button.PRIMARY)) {
return;
}
Element eventTarget = (Element) evt.getTarget();
if (CssUtils.containsClassName(eventTarget, css.expandControl())) {
onExpansionControlEvent(evt, eventTarget);
} else {
Element treeNodeBody =
CssUtils.getAncestorOrSelfWithClassName(eventTarget, css.treeNodeBody());
if (treeNodeBody != null) {
if (Event.CLICK.equals(evt.getType())) {
double currentClickMs = Duration.currentTimeMillis();
if (currentClickMs - previousClickMs < MouseGestureListener.MAX_CLICK_TIMEOUT_MS
&& treeNodeBody.equals(previousClickTreeNodeBody)) {
// Swallow double, triple, etc. clicks on an item's label
return;
} else {
this.previousClickMs = currentClickMs;
this.previousClickTreeNodeBody = treeNodeBody;
}
}
onTreeNodeBodyChildEvent(evt, treeNodeBody);
} else {
onOtherEvent(evt);
}
}
}
/**
* Catch-all that is called if the target element was not matched to an
* element rooted at the TreeNodeBody.
*/
protected void onOtherEvent(Event evt) {
}
/**
* If an event was dispatched by the TreeNodeBody, or one of its children.
*
* IMPORTANT: However, if the event target is the expansion control, do
* not call this method.
*/
protected void onTreeNodeBodyChildEvent(Event evt, Element treeNodeBody) {
}
/**
* If an event was dispatched by the ExpansionControl.
*/
protected void onExpansionControlEvent(Event evt, Element expansionControl) {
}
}
private final Css css;
private final Resources resources;
public View(Resources resources) {
super(Elements.createElement("ul"));
this.resources = resources;
this.css = resources.treeCss();
getElement().setClassName(resources.treeCss().treeRoot());
attachEventListeners();
}
void attachEventListeners() {
// There used to be a MOUSEDOWN handler with stopPropagation() and
// preventDefault() actions, but this badly affected the inline editing
// experience inside the Tree (e.g. debugger's RemoteObjectTree).
getElement().addEventListener(Event.CLICK, new TreeNodeEventListener(true) {
@Override
protected void onTreeNodeBodyChildEvent(Event evt, Element treeNodeBody) {
SignalEvent signalEvent =
SignalEventImpl.create((com.google.gwt.user.client.Event) evt, true);
// Select the node.
dispatchNodeSelectedEvent(treeNodeBody, signalEvent, css);
// Don't dispatch a node action if there is a modifier key depressed.
if (!(signalEvent.getCommandKey() || signalEvent.getShiftKey())) {
dispatchNodeActionEvent(treeNodeBody, css);
TreeNodeElement<D> node = getTreeNodeFromTreeNodeBody(treeNodeBody, css);
if (node.hasChildrenContainer()) {
dispatchExpansionEvent(node, css);
}
}
}
@Override
protected void onExpansionControlEvent(Event evt, Element expansionControl) {
if (!CssUtils.containsClassName(expansionControl, css.leafIcon())) {
/*
* they've clicked on the expand control of a tree node that is a
* directory (so expand it)
*/
TreeNodeElement<D> treeNode =
((JsElement) expansionControl.getParentElement().getParentElement()).<
TreeNodeElement<D>>cast();
dispatchExpansionEvent(treeNode, css);
}
}
}, false);
getElement().addEventListener(Event.CONTEXTMENU, new TreeNodeEventListener(false) {
@Override
public void handleEvent(Event evt) {
super.handleEvent(evt);
evt.stopPropagation();
evt.preventDefault();
}
@Override
protected void onOtherEvent(Event evt) {
MouseEvent mouseEvt = (MouseEvent) evt;
// This is a click on the root.
dispatchOnRootContextMenuEvent(mouseEvt.getClientX(), mouseEvt.getClientY());
}
@Override
protected void onTreeNodeBodyChildEvent(Event evt, Element treeNodeBody) {
MouseEvent mouseEvt = (MouseEvent) evt;
// Dispatch if eventTarget is the treeNodeBody, or if it is a child
// of a treeNodeBody.
dispatchContextMenuEvent(
mouseEvt.getClientX(), mouseEvt.getClientY(), treeNodeBody, css);
}
}, false);
EventListener dragDropEventListener = new EventListener() {
@Override
public void handleEvent(Event event) {
if (getDelegate() != null) {
getDelegate().onDragDropEvent((JsDragEvent) event);
}
}
};
getElement().addEventListener(Event.DROP, dragDropEventListener, false);
getElement().addEventListener(Event.DRAGOVER, dragDropEventListener, false);
getElement().addEventListener(Event.DRAGENTER, dragDropEventListener, false);
getElement().addEventListener(Event.DRAGLEAVE, dragDropEventListener, false);
getElement().addEventListener(Event.DRAGSTART, dragDropEventListener, false);
}
private void dispatchContextMenuEvent(int mouseX, int mouseY, Element treeNodeBody, Css css) {
// We assume the click happened on a TreeNodeBody. We walk up one level
// to grab the treeNode element.
@SuppressWarnings("unchecked")
TreeNodeElement<D> treeNode =
(TreeNodeElement<D>) treeNodeBody.getParentElement();
assert (CssUtils.containsClassName(
treeNode, css.treeNode())) : "Parent of an expandControl wasn't a TreeNode!";
getDelegate().onNodeContextMenu(mouseX, mouseY, treeNode);
}
@SuppressWarnings("unchecked")
private void dispatchExpansionEvent(TreeNodeElement<D> treeNode, Css css) {
// Is the node opened or closed?
if (treeNode.isOpen()) {
getDelegate().onNodeClosed(treeNode);
} else {
// We might have set the CSS to say it is closed, but the animation
// takes a little while. As such, we check to make sure the children
// container is set to display:none before trying to dispatch an open.
// Otherwise we can get into an inconsistent state if we click really
// fast.
Element childrenContainer = treeNode.getChildrenContainer();
if (childrenContainer != null && !CssUtils.isVisible(childrenContainer)) {
getDelegate().onNodeExpanded(treeNode);
}
}
}
private void dispatchNodeActionEvent(Element treeNodeBody, Css css) {
getDelegate().onNodeAction(getTreeNodeFromTreeNodeBody(treeNodeBody, css));
}
private void dispatchNodeSelectedEvent(Element treeNodeBody, SignalEvent evt, Css css) {
getDelegate().onNodeSelected(getTreeNodeFromTreeNodeBody(treeNodeBody, css), evt);
}
private void dispatchOnRootContextMenuEvent(int mouseX, int mouseY) {
getDelegate().onRootContextMenu(mouseX, mouseY);
}
private TreeNodeElement<D> getTreeNodeFromTreeNodeBody(Element treeNodeBody, Css css) {
TreeNodeElement<D> treeNode =
((JsElement) treeNodeBody.getParentElement()).<
TreeNodeElement<D>>cast();
assert (CssUtils.containsClassName(treeNode, css.treeNode())) :
"Unexpected element when looking for tree node: " + treeNode.toString();
return treeNode;
}
}
/**
* Logical events sourced by the Tree's View. Note that these events get
* dispatched synchronously in our DOM event handlers.
*/
private interface ViewEvents<D> {
public void onNodeAction(TreeNodeElement<D> node);
public void onNodeClosed(TreeNodeElement<D> node);
public void onNodeContextMenu(int mouseX, int mouseY, TreeNodeElement<D> node);
public void onDragDropEvent(JsDragEvent event);
public void onNodeExpanded(TreeNodeElement<D> node);
public void onNodeSelected(TreeNodeElement<D> node, SignalEvent event);
public void onRootContextMenu(int mouseX, int mouseY);
public void onRootDragDrop(JsDragEvent event);
}
private class DragDropController {
private TreeNodeElement<D> targetNode;
private boolean hadDragEnterEvent;
private final ScheduledCommand hadDragEnterEventResetter = new ScheduledCommand() {
@Override
public void execute() {
hadDragEnterEvent = false;
}
};
private final Timer hoverToExpandTimer = new Timer() {
@Override
public void run() {
expandNode(targetNode, true, true);
}
};
void handleDragDropEvent(JsDragEvent evt) {
final D rootData = getModel().root;
final NodeDataAdapter<D> dataAdapter = getModel().getDataAdapter();
final Css css = getModel().resources.treeCss();
@SuppressWarnings("unchecked")
TreeNodeElement<D> node =
(TreeNodeElement<D>) CssUtils.getAncestorOrSelfWithClassName((Element) evt.getTarget(),
css.treeNode());
D newTargetData = node != null ? dataAdapter.getDragDropTarget(node.getData()) : rootData;
TreeNodeElement<D> newTargetNode = dataAdapter.getRenderedTreeNode(newTargetData);
String type = evt.getType();
if (Event.DRAGSTART.equals(type)) {
if (getModel().externalEventDelegate != null) {
D sourceData = node != null ? node.getData() : rootData;
// TODO support multiple folder selection.
// We do not support dragging without any folder/file selection.
if (sourceData != rootData) {
TreeNodeElement<D> sourceNode = dataAdapter.getRenderedTreeNode(sourceData);
getModel().externalEventDelegate.onNodeDragStart(sourceNode, evt);
}
}
return;
}
if (Event.DROP.equals(type)) {
if (getModel().externalEventDelegate != null) {
if (newTargetData == rootData) {
getModel().externalEventDelegate.onRootDragDrop(evt);
} else {
getModel().externalEventDelegate.onNodeDragDrop(newTargetNode, evt);
}
}
clearDropTarget();
} else if (Event.DRAGOVER.equals(type)) {
if (newTargetNode != targetNode) {
clearDropTarget();
if (newTargetNode != null) {
// Highlight the node by setting its drop target property
targetNode = newTargetNode;
targetNode.setIsDropTarget(true, css);
if (dataAdapter.hasChildren(newTargetData) && !targetNode.isOpen()) {
hoverToExpandTimer.schedule(HOVER_TO_EXPAND_DELAY_MS);
}
}
}
} else if (Event.DRAGLEAVE.equals(type)) {
if (!hadDragEnterEvent) {
// This wasn't part of a DRAGENTER-DRAGLEAVE pair (see below)
clearDropTarget();
}
} else if (Event.DRAGENTER.equals(type)) {
/*
* DRAGENTER comes before DRAGLEAVE, and a deferred command scheduled
* here will execute after the DRAGLEAVE. We use hadDragEnter to track a
* paired DRAGENTER-DRAGLEAVE so that we can cleanup when we get an
* unpaired DRAGLEAVE.
*/
hadDragEnterEvent = true;
Scheduler.get().scheduleDeferred(hadDragEnterEventResetter);
}
evt.preventDefault();
evt.stopPropagation();
}
private void clearDropTarget() {
hoverToExpandTimer.cancel();
if (targetNode != null) {
targetNode.setIsDropTarget(false, getModel().resources.treeCss());
targetNode = null;
}
}
}
private final DragDropController dragDropController = new DragDropController();
/**
* Handles logical events sourced by the View.
*/
private final ViewEvents<D> viewEventHandler = new ViewEvents<D>() {
@Override
public void onNodeAction(final TreeNodeElement<D> node) {
selectSingleNode(node, true);
}
@Override
public void onNodeClosed(TreeNodeElement<D> node) {
closeNode(node, true);
}
@Override
public void onNodeContextMenu(int mouseX, int mouseY, TreeNodeElement<D> node) {
// We want to select the node if it isn't already selected.
getModel().selectionModel.contextSelect(node.getData());
if (getModel().externalEventDelegate != null) {
getModel().externalEventDelegate.onNodeContextMenu(mouseX, mouseY, node);
}
}
@Override
public void onDragDropEvent(JsDragEvent event) {
dragDropController.handleDragDropEvent(event);
}
@Override
public void onNodeExpanded(TreeNodeElement<D> node) {
expandNode(node, true, true);
}
@Override
public void onNodeSelected(TreeNodeElement<D> node, SignalEvent event) {
getModel().selectionModel.selectNode(node.getData(), event);
}
@Override
public void onRootContextMenu(int mouseX, int mouseY) {
if (getModel().externalEventDelegate != null) {
getModel().externalEventDelegate.onRootContextMenu(mouseX, mouseY);
}
}
@Override
public void onRootDragDrop(JsDragEvent event) {
if (getModel().externalEventDelegate != null) {
getModel().externalEventDelegate.onRootDragDrop(event);
}
}
};
private static final int HOVER_TO_EXPAND_DELAY_MS = 500;
private final Model<D> treeModel;
/**
* Constructor.
*/
public Tree(View<D> view, Model<D> model) {
super(view);
this.treeModel = model;
getView().setDelegate(viewEventHandler);
}
public Model<D> getModel() {
return treeModel;
}
/**
* Selects a node in the tree and auto expands the tree to this node.
*
* @param nodeData the node we want to select and expand to.
* @param dispatchNodeAction whether or not to notify listeners of the node
* action for the selected node.
*/
public void autoExpandAndSelectNode(D nodeData, boolean dispatchNodeAction) {
// Expand the tree to the selected element.
expandPathRecursive(getModel().root, getModel().dataAdapter.getNodePath(nodeData), false);
// By now the node should have a rendered element.
TreeNodeElement<D> renderedNode = getModel().dataAdapter.getRenderedTreeNode(nodeData);
assert (renderedNode != null) : "Expanded selection has a null rendered node!";
selectSingleNode(renderedNode, dispatchNodeAction);
}
private void selectSingleNode(TreeNodeElement<D> renderedNode, boolean dispatchNodeAction) {
getModel().selectionModel.selectSingleNode(renderedNode.getData());
maybeNotifyNodeActionExternal(renderedNode, dispatchNodeAction);
}
/**
* Creates a {@link TreeNodeElement}. This does NOT attach said node to the
* tree. You have to do that manually with {@link TreeNodeElement#addChild}.
*/
public TreeNodeElement<D> createNode(D nodeData) {
return TreeNodeElement.create(
nodeData, getModel().dataAdapter, getModel().nodeRenderer, getModel().resources.treeCss());
}
/**
* @see: {@link #expandNode(TreeNodeElement, boolean, boolean)}.
*/
public void expandNode(TreeNodeElement<D> treeNode) {
expandNode(treeNode, false, false);
}
/**
* Expands a {@link TreeNodeElement} and renders its children if it "needs
* to". "Needs to" is defined as whether or not the children have never been
* rendered before, or if size of the set of rendered children differs from
* the size of children in the underlying model.
*
* @param treeNode the {@link TreeNodeElement} we are expanding.
* @param shouldAnimate whether to animate the expansion
* @param dispatchNodeExpanded whether or not to notify listeners of the node
* expansion
*/
private void expandNode(TreeNodeElement<D> treeNode, boolean shouldAnimate,
boolean dispatchNodeExpanded) {
// This is most likely because someone tried to expand root. Ignore it.
if (treeNode == null) {
return;
}
NodeDataAdapter<D> dataAdapter = getModel().dataAdapter;
// Nothing to do here.
if (!dataAdapter.hasChildren(treeNode.getData())) {
return;
}
// Ensure that the node's children container is birthed.
treeNode.ensureChildrenContainer(dataAdapter, getModel().resources.treeCss());
JsonArray<D> children = dataAdapter.getChildren(treeNode.getData());
// Maybe render it's children if they aren't already rendered.
if (treeNode.getChildrenContainer().getChildren().getLength() != children.size()) {
// Then the model has not been correctly reflected in the UI.
// Blank the children and render a single level for each.
treeNode.getChildrenContainer().setInnerHTML("");
for (int i = 0, n = children.size(); i < n; i++) {
renderRecursive(treeNode.getChildrenContainer(), children.get(i), 0);
}
}
// Render the node as being opened after the children have been added, so that
// AnimationController can correctly measure the height of the child container.
treeNode.openNode(
dataAdapter, getModel().resources.treeCss(), getModel().animator, shouldAnimate);
// Notify listeners of the event.
if (dispatchNodeExpanded && getModel().externalEventDelegate != null) {
getModel().externalEventDelegate.onNodeExpanded(treeNode);
}
}
public void closeNode(TreeNodeElement<D> treeNode) {
closeNode(treeNode, false);
}
private void closeNode(TreeNodeElement<D> treeNode, boolean dispatchNodeClosed) {
if (!treeNode.isOpen()) {
return;
}
treeNode.closeNode(
getModel().dataAdapter, getModel().resources.treeCss(), getModel().animator, true);
if (dispatchNodeClosed && getModel().externalEventDelegate != null) {
getModel().externalEventDelegate.onNodeClosed(treeNode);
}
}
/**
* Takes in a list of paths relative to the root, that correspond to nodes in
* the tree that need to be expanded.
*
* <p>This will try to expand all the given paths recursively, and return the
* array of paths that could not be fully expanded, i.e. when the leaf that
* the path points to was not found in the tree. In these cases all the middle
* nodes that were found in the tree will be expanded though.
*
* <p>The returned array of not expanded paths may be used to save and restore
* the expansion history.
*
* @param paths array of paths to expand
* @param dispatchNodeExpanded whether to dispatch the NodeExpanded event
* @return array of paths that were not expanded, or were partially expanded
*/
public JsonArray<JsonArray<String>> expandPaths(JsonArray<JsonArray<String>> paths,
boolean dispatchNodeExpanded) {
JsonArray<JsonArray<String>> notExpanded = JsonCollections.createArray();
for (int i = 0, n = paths.size(); i < n; i++) {
if (!expandPathRecursive(getModel().root, paths.get(i), dispatchNodeExpanded)) {
notExpanded.add(paths.get(i));
}
}
return notExpanded;
}
/**
* Gets the associated {@link TreeNodeElement} for a given nodeData.
*
* If there is no such node rendered in the tree, then {@code null} is
* returned.
*/
public TreeNodeElement<D> getNode(D nodeData) {
return getModel().getDataAdapter().getRenderedTreeNode(nodeData);
}
public Resources getResources() {
return getModel().resources;
}
public SelectionModel<D> getSelectionModel() {
return getModel().selectionModel;
}
/**
* Removes a node from the DOM. Does not mutate the the underlying model. That
* should be already done before calling this method.
*/
public void removeNode(TreeNodeElement<D> node) {
if (node == null) {
return;
}
// Remove from the DOM
node.removeFromTree();
// Notify the selection model in case it was selected.
getModel().selectionModel.removeNode(node.getData());
}
/**
* Renders the entire tree starting with the root node.
*/
public void renderTree() {
renderTree(-1);
}
/**
* Renders the tree starting with the root node up until the specified depth.
*
* This will NOT restore any expansions. If you want to re-render the tree
* obeying previous expansions then,
*
* @see: {@link #replaceSubtree(Object, Object)}.
*
* @param depth integer indicating how deep we should auto-expand. -1 means
* render the entire tree.
*/
public void renderTree(int depth) {
// Clear the current view.
Element rootElement = getView().getElement();
rootElement.setInnerHTML("");
// If the root is not set, we have nothing to render.
D root = getModel().root;
if (root == null) {
return;
}
// Root is special in that we don't render a directory for it. Only its
// children.
JsonArray<D> children = getModel().dataAdapter.getChildren(root);
for (int i = 0, n = children.size(); i < n; i++) {
renderRecursive(rootElement, children.get(i), depth);
}
}
/**
* Replaces the old node in the tree with data representing the subtree rooted
* where the old node used to be if the old node was rendered.
*
* <p>{@code oldSubtreeData} and {@code incomingSubtreeData} are allowed to be
* the same node (it will simply get re-rendered).
*
* <p>This methods also tries to preserve the original expansion state. Any
* path that was expanded before executing this method but could not be
* expanded after replacing the subtree, will be returned in the result array,
* so that it could be expanded later using the {@link #expandPaths} method,
* if needed (for example, if children of the tree are getting populated
* asynchronously).
*
* @param shouldAnimate if true, the subtree will animate open if it is still open
* @return array paths that could not be expanded in the new subtree
*/
public JsonArray<JsonArray<String>> replaceSubtree(D oldSubtreeData, D incomingSubtreeData,
boolean shouldAnimate) {
// Gather paths that were expanded in this subtree so that we can restore
// them later after rendering.
JsonArray<JsonArray<String>> expandedPaths = gatherExpandedPaths(oldSubtreeData);
boolean wasRoot = (oldSubtreeData == getModel().root);
TreeNodeElement<D> oldRenderedNode = null;
TreeNodeElement<D> newRenderedNode = null;
if (wasRoot) {
// We are rendering root! Just render it from the top. We will restore the
// expansion later.
getModel().setRoot(incomingSubtreeData);
renderTree(0);
} else {
oldRenderedNode = getModel().dataAdapter.getRenderedTreeNode(oldSubtreeData);
// If the node does not have a rendered node, then we have nothing to do.
if (oldRenderedNode == null) {
expandedPaths.clear();
return expandedPaths;
}
JsElement parentElem = oldRenderedNode.getParentElement();
// The old node may have been moved from a rendered to a non-rendered
// state (e.g., into a collapsed folder). In that case, it doesn't have a
// parent, and we're done here.
if (parentElem == null) {
expandedPaths.clear();
return expandedPaths;
}
// Make a new tree node.
newRenderedNode = createNode(incomingSubtreeData);
parentElem.insertBefore(newRenderedNode, oldRenderedNode);
// Remove the old rendered node from the tree.
oldRenderedNode.removeFromParent();
}
// If the old node was the root, or if it and its parents were expanded, then we should
// attempt to restore expansion.
boolean shouldExpand = wasRoot;
if (!wasRoot && oldRenderedNode != null) {
shouldExpand = true;
TreeNodeElement<D> curNode = oldRenderedNode;
while (curNode != null) {
if (!curNode.isOpen()) {
// One of the parents is closed, so we should not expand all paths.
shouldExpand = false;
break;
}
D parentData = getModel().dataAdapter.getParent(curNode.getData());
curNode =
(parentData == null) ? null : getModel().dataAdapter.getRenderedTreeNode(parentData);
}
}
if (shouldExpand) {
// Animate the top node if it was open. If we should not animate, the newRenderedNode will
// still be expanded by the call to expandPaths() below.
if (shouldAnimate && newRenderedNode != null) {
expandNode(newRenderedNode, true, true);
}
// But if it is open, we need to attempt to restore the expansion.
expandedPaths = expandPaths(expandedPaths, true);
} else {
expandedPaths.clear();
}
// TODO: Be more surgical about restoring the selection model. We
// are currently recomputing all selected nodes.
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | true |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/treeview/TreeNodeLabelRenamer.java | client/src/main/java/collide/client/treeview/TreeNodeLabelRenamer.java | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collide.client.treeview;
import collide.client.treeview.TreeNodeMutator.Css;
import elemental.dom.Element;
/**
* Utility for mutating the String name for the model object backing a
* {@link TreeNodeElement}, in place in a {@link Tree}.
*
* In other words, this is a utility class that facilitates renaming of
* {@link TreeNodeElement}s.
*/
public class TreeNodeLabelRenamer<D> {
/**
* Callback that gets invoked right after the model has been changed.
*/
public interface LabelRenamerCallback<D> {
void onCommit(String oldLabel, TreeNodeElement<D> node);
boolean passValidation(TreeNodeElement<D> node, String newLabel);
}
private final NodeDataAdapter<D> dataAdapter;
/**
* The {@link NodeRenderer} that we use to re-render the label portions of the
* {@link TreeNodeElement}.
*/
private final NodeRenderer<D> renderer;
private LabelRenamerCallback<D> callback;
private final TreeNodeMutator<D> treeNodeMutator;
private final TreeNodeMutator.MutationAction<D> mutationAction =
new TreeNodeMutator.MutationAction<D>() {
@Override
public Element getElementForMutation(TreeNodeElement<D> node) {
return renderer.getNodeKeyTextContainer(node.getNodeLabel());
}
@Override
public void onBeforeMutation(TreeNodeElement<D> node) {
// Nothing to do.
}
@Override
public void onMutationCommit(TreeNodeElement<D> node, String oldLabel, String newLabel) {
if (callback != null) {
mutateNodeKey(node, newLabel);
callback.onCommit(oldLabel, node);
callback = null;
}
}
@Override
public boolean passValidation(TreeNodeElement<D> node, String newLabel) {
return callback == null || callback.passValidation(node, newLabel);
}
};
public TreeNodeLabelRenamer(
NodeRenderer<D> renderer, NodeDataAdapter<D> dataAdapter, Css treeMutatorCss) {
this.renderer = renderer;
this.dataAdapter = dataAdapter;
this.treeNodeMutator = new TreeNodeMutator<D>(treeMutatorCss);
}
public boolean isMutating() {
return treeNodeMutator.isMutating();
}
/**
* Replaces the nodes text label with an input box to allow the user to
* rename the node.
*/
public void enterMutation(TreeNodeElement<D> node, LabelRenamerCallback<D> callback) {
// If we are already mutating, return.
if (isMutating()) {
return;
}
this.callback = callback;
treeNodeMutator.enterMutation(node, mutationAction);
}
public void cancel() {
treeNodeMutator.cancel();
}
public NodeDataAdapter<D> getDataAdapter() {
return dataAdapter;
}
public NodeRenderer<D> getRenderer() {
return renderer;
}
public TreeNodeMutator<D> getTreeNodeMutator() {
return treeNodeMutator;
}
/**
* Commits the current text if it passes validation, or cancels the mutation.
*/
public void forceCommit() {
treeNodeMutator.forceCommit();
}
/**
* Updates the name value for the model object for a node, and then replaces
* the label's contents with the new value.
*/
public void mutateNodeKey(TreeNodeElement<D> node, String newName) {
getDataAdapter().setNodeName(node.getData(), newName);
Element elem = getRenderer().getNodeKeyTextContainer(node.getNodeLabel());
elem.setTextContent(newName);
}
}
| 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.